twilio-video 2.18.2 → 2.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! twilio-video.js 2.18.2
1
+ /*! twilio-video.js 2.18.3
2
2
 
3
3
  The following license applies to all parts of this software except as
4
4
  documented below.
@@ -47,12 +47,12 @@ var sdpWithoutSimulcastForNonVP8MediaSections=_this._revertSimulcastForNonVP8Med
47
47
  var hints=[];Array.from(this._trackSidsToRenderHints.keys()).forEach(function(trackSid){var trackState=_this._trackSidsToRenderHints.get(trackSid);if(trackState.isEnabledDirty||trackState.isDimensionDirty){var mspHint={track:trackSid};if(trackState.isEnabledDirty){mspHint.enabled=trackState.enabled;trackState.isEnabledDirty=false}if(trackState.isDimensionDirty){mspHint.render_dimensions=trackState.renderDimensions;trackState.isDimensionDirty=false}hints.push(mspHint)}});if(hints.length>0){var payLoad={type:"render_hints",subscriber:{id:messageId++,hints:hints}};this._log.debug("Outgoing: ",payLoad);this._transport.publish(payLoad);this._isResponsePending=true}};RenderHintsSignaling.prototype.setTrackHint=function(trackSid,renderHint){var trackState=this._trackSidsToRenderHints.get(trackSid)||{isEnabledDirty:false,isDimensionDirty:false};if("enabled"in renderHint&&trackState.enabled!==renderHint.enabled){trackState.enabled=!!renderHint.enabled;trackState.isEnabledDirty=true}if(renderHint.renderDimensions&&!isDeepEqual(renderHint.renderDimensions,trackState.renderDimensions)){trackState.renderDimensions=renderHint.renderDimensions;trackState.isDimensionDirty=true}this._trackSidsToRenderHints.set(trackSid,trackState);this._sendHints()};RenderHintsSignaling.prototype.clearTrackHint=function(trackSid){this._trackSidsToRenderHints.delete(trackSid)};return RenderHintsSignaling}(MediaSignaling);module.exports=RenderHintsSignaling},{"../../util":126,"./mediasignaling":71}],80:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var DominantSpeakerSignaling=require("./dominantspeakersignaling");var NetworkQualityMonitor=require("./networkqualitymonitor");var NetworkQualitySignaling=require("./networkqualitysignaling");var RecordingV2=require("./recording");var RoomSignaling=require("../room");var RemoteParticipantV2=require("./remoteparticipant");var StatsReport=require("../../stats/statsreport");var TrackPrioritySignaling=require("./trackprioritysignaling");var TrackSwitchOffSignaling=require("./trackswitchoffsignaling");var RenderHintsSignaling=require("./renderhintssignaling");var _a=require("../../util"),DEFAULT_SESSION_TIMEOUT_SEC=_a.constants.DEFAULT_SESSION_TIMEOUT_SEC,createBandwidthProfilePayload=_a.createBandwidthProfilePayload,defer=_a.defer,difference=_a.difference,filterObject=_a.filterObject,flatMap=_a.flatMap,oncePerTick=_a.oncePerTick;var MovingAverageDelta=require("../../util/movingaveragedelta");var createTwilioError=require("../../util/twilio-video-errors").createTwilioError;var STATS_PUBLISH_INTERVAL_MS=1e4;var RoomV2=function(_super){__extends(RoomV2,_super);function RoomV2(localParticipant,initialState,transport,peerConnectionManager,options){var _this=this;initialState.options=Object.assign({session_timeout:DEFAULT_SESSION_TIMEOUT_SEC},initialState.options);options=Object.assign({DominantSpeakerSignaling:DominantSpeakerSignaling,NetworkQualityMonitor:NetworkQualityMonitor,NetworkQualitySignaling:NetworkQualitySignaling,RecordingSignaling:RecordingV2,RemoteParticipantV2:RemoteParticipantV2,TrackPrioritySignaling:TrackPrioritySignaling,TrackSwitchOffSignaling:TrackSwitchOffSignaling,bandwidthProfile:null,sessionTimeout:initialState.options.session_timeout*1e3,statsPublishIntervalMs:STATS_PUBLISH_INTERVAL_MS},options);localParticipant.setBandwidthProfile(options.bandwidthProfile);peerConnectionManager.setIceReconnectTimeout(options.sessionTimeout);_this=_super.call(this,localParticipant,initialState.sid,initialState.name,options)||this;var getTrackReceiver=function(id){return _this._getTrackReceiver(id)};var log=_this._log;Object.defineProperties(_this,{_disconnectedParticipantRevisions:{value:new Map},_NetworkQualityMonitor:{value:options.NetworkQualityMonitor},_lastBandwidthProfileRevision:{value:localParticipant.bandwidthProfileRevision,writable:true},_networkQualityMonitor:{value:null,writable:true},_networkQualityConfiguration:{value:localParticipant.networkQualityConfiguration},_peerConnectionManager:{value:peerConnectionManager},_published:{value:new Map},_publishedRevision:{value:0,writable:true},_RemoteParticipantV2:{value:options.RemoteParticipantV2},_subscribed:{value:new Map},_subscribedRevision:{value:0,writable:true},_subscriptionFailures:{value:new Map},_dominantSpeakerSignaling:{value:new options.DominantSpeakerSignaling(getTrackReceiver,{log:log})},_networkQualitySignaling:{value:new options.NetworkQualitySignaling(getTrackReceiver,localParticipant.networkQualityConfiguration,{log:log})},_renderHintsSignaling:{value:new RenderHintsSignaling(getTrackReceiver,{log:log})},_trackPrioritySignaling:{value:new options.TrackPrioritySignaling(getTrackReceiver,{log:log})},_trackSwitchOffSignaling:{value:new options.TrackSwitchOffSignaling(getTrackReceiver,{log:log})},_pendingSwitchOffStates:{value:new Map},_transport:{value:transport},_trackReceiverDeferreds:{value:new Map},mediaRegion:{enumerable:true,value:initialState.options.media_region||null}});_this._initTrackSwitchOffSignaling();_this._initDominantSpeakerSignaling();_this._initNetworkQualityMonitorSignaling();handleLocalParticipantEvents(_this,localParticipant);handlePeerConnectionEvents(_this,peerConnectionManager);handleTransportEvents(_this,transport);periodicallyPublishStats(_this,transport,options.statsPublishIntervalMs);_this._update(initialState);return _this}Object.defineProperty(RoomV2.prototype,"connectionState",{get:function(){return this._peerConnectionManager.connectionState},enumerable:false,configurable:true});Object.defineProperty(RoomV2.prototype,"signalingConnectionState",{get:function(){return this._transport.state==="syncing"?"reconnecting":this._transport.state},enumerable:false,configurable:true});Object.defineProperty(RoomV2.prototype,"iceConnectionState",{get:function(){return this._peerConnectionManager.iceConnectionState},enumerable:false,configurable:true});RoomV2.prototype._deleteTrackReceiverDeferred=function(id){return this._trackReceiverDeferreds.delete(id)};RoomV2.prototype._getOrCreateTrackReceiverDeferred=function(id){var deferred=this._trackReceiverDeferreds.get(id)||defer();var trackReceivers=this._peerConnectionManager.getTrackReceivers();var trackReceiver=trackReceivers.find(function(trackReceiver){return trackReceiver.id===id&&trackReceiver.readyState!=="ended"});if(trackReceiver){deferred.resolve(trackReceiver)}else{this._trackReceiverDeferreds.set(id,deferred)}return deferred};RoomV2.prototype._addTrackReceiver=function(trackReceiver){var deferred=this._getOrCreateTrackReceiverDeferred(trackReceiver.id);deferred.resolve(trackReceiver);return this};RoomV2.prototype._disconnect=function(error){var didDisconnect=_super.prototype._disconnect.call(this,error);if(didDisconnect){this._teardownNetworkQualityMonitor();this._transport.disconnect();this._peerConnectionManager.close()}this.localParticipant.tracks.forEach(function(track){track.publishFailed(error||new Error("LocalParticipant disconnected"))});return didDisconnect};RoomV2.prototype._getTrackReceiver=function(id){var _this=this;return this._getOrCreateTrackReceiverDeferred(id).promise.then(function(trackReceiver){_this._deleteTrackReceiverDeferred(id);return trackReceiver})};RoomV2.prototype._getInitialTrackSwitchOffState=function(trackSid){var initiallySwitchedOff=this._pendingSwitchOffStates.get(trackSid)||false;this._pendingSwitchOffStates.delete(trackSid);if(initiallySwitchedOff){this._log.warn("["+trackSid+"] was initially switched off! ")}return initiallySwitchedOff};RoomV2.prototype._getTrackSidsToTrackSignalings=function(){var trackSidsToTrackSignalings=flatMap(this.participants,function(participant){return Array.from(participant.tracks)});return new Map(trackSidsToTrackSignalings)};RoomV2.prototype._getOrCreateRemoteParticipant=function(participantState){var _this=this;var RemoteParticipantV2=this._RemoteParticipantV2;var participant=this.participants.get(participantState.sid);var self=this;if(!participant){participant=new RemoteParticipantV2(participantState,function(trackSid){return _this._getInitialTrackSwitchOffState(trackSid)},function(trackSid,priority){return _this._trackPrioritySignaling.sendTrackPriorityUpdate(trackSid,"subscribe",priority)},function(trackSid,hint){return _this._renderHintsSignaling.setTrackHint(trackSid,hint)},function(trackSid){return _this._renderHintsSignaling.clearTrackHint(trackSid)});participant.on("stateChanged",function stateChanged(state){if(state==="disconnected"){participant.removeListener("stateChanged",stateChanged);self.participants.delete(participant.sid);self._disconnectedParticipantRevisions.set(participant.sid,participant.revision)}});this.connectParticipant(participant)}return participant};RoomV2.prototype._getState=function(){return{participant:this.localParticipant.getState()}};RoomV2.prototype._maybeAddBandwidthProfile=function(update){var _a=this.localParticipant,bandwidthProfile=_a.bandwidthProfile,bandwidthProfileRevision=_a.bandwidthProfileRevision;if(bandwidthProfile&&this._lastBandwidthProfileRevision<bandwidthProfileRevision){this._lastBandwidthProfileRevision=bandwidthProfileRevision;return Object.assign({bandwidth_profile:createBandwidthProfilePayload(bandwidthProfile)},update)}return update};RoomV2.prototype._publishNewLocalParticipantState=function(){this._transport.publish(this._maybeAddBandwidthProfile(this._getState()))};RoomV2.prototype._publishPeerConnectionState=function(peerConnectionState){this._transport.publish(Object.assign({peer_connections:[peerConnectionState]},this._getState()))};RoomV2.prototype._update=function(roomState){var _this=this;if(roomState.subscribed&&roomState.subscribed.revision>this._subscribedRevision){this._subscribedRevision=roomState.subscribed.revision;roomState.subscribed.tracks.forEach(function(trackState){if(trackState.id){_this._subscriptionFailures.delete(trackState.sid);_this._subscribed.set(trackState.sid,trackState.id)}else if(trackState.error&&!_this._subscriptionFailures.has(trackState.sid)){_this._subscriptionFailures.set(trackState.sid,trackState.error)}});var subscribedTrackSids_1=new Set(roomState.subscribed.tracks.filter(function(trackState){return!!trackState.id}).map(function(trackState){return trackState.sid}));this._subscribed.forEach(function(trackId,trackSid){if(!subscribedTrackSids_1.has(trackSid)){_this._subscribed.delete(trackSid)}})}var participantsToKeep=new Set;(roomState.participants||[]).forEach(function(participantState){if(participantState.sid===_this.localParticipant.sid){return}var disconnectedParticipantRevision=_this._disconnectedParticipantRevisions.get(participantState.sid);if(disconnectedParticipantRevision&&participantState.revision<=disconnectedParticipantRevision){return}if(disconnectedParticipantRevision){_this._disconnectedParticipantRevisions.delete(participantState.sid)}var participant=_this._getOrCreateRemoteParticipant(participantState);participant.update(participantState);participantsToKeep.add(participant)});if(roomState.type==="synced"){this.participants.forEach(function(participant){if(!participantsToKeep.has(participant)){participant.disconnect()}})}handleSubscriptions(this);if(roomState.peer_connections){this._peerConnectionManager.update(roomState.peer_connections,roomState.type==="synced")}if(roomState.recording){this.recording.update(roomState.recording)}if(roomState.published&&roomState.published.revision>this._publishedRevision){this._publishedRevision=roomState.published.revision;roomState.published.tracks.forEach(function(track){if(track.sid){_this._published.set(track.id,track.sid)}});this.localParticipant.update(roomState.published)}if(roomState.participant){this.localParticipant.connect(roomState.participant.sid,roomState.participant.identity)}[this._dominantSpeakerSignaling,this._networkQualitySignaling,this._trackPrioritySignaling,this._trackSwitchOffSignaling,this._renderHintsSignaling].forEach(function(mediaSignaling){var channel=mediaSignaling.channel;if(!mediaSignaling.isSetup&&roomState.media_signaling&&roomState.media_signaling[channel]&&roomState.media_signaling[channel].transport&&roomState.media_signaling[channel].transport.type==="data-channel"){mediaSignaling.setup(roomState.media_signaling[channel].transport.label)}});return this};RoomV2.prototype._initTrackSwitchOffSignaling=function(){var _this=this;this._trackSwitchOffSignaling.on("updated",function(tracksOff,tracksOn){try{_this._log.debug("received trackSwitch: ",{tracksOn:tracksOn,tracksOff:tracksOff});var trackUpdates_1=new Map;tracksOn.forEach(function(trackSid){return trackUpdates_1.set(trackSid,true)});tracksOff.forEach(function(trackSid){if(trackUpdates_1.get(trackSid)){_this._log.warn(trackSid+" is DUPLICATED in both tracksOff and tracksOn list")}trackUpdates_1.set(trackSid,false)});_this.participants.forEach(function(participant){participant.tracks.forEach(function(track){var isOn=trackUpdates_1.get(track.sid);if(typeof isOn!=="undefined"){track.setSwitchedOff(!isOn);trackUpdates_1.delete(track.sid)}})});trackUpdates_1.forEach(function(isOn,trackSid){return _this._pendingSwitchOffStates.set(trackSid,!isOn)})}catch(ex){_this._log.error("error processing track switch off:",ex)}})};RoomV2.prototype._initDominantSpeakerSignaling=function(){var _this=this;this._dominantSpeakerSignaling.on("updated",function(){return _this.setDominantSpeaker(_this._dominantSpeakerSignaling.loudestParticipantSid)})};RoomV2.prototype._initNetworkQualityMonitorSignaling=function(){var _this=this;this._networkQualitySignaling.on("ready",function(){var networkQualityMonitor=new _this._NetworkQualityMonitor(_this._peerConnectionManager,_this._networkQualitySignaling);_this._networkQualityMonitor=networkQualityMonitor;networkQualityMonitor.on("updated",function(){if(_this.iceConnectionState==="failed"){return}_this.localParticipant.setNetworkQualityLevel(networkQualityMonitor.level,networkQualityMonitor.levels);_this.participants.forEach(function(participant){var levels=networkQualityMonitor.remoteLevels.get(participant.sid);if(levels){participant.setNetworkQualityLevel(levels.level,levels)}})});networkQualityMonitor.start()});this._networkQualitySignaling.on("teardown",function(){return _this._teardownNetworkQualityMonitor()})};RoomV2.prototype._teardownNetworkQualityMonitor=function(){if(this._networkQualityMonitor){this._networkQualityMonitor.stop();this._networkQualityMonitor=null}};RoomV2.prototype.getStats=function(){var _this=this;return this._peerConnectionManager.getStats().then(function(responses){return new Map(Array.from(responses).map(function(_a){var _b=__read(_a,2),id=_b[0],response=_b[1];return[id,Object.assign({},response,{localAudioTrackStats:filterAndAddLocalTrackSids(_this,response.localAudioTrackStats),localVideoTrackStats:filterAndAddLocalTrackSids(_this,response.localVideoTrackStats),remoteAudioTrackStats:filterAndAddRemoteTrackSids(_this,response.remoteAudioTrackStats),remoteVideoTrackStats:filterAndAddRemoteTrackSids(_this,response.remoteVideoTrackStats)})]}))})};return RoomV2}(RoomSignaling);function filterAndAddTrackSids(idToSid,trackStats){return trackStats.reduce(function(trackStats,trackStat){var trackSid=idToSid.get(trackStat.trackId);return trackSid?[Object.assign({},trackStat,{trackSid:trackSid})].concat(trackStats):trackStats},[])}function filterAndAddLocalTrackSids(roomV2,localTrackStats){return filterAndAddTrackSids(roomV2._published,localTrackStats)}function filterAndAddRemoteTrackSids(roomV2,remoteTrackStats){var idToSid=new Map(Array.from(roomV2._subscribed.entries()).map(function(_a){var _b=__read(_a,2),sid=_b[0],id=_b[1];return[id,sid]}));return filterAndAddTrackSids(idToSid,remoteTrackStats)}function handleLocalParticipantEvents(roomV2,localParticipant){var localParticipantUpdated=oncePerTick(function(){roomV2._publishNewLocalParticipantState()});var renegotiate=oncePerTick(function(){var trackSenders=flatMap(localParticipant.tracks,function(trackV2){return trackV2.trackTransceiver});roomV2._peerConnectionManager.setTrackSenders(trackSenders)});localParticipant.on("trackAdded",renegotiate);localParticipant.on("trackRemoved",renegotiate);localParticipant.on("updated",localParticipantUpdated);roomV2.on("stateChanged",function stateChanged(state){if(state==="disconnected"){localParticipant.removeListener("trackAdded",renegotiate);localParticipant.removeListener("trackRemoved",renegotiate);localParticipant.removeListener("updated",localParticipantUpdated);roomV2.removeListener("stateChanged",stateChanged);localParticipant.disconnect()}});roomV2.on("signalingConnectionStateChanged",function(){var localParticipant=roomV2.localParticipant,signalingConnectionState=roomV2.signalingConnectionState;var identity=localParticipant.identity,sid=localParticipant.sid;switch(signalingConnectionState){case"connected":localParticipant.connect(sid,identity);break;case"reconnecting":localParticipant.reconnecting();break}})}function handlePeerConnectionEvents(roomV2,peerConnectionManager){peerConnectionManager.on("description",function onDescription(description){roomV2._publishPeerConnectionState(description)});peerConnectionManager.dequeue("description");peerConnectionManager.on("candidates",function onCandidates(candidates){roomV2._publishPeerConnectionState(candidates)});peerConnectionManager.dequeue("candidates");peerConnectionManager.on("trackAdded",roomV2._addTrackReceiver.bind(roomV2));peerConnectionManager.dequeue("trackAdded");peerConnectionManager.getTrackReceivers().forEach(roomV2._addTrackReceiver,roomV2);peerConnectionManager.on("connectionStateChanged",function(){roomV2.emit("connectionStateChanged")});peerConnectionManager.on("iceConnectionStateChanged",function(){roomV2.emit("iceConnectionStateChanged");if(roomV2.iceConnectionState==="failed"){if(roomV2.localParticipant.networkQualityLevel!==null){roomV2.localParticipant.setNetworkQualityLevel(0)}roomV2.participants.forEach(function(participant){if(participant.networkQualityLevel!==null){participant.setNetworkQualityLevel(0)}})}})}function handleTransportEvents(roomV2,transport){transport.on("message",roomV2._update.bind(roomV2));transport.on("stateChanged",function stateChanged(state,error){if(state==="disconnected"){if(roomV2.state!=="disconnected"){roomV2._disconnect(error)}transport.removeListener("stateChanged",stateChanged)}roomV2.emit("signalingConnectionStateChanged")})}function periodicallyPublishStats(roomV2,transport,intervalMs){var movingAverageDeltas=new Map;var oddPublishCount=false;var interval=setInterval(function(){roomV2.getStats().then(function(stats){oddPublishCount=!oddPublishCount;stats.forEach(function(response,id){var report=new StatsReport(id,response,true);transport.publishEvent("quality","stats-report","info",{audioTrackStats:report.remoteAudioTrackStats.map(function(trackStat,i){return addAVSyncMetricsToRemoteTrackStats(trackStat,response.remoteAudioTrackStats[i],movingAverageDeltas)}),localAudioTrackStats:report.localAudioTrackStats.map(function(trackStat,i){return addAVSyncMetricsToLocalTrackStats(trackStat,response.localAudioTrackStats[i],movingAverageDeltas)}),localVideoTrackStats:report.localVideoTrackStats.map(function(trackStat,i){return addAVSyncMetricsToLocalTrackStats(trackStat,response.localVideoTrackStats[i],movingAverageDeltas)}),peerConnectionId:report.peerConnectionId,videoTrackStats:report.remoteVideoTrackStats.map(function(trackStat,i){return addAVSyncMetricsToRemoteTrackStats(trackStat,response.remoteVideoTrackStats[i],movingAverageDeltas)})});var keys=flatMap(["localAudioTrackStats","localVideoTrackStats","remoteAudioTrackStats","remoteVideoTrackStats"],function(prop){return report[prop].map(function(_a){var ssrc=_a.ssrc,trackSid=_a.trackSid;return trackSid+"+"+ssrc})});var movingAverageDeltaKeysToBeRemoved=difference(Array.from(movingAverageDeltas.keys()),keys);movingAverageDeltaKeysToBeRemoved.forEach(function(key){return movingAverageDeltas.delete(key)});if(oddPublishCount){var activeIceCandidatePair=replaceNullsWithDefaults(response.activeIceCandidatePair,report.peerConnectionId);transport.publishEvent("quality","active-ice-candidate-pair","info",activeIceCandidatePair)}})},function(){})},intervalMs);roomV2.on("stateChanged",function onStateChanged(state){if(state==="disconnected"){clearInterval(interval);roomV2.removeListener("stateChanged",onStateChanged)}})}function handleSubscriptions(room){var trackSidsToTrackSignalings=room._getTrackSidsToTrackSignalings();room._subscriptionFailures.forEach(function(error,trackSid){var trackSignaling=trackSidsToTrackSignalings.get(trackSid);if(trackSignaling){room._subscriptionFailures.delete(trackSid);trackSignaling.subscribeFailed(createTwilioError(error.code,error.message))}});trackSidsToTrackSignalings.forEach(function(trackSignaling){var trackId=room._subscribed.get(trackSignaling.sid);if(!trackId||trackSignaling.isSubscribed&&trackSignaling.trackTransceiver.id!==trackId){trackSignaling.setTrackTransceiver(null)}if(trackId){room._getTrackReceiver(trackId).then(function(trackReceiver){return trackSignaling.setTrackTransceiver(trackReceiver)})}})}function addAVSyncMetricsToLocalTrackStats(trackStats,trackResponse,movingAverageDeltas){var framesEncoded=trackResponse.framesEncoded,packetsSent=trackResponse.packetsSent,totalEncodeTime=trackResponse.totalEncodeTime,totalPacketSendDelay=trackResponse.totalPacketSendDelay;var augmentedTrackStats=Object.assign({},trackStats);var key=trackStats.trackSid+"+"+trackStats.ssrc;var trackMovingAverageDeltas=movingAverageDeltas.get(key)||new Map;if(typeof totalEncodeTime==="number"&&typeof framesEncoded==="number"){var trackAvgEncodeDelayMovingAverageDelta=trackMovingAverageDeltas.get("avgEncodeDelay")||new MovingAverageDelta;trackAvgEncodeDelayMovingAverageDelta.putSample(totalEncodeTime*1e3,framesEncoded);augmentedTrackStats.avgEncodeDelay=Math.round(trackAvgEncodeDelayMovingAverageDelta.get());trackMovingAverageDeltas.set("avgEncodeDelay",trackAvgEncodeDelayMovingAverageDelta)}if(typeof totalPacketSendDelay==="number"&&typeof packetsSent==="number"){var trackAvgPacketSendDelayMovingAverageDelta=trackMovingAverageDeltas.get("avgPacketSendDelay")||new MovingAverageDelta;trackAvgPacketSendDelayMovingAverageDelta.putSample(totalPacketSendDelay*1e3,packetsSent);augmentedTrackStats.avgPacketSendDelay=Math.round(trackAvgPacketSendDelayMovingAverageDelta.get());trackMovingAverageDeltas.set("avgPacketSendDelay",trackAvgPacketSendDelayMovingAverageDelta)}movingAverageDeltas.set(key,trackMovingAverageDeltas);return augmentedTrackStats}function addAVSyncMetricsToRemoteTrackStats(trackStats,trackResponse,movingAverageDeltas){var estimatedPlayoutTimestamp=trackResponse.estimatedPlayoutTimestamp,framesDecoded=trackResponse.framesDecoded,jitterBufferDelay=trackResponse.jitterBufferDelay,jitterBufferEmittedCount=trackResponse.jitterBufferEmittedCount,totalDecodeTime=trackResponse.totalDecodeTime;var augmentedTrackStats=Object.assign({},trackStats);var key=trackStats.trackSid+"+"+trackStats.ssrc;var trackMovingAverageDeltas=movingAverageDeltas.get(key)||new Map;if(typeof estimatedPlayoutTimestamp==="number"){augmentedTrackStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}if(typeof framesDecoded==="number"&&typeof totalDecodeTime==="number"){var trackAvgDecodeDelayMovingAverageDelta=trackMovingAverageDeltas.get("avgDecodeDelay")||new MovingAverageDelta;trackAvgDecodeDelayMovingAverageDelta.putSample(totalDecodeTime*1e3,framesDecoded);augmentedTrackStats.avgDecodeDelay=Math.round(trackAvgDecodeDelayMovingAverageDelta.get());trackMovingAverageDeltas.set("avgDecodeDelay",trackAvgDecodeDelayMovingAverageDelta)}if(typeof jitterBufferDelay==="number"&&typeof jitterBufferEmittedCount==="number"){var trackAvgJitterBufferDelayMovingAverageDelta=trackMovingAverageDeltas.get("avgJitterBufferDelay")||new MovingAverageDelta;trackAvgJitterBufferDelayMovingAverageDelta.putSample(jitterBufferDelay*1e3,jitterBufferEmittedCount);augmentedTrackStats.avgJitterBufferDelay=Math.round(trackAvgJitterBufferDelayMovingAverageDelta.get());trackMovingAverageDeltas.set("avgJitterBufferDelay",trackAvgJitterBufferDelayMovingAverageDelta)}movingAverageDeltas.set(key,trackMovingAverageDeltas);return augmentedTrackStats}function replaceNullsWithDefaults(activeIceCandidatePair,peerConnectionId){activeIceCandidatePair=Object.assign({availableIncomingBitrate:0,availableOutgoingBitrate:0,bytesReceived:0,bytesSent:0,consentRequestsSent:0,currentRoundTripTime:0,lastPacketReceivedTimestamp:0,lastPacketSentTimestamp:0,nominated:false,peerConnectionId:peerConnectionId,priority:0,readable:false,requestsReceived:0,requestsSent:0,responsesReceived:0,responsesSent:0,retransmissionsReceived:0,retransmissionsSent:0,state:"failed",totalRoundTripTime:0,transportId:"",writable:false},filterObject(activeIceCandidatePair||{},null));activeIceCandidatePair.localCandidate=Object.assign({candidateType:"host",deleted:false,ip:"",port:0,priority:0,protocol:"udp",url:""},filterObject(activeIceCandidatePair.localCandidate||{},null));activeIceCandidatePair.remoteCandidate=Object.assign({candidateType:"host",ip:"",port:0,priority:0,protocol:"udp",url:""},filterObject(activeIceCandidatePair.remoteCandidate||{},null));return activeIceCandidatePair}module.exports=RoomV2},{"../../stats/statsreport":112,"../../util":126,"../../util/movingaveragedelta":131,"../../util/twilio-video-errors":143,"../room":62,"./dominantspeakersignaling":65,"./networkqualitymonitor":72,"./networkqualitysignaling":73,"./recording":76,"./remoteparticipant":77,"./renderhintssignaling":79,"./trackprioritysignaling":81,"./trackswitchoffsignaling":82}],81:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaSignaling=require("./mediasignaling");var TrackPrioritySignaling=function(_super){__extends(TrackPrioritySignaling,_super);function TrackPrioritySignaling(getReceiver,options){var _this=_super.call(this,getReceiver,"track_priority",options)||this;Object.defineProperties(_this,{_enqueuedPriorityUpdates:{value:new Map}});_this.on("ready",function(transport){Array.from(_this._enqueuedPriorityUpdates.keys()).forEach(function(trackSid){transport.publish({type:"track_priority",track:trackSid,subscribe:_this._enqueuedPriorityUpdates.get(trackSid)})})});return _this}TrackPrioritySignaling.prototype.sendTrackPriorityUpdate=function(trackSid,publishOrSubscribe,priority){if(publishOrSubscribe!=="subscribe"){throw new Error("only subscribe priorities are supported, found: "+publishOrSubscribe)}this._enqueuedPriorityUpdates.set(trackSid,priority);if(this._transport){this._transport.publish({type:"track_priority",track:trackSid,subscribe:priority})}};return TrackPrioritySignaling}(MediaSignaling);module.exports=TrackPrioritySignaling},{"./mediasignaling":71}],82:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var MediaSignaling=require("./mediasignaling");var TrackSwitchOffSignaling=function(_super){__extends(TrackSwitchOffSignaling,_super);function TrackSwitchOffSignaling(getReceiver,options){var _this=_super.call(this,getReceiver,"track_switch_off",options)||this;_this.on("ready",function(transport){transport.on("message",function(message){switch(message.type){case"track_switch_off":_this._setTrackSwitchOffUpdates(message.off||[],message.on||[]);break;default:break}})});return _this}TrackSwitchOffSignaling.prototype._setTrackSwitchOffUpdates=function(tracksSwitchedOff,tracksSwitchedOn){this.emit("updated",tracksSwitchedOff,tracksSwitchedOn)};return TrackSwitchOffSignaling}(MediaSignaling);module.exports=TrackSwitchOffSignaling},{"./mediasignaling":71}],83:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var getSdpFormat=require("@twilio/webrtc/lib/util/sdp").getSdpFormat;var StateMachine=require("../../statemachine");var TwilioConnection=require("../../twilioconnection");var DefaultBackoff=require("backoff");var reconnectBackoffConfig=require("../../util/constants").reconnectBackoffConfig;var Timeout=require("../../util/timeout");var _a=require("../../util/constants"),SDK_NAME=_a.SDK_NAME,SDK_VERSION=_a.SDK_VERSION;var _b=require("../../util"),createBandwidthProfilePayload=_b.createBandwidthProfilePayload,createMediaSignalingPayload=_b.createMediaSignalingPayload,createSubscribePayload=_b.createSubscribePayload,getUserAgent=_b.getUserAgent,isNonArrayObject=_b.isNonArrayObject;var _c=require("../../util/twilio-video-errors"),createTwilioError=_c.createTwilioError,RoomCompletedError=_c.RoomCompletedError,SignalingConnectionError=_c.SignalingConnectionError,SignalingServerBusyError=_c.SignalingServerBusyError;var ICE_VERSION=1;var RSP_VERSION=2;var states={connecting:["connected","disconnected"],connected:["disconnected","syncing"],syncing:["connected","disconnected"],disconnected:[]};var TwilioConnectionTransport=function(_super){__extends(TwilioConnectionTransport,_super);function TwilioConnectionTransport(name,accessToken,localParticipant,peerConnectionManager,wsServer,options){var _this=this;options=Object.assign({Backoff:DefaultBackoff,TwilioConnection:TwilioConnection,iceServers:null,sdpFormat:getSdpFormat(options.sdpSemantics),trackPriority:true,trackSwitchOff:true,renderHints:true,userAgent:getUserAgent()},options);_this=_super.call(this,"connecting",states)||this;Object.defineProperties(_this,{_accessToken:{value:accessToken},_automaticSubscription:{value:options.automaticSubscription},_bandwidthProfile:{value:options.bandwidthProfile},_dominantSpeaker:{value:options.dominantSpeaker},_eventObserver:{value:options.eventObserver,writable:false},_renderHints:{value:options.renderHints},
48
48
  _iceServersStatus:{value:Array.isArray(options.iceServers)?"overrode":"acquire"},_localParticipant:{value:localParticipant},_name:{value:name},_networkQuality:{value:isNonArrayObject(options.networkQuality)||options.networkQuality},_options:{value:options},_peerConnectionManager:{value:peerConnectionManager},_sessionTimer:{value:null,writable:true},_sessionTimeoutMS:{value:0,writable:true},_reconnectBackoff:{value:options.Backoff.exponential(reconnectBackoffConfig)},_session:{value:null,writable:true},_trackPriority:{value:options.trackPriority},_trackSwitchOff:{value:options.trackSwitchOff},_twilioConnection:{value:null,writable:true},_updatesReceived:{value:[]},_updatesToSend:{value:[]},_userAgent:{value:options.userAgent},_wsServer:{value:wsServer}});setupTransport(_this);return _this}TwilioConnectionTransport.prototype._createConnectOrSyncOrDisconnectMessage=function(){if(this.state==="connected"){return null}if(this.state==="disconnected"){return{session:this._session,type:"disconnect",version:RSP_VERSION}}var type={connecting:"connect",syncing:"sync"}[this.state];var message={name:this._name,participant:this._localParticipant.getState(),peer_connections:this._peerConnectionManager.getStates(),type:type,version:RSP_VERSION};if(message.type==="connect"){message.ice_servers=this._iceServersStatus;message.publisher={name:SDK_NAME,sdk_version:SDK_VERSION,user_agent:this._userAgent};if(this._bandwidthProfile){message.bandwidth_profile=createBandwidthProfilePayload(this._bandwidthProfile)}message.media_signaling=createMediaSignalingPayload(this._dominantSpeaker,this._networkQuality,this._trackPriority,this._trackSwitchOff,this._renderHints);message.subscribe=createSubscribePayload(this._automaticSubscription);var sdpFormat=this._options.sdpFormat;if(sdpFormat){message.format=sdpFormat}message.token=this._accessToken}else if(message.type==="sync"){message.session=this._session;message.token=this._accessToken}else if(message.type==="update"){message.session=this._session}return message};TwilioConnectionTransport.prototype._createIceMessage=function(){return{edge:"roaming",token:this._accessToken,type:"ice",version:ICE_VERSION}};TwilioConnectionTransport.prototype._sendConnectOrSyncOrDisconnectMessage=function(){var message=this._createConnectOrSyncOrDisconnectMessage();if(message){this._twilioConnection.sendMessage(message)}};TwilioConnectionTransport.prototype.disconnect=function(error){if(this.state!=="disconnected"){this.preempt("disconnected",null,[error]);this._sendConnectOrSyncOrDisconnectMessage();this._twilioConnection.close();return true}return false};TwilioConnectionTransport.prototype.publish=function(update){switch(this.state){case"connected":this._twilioConnection.sendMessage(Object.assign({session:this._session,type:"update",version:RSP_VERSION},update));return true;case"connecting":case"syncing":this._updatesToSend.push(update);return true;case"disconnected":default:return false}};TwilioConnectionTransport.prototype.publishEvent=function(group,name,level,payload){this._eventObserver.emit("event",{group:group,name:name,level:level,payload:payload})};TwilioConnectionTransport.prototype.sync=function(){if(this.state==="connected"){this.preempt("syncing");this._sendConnectOrSyncOrDisconnectMessage();return true}return false};TwilioConnectionTransport.prototype._setSession=function(session,sessionTimeout){this._session=session;this._sessionTimeoutMS=sessionTimeout*1e3};TwilioConnectionTransport.prototype._getReconnectTimer=function(){var _this=this;if(this._sessionTimeoutMS===0){return null}if(!this._sessionTimer){this._sessionTimer=new Timeout(function(){if(_this._sessionTimer){_this._sessionTimeoutMS=0}},this._sessionTimeoutMS)}return new Promise(function(resolve){_this._reconnectBackoff.once("ready",resolve);_this._reconnectBackoff.backoff()})};TwilioConnectionTransport.prototype._clearReconnectTimer=function(){this._reconnectBackoff.reset();if(this._sessionTimer){this._sessionTimer.clear();this._sessionTimer=null}};return TwilioConnectionTransport}(StateMachine);function reducePeerConnections(peerConnections){return Array.from(peerConnections.reduce(function(peerConnectionsById,update){var reduced=peerConnectionsById.get(update.id)||update;if(!reduced.description&&update.description){reduced.description=update.description}else if(reduced.description&&update.description){if(update.description.revision>reduced.description.revision){reduced.description=update.description}}if(!reduced.ice&&update.ice){reduced.ice=update.ice}else if(reduced.ice&&update.ice){if(update.ice.revision>reduced.ice.revision){reduced.ice=update.ice}}peerConnectionsById.set(reduced.id,reduced);return peerConnectionsById},new Map).values())}function reduceUpdates(updates){return updates.reduce(function(reduced,update){if(!reduced.participant&&update.participant){reduced.participant=update.participant}else if(reduced.participant&&update.participant){if(update.participant.revision>reduced.participant.revision){reduced.participant=update.participant}}if(!reduced.peer_connections&&update.peer_connections){reduced.peer_connections=reducePeerConnections(update.peer_connections)}else if(reduced.peer_connections&&update.peer_connections){reduced.peer_connections=reducePeerConnections(reduced.peer_connections.concat(update.peer_connections))}return reduced},{})}function setupTransport(transport){function createOrResetTwilioConnection(){if(transport.state==="disconnected"){return}if(transport._twilioConnection){transport._twilioConnection.removeListener("message",handleMessage)}var _iceServersStatus=transport._iceServersStatus,_options=transport._options,_wsServer=transport._wsServer,state=transport.state;var TwilioConnection=_options.TwilioConnection;var twilioConnection=new TwilioConnection(_wsServer,Object.assign({helloBody:state==="connecting"&&_iceServersStatus==="acquire"?transport._createIceMessage():transport._createConnectOrSyncOrDisconnectMessage()},_options));twilioConnection.once("close",function(reason){if(reason===TwilioConnection.CloseReason.LOCAL){disconnect()}else{disconnect(new Error(reason))}});twilioConnection.on("message",handleMessage);transport._twilioConnection=twilioConnection}function disconnect(error){if(transport.state==="disconnected"){return}if(!error){transport.disconnect();return}var reconnectTimer=transport._getReconnectTimer();if(!reconnectTimer){var twilioError=error.message===TwilioConnection.CloseReason.BUSY?new SignalingServerBusyError:new SignalingConnectionError;transport.disconnect(twilioError);return}if(transport.state==="connected"){transport.preempt("syncing")}reconnectTimer.then(createOrResetTwilioConnection)}function handleMessage(message){if(transport.state==="disconnected"){return}if(message.type==="error"){transport.disconnect(createTwilioError(message.code,message.message));return}switch(transport.state){case"connected":switch(message.type){case"connected":case"synced":case"update":transport.emit("message",message);return;case"disconnected":transport.disconnect(message.status==="completed"?new RoomCompletedError:null);return;default:return}case"connecting":switch(message.type){case"iced":transport._options.onIced(message.ice_servers).then(function(){transport._sendConnectOrSyncOrDisconnectMessage()});return;case"connected":transport._setSession(message.session,message.options.session_timeout);transport.emit("connected",message);transport.preempt("connected");return;case"synced":case"update":transport._updatesReceived.push(message);return;case"disconnected":transport.disconnect(message.status==="completed"?new RoomCompletedError:null);return;default:return}case"syncing":switch(message.type){case"connected":case"update":transport._updatesReceived.push(message);return;case"synced":transport._clearReconnectTimer();transport.emit("message",message);transport.preempt("connected");return;case"disconnected":transport.disconnect(message.status==="completed"?new RoomCompletedError:null);return;default:return}default:return}}transport.on("stateChanged",function stateChanged(state){switch(state){case"connected":{var updates=transport._updatesToSend.splice(0);if(updates.length){transport.publish(reduceUpdates(updates))}transport._updatesReceived.splice(0).forEach(function(update){return transport.emit("message",update)});return}case"disconnected":transport._twilioConnection.removeListener("message",handleMessage);transport.removeListener("stateChanged",stateChanged);return;case"syncing":return;default:return}});var _options=transport._options,_iceServersStatus=transport._iceServersStatus;var iceServers=_options.iceServers,onIced=_options.onIced;if(_iceServersStatus==="overrode"){onIced(iceServers).then(createOrResetTwilioConnection)}else{createOrResetTwilioConnection()}}module.exports=TwilioConnectionTransport},{"../../statemachine":84,"../../twilioconnection":116,"../../util":126,"../../util/constants":120,"../../util/timeout":142,"../../util/twilio-video-errors":143,"@twilio/webrtc/lib/util/sdp":167,backoff:170}],84:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var EventEmitter=require("events").EventEmitter;var util=require("./util");var StateMachine=function(_super){__extends(StateMachine,_super);function StateMachine(initialState,states){var _this=_super.call(this)||this;var lock=null;var state=initialState;states=transformStates(states);Object.defineProperties(_this,{_lock:{get:function(){return lock},set:function(_lock){lock=_lock}},_reachableStates:{value:reachable(states)},_state:{get:function(){return state},set:function(_state){state=_state}},_states:{value:states},_whenDeferreds:{value:new Set},isLocked:{enumerable:true,get:function(){return lock!==null}},state:{enumerable:true,get:function(){return state}}});_this.on("stateChanged",function(state){_this._whenDeferreds.forEach(function(deferred){deferred.when(state,deferred.resolve,deferred.reject)})});return _this}StateMachine.prototype._whenPromise=function(when){var _this=this;if(typeof when!=="function"){return Promise.reject(new Error("when() executor must be a function"))}var deferred=util.defer();deferred.when=when;this._whenDeferreds.add(deferred);return deferred.promise.then(function(payload){_this._whenDeferreds.delete(deferred);return payload},function(error){_this._whenDeferreds.delete(deferred);throw error})};StateMachine.prototype.bracket=function(name,transitionFunction){var key;var self=this;function releaseLock(error){if(self.hasLock(key)){self.releaseLockCompletely(key)}if(error){throw error}}return this.takeLock(name).then(function gotKey(_key){key=_key;return transitionFunction(key)}).then(function success(result){releaseLock();return result},releaseLock)};StateMachine.prototype.hasLock=function(key){return this._lock===key};StateMachine.prototype.preempt=function(newState,name,payload){if(!isValidTransition(this._states,this.state,newState)){throw new Error('Cannot transition from "'+this.state+'" to "'+newState+'"')}var oldLock;if(this.isLocked){oldLock=this._lock;this._lock=null}var key=null;if(name){key=this.takeLockSync(name)}var preemptionKey=key?null:this.takeLockSync("preemption");this.transition(newState,key||preemptionKey,payload);if(oldLock){oldLock.resolve()}if(preemptionKey){this.releaseLock(preemptionKey)}return key};StateMachine.prototype.releaseLock=function(key){if(!this.isLocked){throw new Error("Could not release the lock for "+key.name+" because the StateMachine is not locked")}else if(!this.hasLock(key)){throw new Error("Could not release the lock for "+key.name+" because "+this._lock.name+" has the lock")}if(key.depth===0){this._lock=null;key.resolve()}else{key.depth--}};StateMachine.prototype.releaseLockCompletely=function(key){if(!this.isLocked){throw new Error("Could not release the lock for "+key.name+" because the StateMachine is not locked")}else if(!this.hasLock(key)){throw new Error("Could not release the lock for "+key.name+" because "+this._lock.name+" has the lock")}key.depth=0;this._lock=null;key.resolve()};StateMachine.prototype.takeLock=function(nameOrKey){var _this=this;if(typeof nameOrKey==="object"){var key_1=nameOrKey;return new Promise(function(resolve){resolve(_this.takeLockSync(key_1))})}var name=nameOrKey;if(this.isLocked){var takeLock=this.takeLock.bind(this,name);return this._lock.promise.then(takeLock)}return Promise.resolve(this.takeLockSync(name))};StateMachine.prototype.takeLockSync=function(nameOrKey){var key=typeof nameOrKey==="string"?null:nameOrKey;var name=key?key.name:nameOrKey;if(key&&!this.hasLock(key)||!key&&this.isLocked){throw new Error("Could not take the lock for "+name+" because the lock for "+this._lock.name+" was not released")}if(key){key.depth++;return key}var lock=makeLock(name);this._lock=lock;return lock};StateMachine.prototype.transition=function(newState,key,payload){payload=payload||[];if(this.isLocked){if(!key){throw new Error("You must provide the key in order to "+"transition")}else if(!this.hasLock(key)){throw new Error("Could not transition using the key for "+key.name+" because "+this._lock.name+" has the lock")}}else if(key){throw new Error("Key provided for "+key.name+", but the StateMachine was not locked (possibly due to preemption)")}if(!isValidTransition(this._states,this.state,newState)){throw new Error('Cannot transition from "'+this.state+'" to "'+newState+'"')}this._state=newState;this.emit.apply(this,__spreadArray([],__read(["stateChanged",newState].concat(payload))))};StateMachine.prototype.tryTransition=function(newState,key,payload){try{this.transition(newState,key,payload)}catch(error){return false}return true};StateMachine.prototype.when=function(state){var _this=this;if(this.state===state){return Promise.resolve(this)}else if(!isValidTransition(this._reachableStates,this.state,state)){return Promise.reject(createUnreachableError(this.state,state))}return this._whenPromise(function(newState,resolve,reject){if(newState===state){resolve(_this)}else if(!isValidTransition(_this._reachableStates,newState,state)){reject(createUnreachableError(newState,state))}})};return StateMachine}(EventEmitter);function isValidTransition(graph,from,to){return graph.get(from).has(to)}function makeLock(name){var lock=util.defer();lock.name=name;lock.depth=0;return lock}function reachable(graph){return Array.from(graph.keys()).reduce(function(newGraph,from){return newGraph.set(from,reachableFrom(graph,from))},new Map)}function reachableFrom(graph,from,to){to=to||new Set;graph.get(from).forEach(function(node){if(!to.has(node)){to.add(node);reachableFrom(graph,node,to).forEach(to.add,to)}});return to}function transformStates(states){var newStates=new Map;for(var key in states){newStates.set(key,new Set(states[key]))}return newStates}function createUnreachableError(here,there){return new Error('"'+there+'" cannot be reached from "'+here+'"')}module.exports=StateMachine},{"./util":126,events:179}],85:[function(require,module,exports){"use strict";function average(xs){xs=xs.filter(function(x){return typeof x==="number"});return xs.length<1?undefined:xs.reduce(function(y,x){return x+y})/xs.length}module.exports=average},{}],86:[function(require,module,exports){"use strict";var IceReport=function(){function IceReport(send,recv,availableSend,rtt){Object.defineProperties(this,{availableSend:{enumerable:true,value:availableSend},recv:{enumerable:true,value:recv},rtt:{enumerable:true,value:rtt},send:{enumerable:true,value:send}})}IceReport.of=function(olderStats,newerStats){var secondsElapsed=(newerStats.timestamp-olderStats.timestamp)/1e3;var deltaBytesSent=newerStats.bytesSent-olderStats.bytesSent;var deltaBytesReceived=newerStats.bytesReceived-olderStats.bytesReceived;var send=secondsElapsed>0?deltaBytesSent/secondsElapsed*8:0;var recv=secondsElapsed>0?deltaBytesReceived/secondsElapsed*8:0;var availableSend=newerStats.availableOutgoingBitrate,rtt=newerStats.currentRoundTripTime;return new IceReport(send,recv,availableSend,rtt)};return IceReport}();module.exports=IceReport},{}],87:[function(require,module,exports){"use strict";var IceReport=require("./icereport");var IceReportFactory=function(){function IceReportFactory(){Object.defineProperties(this,{lastReport:{enumerable:true,value:new IceReport(0,0),writable:true},lastStats:{enumerable:true,value:null,writable:true}})}IceReportFactory.prototype.next=function(newerStats){var olderStats=this.lastStats;this.lastStats=newerStats;if(olderStats){var report=olderStats.id===newerStats.id?IceReport.of(olderStats,newerStats):new IceReport(0,0);this.lastReport=report}return this.lastReport};return IceReportFactory}();module.exports=IceReportFactory},{"./icereport":86}],88:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackStats=require("./localtrackstats");var LocalAudioTrackStats=function(_super){__extends(LocalAudioTrackStats,_super);function LocalAudioTrackStats(trackId,statsReport,prepareForInsights){var _this=_super.call(this,trackId,statsReport,prepareForInsights)||this;Object.defineProperties(_this,{audioLevel:{value:typeof statsReport.audioInputLevel==="number"?statsReport.audioInputLevel:null,enumerable:true},jitter:{value:typeof statsReport.jitter==="number"?statsReport.jitter:null,enumerable:true}});return _this}return LocalAudioTrackStats}(LocalTrackStats);module.exports=LocalAudioTrackStats},{"./localtrackstats":89}],89:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackStats=require("./trackstats");var LocalTrackStats=function(_super){__extends(LocalTrackStats,_super);function LocalTrackStats(trackId,statsReport,prepareForInsights){var _this=_super.call(this,trackId,statsReport)||this;Object.defineProperties(_this,{bytesSent:{value:typeof statsReport.bytesSent==="number"?statsReport.bytesSent:prepareForInsights?0:null,enumerable:true},packetsSent:{value:typeof statsReport.packetsSent==="number"?statsReport.packetsSent:prepareForInsights?0:null,enumerable:true},roundTripTime:{value:typeof statsReport.roundTripTime==="number"?statsReport.roundTripTime:prepareForInsights?0:null,enumerable:true}});return _this}return LocalTrackStats}(TrackStats);module.exports=LocalTrackStats},{"./trackstats":114}],90:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var LocalTrackStats=require("./localtrackstats");var LocalVideoTrackStats=function(_super){__extends(LocalVideoTrackStats,_super);function LocalVideoTrackStats(trackId,statsReport,prepareForInsights){var _this=_super.call(this,trackId,statsReport,prepareForInsights)||this;var captureDimensions=null;if(typeof statsReport.frameWidthInput==="number"&&typeof statsReport.frameHeightInput==="number"){captureDimensions={};Object.defineProperties(captureDimensions,{width:{value:statsReport.frameWidthInput,enumerable:true},height:{value:statsReport.frameHeightInput,enumerable:true}})}var dimensions=null;if(typeof statsReport.frameWidthSent==="number"&&typeof statsReport.frameHeightSent==="number"){dimensions={};Object.defineProperties(dimensions,{width:{value:statsReport.frameWidthSent,enumerable:true},height:{value:statsReport.frameHeightSent,enumerable:true}})}Object.defineProperties(_this,{captureDimensions:{value:captureDimensions,enumerable:true},dimensions:{value:dimensions,enumerable:true},captureFrameRate:{value:typeof statsReport.frameRateInput==="number"?statsReport.frameRateInput:null,enumerable:true},frameRate:{value:typeof statsReport.frameRateSent==="number"?statsReport.frameRateSent:null,enumerable:true}});return _this}return LocalVideoTrackStats}(LocalTrackStats);module.exports=LocalVideoTrackStats},{"./localtrackstats":89}],91:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NetworkQualityMediaStats=require("./networkqualitymediastats");var NetworkQualityAudioStats=function(_super){__extends(NetworkQualityAudioStats,_super);function NetworkQualityAudioStats(mediaLevels){return _super.call(this,mediaLevels)||this}return NetworkQualityAudioStats}(NetworkQualityMediaStats);module.exports=NetworkQualityAudioStats},{"./networkqualitymediastats":95}],92:[function(require,module,exports){"use strict";var NetworkQualityBandwidthStats=function(){function NetworkQualityBandwidthStats(_a){var _b=_a.actual,actual=_b===void 0?null:_b,_c=_a.available,available=_c===void 0?null:_c,_d=_a.level,level=_d===void 0?null:_d;Object.defineProperties(this,{actual:{value:actual,enumerable:true},available:{value:available,enumerable:true},level:{value:level,enumerable:true}})}return NetworkQualityBandwidthStats}();module.exports=NetworkQualityBandwidthStats},{}],93:[function(require,module,exports){"use strict";var NetworkQualityFractionLostStats=function(){function NetworkQualityFractionLostStats(_a){var _b=_a.fractionLost,fractionLost=_b===void 0?null:_b,_c=_a.level,level=_c===void 0?null:_c;Object.defineProperties(this,{fractionLost:{value:fractionLost,enumerable:true},level:{value:level,enumerable:true}})}return NetworkQualityFractionLostStats}();module.exports=NetworkQualityFractionLostStats},{}],94:[function(require,module,exports){"use strict";var NetworkQualityLatencyStats=function(){function NetworkQualityLatencyStats(_a){var _b=_a.jitter,jitter=_b===void 0?null:_b,_c=_a.rtt,rtt=_c===void 0?null:_c,_d=_a.level,level=_d===void 0?null:_d;Object.defineProperties(this,{jitter:{value:jitter,enumerable:true},rtt:{value:rtt,enumerable:true},level:{value:level,enumerable:true}})}return NetworkQualityLatencyStats}();module.exports=NetworkQualityLatencyStats},{}],95:[function(require,module,exports){"use strict";var NetworkQualitySendStats=require("./networkqualitysendstats");var NetworkQualityRecvStats=require("./networkqualityrecvstats");var NetworkQualityMediaStats=function(){function NetworkQualityMediaStats(_a){var send=_a.send,recv=_a.recv,_b=_a.sendStats,sendStats=_b===void 0?null:_b,_c=_a.recvStats,recvStats=_c===void 0?null:_c;Object.defineProperties(this,{send:{value:send,enumerable:true},recv:{value:recv,enumerable:true},sendStats:{value:sendStats?new NetworkQualitySendStats(sendStats):null,enumerable:true},recvStats:{value:recvStats?new NetworkQualityRecvStats(recvStats):null,enumerable:true}})}return NetworkQualityMediaStats}();module.exports=NetworkQualityMediaStats},{"./networkqualityrecvstats":96,"./networkqualitysendstats":98}],96:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NetworkQualitySendOrRecvStats=require("./networkqualitysendorrecvstats");var NetworkQualityRecvStats=function(_super){__extends(NetworkQualityRecvStats,_super);function NetworkQualityRecvStats(sendOrRecvStats){return _super.call(this,sendOrRecvStats)||this}return NetworkQualityRecvStats}(NetworkQualitySendOrRecvStats);module.exports=NetworkQualityRecvStats},{"./networkqualitysendorrecvstats":97}],97:[function(require,module,exports){"use strict";var NetworkQualityBandwidthStats=require("./networkqualitybandwidthstats");var NetworkQualityFractionLostStats=require("./networkqualityfractionloststats");var NetworkQualityLatencyStats=require("./networkqualitylatencystats");var NetworkQualitySendOrRecvStats=function(){function NetworkQualitySendOrRecvStats(_a){var _b=_a.bandwidth,bandwidth=_b===void 0?null:_b,_c=_a.fractionLost,fractionLost=_c===void 0?null:_c,_d=_a.latency,latency=_d===void 0?null:_d;Object.defineProperties(this,{bandwidth:{value:bandwidth?new NetworkQualityBandwidthStats(bandwidth):null,enumerable:true},fractionLost:{value:fractionLost?new NetworkQualityFractionLostStats(fractionLost):null,enumerable:true},latency:{value:latency?new NetworkQualityLatencyStats(latency):null,enumerable:true}})}return NetworkQualitySendOrRecvStats}();module.exports=NetworkQualitySendOrRecvStats},{"./networkqualitybandwidthstats":92,"./networkqualityfractionloststats":93,"./networkqualitylatencystats":94}],98:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NetworkQualitySendOrRecvStats=require("./networkqualitysendorrecvstats");var NetworkQualitySendStats=function(_super){__extends(NetworkQualitySendStats,_super);function NetworkQualitySendStats(sendOrRecvStats){return _super.call(this,sendOrRecvStats)||this}return NetworkQualitySendStats}(NetworkQualitySendOrRecvStats);module.exports=NetworkQualitySendStats},{"./networkqualitysendorrecvstats":97}],99:[function(require,module,exports){"use strict";var NetworkQualityAudioStats=require("./networkqualityaudiostats");var NetworkQualityVideoStats=require("./networkqualityvideostats");var NetworkQualityStats=function(){function NetworkQualityStats(_a){var level=_a.level,audio=_a.audio,video=_a.video;Object.defineProperties(this,{level:{value:level,enumerable:true},audio:{value:audio?new NetworkQualityAudioStats(audio):null,enumerable:true},video:{value:video?new NetworkQualityVideoStats(video):null,enumerable:true}})}return NetworkQualityStats}();module.exports=NetworkQualityStats},{"./networkqualityaudiostats":91,"./networkqualityvideostats":100}],100:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NetworkQualityMediaStats=require("./networkqualitymediastats");var NetworkQualityVideoStats=function(_super){__extends(NetworkQualityVideoStats,_super);function NetworkQualityVideoStats(mediaLevels){return _super.call(this,mediaLevels)||this}return NetworkQualityVideoStats}(NetworkQualityMediaStats);module.exports=NetworkQualityVideoStats},{"./networkqualitymediastats":95}],101:[function(require,module,exports){"use strict";var ReceiverReport=require("./receiverreport");var SenderReport=require("./senderreport");var PeerConnectionReport=function(){function PeerConnectionReport(ice,audio,video){Object.defineProperties(this,{ice:{enumerable:true,value:ice},audio:{enumerable:true,value:audio},video:{enumerable:true,value:video}})}PeerConnectionReport.prototype.summarize=function(){var senderReports=this.audio.send.concat(this.video.send);var send=SenderReport.summarize(senderReports);var receiverReports=this.audio.recv.concat(this.video.recv);var recv=ReceiverReport.summarize(receiverReports);return{ice:this.ice,send:send,recv:recv,audio:{send:SenderReport.summarize(this.audio.send),recv:ReceiverReport.summarize(this.audio.recv)},video:{send:SenderReport.summarize(this.video.send),recv:ReceiverReport.summarize(this.video.recv)}}};return PeerConnectionReport}();module.exports=PeerConnectionReport},{"./receiverreport":103,"./senderreport":110}],102:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var __values=this&&this.__values||function(o){var s=typeof Symbol==="function"&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&typeof o.length==="number")return{next:function(){if(o&&i>=o.length)o=void 0;return{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")};var guessBrowser=require("@twilio/webrtc/lib/util").guessBrowser
49
49
  ;var IceReportFactory=require("./icereportfactory");var PeerConnectionReport=require("./peerconnectionreport");var ReceiverReportFactory=require("./receiverreportfactory");var SenderReportFactory=require("./senderreportfactory");var PeerConnectionReportFactory=function(){function PeerConnectionReportFactory(pc){Object.defineProperties(this,{pc:{enumerable:true,value:pc},ice:{enumerable:true,value:new IceReportFactory},audio:{enumerable:true,value:{send:new Map,recv:new Map}},video:{enumerable:true,value:{send:new Map,recv:new Map}},lastReport:{enumerable:true,value:null,writable:true}})}PeerConnectionReportFactory.prototype.next=function(){var _this=this;var updatePromise=guessBrowser()==="firefox"?updateFirefox(this):updateChrome(this);return updatePromise.then(function(){var audioSenderReportFactories=__spreadArray([],__read(_this.audio.send.values()));var videoSenderReportFactories=__spreadArray([],__read(_this.video.send.values()));var audioReceiverReportFactories=__spreadArray([],__read(_this.audio.recv.values()));var videoReceiverReportFactories=__spreadArray([],__read(_this.video.recv.values()));var report=new PeerConnectionReport(_this.ice.lastReport,{send:audioSenderReportFactories.map(function(factory){return factory.lastReport}).filter(function(report){return report}),recv:audioReceiverReportFactories.map(function(factory){return factory.lastReport}).filter(function(report){return report})},{send:videoSenderReportFactories.map(function(factory){return factory.lastReport}).filter(function(report){return report}),recv:videoReceiverReportFactories.map(function(factory){return factory.lastReport}).filter(function(report){return report})});_this.lastReport=report;return report})};return PeerConnectionReportFactory}();function getSenderOrReceiverReports(sendersOrReceivers){return Promise.all(sendersOrReceivers.map(function(senderOrReceiver){var trackId=senderOrReceiver.track.id;return senderOrReceiver.getStats().then(function(report){var e_1,_a;try{for(var _b=__values(report.values()),_c=_b.next();!_c.done;_c=_b.next()){var stats=_c.value;if(stats.type==="inbound-rtp"){stats.id=trackId+"-"+stats.id}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{if(_c&&!_c.done&&(_a=_b.return))_a.call(_b)}finally{if(e_1)throw e_1.error}}return[trackId,report]})})).then(function(pairs){return new Map(pairs)})}function getOrCreateSenderOrReceiverReportFactory(SenderOrReceiverReportFactory,sendersOrReceiversByMediaType,report,stats,trackId){var sendersOrReceivers=sendersOrReceiversByMediaType[stats.mediaType];if(!trackId){var trackStats=report.get(stats.trackId);if(trackStats){trackId=trackStats.trackIdentifier}}if(sendersOrReceivers&&trackId){if(sendersOrReceivers.has(stats.id)){return sendersOrReceivers.get(stats.id)}var senderOrReceiverFactory=new SenderOrReceiverReportFactory(trackId,stats);sendersOrReceivers.set(stats.id,senderOrReceiverFactory)}return null}function getSenderReportFactoriesByMediaType(factory){return{audio:factory.audio.send,video:factory.video.send}}function getReceiverReportFactoriesByMediaType(factory){return{audio:factory.audio.recv,video:factory.video.recv}}function getOrCreateSenderReportFactory(factory,report,stats,trackId){return getOrCreateSenderOrReceiverReportFactory(SenderReportFactory,getSenderReportFactoriesByMediaType(factory),report,stats,trackId)}function getOrCreateReceiverReportFactory(factory,report,stats,trackId){return getOrCreateSenderOrReceiverReportFactory(ReceiverReportFactory,getReceiverReportFactoriesByMediaType(factory),report,stats,trackId)}function getSenderReportFactoryIdsByMediaType(factory){return{audio:new Set(factory.audio.send.keys()),video:new Set(factory.video.send.keys())}}function getReceiverReportFactoryIdsByMediaType(factory){return{audio:new Set(factory.audio.recv.keys()),video:new Set(factory.video.recv.keys())}}function updateSenderReports(factory,report,senderReportFactoryIdsToDeleteByMediaType,trackId){var e_2,_a;try{for(var _b=__values(report.values()),_c=_b.next();!_c.done;_c=_b.next()){var stats=_c.value;if(stats.type==="outbound-rtp"&&!stats.isRemote){if(guessBrowser()!=="firefox"&&!stats.trackId){continue}var senderReportFactoryIdsToDelete=senderReportFactoryIdsToDeleteByMediaType[stats.mediaType];if(senderReportFactoryIdsToDelete){senderReportFactoryIdsToDelete.delete(stats.id)}var senderReportFactory=getOrCreateSenderReportFactory(factory,report,stats,trackId);if(senderReportFactory){var remoteInboundStats=report.get(stats.remoteId);senderReportFactory.next(trackId||senderReportFactory.trackId,stats,remoteInboundStats)}}}}catch(e_2_1){e_2={error:e_2_1}}finally{try{if(_c&&!_c.done&&(_a=_b.return))_a.call(_b)}finally{if(e_2)throw e_2.error}}}function updateReceiverReports(factory,report,receiverReportFactoryIdsToDeleteByMediaType,trackId){var e_3,_a;try{for(var _b=__values(report.values()),_c=_b.next();!_c.done;_c=_b.next()){var stats=_c.value;if(stats.type==="inbound-rtp"&&!stats.isRemote){var receiverReportFactoryIdsToDelete=receiverReportFactoryIdsToDeleteByMediaType[stats.mediaType];if(receiverReportFactoryIdsToDelete){receiverReportFactoryIdsToDelete.delete(stats.id)}var receiverReportFactory=getOrCreateReceiverReportFactory(factory,report,stats,trackId);if(receiverReportFactory){receiverReportFactory.next(trackId||receiverReportFactory.trackId,stats)}}}}catch(e_3_1){e_3={error:e_3_1}}finally{try{if(_c&&!_c.done&&(_a=_b.return))_a.call(_b)}finally{if(e_3)throw e_3.error}}}function deleteSenderOrReceiverReportFactories(senderOrReceiverReportFactoriesByMediaType,senderOrReceiverReportFactoryIdsByMediaType){var _loop_1=function(mediaType){var senderOrReceiverReportFactories=senderOrReceiverReportFactoriesByMediaType[mediaType];var senderOrReceiverReportFactoryIds=senderOrReceiverReportFactoryIdsByMediaType[mediaType];senderOrReceiverReportFactoryIds.forEach(function(senderOrReceiverReportFactoryId){return senderOrReceiverReportFactories.delete(senderOrReceiverReportFactoryId)})};for(var mediaType in senderOrReceiverReportFactoryIdsByMediaType){_loop_1(mediaType)}}function updateIceReport(ice,report){var e_4,_a,e_5,_b;var selectedCandidatePair;try{for(var _c=__values(report.values()),_d=_c.next();!_d.done;_d=_c.next()){var stats=_d.value;if(stats.type==="transport"){selectedCandidatePair=report.get(stats.selectedCandidatePairId)}}}catch(e_4_1){e_4={error:e_4_1}}finally{try{if(_d&&!_d.done&&(_a=_c.return))_a.call(_c)}finally{if(e_4)throw e_4.error}}if(selectedCandidatePair){ice.next(selectedCandidatePair);return}try{for(var _e=__values(report.values()),_f=_e.next();!_f.done;_f=_e.next()){var stats=_f.value;if(stats.type==="candidate-pair"&&stats.nominated&&("selected"in stats?stats.selected:true)){ice.next(stats)}}}catch(e_5_1){e_5={error:e_5_1}}finally{try{if(_f&&!_f.done&&(_b=_e.return))_b.call(_e)}finally{if(e_5)throw e_5.error}}}function updateFirefox(factory){var senders=factory.pc.getTransceivers().filter(function(transceiver){return transceiver.currentDirection&&transceiver.currentDirection.match(/send/)&&transceiver.sender.track}).map(function(transceiver){return transceiver.sender});var receivers=factory.pc.getTransceivers().filter(function(transceiver){return transceiver.currentDirection&&transceiver.currentDirection.match(/recv/)}).map(function(transceiver){return transceiver.receiver});return Promise.all([getSenderOrReceiverReports(senders),getSenderOrReceiverReports(receivers),factory.pc.getStats()]).then(function(_a){var _b=__read(_a,3),senderReports=_b[0],receiverReports=_b[1],pcReport=_b[2];var senderReportFactoriesByMediaType=getSenderReportFactoriesByMediaType(factory);var senderReportFactoryIdsToDeleteByMediaType=getSenderReportFactoryIdsByMediaType(factory);senderReports.forEach(function(report,trackId){return updateSenderReports(factory,report,senderReportFactoryIdsToDeleteByMediaType,trackId)});deleteSenderOrReceiverReportFactories(senderReportFactoriesByMediaType,senderReportFactoryIdsToDeleteByMediaType);var receiverReportFactoriesByMediaType=getReceiverReportFactoriesByMediaType(factory);var receiverReportFactoryIdsToDeleteByMediaType=getReceiverReportFactoryIdsByMediaType(factory);receiverReports.forEach(function(report,trackId){return updateReceiverReports(factory,report,receiverReportFactoryIdsToDeleteByMediaType,trackId)});deleteSenderOrReceiverReportFactories(receiverReportFactoriesByMediaType,receiverReportFactoryIdsToDeleteByMediaType);updateIceReport(factory.ice,pcReport)})}function updateChrome(factory){return factory.pc.getStats().then(function(report){var senderReportFactoriesByMediaType=getSenderReportFactoriesByMediaType(factory);var senderReportFactoryIdsToDeleteByMediaType=getSenderReportFactoryIdsByMediaType(factory);updateSenderReports(factory,report,senderReportFactoryIdsToDeleteByMediaType);deleteSenderOrReceiverReportFactories(senderReportFactoriesByMediaType,senderReportFactoryIdsToDeleteByMediaType);var receiverReportFactoriesByMediaType=getReceiverReportFactoriesByMediaType(factory);var receiverReportFactoryIdsToDeleteByMediaType=getReceiverReportFactoryIdsByMediaType(factory);updateReceiverReports(factory,report,receiverReportFactoryIdsToDeleteByMediaType);deleteSenderOrReceiverReportFactories(receiverReportFactoriesByMediaType,receiverReportFactoryIdsToDeleteByMediaType);updateIceReport(factory.ice,report)})}module.exports=PeerConnectionReportFactory},{"./icereportfactory":87,"./peerconnectionreport":101,"./receiverreportfactory":104,"./senderreportfactory":111,"@twilio/webrtc/lib/util":165}],103:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var average=require("./average");var SenderOrReceiverReport=require("./senderorreceiverreport");var sum=require("./sum");var ReceiverReport=function(_super){__extends(ReceiverReport,_super);function ReceiverReport(id,trackId,bitrate,deltaPacketsLost,deltaPacketsReceived,fractionLost,jitter){var _this=_super.call(this,id,trackId,bitrate)||this;var phonyFractionLost=deltaPacketsReceived>0?deltaPacketsLost/deltaPacketsReceived:0;Object.defineProperties(_this,{deltaPacketsLost:{enumerable:true,value:deltaPacketsLost},deltaPacketsReceived:{enumerable:true,value:deltaPacketsReceived},fractionLost:{enumerable:true,value:fractionLost},jitter:{enumerable:true,value:jitter},phonyFractionLost:{enumerable:true,value:phonyFractionLost}});return _this}ReceiverReport.of=function(trackId,olderStats,newerStats){if(olderStats.id!==newerStats.id){throw new Error("RTCStats IDs must match")}var secondsElapsed=(newerStats.timestamp-olderStats.timestamp)/1e3;var deltaBytesReceived=newerStats.bytesReceived-olderStats.bytesReceived;var bitrate=secondsElapsed>0?deltaBytesReceived/secondsElapsed*8:0;var deltaPacketsLost=Math.max(newerStats.packetsLost-olderStats.packetsLost,0);var deltaPacketsReceived=newerStats.packetsReceived-olderStats.packetsReceived;var fractionLost=newerStats.fractionLost,jitter=newerStats.jitter;return new ReceiverReport(olderStats.id,trackId,bitrate,deltaPacketsLost,deltaPacketsReceived,fractionLost,jitter)};ReceiverReport.summarize=function(reports){var summaries=reports.map(function(report){return report.summarize()});var bitrate=sum(summaries.map(function(summary){return summary.bitrate}));var fractionLost=average(summaries.map(function(summary){return summary.fractionLost}));var jitter=average(summaries.map(function(summary){return summary.jitter}));return{bitrate:bitrate,fractionLost:fractionLost,jitter:jitter}};ReceiverReport.prototype.summarize=function(){return{bitrate:this.bitrate,fractionLost:typeof this.fractionLost==="number"?this.fractionLost:this.phonyFractionLost,jitter:this.jitter}};return ReceiverReport}(SenderOrReceiverReport);module.exports=ReceiverReport},{"./average":85,"./senderorreceiverreport":108,"./sum":113}],104:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var ReceiverReport=require("./receiverreport");var SenderOrReceiverReportFactory=require("./senderorreceiverreportfactory");var ReceiverReportFactory=function(_super){__extends(ReceiverReportFactory,_super);function ReceiverReportFactory(trackId,initialStats){var _this=_super.call(this,initialStats.id,trackId,initialStats)||this;Object.defineProperties(_this,{lastReport:{enumerable:true,value:null,writable:true}});return _this}ReceiverReportFactory.prototype.next=function(trackId,newerStats){var olderStats=this.lastStats;this.lastStats=newerStats;this.trackId=trackId;var report=ReceiverReport.of(trackId,olderStats,newerStats);this.lastReport=report;return report};return ReceiverReportFactory}(SenderOrReceiverReportFactory);module.exports=ReceiverReportFactory},{"./receiverreport":103,"./senderorreceiverreportfactory":109}],105:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackStats=require("./remotetrackstats");var RemoteAudioTrackStats=function(_super){__extends(RemoteAudioTrackStats,_super);function RemoteAudioTrackStats(trackId,statsReport){var _this=_super.call(this,trackId,statsReport)||this;Object.defineProperties(_this,{audioLevel:{value:typeof statsReport.audioOutputLevel==="number"?statsReport.audioOutputLevel:null,enumerable:true},jitter:{value:typeof statsReport.jitter==="number"?statsReport.jitter:null,enumerable:true}});return _this}return RemoteAudioTrackStats}(RemoteTrackStats);module.exports=RemoteAudioTrackStats},{"./remotetrackstats":106}],106:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TrackStats=require("./trackstats");var RemoteTrackStats=function(_super){__extends(RemoteTrackStats,_super);function RemoteTrackStats(trackId,statsReport){var _this=_super.call(this,trackId,statsReport)||this;Object.defineProperties(_this,{bytesReceived:{value:typeof statsReport.bytesReceived==="number"?statsReport.bytesReceived:null,enumerable:true},packetsReceived:{value:typeof statsReport.packetsReceived==="number"?statsReport.packetsReceived:null,enumerable:true}});return _this}return RemoteTrackStats}(TrackStats);module.exports=RemoteTrackStats},{"./trackstats":114}],107:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var RemoteTrackStats=require("./remotetrackstats");var RemoteVideoTrackStats=function(_super){__extends(RemoteVideoTrackStats,_super);function RemoteVideoTrackStats(trackId,statsReport){var _this=_super.call(this,trackId,statsReport)||this;var dimensions=null;if(typeof statsReport.frameWidthReceived==="number"&&typeof statsReport.frameHeightReceived==="number"){dimensions={};Object.defineProperties(dimensions,{width:{value:statsReport.frameWidthReceived,enumerable:true},height:{value:statsReport.frameHeightReceived,enumerable:true}})}Object.defineProperties(_this,{dimensions:{value:dimensions,enumerable:true},frameRate:{value:typeof statsReport.frameRateReceived==="number"?statsReport.frameRateReceived:null,enumerable:true}});return _this}return RemoteVideoTrackStats}(RemoteTrackStats);module.exports=RemoteVideoTrackStats},{"./remotetrackstats":106}],108:[function(require,module,exports){"use strict";var SenderOrReceiverReport=function(){function SenderOrReceiverReport(id,trackId,bitrate){Object.defineProperties(this,{id:{enumerable:true,value:id},trackId:{enumerable:true,value:trackId},bitrate:{enumerable:true,value:bitrate}})}return SenderOrReceiverReport}();module.exports=SenderOrReceiverReport},{}],109:[function(require,module,exports){"use strict";var SenderOrReceiverReportFactory=function(){function SenderOrReceiverReportFactory(id,trackId,initialStats){Object.defineProperties(this,{id:{enumerable:true,value:id,writable:true},trackId:{enumerable:true,value:trackId,writable:true},lastStats:{enumerable:true,value:initialStats,writable:true}})}return SenderOrReceiverReportFactory}();module.exports=SenderOrReceiverReportFactory},{}],110:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var average=require("./average");var SenderOrReceiverReport=require("./senderorreceiverreport");var sum=require("./sum");var SenderReport=function(_super){__extends(SenderReport,_super);function SenderReport(id,trackId,bitrate,rtt){var _this=_super.call(this,id,trackId,bitrate)||this;Object.defineProperties(_this,{rtt:{enumerable:true,value:rtt}});return _this}SenderReport.of=function(trackId,olderStats,newerStats,newerRemoteStats){if(olderStats.id!==newerStats.id){throw new Error("RTCStats IDs must match")}var secondsElapsed=(newerStats.timestamp-olderStats.timestamp)/1e3;var deltaBytesSent=newerStats.bytesSent-olderStats.bytesSent;var bitrate=secondsElapsed>0?deltaBytesSent/secondsElapsed*8:0;var rtt=newerRemoteStats&&typeof newerRemoteStats.roundTripTime==="number"?newerRemoteStats.roundTripTime/1e3:undefined;return new SenderReport(olderStats.id,trackId,bitrate,rtt)};SenderReport.summarize=function(reports){var bitrate=sum(reports.map(function(report){return report.bitrate}));var rtt=average(reports.map(function(report){return report.rtt}));return{bitrate:bitrate,rtt:rtt}};return SenderReport}(SenderOrReceiverReport);module.exports=SenderReport},{"./average":85,"./senderorreceiverreport":108,"./sum":113}],111:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var SenderOrReceiverReportFactory=require("./senderorreceiverreportfactory");var SenderReport=require("./senderreport");var SenderReportFactory=function(_super){__extends(SenderReportFactory,_super);function SenderReportFactory(trackId,initialStats){var _this=_super.call(this,initialStats.id,trackId,initialStats)||this;Object.defineProperties(_this,{lastReport:{enumerable:true,value:null,writable:true}});return _this}SenderReportFactory.prototype.next=function(trackId,newerStats,newerRemoteStats){var olderStats=this.lastStats;this.lastStats=newerStats;this.trackId=trackId;var report=SenderReport.of(trackId,olderStats,newerStats,newerRemoteStats);this.lastReport=report;return report};return SenderReportFactory}(SenderOrReceiverReportFactory);module.exports=SenderReportFactory},{"./senderorreceiverreportfactory":109,"./senderreport":110}],112:[function(require,module,exports){"use strict";var LocalAudioTrackStats=require("./localaudiotrackstats");var LocalVideoTrackStats=require("./localvideotrackstats");var RemoteAudioTrackStats=require("./remoteaudiotrackstats");var RemoteVideoTrackStats=require("./remotevideotrackstats");var StatsReport=function(){function StatsReport(peerConnectionId,statsResponse,prepareForInsights){if(typeof peerConnectionId!=="string"){throw new Error("RTCPeerConnection id must be a string")}Object.defineProperties(this,{peerConnectionId:{value:peerConnectionId,enumerable:true},localAudioTrackStats:{value:statsResponse.localAudioTrackStats.map(function(report){return new LocalAudioTrackStats(report.trackId,report,prepareForInsights)}),enumerable:true},localVideoTrackStats:{value:statsResponse.localVideoTrackStats.map(function(report){return new LocalVideoTrackStats(report.trackId,report,prepareForInsights)}),enumerable:true},remoteAudioTrackStats:{value:statsResponse.remoteAudioTrackStats.map(function(report){return new RemoteAudioTrackStats(report.trackId,report)}),enumerable:true},remoteVideoTrackStats:{value:statsResponse.remoteVideoTrackStats.map(function(report){return new RemoteVideoTrackStats(report.trackId,report)}),enumerable:true}})}return StatsReport}();module.exports=StatsReport},{"./localaudiotrackstats":88,"./localvideotrackstats":90,"./remoteaudiotrackstats":105,"./remotevideotrackstats":107}],113:[function(require,module,exports){"use strict";function sum(xs){return xs.reduce(function(y,x){return typeof x==="number"?x+y:y},0)}module.exports=sum},{}],114:[function(require,module,exports){"use strict";var TrackStats=function(){function TrackStats(trackId,statsReport){if(typeof trackId!=="string"){throw new Error("Track id must be a string")}Object.defineProperties(this,{trackId:{value:trackId,enumerable:true},trackSid:{value:statsReport.trackSid,enumerable:true},timestamp:{value:statsReport.timestamp,enumerable:true},ssrc:{value:statsReport.ssrc,enumerable:true},packetsLost:{value:typeof statsReport.packetsLost==="number"?statsReport.packetsLost:null,enumerable:true},codec:{value:typeof statsReport.codecName==="string"?statsReport.codecName:null,enumerable:true}})}return TrackStats}();module.exports=TrackStats},{}],115:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var TrackTransceiver=function(_super){__extends(TrackTransceiver,_super);function TrackTransceiver(id,kind){var _this=_super.call(this)||this;Object.defineProperties(_this,{id:{enumerable:true,value:id},kind:{enumerable:true,value:kind}});return _this}TrackTransceiver.prototype.stop=function(){this.emit("stopped")};return TrackTransceiver}(EventEmitter);module.exports=TrackTransceiver},{events:179}],116:[function(require,module,exports){(function(global){(function(){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var StateMachine=require("./statemachine");var _a=require("./util"),buildLogLevels=_a.buildLogLevels,makeUUID=_a.makeUUID;var Log=require("./util/log");var NetworkMonitor=require("./util/networkmonitor");var Timeout=require("./util/timeout");var nInstances=0;var states={closed:[],connecting:["closed","open","waiting"],early:["closed","connecting"],open:["closed"],waiting:["closed","connecting","early","open"]};var events={closed:"close",open:"open",waiting:"waiting"};var TCMP_VERSION=2;var DEFAULT_MAX_CONSECUTIVE_MISSED_HEARTBEATS=3;var DEFAULT_MAX_CONSECUTIVE_FAILED_HELLOS=3;var DEFAULT_MAX_REQUESTED_HEARTBEAT_TIMEOUT=5e3;var DEFAULT_OPEN_TIMEOUT=15e3;var DEFAULT_WELCOME_TIMEOUT=5e3;var OUTGOING_HEARTBEAT_OFFSET=200;var WS_CLOSE_NORMAL=1e3;var WS_CLOSE_WELCOME_TIMEOUT=3e3;var WS_CLOSE_HEARTBEATS_MISSED=3001;var WS_CLOSE_HELLO_FAILED=3002;var WS_CLOSE_SEND_FAILED=3003;var WS_CLOSE_NETWORK_CHANGED=3004;var WS_CLOSE_BUSY_WAIT=3005;var WS_CLOSE_SERVER_BUSY=3006;var WS_CLOSE_OPEN_TIMEOUT=3007;var toplevel=global.window||global;var WebSocket=toplevel.WebSocket?toplevel.WebSocket:require("ws");var CloseReason={BUSY:"busy",FAILED:"failed",LOCAL:"local",REMOTE:"remote",TIMEOUT:"timeout"};var wsCloseCodesToCloseReasons=new Map([[WS_CLOSE_WELCOME_TIMEOUT,CloseReason.TIMEOUT],[WS_CLOSE_HEARTBEATS_MISSED,CloseReason.TIMEOUT],[WS_CLOSE_HELLO_FAILED,CloseReason.FAILED],[WS_CLOSE_SEND_FAILED,CloseReason.FAILED],[WS_CLOSE_NETWORK_CHANGED,CloseReason.TIMEOUT],[WS_CLOSE_SERVER_BUSY,CloseReason.BUSY],[WS_CLOSE_OPEN_TIMEOUT,CloseReason.TIMEOUT]]);var TwilioConnection=function(_super){__extends(TwilioConnection,_super);function TwilioConnection(serverUrl,options){var _this=_super.call(this,"early",states)||this;options=Object.assign({helloBody:null,maxConsecutiveFailedHellos:DEFAULT_MAX_CONSECUTIVE_FAILED_HELLOS,maxConsecutiveMissedHeartbeats:DEFAULT_MAX_CONSECUTIVE_MISSED_HEARTBEATS,requestedHeartbeatTimeout:DEFAULT_MAX_REQUESTED_HEARTBEAT_TIMEOUT,openTimeout:DEFAULT_OPEN_TIMEOUT,welcomeTimeout:DEFAULT_WELCOME_TIMEOUT,Log:Log,WebSocket:WebSocket},options);var logLevels=buildLogLevels(options.logLevel);var log=new options.Log("default",_this,logLevels,options.loggerName);var networkMonitor=options.networkMonitor?new NetworkMonitor(function(){var type=networkMonitor.type;var reason="Network changed"+(type?" to "+type:"");log.debug(reason);_this._close({code:WS_CLOSE_NETWORK_CHANGED,reason:reason})}):null;Object.defineProperties(_this,{_busyWaitTimeout:{value:null,writable:true},_consecutiveHeartbeatsMissed:{value:0,writable:true},_cookie:{value:null,writable:true},_eventObserver:{value:options.eventObserver},_heartbeatTimeout:{value:null,writable:true},_hellosLeft:{value:options.maxConsecutiveFailedHellos,writable:true},_instanceId:{value:++nInstances},_log:{value:log},_messageQueue:{value:[]},_networkMonitor:{value:networkMonitor},_options:{value:options},_openTimeout:{value:null,writable:true},_sendHeartbeatTimeout:{value:null,writable:true},_serverUrl:{value:serverUrl},_welcomeTimeout:{value:null,writable:true},_ws:{value:null,writable:true}});var eventsToLevels={connecting:"info",early:"info",open:"info",waiting:"warning",closed:"info"};_this.on("stateChanged",function(state){var args=[];for(var _i=1;_i<arguments.length;_i++){args[_i-1]=arguments[_i]}if(state in events){_this.emit.apply(_this,__spreadArray([events[state]],__read(args)))}var event={name:state,group:"signaling",level:eventsToLevels[_this.state]};if(state==="closed"){var _a=__read(args,1),reason=_a[0];event.payload={reason:reason};event.level=reason===CloseReason.LOCAL?"info":"error"}_this._eventObserver.emit("event",event)});_this._eventObserver.emit("event",{name:_this.state,group:"signaling",level:eventsToLevels[_this.state]});_this._connect();return _this}TwilioConnection.prototype.toString=function(){return"[TwilioConnection #"+this._instanceId+": "+this._ws.url+"]"};TwilioConnection.prototype._close=function(_a){var code=_a.code,reason=_a.reason;if(this.state==="closed"){return}if(this._openTimeout){this._openTimeout.clear()}if(this._welcomeTimeout){this._welcomeTimeout.clear()}if(this._heartbeatTimeout){this._heartbeatTimeout.clear()}if(this._sendHeartbeatTimeout){this._sendHeartbeatTimeout.clear()}if(this._networkMonitor){this._networkMonitor.stop()}if(this._busyWaitTimeout&&code!==WS_CLOSE_BUSY_WAIT){this._busyWaitTimeout.clear()}this._messageQueue.splice(0);var log=this._log;if(code===WS_CLOSE_NORMAL){log.debug("Closed");this.transition("closed",null,[CloseReason.LOCAL])}else{log.warn("Closed: "+code+" - "+reason);if(code!==WS_CLOSE_BUSY_WAIT){this.transition("closed",null,[wsCloseCodesToCloseReasons.get(code)||CloseReason.REMOTE])}}var readyState=this._ws.readyState;var WebSocket=this._options.WebSocket;if(readyState!==WebSocket.CLOSING&&readyState!==WebSocket.CLOSED){this._ws.close(code,reason)}};TwilioConnection.prototype._connect=function(){var _this=this;var log=this._log;if(this.state==="waiting"){this.transition("early")}else if(this.state!=="early"){log.warn('Unexpected state "'+this.state+'" for connecting to the'+" TCMP server.");return}this._ws=new this._options.WebSocket(this._serverUrl);var ws=this._ws;log.debug("Created a new WebSocket:",ws);ws.addEventListener("close",function(event){return _this._close(event)});var openTimeout=this._options.openTimeout;this._openTimeout=new Timeout(function(){var reason="Failed to open in "+openTimeout+" ms";_this._close({code:WS_CLOSE_OPEN_TIMEOUT,reason:reason})},openTimeout);ws.addEventListener("open",function(){log.debug("WebSocket opened:",ws);_this._openTimeout.clear();_this._startHandshake();if(_this._networkMonitor){_this._networkMonitor.start()}});ws.addEventListener("message",function(message){log.debug("Incoming: "+message.data);try{message=JSON.parse(message.data)}catch(error){_this.emit("error",error);return}switch(message.type){case"bad":
50
- _this._handleBad(message);break;case"busy":_this._handleBusy(message);break;case"bye":break;case"msg":_this._handleMessage(message);case"heartbeat":_this._handleHeartbeat();break;case"welcome":_this._handleWelcome(message);break;default:_this._log.debug("Unknown message type: "+message.type);_this.emit("error",new Error("Unknown message type: "+message.type));break}})};TwilioConnection.prototype._handleBad=function(_a){var reason=_a.reason;var log=this._log;if(!["connecting","open"].includes(this.state)){log.warn('Unexpected state "'+this.state+'" for handling a "bad" message'+" from the TCMP server.");return}if(this.state==="connecting"){log.warn("Closing: "+WS_CLOSE_HELLO_FAILED+" - "+reason);this._close({code:WS_CLOSE_HELLO_FAILED,reason:reason});return}log.debug("Error: "+reason);this.emit("error",new Error(reason))};TwilioConnection.prototype._handleBusy=function(_a){var _this=this;var cookie=_a.cookie,keepAlive=_a.keepAlive,retryAfter=_a.retryAfter;var log=this._log;if(!["connecting","waiting"].includes(this.state)){log.warn('Unexpected state "'+this.state+'" for handling a "busy" message'+" from the TCMP server.");return}if(this._busyWaitTimeout){this._busyWaitTimeout.clear()}if(this._welcomeTimeout){this._welcomeTimeout.clear()}var reason=retryAfter<0?'Received terminal "busy" message':'Received "busy" message, retrying after '+retryAfter+" ms";if(retryAfter<0){log.warn("Closing: "+WS_CLOSE_SERVER_BUSY+" - "+reason);this._close({code:WS_CLOSE_SERVER_BUSY,reason:reason});return}var maxConsecutiveFailedHellos=this._options.maxConsecutiveFailedHellos;this._hellosLeft=maxConsecutiveFailedHellos;this._cookie=cookie||null;if(keepAlive){log.warn(reason);this._busyWaitTimeout=new Timeout(function(){return _this._startHandshake()},retryAfter)}else{log.warn("Closing: "+WS_CLOSE_BUSY_WAIT+" - "+reason);this._close({code:WS_CLOSE_BUSY_WAIT,reason:reason});this._busyWaitTimeout=new Timeout(function(){return _this._connect()},retryAfter)}this.transition("waiting",null,[keepAlive,retryAfter])};TwilioConnection.prototype._handleHeartbeat=function(){if(this.state!=="open"){this._log.warn('Unexpected state "'+this.state+'" for handling a "heartbeat"'+" message from the TCMP server.");return}this._heartbeatTimeout.reset()};TwilioConnection.prototype._handleHeartbeatTimeout=function(){if(this.state!=="open"){return}var log=this._log;var maxConsecutiveMissedHeartbeats=this._options.maxConsecutiveMissedHeartbeats;log.debug("Consecutive heartbeats missed: "+maxConsecutiveMissedHeartbeats);var reason="Missed "+maxConsecutiveMissedHeartbeats+' "heartbeat" messages';log.warn("Closing: "+WS_CLOSE_HEARTBEATS_MISSED+" - "+reason);this._close({code:WS_CLOSE_HEARTBEATS_MISSED,reason:reason})};TwilioConnection.prototype._handleMessage=function(_a){var body=_a.body;if(this.state!=="open"){this._log.warn('Unexpected state "'+this.state+'" for handling a "msg" message'+" from the TCMP server.");return}this.emit("message",body)};TwilioConnection.prototype._handleWelcome=function(_a){var _this=this;var negotiatedTimeout=_a.negotiatedTimeout;var log=this._log;if(!["connecting","waiting"].includes(this.state)){log.warn('Unexpected state "'+this.state+'" for handling a "welcome"'+" message from the TCMP server.");return}if(this.state==="waiting"){log.debug('Received "welcome" message, no need to retry connection.');this._busyWaitTimeout.clear()}var maxConsecutiveMissedHeartbeats=this._options.maxConsecutiveMissedHeartbeats;var heartbeatTimeout=negotiatedTimeout*maxConsecutiveMissedHeartbeats;var outgoingHeartbeatTimeout=negotiatedTimeout-OUTGOING_HEARTBEAT_OFFSET;this._welcomeTimeout.clear();this._heartbeatTimeout=new Timeout(function(){return _this._handleHeartbeatTimeout()},heartbeatTimeout);this._messageQueue.splice(0).forEach(function(message){return _this._send(message)});this._sendHeartbeatTimeout=new Timeout(function(){return _this._sendHeartbeat()},outgoingHeartbeatTimeout);this.transition("open")};TwilioConnection.prototype._handleWelcomeTimeout=function(){if(this.state!=="connecting"){return}var log=this._log;if(this._hellosLeft<=0){var reason="All handshake attempts failed";log.warn("Closing: "+WS_CLOSE_WELCOME_TIMEOUT+" - "+reason);this._close({code:WS_CLOSE_WELCOME_TIMEOUT,reason:reason});return}var maxConsecutiveFailedHellos=this._options.maxConsecutiveFailedHellos;log.warn("Handshake attempt "+(maxConsecutiveFailedHellos-this._hellosLeft)+" failed");this._startHandshake()};TwilioConnection.prototype._send=function(message){var readyState=this._ws.readyState;var WebSocket=this._options.WebSocket;if(readyState===WebSocket.OPEN){var data=JSON.stringify(message);this._log.debug("Outgoing: "+data);try{this._ws.send(data);if(this._sendHeartbeatTimeout){this._sendHeartbeatTimeout.reset()}}catch(error){var reason="Failed to send message";this._log.warn("Closing: "+WS_CLOSE_SEND_FAILED+" - "+reason);this._close({code:WS_CLOSE_SEND_FAILED,reason:reason})}}};TwilioConnection.prototype._sendHeartbeat=function(){if(this.state==="closed"){return}this._send({type:"heartbeat"})};TwilioConnection.prototype._sendHello=function(){var _a=this._options,helloBody=_a.helloBody,timeout=_a.requestedHeartbeatTimeout;var hello={id:makeUUID(),timeout:timeout,type:"hello",version:TCMP_VERSION};if(this._cookie){hello.cookie=this._cookie}if(helloBody){hello.body=helloBody}this._send(hello)};TwilioConnection.prototype._sendOrEnqueue=function(message){var _this=this;if(this.state==="closed"){return}var sendOrEnqueue=this.state==="open"?function(message){return _this._send(message)}:function(message){return _this._messageQueue.push(message)};sendOrEnqueue(message)};TwilioConnection.prototype._startHandshake=function(){var _this=this;if(["early","waiting"].includes(this.state)){this.transition("connecting")}if(this.state!=="connecting"){return}this._hellosLeft--;this._sendHello();var welcomeTimeout=this._options.welcomeTimeout;this._welcomeTimeout=new Timeout(function(){return _this._handleWelcomeTimeout()},welcomeTimeout)};TwilioConnection.prototype.close=function(){if(this.state==="closed"){return}this._sendOrEnqueue({type:"bye"});this._close({code:WS_CLOSE_NORMAL,reason:"Normal"})};TwilioConnection.prototype.sendMessage=function(body){this._sendOrEnqueue({body:body,type:"msg"})};return TwilioConnection}(StateMachine);TwilioConnection.CloseReason=CloseReason;module.exports=TwilioConnection}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./statemachine":84,"./util":126,"./util/log":130,"./util/networkmonitor":132,"./util/timeout":142,ws:201}],117:[function(require,module,exports){"use strict";var defer=require("./").defer;var AsyncVar=function(){function AsyncVar(){Object.defineProperties(this,{_deferreds:{value:[]},_hasValue:{value:false,writable:true},_value:{value:null,writable:true}})}AsyncVar.prototype.put=function(value){this._hasValue=true;this._value=value;var deferred=this._deferreds.shift();if(deferred){deferred.resolve(value)}return this};AsyncVar.prototype.take=function(){var _this=this;if(this._hasValue&&!this._deferreds.length){this._hasValue=false;return Promise.resolve(this._value)}var deferred=defer();this._deferreds.push(deferred);return deferred.promise.then(function(value){_this._hasValue=false;return value})};return AsyncVar}();module.exports=AsyncVar},{"./":126}],118:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};function isAndroid(){return/Android/.test(navigator.userAgent)}function isIOS(){return/iPad|iPhone|iPod/.test(navigator.userAgent)}function isMobile(){return/Mobi/.test(navigator.userAgent)}function isNonChromiumEdge(browser){return browser==="chrome"&&/Edge/.test(navigator.userAgent)&&(typeof chrome==="undefined"||typeof chrome.runtime==="undefined")}function rebrandedChromeBrowser(browser){if(browser!=="chrome"){return null}if("brave"in navigator){return"brave"}var parenthesizedSubstrings=getParenthesizedSubstrings(navigator.userAgent);var nameAndVersions=parenthesizedSubstrings.reduce(function(userAgent,substring){return userAgent.replace(substring,"")},navigator.userAgent);var matches=nameAndVersions.match(/[^\s]+/g)||[];var _a=__read(matches.map(function(nameAndVersion){return nameAndVersion.split("/")[0].toLowerCase()})),browserNames=_a.slice(2);return browserNames.find(function(name){return!["chrome","mobile","safari"].includes(name)})||null}function mobileWebKitBrowser(browser){if(browser!=="safari"){return null}if("brave"in navigator){return"brave"}return["edge","edg"].find(function(name){return navigator.userAgent.toLowerCase().includes(name)})||null}function getParenthesizedSubstrings(string){var openParenthesisPositions=[];var substrings=[];for(var i=0;i<string.length;i++){if(string[i]==="("){openParenthesisPositions.push(i)}else if(string[i]===")"&&openParenthesisPositions.length>0){var openParenthesisPosition=openParenthesisPositions.pop();if(openParenthesisPositions.length===0){substrings.push(string.substring(openParenthesisPosition,i+1))}}}return substrings}module.exports={isAndroid:isAndroid,isIOS:isIOS,isMobile:isMobile,isNonChromiumEdge:isNonChromiumEdge,mobileWebKitBrowser:mobileWebKitBrowser,rebrandedChromeBrowser:rebrandedChromeBrowser}},{}],119:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var CancelablePromise=function(){function CancelablePromise(onCreate,onCancel){var _this=this;Object.defineProperties(this,{_isCancelable:{writable:true,value:true},_isCanceled:{writable:true,value:false},_onCancel:{value:onCancel}});Object.defineProperty(this,"_promise",{value:new Promise(function(resolve,reject){onCreate(function(value){_this._isCancelable=false;resolve(value)},function(reason){_this._isCancelable=false;reject(reason)},function(){return _this._isCanceled})})})}CancelablePromise.reject=function(reason){return new CancelablePromise(function rejected(resolve,reject){reject(reason)},function onCancel(){})};CancelablePromise.resolve=function(result){return new CancelablePromise(function resolved(resolve){resolve(result)},function onCancel(){})};CancelablePromise.prototype.cancel=function(){if(this._isCancelable){this._isCanceled=true;this._onCancel()}return this};CancelablePromise.prototype.catch=function(){var args=[].slice.call(arguments);var promise=this._promise;return new CancelablePromise(function onCreate(resolve,reject){promise.catch.apply(promise,__spreadArray([],__read(args))).then(resolve,reject)},this._onCancel)};CancelablePromise.prototype.then=function(){var args=[].slice.call(arguments);var promise=this._promise;return new CancelablePromise(function onCreate(resolve,reject){promise.then.apply(promise,__spreadArray([],__read(args))).then(resolve,reject)},this._onCancel)};return CancelablePromise}();module.exports=CancelablePromise},{}],120:[function(require,module,exports){"use strict";var packageInfo=require("../../package.json");module.exports.SDK_NAME=packageInfo.name+".js";module.exports.SDK_VERSION=packageInfo.version;module.exports.DEFAULT_ENVIRONMENT="prod";module.exports.DEFAULT_REALM="us1";module.exports.DEFAULT_REGION="gll";module.exports.DEFAULT_LOG_LEVEL="warn";module.exports.DEFAULT_LOGGER_NAME="twilio-video";module.exports.WS_SERVER=function(environment,region){region=region==="gll"?"global":encodeURIComponent(region);return environment==="prod"?"wss://"+region+".vss.twilio.com/signaling":"wss://"+region+".vss."+environment+".twilio.com/signaling"};module.exports.PUBLISH_MAX_ATTEMPTS=5;module.exports.PUBLISH_BACKOFF_JITTER=10;module.exports.PUBLISH_BACKOFF_MS=20;function article(word){return["a","e","i","o","u"].includes(word.toLowerCase()[0])?"an":"a"}module.exports.typeErrors={ILLEGAL_INVOKE:function(name,context){return new TypeError("Illegal call to "+name+": "+context)},INVALID_TYPE:function(name,type){return new TypeError(name+" must be "+article(type)+" "+type)},INVALID_VALUE:function(name,values){return new RangeError(name+" must be one of "+values.join(", "))},REQUIRED_ARGUMENT:function(name){return new TypeError(name+" must be specified")}};module.exports.DEFAULT_FRAME_RATE=24;module.exports.DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS=1e4;module.exports.DEFAULT_ICE_GATHERING_TIMEOUT_MS=15e3;module.exports.DEFAULT_SESSION_TIMEOUT_SEC=30;module.exports.DEFAULT_NQ_LEVEL_LOCAL=1;module.exports.DEFAULT_NQ_LEVEL_REMOTE=0;module.exports.MAX_NQ_LEVEL=3;module.exports.ICE_ACTIVITY_CHECK_PERIOD_MS=1e3;module.exports.ICE_INACTIVITY_THRESHOLD_MS=3e3;module.exports.iceRestartBackoffConfig={factor:1.1,initialDelay:1,maxDelay:module.exports.DEFAULT_SESSION_TIMEOUT_SEC*1e3,randomisationFactor:.5};module.exports.reconnectBackoffConfig={factor:1.5,initialDelay:80,randomisationFactor:.5};module.exports.subscriptionMode={MODE_COLLABORATION:"collaboration",MODE_GRID:"grid",MODE_PRESENTATION:"presentation"};module.exports.trackSwitchOffMode={MODE_DISABLED:"disabled",MODE_DETECTED:"detected",MODE_PREDICTED:"predicted"};module.exports.trackPriority={PRIORITY_HIGH:"high",PRIORITY_LOW:"low",PRIORITY_STANDARD:"standard"};module.exports.clientTrackSwitchOffControl={MODE_AUTO:"auto",MODE_MANUAL:"manual"};module.exports.videoContentPreferencesMode={MODE_AUTO:"auto",MODE_MANUAL:"manual"}},{"../../package.json":200}],121:[function(require,module,exports){"use strict";var detectSilence=require("../webaudio/detectsilence");var N_ATTEMPTS=3;var ATTEMPT_DURATION_MS=250;function detectSilentAudio(el){var AudioContextFactory=require("../webaudio/audiocontext");var holder={};var audioContext=AudioContextFactory.getOrCreate(holder);var attemptsLeft=N_ATTEMPTS;function doCheckSilence(){attemptsLeft--;return detectSilence(audioContext,el.srcObject,ATTEMPT_DURATION_MS).then(function(isSilent){if(!isSilent){return false}if(attemptsLeft>0){return doCheckSilence()}return true}).catch(function(){return true})}return doCheckSilence().finally(function(){AudioContextFactory.release(holder)})}module.exports=detectSilentAudio},{"../webaudio/audiocontext":147,"../webaudio/detectsilence":148}],122:[function(require,module,exports){"use strict";var canvas=null;var N_SAMPLES=3;var SAMPLE_HEIGHT=50;var SAMPLE_INTERVAL_MS=250;var SAMPLE_WIDTH=50;function checkSilence(el){try{var context=canvas.getContext("2d");context.drawImage(el,0,0,SAMPLE_WIDTH,SAMPLE_HEIGHT);var frame=context.getImageData(0,0,SAMPLE_WIDTH,SAMPLE_HEIGHT);var frameDataWithoutAlpha=frame.data.filter(function(item,i){return(i+1)%4});var max=Math.max.apply(Math,frameDataWithoutAlpha);return max===0}catch(ex){console.log("Error checking silence: ",ex);return false}}function detectSilentVideo(el){canvas=canvas||document.createElement("canvas");return new Promise(function(resolve){var samplesLeft=N_SAMPLES;setTimeout(function doCheckSilence(){samplesLeft--;if(!checkSilence(el)){return resolve(false)}if(samplesLeft>0){return setTimeout(doCheckSilence,SAMPLE_INTERVAL_MS)}return resolve(true)},SAMPLE_INTERVAL_MS)})}module.exports=detectSilentVideo},{}],123:[function(require,module,exports){"use strict";var DocumentVisibilityMonitor=function(){function DocumentVisibilityMonitor(nPhases){var _this=this;if(nPhases===void 0){nPhases=1}Object.defineProperties(this,{_listeners:{value:[]},_onVisibilityChange:{value:function(){_this._emitVisible(document.visibilityState==="visible")}}});for(var i=0;i<nPhases;i++){this._listeners.push([])}}DocumentVisibilityMonitor.prototype.clear=function(){var nPhases=this._listeners.length;for(var i=0;i<nPhases;i++){this._listeners[i]=[]}};DocumentVisibilityMonitor.prototype._listenerCount=function(){return this._listeners.reduce(function(count,phaseListeners){return count+phaseListeners.length},0)};DocumentVisibilityMonitor.prototype._emitVisible=function(isVisible){var _this=this;var promise=Promise.resolve();var _loop_1=function(phase){promise=promise.then(function(){return _this._emitVisiblePhase(phase,isVisible)})};for(var phase=1;phase<=this._listeners.length;phase++){_loop_1(phase)}return promise};DocumentVisibilityMonitor.prototype._emitVisiblePhase=function(phase,isVisible){var phaseListeners=this._listeners[phase-1];return Promise.all(phaseListeners.map(function(listener){var ret=listener(isVisible);return ret instanceof Promise?ret:Promise.resolve(ret)}))};DocumentVisibilityMonitor.prototype._start=function(){document.addEventListener("visibilitychange",this._onVisibilityChange)};DocumentVisibilityMonitor.prototype._stop=function(){document.removeEventListener("visibilitychange",this._onVisibilityChange)};DocumentVisibilityMonitor.prototype.onVisibilityChange=function(phase,listener){if(typeof phase!=="number"||phase<=0||phase>this._listeners.length){throw new Error("invalid phase: ",phase)}var phaseListeners=this._listeners[phase-1];phaseListeners.push(listener);if(this._listenerCount()===1){this._start()}return this};DocumentVisibilityMonitor.prototype.offVisibilityChange=function(phase,listener){if(typeof phase!=="number"||phase<=0||phase>this._listeners.length){throw new Error("invalid phase: ",phase)}var phaseListeners=this._listeners[phase-1];var index=phaseListeners.indexOf(listener);if(index!==-1){phaseListeners.splice(index,1);if(this._listenerCount()===0){this._stop()}}return this};return DocumentVisibilityMonitor}();module.exports=new DocumentVisibilityMonitor(2)},{}],124:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var VALID_GROUPS=["signaling","room","media","quality","video-processor","preflight"];var VALID_LEVELS=["debug","error","info","warning"];var EventObserver=function(_super){__extends(EventObserver,_super);function EventObserver(publisher,connectTimestamp,log,eventListener){if(eventListener===void 0){eventListener=null}var _this=_super.call(this)||this;_this.on("event",function(_a){var name=_a.name,group=_a.group,level=_a.level,payload=_a.payload;if(typeof name!=="string"){log.error("Unexpected name: ",name);throw new Error("Unexpected name: ",name)}if(!VALID_GROUPS.includes(group)){log.error("Unexpected group: ",group);throw new Error("Unexpected group: ",group)}if(!VALID_LEVELS.includes(level)){log.error("Unexpected level: ",level);throw new Error("Unexpected level: ",level)}var timestamp=Date.now();var elapsedTime=timestamp-connectTimestamp;var publisherPayload=Object.assign({elapsedTime:elapsedTime,level:level},payload?payload:{});publisher.publish(group,name,publisherPayload);var event=Object.assign({elapsedTime:elapsedTime,group:group,level:level,name:name,timestamp:timestamp},payload?{payload:payload}:{});var logLevel={debug:"debug",error:"error",info:"info",warning:"warn"}[level];log[logLevel]("event",event);if(eventListener&&group==="signaling"){eventListener.emit("event",event)}});return _this}return EventObserver}(EventEmitter);module.exports=EventObserver},{events:179}],125:[function(require,module,exports){"use strict";var Filter=function(){function Filter(options){options=Object.assign({getKey:function defaultGetKey(a){return a},getValue:function defaultGetValue(a){return a},isLessThanOrEqualTo:function defaultIsLessThanOrEqualTo(a,b){return a<=b}},options);Object.defineProperties(this,{_getKey:{value:options.getKey},_getValue:{value:options.getValue},_isLessThanOrEqualTo:{value:options.isLessThanOrEqualTo},_map:{value:new Map}})}Filter.prototype.toMap=function(){return new Map(this._map)};Filter.prototype.updateAndFilter=function(entries){return entries.filter(this.update,this)};Filter.prototype.update=function(entry){var key=this._getKey(entry);var value=this._getValue(entry);if(this._map.has(key)&&this._isLessThanOrEqualTo(value,this._map.get(key))){return false}this._map.set(key,value);return true};return Filter}();module.exports=Filter},{}],126:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var constants=require("./constants");var E=constants.typeErrors,trackPriority=constants.trackPriority;var util=require("@twilio/webrtc/lib/util");var sessionSID=require("./sid").sessionSID;function asLocalTrack(track,options){if(track instanceof options.LocalAudioTrack||track instanceof options.LocalVideoTrack||track instanceof options.LocalDataTrack){return track}if(track instanceof options.MediaStreamTrack){return track.kind==="audio"?new options.LocalAudioTrack(track,options):new options.LocalVideoTrack(track,options)}throw E.INVALID_TYPE("track","LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}function asLocalTrackPublication(track,signaling,unpublish,options){var LocalTrackPublication={audio:options.LocalAudioTrackPublication,video:options.LocalVideoTrackPublication,data:options.LocalDataTrackPublication}[track.kind];return new LocalTrackPublication(signaling,track,unpublish,options)}function capitalize(word){return word[0].toUpperCase()+word.slice(1)}function deprecateEvents(name,emitter,events,log){var warningsShown=new Set;emitter.on("newListener",function newListener(event){if(events.has(event)&&!warningsShown.has(event)){log.deprecated(name+"#"+event+" has been deprecated and scheduled for removal in twilio-video.js@2.0.0."+(events.get(event)?" Use "+name+"#"+events.get(event)+" instead.":""));warningsShown.add(event)}if(warningsShown.size>=events.size){emitter.removeListener("newListener",newListener)}})}function difference(list1,list2){list1=Array.isArray(list1)?new Set(list1):new Set(list1.values());list2=Array.isArray(list2)?new Set(list2):new Set(list2.values());var difference=new Set;list1.forEach(function(item){if(!list2.has(item)){difference.add(item)}});return difference}function filterObject(object,filterValue){return Object.keys(object).reduce(function(filtered,key){if(object[key]!==filterValue){filtered[key]=object[key]}return filtered},{})}function flatMap(list,mapFn){var listArray=list instanceof Map||list instanceof Set?Array.from(list.values()):list;mapFn=mapFn||function mapFn(item){return item};return listArray.reduce(function(flattened,item){var mapped=mapFn(item);return flattened.concat(mapped)},[])}function getUserAgent(){return typeof navigator!=="undefined"&&navigator.userAgent?navigator.userAgent:"Unknown"}function getPlatform(){var userAgent=getUserAgent();var _a=__read(userAgent.match(/\(([^)]+)\)/)||[],2),_b=_a[1],match=_b===void 0?"unknown":_b;var _c=__read(match.split(";").map(function(entry){return entry.trim()}),1),platform=_c[0];return platform.toLowerCase()}function makeUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;var v=c==="x"?r:r&3|8;return v.toString(16)})}function oncePerTick(fn){var timeout=null;function nextTick(){timeout=null;fn()}return function scheduleNextTick(){if(timeout){clearTimeout(timeout)}timeout=setTimeout(nextTick)}}function promiseFromEvents(operation,eventEmitter,successEvent,failureEvent){return new Promise(function(resolve,reject){function onSuccess(){var args=[].slice.call(arguments);if(failureEvent){eventEmitter.removeListener(failureEvent,onFailure)}resolve.apply(void 0,__spreadArray([],__read(args)))}function onFailure(){var args=[].slice.call(arguments);eventEmitter.removeListener(successEvent,onSuccess);reject.apply(void 0,__spreadArray([],__read(args)))}eventEmitter.once(successEvent,onSuccess);if(failureEvent){eventEmitter.once(failureEvent,onFailure)}operation()})}function getOrNull(obj,path){return path.split(".").reduce(function(output,step){if(!output){return null}return output[step]},obj)}function defer(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject});return deferred}function delegateMethod(source,wrapper,target,methodName){if(methodName in wrapper){return}else if(methodName.match(/^on[a-z]+$/)){return}var type;try{type=typeof source[methodName]}catch(error){}if(type!=="function"){return}wrapper[methodName]=function(){var _a;var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return(_a=this[target])[methodName].apply(_a,__spreadArray([],__read(args)))}}function delegateMethods(source,wrapper,target){for(var methodName in source){delegateMethod(source,wrapper,target,methodName)}}function isDeepEqual(val1,val2){if(val1===val2){return true}if(typeof val1!==typeof val2){return false}if(val1===null){return val2===null}if(val2===null){return false}if(Array.isArray(val1)){return Array.isArray(val2)&&val1.length===val2.length&&val1.every(function(val,i){return isDeepEqual(val,val2[i])})}if(typeof val1==="object"){var val1Keys=Object.keys(val1).sort();var val2Keys=Object.keys(val2).sort();return!Array.isArray(val2)&&isDeepEqual(val1Keys,val2Keys)&&val1Keys.every(function(key){return isDeepEqual(val1[key],val2[key])})}return false}function isNonArrayObject(object){return typeof object==="object"&&!Array.isArray(object)}function proxyProperties(source,wrapper,target){Object.getOwnPropertyNames(source).forEach(function(propertyName){proxyProperty(source,wrapper,target,propertyName)})}function proxyProperty(source,wrapper,target,propertyName){if(propertyName in wrapper){return}else if(propertyName.match(/^on[a-z]+$/)){Object.defineProperty(wrapper,propertyName,{value:null,writable:true});target.addEventListener(propertyName.slice(2),function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}wrapper.dispatchEvent.apply(wrapper,__spreadArray([],__read(args)))});return}Object.defineProperty(wrapper,propertyName,{enumerable:true,get:function(){return target[propertyName]}})}function legacyPromise(promise,onSuccess,onFailure){if(onSuccess){return promise.then(function(result){onSuccess(result)},function(error){onFailure(error)})}return promise}function buildLogLevels(logLevel){if(typeof logLevel==="string"){return{default:logLevel,media:logLevel,signaling:logLevel,webrtc:logLevel}}return logLevel}function trackClass(track,local){local=local?"Local":"";return local+(track.kind||"").replace(/\w{1}/,function(m){return m.toUpperCase()})+"Track"}function trackPublicationClass(publication,local){local=local?"Local":"";return local+(publication.kind||"").replace(/\w{1}/,function(m){return m.toUpperCase()})+"TrackPublication"}function hidePrivateProperties(object){Object.getOwnPropertyNames(object).forEach(function(name){if(name.startsWith("_")){hideProperty(object,name)}})}function hidePrivateAndCertainPublicPropertiesInClass(klass,props){return function(_super){__extends(class_1,_super);function class_1(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}var _this=_super.apply(this,__spreadArray([],__read(args)))||this;hidePrivateProperties(_this);hidePublicProperties(_this,props);return _this}return class_1}(klass)}function hideProperty(object,name){var descriptor=Object.getOwnPropertyDescriptor(object,name);descriptor.enumerable=false;Object.defineProperty(object,name,descriptor)}function hidePublicProperties(object,props){if(props===void 0){props=[]}props.forEach(function(name){if(object.hasOwnProperty(name)){hideProperty(object,name)}})}function arrayToJSON(array){return array.map(valueToJSON)}function setToJSON(set){return arrayToJSON(__spreadArray([],__read(set)))}function mapToJSON(map){return __spreadArray([],__read(map.entries())).reduce(function(json,_a){var _b;var _c=__read(_a,2),key=_c[0],value=_c[1];return Object.assign((_b={},_b[key]=valueToJSON(value),_b),json)},{})}function objectToJSON(object){return Object.entries(object).reduce(function(json,_a){var _b;var _c=__read(_a,2),key=_c[0],value=_c[1];return Object.assign((_b={},_b[key]=valueToJSON(value),_b),json)},{})}function valueToJSON(value){if(Array.isArray(value)){return arrayToJSON(value)}else if(value instanceof Set){return setToJSON(value)}else if(value instanceof Map){return mapToJSON(value)}else if(value&&typeof value==="object"){return objectToJSON(value)}return value}function createRoomConnectEventPayload(connectOptions){function boolToString(val){return val?"true":"false"}var payload={sessionSID:sessionSID,iceServers:(connectOptions.iceServers||[]).length,audioTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="audio"}).length,videoTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="video"}).length,dataTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="data"}).length};[["audio"],["automaticSubscription"],["enableDscp"],["eventListener"],["preflight"],["video"],["dominantSpeaker","enableDominantSpeaker"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;payload[eventProp]=boolToString(!!connectOptions[prop])});[["maxVideoBitrate"],["maxAudioBitrate"],["iceTransportPolicy"],["region"],["name","roomName"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;if(typeof connectOptions[prop]==="number"||typeof connectOptions[prop]==="string"){payload[eventProp]=connectOptions[prop]}});["preferredAudioCodecs","preferredVideoCodecs"].forEach(function(prop){if(prop in connectOptions){payload[prop]=JSON.stringify(connectOptions[prop])}});if("networkQuality"in connectOptions){payload.networkQualityConfiguration={};if(isNonArrayObject(connectOptions.networkQuality)){["local","remote"].forEach(function(prop){if(typeof connectOptions.networkQuality[prop]==="number"){payload.networkQualityConfiguration[prop]=connectOptions.networkQuality[prop]}})}else{payload.networkQualityConfiguration.remote=0;payload.networkQualityConfiguration.local=connectOptions.networkQuality?1:0}}if(connectOptions.bandwidthProfile&&connectOptions.bandwidthProfile.video){var videoBPOptions_1=connectOptions.bandwidthProfile.video||{};payload.bandwidthProfileOptions={}
51
- ;["mode","maxTracks","trackSwitchOffMode","dominantSpeakerPriority","maxSubscriptionBitrate","renderDimensions","contentPreferencesMode","clientTrackSwitchOffControl"].forEach(function(prop){if(typeof videoBPOptions_1[prop]==="number"||typeof videoBPOptions_1[prop]==="string"){payload.bandwidthProfileOptions[prop]=videoBPOptions_1[prop]}else if(typeof videoBPOptions_1[prop]==="boolean"){payload.bandwidthProfileOptions[prop]=boolToString(videoBPOptions_1[prop])}else if(typeof videoBPOptions_1[prop]==="object"){payload.bandwidthProfileOptions[prop]=JSON.stringify(videoBPOptions_1[prop])}})}return{group:"room",name:"connect",level:"info",payload:payload}}function createBandwidthProfilePayload(bandwidthProfile){return createRSPPayload(bandwidthProfile,[{prop:"video",type:"object",transform:createBandwidthProfileVideoPayload}])}function createBandwidthProfileVideoPayload(bandwidthProfileVideo){return createRSPPayload(bandwidthProfileVideo,[{prop:"dominantSpeakerPriority",type:"string",payloadProp:"active_speaker_priority"},{prop:"maxSubscriptionBitrate",type:"number",payloadProp:"max_subscription_bandwidth"},{prop:"maxTracks",type:"number",payloadProp:"max_tracks"},{prop:"mode",type:"string"},{prop:"renderDimensions",type:"object",payloadProp:"render_dimensions",transform:createRenderDimensionsPayload},{prop:"trackSwitchOffMode",type:"string",payloadProp:"track_switch_off"}])}function createMediaSignalingPayload(dominantSpeaker,networkQuality,trackPriority,trackSwitchOff,renderHints){var transports={transports:[{type:"data-channel"}]};return Object.assign(dominantSpeaker?{active_speaker:transports}:{},networkQuality?{network_quality:transports}:{},renderHints?{render_hints:transports}:{},trackPriority?{track_priority:transports}:{},trackSwitchOff?{track_switch_off:transports}:{})}function createDimensionsPayload(dimensions){return createRSPPayload(dimensions,[{prop:"height",type:"number"},{prop:"width",type:"number"}])}function createRenderDimensionsPayload(renderDimensions){var PRIORITY_HIGH=trackPriority.PRIORITY_HIGH,PRIORITY_LOW=trackPriority.PRIORITY_LOW,PRIORITY_STANDARD=trackPriority.PRIORITY_STANDARD;return createRSPPayload(renderDimensions,[{prop:PRIORITY_HIGH,type:"object",transform:createDimensionsPayload},{prop:PRIORITY_LOW,type:"object",transform:createDimensionsPayload},{prop:PRIORITY_STANDARD,type:"object",transform:createDimensionsPayload}])}function createRSPPayload(object,propConversions){return propConversions.reduce(function(payload,_a){var _b;var prop=_a.prop,type=_a.type,_c=_a.payloadProp,payloadProp=_c===void 0?prop:_c,_d=_a.transform,transform=_d===void 0?function(x){return x}:_d;return typeof object[prop]===type?Object.assign((_b={},_b[payloadProp]=transform(object[prop]),_b),payload):payload},{})}function createSubscribePayload(automaticSubscription){return{rules:[{type:automaticSubscription?"include":"exclude",all:true}],revision:1}}function withJitter(value,jitter){var rand=Math.random();return value-jitter+Math.floor(2*jitter*rand+.5)}function inRange(num,min,max){return min<=num&&num<=max}function isChromeScreenShareTrack(track){var isChrome=util.guessBrowser()==="chrome";return isChrome&&track.kind==="video"&&track.label&&(/^screen:[0-9]+/.test(track.label)||/^web-contents-media-stream:[0-9/]+/.test(track.label)||/^window:[0-9]+/.test(track.label))}function isUserMediaTrack(track){return typeof track.getSettings().deviceId==="string"}function waitForSometime(timeoutMS){if(timeoutMS===void 0){timeoutMS=10}return new Promise(function(resolve){return setTimeout(resolve,timeoutMS)})}function waitForEvent(eventTarget,event){return new Promise(function(resolve){eventTarget.addEventListener(event,function onevent(e){eventTarget.removeEventListener(event,onevent);resolve(e)})})}exports.constants=constants;exports.createBandwidthProfilePayload=createBandwidthProfilePayload;exports.createMediaSignalingPayload=createMediaSignalingPayload;exports.createRoomConnectEventPayload=createRoomConnectEventPayload;exports.createSubscribePayload=createSubscribePayload;exports.asLocalTrack=asLocalTrack;exports.asLocalTrackPublication=asLocalTrackPublication;exports.capitalize=capitalize;exports.deprecateEvents=deprecateEvents;exports.difference=difference;exports.filterObject=filterObject;exports.flatMap=flatMap;exports.getPlatform=getPlatform;exports.getUserAgent=getUserAgent;exports.hidePrivateProperties=hidePrivateProperties;exports.hidePrivateAndCertainPublicPropertiesInClass=hidePrivateAndCertainPublicPropertiesInClass;exports.isDeepEqual=isDeepEqual;exports.isNonArrayObject=isNonArrayObject;exports.inRange=inRange;exports.makeUUID=makeUUID;exports.oncePerTick=oncePerTick;exports.promiseFromEvents=promiseFromEvents;exports.getOrNull=getOrNull;exports.defer=defer;exports.delegateMethods=delegateMethods;exports.proxyProperties=proxyProperties;exports.legacyPromise=legacyPromise;exports.buildLogLevels=buildLogLevels;exports.trackClass=trackClass;exports.trackPublicationClass=trackPublicationClass;exports.valueToJSON=valueToJSON;exports.withJitter=withJitter;exports.isChromeScreenShareTrack=isChromeScreenShareTrack;exports.isUserMediaTrack=isUserMediaTrack;exports.waitForSometime=waitForSometime;exports.waitForEvent=waitForEvent},{"./constants":120,"./sid":140,"@twilio/webrtc/lib/util":165}],127:[function(require,module,exports){(function(global){(function(){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var getUserAgent=require("..").getUserAgent;var MAX_RECONNECT_ATTEMPTS=5;var RECONNECT_INTERVAL_MS=50;var WS_CLOSE_NORMAL=1e3;var toplevel=global.window||global;var WebSocket=toplevel.WebSocket?toplevel.WebSocket:require("ws");var util=require("../../util");var InsightsPublisher=function(_super){__extends(InsightsPublisher,_super);function InsightsPublisher(token,sdkName,sdkVersion,environment,realm,options){var _this=_super.call(this)||this;options=Object.assign({gateway:createGateway(environment,realm)+"/v1/VideoEvents",maxReconnectAttempts:MAX_RECONNECT_ATTEMPTS,reconnectIntervalMs:RECONNECT_INTERVAL_MS,userAgent:getUserAgent(),WebSocket:WebSocket},options);Object.defineProperties(_this,{_connectTimestamp:{value:0,writable:true},_eventQueue:{value:[]},_readyToConnect:{value:util.defer()},_reconnectAttemptsLeft:{value:options.maxReconnectAttempts,writable:true},_ws:{value:null,writable:true},_WebSocket:{value:options.WebSocket}});_this._readyToConnect.promise.then(function(_a){var roomSid=_a.roomSid,participantSid=_a.participantSid;var self=_this;_this.on("disconnected",function maybeReconnect(error){self._session=null;if(error&&self._reconnectAttemptsLeft>0){self.emit("reconnecting");reconnect(self,token,sdkName,sdkVersion,roomSid,participantSid,options);return}self.removeListener("disconnected",maybeReconnect)});connect(_this,token,sdkName,sdkVersion,roomSid,participantSid,options)}).catch(function(){});return _this}InsightsPublisher.prototype.connect=function(roomSid,participantSid){this._readyToConnect.resolve({roomSid:roomSid,participantSid:participantSid})};InsightsPublisher.prototype._publish=function(event){event.session=this._session;this._ws.send(JSON.stringify(event))};InsightsPublisher.prototype.disconnect=function(){if(this._ws===null||this._ws.readyState===this._WebSocket.CLOSING||this._ws.readyState===this._WebSocket.CLOSED){return false}try{this._ws.close()}catch(error){}this.emit("disconnected");return true};InsightsPublisher.prototype.publish=function(groupName,eventName,payload){if(this._ws!==null&&(this._ws.readyState===this._WebSocket.CLOSING||this._ws.readyState===this._WebSocket.CLOSED)){return false}var publishOrEnqueue=typeof this._session==="string"?this._publish.bind(this):this._eventQueue.push.bind(this._eventQueue);publishOrEnqueue({group:groupName,name:eventName,payload:payload,timestamp:Date.now(),type:"event",version:1});return true};return InsightsPublisher}(EventEmitter);function connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options){publisher._connectTimestamp=Date.now();publisher._reconnectAttemptsLeft--;publisher._ws=new options.WebSocket(options.gateway);var ws=publisher._ws;ws.addEventListener("close",function(event){if(event.code===WS_CLOSE_NORMAL){publisher.emit("disconnected");return}publisher.emit("disconnected",new Error("WebSocket Error "+event.code+": "+event.reason))});ws.addEventListener("message",function(message){handleConnectResponse(publisher,JSON.parse(message.data),options)});ws.addEventListener("open",function(){var connectRequest={type:"connect",token:token,version:1};connectRequest.publisher={name:sdkName,sdkVersion:sdkVersion,userAgent:options.userAgent,participantSid:participantSid,roomSid:roomSid};ws.send(JSON.stringify(connectRequest))})}function createGateway(environment,realm){return environment==="prod"?"wss://sdkgw."+realm+".twilio.com":"wss://sdkgw."+environment+"-"+realm+".twilio.com"}function handleConnectResponse(publisher,response,options){switch(response.type){case"connected":publisher._session=response.session;publisher._reconnectAttemptsLeft=options.maxReconnectAttempts;publisher._eventQueue.splice(0).forEach(publisher._publish,publisher);publisher.emit("connected");break;case"error":publisher._ws.close();publisher.emit("disconnected",new Error(response.message));break}}function reconnect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options){var connectInterval=Date.now()-publisher._connectTimestamp;var timeToWait=options.reconnectIntervalMs-connectInterval;if(timeToWait>0){setTimeout(function(){connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options)},timeToWait);return}connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options)}module.exports=InsightsPublisher}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"..":126,"../../util":126,events:179,ws:201}],128:[function(require,module,exports){"use strict";var InsightsPublisher=function(){function InsightsPublisher(){Object.defineProperties(this,{_connected:{writable:true,value:true}})}InsightsPublisher.prototype.connect=function(){};InsightsPublisher.prototype.disconnect=function(){if(this._connected){this._connected=false;return true}return false};InsightsPublisher.prototype.publish=function(){return this._connected};return InsightsPublisher}();module.exports=InsightsPublisher},{}],129:[function(require,module,exports){"use strict";var defer=require("./").defer;var LocalMediaRestartDeferreds=function(){function LocalMediaRestartDeferreds(){Object.defineProperties(this,{_audio:{value:defer(),writable:true},_video:{value:defer(),writable:true}});this._audio.resolve();this._video.resolve()}LocalMediaRestartDeferreds.prototype.resolveDeferred=function(kind){if(kind==="audio"){this._audio.resolve()}else{this._video.resolve()}};LocalMediaRestartDeferreds.prototype.startDeferred=function(kind){if(kind==="audio"){this._audio=defer()}else{this._video=defer()}};LocalMediaRestartDeferreds.prototype.whenResolved=function(kind){return kind==="audio"?this._audio.promise:this._video.promise};return LocalMediaRestartDeferreds}();module.exports=new LocalMediaRestartDeferreds},{"./":126}],130:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var defaultGetLogger=require("../vendor/loglevel").getLogger;var constants=require("./constants");var DEFAULT_LOG_LEVEL=constants.DEFAULT_LOG_LEVEL,DEFAULT_LOGGER_NAME=constants.DEFAULT_LOGGER_NAME;var E=require("./constants").typeErrors;var deprecationWarningsByComponentConstructor;function getDeprecationWarnings(componentConstructor){deprecationWarningsByComponentConstructor=deprecationWarningsByComponentConstructor||new Map;if(deprecationWarningsByComponentConstructor.has(componentConstructor)){return deprecationWarningsByComponentConstructor.get(componentConstructor)}var deprecationWarnings=new Set;deprecationWarningsByComponentConstructor.set(componentConstructor,deprecationWarnings);return deprecationWarnings}var Log=function(){function Log(moduleName,component,logLevels,loggerName,getLogger){if(typeof moduleName!=="string"){throw E.INVALID_TYPE("moduleName","string")}if(!component){throw E.REQUIRED_ARGUMENT("component")}if(typeof logLevels!=="object"){logLevels={}}getLogger=getLogger||defaultGetLogger;validateLogLevels(logLevels);Object.defineProperties(this,{_component:{value:component},_logLevels:{value:logLevels},_warnings:{value:new Set},_loggerName:{get:function get(){var name=loggerName&&typeof loggerName==="string"?loggerName:DEFAULT_LOGGER_NAME;if(!this._logLevelsEqual){name=name+"-"+moduleName}return name}},_logger:{get:function get(){var logger=getLogger(this._loggerName);var level=this._logLevels[moduleName]||DEFAULT_LOG_LEVEL;level=level==="off"?"silent":level;logger.setDefaultLevel(level);return logger}},_logLevelsEqual:{get:function get(){return new Set(Object.values(this._logLevels)).size===1}},logLevel:{get:function get(){return Log.getLevelByName(logLevels[moduleName]||DEFAULT_LOG_LEVEL)}},name:{get:component.toString.bind(component)}})}Log.getLevelByName=function(name){if(!isNaN(name)){return parseInt(name,10)}name=name.toUpperCase();validateLogLevel(name);return Log[name]};Log.prototype.createLog=function(moduleName,component){var name=this._loggerName;if(!this._logLevelsEqual){name=name.substring(0,name.lastIndexOf("-"))}return new Log(moduleName,component,this._logLevels,name)};Log.prototype.setLevels=function(levels){validateLogLevels(levels);Object.assign(this._logLevels,levels);return this};Log.prototype.log=function(logLevel,messages){var name=Log._levels[logLevel];if(!name){throw E.INVALID_VALUE("logLevel",LOG_LEVEL_VALUES)}name=name.toLowerCase();var prefix=[(new Date).toISOString(),name,this.name];(this._logger[name]||function noop(){}).apply(void 0,__spreadArray([],__read(prefix.concat(messages))));return this};Log.prototype.debug=function(){return this.log(Log.DEBUG,[].slice.call(arguments))};Log.prototype.deprecated=function(deprecationWarning){var deprecationWarnings=getDeprecationWarnings(this._component.constructor);if(deprecationWarnings.has(deprecationWarning)){return this}deprecationWarnings.add(deprecationWarning);return this.warn(deprecationWarning)};Log.prototype.info=function(){return this.log(Log.INFO,[].slice.call(arguments))};Log.prototype.warn=function(){return this.log(Log.WARN,[].slice.call(arguments))};Log.prototype.warnOnce=function(warning){if(this._warnings.has(warning)){return this}this._warnings.add(warning);return this.warn(warning)};Log.prototype.error=function(){return this.log(Log.ERROR,[].slice.call(arguments))};Log.prototype.throw=function(error,customMessage){if(error.clone){error=error.clone(customMessage)}this.log(Log.ERROR,error);throw error};return Log}();Object.defineProperties(Log,{DEBUG:{value:0},INFO:{value:1},WARN:{value:2},ERROR:{value:3},OFF:{value:4},_levels:{value:["DEBUG","INFO","WARN","ERROR","OFF"]}});var LOG_LEVELS_SET={};var LOG_LEVEL_VALUES=[];var LOG_LEVEL_NAMES=Log._levels.map(function(level,i){LOG_LEVELS_SET[level]=true;LOG_LEVEL_VALUES.push(i);return level});function validateLogLevel(level){if(!(level in LOG_LEVELS_SET)){throw E.INVALID_VALUE("level",LOG_LEVEL_NAMES)}}function validateLogLevels(levels){Object.keys(levels).forEach(function(moduleName){validateLogLevel(levels[moduleName].toUpperCase())})}module.exports=Log},{"../vendor/loglevel":146,"./constants":120}],131:[function(require,module,exports){"use strict";var MovingAverageDelta=function(){function MovingAverageDelta(){Object.defineProperties(this,{_samples:{value:[{denominator:0,numerator:0},{denominator:0,numerator:0}]}})}MovingAverageDelta.prototype.get=function(){var samples=this._samples;var denominatorDelta=samples[1].denominator-samples[0].denominator||Infinity;var numeratorDelta=samples[1].numerator-samples[0].numerator;return numeratorDelta/denominatorDelta};MovingAverageDelta.prototype.putSample=function(numerator,denominator){var samples=this._samples;samples.shift();samples.push({denominator:denominator,numerator:numerator})};return MovingAverageDelta}();module.exports=MovingAverageDelta},{}],132:[function(require,module,exports){"use strict";var NetworkMonitor=function(){function NetworkMonitor(onNetworkChanged,options){var _this=this;options=Object.assign({navigator:navigator,window:window},options);var nav=options.navigator;var connection=nav.connection||{type:null};var type=connection.type;var _a=connection.type?{_events:{value:["change","typechange"]},_listener:{value:function(){var networkChanged=type!==_this.type&&_this.isOnline;type=_this.type;if(networkChanged){onNetworkChanged()}}},_target:{value:connection}}:{_events:{value:["online"]},_listener:{value:onNetworkChanged},_target:{value:options.window}},_events=_a._events,_listener=_a._listener,_target=_a._target;Object.defineProperties(this,{isOnline:{enumerable:true,get:function(){return typeof nav.onLine==="boolean"?nav.onLine:true}},type:{enumerable:true,get:function(){return connection.type||null}},_listener:_listener,_events:_events,_target:_target})}NetworkMonitor.prototype.start=function(){var _this=this;this._events.forEach(function(event){_this._target.addEventListener(event,_this._listener)})};NetworkMonitor.prototype.stop=function(){var _this=this;this._events.forEach(function(event){_this._target.removeEventListener(event,_this._listener)})};return NetworkMonitor}();module.exports=NetworkMonitor},{}],133:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NullObserver=function(){function NullObserver(callback){Object.defineProperties(this,{_callback:{value:callback}})}NullObserver.prototype.observe=function(){};NullObserver.prototype.unobserve=function(){};NullObserver.prototype.makeVisible=function(videoEl){var visibleEntry=this._makeFakeEntry(videoEl,true);this._callback([visibleEntry])};NullObserver.prototype.makeInvisible=function(videoEl){var invisibleEntry=this._makeFakeEntry(videoEl,false);this._callback([invisibleEntry])};NullObserver.prototype._makeFakeEntry=function(videoElement,isIntersecting){return{target:videoElement,isIntersecting:isIntersecting}};return NullObserver}();var NullIntersectionObserver=function(_super){__extends(NullIntersectionObserver,_super);function NullIntersectionObserver(){return _super!==null&&_super.apply(this,arguments)||this}return NullIntersectionObserver}(NullObserver);var NullResizeObserver=function(_super){__extends(NullResizeObserver,_super);function NullResizeObserver(){return _super!==null&&_super.apply(this,arguments)||this}NullResizeObserver.prototype.resize=function(videoEl){var entry=this._makeFakeEntry(videoEl,true);this._callback([entry])};return NullResizeObserver}(NullObserver);module.exports={NullIntersectionObserver:NullIntersectionObserver,NullResizeObserver:NullResizeObserver,NullObserver:NullObserver}},{}],134:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var _a=require("../"),difference=_a.difference,flatMap=_a.flatMap;var setSimulcastInMediaSection=require("./simulcast");var ptToFixedBitrateAudioCodecName={0:"PCMU",8:"PCMA"};var RTCP_BITRATE=16e3;function createBLine(modifier,maxBitrate){if(!maxBitrate){return null}return"\r\nb="+modifier+":"+(modifier==="AS"?Math.round((maxBitrate+RTCP_BITRATE)/950):maxBitrate)}function createCodecMapForMediaSection(section){return Array.from(createPtToCodecName(section)).reduce(function(codecMap,pair){var pt=pair[0];var codecName=pair[1];var pts=codecMap.get(codecName)||[];return codecMap.set(codecName,pts.concat(pt))},new Map)}function createMidToMediaSectionMap(sdp){return getMediaSections(sdp).reduce(function(midsToMediaSections,mediaSection){var mid=getMidForMediaSection(mediaSection);return mid?midsToMediaSections.set(mid,mediaSection):midsToMediaSections},new Map)}function createPtToCodecName(mediaSection){return getPayloadTypesInMediaSection(mediaSection).reduce(function(ptToCodecName,pt){var rtpmapPattern=new RegExp("a=rtpmap:"+pt+" ([^/]+)");var matches=mediaSection.match(rtpmapPattern);var codecName=matches?matches[1].toLowerCase():ptToFixedBitrateAudioCodecName[pt]?ptToFixedBitrateAudioCodecName[pt].toLowerCase():"";return ptToCodecName.set(pt,codecName)},new Map)}function getFmtpAttributesForPt(pt,mediaSection){var fmtpRegex=new RegExp("^a=fmtp:"+pt+" (.+)$","m");var matches=mediaSection.match(fmtpRegex);return matches&&matches[1].split(";").reduce(function(attrs,nvPair){var _a=__read(nvPair.split("="),2),name=_a[0],value=_a[1];attrs[name]=isNaN(value)?value:parseInt(value,10);return attrs},{})}function getMidForMediaSection(mediaSection){var midMatches=mediaSection.match(/^a=mid:(.+)$/m);return midMatches&&midMatches[1]}function getMediaSections(sdp,kind,direction){return sdp.replace(/\r\n\r\n$/,"\r\n").split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+(kind||".*"),"gm");var directionPattern=new RegExp("a="+(direction||".*"),"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getPayloadTypesInMediaSection(section){var mLine=section.split("\r\n")[0];var matches=mLine.match(/([0-9]+)/g);if(!matches){return[]}return matches.slice(1).map(function(match){return parseInt(match,10)})}function getReorderedPayloadTypes(codecMap,preferredCodecs){preferredCodecs=preferredCodecs.map(function(_a){var codec=_a.codec;return codec.toLowerCase()});var preferredPayloadTypes=flatMap(preferredCodecs,function(codecName){return codecMap.get(codecName)||[]});var remainingCodecs=difference(Array.from(codecMap.keys()),preferredCodecs);var remainingPayloadTypes=flatMap(remainingCodecs,function(codecName){return codecMap.get(codecName)});return preferredPayloadTypes.concat(remainingPayloadTypes)}function setBitrateInMediaSection(modifier,maxBitrate,section){var bLine=createBLine(modifier,maxBitrate)||"";var bLinePattern=/\r\nb=(AS|TIAS):([0-9]+)/;var bLineMatched=section.match(bLinePattern);if(!bLineMatched){return section.replace(/(\r\n)?$/,bLine+"$1")}var maxBitrateMatched=parseInt(bLineMatched[2],10);maxBitrate=maxBitrate||Infinity;bLine=createBLine(modifier,Math.min(maxBitrateMatched,maxBitrate));return section.replace(bLinePattern,bLine)}function setBitrateParameters(sdp,modifier,maxAudioBitrate,maxVideoBitrate){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){if(!/^m=(audio|video)/.test(section)||!/a=(recvonly|sendrecv)/.test(section)){return section}var kind=section.match(/^m=(audio|video)/)[1];var maxBitrate=kind==="audio"?maxAudioBitrate:maxVideoBitrate;return setBitrateInMediaSection(modifier,maxBitrate,section)})).join("\r\n")}function setPayloadTypesInMediaSection(payloadTypes,section){var lines=section.split("\r\n");var mLine=lines[0];var otherLines=lines.slice(1);mLine=mLine.replace(/([0-9]+\s?)+$/,payloadTypes.join(" "));return[mLine].concat(otherLines).join("\r\n")}function setCodecPreferences(sdp,preferredAudioCodecs,preferredVideoCodecs){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){if(!/^m=(audio|video)/.test(section)){return section}var kind=section.match(/^m=(audio|video)/)[1];var codecMap=createCodecMapForMediaSection(section);var preferredCodecs=kind==="audio"?preferredAudioCodecs:preferredVideoCodecs;var payloadTypes=getReorderedPayloadTypes(codecMap,preferredCodecs);var newSection=setPayloadTypesInMediaSection(payloadTypes,section);var pcmaPayloadTypes=codecMap.get("pcma")||[];var pcmuPayloadTypes=codecMap.get("pcmu")||[];var fixedBitratePayloadTypes=kind==="audio"?new Set(pcmaPayloadTypes.concat(pcmuPayloadTypes)):new Set;return fixedBitratePayloadTypes.has(payloadTypes[0])?newSection.replace(/\r\nb=(AS|TIAS):([0-9]+)/g,""):newSection})).join("\r\n")}function setSimulcast(sdp,sdpFormat,trackIdsToAttributes){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){section=section.replace(/\r\n$/,"");if(!/^m=video/.test(section)){return section}var codecMap=createCodecMapForMediaSection(section);var payloadTypes=getPayloadTypesInMediaSection(section);var vp8PayloadTypes=new Set(codecMap.get("vp8")||[]);var hasVP8PayloadType=payloadTypes.some(function(payloadType){return vp8PayloadTypes.has(payloadType)});return hasVP8PayloadType?setSimulcastInMediaSection(section,sdpFormat,trackIdsToAttributes):section})).concat("").join("\r\n")}function unifiedPlanGetMatchingPayloadTypes(peerCodec,peerPt,codecsToPts,section,peerSection){var matchingPts=codecsToPts.get(peerCodec)||[];if(matchingPts.length<=1){return matchingPts}var peerFmtpAttrs=getFmtpAttributesForPt(peerPt,peerSection);if(!peerFmtpAttrs){return matchingPts}var matchingPt=matchingPts.find(function(pt){var fmtpAttrs=getFmtpAttributesForPt(pt,section);return fmtpAttrs&&Object.keys(peerFmtpAttrs).every(function(attr){return peerFmtpAttrs[attr]===fmtpAttrs[attr]})});return typeof matchingPt==="number"?[matchingPt]:matchingPts}function unifiedPlanFilterCodecsInMediaSection(section,peerMidsToMediaSections,codecsToRemove){if(!/^m=(audio|video)/.test(section)){return section}var mid=getMidForMediaSection(section);var peerSection=mid&&peerMidsToMediaSections.get(mid);if(!peerSection){return section}var peerPtToCodecs=createPtToCodecName(peerSection);var codecsToPts=createCodecMapForMediaSection(section);var pts=flatMap(Array.from(peerPtToCodecs),function(_a){var _b=__read(_a,2),peerPt=_b[0],peerCodec=_b[1];return peerCodec!=="rtx"&&!codecsToRemove.includes(peerCodec)?unifiedPlanGetMatchingPayloadTypes(peerCodec,peerPt,codecsToPts,section,peerSection):[]});var rtxPts=codecsToPts.get("rtx")||[];pts=pts.concat(rtxPts.filter(function(rtxPt){var fmtpAttrs=getFmtpAttributesForPt(rtxPt,section);return fmtpAttrs&&pts.includes(fmtpAttrs.apt)}));var lines=section.split("\r\n").filter(function(line){var ptMatches=line.match(/^a=(rtpmap|fmtp|rtcp-fb):(.+) .+$/);var pt=ptMatches&&ptMatches[2];return!ptMatches||pt&&pts.includes(parseInt(pt,10))});var orderedPts=getPayloadTypesInMediaSection(section).filter(function(pt){return pts.includes(pt)});return setPayloadTypesInMediaSection(orderedPts,lines.join("\r\n"))}function unifiedPlanFilterLocalCodecs(localSdp,remoteSdp){var localMediaSections=getMediaSections(localSdp);var localSession=localSdp.split("\r\nm=")[0];var remoteMidsToMediaSections=createMidToMediaSectionMap(remoteSdp);return[localSession].concat(localMediaSections.map(function(localSection){return unifiedPlanFilterCodecsInMediaSection(localSection,remoteMidsToMediaSections,[])})).join("\r\n")}function revertSimulcastForNonVP8MediaSections(localSdp,localSdpWithoutSimulcast,remoteSdp){var remoteMidToMediaSections=createMidToMediaSectionMap(remoteSdp);var localMidToMediaSectionsWithoutSimulcast=createMidToMediaSectionMap(localSdpWithoutSimulcast);var mediaSections=getMediaSections(localSdp);var session=localSdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){section=section.replace(/\r\n$/,"");if(!/^m=video/.test(section)){return section}var midMatches=section.match(/^a=mid:(.+)$/m);var mid=midMatches&&midMatches[1];if(!mid){return section}var remoteSection=remoteMidToMediaSections.get(mid);var remotePtToCodecs=createPtToCodecName(remoteSection);var remotePayloadTypes=getPayloadTypesInMediaSection(remoteSection);var isVP8ThePreferredCodec=remotePayloadTypes.length&&remotePtToCodecs.get(remotePayloadTypes[0])==="vp8";return isVP8ThePreferredCodec?section:localMidToMediaSectionsWithoutSimulcast.get(mid).replace(/\r\n$/,"")})).concat("").join("\r\n")}function unifiedPlanAddOrRewriteNewTrackIds(sdp,activeMidsToTrackIds,trackIdsByKind){var newMidsToTrackIds=Array.from(trackIdsByKind).reduce(function(midsToTrackIds,_a){var _b=__read(_a,2),kind=_b[0],trackIds=_b[1];var mediaSections=getMediaSections(sdp,kind,"send(only|recv)");var newMids=mediaSections.map(getMidForMediaSection).filter(function(mid){return!activeMidsToTrackIds.has(mid)});newMids.forEach(function(mid,i){return midsToTrackIds.set(mid,trackIds[i])});return midsToTrackIds},new Map);return unifiedPlanAddOrRewriteTrackIds(sdp,newMidsToTrackIds)}function unifiedPlanAddOrRewriteTrackIds(sdp,midsToTrackIds){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(mediaSection){if(!/^m=(audio|video)/.test(mediaSection)){return mediaSection}var mid=getMidForMediaSection(mediaSection);if(!mid){return mediaSection}var trackId=midsToTrackIds.get(mid);if(!trackId){return mediaSection}var attributes=(mediaSection.match(/^a=msid:(.+)$/m)||[])[1];if(!attributes){return mediaSection}var _a=__read(attributes.split(" "),2),msid=_a[0],trackIdToRewrite=_a[1];var msidRegex=new RegExp("msid:"+msid+(trackIdToRewrite?" "+trackIdToRewrite:"")+"$","gm");return mediaSection.replace(msidRegex,"msid:"+msid+" "+trackId)})).join("\r\n")}function removeSSRCAttributes(sdp,ssrcAttributesToRemove){return sdp.split("\r\n").filter(function(line){return!ssrcAttributesToRemove.find(function(srcAttribute){return new RegExp("a=ssrc:.*"+srcAttribute+":","g").test(line)})}).join("\r\n")}function disableRtx(sdp){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(mediaSection){if(!/^m=video/.test(mediaSection)){return mediaSection}var codecsToPts=createCodecMapForMediaSection(mediaSection);var rtxPts=codecsToPts.get("rtx");if(!rtxPts){return mediaSection}var pts=new Set(getPayloadTypesInMediaSection(mediaSection));rtxPts.forEach(function(rtxPt){return pts.delete(rtxPt)});var rtxSSRCMatches=mediaSection.match(/a=ssrc-group:FID [0-9]+ ([0-9]+)/);var rtxSSRC=rtxSSRCMatches&&rtxSSRCMatches[1];var filterRegexes=[/^a=fmtp:.+ apt=.+$/,/^a=rtpmap:.+ rtx\/.+$/,/^a=ssrc-group:.+$/].concat(rtxSSRC?[new RegExp("^a=ssrc:"+rtxSSRC+" .+$")]:[]);mediaSection=mediaSection.split("\r\n").filter(function(line){return filterRegexes.every(function(regex){return!regex.test(line)})}).join("\r\n");return setPayloadTypesInMediaSection(Array.from(pts),mediaSection)})).join("\r\n")}
52
- function generateFmtpLineFromPtAndAttributes(pt,fmtpAttrs){var serializedFmtpAttrs=Object.entries(fmtpAttrs).map(function(_a){var _b=__read(_a,2),name=_b[0],value=_b[1];return name+"="+value}).join(";");return"a=fmtp:"+pt+" "+serializedFmtpAttrs}function enableDtxForOpus(sdp,mids){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];mids=mids||mediaSections.filter(function(section){return/^m=audio/.test(section)}).map(getMidForMediaSection);return[session].concat(mediaSections.map(function(section){if(!/^m=audio/.test(section)){return section}var codecsToPts=createCodecMapForMediaSection(section);var opusPt=codecsToPts.get("opus");if(!opusPt){return section}var opusFmtpAttrs=getFmtpAttributesForPt(opusPt,section);if(!opusFmtpAttrs){return section}var origOpusFmtpLine=generateFmtpLineFromPtAndAttributes(opusPt,opusFmtpAttrs);var origOpusFmtpRegex=new RegExp(origOpusFmtpLine);var mid=getMidForMediaSection(section);if(mids.includes(mid)){opusFmtpAttrs.usedtx=1}else{delete opusFmtpAttrs.usedtx}var opusFmtpLineWithDtx=generateFmtpLineFromPtAndAttributes(opusPt,opusFmtpAttrs);return section.replace(origOpusFmtpRegex,opusFmtpLineWithDtx)})).join("\r\n")}exports.createCodecMapForMediaSection=createCodecMapForMediaSection;exports.createPtToCodecName=createPtToCodecName;exports.disableRtx=disableRtx;exports.enableDtxForOpus=enableDtxForOpus;exports.getMediaSections=getMediaSections;exports.removeSSRCAttributes=removeSSRCAttributes;exports.revertSimulcastForNonVP8MediaSections=revertSimulcastForNonVP8MediaSections;exports.setBitrateParameters=setBitrateParameters;exports.setCodecPreferences=setCodecPreferences;exports.setSimulcast=setSimulcast;exports.unifiedPlanFilterLocalCodecs=unifiedPlanFilterLocalCodecs;exports.unifiedPlanAddOrRewriteNewTrackIds=unifiedPlanAddOrRewriteNewTrackIds;exports.unifiedPlanAddOrRewriteTrackIds=unifiedPlanAddOrRewriteTrackIds},{"../":126,"./simulcast":136}],135:[function(require,module,exports){"use strict";var RTCSessionDescription=require("@twilio/webrtc").RTCSessionDescription;var createPtToCodecName=require("./").createPtToCodecName;var getMediaSections=require("./").getMediaSections;function workaround(description){var descriptionInit={type:description.type};if(description.type!=="rollback"){descriptionInit.sdp=sdpWorkaround(description.sdp)}return new RTCSessionDescription(descriptionInit)}function sdpWorkaround(sdp){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(mediaSectionWorkaround)).join("\r\n")}function mediaSectionWorkaround(mediaSection){var ptToCodecName=createPtToCodecName(mediaSection);mediaSection=deleteDuplicateRtxPts(mediaSection,ptToCodecName);var codecNameToPts=createCodecNameToPts(ptToCodecName);var rtxPts=codecNameToPts.get("rtx")||new Set;var invalidRtxPts=new Set;var rtxPtToAssociatedPt=createRtxPtToAssociatedPt(mediaSection,ptToCodecName,rtxPts,invalidRtxPts);var associatedPtToRtxPt=createAssociatedPtToRtxPt(rtxPtToAssociatedPt,invalidRtxPts);var unassociatedRtxPts=Array.from(invalidRtxPts);var knownCodecNames=["h264","vp8","vp9"];var unassociatedPts=knownCodecNames.reduce(function(unassociatedPts,codecName){var pts=codecNameToPts.get(codecName)||new Set;return Array.from(pts).reduce(function(unassociatedPts,pt){return associatedPtToRtxPt.has(pt)?unassociatedPts:unassociatedPts.add(pt)},unassociatedPts)},new Set);unassociatedPts.forEach(function(pt){if(unassociatedRtxPts.length){var rtxPt=unassociatedRtxPts.shift();mediaSection=deleteFmtpAttributesForRtxPt(mediaSection,rtxPt);mediaSection=addFmtpAttributeForRtxPt(mediaSection,rtxPt,pt)}});unassociatedRtxPts.forEach(function(rtxPt){mediaSection=deleteFmtpAttributesForRtxPt(mediaSection,rtxPt);mediaSection=deleteRtpmapAttributesForRtxPt(mediaSection,rtxPt)});return mediaSection}function deleteDuplicateRtxPts(mediaSection,ptToCodecName){return Array.from(ptToCodecName.keys()).reduce(function(section,pt){var rtpmapRegex=new RegExp("^a=rtpmap:"+pt+" rtx.+$","gm");return(section.match(rtpmapRegex)||[]).slice(ptToCodecName.get(pt)==="rtx"?1:0).reduce(function(section,rtpmap){var rtpmapRegex=new RegExp("\r\n"+rtpmap);var fmtpmapRegex=new RegExp("\r\na=fmtp:"+pt+" apt=[0-9]+");return section.replace(rtpmapRegex,"").replace(fmtpmapRegex,"")},section)},mediaSection)}function createCodecNameToPts(ptToCodecName){var codecNameToPts=new Map;ptToCodecName.forEach(function(codecName,pt){var pts=codecNameToPts.get(codecName)||new Set;return codecNameToPts.set(codecName,pts.add(pt))});return codecNameToPts}function createRtxPtToAssociatedPt(mediaSection,ptToCodecName,rtxPts,invalidRtxPts){return Array.from(rtxPts).reduce(function(rtxPtToAssociatedPt,rtxPt){var fmtpPattern=new RegExp("a=fmtp:"+rtxPt+" apt=(\\d+)");var matches=mediaSection.match(fmtpPattern);if(!matches){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}var pt=Number.parseInt(matches[1]);if(!ptToCodecName.has(pt)){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}var codecName=ptToCodecName.get(pt);if(codecName==="rtx"){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}return rtxPtToAssociatedPt.set(rtxPt,pt)},new Map)}function createAssociatedPtToRtxPt(rtxPtToAssociatedPt,invalidRtxPts){var associatedPtToRtxPts=Array.from(rtxPtToAssociatedPt).reduce(function(associatedPtToRtxPts,pair){var rtxPt=pair[0];var pt=pair[1];var rtxPts=associatedPtToRtxPts.get(pt)||new Set;return associatedPtToRtxPts.set(pt,rtxPts.add(rtxPt))},new Map);return Array.from(associatedPtToRtxPts).reduce(function(associatedPtToRtxPt,pair){var pt=pair[0];var rtxPts=Array.from(pair[1]);if(rtxPts.length>1){rtxPts.forEach(function(rtxPt){invalidRtxPts.add(rtxPt)});return associatedPtToRtxPt}return associatedPtToRtxPt.set(pt,rtxPts[0])},new Map)}function deleteFmtpAttributesForRtxPt(mediaSection,rtxPt){var pattern=new RegExp("a=fmtp:"+rtxPt+".*\r\n","gm");return mediaSection.replace(pattern,"")}function deleteRtpmapAttributesForRtxPt(mediaSection,rtxPt){var pattern=new RegExp("a=rtpmap:"+rtxPt+".*\r\n","gm");return mediaSection.replace(pattern,"")}function addFmtpAttributeForRtxPt(mediaSection,rtxPt,pt){return mediaSection.endsWith("\r\n")?mediaSection+"a=fmtp:"+rtxPt+" apt="+pt+"\r\n":mediaSection+"\r\na=fmtp:"+rtxPt+" apt="+pt}module.exports=workaround},{"./":134,"@twilio/webrtc":152}],136:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var difference=require("../").difference;var flatMap=require("../").flatMap;function createSSRC(){var ssrcMax=4294967295;return String(Math.floor(Math.random()*ssrcMax))}var TrackAttributes=function(){function TrackAttributes(trackId,streamId,cName){Object.defineProperties(this,{cName:{enumerable:true,value:cName},isSimulcastEnabled:{enumerable:true,value:false,writable:true},primarySSRCs:{enumerable:true,value:new Set},rtxPairs:{enumerable:true,value:new Map},streamId:{enumerable:true,value:streamId},trackId:{enumerable:true,value:trackId}})}TrackAttributes.prototype.addSimulcastSSRCs=function(){if(this.isSimulcastEnabled){return}var simulcastSSRCs=[createSSRC(),createSSRC()];simulcastSSRCs.forEach(function(ssrc){this.primarySSRCs.add(ssrc)},this);if(this.rtxPairs.size){simulcastSSRCs.forEach(function(ssrc){this.rtxPairs.set(createSSRC(),ssrc)},this)}};TrackAttributes.prototype.addSSRC=function(ssrc,primarySSRC,isSimSSRC){if(primarySSRC){this.rtxPairs.set(ssrc,primarySSRC)}else{this.primarySSRCs.add(ssrc)}this.isSimulcastEnabled=this.isSimulcastEnabled||isSimSSRC};TrackAttributes.prototype.toSdpLines=function(excludeRtx){var _this=this;var rtxPairs=excludeRtx?[]:Array.from(this.rtxPairs.entries()).map(function(rtxPair){return rtxPair.reverse()});var simSSRCs=Array.from(this.primarySSRCs.values());var ssrcs=rtxPairs.length?flatMap(rtxPairs):simSSRCs;var attrLines=flatMap(ssrcs,function(ssrc){return["a=ssrc:"+ssrc+" cname:"+_this.cName,"a=ssrc:"+ssrc+" msid:"+_this.streamId+" "+_this.trackId]});var rtxPairLines=rtxPairs.map(function(rtxPair){return"a=ssrc-group:FID "+rtxPair.join(" ")});var simGroupLines=["a=ssrc-group:SIM "+simSSRCs.join(" ")];return rtxPairLines.concat(attrLines).concat(simGroupLines)};return TrackAttributes}();function getMatches(section,pattern){var matches=section.match(new RegExp(pattern,"gm"))||[];return matches.map(function(match){var matches=match.match(new RegExp(pattern))||[];return matches.slice(1)})}function getSimulcastSSRCs(section){var simGroupPattern="^a=ssrc-group:SIM ([0-9]+) ([0-9]+) ([0-9]+)$";return new Set(flatMap(getMatches(section,simGroupPattern)))}function getSSRCAttribute(section,ssrc,attribute){var pattern="a=ssrc:"+ssrc+" "+attribute+":(.+)";return section.match(new RegExp(pattern))[1]}function getSSRCRtxPairs(section){var rtxPairPattern="^a=ssrc-group:FID ([0-9]+) ([0-9]+)$";return new Map(getMatches(section,rtxPairPattern).map(function(pair){return pair.reverse()}))}function createSSRCAttributeTuples(section,sdpFormat){return{planb:createPlanBSSRCAttributeTuples,unified:createUnifiedPlanSSRCAttributeTuples}[sdpFormat](section)}function createPlanBSSRCAttributeTuples(section){return getMatches(section,"^a=ssrc:([0-9]+) msid:([^\\s]+) ([^\\s]+)$")}function createUnifiedPlanSSRCAttributeTuples(section){var _a=__read(flatMap(getMatches(section,"^a=msid:(.+) (.+)$")),2),streamId=_a[0],trackId=_a[1];var ssrcs=flatMap(getMatches(section,"^a=ssrc:(.+) cname:.+$"));return ssrcs.map(function(ssrc){return[ssrc,streamId,trackId]})}function createTrackIdsToAttributes(section,sdpFormat){var simSSRCs=getSimulcastSSRCs(section);var rtxPairs=getSSRCRtxPairs(section);var ssrcAttrTuples=createSSRCAttributeTuples(section,sdpFormat);return ssrcAttrTuples.reduce(function(trackIdsToSSRCs,tuple){var ssrc=tuple[0];var streamId=tuple[1];var trackId=tuple[2];var trackAttributes=trackIdsToSSRCs.get(trackId)||new TrackAttributes(trackId,streamId,getSSRCAttribute(section,ssrc,"cname"));var primarySSRC=rtxPairs.get(ssrc)||null;trackAttributes.addSSRC(ssrc,primarySSRC,simSSRCs.has(ssrc));return trackIdsToSSRCs.set(trackId,trackAttributes)},new Map)}function setSimulcastInMediaSection(section,sdpFormat,trackIdsToAttributes){var newTrackIdsToAttributes=createTrackIdsToAttributes(section,sdpFormat);var newTrackIds=Array.from(newTrackIdsToAttributes.keys());var trackIds=Array.from(trackIdsToAttributes.keys());var trackIdsToAdd=difference(newTrackIds,trackIds);var trackIdsToIgnore=difference(trackIds,newTrackIds);var trackAttributesToAdd=flatMap(trackIdsToAdd,function(trackId){return newTrackIdsToAttributes.get(trackId)});trackAttributesToAdd.forEach(function(trackAttributes){trackAttributes.addSimulcastSSRCs();trackIdsToAttributes.set(trackAttributes.trackId,trackAttributes)});trackIds=Array.from(trackIdsToAttributes.keys());var relevantTrackIds=difference(trackIds,trackIdsToIgnore);var relevantTrackAttributes=flatMap(relevantTrackIds,function(trackId){return trackIdsToAttributes.get(trackId)});var excludeRtx=!section.match(/a=rtpmap:[0-9]+ rtx/);var relevantSdpLines=flatMap(relevantTrackAttributes,function(trackAttributes){return trackAttributes.toSdpLines(excludeRtx)});var sectionLines=flatMap(new Set(section.split("\r\n").concat(relevantSdpLines)));var xGoogleFlagConference="a=x-google-flag:conference";if(!section.match(xGoogleFlagConference)){sectionLines.push(xGoogleFlagConference)}return sectionLines.join("\r\n")}module.exports=setSimulcastInMediaSection},{"../":126}],137:[function(require,module,exports){"use strict";var IdentityTrackMatcher=function(){function IdentityTrackMatcher(){}IdentityTrackMatcher.prototype.match=function(event){return event.track.id};IdentityTrackMatcher.prototype.update=function(){};return IdentityTrackMatcher}();module.exports=IdentityTrackMatcher},{}],138:[function(require,module,exports){"use strict";var getMediaSections=require("../").getMediaSections;var MIDTrackMatcher=function(){function MIDTrackMatcher(){Object.defineProperties(this,{_midsToTrackIds:{value:new Map,writable:true}})}MIDTrackMatcher.prototype.match=function(event){return this._midsToTrackIds.get(event.transceiver.mid)||null};MIDTrackMatcher.prototype.update=function(sdp){var sections=getMediaSections(sdp,"(audio|video)");this._midsToTrackIds=sections.reduce(function(midsToTrackIds,section){var midMatches=section.match(/^a=mid:(.+)$/m)||[];var trackIdMatches=section.match(/^a=msid:.+ (.+)$/m)||[];var mid=midMatches[1];var trackId=trackIdMatches[1];return mid&&trackId?midsToTrackIds.set(mid,trackId):midsToTrackIds},this._midsToTrackIds)};return MIDTrackMatcher}();module.exports=MIDTrackMatcher},{"../":134}],139:[function(require,module,exports){"use strict";var util=require("../../");var getMediaSections=require("../").getMediaSections;function create(){return{matched:new Set,unmatched:new Set}}function match(mAndM){var unmatched=Array.from(mAndM.unmatched);if(!unmatched.length){return null}var id=unmatched[0];mAndM.matched.add(id);mAndM.unmatched.delete(id);return id}function update(mAndM,ids){ids=new Set(ids);var removedMatchedIds=util.difference(mAndM.matched,ids);removedMatchedIds.forEach(mAndM.matched.delete,mAndM.matched);mAndM.unmatched=util.difference(ids,mAndM.matched)}function parse(kind,sdp){var mediaSections=getMediaSections(sdp,kind);var pattern="msid: ?(.+) +(.+) ?$";return new Set(util.flatMap(mediaSections,function(mediaSection){return mediaSection.match(new RegExp(pattern,"mg"))||[]}).map(function(msid){return msid.match(new RegExp(pattern))[2]}))}var OrderedTrackMatcher=function(){function OrderedTrackMatcher(){if(!(this instanceof OrderedTrackMatcher)){return new OrderedTrackMatcher}Object.defineProperties(this,{audio:{enumerable:true,value:create()},video:{enumerable:true,value:create()}})}OrderedTrackMatcher.prototype.match=function(event){return match(this[event.track.kind])};OrderedTrackMatcher.prototype.update=function(sdp){["audio","video"].forEach(function(kind){update(this[kind],parse(kind,sdp))},this)};return OrderedTrackMatcher}();module.exports=OrderedTrackMatcher},{"../":134,"../../":126}],140:[function(require,module,exports){var SID_CHARS="1234567890abcdef";var SID_CHAR_LENGTH=32;function createSID(prefix){var result="";for(var i=0;i<SID_CHAR_LENGTH;i++){result+=SID_CHARS.charAt(Math.floor(Math.random()*SID_CHARS.length))}return""+prefix+result}exports.sessionSID=createSID("SS");exports.createSID=createSID},{}],141:[function(require,module,exports){"use strict";var _a=require("@twilio/webrtc/lib/util"),guessBrowser=_a.guessBrowser,isWebRTCSupported=_a.support;var _b=require("./browserdetection"),isAndroid=_b.isAndroid,isMobile=_b.isMobile,isNonChromiumEdge=_b.isNonChromiumEdge,rebrandedChromeBrowser=_b.rebrandedChromeBrowser,mobileWebKitBrowser=_b.mobileWebKitBrowser;var SUPPORTED_CHROME_BASED_BROWSERS=["crios","edg","edge","electron","headlesschrome"];var SUPPORTED_ANDROID_BROWSERS=["chrome","firefox"];var SUPPORTED_IOS_BROWSERS=["chrome","safari"];var SUPPORTED_MOBILE_WEBKIT_BASED_BROWSERS=[];function isSupported(){var browser=guessBrowser();if(!browser){return false}var rebrandedChrome=rebrandedChromeBrowser(browser);var mobileWebKit=mobileWebKitBrowser(browser);var supportedMobileBrowsers=isAndroid()?SUPPORTED_ANDROID_BROWSERS:SUPPORTED_IOS_BROWSERS;return!!browser&&isWebRTCSupported()&&(!rebrandedChrome||SUPPORTED_CHROME_BASED_BROWSERS.includes(rebrandedChrome))&&!isNonChromiumEdge(browser)&&(!mobileWebKit||SUPPORTED_MOBILE_WEBKIT_BASED_BROWSERS.includes(mobileWebKit))&&(!isMobile()||supportedMobileBrowsers.includes(browser))}module.exports=isSupported},{"./browserdetection":118,"@twilio/webrtc/lib/util":165}],142:[function(require,module,exports){"use strict";var Timeout=function(){function Timeout(fn,delay,autoStart){if(autoStart===void 0){autoStart=true}Object.defineProperties(this,{_delay:{value:delay,writable:true},_fn:{value:fn},_timeout:{value:null,writable:true}});if(autoStart){this.start()}}Object.defineProperty(Timeout.prototype,"delay",{get:function(){return this._delay},enumerable:false,configurable:true});Object.defineProperty(Timeout.prototype,"isSet",{get:function(){return!!this._timeout},enumerable:false,configurable:true});Timeout.prototype.setDelay=function(delay){this._delay=delay};Timeout.prototype.start=function(){var _this=this;if(!this.isSet){this._timeout=setTimeout(function(){var fn=_this._fn;_this.clear();fn()},this._delay)}};Timeout.prototype.clear=function(){clearTimeout(this._timeout);this._timeout=null};Timeout.prototype.reset=function(){this.clear();this.start()};return Timeout}();module.exports=Timeout},{}],143:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TwilioError=require("./twilioerror");var TwilioErrorByCode={};exports.createTwilioError=function createTwilioError(code,message){code=typeof code==="number"?code:0;message=typeof message==="string"&&message?message:"Unknown error";return TwilioErrorByCode[code]?new TwilioErrorByCode[code]:new TwilioError(code,message)};var AccessTokenInvalidError=function(_super){__extends(AccessTokenInvalidError,_super);function AccessTokenInvalidError(){var _this=_super.call(this,20101,"Invalid Access Token")||this;Object.setPrototypeOf(_this,AccessTokenInvalidError.prototype);return _this}return AccessTokenInvalidError}(TwilioError);exports.AccessTokenInvalidError=AccessTokenInvalidError;Object.defineProperty(TwilioErrorByCode,20101,{value:AccessTokenInvalidError});var AccessTokenHeaderInvalidError=function(_super){__extends(AccessTokenHeaderInvalidError,_super);function AccessTokenHeaderInvalidError(){var _this=_super.call(this,20102,"Invalid Access Token header")||this;Object.setPrototypeOf(_this,AccessTokenHeaderInvalidError.prototype);return _this}return AccessTokenHeaderInvalidError}(TwilioError);exports.AccessTokenHeaderInvalidError=AccessTokenHeaderInvalidError;Object.defineProperty(TwilioErrorByCode,20102,{value:AccessTokenHeaderInvalidError});var AccessTokenIssuerInvalidError=function(_super){__extends(AccessTokenIssuerInvalidError,_super);function AccessTokenIssuerInvalidError(){var _this=_super.call(this,20103,"Invalid Access Token issuer/subject")||this;Object.setPrototypeOf(_this,AccessTokenIssuerInvalidError.prototype);return _this}return AccessTokenIssuerInvalidError}(TwilioError);exports.AccessTokenIssuerInvalidError=AccessTokenIssuerInvalidError;Object.defineProperty(TwilioErrorByCode,20103,{value:AccessTokenIssuerInvalidError});var AccessTokenExpiredError=function(_super){__extends(AccessTokenExpiredError,_super);function AccessTokenExpiredError(){var _this=_super.call(this,20104,"Access Token expired or expiration date invalid")||this;Object.setPrototypeOf(_this,AccessTokenExpiredError.prototype);return _this}return AccessTokenExpiredError}(TwilioError);exports.AccessTokenExpiredError=AccessTokenExpiredError;Object.defineProperty(TwilioErrorByCode,20104,{value:AccessTokenExpiredError});var AccessTokenNotYetValidError=function(_super){__extends(AccessTokenNotYetValidError,_super);function AccessTokenNotYetValidError(){var _this=_super.call(this,20105,"Access Token not yet valid")||this;Object.setPrototypeOf(_this,AccessTokenNotYetValidError.prototype);return _this}return AccessTokenNotYetValidError}(TwilioError);exports.AccessTokenNotYetValidError=AccessTokenNotYetValidError;Object.defineProperty(TwilioErrorByCode,20105,{value:AccessTokenNotYetValidError});var AccessTokenGrantsInvalidError=function(_super){__extends(AccessTokenGrantsInvalidError,_super);function AccessTokenGrantsInvalidError(){var _this=_super.call(this,20106,"Invalid Access Token grants")||this;Object.setPrototypeOf(_this,AccessTokenGrantsInvalidError.prototype);return _this}return AccessTokenGrantsInvalidError}(TwilioError);exports.AccessTokenGrantsInvalidError=AccessTokenGrantsInvalidError;Object.defineProperty(TwilioErrorByCode,20106,{value:AccessTokenGrantsInvalidError});var AccessTokenSignatureInvalidError=function(_super){__extends(AccessTokenSignatureInvalidError,_super);function AccessTokenSignatureInvalidError(){var _this=_super.call(this,20107,"Invalid Access Token signature")||this;Object.setPrototypeOf(_this,AccessTokenSignatureInvalidError.prototype);return _this}return AccessTokenSignatureInvalidError}(TwilioError);exports.AccessTokenSignatureInvalidError=AccessTokenSignatureInvalidError;Object.defineProperty(TwilioErrorByCode,20107,{value:AccessTokenSignatureInvalidError});var SignalingConnectionError=function(_super){__extends(SignalingConnectionError,_super);function SignalingConnectionError(){var _this=_super.call(this,53e3,"Signaling connection error")||this;Object.setPrototypeOf(_this,SignalingConnectionError.prototype);return _this}return SignalingConnectionError}(TwilioError);exports.SignalingConnectionError=SignalingConnectionError;Object.defineProperty(TwilioErrorByCode,53e3,{value:SignalingConnectionError});var SignalingConnectionDisconnectedError=function(_super){__extends(SignalingConnectionDisconnectedError,_super);function SignalingConnectionDisconnectedError(){var _this=_super.call(this,53001,"Signaling connection disconnected")||this;Object.setPrototypeOf(_this,SignalingConnectionDisconnectedError.prototype);return _this}return SignalingConnectionDisconnectedError}(TwilioError);exports.SignalingConnectionDisconnectedError=SignalingConnectionDisconnectedError;Object.defineProperty(TwilioErrorByCode,53001,{value:SignalingConnectionDisconnectedError});var SignalingConnectionTimeoutError=function(_super){__extends(SignalingConnectionTimeoutError,_super);function SignalingConnectionTimeoutError(){var _this=_super.call(this,53002,"Signaling connection timed out")||this;Object.setPrototypeOf(_this,SignalingConnectionTimeoutError.prototype);return _this}return SignalingConnectionTimeoutError}(TwilioError);exports.SignalingConnectionTimeoutError=SignalingConnectionTimeoutError;Object.defineProperty(TwilioErrorByCode,53002,{value:SignalingConnectionTimeoutError});var SignalingIncomingMessageInvalidError=function(_super){__extends(SignalingIncomingMessageInvalidError,_super);function SignalingIncomingMessageInvalidError(){var _this=_super.call(this,53003,"Client received an invalid signaling message")||this;Object.setPrototypeOf(_this,SignalingIncomingMessageInvalidError.prototype);return _this}return SignalingIncomingMessageInvalidError}(TwilioError);exports.SignalingIncomingMessageInvalidError=SignalingIncomingMessageInvalidError;Object.defineProperty(TwilioErrorByCode,53003,{value:SignalingIncomingMessageInvalidError});var SignalingOutgoingMessageInvalidError=function(_super){__extends(SignalingOutgoingMessageInvalidError,_super);function SignalingOutgoingMessageInvalidError(){var _this=_super.call(this,53004,"Client sent an invalid signaling message")||this;Object.setPrototypeOf(_this,SignalingOutgoingMessageInvalidError.prototype);return _this}return SignalingOutgoingMessageInvalidError}(TwilioError);exports.SignalingOutgoingMessageInvalidError=SignalingOutgoingMessageInvalidError;Object.defineProperty(TwilioErrorByCode,53004,{value:SignalingOutgoingMessageInvalidError});var SignalingServerBusyError=function(_super){__extends(SignalingServerBusyError,_super);function SignalingServerBusyError(){var _this=_super.call(this,53006,"Video server is busy")||this;Object.setPrototypeOf(_this,SignalingServerBusyError.prototype);return _this}return SignalingServerBusyError}(TwilioError);exports.SignalingServerBusyError=SignalingServerBusyError;Object.defineProperty(TwilioErrorByCode,53006,{value:SignalingServerBusyError});var RoomNameInvalidError=function(_super){__extends(RoomNameInvalidError,_super);function RoomNameInvalidError(){var _this=_super.call(this,53100,"Room name is invalid")||this;Object.setPrototypeOf(_this,RoomNameInvalidError.prototype);return _this}return RoomNameInvalidError}(TwilioError);exports.RoomNameInvalidError=RoomNameInvalidError;Object.defineProperty(TwilioErrorByCode,53100,{value:RoomNameInvalidError});var RoomNameTooLongError=function(_super){__extends(RoomNameTooLongError,_super);function RoomNameTooLongError(){var _this=_super.call(this,53101,"Room name is too long")||this;Object.setPrototypeOf(_this,RoomNameTooLongError.prototype);return _this}return RoomNameTooLongError}(TwilioError);exports.RoomNameTooLongError=RoomNameTooLongError;Object.defineProperty(TwilioErrorByCode,53101,{value:RoomNameTooLongError});var RoomNameCharsInvalidError=function(_super){__extends(RoomNameCharsInvalidError,_super);function RoomNameCharsInvalidError(){var _this=_super.call(this,53102,"Room name contains invalid characters")||this;Object.setPrototypeOf(_this,RoomNameCharsInvalidError.prototype);return _this}return RoomNameCharsInvalidError}(TwilioError);exports.RoomNameCharsInvalidError=RoomNameCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53102,{value:RoomNameCharsInvalidError});var RoomCreateFailedError=function(_super){__extends(RoomCreateFailedError,_super);function RoomCreateFailedError(){var _this=_super.call(this,53103,"Unable to create Room")||this;Object.setPrototypeOf(_this,RoomCreateFailedError.prototype);return _this}return RoomCreateFailedError}(TwilioError);exports.RoomCreateFailedError=RoomCreateFailedError;Object.defineProperty(TwilioErrorByCode,53103,{value:RoomCreateFailedError});var RoomConnectFailedError=function(_super){__extends(RoomConnectFailedError,_super);function RoomConnectFailedError(){var _this=_super.call(this,53104,"Unable to connect to Room")||this;Object.setPrototypeOf(_this,RoomConnectFailedError.prototype);return _this}return RoomConnectFailedError}(TwilioError);exports.RoomConnectFailedError=RoomConnectFailedError;Object.defineProperty(TwilioErrorByCode,53104,{value:RoomConnectFailedError});var RoomMaxParticipantsExceededError=function(_super){__extends(RoomMaxParticipantsExceededError,_super);function RoomMaxParticipantsExceededError(){var _this=_super.call(this,53105,"Room contains too many Participants")||this;Object.setPrototypeOf(_this,RoomMaxParticipantsExceededError.prototype);return _this}return RoomMaxParticipantsExceededError}(TwilioError);exports.RoomMaxParticipantsExceededError=RoomMaxParticipantsExceededError;Object.defineProperty(TwilioErrorByCode,53105,{value:RoomMaxParticipantsExceededError});var RoomNotFoundError=function(_super){__extends(RoomNotFoundError,_super);function RoomNotFoundError(){var _this=_super.call(this,53106,"Room not found")||this;Object.setPrototypeOf(_this,RoomNotFoundError.prototype);return _this}return RoomNotFoundError}(TwilioError);exports.RoomNotFoundError=RoomNotFoundError;Object.defineProperty(TwilioErrorByCode,53106,{value:RoomNotFoundError});var RoomMaxParticipantsOutOfRangeError=function(_super){__extends(RoomMaxParticipantsOutOfRangeError,_super);function RoomMaxParticipantsOutOfRangeError(){var _this=_super.call(this,53107,"MaxParticipants is out of range")||this;Object.setPrototypeOf(_this,RoomMaxParticipantsOutOfRangeError.prototype);return _this}return RoomMaxParticipantsOutOfRangeError}(TwilioError);exports.RoomMaxParticipantsOutOfRangeError=RoomMaxParticipantsOutOfRangeError;Object.defineProperty(TwilioErrorByCode,53107,{value:RoomMaxParticipantsOutOfRangeError});var RoomTypeInvalidError=function(_super){__extends(RoomTypeInvalidError,_super);function RoomTypeInvalidError(){var _this=_super.call(this,53108,"RoomType is not valid")||this;Object.setPrototypeOf(_this,RoomTypeInvalidError.prototype);return _this}return RoomTypeInvalidError}(TwilioError);exports.RoomTypeInvalidError=RoomTypeInvalidError;Object.defineProperty(TwilioErrorByCode,53108,{value:RoomTypeInvalidError});var RoomTimeoutOutOfRangeError=function(_super){__extends(RoomTimeoutOutOfRangeError,_super);function RoomTimeoutOutOfRangeError(){var _this=_super.call(this,53109,"Timeout is out of range")||this;Object.setPrototypeOf(_this,RoomTimeoutOutOfRangeError.prototype);return _this}return RoomTimeoutOutOfRangeError}(TwilioError);exports.RoomTimeoutOutOfRangeError=RoomTimeoutOutOfRangeError;Object.defineProperty(TwilioErrorByCode,53109,{value:RoomTimeoutOutOfRangeError});var RoomStatusCallbackMethodInvalidError=function(_super){__extends(RoomStatusCallbackMethodInvalidError,_super);function RoomStatusCallbackMethodInvalidError(){var _this=_super.call(this,53110,"StatusCallbackMethod is invalid")||this;Object.setPrototypeOf(_this,RoomStatusCallbackMethodInvalidError.prototype);return _this}return RoomStatusCallbackMethodInvalidError}(TwilioError);exports.RoomStatusCallbackMethodInvalidError=RoomStatusCallbackMethodInvalidError;Object.defineProperty(TwilioErrorByCode,53110,{value:RoomStatusCallbackMethodInvalidError});var RoomStatusCallbackInvalidError=function(_super){__extends(RoomStatusCallbackInvalidError,_super);function RoomStatusCallbackInvalidError(){var _this=_super.call(this,53111,"StatusCallback is invalid")||this;Object.setPrototypeOf(_this,RoomStatusCallbackInvalidError.prototype);return _this}return RoomStatusCallbackInvalidError}(TwilioError);exports.RoomStatusCallbackInvalidError=RoomStatusCallbackInvalidError;Object.defineProperty(TwilioErrorByCode,53111,{value:RoomStatusCallbackInvalidError});var RoomStatusInvalidError=function(_super){__extends(RoomStatusInvalidError,_super);function RoomStatusInvalidError(){var _this=_super.call(this,53112,"Status is invalid")||this;Object.setPrototypeOf(_this,RoomStatusInvalidError.prototype);return _this}return RoomStatusInvalidError}(TwilioError);exports.RoomStatusInvalidError=RoomStatusInvalidError;Object.defineProperty(TwilioErrorByCode,53112,{value:RoomStatusInvalidError});var RoomRoomExistsError=function(_super){__extends(RoomRoomExistsError,_super);function RoomRoomExistsError(){var _this=_super.call(this,53113,"Room exists")||this;Object.setPrototypeOf(_this,RoomRoomExistsError.prototype);return _this}return RoomRoomExistsError}(TwilioError);exports.RoomRoomExistsError=RoomRoomExistsError;Object.defineProperty(TwilioErrorByCode,53113,{value:RoomRoomExistsError});var RoomInvalidParametersError=function(_super){__extends(RoomInvalidParametersError,_super);function RoomInvalidParametersError(){var _this=_super.call(this,53114,"Room creation parameter(s) incompatible with the Room type")||this;Object.setPrototypeOf(_this,RoomInvalidParametersError.prototype);return _this}return RoomInvalidParametersError}(TwilioError);exports.RoomInvalidParametersError=RoomInvalidParametersError;Object.defineProperty(TwilioErrorByCode,53114,{value:RoomInvalidParametersError});var RoomMediaRegionInvalidError=function(_super){__extends(RoomMediaRegionInvalidError,_super);function RoomMediaRegionInvalidError(){var _this=_super.call(this,53115,"MediaRegion is invalid")||this;Object.setPrototypeOf(_this,RoomMediaRegionInvalidError.prototype);return _this}return RoomMediaRegionInvalidError}(TwilioError);exports.RoomMediaRegionInvalidError=RoomMediaRegionInvalidError;Object.defineProperty(TwilioErrorByCode,53115,{value:RoomMediaRegionInvalidError});var RoomMediaRegionUnavailableError=function(_super){__extends(RoomMediaRegionUnavailableError,_super);function RoomMediaRegionUnavailableError(){var _this=_super.call(this,53116,"There are no media servers available in the MediaRegion")||this;Object.setPrototypeOf(_this,RoomMediaRegionUnavailableError.prototype);return _this}return RoomMediaRegionUnavailableError}(TwilioError)
53
- ;exports.RoomMediaRegionUnavailableError=RoomMediaRegionUnavailableError;Object.defineProperty(TwilioErrorByCode,53116,{value:RoomMediaRegionUnavailableError});var RoomSubscriptionOperationNotSupportedError=function(_super){__extends(RoomSubscriptionOperationNotSupportedError,_super);function RoomSubscriptionOperationNotSupportedError(){var _this=_super.call(this,53117,"The subscription operation requested is not supported for the Room type")||this;Object.setPrototypeOf(_this,RoomSubscriptionOperationNotSupportedError.prototype);return _this}return RoomSubscriptionOperationNotSupportedError}(TwilioError);exports.RoomSubscriptionOperationNotSupportedError=RoomSubscriptionOperationNotSupportedError;Object.defineProperty(TwilioErrorByCode,53117,{value:RoomSubscriptionOperationNotSupportedError});var RoomCompletedError=function(_super){__extends(RoomCompletedError,_super);function RoomCompletedError(){var _this=_super.call(this,53118,"Room completed")||this;Object.setPrototypeOf(_this,RoomCompletedError.prototype);return _this}return RoomCompletedError}(TwilioError);exports.RoomCompletedError=RoomCompletedError;Object.defineProperty(TwilioErrorByCode,53118,{value:RoomCompletedError});var RoomAudioOnlyFlagNotSupportedError=function(_super){__extends(RoomAudioOnlyFlagNotSupportedError,_super);function RoomAudioOnlyFlagNotSupportedError(){var _this=_super.call(this,53124,"The AudioOnly flag is not supported for the Room type")||this;Object.setPrototypeOf(_this,RoomAudioOnlyFlagNotSupportedError.prototype);return _this}return RoomAudioOnlyFlagNotSupportedError}(TwilioError);exports.RoomAudioOnlyFlagNotSupportedError=RoomAudioOnlyFlagNotSupportedError;Object.defineProperty(TwilioErrorByCode,53124,{value:RoomAudioOnlyFlagNotSupportedError});var RoomTrackKindNotSupportedError=function(_super){__extends(RoomTrackKindNotSupportedError,_super);function RoomTrackKindNotSupportedError(){var _this=_super.call(this,53125,"The track kind is not supported by the Room")||this;Object.setPrototypeOf(_this,RoomTrackKindNotSupportedError.prototype);return _this}return RoomTrackKindNotSupportedError}(TwilioError);exports.RoomTrackKindNotSupportedError=RoomTrackKindNotSupportedError;Object.defineProperty(TwilioErrorByCode,53125,{value:RoomTrackKindNotSupportedError});var ParticipantIdentityInvalidError=function(_super){__extends(ParticipantIdentityInvalidError,_super);function ParticipantIdentityInvalidError(){var _this=_super.call(this,53200,"Participant identity is invalid")||this;Object.setPrototypeOf(_this,ParticipantIdentityInvalidError.prototype);return _this}return ParticipantIdentityInvalidError}(TwilioError);exports.ParticipantIdentityInvalidError=ParticipantIdentityInvalidError;Object.defineProperty(TwilioErrorByCode,53200,{value:ParticipantIdentityInvalidError});var ParticipantIdentityTooLongError=function(_super){__extends(ParticipantIdentityTooLongError,_super);function ParticipantIdentityTooLongError(){var _this=_super.call(this,53201,"Participant identity is too long")||this;Object.setPrototypeOf(_this,ParticipantIdentityTooLongError.prototype);return _this}return ParticipantIdentityTooLongError}(TwilioError);exports.ParticipantIdentityTooLongError=ParticipantIdentityTooLongError;Object.defineProperty(TwilioErrorByCode,53201,{value:ParticipantIdentityTooLongError});var ParticipantIdentityCharsInvalidError=function(_super){__extends(ParticipantIdentityCharsInvalidError,_super);function ParticipantIdentityCharsInvalidError(){var _this=_super.call(this,53202,"Participant identity contains invalid characters")||this;Object.setPrototypeOf(_this,ParticipantIdentityCharsInvalidError.prototype);return _this}return ParticipantIdentityCharsInvalidError}(TwilioError);exports.ParticipantIdentityCharsInvalidError=ParticipantIdentityCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53202,{value:ParticipantIdentityCharsInvalidError});var ParticipantMaxTracksExceededError=function(_super){__extends(ParticipantMaxTracksExceededError,_super);function ParticipantMaxTracksExceededError(){var _this=_super.call(this,53203,"The maximum number of published tracks allowed in the Room at the same time has been reached")||this;Object.setPrototypeOf(_this,ParticipantMaxTracksExceededError.prototype);return _this}return ParticipantMaxTracksExceededError}(TwilioError);exports.ParticipantMaxTracksExceededError=ParticipantMaxTracksExceededError;Object.defineProperty(TwilioErrorByCode,53203,{value:ParticipantMaxTracksExceededError});var ParticipantNotFoundError=function(_super){__extends(ParticipantNotFoundError,_super);function ParticipantNotFoundError(){var _this=_super.call(this,53204,"Participant not found")||this;Object.setPrototypeOf(_this,ParticipantNotFoundError.prototype);return _this}return ParticipantNotFoundError}(TwilioError);exports.ParticipantNotFoundError=ParticipantNotFoundError;Object.defineProperty(TwilioErrorByCode,53204,{value:ParticipantNotFoundError});var ParticipantDuplicateIdentityError=function(_super){__extends(ParticipantDuplicateIdentityError,_super);function ParticipantDuplicateIdentityError(){var _this=_super.call(this,53205,"Participant disconnected because of duplicate identity")||this;Object.setPrototypeOf(_this,ParticipantDuplicateIdentityError.prototype);return _this}return ParticipantDuplicateIdentityError}(TwilioError);exports.ParticipantDuplicateIdentityError=ParticipantDuplicateIdentityError;Object.defineProperty(TwilioErrorByCode,53205,{value:ParticipantDuplicateIdentityError});var TrackInvalidError=function(_super){__extends(TrackInvalidError,_super);function TrackInvalidError(){var _this=_super.call(this,53300,"Track is invalid")||this;Object.setPrototypeOf(_this,TrackInvalidError.prototype);return _this}return TrackInvalidError}(TwilioError);exports.TrackInvalidError=TrackInvalidError;Object.defineProperty(TwilioErrorByCode,53300,{value:TrackInvalidError});var TrackNameInvalidError=function(_super){__extends(TrackNameInvalidError,_super);function TrackNameInvalidError(){var _this=_super.call(this,53301,"Track name is invalid")||this;Object.setPrototypeOf(_this,TrackNameInvalidError.prototype);return _this}return TrackNameInvalidError}(TwilioError);exports.TrackNameInvalidError=TrackNameInvalidError;Object.defineProperty(TwilioErrorByCode,53301,{value:TrackNameInvalidError});var TrackNameTooLongError=function(_super){__extends(TrackNameTooLongError,_super);function TrackNameTooLongError(){var _this=_super.call(this,53302,"Track name is too long")||this;Object.setPrototypeOf(_this,TrackNameTooLongError.prototype);return _this}return TrackNameTooLongError}(TwilioError);exports.TrackNameTooLongError=TrackNameTooLongError;Object.defineProperty(TwilioErrorByCode,53302,{value:TrackNameTooLongError});var TrackNameCharsInvalidError=function(_super){__extends(TrackNameCharsInvalidError,_super);function TrackNameCharsInvalidError(){var _this=_super.call(this,53303,"Track name contains invalid characters")||this;Object.setPrototypeOf(_this,TrackNameCharsInvalidError.prototype);return _this}return TrackNameCharsInvalidError}(TwilioError);exports.TrackNameCharsInvalidError=TrackNameCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53303,{value:TrackNameCharsInvalidError});var TrackNameIsDuplicatedError=function(_super){__extends(TrackNameIsDuplicatedError,_super);function TrackNameIsDuplicatedError(){var _this=_super.call(this,53304,"Track name is duplicated")||this;Object.setPrototypeOf(_this,TrackNameIsDuplicatedError.prototype);return _this}return TrackNameIsDuplicatedError}(TwilioError);exports.TrackNameIsDuplicatedError=TrackNameIsDuplicatedError;Object.defineProperty(TwilioErrorByCode,53304,{value:TrackNameIsDuplicatedError});var TrackServerTrackCapacityReachedError=function(_super){__extends(TrackServerTrackCapacityReachedError,_super);function TrackServerTrackCapacityReachedError(){var _this=_super.call(this,53305,"The server has reached capacity and cannot fulfill this request")||this;Object.setPrototypeOf(_this,TrackServerTrackCapacityReachedError.prototype);return _this}return TrackServerTrackCapacityReachedError}(TwilioError);exports.TrackServerTrackCapacityReachedError=TrackServerTrackCapacityReachedError;Object.defineProperty(TwilioErrorByCode,53305,{value:TrackServerTrackCapacityReachedError});var MediaClientLocalDescFailedError=function(_super){__extends(MediaClientLocalDescFailedError,_super);function MediaClientLocalDescFailedError(){var _this=_super.call(this,53400,"Client is unable to create or apply a local media description")||this;Object.setPrototypeOf(_this,MediaClientLocalDescFailedError.prototype);return _this}return MediaClientLocalDescFailedError}(TwilioError);exports.MediaClientLocalDescFailedError=MediaClientLocalDescFailedError;Object.defineProperty(TwilioErrorByCode,53400,{value:MediaClientLocalDescFailedError});var MediaServerLocalDescFailedError=function(_super){__extends(MediaServerLocalDescFailedError,_super);function MediaServerLocalDescFailedError(){var _this=_super.call(this,53401,"Server is unable to create or apply a local media description")||this;Object.setPrototypeOf(_this,MediaServerLocalDescFailedError.prototype);return _this}return MediaServerLocalDescFailedError}(TwilioError);exports.MediaServerLocalDescFailedError=MediaServerLocalDescFailedError;Object.defineProperty(TwilioErrorByCode,53401,{value:MediaServerLocalDescFailedError});var MediaClientRemoteDescFailedError=function(_super){__extends(MediaClientRemoteDescFailedError,_super);function MediaClientRemoteDescFailedError(){var _this=_super.call(this,53402,"Client is unable to apply a remote media description")||this;Object.setPrototypeOf(_this,MediaClientRemoteDescFailedError.prototype);return _this}return MediaClientRemoteDescFailedError}(TwilioError);exports.MediaClientRemoteDescFailedError=MediaClientRemoteDescFailedError;Object.defineProperty(TwilioErrorByCode,53402,{value:MediaClientRemoteDescFailedError});var MediaServerRemoteDescFailedError=function(_super){__extends(MediaServerRemoteDescFailedError,_super);function MediaServerRemoteDescFailedError(){var _this=_super.call(this,53403,"Server is unable to apply a remote media description")||this;Object.setPrototypeOf(_this,MediaServerRemoteDescFailedError.prototype);return _this}return MediaServerRemoteDescFailedError}(TwilioError);exports.MediaServerRemoteDescFailedError=MediaServerRemoteDescFailedError;Object.defineProperty(TwilioErrorByCode,53403,{value:MediaServerRemoteDescFailedError});var MediaNoSupportedCodecError=function(_super){__extends(MediaNoSupportedCodecError,_super);function MediaNoSupportedCodecError(){var _this=_super.call(this,53404,"No supported codec")||this;Object.setPrototypeOf(_this,MediaNoSupportedCodecError.prototype);return _this}return MediaNoSupportedCodecError}(TwilioError);exports.MediaNoSupportedCodecError=MediaNoSupportedCodecError;Object.defineProperty(TwilioErrorByCode,53404,{value:MediaNoSupportedCodecError});var MediaConnectionError=function(_super){__extends(MediaConnectionError,_super);function MediaConnectionError(){var _this=_super.call(this,53405,"Media connection failed or Media activity ceased")||this;Object.setPrototypeOf(_this,MediaConnectionError.prototype);return _this}return MediaConnectionError}(TwilioError);exports.MediaConnectionError=MediaConnectionError;Object.defineProperty(TwilioErrorByCode,53405,{value:MediaConnectionError});var MediaDTLSTransportFailedError=function(_super){__extends(MediaDTLSTransportFailedError,_super);function MediaDTLSTransportFailedError(){var _this=_super.call(this,53407,"Media connection failed due to DTLS handshake failure")||this;Object.setPrototypeOf(_this,MediaDTLSTransportFailedError.prototype);return _this}return MediaDTLSTransportFailedError}(TwilioError);exports.MediaDTLSTransportFailedError=MediaDTLSTransportFailedError;Object.defineProperty(TwilioErrorByCode,53407,{value:MediaDTLSTransportFailedError});var ConfigurationAcquireFailedError=function(_super){__extends(ConfigurationAcquireFailedError,_super);function ConfigurationAcquireFailedError(){var _this=_super.call(this,53500,"Unable to acquire configuration")||this;Object.setPrototypeOf(_this,ConfigurationAcquireFailedError.prototype);return _this}return ConfigurationAcquireFailedError}(TwilioError);exports.ConfigurationAcquireFailedError=ConfigurationAcquireFailedError;Object.defineProperty(TwilioErrorByCode,53500,{value:ConfigurationAcquireFailedError});var ConfigurationAcquireTurnFailedError=function(_super){__extends(ConfigurationAcquireTurnFailedError,_super);function ConfigurationAcquireTurnFailedError(){var _this=_super.call(this,53501,"Unable to acquire TURN credentials")||this;Object.setPrototypeOf(_this,ConfigurationAcquireTurnFailedError.prototype);return _this}return ConfigurationAcquireTurnFailedError}(TwilioError);exports.ConfigurationAcquireTurnFailedError=ConfigurationAcquireTurnFailedError;Object.defineProperty(TwilioErrorByCode,53501,{value:ConfigurationAcquireTurnFailedError})},{"./twilioerror":144}],144:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var TwilioError=function(_super){__extends(TwilioError,_super);function TwilioError(code){var _this=this;var args=[].slice.call(arguments,1);_this=_super.apply(this,__spreadArray([],__read(args)))||this;Object.setPrototypeOf(_this,TwilioError.prototype);var error=Error.apply(_this,args);error.name="TwilioError";Object.defineProperty(_this,"code",{value:code,enumerable:true});Object.getOwnPropertyNames(error).forEach(function(prop){Object.defineProperty(this,prop,{value:error[prop],enumerable:true})},_this);return _this}TwilioError.prototype.toString=function(){var message=this.message?": "+this.message:"";return this.name+" "+this.code+message};return TwilioError}(Error);module.exports=TwilioError},{}],145:[function(require,module,exports){"use strict";var isNonArrayObject=require("./").isNonArrayObject;var _a=require("./constants"),E=_a.typeErrors,clientTrackSwitchOffControl=_a.clientTrackSwitchOffControl,videoContentPreferencesMode=_a.videoContentPreferencesMode,subscriptionMode=_a.subscriptionMode,trackPriority=_a.trackPriority,trackSwitchOffMode=_a.trackSwitchOffMode;function validateBandwidthProfile(bandwidthProfile){var error=validateObject(bandwidthProfile,"options.bandwidthProfile");if(!bandwidthProfile||error){return error}error=validateObject(bandwidthProfile.video,"options.bandwidthProfile.video",[{prop:"contentPreferencesMode",values:Object.values(videoContentPreferencesMode)},{prop:"dominantSpeakerPriority",values:Object.values(trackPriority)},{prop:"maxSubscriptionBitrate",type:"number"},{prop:"maxTracks",type:"number"},{prop:"mode",values:Object.values(subscriptionMode)},{prop:"clientTrackSwitchOffControl",values:Object.values(clientTrackSwitchOffControl)},{prop:"trackSwitchOffMode",values:Object.values(trackSwitchOffMode)}]);if(error){return error}if(bandwidthProfile.video){if("maxTracks"in bandwidthProfile.video&&"clientTrackSwitchOffControl"in bandwidthProfile.video){return new TypeError("options.bandwidthProfile.video.maxTracks is deprecated. Use options.bandwidthProfile.video.clientTrackSwitchOffControl instead.")}if("renderDimensions"in bandwidthProfile.video&&"contentPreferencesMode"in bandwidthProfile.video){return new TypeError("options.bandwidthProfile.video.renderDimensions is deprecated. Use options.bandwidthProfile.video.contentPreferencesMode instead.")}return validateRenderDimensions(bandwidthProfile.video.renderDimensions)}return null}function validateLocalTrack(track,options){if(!(track instanceof options.LocalAudioTrack||track instanceof options.LocalDataTrack||track instanceof options.LocalVideoTrack||track instanceof options.MediaStreamTrack)){throw E.INVALID_TYPE("track","LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}}function validateObject(object,name,propChecks){if(propChecks===void 0){propChecks=[]}if(typeof object==="undefined"){return null}if(object===null||!isNonArrayObject(object)){return E.INVALID_TYPE(name,"object")}return propChecks.reduce(function(error,_a){var prop=_a.prop,type=_a.type,values=_a.values;if(error||!(prop in object)){return error}var value=object[prop];if(type&&typeof value!==type){return E.INVALID_TYPE(name+"."+prop,type)}if(type==="number"&&isNaN(value)){return E.INVALID_TYPE(name+"."+prop,type)}if(Array.isArray(values)&&!values.includes(value)){return E.INVALID_VALUE(name+"."+prop,values)}return error},null)}function validateRenderDimensions(renderDimensions){var name="options.bandwidthProfile.video.renderDimensions";var error=validateObject(renderDimensions,name);return renderDimensions?error||Object.values(trackPriority).reduce(function(error,prop){return error||validateObject(renderDimensions[prop],name+"."+prop,[{prop:"height",type:"number"},{prop:"width",type:"number"}])},null):error}exports.validateBandwidthProfile=validateBandwidthProfile;exports.validateLocalTrack=validateLocalTrack;exports.validateObject=validateObject},{"./":126,"./constants":120}],146:[function(require,module,exports){var noop=function(){};var undefinedType="undefined";var isIE=typeof window!==undefinedType&&typeof window.navigator!==undefinedType&&/Trident\/|MSIE /.test(window.navigator.userAgent);var logMethods=["trace","debug","info","warn","error"];function bindMethod(obj,methodName){var method=obj[methodName];if(typeof method.bind==="function"){return method.bind(obj)}else{try{return Function.prototype.bind.call(method,obj)}catch(e){return function(){return Function.prototype.apply.apply(method,[obj,arguments])}}}}function traceForIE(){if(console.log){if(console.log.apply){console.log.apply(console,arguments)}else{Function.prototype.apply.apply(console.log,[console,arguments])}}if(console.trace)console.trace()}function realMethod(methodName){if(methodName==="debug"){methodName="log"}if(typeof console===undefinedType){return false}else if(methodName==="trace"&&isIE){return traceForIE}else if(console[methodName]!==undefined){return bindMethod(console,methodName)}else if(console.log!==undefined){return bindMethod(console,"log")}else{return noop}}function replaceLoggingMethods(level,loggerName){for(var i=0;i<logMethods.length;i++){var methodName=logMethods[i];this[methodName]=i<level?noop:this.methodFactory(methodName,level,loggerName)}this.log=this.debug}function enableLoggingWhenConsoleArrives(methodName,level,loggerName){return function(){if(typeof console!==undefinedType){replaceLoggingMethods.call(this,level,loggerName);this[methodName].apply(this,arguments)}}}function defaultMethodFactory(methodName,level,loggerName){return realMethod(methodName)||enableLoggingWhenConsoleArrives.apply(this,arguments)}function Logger(name,defaultLevel,factory){var self=this;var currentLevel;var storageKey="loglevel";if(typeof name==="string"){storageKey+=":"+name}else if(typeof name==="symbol"){storageKey=undefined}function persistLevelIfPossible(levelNum){var levelName=(logMethods[levelNum]||"silent").toUpperCase();if(typeof window===undefinedType||!storageKey)return;try{window.localStorage[storageKey]=levelName;return}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"="+levelName+";"}catch(ignore){}}function getPersistedLevel(){var storedLevel;if(typeof window===undefinedType||!storageKey)return;try{storedLevel=window.localStorage[storageKey]}catch(ignore){}if(typeof storedLevel===undefinedType){try{var cookie=window.document.cookie;var location=cookie.indexOf(encodeURIComponent(storageKey)+"=");if(location!==-1){storedLevel=/^([^;]+)/.exec(cookie.slice(location))[1]}}catch(ignore){}}if(self.levels[storedLevel]===undefined){storedLevel=undefined}return storedLevel}self.name=name;self.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5};self.methodFactory=factory||defaultMethodFactory;self.getLevel=function(){return currentLevel};self.setLevel=function(level,persist){if(typeof level==="string"&&self.levels[level.toUpperCase()]!==undefined){level=self.levels[level.toUpperCase()]}if(typeof level==="number"&&level>=0&&level<=self.levels.SILENT){currentLevel=level;if(persist!==false){persistLevelIfPossible(level)}replaceLoggingMethods.call(self,level,name);if(typeof console===undefinedType&&level<self.levels.SILENT){return"No console available for logging"}}else{throw"log.setLevel() called with invalid level: "+level}};self.setDefaultLevel=function(level){if(!getPersistedLevel()){self.setLevel(level,false)}};self.enableAll=function(persist){self.setLevel(self.levels.TRACE,persist)};self.disableAll=function(persist){self.setLevel(self.levels.SILENT,persist)};var initialLevel=getPersistedLevel();if(initialLevel==null){initialLevel=defaultLevel==null?"WARN":defaultLevel}self.setLevel(initialLevel,false)}var defaultLogger=new Logger;var _loggersByName={};defaultLogger.getLogger=function getLogger(name){if(typeof name!=="symbol"&&typeof name!=="string"||name===""){throw new TypeError("You must supply a name when creating a logger.")}var logger=_loggersByName[name];if(!logger){logger=_loggersByName[name]=new Logger(name,defaultLogger.getLevel(),defaultLogger.methodFactory)}return logger};var _log=typeof window!==undefinedType?window.log:undefined;defaultLogger.noConflict=function(){if(typeof window!==undefinedType&&window.log===defaultLogger){window.log=_log}return defaultLogger};defaultLogger.getLoggers=function getLoggers(){return _loggersByName};defaultLogger["default"]=defaultLogger;module.exports=defaultLogger},{}],147:[function(require,module,exports){"use strict";var NativeAudioContext=typeof AudioContext!=="undefined"?AudioContext:typeof webkitAudioContext!=="undefined"?webkitAudioContext:null;var AudioContextFactory=function(){function AudioContextFactory(options){options=Object.assign({AudioContext:NativeAudioContext},options);Object.defineProperties(this,{_AudioContext:{value:options.AudioContext},_audioContext:{value:null,writable:true},_holders:{value:new Set},AudioContextFactory:{enumerable:true,value:AudioContextFactory}})}AudioContextFactory.prototype.getOrCreate=function(holder){if(!this._holders.has(holder)){this._holders.add(holder);if(this._AudioContext&&!this._audioContext){try{this._audioContext=new this._AudioContext}catch(error){}}}return this._audioContext};AudioContextFactory.prototype.release=function(holder){if(this._holders.has(holder)){this._holders.delete(holder);if(!this._holders.size&&this._audioContext){this._audioContext.close();this._audioContext=null}}};return AudioContextFactory}();module.exports=new AudioContextFactory},{}],148:[function(require,module,exports){"use strict";function delay(timeout){timeout=typeof timeout==="number"?timeout:0;return new Promise(function(resolve){return setTimeout(resolve,timeout)})}function detectSilence(audioContext,stream,timeout){timeout=typeof timeout==="number"?timeout:250;var source=audioContext.createMediaStreamSource(stream);var analyser=audioContext.createAnalyser();analyser.fftSize=2048;source.connect(analyser);var samples=new Uint8Array(analyser.fftSize);var timeoutDidFire=false;setTimeout(function(){timeoutDidFire=true},timeout);function doDetectSilence(){if(timeoutDidFire){return Promise.resolve(true)}analyser.getByteTimeDomainData(samples);return samples.some(function(sample){return sample!==128&&sample!==0})?Promise.resolve(false):delay().then(doDetectSilence)}return doDetectSilence().then(function(isSilent){source.disconnect();return isSilent},function(error){source.disconnect();throw error})}module.exports=detectSilence},{}],149:[function(require,module,exports){"use strict";var detectSilence=require("./detectsilence");function workaround(log,getUserMedia,constraints,n,timeout){n=typeof n==="number"?n:3;var retry=0;var AudioContextFactory=require("./audiocontext");var holder={};var audioContext=AudioContextFactory.getOrCreate(holder);function doWorkaround(){return getUserMedia(constraints).then(function(stream){var isSilentPromise=constraints.audio?detectSilence(audioContext,stream,timeout).catch(function(err){log.warn("Encountered an error while detecting silence",err);return true}):Promise.resolve(false);return isSilentPromise.then(function(isSilent){if(!isSilent){log.info("Got a non-silent audio MediaStreamTrack; returning it.");return stream}else if(n<=0){log.warn("Got a silent audio MediaStreamTrack. Normally we would try to get a new one, but we've run out of retries; returning it anyway.");return stream}log.warn("Got a silent audio MediaStreamTrack. Stopping all MediaStreamTracks and calling getUserMedia again. This is retry #"+ ++retry+".");stream.getTracks().forEach(function(track){return track.stop()});n--;return doWorkaround()})})}return doWorkaround().then(function(stream){AudioContextFactory.release(holder);return stream},function(error){AudioContextFactory.release(holder);throw error})}module.exports=workaround},{"./audiocontext":147,"./detectsilence":148}],150:[function(require,module,exports){"use strict";var flatMap=require("./util").flatMap;var guessBrowser=require("./util").guessBrowser;var guessBrowserVersion=require("./util").guessBrowserVersion;var getSdpFormat=require("./util/sdp").getSdpFormat;var guess=guessBrowser();var guessVersion=guessBrowserVersion();var isChrome=guess==="chrome";var isFirefox=guess==="firefox";var isSafari=guess==="safari";var chromeMajorVersion=isChrome?guessVersion.major:null;var CHROME_LEGACY_MAX_AUDIO_LEVEL=32767;function getStats(peerConnection,options){if(!(peerConnection&&typeof peerConnection.getStats==="function")){return Promise.reject(new Error("Given PeerConnection does not support getStats"))}return _getStats(peerConnection,options)}function _getStats(peerConnection,options){var localAudioTracks=getTracks(peerConnection,"audio","local");var localVideoTracks=getTracks(peerConnection,"video","local");var remoteAudioTracks=getTracks(peerConnection,"audio");var remoteVideoTracks=getTracks(peerConnection,"video");var statsResponse={activeIceCandidatePair:null,localAudioTrackStats:[],localVideoTrackStats:[],remoteAudioTrackStats:[],remoteVideoTrackStats:[]};var trackStatsPromises=flatMap([[localAudioTracks,"localAudioTrackStats",false],[localVideoTracks,"localVideoTrackStats",false],[remoteAudioTracks,"remoteAudioTrackStats",true],[remoteVideoTracks,"remoteVideoTrackStats",true]],function(triple){var tracks=triple[0];var statsArrayName=triple[1];var isRemote=triple[2];return tracks.map(function(track){return getTrackStats(peerConnection,track,Object.assign({isRemote:isRemote},options)).then(function(trackStatsArray){trackStatsArray.forEach(function(trackStats){trackStats.trackId=track.id;statsResponse[statsArrayName].push(trackStats)})})})});return Promise.all(trackStatsPromises).then(function(){return getActiveIceCandidatePairStats(peerConnection,options)}).then(function(activeIceCandidatePairStatsReport){statsResponse.activeIceCandidatePair=activeIceCandidatePairStatsReport;return statsResponse})}function getActiveIceCandidatePairStats(peerConnection,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome||typeof options.testForSafari!=="undefined"||isSafari){return peerConnection.getStats().then(standardizeChromeOrSafariActiveIceCandidatePairStats)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return peerConnection.getStats().then(standardizeFirefoxActiveIceCandidatePairStats)}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function standardizeChromeOrSafariActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",type:"string"},{key:"port",type:"number"},{key:"priority",type:"number"},{key:"protocol",type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",type:"string"}]);var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeLocalCandidateStats[keyInfo.key]===keyInfo.type?activeLocalCandidateStats[keyInfo.key]:keyInfo.key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeRemoteCandidateStats[keyInfo.key]===keyInfo.type?activeRemoteCandidateStats[keyInfo.key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string",fixup:function(state){return state==="inprogress"?"in-progress":state}},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?keyInfo.fixup?keyInfo.fixup(activeCandidatePairStats[keyInfo.key]):activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function standardizeFirefoxActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",ffKeys:["address","ipAddress"],type:"string"},{key:"port",ffKeys:["portNumber"],type:"number"},{key:"priority",type:"number"},{key:"protocol",ffKeys:["transport"],type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",type:"string"}]);var candidateTypes={host:"host",peerreflexive:"prflx",relayed:"relay",serverreflexive:"srflx"}
54
- ;var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeLocalCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeLocalCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeLocalCandidateStats[key]]||activeLocalCandidateStats[key]:activeLocalCandidateStats[key]:key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeRemoteCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeRemoteCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeRemoteCandidateStats[key]]||activeRemoteCandidateStats[key]:activeRemoteCandidateStats[key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string"},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function getTracks(peerConnection,kind,localOrRemote){var getSendersOrReceivers=localOrRemote==="local"?"getSenders":"getReceivers";if(peerConnection[getSendersOrReceivers]){return peerConnection[getSendersOrReceivers]().map(function(senderOrReceiver){return senderOrReceiver.track}).filter(function(track){return track&&track.kind===kind})}var getStreams=localOrRemote==="local"?"getLocalStreams":"getRemoteStreams";return flatMap(peerConnection[getStreams](),function(stream){var getTracks=kind==="audio"?"getAudioTracks":"getVideoTracks";return stream[getTracks]()})}function getTrackStats(peerConnection,track,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome){return chromeOrSafariGetTrackStats(peerConnection,track)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return firefoxGetTrackStats(peerConnection,track,options.isRemote)}if(typeof options.testForSafari!=="undefined"||isSafari){if(typeof options.testForSafari!=="undefined"||getSdpFormat()==="unified"){return chromeOrSafariGetTrackStats(peerConnection,track)}return Promise.reject(new Error(["getStats() is not supported on this version of Safari","due to this bug: https://bugs.webkit.org/show_bug.cgi?id=192601"].join(" ")))}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function chromeOrSafariGetTrackStats(peerConnection,track){return new Promise(function(resolve,reject){if(chromeMajorVersion&&chromeMajorVersion<67){peerConnection.getStats(function(response){resolve([standardizeChromeLegacyStats(response,track)])},null,reject);return}peerConnection.getStats(track).then(function(response){resolve(standardizeChromeOrSafariStats(response))},reject)})}function firefoxGetTrackStats(peerConnection,track,isRemote){return new Promise(function(resolve,reject){peerConnection.getStats(track).then(function(response){resolve([standardizeFirefoxStats(response,isRemote)])},reject)})}function standardizeChromeLegacyStats(response,track){var ssrcReport=response.result().find(function(report){return report.type==="ssrc"&&report.stat("googTrackId")===track.id});var standardizedStats={};if(ssrcReport){standardizedStats.timestamp=Math.round(Number(ssrcReport.timestamp));standardizedStats=ssrcReport.names().reduce(function(stats,name){switch(name){case"googCodecName":stats.codecName=ssrcReport.stat(name);break;case"googRtt":stats.roundTripTime=Number(ssrcReport.stat(name));break;case"googJitterReceived":stats.jitter=Number(ssrcReport.stat(name));break;case"googFrameWidthInput":stats.frameWidthInput=Number(ssrcReport.stat(name));break;case"googFrameHeightInput":stats.frameHeightInput=Number(ssrcReport.stat(name));break;case"googFrameWidthSent":stats.frameWidthSent=Number(ssrcReport.stat(name));break;case"googFrameHeightSent":stats.frameHeightSent=Number(ssrcReport.stat(name));break;case"googFrameWidthReceived":stats.frameWidthReceived=Number(ssrcReport.stat(name));break;case"googFrameHeightReceived":stats.frameHeightReceived=Number(ssrcReport.stat(name));break;case"googFrameRateInput":stats.frameRateInput=Number(ssrcReport.stat(name));break;case"googFrameRateSent":stats.frameRateSent=Number(ssrcReport.stat(name));break;case"googFrameRateReceived":stats.frameRateReceived=Number(ssrcReport.stat(name));break;case"ssrc":stats[name]=ssrcReport.stat(name);break;case"bytesReceived":case"bytesSent":case"packetsLost":case"packetsReceived":case"packetsSent":case"audioInputLevel":case"audioOutputLevel":stats[name]=Number(ssrcReport.stat(name));break}return stats},standardizedStats)}return standardizedStats}function standardizeChromeOrSafariStats(response){var inbound=null;var outbound=[];var remoteInbound=null;var remoteOutbound=null;var track=null;var codec=null;response.forEach(function(stat){switch(stat.type){case"inbound-rtp":inbound=stat;break;case"outbound-rtp":outbound.push(stat);break;case"track":track=stat;break;case"codec":codec=stat;break;case"remote-inbound-rtp":remoteInbound=stat;break;case"remote-outbound-rtp":remoteOutbound=stat;break}});var isRemote=track&&track.remoteSource;var mainSources=isRemote?[inbound]:outbound;var stats=[];var remoteSource=isRemote?remoteOutbound:remoteInbound;mainSources.forEach(function(source){var standardizedStats={};var statSources=[source,track,codec,remoteSource&&remoteSource.ssrc===source.ssrc?remoteSource:null];function getStatValue(name){var sourceFound=statSources.find(function(statSource){return statSource&&typeof statSource[name]!=="undefined"})||null;return sourceFound?sourceFound[name]:null}var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var mimeType=getStatValue("mimeType");if(typeof mimeType==="string"){mimeType=mimeType.split("/");standardizedStats.codecName=mimeType[mimeType.length-1]}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameWidth=getStatValue("frameWidth");if(typeof frameWidth==="number"){if(isRemote){standardizedStats.frameWidthReceived=frameWidth}else{standardizedStats.frameWidthSent=frameWidth}}var frameHeight=getStatValue("frameHeight");if(typeof frameHeight==="number"){if(isRemote){standardizedStats.frameHeightReceived=frameHeight}else{standardizedStats.frameHeightSent=frameHeight}}var framesPerSecond=getStatValue("framesPerSecond");if(typeof framesPerSecond==="number"){standardizedStats.frameRateSent=framesPerSecond}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var audioLevel=getStatValue("audioLevel");if(typeof audioLevel==="number"){audioLevel=Math.round(audioLevel*CHROME_LEGACY_MAX_AUDIO_LEVEL);if(isRemote){standardizedStats.audioOutputLevel=audioLevel}else{standardizedStats.audioInputLevel=audioLevel}}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}stats.push(standardizedStats)});return stats}function standardizeFirefoxStats(response,isRemote){response=response||new Map;var inbound=null;var outbound=null;response.forEach(function(stat){if(stat.isRemote){return}switch(stat.type){case"inbound-rtp":inbound=stat;outbound=response.get(stat.remoteId);break;case"outbound-rtp":outbound=stat;inbound=response.get(stat.remoteId);break}});var first=isRemote?inbound:outbound;var second=isRemote?outbound:inbound;function getStatValue(name){if(first&&typeof first[name]!=="undefined"){return first[name]}if(second&&typeof second[name]!=="undefined"){return second[name]}return null}var standardizedStats={};var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameRateSent=getStatValue("framerateMean");if(typeof frameRateSent==="number"){standardizedStats.frameRateSent=Math.round(frameRateSent)}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var frameRateReceived=getStatValue("framerateMean");if(typeof frameRateReceived==="number"){standardizedStats.frameRateReceived=Math.round(frameRateReceived)}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}return standardizedStats}module.exports=getStats},{"./util":165,"./util/sdp":167}],151:[function(require,module,exports){"use strict";function getUserMedia(constraints){if(typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"){constraints=constraints||{audio:true,video:true};return navigator.mediaDevices.getUserMedia(constraints)}return Promise.reject(new Error("getUserMedia is not supported"))}module.exports=getUserMedia},{}],152:[function(require,module,exports){"use strict";var WebRTC={};Object.defineProperties(WebRTC,{getStats:{enumerable:true,value:require("./getstats")},getUserMedia:{enumerable:true,value:require("./getusermedia")},MediaStream:{enumerable:true,value:require("./mediastream")},MediaStreamTrack:{enumerable:true,value:require("./mediastreamtrack")},RTCIceCandidate:{enumerable:true,value:require("./rtcicecandidate")},RTCPeerConnection:{enumerable:true,value:require("./rtcpeerconnection")},RTCSessionDescription:{enumerable:true,value:require("./rtcsessiondescription")},version:{enumerable:true,value:require("../package.json").version}});module.exports=WebRTC},{"../package.json":168,"./getstats":150,"./getusermedia":151,"./mediastream":153,"./mediastreamtrack":154,"./rtcicecandidate":155,"./rtcpeerconnection":158,"./rtcsessiondescription":163}],153:[function(require,module,exports){"use strict";if(typeof MediaStream==="function"){module.exports=MediaStream}else{module.exports=function MediaStream(){throw new Error("MediaStream is not supported")}}},{}],154:[function(require,module,exports){"use strict";if(typeof MediaStreamTrack==="function"){module.exports=MediaStreamTrack}else{module.exports=function MediaStreamTrack(){throw new Error("MediaStreamTrack is not supported")}}},{}],155:[function(require,module,exports){"use strict";if(typeof RTCIceCandidate==="function"){module.exports=RTCIceCandidate}else{module.exports=function RTCIceCandidate(){throw new Error("RTCIceCandidate is not supported")}}},{}],156:[function(require,module,exports){"use strict";var ChromeRTCSessionDescription=require("../rtcsessiondescription/chrome");var EventTarget=require("../util/eventtarget");var inherits=require("util").inherits;var Latch=require("../util/latch");var MediaStream=require("../mediastream");var RTCRtpSenderShim=require("../rtcrtpsender");var sdpUtils=require("../util/sdp");var util=require("../util");var isIOSChrome=require("../util").isIOSChrome;var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";function ChromeRTCPeerConnection(configuration,constraints){if(!(this instanceof ChromeRTCPeerConnection)){return new ChromeRTCPeerConnection(configuration,constraints)}EventTarget.call(this);configuration=configuration||{};var newConfiguration=Object.assign(configuration.iceTransportPolicy?{iceTransports:configuration.iceTransportPolicy}:{},configuration);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"signalingstatechange");var sdpFormat=sdpUtils.getSdpFormat(newConfiguration.sdpSemantics);var peerConnection=new RTCPeerConnection(newConfiguration,constraints);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_localStream:{value:new MediaStream},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_sdpFormat:{value:sdpFormat},_senders:{value:new Map},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer?this._pendingLocalOffer:peerConnection.localDescription}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer?this._pendingRemoteOffer:peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.ontrack=function ontrack(){};if(typeof RTCPeerConnection.prototype.addTrack!=="function"){peerConnection.addStream(this._localStream)}util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(ChromeRTCPeerConnection,EventTarget);if(typeof RTCPeerConnection.prototype.addTrack!=="function"){ChromeRTCPeerConnection.prototype.addTrack=function addTrack(){var args=[].slice.call(arguments);var track=args[0];if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection is closed")}var sender=this._senders.get(track);if(sender&&sender.track){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection already has it")}this._peerConnection.removeStream(this._localStream);this._localStream.addTrack(track);this._peerConnection.addStream(this._localStream);sender=new RTCRtpSenderShim(track);this._senders.set(track,sender);return sender};ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}var track=sender.track;if(!track){return}sender=this._senders.get(track);if(sender&&sender.track){sender.track=null;this._peerConnection.removeStream(this._localStream);this._localStream.removeTrack(track);this._peerConnection.addStream(this._localStream)}};ChromeRTCPeerConnection.prototype.getSenders=function getSenders(){return Array.from(this._senders.values())}}else{ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}try{this._peerConnection.removeTrack(sender)}catch(e){}}}ChromeRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var args=[].slice.call(arguments);var promise;var self=this;if(this.signalingState==="have-remote-offer"){promise=this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}else{promise=this._peerConnection.addIceCandidate(candidate)}return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._pendingLocalOffer=null;this._pendingRemoteOffer=null;this._peerConnection.close()}};ChromeRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;if(this._pendingRemoteOffer){promise=this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}else{promise=this._peerConnection.createAnswer().then(function(answer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})})}return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var self=this;if(isIOSChrome()){if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}}var promise=this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){dataChannelDict=shimDataChannelInit(dataChannelDict);var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};ChromeRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}var promise=setDescription(this,true,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];this._rolledBackTracksToSSRCs.clear();var promise=setDescription(this,false,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};util.delegateMethods(RTCPeerConnection.prototype,ChromeRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";var promise;if(!local&&pendingRemoteOffer&&description.type==="answer"){promise=setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(unwrap(description));promise=Promise.resolve();if(peerConnection.signalingState!==previousSignalingState){promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){promise=Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}else{clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);promise=Promise.resolve();promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}return promise||peerConnection._peerConnection[setLocalDescription](unwrap(description))}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function unwrap(description){if(description instanceof ChromeRTCSessionDescription){if(description._description){return description._description}}return new RTCSessionDescription(description)}function needsMaxPacketLifeTimeShim(){return"maxRetransmitTime"in RTCDataChannel.prototype&&!("maxPacketLifeTime"in RTCDataChannel.prototype)}function shimDataChannelInit(dataChannelDict){dataChannelDict=Object.assign({},dataChannelDict);if(needsMaxPacketLifeTimeShim()&&"maxPacketLifeTime"in dataChannelDict){dataChannelDict.maxRetransmitTime=dataChannelDict.maxPacketLifeTime}return dataChannelDict}function shimDataChannel(dataChannel){Object.defineProperty(dataChannel,"maxRetransmits",{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits});if(needsMaxPacketLifeTimeShim()){Object.defineProperty(dataChannel,"maxPacketLifeTime",{value:dataChannel.maxRetransmitTime===65535?null:dataChannel.maxRetransmitTime})}return dataChannel}function updateTrackIdsToSSRCs(sdpFormat,tracksToSSRCs,sdp){return sdpFormat==="unified"?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs(tracksToSSRCs,sdp):sdpUtils.updatePlanBTrackIdsToSSRCs(tracksToSSRCs,sdp)}module.exports=ChromeRTCPeerConnection},{"../mediastream":153,"../rtcrtpsender":160,"../rtcsessiondescription/chrome":161,"../util":165,"../util/eventtarget":164,"../util/latch":166,"../util/sdp":167,util:198}],157:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var FirefoxRTCSessionDescription=require("../rtcsessiondescription/firefox");var inherits=require("util").inherits;var updateTracksToSSRCs=require("../util/sdp").updateUnifiedPlanTrackIdsToSSRCs;var util=require("../util");var needsWorkaroundForBug1480277=typeof navigator==="object"&&navigator.userAgent&&(navigator.userAgent.match(/Firefox\/61/)||navigator.userAgent.match(/Firefox\/62/));function FirefoxRTCPeerConnection(configuration){if(!(this instanceof FirefoxRTCPeerConnection)){return new FirefoxRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"signalingstatechange");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_initiallyNegotiatedDtlsRole:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_rollingBack:{value:false,writable:true},_tracksToSSRCs:{value:new Map},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},localDescription:{enumerable:true,get:function(){return overwriteWithInitiallyNegotiatedDtlsRole(this._peerConnection.localDescription,this._initiallyNegotiatedDtlsRole)}},signalingState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.signalingState}}});var self=this;var previousSignalingState;peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(!self._rollingBack&&self.signalingState!==previousSignalingState){previousSignalingState=self.signalingState;var dispatchEventToSelf=self.dispatchEvent.apply.bind(self.dispatchEvent,self,arguments);if(self._isClosed){setTimeout(dispatchEventToSelf)}else{dispatchEventToSelf()}}});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(FirefoxRTCPeerConnection,EventTarget);Object.defineProperty(FirefoxRTCPeerConnection.prototype,"peerIdentity",{enumerable:true,value:Promise.resolve({idp:"",name:""})});if(needsWorkaroundForBug1480277){FirefoxRTCPeerConnection.prototype.addTrack=function addTrack(){var track=arguments[0];var sender=this._peerConnection.addTrack.apply(this._peerConnection,arguments);sender.replaceTrack(track);return sender}}FirefoxRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;promise=this._peerConnection.createAnswer().then(function createAnswerSucceeded(answer){saveInitiallyNegotiatedDtlsRole(self,answer);return overwriteWithInitiallyNegotiatedDtlsRole(answer,self._initiallyNegotiatedDtlsRole)});return typeof args[0]==="function"?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var promise;var self=this;if(this.signalingState==="have-local-offer"||this.signalingState==="have-remote-offer"){var local=this.signalingState==="have-local-offer";promise=rollback(this,local,function rollbackSucceeded(){return self.createOffer(options)})}else{promise=self._peerConnection.createOffer(options)}promise=promise.then(function(offer){return new FirefoxRTCSessionDescription({type:offer.type,sdp:updateTracksToSSRCs(self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;if(description&&description.type==="answer"&&this.signalingState==="have-local-offer"){promise=Promise.reject(new Error("Cannot set local answer in state have-local-offer"))}if(promise){return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise}return this._peerConnection.setLocalDescription.apply(this._peerConnection,args)};FirefoxRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;var self=this;if(description&&this.signalingState==="have-remote-offer"){if(description.type==="answer"){promise=Promise.reject(new Error("Cannot set remote answer in state have-remote-offer"))}else if(description.type==="offer"){promise=rollback(this,false,function rollbackSucceeded(){return self._peerConnection.setRemoteDescription(description)})}}if(!promise){promise=this._peerConnection.setRemoteDescription(description)}promise=promise.then(function setRemoteDescriptionSucceeded(){
55
- saveInitiallyNegotiatedDtlsRole(self,description,true)});return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};FirefoxRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._isClosed=true;this._peerConnection.close()}};util.delegateMethods(RTCPeerConnection.prototype,FirefoxRTCPeerConnection.prototype,"_peerConnection");function rollback(peerConnection,local,onceRolledBack){var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";peerConnection._rollingBack=true;return peerConnection._peerConnection[setLocalDescription](new FirefoxRTCSessionDescription({type:"rollback"})).then(onceRolledBack).then(function onceRolledBackSucceeded(result){peerConnection._rollingBack=false;return result},function rollbackOrOnceRolledBackFailed(error){peerConnection._rollingBack=false;throw error})}function saveInitiallyNegotiatedDtlsRole(peerConnection,description,remote){if(peerConnection._initiallyNegotiatedDtlsRole||description.type==="offer"){return}var match=description.sdp.match(/a=setup:([a-z]+)/);if(!match){return}var dtlsRole=match[1];peerConnection._initiallyNegotiatedDtlsRole=remote?{active:"passive",passive:"active"}[dtlsRole]:dtlsRole}function overwriteWithInitiallyNegotiatedDtlsRole(description,dtlsRole){if(description&&description.type==="answer"&&dtlsRole){return new FirefoxRTCSessionDescription({type:description.type,sdp:description.sdp.replace(/a=setup:[a-z]+/g,"a=setup:"+dtlsRole)})}return description}module.exports=FirefoxRTCPeerConnection},{"../rtcsessiondescription/firefox":162,"../util":165,"../util/eventtarget":164,"../util/sdp":167,util:198}],158:[function(require,module,exports){"use strict";if(typeof RTCPeerConnection==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;case"safari":module.exports=require("./safari");break;default:module.exports=RTCPeerConnection;break}}else{module.exports=function RTCPeerConnection(){throw new Error("RTCPeerConnection is not supported")}}},{"../util":165,"./chrome":156,"./firefox":157,"./safari":159}],159:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var inherits=require("util").inherits;var Latch=require("../util/latch");var sdpUtils=require("../util/sdp");var util=require("../util");var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";var updateTrackIdsToSSRCs=isUnifiedPlan?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs:sdpUtils.updatePlanBTrackIdsToSSRCs;function SafariRTCPeerConnection(configuration){if(!(this instanceof SafariRTCPeerConnection)){return new SafariRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"iceconnectionstatechange");util.interceptEvent(this,"signalingstatechange");util.interceptEvent(this,"track");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_audioTransceiver:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},_videoTransceiver:{value:null,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer||this._peerConnection.localDescription}},iceConnectionState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.iceConnectionState}},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer||this._peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._isClosed){return"closed"}else if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return this._peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("iceconnectionstatechange",function oniceconnectionstatechange(){if(self._isClosed){return}self.dispatchEvent.apply(self,arguments)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(self._isClosed){return}if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.addEventListener("track",function ontrack(event){self._pendingRemoteOffer=null;self.dispatchEvent(event)});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(SafariRTCPeerConnection,EventTarget);SafariRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var self=this;if(this.signalingState==="have-remote-offer"){return this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}return this._peerConnection.addIceCandidate(candidate)};SafariRTCPeerConnection.prototype.createOffer=function createOffer(options){options=Object.assign({},options);var self=this;if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}return this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new RTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,offer.sdp)})})};SafariRTCPeerConnection.prototype.createAnswer=function createAnswer(options){var self=this;if(this._pendingRemoteOffer){return this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}return this._peerConnection.createAnswer(options).then(function createAnswerSucceeded(answer){self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer})};SafariRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};SafariRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){sender.replaceTrack(null);this._peerConnection.removeTrack(sender)};SafariRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(description){if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}return setDescription(this,true,description)};SafariRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(description){this._rolledBackTracksToSSRCs.clear();return setDescription(this,false,description)};SafariRTCPeerConnection.prototype.close=function close(){if(this._isClosed){return}this._isClosed=true;this._peerConnection.close();var self=this;setTimeout(function(){self.dispatchEvent(new Event("iceconnectionstatechange"));self.dispatchEvent(new Event("signalingstatechange"))})};util.delegateMethods(RTCPeerConnection.prototype,SafariRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";if(!local&&pendingRemoteOffer&&description.type==="answer"){return setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(description);if(peerConnection.signalingState!==previousSignalingState){return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return Promise.resolve()}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){return Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return peerConnection._peerConnection[setLocalDescription](description)}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function shimDataChannel(dataChannel){return Object.defineProperties(dataChannel,{maxPacketLifeTime:{value:dataChannel.maxPacketLifeTime===65535?null:dataChannel.maxPacketLifeTime},maxRetransmits:{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits}})}module.exports=SafariRTCPeerConnection},{"../util":165,"../util/eventtarget":164,"../util/latch":166,"../util/sdp":167,util:198}],160:[function(require,module,exports){"use strict";function RTCRtpSenderShim(track){Object.defineProperties(this,{track:{enumerable:true,value:track,writable:true}})}module.exports=RTCRtpSenderShim},{}],161:[function(require,module,exports){"use strict";function ChromeRTCSessionDescription(descriptionInitDict){if(!(this instanceof ChromeRTCSessionDescription)){return new ChromeRTCSessionDescription(descriptionInitDict)}var description=descriptionInitDict&&descriptionInitDict.type==="rollback"?null:new RTCSessionDescription(descriptionInitDict);Object.defineProperties(this,{_description:{get:function(){return description}},sdp:{enumerable:true,value:description?description.sdp:descriptionInitDict.sdp},type:{enumerable:true,value:description?description.type:descriptionInitDict.type}})}module.exports=ChromeRTCSessionDescription},{}],162:[function(require,module,exports){"use strict";module.exports=RTCSessionDescription},{}],163:[function(require,module,exports){"use strict";if(typeof RTCSessionDescription==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;default:module.exports=RTCSessionDescription;break}}else{module.exports=function RTCSessionDescription(){throw new Error("RTCSessionDescription is not supported")}}},{"../util":165,"./chrome":161,"./firefox":162}],164:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter;function EventTarget(){Object.defineProperties(this,{_eventEmitter:{value:new EventEmitter}})}EventTarget.prototype.dispatchEvent=function dispatchEvent(event){return this._eventEmitter.emit(event.type,event)};EventTarget.prototype.addEventListener=function addEventListener(){return this._eventEmitter.addListener.apply(this._eventEmitter,arguments)};EventTarget.prototype.removeEventListener=function removeEventListener(){return this._eventEmitter.removeListener.apply(this._eventEmitter,arguments)};module.exports=EventTarget},{events:179}],165:[function(require,module,exports){"use strict";function defer(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject});return deferred}function delegateMethod(source,wrapper,target,methodName){if(methodName in wrapper){return}else if(methodName.match(/^on[a-z]+$/)){return}var isProperty=false;try{var propDesc=Object.getOwnPropertyDescriptor(source,methodName);isProperty=propDesc&&!!propDesc.get}catch(error){}if(isProperty){return}var type;try{type=typeof source[methodName]}catch(error){}if(type!=="function"){return}wrapper[methodName]=function(){return this[target][methodName].apply(this[target],arguments)}}function delegateMethods(source,wrapper,target){for(var methodName in source){delegateMethod(source,wrapper,target,methodName)}}function difference(list1,list2){list1=Array.isArray(list1)?new Set(list1):new Set(list1.values());list2=Array.isArray(list2)?new Set(list2):new Set(list2.values());var difference=new Set;list1.forEach(function(item){if(!list2.has(item)){difference.add(item)}});return difference}function flatMap(list,mapFn){var listArray=list instanceof Map||list instanceof Set?Array.from(list.values()):list;return listArray.reduce(function(flattened,item){var mapped=mapFn(item);return flattened.concat(mapped)},[])}function getUserAgent(){return typeof navigator!=="undefined"&&typeof navigator.userAgent==="string"?navigator.userAgent:null}function guessBrowser(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}if(/Chrome|CriOS/.test(userAgent)){return"chrome"}if(/Firefox|FxiOS/.test(userAgent)){return"firefox"}if(/Safari/.test(userAgent)){return"safari"}return null}function guessBrowserVersion(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}var prefix={chrome:"Chrome|CriOS",firefox:"Firefox|FxiOS",safari:"Version"}[guessBrowser(userAgent)];if(!prefix){return null}var regex=new RegExp("("+prefix+")/([^\\s]+)");var match=(userAgent.match(regex)||[])[2];if(!match){return null}var versions=match.split(".").map(Number);return{major:isNaN(versions[0])?null:versions[0],minor:isNaN(versions[1])?null:versions[1]}}function isIOSChrome(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}return/Mobi/.test(userAgent)&&guessBrowser()==="chrome"&&/iPad|iPhone|iPod/.test(userAgent)}function interceptEvent(target,type){var currentListener=null;Object.defineProperty(target,"on"+type,{get:function(){return currentListener},set:function(newListener){if(currentListener){this.removeEventListener(type,currentListener)}if(typeof newListener==="function"){currentListener=newListener;this.addEventListener(type,currentListener)}else{currentListener=null}}})}function legacyPromise(promise,onSuccess,onFailure){if(onSuccess){return promise.then(function(result){onSuccess(result)},function(error){onFailure(error)})}return promise}function makeUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;var v=c==="x"?r:r&3|8;return v.toString(16)})}function proxyProperties(source,wrapper,target){Object.getOwnPropertyNames(source).forEach(function(propertyName){proxyProperty(source,wrapper,target,propertyName)})}function proxyProperty(source,wrapper,target,propertyName){if(propertyName in wrapper){return}else if(propertyName.match(/^on[a-z]+$/)){Object.defineProperty(wrapper,propertyName,{value:null,writable:true});target.addEventListener(propertyName.slice(2),function(){wrapper.dispatchEvent.apply(wrapper,arguments)});return}Object.defineProperty(wrapper,propertyName,{enumerable:true,get:function(){return target[propertyName]}})}function support(){return typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"&&typeof RTCPeerConnection==="function"}exports.defer=defer;exports.delegateMethods=delegateMethods;exports.difference=difference;exports.flatMap=flatMap;exports.guessBrowser=guessBrowser;exports.guessBrowserVersion=guessBrowserVersion;exports.isIOSChrome=isIOSChrome;exports.interceptEvent=interceptEvent;exports.legacyPromise=legacyPromise;exports.makeUUID=makeUUID;exports.proxyProperties=proxyProperties;exports.support=support},{}],166:[function(require,module,exports){"use strict";var defer=require("./").defer;var states={high:new Set(["low"]),low:new Set(["high"])};function Latch(initialState){if(!(this instanceof Latch)){return new Latch(initialState)}var state=initialState||"low";Object.defineProperties(this,{_state:{set:function(_state){if(state!==_state){state=_state;var whenDeferreds=this._whenDeferreds.get(state);whenDeferreds.forEach(function(deferred){deferred.resolve(this)},this);whenDeferreds.clear()}},get:function(){return state}},_whenDeferreds:{value:new Map([["high",new Set],["low",new Set]])},state:{enumerable:true,get:function(){return this._state}}})}Latch.prototype.lower=function lower(){return this.transition("low")};Latch.prototype.raise=function raise(){return this.transition("high")};Latch.prototype.transition=function transition(newState){if(!states[this.state].has(newState)){throw createUnreachableStateError(this.state,newState)}this._state=newState;return this};Latch.prototype.when=function when(state){if(this.state===state){return Promise.resolve(this)}if(!states[this.state].has(state)){return Promise.reject(createUnreachableStateError(this.state,state))}var deferred=defer();this._whenDeferreds.get(state).add(deferred);return deferred.promise};function createUnreachableStateError(from,to){return new Error('Cannot transition from "'+from+'" to "'+to+'"')}module.exports=Latch},{"./":165}],167:[function(require,module,exports){"use strict";var flatMap=require("./").flatMap;var guessBrowser=require("./").guessBrowser;var isSdpSemanticsSupported=null;function checkIfSdpSemanticsIsSupported(){if(typeof isSdpSemanticsSupported==="boolean"){return isSdpSemanticsSupported}if(typeof RTCPeerConnection==="undefined"){isSdpSemanticsSupported=false;return isSdpSemanticsSupported}try{new RTCPeerConnection({sdpSemantics:"foo"});isSdpSemanticsSupported=false}catch(e){isSdpSemanticsSupported=true}return isSdpSemanticsSupported}var chromeSdpFormat=null;function getChromeDefaultSdpFormat(){if(!chromeSdpFormat){if(typeof RTCPeerConnection!=="undefined"&&"addTransceiver"in RTCPeerConnection.prototype){try{(new RTCPeerConnection).addTransceiver("audio");chromeSdpFormat="unified"}catch(e){chromeSdpFormat="planb"}}else{chromeSdpFormat="planb"}}return chromeSdpFormat}function getChromeSdpFormat(sdpSemantics){if(!sdpSemantics||!checkIfSdpSemanticsIsSupported()){return getChromeDefaultSdpFormat()}return{"plan-b":"planb","unified-plan":"unified"}[sdpSemantics]}function getSafariSdpFormat(){return typeof RTCRtpTransceiver!=="undefined"&&"currentDirection"in RTCRtpTransceiver.prototype?"unified":"planb"}function getSdpFormat(sdpSemantics){return{chrome:getChromeSdpFormat(sdpSemantics),firefox:"unified",safari:getSafariSdpFormat()}[guessBrowser()]||null}function getMatches(pattern,lines){var matches=lines.match(new RegExp(pattern,"gm"))||[];return matches.reduce(function(results,line){var match=line.match(new RegExp(pattern));return match?results.add(match[1]):results},new Set)}function getTrackIds(pattern,sdp){return getMatches(pattern,sdp)}function getPlanBTrackIds(sdp){return getTrackIds("^a=ssrc:[0-9]+ +msid:.+ +(.+) *$",sdp)}function getUnifiedPlanTrackIds(sdp){return getTrackIds("^a=msid:.+ +(.+) *$",sdp)}function getPlanBSSRCs(sdp,trackId){var pattern="^a=ssrc:([0-9]+) +msid:[^ ]+ +"+trackId+" *$";return getMatches(pattern,sdp)}function getMediaSections(sdp,kind,direction){kind=kind||".*";direction=direction||".*";return sdp.split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+kind,"gm");var directionPattern=new RegExp("a="+direction,"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getMediaSectionSSRCs(mediaSection){return Array.from(getMatches("^a=ssrc:([0-9]+) +.*$",mediaSection))}function getUnifiedPlanSSRCs(sdp,trackId){var mediaSections=getMediaSections(sdp);var msidAttrRegExp=new RegExp("^a=msid:[^ ]+ +"+trackId+" *$","gm");var matchingMediaSections=mediaSections.filter(function(mediaSection){return mediaSection.match(msidAttrRegExp)});return new Set(flatMap(matchingMediaSections,getMediaSectionSSRCs))}function getTrackIdsToSSRCs(getTrackIds,getSSRCs,sdp){return new Map(Array.from(getTrackIds(sdp)).map(function(trackId){return[trackId,getSSRCs(sdp,trackId)]}))}function getPlanBTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getPlanBTrackIds,getPlanBSSRCs,sdp)}function getUnifiedPlanTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getUnifiedPlanTrackIds,getUnifiedPlanSSRCs,sdp)}function updateTrackIdsToSSRCs(getTrackIdsToSSRCs,trackIdsToSSRCs,sdp){var newTrackIdsToSSRCs=getTrackIdsToSSRCs(sdp);var newSSRCsToOldSSRCs=new Map;newTrackIdsToSSRCs.forEach(function(ssrcs,trackId){if(!trackIdsToSSRCs.has(trackId)){trackIdsToSSRCs.set(trackId,ssrcs);return}var oldSSRCs=Array.from(trackIdsToSSRCs.get(trackId));var newSSRCs=Array.from(ssrcs);oldSSRCs.forEach(function(oldSSRC,i){var newSSRC=newSSRCs[i];newSSRCsToOldSSRCs.set(newSSRC,oldSSRC);var pattern="^a=ssrc:"+newSSRC+" (.*)$";var replacement="a=ssrc:"+oldSSRC+" $1";sdp=sdp.replace(new RegExp(pattern,"gm"),replacement)})});var pattern="^(a=ssrc-group:[^ ]+ +)(.*)$";var matches=sdp.match(new RegExp(pattern,"gm"))||[];matches.forEach(function(line){var match=line.match(new RegExp(pattern));if(!match){return}var prefix=match[1];var newSSRCs=match[2];var oldSSRCs=newSSRCs.split(" ").map(function(newSSRC){var oldSSRC=newSSRCsToOldSSRCs.get(newSSRC);return oldSSRC?oldSSRC:newSSRC}).join(" ");sdp=sdp.replace(match[0],prefix+oldSSRCs)});return sdp}function updatePlanBTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getPlanBTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}function updateUnifiedPlanTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getUnifiedPlanTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}exports.getSdpFormat=getSdpFormat;exports.getMediaSections=getMediaSections;exports.getPlanBTrackIds=getPlanBTrackIds;exports.getUnifiedPlanTrackIds=getUnifiedPlanTrackIds;exports.getPlanBSSRCs=getPlanBSSRCs;exports.getUnifiedPlanSSRCs=getUnifiedPlanSSRCs;exports.updatePlanBTrackIdsToSSRCs=updatePlanBTrackIdsToSSRCs;exports.updateUnifiedPlanTrackIdsToSSRCs=updateUnifiedPlanTrackIdsToSSRCs},{"./":165}],168:[function(require,module,exports){module.exports={_from:"@twilio/webrtc@4.5.1",_id:"@twilio/webrtc@4.5.1",_inBundle:false,_integrity:"sha512-0GwnffxJ71jm/7sYD8MYHzZRCR59p7KYqiMO8/Fmny7S4L0s8Ms36ghUUfCE7x/XuWjAC4FU6L/DkFN1Ewuu8Q==",_location:"/@twilio/webrtc",_phantomChildren:{},_requested:{type:"version",registry:true,raw:"@twilio/webrtc@4.5.1",name:"@twilio/webrtc",escapedName:"@twilio%2fwebrtc",scope:"@twilio",rawSpec:"4.5.1",saveSpec:null,fetchSpec:"4.5.1"},_requiredBy:["/"],_resolved:"https://registry.npmjs.org/@twilio/webrtc/-/webrtc-4.5.1.tgz",_shasum:"9a69b8f3709624b215e9481097626b1d3ae879ba",_spec:"@twilio/webrtc@4.5.1",_where:"/home/circleci/project",author:{name:"Manjesh Malavalli",email:"mmalavalli@twilio.com"},bugs:{url:"https://github.com/twilio/twilio-webrtc.js/issues"},bundleDependencies:false,contributors:[{name:"Mark Roberts",email:"mroberts@twilio.com"},{name:"Ryan Rowland",email:"rrowland@twilio.com"},{name:"Makarand Patwardhan",email:"mpatwardhan@twilio.com"}],deprecated:false,description:"WebRTC-related APIs and shims used by twilio-video.js",devDependencies:{browserify:"^14.4.0",electron:"9.4.0",envify:"^4.1.0",eslint:"^4.4.1","is-docker":"^2.0.0",istanbul:"^0.4.5",karma:"^6.3.4","karma-browserify":"^8.1.0","karma-chrome-launcher":"^2.2.0","karma-edgium-launcher":"^4.0.0-0","karma-electron":"^6.1.0","karma-firefox-launcher":"^1.0.1","karma-htmlfile-reporter":"^0.3.8","karma-junit-reporter":"^1.2.0","karma-mocha":"^2.0.1","karma-safari-launcher":"~0.1","karma-spec-reporter":"0.0.31",mocha:"^9.1.1","npm-run-all":"^4.0.2",rimraf:"^2.6.1","simple-git":"^2.4.0","twilio-release-tool":"^1.0.0",watchify:"^4.0.0","webrtc-adapter":"^6.4.8"},homepage:"https://github.com/twilio/twilio-webrtc.js#readme",keywords:["shim","twilio","video","webrtc"],license:"BSD-3-Clause",main:"./lib/index.js",name:"@twilio/webrtc",repository:{type:"git",url:"git+https://github.com/twilio/twilio-webrtc.js.git"},scripts:{build:"npm-run-all clean lint test",clean:"rimraf coverage",lint:"eslint ./lib",test:"npm-run-all test:*","test:integration":"npm-run-all test:integration:*","test:integration:adapter":"karma start karma/integration.adapter.conf.js","test:integration:native":"karma start karma/integration.conf.js","test:unit":"istanbul cover node_modules/mocha/bin/_mocha -- ./test/unit/index.js"},version:"4.5.1"}},{}],169:[function(require,module,exports){(function(global){(function(){"use strict";var possibleNames=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"];var g=typeof globalThis==="undefined"?global:globalThis;module.exports=function availableTypedArrays(){var out=[];for(var i=0;i<possibleNames.length;i++){if(typeof g[possibleNames[i]]==="function"){out[out.length]=possibleNames[i]}}return out}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],170:[function(require,module,exports){var Backoff=require("./lib/backoff");var ExponentialBackoffStrategy=require("./lib/strategy/exponential");var FibonacciBackoffStrategy=require("./lib/strategy/fibonacci");var FunctionCall=require("./lib/function_call.js");module.exports.Backoff=Backoff;module.exports.FunctionCall=FunctionCall;module.exports.FibonacciStrategy=FibonacciBackoffStrategy;module.exports.ExponentialStrategy=ExponentialBackoffStrategy;module.exports.fibonacci=function(options){return new Backoff(new FibonacciBackoffStrategy(options))};module.exports.exponential=function(options){return new Backoff(new ExponentialBackoffStrategy(options))};module.exports.call=function(fn,vargs,callback){var args=Array.prototype.slice.call(arguments);fn=args[0];vargs=args.slice(1,args.length-1);callback=args[args.length-1];return new FunctionCall(fn,vargs,callback)}},{"./lib/backoff":171,"./lib/function_call.js":172,"./lib/strategy/exponential":173,"./lib/strategy/fibonacci":174}],171:[function(require,module,exports){var events=require("events");var precond=require("precond");var util=require("util");function Backoff(backoffStrategy){events.EventEmitter.call(this);this.backoffStrategy_=backoffStrategy;this.maxNumberOfRetry_=-1;this.backoffNumber_=0;this.backoffDelay_=0;this.timeoutID_=-1;this.handlers={backoff:this.onBackoff_.bind(this)}}util.inherits(Backoff,events.EventEmitter);Backoff.prototype.failAfter=function(maxNumberOfRetry){precond.checkArgument(maxNumberOfRetry>0,"Expected a maximum number of retry greater than 0 but got %s.",maxNumberOfRetry);this.maxNumberOfRetry_=maxNumberOfRetry};Backoff.prototype.backoff=function(err){precond.checkState(this.timeoutID_===-1,"Backoff in progress.");if(this.backoffNumber_===this.maxNumberOfRetry_){this.emit("fail",err);this.reset()}else{this.backoffDelay_=this.backoffStrategy_.next();this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_);this.emit("backoff",this.backoffNumber_,this.backoffDelay_,err)}};Backoff.prototype.onBackoff_=function(){this.timeoutID_=-1;this.emit("ready",this.backoffNumber_,this.backoffDelay_);this.backoffNumber_++};Backoff.prototype.reset=function(){this.backoffNumber_=0;this.backoffStrategy_.reset();clearTimeout(this.timeoutID_);this.timeoutID_=-1};module.exports=Backoff},{events:179,precond:192,util:198}],172:[function(require,module,exports){var events=require("events");var precond=require("precond");var util=require("util");var Backoff=require("./backoff");var FibonacciBackoffStrategy=require("./strategy/fibonacci");function FunctionCall(fn,args,callback){events.EventEmitter.call(this);precond.checkIsFunction(fn,"Expected fn to be a function.");precond.checkIsArray(args,"Expected args to be an array.");precond.checkIsFunction(callback,"Expected callback to be a function.");this.function_=fn;this.arguments_=args;this.callback_=callback;this.lastResult_=[];this.numRetries_=0;this.backoff_=null;this.strategy_=null;this.failAfter_=-1;this.retryPredicate_=FunctionCall.DEFAULT_RETRY_PREDICATE_;this.state_=FunctionCall.State_.PENDING}util.inherits(FunctionCall,events.EventEmitter);FunctionCall.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3};FunctionCall.DEFAULT_RETRY_PREDICATE_=function(err){return true};FunctionCall.prototype.isPending=function(){return this.state_==FunctionCall.State_.PENDING};FunctionCall.prototype.isRunning=function(){return this.state_==FunctionCall.State_.RUNNING};FunctionCall.prototype.isCompleted=function(){return this.state_==FunctionCall.State_.COMPLETED};FunctionCall.prototype.isAborted=function(){return this.state_==FunctionCall.State_.ABORTED};FunctionCall.prototype.setStrategy=function(strategy){precond.checkState(this.isPending(),"FunctionCall in progress.");this.strategy_=strategy;return this};FunctionCall.prototype.retryIf=function(retryPredicate){precond.checkState(this.isPending(),"FunctionCall in progress.");this.retryPredicate_=retryPredicate;return this};FunctionCall.prototype.getLastResult=function(){return this.lastResult_.concat()};FunctionCall.prototype.getNumRetries=function(){return this.numRetries_};FunctionCall.prototype.failAfter=function(maxNumberOfRetry){precond.checkState(this.isPending(),"FunctionCall in progress.");this.failAfter_=maxNumberOfRetry;return this};FunctionCall.prototype.abort=function(){if(this.isCompleted()||this.isAborted()){return}if(this.isRunning()){this.backoff_.reset()}this.state_=FunctionCall.State_.ABORTED;this.lastResult_=[new Error("Backoff aborted.")];this.emit("abort");this.doCallback_()};FunctionCall.prototype.start=function(backoffFactory){precond.checkState(!this.isAborted(),"FunctionCall is aborted.");precond.checkState(this.isPending(),"FunctionCall already started.")
56
- ;var strategy=this.strategy_||new FibonacciBackoffStrategy;this.backoff_=backoffFactory?backoffFactory(strategy):new Backoff(strategy);this.backoff_.on("ready",this.doCall_.bind(this,true));this.backoff_.on("fail",this.doCallback_.bind(this));this.backoff_.on("backoff",this.handleBackoff_.bind(this));if(this.failAfter_>0){this.backoff_.failAfter(this.failAfter_)}this.state_=FunctionCall.State_.RUNNING;this.doCall_(false)};FunctionCall.prototype.doCall_=function(isRetry){if(isRetry){this.numRetries_++}var eventArgs=["call"].concat(this.arguments_);events.EventEmitter.prototype.emit.apply(this,eventArgs);var callback=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(callback))};FunctionCall.prototype.doCallback_=function(){this.callback_.apply(null,this.lastResult_)};FunctionCall.prototype.handleFunctionCallback_=function(){if(this.isAborted()){return}var args=Array.prototype.slice.call(arguments);this.lastResult_=args;events.EventEmitter.prototype.emit.apply(this,["callback"].concat(args));var err=args[0];if(err&&this.retryPredicate_(err)){this.backoff_.backoff(err)}else{this.state_=FunctionCall.State_.COMPLETED;this.doCallback_()}};FunctionCall.prototype.handleBackoff_=function(number,delay,err){this.emit("backoff",number,delay,err)};module.exports=FunctionCall},{"./backoff":171,"./strategy/fibonacci":174,events:179,precond:192,util:198}],173:[function(require,module,exports){var util=require("util");var precond=require("precond");var BackoffStrategy=require("./strategy");function ExponentialBackoffStrategy(options){BackoffStrategy.call(this,options);this.backoffDelay_=0;this.nextBackoffDelay_=this.getInitialDelay();this.factor_=ExponentialBackoffStrategy.DEFAULT_FACTOR;if(options&&options.factor!==undefined){precond.checkArgument(options.factor>1,"Exponential factor should be greater than 1 but got %s.",options.factor);this.factor_=options.factor}}util.inherits(ExponentialBackoffStrategy,BackoffStrategy);ExponentialBackoffStrategy.DEFAULT_FACTOR=2;ExponentialBackoffStrategy.prototype.next_=function(){this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay());this.nextBackoffDelay_=this.backoffDelay_*this.factor_;return this.backoffDelay_};ExponentialBackoffStrategy.prototype.reset_=function(){this.backoffDelay_=0;this.nextBackoffDelay_=this.getInitialDelay()};module.exports=ExponentialBackoffStrategy},{"./strategy":175,precond:192,util:198}],174:[function(require,module,exports){var util=require("util");var BackoffStrategy=require("./strategy");function FibonacciBackoffStrategy(options){BackoffStrategy.call(this,options);this.backoffDelay_=0;this.nextBackoffDelay_=this.getInitialDelay()}util.inherits(FibonacciBackoffStrategy,BackoffStrategy);FibonacciBackoffStrategy.prototype.next_=function(){var backoffDelay=Math.min(this.nextBackoffDelay_,this.getMaxDelay());this.nextBackoffDelay_+=this.backoffDelay_;this.backoffDelay_=backoffDelay;return backoffDelay};FibonacciBackoffStrategy.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay();this.backoffDelay_=0};module.exports=FibonacciBackoffStrategy},{"./strategy":175,util:198}],175:[function(require,module,exports){var events=require("events");var util=require("util");function isDef(value){return value!==undefined&&value!==null}function BackoffStrategy(options){options=options||{};if(isDef(options.initialDelay)&&options.initialDelay<1){throw new Error("The initial timeout must be greater than 0.")}else if(isDef(options.maxDelay)&&options.maxDelay<1){throw new Error("The maximal timeout must be greater than 0.")}this.initialDelay_=options.initialDelay||100;this.maxDelay_=options.maxDelay||1e4;if(this.maxDelay_<=this.initialDelay_){throw new Error("The maximal backoff delay must be "+"greater than the initial backoff delay.")}if(isDef(options.randomisationFactor)&&(options.randomisationFactor<0||options.randomisationFactor>1)){throw new Error("The randomisation factor must be between 0 and 1.")}this.randomisationFactor_=options.randomisationFactor||0}BackoffStrategy.prototype.getMaxDelay=function(){return this.maxDelay_};BackoffStrategy.prototype.getInitialDelay=function(){return this.initialDelay_};BackoffStrategy.prototype.next=function(){var backoffDelay=this.next_();var randomisationMultiple=1+Math.random()*this.randomisationFactor_;var randomizedDelay=Math.round(backoffDelay*randomisationMultiple);return randomizedDelay};BackoffStrategy.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")};BackoffStrategy.prototype.reset=function(){this.reset_()};BackoffStrategy.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")};module.exports=BackoffStrategy},{events:179,util:198}],176:[function(require,module,exports){"use strict";var GetIntrinsic=require("get-intrinsic");var callBind=require("./");var $indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function callBoundIntrinsic(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);if(typeof intrinsic==="function"&&$indexOf(name,".prototype.")>-1){return callBind(intrinsic)}return intrinsic}},{"./":177,"get-intrinsic":183}],177:[function(require,module,exports){"use strict";var bind=require("function-bind");var GetIntrinsic=require("get-intrinsic");var $apply=GetIntrinsic("%Function.prototype.apply%");var $call=GetIntrinsic("%Function.prototype.call%");var $reflectApply=GetIntrinsic("%Reflect.apply%",true)||bind.call($call,$apply);var $gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",true);var $defineProperty=GetIntrinsic("%Object.defineProperty%",true);var $max=GetIntrinsic("%Math.max%");if($defineProperty){try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}}module.exports=function callBind(originalFunction){var func=$reflectApply(bind,$call,arguments);if($gOPD&&$defineProperty){var desc=$gOPD(func,"length");if(desc.configurable){$defineProperty(func,"length",{value:1+$max(0,originalFunction.length-(arguments.length-1))})}}return func};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments)};if($defineProperty){$defineProperty(module.exports,"apply",{value:applyBind})}else{module.exports.apply=applyBind}},{"function-bind":182,"get-intrinsic":183}],178:[function(require,module,exports){"use strict";var GetIntrinsic=require("get-intrinsic");var $gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",true);if($gOPD){try{$gOPD([],"length")}catch(e){$gOPD=null}}module.exports=$gOPD},{"get-intrinsic":183}],179:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i<arguments.length;i++)args.push(arguments[i]);var doError=type==="error";var events=this._events;if(events!==undefined)doError=doError&&events.error===undefined;else if(!doError)return false;if(doError){var er;if(args.length>0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)ReflectApply(listeners[i],this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;checkListener(listener);events=target._events;if(events===undefined){events=target._events=Object.create(null);target._eventsCount=0}else{if(events.newListener!==undefined){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(existing===undefined){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else if(prepend){existing.unshift(listener)}else{existing.push(listener)}m=_getMaxListeners(target);if(m>0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners!==undefined){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver);reject(err)}function resolver(){if(typeof emitter.removeListener==="function"){emitter.removeListener("error",errorListener)}resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:true});if(name!=="error"){addErrorHandlerIfEventEmitter(emitter,errorListener,{once:true})}})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){if(typeof emitter.on==="function"){eventTargetAgnosticAddListener(emitter,"error",handler,flags)}}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if(typeof emitter.on==="function"){if(flags.once){emitter.once(name,listener)}else{emitter.on(name,listener)}}else if(typeof emitter.addEventListener==="function"){emitter.addEventListener(name,function wrapListener(arg){if(flags.once){emitter.removeEventListener(name,wrapListener)}listener(arg)})}else{throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter)}}},{}],180:[function(require,module,exports){var hasOwn=Object.prototype.hasOwnProperty;var toString=Object.prototype.toString;module.exports=function forEach(obj,fn,ctx){if(toString.call(fn)!=="[object Function]"){throw new TypeError("iterator must be a function")}var l=obj.length;if(l===+l){for(var i=0;i<l;i++){fn.call(ctx,obj[i],i,obj)}}else{for(var k in obj){if(hasOwn.call(obj,k)){fn.call(ctx,obj[k],k,obj)}}}}},{}],181:[function(require,module,exports){"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ";var slice=Array.prototype.slice;var toStr=Object.prototype.toString;var funcType="[object Function]";module.exports=function bind(that){var target=this;if(typeof target!=="function"||toStr.call(target)!==funcType){throw new TypeError(ERROR_MESSAGE+target)}var args=slice.call(arguments,1);var bound;var binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));if(Object(result)===result){return result}return this}else{return target.apply(that,args.concat(slice.call(arguments)))}};var boundLength=Math.max(0,target.length-args.length);var boundArgs=[];for(var i=0;i<boundLength;i++){boundArgs.push("$"+i)}bound=Function("binder","return function ("+boundArgs.join(",")+"){ return binder.apply(this,arguments); }")(binder);if(target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype;bound.prototype=new Empty;Empty.prototype=null}return bound}},{}],182:[function(require,module,exports){"use strict";var implementation=require("./implementation");module.exports=Function.prototype.bind||implementation},{"./implementation":181}],183:[function(require,module,exports){"use strict";var undefined;var $SyntaxError=SyntaxError;var $Function=Function;var $TypeError=TypeError;var getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}};var $gOPD=Object.getOwnPropertyDescriptor;if($gOPD){try{$gOPD({},"")}catch(e){$gOPD=null}}var throwTypeError=function(){throw new $TypeError};var ThrowTypeError=$gOPD?function(){try{arguments.callee;return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError;var hasSymbols=require("has-symbols")();var getProto=Object.getPrototypeOf||function(x){return x.__proto__};var needsEval={};var TypedArray=typeof Uint8Array==="undefined"?undefined:getProto(Uint8Array);var INTRINSICS={"%AggregateError%":typeof AggregateError==="undefined"?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer==="undefined"?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":typeof Atomics==="undefined"?undefined:Atomics,"%BigInt%":typeof BigInt==="undefined"?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":typeof DataView==="undefined"?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array==="undefined"?undefined:Float32Array,"%Float64Array%":typeof Float64Array==="undefined"?undefined:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry==="undefined"?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":typeof Int8Array==="undefined"?undefined:Int8Array,"%Int16Array%":typeof Int16Array==="undefined"?undefined:Int16Array,"%Int32Array%":typeof Int32Array==="undefined"?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":typeof JSON==="object"?JSON:undefined,"%Map%":typeof Map==="undefined"?undefined:Map,"%MapIteratorPrototype%":typeof Map==="undefined"||!hasSymbols?undefined:getProto((new Map)[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise==="undefined"?undefined:Promise,"%Proxy%":typeof Proxy==="undefined"?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect==="undefined"?undefined:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set==="undefined"?undefined:Set,"%SetIteratorPrototype%":typeof Set==="undefined"||!hasSymbols?undefined:getProto((new Set)[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer==="undefined"?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":typeof Uint8Array==="undefined"?undefined:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray==="undefined"?undefined:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array==="undefined"?undefined:Uint16Array,"%Uint32Array%":typeof Uint32Array==="undefined"?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap==="undefined"?undefined:WeakMap,"%WeakRef%":typeof WeakRef==="undefined"?undefined:WeakRef,"%WeakSet%":typeof WeakSet==="undefined"?undefined:WeakSet};var doEval=function doEval(name){var value;if(name==="%AsyncFunction%"){value=getEvalledConstructor("async function () {}")}else if(name==="%GeneratorFunction%"){value=getEvalledConstructor("function* () {}")}else if(name==="%AsyncGeneratorFunction%"){value=getEvalledConstructor("async function* () {}")}else if(name==="%AsyncGenerator%"){var fn=doEval("%AsyncGeneratorFunction%");if(fn){value=fn.prototype}}else if(name==="%AsyncIteratorPrototype%"){var gen=doEval("%AsyncGenerator%");if(gen){value=getProto(gen.prototype)}}INTRINSICS[name]=value;return value};var LEGACY_ALIASES={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]};var bind=require("function-bind");var hasOwn=require("has");var $concat=bind.call(Function.call,Array.prototype.concat);var $spliceApply=bind.call(Function.apply,Array.prototype.splice);var $replace=bind.call(Function.call,String.prototype.replace);var $strSlice=bind.call(Function.call,String.prototype.slice);var rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;var reEscapeChar=/\\(\\)?/g;var stringToPath=function stringToPath(string){var first=$strSlice(string,0,1);var last=$strSlice(string,-1);if(first==="%"&&last!=="%"){throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`")}else if(last==="%"&&first!=="%"){throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`")}var result=[];$replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match});return result};var getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var intrinsicName=name;var alias;if(hasOwn(LEGACY_ALIASES,intrinsicName)){alias=LEGACY_ALIASES[intrinsicName];intrinsicName="%"+alias[0]+"%"}if(hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval){value=doEval(intrinsicName)}if(typeof value==="undefined"&&!allowMissing){throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!")}return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};module.exports=function GetIntrinsic(name,allowMissing){if(typeof name!=="string"||name.length===0){throw new $TypeError("intrinsic name must be a non-empty string")}if(arguments.length>1&&typeof allowMissing!=="boolean"){throw new $TypeError('"allowMissing" argument must be a boolean')}var parts=stringToPath(name);var intrinsicBaseName=parts.length>0?parts[0]:"";var intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing);var intrinsicRealName=intrinsic.name;var value=intrinsic.value;var skipFurtherCaching=false;var alias=intrinsic.alias;if(alias){intrinsicBaseName=alias[0];$spliceApply(parts,$concat([0,1],alias))}for(var i=1,isOwn=true;i<parts.length;i+=1){var part=parts[i];var first=$strSlice(part,0,1);var last=$strSlice(part,-1);if((first==='"'||first==="'"||first==="`"||(last==='"'||last==="'"||last==="`"))&&first!==last){throw new $SyntaxError("property names with quotes must have matching quotes")}if(part==="constructor"||!isOwn){skipFurtherCaching=true}intrinsicBaseName+="."+part;intrinsicRealName="%"+intrinsicBaseName+"%";if(hasOwn(INTRINSICS,intrinsicRealName)){value=INTRINSICS[intrinsicRealName]}else if(value!=null){if(!(part in value)){if(!allowMissing){throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.")}return void undefined}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);isOwn=!!desc;if(isOwn&&"get"in desc&&!("originalValue"in desc.get)){value=desc.get}else{value=value[part]}}else{isOwn=hasOwn(value,part);value=value[part]}if(isOwn&&!skipFurtherCaching){INTRINSICS[intrinsicRealName]=value}}}return value}},{"function-bind":182,has:187,"has-symbols":184}],184:[function(require,module,exports){"use strict";var origSymbol=typeof Symbol!=="undefined"&&Symbol;var hasSymbolSham=require("./shams");module.exports=function hasNativeSymbols(){if(typeof origSymbol!=="function"){return false}if(typeof Symbol!=="function"){return false}if(typeof origSymbol("foo")!=="symbol"){return false}if(typeof Symbol("bar")!=="symbol"){return false}return hasSymbolSham()}},{"./shams":185}],185:[function(require,module,exports){"use strict";module.exports=function hasSymbols(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function"){return false}if(typeof Symbol.iterator==="symbol"){return true}var obj={};var sym=Symbol("test");var symObj=Object(sym);if(typeof sym==="string"){return false}if(Object.prototype.toString.call(sym)!=="[object Symbol]"){return false}if(Object.prototype.toString.call(symObj)!=="[object Symbol]"){return false}var symVal=42;obj[sym]=symVal;for(sym in obj){return false}if(typeof Object.keys==="function"&&Object.keys(obj).length!==0){return false}if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(obj).length!==0){return false}var syms=Object.getOwnPropertySymbols(obj);if(syms.length!==1||syms[0]!==sym){return false}if(!Object.prototype.propertyIsEnumerable.call(obj,sym)){return false}if(typeof Object.getOwnPropertyDescriptor==="function"){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(descriptor.value!==symVal||descriptor.enumerable!==true){return false}}return true}},{}],186:[function(require,module,exports){"use strict";var hasSymbols=require("has-symbols/shams");module.exports=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}},{"has-symbols/shams":185}],187:[function(require,module,exports){"use strict";var bind=require("function-bind");module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":182}],188:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],189:[function(require,module,exports){"use strict";var hasToStringTag=require("has-tostringtag/shams")();var callBound=require("call-bind/callBound");var $toString=callBound("Object.prototype.toString");var isStandardArguments=function isArguments(value){if(hasToStringTag&&value&&typeof value==="object"&&Symbol.toStringTag in value){return false}return $toString(value)==="[object Arguments]"};var isLegacyArguments=function isArguments(value){if(isStandardArguments(value)){return true}return value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&$toString(value)!=="[object Array]"&&$toString(value.callee)==="[object Function]"};var supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments;module.exports=supportsStandardArguments?isStandardArguments:isLegacyArguments},{"call-bind/callBound":176,"has-tostringtag/shams":186}],190:[function(require,module,exports){"use strict";var toStr=Object.prototype.toString;var fnToStr=Function.prototype.toString;var isFnRegex=/^\s*(?:function)?\*/;var hasToStringTag=require("has-tostringtag/shams")();var getProto=Object.getPrototypeOf;var getGeneratorFunc=function(){if(!hasToStringTag){return false}try{return Function("return function*() {}")()}catch(e){}};var GeneratorFunction;module.exports=function isGeneratorFunction(fn){if(typeof fn!=="function"){return false}if(isFnRegex.test(fnToStr.call(fn))){return true}if(!hasToStringTag){var str=toStr.call(fn);return str==="[object GeneratorFunction]"}if(!getProto){return false}if(typeof GeneratorFunction==="undefined"){var generatorFunc=getGeneratorFunc();GeneratorFunction=generatorFunc?getProto(generatorFunc):false}return getProto(fn)===GeneratorFunction}},{"has-tostringtag/shams":186}],191:[function(require,module,exports){(function(global){(function(){
57
- "use strict";var forEach=require("foreach");var availableTypedArrays=require("available-typed-arrays");var callBound=require("call-bind/callBound");var $toString=callBound("Object.prototype.toString");var hasToStringTag=require("has-tostringtag/shams")();var g=typeof globalThis==="undefined"?global:globalThis;var typedArrays=availableTypedArrays();var $indexOf=callBound("Array.prototype.indexOf",true)||function indexOf(array,value){for(var i=0;i<array.length;i+=1){if(array[i]===value){return i}}return-1};var $slice=callBound("String.prototype.slice");var toStrTags={};var gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor");var getPrototypeOf=Object.getPrototypeOf;if(hasToStringTag&&gOPD&&getPrototypeOf){forEach(typedArrays,function(typedArray){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr);var descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}})}var tryTypedArrays=function tryAllTypedArrays(value){var anyTrue=false;forEach(toStrTags,function(getter,typedArray){if(!anyTrue){try{anyTrue=getter.call(value)===typedArray}catch(e){}}});return anyTrue};module.exports=function isTypedArray(value){if(!value||typeof value!=="object"){return false}if(!hasToStringTag||!(Symbol.toStringTag in value)){var tag=$slice($toString(value),8,-1);return $indexOf(typedArrays,tag)>-1}if(!gOPD){return false}return tryTypedArrays(value)}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"available-typed-arrays":169,"call-bind/callBound":176,"es-abstract/helpers/getOwnPropertyDescriptor":178,foreach:180,"has-tostringtag/shams":186}],192:[function(require,module,exports){module.exports=require("./lib/checks")},{"./lib/checks":193}],193:[function(require,module,exports){var util=require("util");var errors=module.exports=require("./errors");function failCheck(ExceptionConstructor,callee,messageFormat,formatArgs){messageFormat=messageFormat||"";var message=util.format.apply(this,[messageFormat].concat(formatArgs));var error=new ExceptionConstructor(message);Error.captureStackTrace(error,callee);throw error}function failArgumentCheck(callee,message,formatArgs){failCheck(errors.IllegalArgumentError,callee,message,formatArgs)}function failStateCheck(callee,message,formatArgs){failCheck(errors.IllegalStateError,callee,message,formatArgs)}module.exports.checkArgument=function(value,message){if(!value){failArgumentCheck(arguments.callee,message,Array.prototype.slice.call(arguments,2))}};module.exports.checkState=function(value,message){if(!value){failStateCheck(arguments.callee,message,Array.prototype.slice.call(arguments,2))}};module.exports.checkIsDef=function(value,message){if(value!==undefined){return value}failArgumentCheck(arguments.callee,message||"Expected value to be defined but was undefined.",Array.prototype.slice.call(arguments,2))};module.exports.checkIsDefAndNotNull=function(value,message){if(value!=null){return value}failArgumentCheck(arguments.callee,message||'Expected value to be defined and not null but got "'+typeOf(value)+'".',Array.prototype.slice.call(arguments,2))};function typeOf(value){var s=typeof value;if(s=="object"){if(!value){return"null"}else if(value instanceof Array){return"array"}}return s}function typeCheck(expect){return function(value,message){var type=typeOf(value);if(type==expect){return value}failArgumentCheck(arguments.callee,message||'Expected "'+expect+'" but got "'+type+'".',Array.prototype.slice.call(arguments,2))}}module.exports.checkIsString=typeCheck("string");module.exports.checkIsArray=typeCheck("array");module.exports.checkIsNumber=typeCheck("number");module.exports.checkIsBoolean=typeCheck("boolean");module.exports.checkIsFunction=typeCheck("function");module.exports.checkIsObject=typeCheck("object")},{"./errors":194,util:198}],194:[function(require,module,exports){var util=require("util");function IllegalArgumentError(message){Error.call(this,message);this.message=message}util.inherits(IllegalArgumentError,Error);IllegalArgumentError.prototype.name="IllegalArgumentError";function IllegalStateError(message){Error.call(this,message);this.message=message}util.inherits(IllegalStateError,Error);IllegalStateError.prototype.name="IllegalStateError";module.exports.IllegalStateError=IllegalStateError;module.exports.IllegalArgumentError=IllegalArgumentError},{util:198}],195:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";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.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[]};process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],196:[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"}},{}],197:[function(require,module,exports){"use strict";var isArgumentsObject=require("is-arguments");var isGeneratorFunction=require("is-generator-function");var whichTypedArray=require("which-typed-array");var isTypedArray=require("is-typed-array");function uncurryThis(f){return f.call.bind(f)}var BigIntSupported=typeof BigInt!=="undefined";var SymbolSupported=typeof Symbol!=="undefined";var ObjectToString=uncurryThis(Object.prototype.toString);var numberValue=uncurryThis(Number.prototype.valueOf);var stringValue=uncurryThis(String.prototype.valueOf);var booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported){var bigIntValue=uncurryThis(BigInt.prototype.valueOf)}if(SymbolSupported){var symbolValue=uncurryThis(Symbol.prototype.valueOf)}function checkBoxedPrimitive(value,prototypeValueOf){if(typeof value!=="object"){return false}try{prototypeValueOf(value);return true}catch(e){return false}}exports.isArgumentsObject=isArgumentsObject;exports.isGeneratorFunction=isGeneratorFunction;exports.isTypedArray=isTypedArray;function isPromise(input){return typeof Promise!=="undefined"&&input instanceof Promise||input!==null&&typeof input==="object"&&typeof input.then==="function"&&typeof input.catch==="function"}exports.isPromise=isPromise;function isArrayBufferView(value){if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView){return ArrayBuffer.isView(value)}return isTypedArray(value)||isDataView(value)}exports.isArrayBufferView=isArrayBufferView;function isUint8Array(value){return whichTypedArray(value)==="Uint8Array"}exports.isUint8Array=isUint8Array;function isUint8ClampedArray(value){return whichTypedArray(value)==="Uint8ClampedArray"}exports.isUint8ClampedArray=isUint8ClampedArray;function isUint16Array(value){return whichTypedArray(value)==="Uint16Array"}exports.isUint16Array=isUint16Array;function isUint32Array(value){return whichTypedArray(value)==="Uint32Array"}exports.isUint32Array=isUint32Array;function isInt8Array(value){return whichTypedArray(value)==="Int8Array"}exports.isInt8Array=isInt8Array;function isInt16Array(value){return whichTypedArray(value)==="Int16Array"}exports.isInt16Array=isInt16Array;function isInt32Array(value){return whichTypedArray(value)==="Int32Array"}exports.isInt32Array=isInt32Array;function isFloat32Array(value){return whichTypedArray(value)==="Float32Array"}exports.isFloat32Array=isFloat32Array;function isFloat64Array(value){return whichTypedArray(value)==="Float64Array"}exports.isFloat64Array=isFloat64Array;function isBigInt64Array(value){return whichTypedArray(value)==="BigInt64Array"}exports.isBigInt64Array=isBigInt64Array;function isBigUint64Array(value){return whichTypedArray(value)==="BigUint64Array"}exports.isBigUint64Array=isBigUint64Array;function isMapToString(value){return ObjectToString(value)==="[object Map]"}isMapToString.working=typeof Map!=="undefined"&&isMapToString(new Map);function isMap(value){if(typeof Map==="undefined"){return false}return isMapToString.working?isMapToString(value):value instanceof Map}exports.isMap=isMap;function isSetToString(value){return ObjectToString(value)==="[object Set]"}isSetToString.working=typeof Set!=="undefined"&&isSetToString(new Set);function isSet(value){if(typeof Set==="undefined"){return false}return isSetToString.working?isSetToString(value):value instanceof Set}exports.isSet=isSet;function isWeakMapToString(value){return ObjectToString(value)==="[object WeakMap]"}isWeakMapToString.working=typeof WeakMap!=="undefined"&&isWeakMapToString(new WeakMap);function isWeakMap(value){if(typeof WeakMap==="undefined"){return false}return isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap}exports.isWeakMap=isWeakMap;function isWeakSetToString(value){return ObjectToString(value)==="[object WeakSet]"}isWeakSetToString.working=typeof WeakSet!=="undefined"&&isWeakSetToString(new WeakSet);function isWeakSet(value){return isWeakSetToString(value)}exports.isWeakSet=isWeakSet;function isArrayBufferToString(value){return ObjectToString(value)==="[object ArrayBuffer]"}isArrayBufferToString.working=typeof ArrayBuffer!=="undefined"&&isArrayBufferToString(new ArrayBuffer);function isArrayBuffer(value){if(typeof ArrayBuffer==="undefined"){return false}return isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer}exports.isArrayBuffer=isArrayBuffer;function isDataViewToString(value){return ObjectToString(value)==="[object DataView]"}isDataViewToString.working=typeof ArrayBuffer!=="undefined"&&typeof DataView!=="undefined"&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1));function isDataView(value){if(typeof DataView==="undefined"){return false}return isDataViewToString.working?isDataViewToString(value):value instanceof DataView}exports.isDataView=isDataView;var SharedArrayBufferCopy=typeof SharedArrayBuffer!=="undefined"?SharedArrayBuffer:undefined;function isSharedArrayBufferToString(value){return ObjectToString(value)==="[object SharedArrayBuffer]"}function isSharedArrayBuffer(value){if(typeof SharedArrayBufferCopy==="undefined"){return false}if(typeof isSharedArrayBufferToString.working==="undefined"){isSharedArrayBufferToString.working=isSharedArrayBufferToString(new SharedArrayBufferCopy)}return isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBufferCopy}exports.isSharedArrayBuffer=isSharedArrayBuffer;function isAsyncFunction(value){return ObjectToString(value)==="[object AsyncFunction]"}exports.isAsyncFunction=isAsyncFunction;function isMapIterator(value){return ObjectToString(value)==="[object Map Iterator]"}exports.isMapIterator=isMapIterator;function isSetIterator(value){return ObjectToString(value)==="[object Set Iterator]"}exports.isSetIterator=isSetIterator;function isGeneratorObject(value){return ObjectToString(value)==="[object Generator]"}exports.isGeneratorObject=isGeneratorObject;function isWebAssemblyCompiledModule(value){return ObjectToString(value)==="[object WebAssembly.Module]"}exports.isWebAssemblyCompiledModule=isWebAssemblyCompiledModule;function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}exports.isNumberObject=isNumberObject;function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}exports.isStringObject=isStringObject;function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}exports.isBooleanObject=isBooleanObject;function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}exports.isBigIntObject=isBigIntObject;function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}exports.isSymbolObject=isSymbolObject;function isBoxedPrimitive(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)}exports.isBoxedPrimitive=isBoxedPrimitive;function isAnyArrayBuffer(value){return typeof Uint8Array!=="undefined"&&(isArrayBuffer(value)||isSharedArrayBuffer(value))}exports.isAnyArrayBuffer=isAnyArrayBuffer;["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(method){Object.defineProperty(exports,method,{enumerable:false,value:function(){throw new Error(method+" is not supported in userland")}})})},{"is-arguments":189,"is-generator-function":190,"is-typed-array":191,"which-typed-array":199}],198:[function(require,module,exports){(function(process){(function(){var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function getOwnPropertyDescriptors(obj){var keys=Object.keys(obj);var descriptors={};for(var i=0;i<keys.length;i++){descriptors[keys[i]]=Object.getOwnPropertyDescriptor(obj,keys[i])}return descriptors};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};exports.deprecate=function(fn,msg){if(typeof process!=="undefined"&&process.noDeprecation===true){return fn}if(typeof process==="undefined"){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}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 debugEnvRegex=/^$/;if(process.env.NODE_DEBUG){var debugEnv=process.env.NODE_DEBUG;debugEnv=debugEnv.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase();debugEnvRegex=new RegExp("^"+debugEnv+"$","i")}exports.debuglog=function(set){set=set.toUpperCase();if(!debugs[set]){if(debugEnvRegex.test(set)){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]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}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;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]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"\x1b["+inspect.colors[style][0]+"m"+str+"\x1b["+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){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}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=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}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");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]}exports.types=require("./support/types");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;exports.types.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;exports.types.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;exports.types.isNativeError=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"||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"];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(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){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)}var kCustomPromisifiedSymbol=typeof Symbol!=="undefined"?Symbol("util.promisify.custom"):undefined;exports.promisify=function promisify(original){if(typeof original!=="function")throw new TypeError('The "original" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if(typeof fn!=="function"){throw new TypeError('The "util.promisify.custom" argument must be of type Function')}Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:false,writable:false,configurable:true});return fn}function fn(){var promiseResolve,promiseReject;var promise=new Promise(function(resolve,reject){promiseResolve=resolve;promiseReject=reject});var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i])}args.push(function(err,value){if(err){promiseReject(err)}else{promiseResolve(value)}});try{original.apply(this,args)}catch(err){promiseReject(err)}return promise}Object.setPrototypeOf(fn,Object.getPrototypeOf(original));if(kCustomPromisifiedSymbol)Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:false,writable:false,configurable:true});return Object.defineProperties(fn,getOwnPropertyDescriptors(original))};exports.promisify.custom=kCustomPromisifiedSymbol;function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason;reason=newReason}return cb(reason)}function callbackify(original){if(typeof original!=="function"){throw new TypeError('The "original" argument must be of type Function')}function callbackified(){var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i])}var maybeCb=args.pop();if(typeof maybeCb!=="function"){throw new TypeError("The last argument must be of type Function")}var self=this;var cb=function(){return maybeCb.apply(self,arguments)};original.apply(this,args).then(function(ret){process.nextTick(cb.bind(null,null,ret))},function(rej){process.nextTick(callbackifyOnRejected.bind(null,rej,cb))})}Object.setPrototypeOf(callbackified,Object.getPrototypeOf(original));Object.defineProperties(callbackified,getOwnPropertyDescriptors(original));return callbackified}exports.callbackify=callbackify}).call(this)}).call(this,require("_process"))},{"./support/isBuffer":196,"./support/types":197,_process:195,inherits:188}],199:[function(require,module,exports){(function(global){(function(){"use strict";var forEach=require("foreach");var availableTypedArrays=require("available-typed-arrays");var callBound=require("call-bind/callBound");var $toString=callBound("Object.prototype.toString");var hasToStringTag=require("has-tostringtag/shams")();var g=typeof globalThis==="undefined"?global:globalThis;var typedArrays=availableTypedArrays();var $slice=callBound("String.prototype.slice");var toStrTags={};var gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor");var getPrototypeOf=Object.getPrototypeOf;if(hasToStringTag&&gOPD&&getPrototypeOf){forEach(typedArrays,function(typedArray){if(typeof g[typedArray]==="function"){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr);var descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}}})}var tryTypedArrays=function tryAllTypedArrays(value){var foundName=false;forEach(toStrTags,function(getter,typedArray){if(!foundName){try{var name=getter.call(value);if(name===typedArray){foundName=name}}catch(e){}}});return foundName};var isTypedArray=require("is-typed-array");module.exports=function whichTypedArray(value){if(!isTypedArray(value)){return false}if(!hasToStringTag||!(Symbol.toStringTag in value)){return $slice($toString(value),8,-1)}return tryTypedArrays(value)}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"available-typed-arrays":169,"call-bind/callBound":176,"es-abstract/helpers/getOwnPropertyDescriptor":178,foreach:180,"has-tostringtag/shams":186,"is-typed-array":191}],200:[function(require,module,exports){module.exports={name:"twilio-video",title:"Twilio Video",description:"Twilio Video JavaScript Library",version:"2.18.2",homepage:"https://twilio.com",author:"Mark Andrus Roberts <mroberts@twilio.com>",contributors:["Ryan Rowland <rrowland@twilio.com>","Manjesh Malavalli <mmalavalli@twilio.com>","Makarand Patwardhan <mpatwardhan@twilio.com>"],keywords:["twilio","webrtc","library","javascript","video","rooms"],repository:{type:"git",url:"https://github.com/twilio/twilio-video.js.git"},devDependencies:{"@babel/core":"^7.14.2","@babel/preset-env":"^7.14.2","@babel/preset-typescript":"^7.13.0","@types/express":"^4.11.0","@types/node":"^8.5.1","@types/selenium-webdriver":"^3.0.8","@types/ws":"^3.2.1","@typescript-eslint/eslint-plugin":"^4.13.0","@typescript-eslint/parser":"^4.0.0","babel-cli":"^6.26.0","babel-preset-es2015":"^6.24.1",browserify:"^17.0.0",cheerio:"^0.22.0",cors:"^2.8.5",electron:"^9.1.0",envify:"^4.0.0",eslint:"^6.2.1","eslint-config-standard":"^14.0.0","eslint-plugin-import":"^2.18.2","eslint-plugin-node":"^9.1.0","eslint-plugin-promise":"^4.2.1","eslint-plugin-standard":"^4.0.1",express:"^4.16.2",glob:"^7.1.7","ink-docstrap":"^1.3.2",inquirer:"^7.0.0","is-docker":"^2.0.0",jsdoc:"^3.5.5","jsdoc-babel":"^0.5.0","json-loader":"^0.5.7",karma:"^5.0.2","karma-browserify":"^8.0.0","karma-chrome-launcher":"^2.0.0","karma-edgium-launcher":"^4.0.0-0","karma-electron":"^6.1.0","karma-firefox-launcher":"^1.3.0","karma-htmlfile-reporter":"^0.3.8","karma-junit-reporter":"^1.2.0","karma-mocha":"^1.3.0","karma-safari-launcher":"^1.0.0","karma-spec-reporter":"0.0.32","karma-typescript":"^5.5.1","karma-typescript-es6-transform":"^5.5.1",mocha:"^3.2.0","mock-require":"^3.0.3",ncp:"^2.0.0","node-http-server":"^8.1.2","npm-run-all":"^4.0.2",nyc:"^15.1.0",requirejs:"^2.3.3",rimraf:"^2.6.1","simple-git":"^1.126.0",sinon:"^4.0.1","ts-node":"4.0.1",tslint:"5.8.0",twilio:"^3.49.0","twilio-release-tool":"^1.0.2",typescript:"4.2.2","uglify-js":"^2.8.22","vinyl-fs":"^2.4.4","vinyl-source-stream":"^1.1.0",watchify:"^3.11.1","webrtc-adapter":"^7.7.1"},engines:{node:">=0.12"},license:"BSD-3-Clause",main:"./es5/index.js",types:"./tsdef/index.d.ts",scripts:{"lint:js":"eslint ./lib ./test/*.js ./docker/**/*.js ./test/framework/*.js ./test/lib/*.js ./test/integration/** ./test/unit/** ","lint:ts":"eslint ./tsdef/*.ts ./lib/**/*.ts",lint:"npm-run-all lint:js lint:ts",printVersion:"node --version && npm --version","test:unit":"npm-run-all printVersion build:es5 test:unit:js test:unit:ts","test:unit:js":"nyc --report-dir=./coverage/js --extension=.js --include=lib/**/* --reporter=html --reporter=lcov --reporter=text mocha ./test/unit/index.js","test:unit:ts":"nyc --report-dir=./coverage/ts --extension=.ts --include=lib/**/* --reporter=html --reporter=lcov --reporter=text mocha -r ts-node/register ./test/unit/index.ts","test:serversiderender":"mocha ./test/serversiderender/index.js","test:integration:adapter":"node ./scripts/karma.js karma/integration.adapter.conf.js","test:integration":"npm run build:es5 && node ./scripts/karma.js karma/integration.conf.js","test:umd:install":"npm install puppeteer@5.5.0","test:umd":"mocha ./test/umd/index.js",
58
- "test:crossbrowser:build:clean":"rimraf ./test/crossbrowser/lib ./test/crossbrowser/src/browser/index.js","test:crossbrowser:build:lint":"cd ./test/crossbrowser && tslint --project tsconfig.json","test:crossbrowser:build:tsc":"cd ./test/crossbrowser && tsc","test:crossbrowser:build:browser":"cd ./test/crossbrowser && browserify lib/crossbrowser/src/browser/index.js > src/browser/index.js","test:crossbrowser:build":"npm-run-all test:crossbrowser:build:*","test:crossbrowser:test":"cd ./test/crossbrowser && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:crossbrowser":"npm-run-all test:crossbrowser:*","test:sdkdriver:build:clean":"rimraf ./test/lib/sdkdriver/lib ./test/lib/sdkdriver/test/integration/browser/index.js","test:sdkdriver:build:lint":"cd ./test/lib/sdkdriver && tslint --project tsconfig.json","test:sdkdriver:build:tsc":"cd ./test/lib/sdkdriver && tsc --rootDir src","test:sdkdriver:build":"npm-run-all test:sdkdriver:build:*","test:sdkdriver:test:unit":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/unit/spec/**/*.ts","test:sdkdriver:test:integration:browser":"cd ./test/lib/sdkdriver/test/integration && browserify browser/browser.js > browser/index.js","test:sdkdriver:test:integration:run":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:sdkdriver:test:integration":"npm-run-all test:sdkdriver:test:integration:*","test:sdkdriver:test":"npm-run-all test:sdkdriver:test:*","test:sdkdriver":"npm-run-all test:sdkdriver:*","test:framework:angular:install":"cd ./test/framework/twilio-video-angular && rimraf ./node_modules package-lock.json && npm install","test:framework:angular:run":"mocha ./test/framework/twilio-video-angular.js","test:framework:angular":"npm-run-all test:framework:angular:*","test:framework:no-framework:run":"mocha ./test/framework/twilio-video-no-framework.js","test:framework:no-framework":"npm-run-all test:framework:no-framework:*","test:framework:react:install":"cd ./test/framework/twilio-video-react && rimraf ./node_modules package-lock.json && npm install","test:framework:react:test":"node ./scripts/framework.js twilio-video-react","test:framework:react:build":"cd ./test/framework/twilio-video-react && npm run build","test:framework:react:run":"mocha ./test/framework/twilio-video-react.js","test:framework:react":"npm-run-all test:framework:react:*","test:framework:install":"npm install chromedriver && npm install selenium-webdriver && npm install geckodriver && npm install puppeteer","test:framework":"npm-run-all test:framework:install test:framework:no-framework test:framework:react",test:"npm-run-all test:unit test:integration","build:es5":"rimraf ./es5 && tsc tsdef/twilio-video-tests.ts --noEmit && tsc","build:js":"node ./scripts/build.js ./src/twilio-video.js ./LICENSE.md ./dist/twilio-video.js","build:min.js":'uglifyjs ./dist/twilio-video.js -o ./dist/twilio-video.min.js --comments "/^! twilio-video.js/" -b beautify=false,ascii_only=true',build:"npm-run-all clean lint docs test:unit test:integration build:es5 build:js build:min.js test:umd","build:quick":"npm-run-all clean lint docs build:es5 build:js build:min.js",docs:"node ./scripts/docs.js ./dist/docs",watch:"tsc -w",clean:"rimraf ./coverage ./es5 ./dist"},dependencies:{"@twilio/webrtc":"4.5.1",backoff:"^2.5.0",ws:"^7.4.6",xmlhttprequest:"^1.8.0"},browser:{ws:"./src/ws.js",xmlhttprequest:"./src/xmlhttprequest.js"}}},{}],201:[function(require,module,exports){module.exports=WebSocket},{}]},{},[11]);var Video=bundle(11);if(typeof define==="function"&&define.amd){define([],function(){return Video})}else{var Twilio=root.Twilio=root.Twilio||{};Twilio.Video=Twilio.Video||Video}})(typeof window!=="undefined"?window:typeof global!=="undefined"?global:this);
50
+ _this._handleBad(message);break;case"busy":_this._handleBusy(message);break;case"bye":break;case"msg":_this._handleMessage(message);case"heartbeat":_this._handleHeartbeat();break;case"welcome":_this._handleWelcome(message);break;default:_this._log.debug("Unknown message type: "+message.type);_this.emit("error",new Error("Unknown message type: "+message.type));break}})};TwilioConnection.prototype._handleBad=function(_a){var reason=_a.reason;var log=this._log;if(!["connecting","open"].includes(this.state)){log.warn('Unexpected state "'+this.state+'" for handling a "bad" message'+" from the TCMP server.");return}if(this.state==="connecting"){log.warn("Closing: "+WS_CLOSE_HELLO_FAILED+" - "+reason);this._close({code:WS_CLOSE_HELLO_FAILED,reason:reason});return}log.debug("Error: "+reason);this.emit("error",new Error(reason))};TwilioConnection.prototype._handleBusy=function(_a){var _this=this;var cookie=_a.cookie,keepAlive=_a.keepAlive,retryAfter=_a.retryAfter;var log=this._log;if(!["connecting","waiting"].includes(this.state)){log.warn('Unexpected state "'+this.state+'" for handling a "busy" message'+" from the TCMP server.");return}if(this._busyWaitTimeout){this._busyWaitTimeout.clear()}if(this._welcomeTimeout){this._welcomeTimeout.clear()}var reason=retryAfter<0?'Received terminal "busy" message':'Received "busy" message, retrying after '+retryAfter+" ms";if(retryAfter<0){log.warn("Closing: "+WS_CLOSE_SERVER_BUSY+" - "+reason);this._close({code:WS_CLOSE_SERVER_BUSY,reason:reason});return}var maxConsecutiveFailedHellos=this._options.maxConsecutiveFailedHellos;this._hellosLeft=maxConsecutiveFailedHellos;this._cookie=cookie||null;if(keepAlive){log.warn(reason);this._busyWaitTimeout=new Timeout(function(){return _this._startHandshake()},retryAfter)}else{log.warn("Closing: "+WS_CLOSE_BUSY_WAIT+" - "+reason);this._close({code:WS_CLOSE_BUSY_WAIT,reason:reason});this._busyWaitTimeout=new Timeout(function(){return _this._connect()},retryAfter)}this.transition("waiting",null,[keepAlive,retryAfter])};TwilioConnection.prototype._handleHeartbeat=function(){if(this.state!=="open"){this._log.warn('Unexpected state "'+this.state+'" for handling a "heartbeat"'+" message from the TCMP server.");return}this._heartbeatTimeout.reset()};TwilioConnection.prototype._handleHeartbeatTimeout=function(){if(this.state!=="open"){return}var log=this._log;var maxConsecutiveMissedHeartbeats=this._options.maxConsecutiveMissedHeartbeats;log.debug("Consecutive heartbeats missed: "+maxConsecutiveMissedHeartbeats);var reason="Missed "+maxConsecutiveMissedHeartbeats+' "heartbeat" messages';log.warn("Closing: "+WS_CLOSE_HEARTBEATS_MISSED+" - "+reason);this._close({code:WS_CLOSE_HEARTBEATS_MISSED,reason:reason})};TwilioConnection.prototype._handleMessage=function(_a){var body=_a.body;if(this.state!=="open"){this._log.warn('Unexpected state "'+this.state+'" for handling a "msg" message'+" from the TCMP server.");return}this.emit("message",body)};TwilioConnection.prototype._handleWelcome=function(_a){var _this=this;var negotiatedTimeout=_a.negotiatedTimeout;var log=this._log;if(!["connecting","waiting"].includes(this.state)){log.warn('Unexpected state "'+this.state+'" for handling a "welcome"'+" message from the TCMP server.");return}if(this.state==="waiting"){log.debug('Received "welcome" message, no need to retry connection.');this._busyWaitTimeout.clear()}var maxConsecutiveMissedHeartbeats=this._options.maxConsecutiveMissedHeartbeats;var heartbeatTimeout=negotiatedTimeout*maxConsecutiveMissedHeartbeats;var outgoingHeartbeatTimeout=negotiatedTimeout-OUTGOING_HEARTBEAT_OFFSET;this._welcomeTimeout.clear();this._heartbeatTimeout=new Timeout(function(){return _this._handleHeartbeatTimeout()},heartbeatTimeout);this._messageQueue.splice(0).forEach(function(message){return _this._send(message)});this._sendHeartbeatTimeout=new Timeout(function(){return _this._sendHeartbeat()},outgoingHeartbeatTimeout);this.transition("open")};TwilioConnection.prototype._handleWelcomeTimeout=function(){if(this.state!=="connecting"){return}var log=this._log;if(this._hellosLeft<=0){var reason="All handshake attempts failed";log.warn("Closing: "+WS_CLOSE_WELCOME_TIMEOUT+" - "+reason);this._close({code:WS_CLOSE_WELCOME_TIMEOUT,reason:reason});return}var maxConsecutiveFailedHellos=this._options.maxConsecutiveFailedHellos;log.warn("Handshake attempt "+(maxConsecutiveFailedHellos-this._hellosLeft)+" failed");this._startHandshake()};TwilioConnection.prototype._send=function(message){var readyState=this._ws.readyState;var WebSocket=this._options.WebSocket;if(readyState===WebSocket.OPEN){var data=JSON.stringify(message);this._log.debug("Outgoing: "+data);try{this._ws.send(data);if(this._sendHeartbeatTimeout){this._sendHeartbeatTimeout.reset()}}catch(error){var reason="Failed to send message";this._log.warn("Closing: "+WS_CLOSE_SEND_FAILED+" - "+reason);this._close({code:WS_CLOSE_SEND_FAILED,reason:reason})}}};TwilioConnection.prototype._sendHeartbeat=function(){if(this.state==="closed"){return}this._send({type:"heartbeat"})};TwilioConnection.prototype._sendHello=function(){var _a=this._options,helloBody=_a.helloBody,timeout=_a.requestedHeartbeatTimeout;var hello={id:makeUUID(),timeout:timeout,type:"hello",version:TCMP_VERSION};if(this._cookie){hello.cookie=this._cookie}if(helloBody){hello.body=helloBody}this._send(hello)};TwilioConnection.prototype._sendOrEnqueue=function(message){var _this=this;if(this.state==="closed"){return}var sendOrEnqueue=this.state==="open"?function(message){return _this._send(message)}:function(message){return _this._messageQueue.push(message)};sendOrEnqueue(message)};TwilioConnection.prototype._startHandshake=function(){var _this=this;if(["early","waiting"].includes(this.state)){this.transition("connecting")}if(this.state!=="connecting"){return}this._hellosLeft--;this._sendHello();var welcomeTimeout=this._options.welcomeTimeout;this._welcomeTimeout=new Timeout(function(){return _this._handleWelcomeTimeout()},welcomeTimeout)};TwilioConnection.prototype.close=function(){if(this.state==="closed"){return}this._sendOrEnqueue({type:"bye"});this._close({code:WS_CLOSE_NORMAL,reason:"Normal"})};TwilioConnection.prototype.sendMessage=function(body){this._sendOrEnqueue({body:body,type:"msg"})};return TwilioConnection}(StateMachine);TwilioConnection.CloseReason=CloseReason;module.exports=TwilioConnection}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./statemachine":84,"./util":126,"./util/log":130,"./util/networkmonitor":132,"./util/timeout":142,ws:201}],117:[function(require,module,exports){"use strict";var defer=require("./").defer;var AsyncVar=function(){function AsyncVar(){Object.defineProperties(this,{_deferreds:{value:[]},_hasValue:{value:false,writable:true},_value:{value:null,writable:true}})}AsyncVar.prototype.put=function(value){this._hasValue=true;this._value=value;var deferred=this._deferreds.shift();if(deferred){deferred.resolve(value)}return this};AsyncVar.prototype.take=function(){var _this=this;if(this._hasValue&&!this._deferreds.length){this._hasValue=false;return Promise.resolve(this._value)}var deferred=defer();this._deferreds.push(deferred);return deferred.promise.then(function(value){_this._hasValue=false;return value})};return AsyncVar}();module.exports=AsyncVar},{"./":126}],118:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};function isAndroid(){return/Android/.test(navigator.userAgent)}function isIOS(){return/iPad|iPhone|iPod/.test(navigator.userAgent)}function isMobile(){return/Mobi/.test(navigator.userAgent)}function isNonChromiumEdge(browser){return browser==="chrome"&&/Edge/.test(navigator.userAgent)&&(typeof chrome==="undefined"||typeof chrome.runtime==="undefined")}function rebrandedChromeBrowser(browser){if(browser!=="chrome"){return null}if("brave"in navigator){return"brave"}var parenthesizedSubstrings=getParenthesizedSubstrings(navigator.userAgent);var nameAndVersions=parenthesizedSubstrings.reduce(function(userAgent,substring){return userAgent.replace(substring,"")},navigator.userAgent);var matches=nameAndVersions.match(/[^\s]+/g)||[];var _a=__read(matches.map(function(nameAndVersion){return nameAndVersion.split("/")[0].toLowerCase()})),browserNames=_a.slice(2);return browserNames.find(function(name){return!["chrome","mobile","safari"].includes(name)})||null}function mobileWebKitBrowser(browser){if(browser!=="safari"){return null}if("brave"in navigator){return"brave"}return["edge","edg"].find(function(name){return navigator.userAgent.toLowerCase().includes(name)})||null}function getParenthesizedSubstrings(string){var openParenthesisPositions=[];var substrings=[];for(var i=0;i<string.length;i++){if(string[i]==="("){openParenthesisPositions.push(i)}else if(string[i]===")"&&openParenthesisPositions.length>0){var openParenthesisPosition=openParenthesisPositions.pop();if(openParenthesisPositions.length===0){substrings.push(string.substring(openParenthesisPosition,i+1))}}}return substrings}module.exports={isAndroid:isAndroid,isIOS:isIOS,isMobile:isMobile,isNonChromiumEdge:isNonChromiumEdge,mobileWebKitBrowser:mobileWebKitBrowser,rebrandedChromeBrowser:rebrandedChromeBrowser}},{}],119:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var CancelablePromise=function(){function CancelablePromise(onCreate,onCancel){var _this=this;Object.defineProperties(this,{_isCancelable:{writable:true,value:true},_isCanceled:{writable:true,value:false},_onCancel:{value:onCancel}});Object.defineProperty(this,"_promise",{value:new Promise(function(resolve,reject){onCreate(function(value){_this._isCancelable=false;resolve(value)},function(reason){_this._isCancelable=false;reject(reason)},function(){return _this._isCanceled})})})}CancelablePromise.reject=function(reason){return new CancelablePromise(function rejected(resolve,reject){reject(reason)},function onCancel(){})};CancelablePromise.resolve=function(result){return new CancelablePromise(function resolved(resolve){resolve(result)},function onCancel(){})};CancelablePromise.prototype.cancel=function(){if(this._isCancelable){this._isCanceled=true;this._onCancel()}return this};CancelablePromise.prototype.catch=function(){var args=[].slice.call(arguments);var promise=this._promise;return new CancelablePromise(function onCreate(resolve,reject){promise.catch.apply(promise,__spreadArray([],__read(args))).then(resolve,reject)},this._onCancel)};CancelablePromise.prototype.then=function(){var args=[].slice.call(arguments);var promise=this._promise;return new CancelablePromise(function onCreate(resolve,reject){promise.then.apply(promise,__spreadArray([],__read(args))).then(resolve,reject)},this._onCancel)};CancelablePromise.prototype.finally=function(){var args=[].slice.call(arguments);var promise=this._promise;return new CancelablePromise(function onCreate(resolve,reject){promise.finally.apply(promise,__spreadArray([],__read(args))).then(resolve,reject)},this._onCancel)};return CancelablePromise}();module.exports=CancelablePromise},{}],120:[function(require,module,exports){"use strict";var packageInfo=require("../../package.json");module.exports.SDK_NAME=packageInfo.name+".js";module.exports.SDK_VERSION=packageInfo.version;module.exports.DEFAULT_ENVIRONMENT="prod";module.exports.DEFAULT_REALM="us1";module.exports.DEFAULT_REGION="gll";module.exports.DEFAULT_LOG_LEVEL="warn";module.exports.DEFAULT_LOGGER_NAME="twilio-video";module.exports.WS_SERVER=function(environment,region){region=region==="gll"?"global":encodeURIComponent(region);return environment==="prod"?"wss://"+region+".vss.twilio.com/signaling":"wss://"+region+".vss."+environment+".twilio.com/signaling"};module.exports.PUBLISH_MAX_ATTEMPTS=5;module.exports.PUBLISH_BACKOFF_JITTER=10;module.exports.PUBLISH_BACKOFF_MS=20;function article(word){return["a","e","i","o","u"].includes(word.toLowerCase()[0])?"an":"a"}module.exports.typeErrors={ILLEGAL_INVOKE:function(name,context){return new TypeError("Illegal call to "+name+": "+context)},INVALID_TYPE:function(name,type){return new TypeError(name+" must be "+article(type)+" "+type)},INVALID_VALUE:function(name,values){return new RangeError(name+" must be one of "+values.join(", "))},REQUIRED_ARGUMENT:function(name){return new TypeError(name+" must be specified")}};module.exports.DEFAULT_FRAME_RATE=24;module.exports.DEFAULT_VIDEO_PROCESSOR_STATS_INTERVAL_MS=1e4;module.exports.DEFAULT_ICE_GATHERING_TIMEOUT_MS=15e3;module.exports.DEFAULT_SESSION_TIMEOUT_SEC=30;module.exports.DEFAULT_NQ_LEVEL_LOCAL=1;module.exports.DEFAULT_NQ_LEVEL_REMOTE=0;module.exports.MAX_NQ_LEVEL=3;module.exports.ICE_ACTIVITY_CHECK_PERIOD_MS=1e3;module.exports.ICE_INACTIVITY_THRESHOLD_MS=3e3;module.exports.iceRestartBackoffConfig={factor:1.1,initialDelay:1,maxDelay:module.exports.DEFAULT_SESSION_TIMEOUT_SEC*1e3,randomisationFactor:.5};module.exports.reconnectBackoffConfig={factor:1.5,initialDelay:80,randomisationFactor:.5};module.exports.subscriptionMode={MODE_COLLABORATION:"collaboration",MODE_GRID:"grid",MODE_PRESENTATION:"presentation"};module.exports.trackSwitchOffMode={MODE_DISABLED:"disabled",MODE_DETECTED:"detected",MODE_PREDICTED:"predicted"};module.exports.trackPriority={PRIORITY_HIGH:"high",PRIORITY_LOW:"low",PRIORITY_STANDARD:"standard"};module.exports.clientTrackSwitchOffControl={MODE_AUTO:"auto",MODE_MANUAL:"manual"};module.exports.videoContentPreferencesMode={MODE_AUTO:"auto",MODE_MANUAL:"manual"}},{"../../package.json":200}],121:[function(require,module,exports){"use strict";var detectSilence=require("../webaudio/detectsilence");var N_ATTEMPTS=3;var ATTEMPT_DURATION_MS=250;function detectSilentAudio(el){var AudioContextFactory=require("../webaudio/audiocontext");var holder={};var audioContext=AudioContextFactory.getOrCreate(holder);var attemptsLeft=N_ATTEMPTS;function doCheckSilence(){attemptsLeft--;return detectSilence(audioContext,el.srcObject,ATTEMPT_DURATION_MS).then(function(isSilent){if(!isSilent){return false}if(attemptsLeft>0){return doCheckSilence()}return true}).catch(function(){return true})}return doCheckSilence().finally(function(){AudioContextFactory.release(holder)})}module.exports=detectSilentAudio},{"../webaudio/audiocontext":147,"../webaudio/detectsilence":148}],122:[function(require,module,exports){"use strict";var canvas=null;var N_SAMPLES=3;var SAMPLE_HEIGHT=50;var SAMPLE_INTERVAL_MS=250;var SAMPLE_WIDTH=50;function checkSilence(el){try{var context=canvas.getContext("2d");context.drawImage(el,0,0,SAMPLE_WIDTH,SAMPLE_HEIGHT);var frame=context.getImageData(0,0,SAMPLE_WIDTH,SAMPLE_HEIGHT);var frameDataWithoutAlpha=frame.data.filter(function(item,i){return(i+1)%4});var max=Math.max.apply(Math,frameDataWithoutAlpha);return max===0}catch(ex){console.log("Error checking silence: ",ex);return false}}function detectSilentVideo(el){canvas=canvas||document.createElement("canvas");return new Promise(function(resolve){var samplesLeft=N_SAMPLES;setTimeout(function doCheckSilence(){samplesLeft--;if(!checkSilence(el)){return resolve(false)}if(samplesLeft>0){return setTimeout(doCheckSilence,SAMPLE_INTERVAL_MS)}return resolve(true)},SAMPLE_INTERVAL_MS)})}module.exports=detectSilentVideo},{}],123:[function(require,module,exports){"use strict";var DocumentVisibilityMonitor=function(){function DocumentVisibilityMonitor(nPhases){var _this=this;if(nPhases===void 0){nPhases=1}Object.defineProperties(this,{_listeners:{value:[]},_onVisibilityChange:{value:function(){_this._emitVisible(document.visibilityState==="visible")}}});for(var i=0;i<nPhases;i++){this._listeners.push([])}}DocumentVisibilityMonitor.prototype.clear=function(){var nPhases=this._listeners.length;for(var i=0;i<nPhases;i++){this._listeners[i]=[]}};DocumentVisibilityMonitor.prototype._listenerCount=function(){return this._listeners.reduce(function(count,phaseListeners){return count+phaseListeners.length},0)};DocumentVisibilityMonitor.prototype._emitVisible=function(isVisible){var _this=this;var promise=Promise.resolve();var _loop_1=function(phase){promise=promise.then(function(){return _this._emitVisiblePhase(phase,isVisible)})};for(var phase=1;phase<=this._listeners.length;phase++){_loop_1(phase)}return promise};DocumentVisibilityMonitor.prototype._emitVisiblePhase=function(phase,isVisible){var phaseListeners=this._listeners[phase-1];return Promise.all(phaseListeners.map(function(listener){var ret=listener(isVisible);return ret instanceof Promise?ret:Promise.resolve(ret)}))};DocumentVisibilityMonitor.prototype._start=function(){document.addEventListener("visibilitychange",this._onVisibilityChange)};DocumentVisibilityMonitor.prototype._stop=function(){document.removeEventListener("visibilitychange",this._onVisibilityChange)};DocumentVisibilityMonitor.prototype.onVisibilityChange=function(phase,listener){if(typeof phase!=="number"||phase<=0||phase>this._listeners.length){throw new Error("invalid phase: ",phase)}var phaseListeners=this._listeners[phase-1];phaseListeners.push(listener);if(this._listenerCount()===1){this._start()}return this};DocumentVisibilityMonitor.prototype.offVisibilityChange=function(phase,listener){if(typeof phase!=="number"||phase<=0||phase>this._listeners.length){throw new Error("invalid phase: ",phase)}var phaseListeners=this._listeners[phase-1];var index=phaseListeners.indexOf(listener);if(index!==-1){phaseListeners.splice(index,1);if(this._listenerCount()===0){this._stop()}}return this};return DocumentVisibilityMonitor}();module.exports=new DocumentVisibilityMonitor(2)},{}],124:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var VALID_GROUPS=["signaling","room","media","quality","video-processor","preflight"];var VALID_LEVELS=["debug","error","info","warning"];var EventObserver=function(_super){__extends(EventObserver,_super);function EventObserver(publisher,connectTimestamp,log,eventListener){if(eventListener===void 0){eventListener=null}var _this=_super.call(this)||this;_this.on("event",function(_a){var name=_a.name,group=_a.group,level=_a.level,payload=_a.payload;if(typeof name!=="string"){log.error("Unexpected name: ",name);throw new Error("Unexpected name: ",name)}if(!VALID_GROUPS.includes(group)){log.error("Unexpected group: ",group);throw new Error("Unexpected group: ",group)}if(!VALID_LEVELS.includes(level)){log.error("Unexpected level: ",level);throw new Error("Unexpected level: ",level)}var timestamp=Date.now();var elapsedTime=timestamp-connectTimestamp;var publisherPayload=Object.assign({elapsedTime:elapsedTime,level:level},payload?payload:{});publisher.publish(group,name,publisherPayload);var event=Object.assign({elapsedTime:elapsedTime,group:group,level:level,name:name,timestamp:timestamp},payload?{payload:payload}:{});var logLevel={debug:"debug",error:"error",info:"info",warning:"warn"}[level];log[logLevel]("event",event);if(eventListener&&group==="signaling"){eventListener.emit("event",event)}});return _this}return EventObserver}(EventEmitter);module.exports=EventObserver},{events:179}],125:[function(require,module,exports){"use strict";var Filter=function(){function Filter(options){options=Object.assign({getKey:function defaultGetKey(a){return a},getValue:function defaultGetValue(a){return a},isLessThanOrEqualTo:function defaultIsLessThanOrEqualTo(a,b){return a<=b}},options);Object.defineProperties(this,{_getKey:{value:options.getKey},_getValue:{value:options.getValue},_isLessThanOrEqualTo:{value:options.isLessThanOrEqualTo},_map:{value:new Map}})}Filter.prototype.toMap=function(){return new Map(this._map)};Filter.prototype.updateAndFilter=function(entries){return entries.filter(this.update,this)};Filter.prototype.update=function(entry){var key=this._getKey(entry);var value=this._getValue(entry);if(this._map.has(key)&&this._isLessThanOrEqualTo(value,this._map.get(key))){return false}this._map.set(key,value);return true};return Filter}();module.exports=Filter},{}],126:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var constants=require("./constants");var E=constants.typeErrors,trackPriority=constants.trackPriority;var util=require("@twilio/webrtc/lib/util");var sessionSID=require("./sid").sessionSID;function asLocalTrack(track,options){if(track instanceof options.LocalAudioTrack||track instanceof options.LocalVideoTrack||track instanceof options.LocalDataTrack){return track}if(track instanceof options.MediaStreamTrack){return track.kind==="audio"?new options.LocalAudioTrack(track,options):new options.LocalVideoTrack(track,options)}throw E.INVALID_TYPE("track","LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}function asLocalTrackPublication(track,signaling,unpublish,options){var LocalTrackPublication={audio:options.LocalAudioTrackPublication,video:options.LocalVideoTrackPublication,data:options.LocalDataTrackPublication}[track.kind];return new LocalTrackPublication(signaling,track,unpublish,options)}function capitalize(word){return word[0].toUpperCase()+word.slice(1)}function deprecateEvents(name,emitter,events,log){var warningsShown=new Set;emitter.on("newListener",function newListener(event){if(events.has(event)&&!warningsShown.has(event)){log.deprecated(name+"#"+event+" has been deprecated and scheduled for removal in twilio-video.js@2.0.0."+(events.get(event)?" Use "+name+"#"+events.get(event)+" instead.":""));warningsShown.add(event)}if(warningsShown.size>=events.size){emitter.removeListener("newListener",newListener)}})}function difference(list1,list2){list1=Array.isArray(list1)?new Set(list1):new Set(list1.values());list2=Array.isArray(list2)?new Set(list2):new Set(list2.values());var difference=new Set;list1.forEach(function(item){if(!list2.has(item)){difference.add(item)}});return difference}function filterObject(object,filterValue){return Object.keys(object).reduce(function(filtered,key){if(object[key]!==filterValue){filtered[key]=object[key]}return filtered},{})}function flatMap(list,mapFn){var listArray=list instanceof Map||list instanceof Set?Array.from(list.values()):list;mapFn=mapFn||function mapFn(item){return item};return listArray.reduce(function(flattened,item){var mapped=mapFn(item);return flattened.concat(mapped)},[])}function getUserAgent(){return typeof navigator!=="undefined"&&navigator.userAgent?navigator.userAgent:"Unknown"}function getPlatform(){var userAgent=getUserAgent();var _a=__read(userAgent.match(/\(([^)]+)\)/)||[],2),_b=_a[1],match=_b===void 0?"unknown":_b;var _c=__read(match.split(";").map(function(entry){return entry.trim()}),1),platform=_c[0];return platform.toLowerCase()}function makeUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;var v=c==="x"?r:r&3|8;return v.toString(16)})}function oncePerTick(fn){var timeout=null;function nextTick(){timeout=null;fn()}return function scheduleNextTick(){if(timeout){clearTimeout(timeout)}timeout=setTimeout(nextTick)}}function promiseFromEvents(operation,eventEmitter,successEvent,failureEvent){return new Promise(function(resolve,reject){function onSuccess(){var args=[].slice.call(arguments);if(failureEvent){eventEmitter.removeListener(failureEvent,onFailure)}resolve.apply(void 0,__spreadArray([],__read(args)))}function onFailure(){var args=[].slice.call(arguments);eventEmitter.removeListener(successEvent,onSuccess);reject.apply(void 0,__spreadArray([],__read(args)))}eventEmitter.once(successEvent,onSuccess);if(failureEvent){eventEmitter.once(failureEvent,onFailure)}operation()})}function getOrNull(obj,path){return path.split(".").reduce(function(output,step){if(!output){return null}return output[step]},obj)}function defer(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject});return deferred}function delegateMethod(source,wrapper,target,methodName){if(methodName in wrapper){return}else if(methodName.match(/^on[a-z]+$/)){return}var type;try{type=typeof source[methodName]}catch(error){}if(type!=="function"){return}wrapper[methodName]=function(){var _a;var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return(_a=this[target])[methodName].apply(_a,__spreadArray([],__read(args)))}}function delegateMethods(source,wrapper,target){for(var methodName in source){delegateMethod(source,wrapper,target,methodName)}}function isDeepEqual(val1,val2){if(val1===val2){return true}if(typeof val1!==typeof val2){return false}if(val1===null){return val2===null}if(val2===null){return false}if(Array.isArray(val1)){return Array.isArray(val2)&&val1.length===val2.length&&val1.every(function(val,i){return isDeepEqual(val,val2[i])})}if(typeof val1==="object"){var val1Keys=Object.keys(val1).sort();var val2Keys=Object.keys(val2).sort();return!Array.isArray(val2)&&isDeepEqual(val1Keys,val2Keys)&&val1Keys.every(function(key){return isDeepEqual(val1[key],val2[key])})}return false}function isNonArrayObject(object){return typeof object==="object"&&!Array.isArray(object)}function proxyProperties(source,wrapper,target){Object.getOwnPropertyNames(source).forEach(function(propertyName){proxyProperty(source,wrapper,target,propertyName)})}function proxyProperty(source,wrapper,target,propertyName){if(propertyName in wrapper){return}else if(propertyName.match(/^on[a-z]+$/)){Object.defineProperty(wrapper,propertyName,{value:null,writable:true});target.addEventListener(propertyName.slice(2),function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}wrapper.dispatchEvent.apply(wrapper,__spreadArray([],__read(args)))});return}Object.defineProperty(wrapper,propertyName,{enumerable:true,get:function(){return target[propertyName]}})}function legacyPromise(promise,onSuccess,onFailure){if(onSuccess){return promise.then(function(result){onSuccess(result)},function(error){onFailure(error)})}return promise}function buildLogLevels(logLevel){if(typeof logLevel==="string"){return{default:logLevel,media:logLevel,signaling:logLevel,webrtc:logLevel}}return logLevel}function trackClass(track,local){local=local?"Local":"";return local+(track.kind||"").replace(/\w{1}/,function(m){return m.toUpperCase()})+"Track"}function trackPublicationClass(publication,local){local=local?"Local":"";return local+(publication.kind||"").replace(/\w{1}/,function(m){return m.toUpperCase()})+"TrackPublication"}function hidePrivateProperties(object){Object.getOwnPropertyNames(object).forEach(function(name){if(name.startsWith("_")){hideProperty(object,name)}})}function hidePrivateAndCertainPublicPropertiesInClass(klass,props){return function(_super){__extends(class_1,_super);function class_1(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}var _this=_super.apply(this,__spreadArray([],__read(args)))||this;hidePrivateProperties(_this);hidePublicProperties(_this,props);return _this}return class_1}(klass)}function hideProperty(object,name){var descriptor=Object.getOwnPropertyDescriptor(object,name);descriptor.enumerable=false;Object.defineProperty(object,name,descriptor)}function hidePublicProperties(object,props){if(props===void 0){props=[]}props.forEach(function(name){if(object.hasOwnProperty(name)){hideProperty(object,name)}})}function arrayToJSON(array){return array.map(valueToJSON)}function setToJSON(set){return arrayToJSON(__spreadArray([],__read(set)))}function mapToJSON(map){return __spreadArray([],__read(map.entries())).reduce(function(json,_a){var _b;var _c=__read(_a,2),key=_c[0],value=_c[1];return Object.assign((_b={},_b[key]=valueToJSON(value),_b),json)},{})}function objectToJSON(object){return Object.entries(object).reduce(function(json,_a){var _b;var _c=__read(_a,2),key=_c[0],value=_c[1];return Object.assign((_b={},_b[key]=valueToJSON(value),_b),json)},{})}function valueToJSON(value){if(Array.isArray(value)){return arrayToJSON(value)}else if(value instanceof Set){return setToJSON(value)}else if(value instanceof Map){return mapToJSON(value)}else if(value&&typeof value==="object"){return objectToJSON(value)}return value}function createRoomConnectEventPayload(connectOptions){function boolToString(val){return val?"true":"false"}var payload={sessionSID:sessionSID,iceServers:(connectOptions.iceServers||[]).length,audioTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="audio"}).length,videoTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="video"}).length,dataTracks:(connectOptions.tracks||[]).filter(function(track){return track.kind==="data"}).length};[["audio"],["automaticSubscription"],["enableDscp"],["eventListener"],["preflight"],["video"],["dominantSpeaker","enableDominantSpeaker"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;payload[eventProp]=boolToString(!!connectOptions[prop])});[["maxVideoBitrate"],["maxAudioBitrate"],["iceTransportPolicy"],["region"],["name","roomName"]].forEach(function(_a){var _b=__read(_a,2),prop=_b[0],eventProp=_b[1];eventProp=eventProp||prop;if(typeof connectOptions[prop]==="number"||typeof connectOptions[prop]==="string"){payload[eventProp]=connectOptions[prop]}});["preferredAudioCodecs","preferredVideoCodecs"].forEach(function(prop){if(prop in connectOptions){payload[prop]=JSON.stringify(connectOptions[prop])}});if("networkQuality"in connectOptions){payload.networkQualityConfiguration={};if(isNonArrayObject(connectOptions.networkQuality)){["local","remote"].forEach(function(prop){if(typeof connectOptions.networkQuality[prop]==="number"){payload.networkQualityConfiguration[prop]=connectOptions.networkQuality[prop]}})}else{payload.networkQualityConfiguration.remote=0;payload.networkQualityConfiguration.local=connectOptions.networkQuality?1:0}}
51
+ if(connectOptions.bandwidthProfile&&connectOptions.bandwidthProfile.video){var videoBPOptions_1=connectOptions.bandwidthProfile.video||{};payload.bandwidthProfileOptions={};["mode","maxTracks","trackSwitchOffMode","dominantSpeakerPriority","maxSubscriptionBitrate","renderDimensions","contentPreferencesMode","clientTrackSwitchOffControl"].forEach(function(prop){if(typeof videoBPOptions_1[prop]==="number"||typeof videoBPOptions_1[prop]==="string"){payload.bandwidthProfileOptions[prop]=videoBPOptions_1[prop]}else if(typeof videoBPOptions_1[prop]==="boolean"){payload.bandwidthProfileOptions[prop]=boolToString(videoBPOptions_1[prop])}else if(typeof videoBPOptions_1[prop]==="object"){payload.bandwidthProfileOptions[prop]=JSON.stringify(videoBPOptions_1[prop])}})}return{group:"room",name:"connect",level:"info",payload:payload}}function createBandwidthProfilePayload(bandwidthProfile){return createRSPPayload(bandwidthProfile,[{prop:"video",type:"object",transform:createBandwidthProfileVideoPayload}])}function createBandwidthProfileVideoPayload(bandwidthProfileVideo){return createRSPPayload(bandwidthProfileVideo,[{prop:"dominantSpeakerPriority",type:"string",payloadProp:"active_speaker_priority"},{prop:"maxSubscriptionBitrate",type:"number",payloadProp:"max_subscription_bandwidth"},{prop:"maxTracks",type:"number",payloadProp:"max_tracks"},{prop:"mode",type:"string"},{prop:"renderDimensions",type:"object",payloadProp:"render_dimensions",transform:createRenderDimensionsPayload},{prop:"trackSwitchOffMode",type:"string",payloadProp:"track_switch_off"}])}function createMediaSignalingPayload(dominantSpeaker,networkQuality,trackPriority,trackSwitchOff,renderHints){var transports={transports:[{type:"data-channel"}]};return Object.assign(dominantSpeaker?{active_speaker:transports}:{},networkQuality?{network_quality:transports}:{},renderHints?{render_hints:transports}:{},trackPriority?{track_priority:transports}:{},trackSwitchOff?{track_switch_off:transports}:{})}function createDimensionsPayload(dimensions){return createRSPPayload(dimensions,[{prop:"height",type:"number"},{prop:"width",type:"number"}])}function createRenderDimensionsPayload(renderDimensions){var PRIORITY_HIGH=trackPriority.PRIORITY_HIGH,PRIORITY_LOW=trackPriority.PRIORITY_LOW,PRIORITY_STANDARD=trackPriority.PRIORITY_STANDARD;return createRSPPayload(renderDimensions,[{prop:PRIORITY_HIGH,type:"object",transform:createDimensionsPayload},{prop:PRIORITY_LOW,type:"object",transform:createDimensionsPayload},{prop:PRIORITY_STANDARD,type:"object",transform:createDimensionsPayload}])}function createRSPPayload(object,propConversions){return propConversions.reduce(function(payload,_a){var _b;var prop=_a.prop,type=_a.type,_c=_a.payloadProp,payloadProp=_c===void 0?prop:_c,_d=_a.transform,transform=_d===void 0?function(x){return x}:_d;return typeof object[prop]===type?Object.assign((_b={},_b[payloadProp]=transform(object[prop]),_b),payload):payload},{})}function createSubscribePayload(automaticSubscription){return{rules:[{type:automaticSubscription?"include":"exclude",all:true}],revision:1}}function withJitter(value,jitter){var rand=Math.random();return value-jitter+Math.floor(2*jitter*rand+.5)}function inRange(num,min,max){return min<=num&&num<=max}function isChromeScreenShareTrack(track){var isChrome=util.guessBrowser()==="chrome";return isChrome&&track.kind==="video"&&track.label&&(/^screen:[0-9]+/.test(track.label)||/^web-contents-media-stream:[0-9/]+/.test(track.label)||/^window:[0-9]+/.test(track.label))}function isUserMediaTrack(track){return typeof track.getSettings().deviceId==="string"}function waitForSometime(timeoutMS){if(timeoutMS===void 0){timeoutMS=10}return new Promise(function(resolve){return setTimeout(resolve,timeoutMS)})}function waitForEvent(eventTarget,event){return new Promise(function(resolve){eventTarget.addEventListener(event,function onevent(e){eventTarget.removeEventListener(event,onevent);resolve(e)})})}exports.constants=constants;exports.createBandwidthProfilePayload=createBandwidthProfilePayload;exports.createMediaSignalingPayload=createMediaSignalingPayload;exports.createRoomConnectEventPayload=createRoomConnectEventPayload;exports.createSubscribePayload=createSubscribePayload;exports.asLocalTrack=asLocalTrack;exports.asLocalTrackPublication=asLocalTrackPublication;exports.capitalize=capitalize;exports.deprecateEvents=deprecateEvents;exports.difference=difference;exports.filterObject=filterObject;exports.flatMap=flatMap;exports.getPlatform=getPlatform;exports.getUserAgent=getUserAgent;exports.hidePrivateProperties=hidePrivateProperties;exports.hidePrivateAndCertainPublicPropertiesInClass=hidePrivateAndCertainPublicPropertiesInClass;exports.isDeepEqual=isDeepEqual;exports.isNonArrayObject=isNonArrayObject;exports.inRange=inRange;exports.makeUUID=makeUUID;exports.oncePerTick=oncePerTick;exports.promiseFromEvents=promiseFromEvents;exports.getOrNull=getOrNull;exports.defer=defer;exports.delegateMethods=delegateMethods;exports.proxyProperties=proxyProperties;exports.legacyPromise=legacyPromise;exports.buildLogLevels=buildLogLevels;exports.trackClass=trackClass;exports.trackPublicationClass=trackPublicationClass;exports.valueToJSON=valueToJSON;exports.withJitter=withJitter;exports.isChromeScreenShareTrack=isChromeScreenShareTrack;exports.isUserMediaTrack=isUserMediaTrack;exports.waitForSometime=waitForSometime;exports.waitForEvent=waitForEvent},{"./constants":120,"./sid":140,"@twilio/webrtc/lib/util":165}],127:[function(require,module,exports){(function(global){(function(){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var EventEmitter=require("events").EventEmitter;var getUserAgent=require("..").getUserAgent;var MAX_RECONNECT_ATTEMPTS=5;var RECONNECT_INTERVAL_MS=50;var WS_CLOSE_NORMAL=1e3;var toplevel=global.window||global;var WebSocket=toplevel.WebSocket?toplevel.WebSocket:require("ws");var util=require("../../util");var InsightsPublisher=function(_super){__extends(InsightsPublisher,_super);function InsightsPublisher(token,sdkName,sdkVersion,environment,realm,options){var _this=_super.call(this)||this;options=Object.assign({gateway:createGateway(environment,realm)+"/v1/VideoEvents",maxReconnectAttempts:MAX_RECONNECT_ATTEMPTS,reconnectIntervalMs:RECONNECT_INTERVAL_MS,userAgent:getUserAgent(),WebSocket:WebSocket},options);Object.defineProperties(_this,{_connectTimestamp:{value:0,writable:true},_eventQueue:{value:[]},_readyToConnect:{value:util.defer()},_reconnectAttemptsLeft:{value:options.maxReconnectAttempts,writable:true},_ws:{value:null,writable:true},_WebSocket:{value:options.WebSocket}});_this._readyToConnect.promise.then(function(_a){var roomSid=_a.roomSid,participantSid=_a.participantSid;var self=_this;_this.on("disconnected",function maybeReconnect(error){self._session=null;if(error&&self._reconnectAttemptsLeft>0){self.emit("reconnecting");reconnect(self,token,sdkName,sdkVersion,roomSid,participantSid,options);return}self.removeListener("disconnected",maybeReconnect)});connect(_this,token,sdkName,sdkVersion,roomSid,participantSid,options)}).catch(function(){});return _this}InsightsPublisher.prototype.connect=function(roomSid,participantSid){this._readyToConnect.resolve({roomSid:roomSid,participantSid:participantSid})};InsightsPublisher.prototype._publish=function(event){event.session=this._session;this._ws.send(JSON.stringify(event))};InsightsPublisher.prototype.disconnect=function(){if(this._ws===null||this._ws.readyState===this._WebSocket.CLOSING||this._ws.readyState===this._WebSocket.CLOSED){return false}try{this._ws.close()}catch(error){}this.emit("disconnected");return true};InsightsPublisher.prototype.publish=function(groupName,eventName,payload){if(this._ws!==null&&(this._ws.readyState===this._WebSocket.CLOSING||this._ws.readyState===this._WebSocket.CLOSED)){return false}var publishOrEnqueue=typeof this._session==="string"?this._publish.bind(this):this._eventQueue.push.bind(this._eventQueue);publishOrEnqueue({group:groupName,name:eventName,payload:payload,timestamp:Date.now(),type:"event",version:1});return true};return InsightsPublisher}(EventEmitter);function connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options){publisher._connectTimestamp=Date.now();publisher._reconnectAttemptsLeft--;publisher._ws=new options.WebSocket(options.gateway);var ws=publisher._ws;ws.addEventListener("close",function(event){if(event.code===WS_CLOSE_NORMAL){publisher.emit("disconnected");return}publisher.emit("disconnected",new Error("WebSocket Error "+event.code+": "+event.reason))});ws.addEventListener("message",function(message){handleConnectResponse(publisher,JSON.parse(message.data),options)});ws.addEventListener("open",function(){var connectRequest={type:"connect",token:token,version:1};connectRequest.publisher={name:sdkName,sdkVersion:sdkVersion,userAgent:options.userAgent,participantSid:participantSid,roomSid:roomSid};ws.send(JSON.stringify(connectRequest))})}function createGateway(environment,realm){return environment==="prod"?"wss://sdkgw."+realm+".twilio.com":"wss://sdkgw."+environment+"-"+realm+".twilio.com"}function handleConnectResponse(publisher,response,options){switch(response.type){case"connected":publisher._session=response.session;publisher._reconnectAttemptsLeft=options.maxReconnectAttempts;publisher._eventQueue.splice(0).forEach(publisher._publish,publisher);publisher.emit("connected");break;case"error":publisher._ws.close();publisher.emit("disconnected",new Error(response.message));break}}function reconnect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options){var connectInterval=Date.now()-publisher._connectTimestamp;var timeToWait=options.reconnectIntervalMs-connectInterval;if(timeToWait>0){setTimeout(function(){connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options)},timeToWait);return}connect(publisher,token,sdkName,sdkVersion,roomSid,participantSid,options)}module.exports=InsightsPublisher}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"..":126,"../../util":126,events:179,ws:201}],128:[function(require,module,exports){"use strict";var InsightsPublisher=function(){function InsightsPublisher(){Object.defineProperties(this,{_connected:{writable:true,value:true}})}InsightsPublisher.prototype.connect=function(){};InsightsPublisher.prototype.disconnect=function(){if(this._connected){this._connected=false;return true}return false};InsightsPublisher.prototype.publish=function(){return this._connected};return InsightsPublisher}();module.exports=InsightsPublisher},{}],129:[function(require,module,exports){"use strict";var defer=require("./").defer;var LocalMediaRestartDeferreds=function(){function LocalMediaRestartDeferreds(){Object.defineProperties(this,{_audio:{value:defer(),writable:true},_video:{value:defer(),writable:true}});this._audio.resolve();this._video.resolve()}LocalMediaRestartDeferreds.prototype.resolveDeferred=function(kind){if(kind==="audio"){this._audio.resolve()}else{this._video.resolve()}};LocalMediaRestartDeferreds.prototype.startDeferred=function(kind){if(kind==="audio"){this._audio=defer()}else{this._video=defer()}};LocalMediaRestartDeferreds.prototype.whenResolved=function(kind){return kind==="audio"?this._audio.promise:this._video.promise};return LocalMediaRestartDeferreds}();module.exports=new LocalMediaRestartDeferreds},{"./":126}],130:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var defaultGetLogger=require("../vendor/loglevel").getLogger;var constants=require("./constants");var DEFAULT_LOG_LEVEL=constants.DEFAULT_LOG_LEVEL,DEFAULT_LOGGER_NAME=constants.DEFAULT_LOGGER_NAME;var E=require("./constants").typeErrors;var deprecationWarningsByComponentConstructor;function getDeprecationWarnings(componentConstructor){deprecationWarningsByComponentConstructor=deprecationWarningsByComponentConstructor||new Map;if(deprecationWarningsByComponentConstructor.has(componentConstructor)){return deprecationWarningsByComponentConstructor.get(componentConstructor)}var deprecationWarnings=new Set;deprecationWarningsByComponentConstructor.set(componentConstructor,deprecationWarnings);return deprecationWarnings}var Log=function(){function Log(moduleName,component,logLevels,loggerName,getLogger){if(typeof moduleName!=="string"){throw E.INVALID_TYPE("moduleName","string")}if(!component){throw E.REQUIRED_ARGUMENT("component")}if(typeof logLevels!=="object"){logLevels={}}getLogger=getLogger||defaultGetLogger;validateLogLevels(logLevels);Object.defineProperties(this,{_component:{value:component},_logLevels:{value:logLevels},_warnings:{value:new Set},_loggerName:{get:function get(){var name=loggerName&&typeof loggerName==="string"?loggerName:DEFAULT_LOGGER_NAME;if(!this._logLevelsEqual){name=name+"-"+moduleName}return name}},_logger:{get:function get(){var logger=getLogger(this._loggerName);var level=this._logLevels[moduleName]||DEFAULT_LOG_LEVEL;level=level==="off"?"silent":level;logger.setDefaultLevel(level);return logger}},_logLevelsEqual:{get:function get(){return new Set(Object.values(this._logLevels)).size===1}},logLevel:{get:function get(){return Log.getLevelByName(logLevels[moduleName]||DEFAULT_LOG_LEVEL)}},name:{get:component.toString.bind(component)}})}Log.getLevelByName=function(name){if(!isNaN(name)){return parseInt(name,10)}name=name.toUpperCase();validateLogLevel(name);return Log[name]};Log.prototype.createLog=function(moduleName,component){var name=this._loggerName;if(!this._logLevelsEqual){name=name.substring(0,name.lastIndexOf("-"))}return new Log(moduleName,component,this._logLevels,name)};Log.prototype.setLevels=function(levels){validateLogLevels(levels);Object.assign(this._logLevels,levels);return this};Log.prototype.log=function(logLevel,messages){var name=Log._levels[logLevel];if(!name){throw E.INVALID_VALUE("logLevel",LOG_LEVEL_VALUES)}name=name.toLowerCase();var prefix=[(new Date).toISOString(),name,this.name];(this._logger[name]||function noop(){}).apply(void 0,__spreadArray([],__read(prefix.concat(messages))));return this};Log.prototype.debug=function(){return this.log(Log.DEBUG,[].slice.call(arguments))};Log.prototype.deprecated=function(deprecationWarning){var deprecationWarnings=getDeprecationWarnings(this._component.constructor);if(deprecationWarnings.has(deprecationWarning)){return this}deprecationWarnings.add(deprecationWarning);return this.warn(deprecationWarning)};Log.prototype.info=function(){return this.log(Log.INFO,[].slice.call(arguments))};Log.prototype.warn=function(){return this.log(Log.WARN,[].slice.call(arguments))};Log.prototype.warnOnce=function(warning){if(this._warnings.has(warning)){return this}this._warnings.add(warning);return this.warn(warning)};Log.prototype.error=function(){return this.log(Log.ERROR,[].slice.call(arguments))};Log.prototype.throw=function(error,customMessage){if(error.clone){error=error.clone(customMessage)}this.log(Log.ERROR,error);throw error};return Log}();Object.defineProperties(Log,{DEBUG:{value:0},INFO:{value:1},WARN:{value:2},ERROR:{value:3},OFF:{value:4},_levels:{value:["DEBUG","INFO","WARN","ERROR","OFF"]}});var LOG_LEVELS_SET={};var LOG_LEVEL_VALUES=[];var LOG_LEVEL_NAMES=Log._levels.map(function(level,i){LOG_LEVELS_SET[level]=true;LOG_LEVEL_VALUES.push(i);return level});function validateLogLevel(level){if(!(level in LOG_LEVELS_SET)){throw E.INVALID_VALUE("level",LOG_LEVEL_NAMES)}}function validateLogLevels(levels){Object.keys(levels).forEach(function(moduleName){validateLogLevel(levels[moduleName].toUpperCase())})}module.exports=Log},{"../vendor/loglevel":146,"./constants":120}],131:[function(require,module,exports){"use strict";var MovingAverageDelta=function(){function MovingAverageDelta(){Object.defineProperties(this,{_samples:{value:[{denominator:0,numerator:0},{denominator:0,numerator:0}]}})}MovingAverageDelta.prototype.get=function(){var samples=this._samples;var denominatorDelta=samples[1].denominator-samples[0].denominator||Infinity;var numeratorDelta=samples[1].numerator-samples[0].numerator;return numeratorDelta/denominatorDelta};MovingAverageDelta.prototype.putSample=function(numerator,denominator){var samples=this._samples;samples.shift();samples.push({denominator:denominator,numerator:numerator})};return MovingAverageDelta}();module.exports=MovingAverageDelta},{}],132:[function(require,module,exports){"use strict";var NetworkMonitor=function(){function NetworkMonitor(onNetworkChanged,options){var _this=this;options=Object.assign({navigator:navigator,window:window},options);var nav=options.navigator;var connection=nav.connection||{type:null};var type=connection.type;var _a=connection.type?{_events:{value:["change","typechange"]},_listener:{value:function(){var networkChanged=type!==_this.type&&_this.isOnline;type=_this.type;if(networkChanged){onNetworkChanged()}}},_target:{value:connection}}:{_events:{value:["online"]},_listener:{value:onNetworkChanged},_target:{value:options.window}},_events=_a._events,_listener=_a._listener,_target=_a._target;Object.defineProperties(this,{isOnline:{enumerable:true,get:function(){return typeof nav.onLine==="boolean"?nav.onLine:true}},type:{enumerable:true,get:function(){return connection.type||null}},_listener:_listener,_events:_events,_target:_target})}NetworkMonitor.prototype.start=function(){var _this=this;this._events.forEach(function(event){_this._target.addEventListener(event,_this._listener)})};NetworkMonitor.prototype.stop=function(){var _this=this;this._events.forEach(function(event){_this._target.removeEventListener(event,_this._listener)})};return NetworkMonitor}();module.exports=NetworkMonitor},{}],133:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var NullObserver=function(){function NullObserver(callback){Object.defineProperties(this,{_callback:{value:callback}})}NullObserver.prototype.observe=function(){};NullObserver.prototype.unobserve=function(){};NullObserver.prototype.makeVisible=function(videoEl){var visibleEntry=this._makeFakeEntry(videoEl,true);this._callback([visibleEntry])};NullObserver.prototype.makeInvisible=function(videoEl){var invisibleEntry=this._makeFakeEntry(videoEl,false);this._callback([invisibleEntry])};NullObserver.prototype._makeFakeEntry=function(videoElement,isIntersecting){return{target:videoElement,isIntersecting:isIntersecting}};return NullObserver}();var NullIntersectionObserver=function(_super){__extends(NullIntersectionObserver,_super);function NullIntersectionObserver(){return _super!==null&&_super.apply(this,arguments)||this}return NullIntersectionObserver}(NullObserver);var NullResizeObserver=function(_super){__extends(NullResizeObserver,_super);function NullResizeObserver(){return _super!==null&&_super.apply(this,arguments)||this}NullResizeObserver.prototype.resize=function(videoEl){var entry=this._makeFakeEntry(videoEl,true);this._callback([entry])};return NullResizeObserver}(NullObserver);module.exports={NullIntersectionObserver:NullIntersectionObserver,NullResizeObserver:NullResizeObserver,NullObserver:NullObserver}},{}],134:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var _a=require("../"),difference=_a.difference,flatMap=_a.flatMap;var setSimulcastInMediaSection=require("./simulcast");var ptToFixedBitrateAudioCodecName={0:"PCMU",8:"PCMA"};var RTCP_BITRATE=16e3;function createBLine(modifier,maxBitrate){if(!maxBitrate){return null}return"\r\nb="+modifier+":"+(modifier==="AS"?Math.round((maxBitrate+RTCP_BITRATE)/950):maxBitrate)}function createCodecMapForMediaSection(section){return Array.from(createPtToCodecName(section)).reduce(function(codecMap,pair){var pt=pair[0];var codecName=pair[1];var pts=codecMap.get(codecName)||[];return codecMap.set(codecName,pts.concat(pt))},new Map)}function createMidToMediaSectionMap(sdp){return getMediaSections(sdp).reduce(function(midsToMediaSections,mediaSection){var mid=getMidForMediaSection(mediaSection);return mid?midsToMediaSections.set(mid,mediaSection):midsToMediaSections},new Map)}function createPtToCodecName(mediaSection){return getPayloadTypesInMediaSection(mediaSection).reduce(function(ptToCodecName,pt){var rtpmapPattern=new RegExp("a=rtpmap:"+pt+" ([^/]+)");var matches=mediaSection.match(rtpmapPattern);var codecName=matches?matches[1].toLowerCase():ptToFixedBitrateAudioCodecName[pt]?ptToFixedBitrateAudioCodecName[pt].toLowerCase():"";return ptToCodecName.set(pt,codecName)},new Map)}function getFmtpAttributesForPt(pt,mediaSection){var fmtpRegex=new RegExp("^a=fmtp:"+pt+" (.+)$","m");var matches=mediaSection.match(fmtpRegex);return matches&&matches[1].split(";").reduce(function(attrs,nvPair){var _a=__read(nvPair.split("="),2),name=_a[0],value=_a[1];attrs[name]=isNaN(value)?value:parseInt(value,10);return attrs},{})}function getMidForMediaSection(mediaSection){var midMatches=mediaSection.match(/^a=mid:(.+)$/m);return midMatches&&midMatches[1]}function getMediaSections(sdp,kind,direction){return sdp.replace(/\r\n\r\n$/,"\r\n").split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+(kind||".*"),"gm");var directionPattern=new RegExp("a="+(direction||".*"),"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getPayloadTypesInMediaSection(section){var mLine=section.split("\r\n")[0];var matches=mLine.match(/([0-9]+)/g);if(!matches){return[]}return matches.slice(1).map(function(match){return parseInt(match,10)})}function getReorderedPayloadTypes(codecMap,preferredCodecs){preferredCodecs=preferredCodecs.map(function(_a){var codec=_a.codec;return codec.toLowerCase()});var preferredPayloadTypes=flatMap(preferredCodecs,function(codecName){return codecMap.get(codecName)||[]});var remainingCodecs=difference(Array.from(codecMap.keys()),preferredCodecs);var remainingPayloadTypes=flatMap(remainingCodecs,function(codecName){return codecMap.get(codecName)});return preferredPayloadTypes.concat(remainingPayloadTypes)}function setBitrateInMediaSection(modifier,maxBitrate,section){var bLine=createBLine(modifier,maxBitrate)||"";var bLinePattern=/\r\nb=(AS|TIAS):([0-9]+)/;var bLineMatched=section.match(bLinePattern);if(!bLineMatched){return section.replace(/(\r\n)?$/,bLine+"$1")}var maxBitrateMatched=parseInt(bLineMatched[2],10);maxBitrate=maxBitrate||Infinity;bLine=createBLine(modifier,Math.min(maxBitrateMatched,maxBitrate));return section.replace(bLinePattern,bLine)}function setBitrateParameters(sdp,modifier,maxAudioBitrate,maxVideoBitrate){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){if(!/^m=(audio|video)/.test(section)||!/a=(recvonly|sendrecv)/.test(section)){return section}var kind=section.match(/^m=(audio|video)/)[1];var maxBitrate=kind==="audio"?maxAudioBitrate:maxVideoBitrate;return setBitrateInMediaSection(modifier,maxBitrate,section)})).join("\r\n")}function setPayloadTypesInMediaSection(payloadTypes,section){var lines=section.split("\r\n");var mLine=lines[0];var otherLines=lines.slice(1);mLine=mLine.replace(/([0-9]+\s?)+$/,payloadTypes.join(" "));return[mLine].concat(otherLines).join("\r\n")}function setCodecPreferences(sdp,preferredAudioCodecs,preferredVideoCodecs){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){if(!/^m=(audio|video)/.test(section)){return section}var kind=section.match(/^m=(audio|video)/)[1];var codecMap=createCodecMapForMediaSection(section);var preferredCodecs=kind==="audio"?preferredAudioCodecs:preferredVideoCodecs;var payloadTypes=getReorderedPayloadTypes(codecMap,preferredCodecs);var newSection=setPayloadTypesInMediaSection(payloadTypes,section);var pcmaPayloadTypes=codecMap.get("pcma")||[];var pcmuPayloadTypes=codecMap.get("pcmu")||[];var fixedBitratePayloadTypes=kind==="audio"?new Set(pcmaPayloadTypes.concat(pcmuPayloadTypes)):new Set;return fixedBitratePayloadTypes.has(payloadTypes[0])?newSection.replace(/\r\nb=(AS|TIAS):([0-9]+)/g,""):newSection})).join("\r\n")}function setSimulcast(sdp,sdpFormat,trackIdsToAttributes){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){section=section.replace(/\r\n$/,"");if(!/^m=video/.test(section)){return section}var codecMap=createCodecMapForMediaSection(section);var payloadTypes=getPayloadTypesInMediaSection(section);var vp8PayloadTypes=new Set(codecMap.get("vp8")||[]);var hasVP8PayloadType=payloadTypes.some(function(payloadType){return vp8PayloadTypes.has(payloadType)});return hasVP8PayloadType?setSimulcastInMediaSection(section,sdpFormat,trackIdsToAttributes):section})).concat("").join("\r\n")}function unifiedPlanGetMatchingPayloadTypes(peerCodec,peerPt,codecsToPts,section,peerSection){var matchingPts=codecsToPts.get(peerCodec)||[];if(matchingPts.length<=1){return matchingPts}var peerFmtpAttrs=getFmtpAttributesForPt(peerPt,peerSection);if(!peerFmtpAttrs){return matchingPts}var matchingPt=matchingPts.find(function(pt){var fmtpAttrs=getFmtpAttributesForPt(pt,section);return fmtpAttrs&&Object.keys(peerFmtpAttrs).every(function(attr){return peerFmtpAttrs[attr]===fmtpAttrs[attr]})});return typeof matchingPt==="number"?[matchingPt]:matchingPts}function unifiedPlanFilterCodecsInMediaSection(section,peerMidsToMediaSections,codecsToRemove){if(!/^m=(audio|video)/.test(section)){return section}var mid=getMidForMediaSection(section);var peerSection=mid&&peerMidsToMediaSections.get(mid);if(!peerSection){return section}var peerPtToCodecs=createPtToCodecName(peerSection);var codecsToPts=createCodecMapForMediaSection(section);var pts=flatMap(Array.from(peerPtToCodecs),function(_a){var _b=__read(_a,2),peerPt=_b[0],peerCodec=_b[1];return peerCodec!=="rtx"&&!codecsToRemove.includes(peerCodec)?unifiedPlanGetMatchingPayloadTypes(peerCodec,peerPt,codecsToPts,section,peerSection):[]});var rtxPts=codecsToPts.get("rtx")||[];pts=pts.concat(rtxPts.filter(function(rtxPt){var fmtpAttrs=getFmtpAttributesForPt(rtxPt,section);return fmtpAttrs&&pts.includes(fmtpAttrs.apt)}));var lines=section.split("\r\n").filter(function(line){var ptMatches=line.match(/^a=(rtpmap|fmtp|rtcp-fb):(.+) .+$/);var pt=ptMatches&&ptMatches[2];return!ptMatches||pt&&pts.includes(parseInt(pt,10))});var orderedPts=getPayloadTypesInMediaSection(section).filter(function(pt){return pts.includes(pt)});return setPayloadTypesInMediaSection(orderedPts,lines.join("\r\n"))}function unifiedPlanFilterLocalCodecs(localSdp,remoteSdp){var localMediaSections=getMediaSections(localSdp);var localSession=localSdp.split("\r\nm=")[0];var remoteMidsToMediaSections=createMidToMediaSectionMap(remoteSdp);return[localSession].concat(localMediaSections.map(function(localSection){return unifiedPlanFilterCodecsInMediaSection(localSection,remoteMidsToMediaSections,[])})).join("\r\n")}function revertSimulcastForNonVP8MediaSections(localSdp,localSdpWithoutSimulcast,remoteSdp){var remoteMidToMediaSections=createMidToMediaSectionMap(remoteSdp);var localMidToMediaSectionsWithoutSimulcast=createMidToMediaSectionMap(localSdpWithoutSimulcast);var mediaSections=getMediaSections(localSdp);var session=localSdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(section){section=section.replace(/\r\n$/,"");if(!/^m=video/.test(section)){return section}var midMatches=section.match(/^a=mid:(.+)$/m);var mid=midMatches&&midMatches[1];if(!mid){return section}var remoteSection=remoteMidToMediaSections.get(mid);var remotePtToCodecs=createPtToCodecName(remoteSection);var remotePayloadTypes=getPayloadTypesInMediaSection(remoteSection);var isVP8ThePreferredCodec=remotePayloadTypes.length&&remotePtToCodecs.get(remotePayloadTypes[0])==="vp8";return isVP8ThePreferredCodec?section:localMidToMediaSectionsWithoutSimulcast.get(mid).replace(/\r\n$/,"")})).concat("").join("\r\n")}function unifiedPlanAddOrRewriteNewTrackIds(sdp,activeMidsToTrackIds,trackIdsByKind){var newMidsToTrackIds=Array.from(trackIdsByKind).reduce(function(midsToTrackIds,_a){var _b=__read(_a,2),kind=_b[0],trackIds=_b[1];var mediaSections=getMediaSections(sdp,kind,"send(only|recv)");var newMids=mediaSections.map(getMidForMediaSection).filter(function(mid){return!activeMidsToTrackIds.has(mid)});newMids.forEach(function(mid,i){return midsToTrackIds.set(mid,trackIds[i])});return midsToTrackIds},new Map);return unifiedPlanAddOrRewriteTrackIds(sdp,newMidsToTrackIds)}function unifiedPlanAddOrRewriteTrackIds(sdp,midsToTrackIds){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(mediaSection){if(!/^m=(audio|video)/.test(mediaSection)){return mediaSection}var mid=getMidForMediaSection(mediaSection);if(!mid){return mediaSection}var trackId=midsToTrackIds.get(mid);if(!trackId){return mediaSection}var attributes=(mediaSection.match(/^a=msid:(.+)$/m)||[])[1];if(!attributes){return mediaSection}var _a=__read(attributes.split(" "),2),msid=_a[0],trackIdToRewrite=_a[1];var msidRegex=new RegExp("msid:"+msid+(trackIdToRewrite?" "+trackIdToRewrite:"")+"$","gm");return mediaSection.replace(msidRegex,"msid:"+msid+" "+trackId)})).join("\r\n")}function removeSSRCAttributes(sdp,ssrcAttributesToRemove){return sdp.split("\r\n").filter(function(line){return!ssrcAttributesToRemove.find(function(srcAttribute){return new RegExp("a=ssrc:.*"+srcAttribute+":","g").test(line)})}).join("\r\n")}function disableRtx(sdp){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(function(mediaSection){if(!/^m=video/.test(mediaSection)){return mediaSection}var codecsToPts=createCodecMapForMediaSection(mediaSection);var rtxPts=codecsToPts.get("rtx");if(!rtxPts){return mediaSection}var pts=new Set(getPayloadTypesInMediaSection(mediaSection));rtxPts.forEach(function(rtxPt){return pts.delete(rtxPt)});var rtxSSRCMatches=mediaSection.match(/a=ssrc-group:FID [0-9]+ ([0-9]+)/);var rtxSSRC=rtxSSRCMatches&&rtxSSRCMatches[1];var filterRegexes=[/^a=fmtp:.+ apt=.+$/,/^a=rtpmap:.+ rtx\/.+$/,/^a=ssrc-group:.+$/].concat(rtxSSRC?[new RegExp("^a=ssrc:"+rtxSSRC+" .+$")]:[]);mediaSection=mediaSection.split("\r\n").filter(function(line){
52
+ return filterRegexes.every(function(regex){return!regex.test(line)})}).join("\r\n");return setPayloadTypesInMediaSection(Array.from(pts),mediaSection)})).join("\r\n")}function generateFmtpLineFromPtAndAttributes(pt,fmtpAttrs){var serializedFmtpAttrs=Object.entries(fmtpAttrs).map(function(_a){var _b=__read(_a,2),name=_b[0],value=_b[1];return name+"="+value}).join(";");return"a=fmtp:"+pt+" "+serializedFmtpAttrs}function enableDtxForOpus(sdp,mids){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];mids=mids||mediaSections.filter(function(section){return/^m=audio/.test(section)}).map(getMidForMediaSection);return[session].concat(mediaSections.map(function(section){if(!/^m=audio/.test(section)){return section}var codecsToPts=createCodecMapForMediaSection(section);var opusPt=codecsToPts.get("opus");if(!opusPt){return section}var opusFmtpAttrs=getFmtpAttributesForPt(opusPt,section);if(!opusFmtpAttrs){return section}var origOpusFmtpLine=generateFmtpLineFromPtAndAttributes(opusPt,opusFmtpAttrs);var origOpusFmtpRegex=new RegExp(origOpusFmtpLine);var mid=getMidForMediaSection(section);if(mids.includes(mid)){opusFmtpAttrs.usedtx=1}else{delete opusFmtpAttrs.usedtx}var opusFmtpLineWithDtx=generateFmtpLineFromPtAndAttributes(opusPt,opusFmtpAttrs);return section.replace(origOpusFmtpRegex,opusFmtpLineWithDtx)})).join("\r\n")}exports.createCodecMapForMediaSection=createCodecMapForMediaSection;exports.createPtToCodecName=createPtToCodecName;exports.disableRtx=disableRtx;exports.enableDtxForOpus=enableDtxForOpus;exports.getMediaSections=getMediaSections;exports.removeSSRCAttributes=removeSSRCAttributes;exports.revertSimulcastForNonVP8MediaSections=revertSimulcastForNonVP8MediaSections;exports.setBitrateParameters=setBitrateParameters;exports.setCodecPreferences=setCodecPreferences;exports.setSimulcast=setSimulcast;exports.unifiedPlanFilterLocalCodecs=unifiedPlanFilterLocalCodecs;exports.unifiedPlanAddOrRewriteNewTrackIds=unifiedPlanAddOrRewriteNewTrackIds;exports.unifiedPlanAddOrRewriteTrackIds=unifiedPlanAddOrRewriteTrackIds},{"../":126,"./simulcast":136}],135:[function(require,module,exports){"use strict";var RTCSessionDescription=require("@twilio/webrtc").RTCSessionDescription;var createPtToCodecName=require("./").createPtToCodecName;var getMediaSections=require("./").getMediaSections;function workaround(description){var descriptionInit={type:description.type};if(description.type!=="rollback"){descriptionInit.sdp=sdpWorkaround(description.sdp)}return new RTCSessionDescription(descriptionInit)}function sdpWorkaround(sdp){var mediaSections=getMediaSections(sdp);var session=sdp.split("\r\nm=")[0];return[session].concat(mediaSections.map(mediaSectionWorkaround)).join("\r\n")}function mediaSectionWorkaround(mediaSection){var ptToCodecName=createPtToCodecName(mediaSection);mediaSection=deleteDuplicateRtxPts(mediaSection,ptToCodecName);var codecNameToPts=createCodecNameToPts(ptToCodecName);var rtxPts=codecNameToPts.get("rtx")||new Set;var invalidRtxPts=new Set;var rtxPtToAssociatedPt=createRtxPtToAssociatedPt(mediaSection,ptToCodecName,rtxPts,invalidRtxPts);var associatedPtToRtxPt=createAssociatedPtToRtxPt(rtxPtToAssociatedPt,invalidRtxPts);var unassociatedRtxPts=Array.from(invalidRtxPts);var knownCodecNames=["h264","vp8","vp9"];var unassociatedPts=knownCodecNames.reduce(function(unassociatedPts,codecName){var pts=codecNameToPts.get(codecName)||new Set;return Array.from(pts).reduce(function(unassociatedPts,pt){return associatedPtToRtxPt.has(pt)?unassociatedPts:unassociatedPts.add(pt)},unassociatedPts)},new Set);unassociatedPts.forEach(function(pt){if(unassociatedRtxPts.length){var rtxPt=unassociatedRtxPts.shift();mediaSection=deleteFmtpAttributesForRtxPt(mediaSection,rtxPt);mediaSection=addFmtpAttributeForRtxPt(mediaSection,rtxPt,pt)}});unassociatedRtxPts.forEach(function(rtxPt){mediaSection=deleteFmtpAttributesForRtxPt(mediaSection,rtxPt);mediaSection=deleteRtpmapAttributesForRtxPt(mediaSection,rtxPt)});return mediaSection}function deleteDuplicateRtxPts(mediaSection,ptToCodecName){return Array.from(ptToCodecName.keys()).reduce(function(section,pt){var rtpmapRegex=new RegExp("^a=rtpmap:"+pt+" rtx.+$","gm");return(section.match(rtpmapRegex)||[]).slice(ptToCodecName.get(pt)==="rtx"?1:0).reduce(function(section,rtpmap){var rtpmapRegex=new RegExp("\r\n"+rtpmap);var fmtpmapRegex=new RegExp("\r\na=fmtp:"+pt+" apt=[0-9]+");return section.replace(rtpmapRegex,"").replace(fmtpmapRegex,"")},section)},mediaSection)}function createCodecNameToPts(ptToCodecName){var codecNameToPts=new Map;ptToCodecName.forEach(function(codecName,pt){var pts=codecNameToPts.get(codecName)||new Set;return codecNameToPts.set(codecName,pts.add(pt))});return codecNameToPts}function createRtxPtToAssociatedPt(mediaSection,ptToCodecName,rtxPts,invalidRtxPts){return Array.from(rtxPts).reduce(function(rtxPtToAssociatedPt,rtxPt){var fmtpPattern=new RegExp("a=fmtp:"+rtxPt+" apt=(\\d+)");var matches=mediaSection.match(fmtpPattern);if(!matches){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}var pt=Number.parseInt(matches[1]);if(!ptToCodecName.has(pt)){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}var codecName=ptToCodecName.get(pt);if(codecName==="rtx"){invalidRtxPts.add(rtxPt);return rtxPtToAssociatedPt}return rtxPtToAssociatedPt.set(rtxPt,pt)},new Map)}function createAssociatedPtToRtxPt(rtxPtToAssociatedPt,invalidRtxPts){var associatedPtToRtxPts=Array.from(rtxPtToAssociatedPt).reduce(function(associatedPtToRtxPts,pair){var rtxPt=pair[0];var pt=pair[1];var rtxPts=associatedPtToRtxPts.get(pt)||new Set;return associatedPtToRtxPts.set(pt,rtxPts.add(rtxPt))},new Map);return Array.from(associatedPtToRtxPts).reduce(function(associatedPtToRtxPt,pair){var pt=pair[0];var rtxPts=Array.from(pair[1]);if(rtxPts.length>1){rtxPts.forEach(function(rtxPt){invalidRtxPts.add(rtxPt)});return associatedPtToRtxPt}return associatedPtToRtxPt.set(pt,rtxPts[0])},new Map)}function deleteFmtpAttributesForRtxPt(mediaSection,rtxPt){var pattern=new RegExp("a=fmtp:"+rtxPt+".*\r\n","gm");return mediaSection.replace(pattern,"")}function deleteRtpmapAttributesForRtxPt(mediaSection,rtxPt){var pattern=new RegExp("a=rtpmap:"+rtxPt+".*\r\n","gm");return mediaSection.replace(pattern,"")}function addFmtpAttributeForRtxPt(mediaSection,rtxPt,pt){return mediaSection.endsWith("\r\n")?mediaSection+"a=fmtp:"+rtxPt+" apt="+pt+"\r\n":mediaSection+"\r\na=fmtp:"+rtxPt+" apt="+pt}module.exports=workaround},{"./":134,"@twilio/webrtc":152}],136:[function(require,module,exports){"use strict";var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var difference=require("../").difference;var flatMap=require("../").flatMap;function createSSRC(){var ssrcMax=4294967295;return String(Math.floor(Math.random()*ssrcMax))}var TrackAttributes=function(){function TrackAttributes(trackId,streamId,cName){Object.defineProperties(this,{cName:{enumerable:true,value:cName},isSimulcastEnabled:{enumerable:true,value:false,writable:true},primarySSRCs:{enumerable:true,value:new Set},rtxPairs:{enumerable:true,value:new Map},streamId:{enumerable:true,value:streamId},trackId:{enumerable:true,value:trackId}})}TrackAttributes.prototype.addSimulcastSSRCs=function(){if(this.isSimulcastEnabled){return}var simulcastSSRCs=[createSSRC(),createSSRC()];simulcastSSRCs.forEach(function(ssrc){this.primarySSRCs.add(ssrc)},this);if(this.rtxPairs.size){simulcastSSRCs.forEach(function(ssrc){this.rtxPairs.set(createSSRC(),ssrc)},this)}};TrackAttributes.prototype.addSSRC=function(ssrc,primarySSRC,isSimSSRC){if(primarySSRC){this.rtxPairs.set(ssrc,primarySSRC)}else{this.primarySSRCs.add(ssrc)}this.isSimulcastEnabled=this.isSimulcastEnabled||isSimSSRC};TrackAttributes.prototype.toSdpLines=function(excludeRtx){var _this=this;var rtxPairs=excludeRtx?[]:Array.from(this.rtxPairs.entries()).map(function(rtxPair){return rtxPair.reverse()});var simSSRCs=Array.from(this.primarySSRCs.values());var ssrcs=rtxPairs.length?flatMap(rtxPairs):simSSRCs;var attrLines=flatMap(ssrcs,function(ssrc){return["a=ssrc:"+ssrc+" cname:"+_this.cName,"a=ssrc:"+ssrc+" msid:"+_this.streamId+" "+_this.trackId]});var rtxPairLines=rtxPairs.map(function(rtxPair){return"a=ssrc-group:FID "+rtxPair.join(" ")});var simGroupLines=["a=ssrc-group:SIM "+simSSRCs.join(" ")];return rtxPairLines.concat(attrLines).concat(simGroupLines)};return TrackAttributes}();function getMatches(section,pattern){var matches=section.match(new RegExp(pattern,"gm"))||[];return matches.map(function(match){var matches=match.match(new RegExp(pattern))||[];return matches.slice(1)})}function getSimulcastSSRCs(section){var simGroupPattern="^a=ssrc-group:SIM ([0-9]+) ([0-9]+) ([0-9]+)$";return new Set(flatMap(getMatches(section,simGroupPattern)))}function getSSRCAttribute(section,ssrc,attribute){var pattern="a=ssrc:"+ssrc+" "+attribute+":(.+)";return section.match(new RegExp(pattern))[1]}function getSSRCRtxPairs(section){var rtxPairPattern="^a=ssrc-group:FID ([0-9]+) ([0-9]+)$";return new Map(getMatches(section,rtxPairPattern).map(function(pair){return pair.reverse()}))}function createSSRCAttributeTuples(section,sdpFormat){return{planb:createPlanBSSRCAttributeTuples,unified:createUnifiedPlanSSRCAttributeTuples}[sdpFormat](section)}function createPlanBSSRCAttributeTuples(section){return getMatches(section,"^a=ssrc:([0-9]+) msid:([^\\s]+) ([^\\s]+)$")}function createUnifiedPlanSSRCAttributeTuples(section){var _a=__read(flatMap(getMatches(section,"^a=msid:(.+) (.+)$")),2),streamId=_a[0],trackId=_a[1];var ssrcs=flatMap(getMatches(section,"^a=ssrc:(.+) cname:.+$"));return ssrcs.map(function(ssrc){return[ssrc,streamId,trackId]})}function createTrackIdsToAttributes(section,sdpFormat){var simSSRCs=getSimulcastSSRCs(section);var rtxPairs=getSSRCRtxPairs(section);var ssrcAttrTuples=createSSRCAttributeTuples(section,sdpFormat);return ssrcAttrTuples.reduce(function(trackIdsToSSRCs,tuple){var ssrc=tuple[0];var streamId=tuple[1];var trackId=tuple[2];var trackAttributes=trackIdsToSSRCs.get(trackId)||new TrackAttributes(trackId,streamId,getSSRCAttribute(section,ssrc,"cname"));var primarySSRC=rtxPairs.get(ssrc)||null;trackAttributes.addSSRC(ssrc,primarySSRC,simSSRCs.has(ssrc));return trackIdsToSSRCs.set(trackId,trackAttributes)},new Map)}function setSimulcastInMediaSection(section,sdpFormat,trackIdsToAttributes){var newTrackIdsToAttributes=createTrackIdsToAttributes(section,sdpFormat);var newTrackIds=Array.from(newTrackIdsToAttributes.keys());var trackIds=Array.from(trackIdsToAttributes.keys());var trackIdsToAdd=difference(newTrackIds,trackIds);var trackIdsToIgnore=difference(trackIds,newTrackIds);var trackAttributesToAdd=flatMap(trackIdsToAdd,function(trackId){return newTrackIdsToAttributes.get(trackId)});trackAttributesToAdd.forEach(function(trackAttributes){trackAttributes.addSimulcastSSRCs();trackIdsToAttributes.set(trackAttributes.trackId,trackAttributes)});trackIds=Array.from(trackIdsToAttributes.keys());var relevantTrackIds=difference(trackIds,trackIdsToIgnore);var relevantTrackAttributes=flatMap(relevantTrackIds,function(trackId){return trackIdsToAttributes.get(trackId)});var excludeRtx=!section.match(/a=rtpmap:[0-9]+ rtx/);var relevantSdpLines=flatMap(relevantTrackAttributes,function(trackAttributes){return trackAttributes.toSdpLines(excludeRtx)});var sectionLines=flatMap(new Set(section.split("\r\n").concat(relevantSdpLines)));var xGoogleFlagConference="a=x-google-flag:conference";if(!section.match(xGoogleFlagConference)){sectionLines.push(xGoogleFlagConference)}return sectionLines.join("\r\n")}module.exports=setSimulcastInMediaSection},{"../":126}],137:[function(require,module,exports){"use strict";var IdentityTrackMatcher=function(){function IdentityTrackMatcher(){}IdentityTrackMatcher.prototype.match=function(event){return event.track.id};IdentityTrackMatcher.prototype.update=function(){};return IdentityTrackMatcher}();module.exports=IdentityTrackMatcher},{}],138:[function(require,module,exports){"use strict";var getMediaSections=require("../").getMediaSections;var MIDTrackMatcher=function(){function MIDTrackMatcher(){Object.defineProperties(this,{_midsToTrackIds:{value:new Map,writable:true}})}MIDTrackMatcher.prototype.match=function(event){return this._midsToTrackIds.get(event.transceiver.mid)||null};MIDTrackMatcher.prototype.update=function(sdp){var sections=getMediaSections(sdp,"(audio|video)");this._midsToTrackIds=sections.reduce(function(midsToTrackIds,section){var midMatches=section.match(/^a=mid:(.+)$/m)||[];var trackIdMatches=section.match(/^a=msid:.+ (.+)$/m)||[];var mid=midMatches[1];var trackId=trackIdMatches[1];return mid&&trackId?midsToTrackIds.set(mid,trackId):midsToTrackIds},this._midsToTrackIds)};return MIDTrackMatcher}();module.exports=MIDTrackMatcher},{"../":134}],139:[function(require,module,exports){"use strict";var util=require("../../");var getMediaSections=require("../").getMediaSections;function create(){return{matched:new Set,unmatched:new Set}}function match(mAndM){var unmatched=Array.from(mAndM.unmatched);if(!unmatched.length){return null}var id=unmatched[0];mAndM.matched.add(id);mAndM.unmatched.delete(id);return id}function update(mAndM,ids){ids=new Set(ids);var removedMatchedIds=util.difference(mAndM.matched,ids);removedMatchedIds.forEach(mAndM.matched.delete,mAndM.matched);mAndM.unmatched=util.difference(ids,mAndM.matched)}function parse(kind,sdp){var mediaSections=getMediaSections(sdp,kind);var pattern="msid: ?(.+) +(.+) ?$";return new Set(util.flatMap(mediaSections,function(mediaSection){return mediaSection.match(new RegExp(pattern,"mg"))||[]}).map(function(msid){return msid.match(new RegExp(pattern))[2]}))}var OrderedTrackMatcher=function(){function OrderedTrackMatcher(){if(!(this instanceof OrderedTrackMatcher)){return new OrderedTrackMatcher}Object.defineProperties(this,{audio:{enumerable:true,value:create()},video:{enumerable:true,value:create()}})}OrderedTrackMatcher.prototype.match=function(event){return match(this[event.track.kind])};OrderedTrackMatcher.prototype.update=function(sdp){["audio","video"].forEach(function(kind){update(this[kind],parse(kind,sdp))},this)};return OrderedTrackMatcher}();module.exports=OrderedTrackMatcher},{"../":134,"../../":126}],140:[function(require,module,exports){var SID_CHARS="1234567890abcdef";var SID_CHAR_LENGTH=32;function createSID(prefix){var result="";for(var i=0;i<SID_CHAR_LENGTH;i++){result+=SID_CHARS.charAt(Math.floor(Math.random()*SID_CHARS.length))}return""+prefix+result}exports.sessionSID=createSID("SS");exports.createSID=createSID},{}],141:[function(require,module,exports){"use strict";var _a=require("@twilio/webrtc/lib/util"),guessBrowser=_a.guessBrowser,isWebRTCSupported=_a.support;var _b=require("./browserdetection"),isAndroid=_b.isAndroid,isMobile=_b.isMobile,isNonChromiumEdge=_b.isNonChromiumEdge,rebrandedChromeBrowser=_b.rebrandedChromeBrowser,mobileWebKitBrowser=_b.mobileWebKitBrowser;var SUPPORTED_CHROME_BASED_BROWSERS=["crios","edg","edge","electron","headlesschrome"];var SUPPORTED_ANDROID_BROWSERS=["chrome","firefox"];var SUPPORTED_IOS_BROWSERS=["chrome","safari"];var SUPPORTED_MOBILE_WEBKIT_BASED_BROWSERS=[];function isSupported(){var browser=guessBrowser();if(!browser){return false}var rebrandedChrome=rebrandedChromeBrowser(browser);var mobileWebKit=mobileWebKitBrowser(browser);var supportedMobileBrowsers=isAndroid()?SUPPORTED_ANDROID_BROWSERS:SUPPORTED_IOS_BROWSERS;return!!browser&&isWebRTCSupported()&&(!rebrandedChrome||SUPPORTED_CHROME_BASED_BROWSERS.includes(rebrandedChrome))&&!isNonChromiumEdge(browser)&&(!mobileWebKit||SUPPORTED_MOBILE_WEBKIT_BASED_BROWSERS.includes(mobileWebKit))&&(!isMobile()||supportedMobileBrowsers.includes(browser))}module.exports=isSupported},{"./browserdetection":118,"@twilio/webrtc/lib/util":165}],142:[function(require,module,exports){"use strict";var Timeout=function(){function Timeout(fn,delay,autoStart){if(autoStart===void 0){autoStart=true}Object.defineProperties(this,{_delay:{value:delay,writable:true},_fn:{value:fn},_timeout:{value:null,writable:true}});if(autoStart){this.start()}}Object.defineProperty(Timeout.prototype,"delay",{get:function(){return this._delay},enumerable:false,configurable:true});Object.defineProperty(Timeout.prototype,"isSet",{get:function(){return!!this._timeout},enumerable:false,configurable:true});Timeout.prototype.setDelay=function(delay){this._delay=delay};Timeout.prototype.start=function(){var _this=this;if(!this.isSet){this._timeout=setTimeout(function(){var fn=_this._fn;_this.clear();fn()},this._delay)}};Timeout.prototype.clear=function(){clearTimeout(this._timeout);this._timeout=null};Timeout.prototype.reset=function(){this.clear();this.start()};return Timeout}();module.exports=Timeout},{}],143:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var TwilioError=require("./twilioerror");var TwilioErrorByCode={};exports.createTwilioError=function createTwilioError(code,message){code=typeof code==="number"?code:0;message=typeof message==="string"&&message?message:"Unknown error";return TwilioErrorByCode[code]?new TwilioErrorByCode[code]:new TwilioError(code,message)};var AccessTokenInvalidError=function(_super){__extends(AccessTokenInvalidError,_super);function AccessTokenInvalidError(){var _this=_super.call(this,20101,"Invalid Access Token")||this;Object.setPrototypeOf(_this,AccessTokenInvalidError.prototype);return _this}return AccessTokenInvalidError}(TwilioError);exports.AccessTokenInvalidError=AccessTokenInvalidError;Object.defineProperty(TwilioErrorByCode,20101,{value:AccessTokenInvalidError});var AccessTokenHeaderInvalidError=function(_super){__extends(AccessTokenHeaderInvalidError,_super);function AccessTokenHeaderInvalidError(){var _this=_super.call(this,20102,"Invalid Access Token header")||this;Object.setPrototypeOf(_this,AccessTokenHeaderInvalidError.prototype);return _this}return AccessTokenHeaderInvalidError}(TwilioError);exports.AccessTokenHeaderInvalidError=AccessTokenHeaderInvalidError;Object.defineProperty(TwilioErrorByCode,20102,{value:AccessTokenHeaderInvalidError});var AccessTokenIssuerInvalidError=function(_super){__extends(AccessTokenIssuerInvalidError,_super);function AccessTokenIssuerInvalidError(){var _this=_super.call(this,20103,"Invalid Access Token issuer/subject")||this;Object.setPrototypeOf(_this,AccessTokenIssuerInvalidError.prototype);return _this}return AccessTokenIssuerInvalidError}(TwilioError);exports.AccessTokenIssuerInvalidError=AccessTokenIssuerInvalidError;Object.defineProperty(TwilioErrorByCode,20103,{value:AccessTokenIssuerInvalidError});var AccessTokenExpiredError=function(_super){__extends(AccessTokenExpiredError,_super);function AccessTokenExpiredError(){var _this=_super.call(this,20104,"Access Token expired or expiration date invalid")||this;Object.setPrototypeOf(_this,AccessTokenExpiredError.prototype);return _this}return AccessTokenExpiredError}(TwilioError);exports.AccessTokenExpiredError=AccessTokenExpiredError;Object.defineProperty(TwilioErrorByCode,20104,{value:AccessTokenExpiredError});var AccessTokenNotYetValidError=function(_super){__extends(AccessTokenNotYetValidError,_super);function AccessTokenNotYetValidError(){var _this=_super.call(this,20105,"Access Token not yet valid")||this;Object.setPrototypeOf(_this,AccessTokenNotYetValidError.prototype);return _this}return AccessTokenNotYetValidError}(TwilioError);exports.AccessTokenNotYetValidError=AccessTokenNotYetValidError;Object.defineProperty(TwilioErrorByCode,20105,{value:AccessTokenNotYetValidError});var AccessTokenGrantsInvalidError=function(_super){__extends(AccessTokenGrantsInvalidError,_super);function AccessTokenGrantsInvalidError(){var _this=_super.call(this,20106,"Invalid Access Token grants")||this;Object.setPrototypeOf(_this,AccessTokenGrantsInvalidError.prototype);return _this}return AccessTokenGrantsInvalidError}(TwilioError);exports.AccessTokenGrantsInvalidError=AccessTokenGrantsInvalidError;Object.defineProperty(TwilioErrorByCode,20106,{value:AccessTokenGrantsInvalidError});var AccessTokenSignatureInvalidError=function(_super){__extends(AccessTokenSignatureInvalidError,_super);function AccessTokenSignatureInvalidError(){var _this=_super.call(this,20107,"Invalid Access Token signature")||this;Object.setPrototypeOf(_this,AccessTokenSignatureInvalidError.prototype);return _this}return AccessTokenSignatureInvalidError}(TwilioError);exports.AccessTokenSignatureInvalidError=AccessTokenSignatureInvalidError;Object.defineProperty(TwilioErrorByCode,20107,{value:AccessTokenSignatureInvalidError});var SignalingConnectionError=function(_super){__extends(SignalingConnectionError,_super);function SignalingConnectionError(){var _this=_super.call(this,53e3,"Signaling connection error")||this;Object.setPrototypeOf(_this,SignalingConnectionError.prototype);return _this}return SignalingConnectionError}(TwilioError);exports.SignalingConnectionError=SignalingConnectionError;Object.defineProperty(TwilioErrorByCode,53e3,{value:SignalingConnectionError});var SignalingConnectionDisconnectedError=function(_super){__extends(SignalingConnectionDisconnectedError,_super);function SignalingConnectionDisconnectedError(){var _this=_super.call(this,53001,"Signaling connection disconnected")||this;Object.setPrototypeOf(_this,SignalingConnectionDisconnectedError.prototype);return _this}return SignalingConnectionDisconnectedError}(TwilioError);exports.SignalingConnectionDisconnectedError=SignalingConnectionDisconnectedError;Object.defineProperty(TwilioErrorByCode,53001,{value:SignalingConnectionDisconnectedError});var SignalingConnectionTimeoutError=function(_super){__extends(SignalingConnectionTimeoutError,_super);function SignalingConnectionTimeoutError(){var _this=_super.call(this,53002,"Signaling connection timed out")||this;Object.setPrototypeOf(_this,SignalingConnectionTimeoutError.prototype);return _this}return SignalingConnectionTimeoutError}(TwilioError);exports.SignalingConnectionTimeoutError=SignalingConnectionTimeoutError;Object.defineProperty(TwilioErrorByCode,53002,{value:SignalingConnectionTimeoutError});var SignalingIncomingMessageInvalidError=function(_super){__extends(SignalingIncomingMessageInvalidError,_super);function SignalingIncomingMessageInvalidError(){var _this=_super.call(this,53003,"Client received an invalid signaling message")||this;Object.setPrototypeOf(_this,SignalingIncomingMessageInvalidError.prototype);return _this}return SignalingIncomingMessageInvalidError}(TwilioError);exports.SignalingIncomingMessageInvalidError=SignalingIncomingMessageInvalidError;Object.defineProperty(TwilioErrorByCode,53003,{value:SignalingIncomingMessageInvalidError});var SignalingOutgoingMessageInvalidError=function(_super){__extends(SignalingOutgoingMessageInvalidError,_super);function SignalingOutgoingMessageInvalidError(){var _this=_super.call(this,53004,"Client sent an invalid signaling message")||this;Object.setPrototypeOf(_this,SignalingOutgoingMessageInvalidError.prototype);return _this}return SignalingOutgoingMessageInvalidError}(TwilioError);exports.SignalingOutgoingMessageInvalidError=SignalingOutgoingMessageInvalidError;Object.defineProperty(TwilioErrorByCode,53004,{value:SignalingOutgoingMessageInvalidError});var SignalingServerBusyError=function(_super){__extends(SignalingServerBusyError,_super);function SignalingServerBusyError(){var _this=_super.call(this,53006,"Video server is busy")||this;Object.setPrototypeOf(_this,SignalingServerBusyError.prototype);return _this}return SignalingServerBusyError}(TwilioError);exports.SignalingServerBusyError=SignalingServerBusyError;Object.defineProperty(TwilioErrorByCode,53006,{value:SignalingServerBusyError});var RoomNameInvalidError=function(_super){__extends(RoomNameInvalidError,_super);function RoomNameInvalidError(){var _this=_super.call(this,53100,"Room name is invalid")||this;Object.setPrototypeOf(_this,RoomNameInvalidError.prototype);return _this}return RoomNameInvalidError}(TwilioError);exports.RoomNameInvalidError=RoomNameInvalidError;Object.defineProperty(TwilioErrorByCode,53100,{value:RoomNameInvalidError});var RoomNameTooLongError=function(_super){__extends(RoomNameTooLongError,_super);function RoomNameTooLongError(){var _this=_super.call(this,53101,"Room name is too long")||this;Object.setPrototypeOf(_this,RoomNameTooLongError.prototype);return _this}return RoomNameTooLongError}(TwilioError);exports.RoomNameTooLongError=RoomNameTooLongError;Object.defineProperty(TwilioErrorByCode,53101,{value:RoomNameTooLongError});var RoomNameCharsInvalidError=function(_super){__extends(RoomNameCharsInvalidError,_super);function RoomNameCharsInvalidError(){var _this=_super.call(this,53102,"Room name contains invalid characters")||this;Object.setPrototypeOf(_this,RoomNameCharsInvalidError.prototype);return _this}return RoomNameCharsInvalidError}(TwilioError);exports.RoomNameCharsInvalidError=RoomNameCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53102,{value:RoomNameCharsInvalidError});var RoomCreateFailedError=function(_super){__extends(RoomCreateFailedError,_super);function RoomCreateFailedError(){var _this=_super.call(this,53103,"Unable to create Room")||this;Object.setPrototypeOf(_this,RoomCreateFailedError.prototype);return _this}return RoomCreateFailedError}(TwilioError);exports.RoomCreateFailedError=RoomCreateFailedError;Object.defineProperty(TwilioErrorByCode,53103,{value:RoomCreateFailedError});var RoomConnectFailedError=function(_super){__extends(RoomConnectFailedError,_super);function RoomConnectFailedError(){var _this=_super.call(this,53104,"Unable to connect to Room")||this;Object.setPrototypeOf(_this,RoomConnectFailedError.prototype);return _this}return RoomConnectFailedError}(TwilioError);exports.RoomConnectFailedError=RoomConnectFailedError;Object.defineProperty(TwilioErrorByCode,53104,{value:RoomConnectFailedError});var RoomMaxParticipantsExceededError=function(_super){__extends(RoomMaxParticipantsExceededError,_super);function RoomMaxParticipantsExceededError(){var _this=_super.call(this,53105,"Room contains too many Participants")||this;Object.setPrototypeOf(_this,RoomMaxParticipantsExceededError.prototype);return _this}return RoomMaxParticipantsExceededError}(TwilioError);exports.RoomMaxParticipantsExceededError=RoomMaxParticipantsExceededError;Object.defineProperty(TwilioErrorByCode,53105,{value:RoomMaxParticipantsExceededError});var RoomNotFoundError=function(_super){__extends(RoomNotFoundError,_super);function RoomNotFoundError(){var _this=_super.call(this,53106,"Room not found")||this;Object.setPrototypeOf(_this,RoomNotFoundError.prototype);return _this}return RoomNotFoundError}(TwilioError);exports.RoomNotFoundError=RoomNotFoundError;Object.defineProperty(TwilioErrorByCode,53106,{value:RoomNotFoundError});var RoomMaxParticipantsOutOfRangeError=function(_super){__extends(RoomMaxParticipantsOutOfRangeError,_super);function RoomMaxParticipantsOutOfRangeError(){var _this=_super.call(this,53107,"MaxParticipants is out of range")||this;Object.setPrototypeOf(_this,RoomMaxParticipantsOutOfRangeError.prototype);return _this}return RoomMaxParticipantsOutOfRangeError}(TwilioError);exports.RoomMaxParticipantsOutOfRangeError=RoomMaxParticipantsOutOfRangeError;Object.defineProperty(TwilioErrorByCode,53107,{value:RoomMaxParticipantsOutOfRangeError});var RoomTypeInvalidError=function(_super){__extends(RoomTypeInvalidError,_super);function RoomTypeInvalidError(){var _this=_super.call(this,53108,"RoomType is not valid")||this;Object.setPrototypeOf(_this,RoomTypeInvalidError.prototype);return _this}return RoomTypeInvalidError}(TwilioError);exports.RoomTypeInvalidError=RoomTypeInvalidError;Object.defineProperty(TwilioErrorByCode,53108,{value:RoomTypeInvalidError});var RoomTimeoutOutOfRangeError=function(_super){__extends(RoomTimeoutOutOfRangeError,_super);function RoomTimeoutOutOfRangeError(){var _this=_super.call(this,53109,"Timeout is out of range")||this;Object.setPrototypeOf(_this,RoomTimeoutOutOfRangeError.prototype);return _this}return RoomTimeoutOutOfRangeError}(TwilioError);exports.RoomTimeoutOutOfRangeError=RoomTimeoutOutOfRangeError;Object.defineProperty(TwilioErrorByCode,53109,{value:RoomTimeoutOutOfRangeError});var RoomStatusCallbackMethodInvalidError=function(_super){__extends(RoomStatusCallbackMethodInvalidError,_super);function RoomStatusCallbackMethodInvalidError(){var _this=_super.call(this,53110,"StatusCallbackMethod is invalid")||this;Object.setPrototypeOf(_this,RoomStatusCallbackMethodInvalidError.prototype);return _this}return RoomStatusCallbackMethodInvalidError}(TwilioError);exports.RoomStatusCallbackMethodInvalidError=RoomStatusCallbackMethodInvalidError;Object.defineProperty(TwilioErrorByCode,53110,{value:RoomStatusCallbackMethodInvalidError});var RoomStatusCallbackInvalidError=function(_super){__extends(RoomStatusCallbackInvalidError,_super);function RoomStatusCallbackInvalidError(){var _this=_super.call(this,53111,"StatusCallback is invalid")||this;Object.setPrototypeOf(_this,RoomStatusCallbackInvalidError.prototype);return _this}return RoomStatusCallbackInvalidError}(TwilioError);exports.RoomStatusCallbackInvalidError=RoomStatusCallbackInvalidError;Object.defineProperty(TwilioErrorByCode,53111,{value:RoomStatusCallbackInvalidError});var RoomStatusInvalidError=function(_super){__extends(RoomStatusInvalidError,_super);function RoomStatusInvalidError(){var _this=_super.call(this,53112,"Status is invalid")||this;Object.setPrototypeOf(_this,RoomStatusInvalidError.prototype);return _this}return RoomStatusInvalidError}(TwilioError);exports.RoomStatusInvalidError=RoomStatusInvalidError;Object.defineProperty(TwilioErrorByCode,53112,{value:RoomStatusInvalidError});var RoomRoomExistsError=function(_super){__extends(RoomRoomExistsError,_super);function RoomRoomExistsError(){var _this=_super.call(this,53113,"Room exists")||this;Object.setPrototypeOf(_this,RoomRoomExistsError.prototype);return _this}return RoomRoomExistsError}(TwilioError);exports.RoomRoomExistsError=RoomRoomExistsError;Object.defineProperty(TwilioErrorByCode,53113,{value:RoomRoomExistsError});var RoomInvalidParametersError=function(_super){__extends(RoomInvalidParametersError,_super);function RoomInvalidParametersError(){var _this=_super.call(this,53114,"Room creation parameter(s) incompatible with the Room type")||this;Object.setPrototypeOf(_this,RoomInvalidParametersError.prototype);return _this}return RoomInvalidParametersError}(TwilioError);exports.RoomInvalidParametersError=RoomInvalidParametersError;Object.defineProperty(TwilioErrorByCode,53114,{value:RoomInvalidParametersError});var RoomMediaRegionInvalidError=function(_super){__extends(RoomMediaRegionInvalidError,_super);function RoomMediaRegionInvalidError(){var _this=_super.call(this,53115,"MediaRegion is invalid")||this;Object.setPrototypeOf(_this,RoomMediaRegionInvalidError.prototype);return _this}return RoomMediaRegionInvalidError}(TwilioError);exports.RoomMediaRegionInvalidError=RoomMediaRegionInvalidError;Object.defineProperty(TwilioErrorByCode,53115,{value:RoomMediaRegionInvalidError});var RoomMediaRegionUnavailableError=function(_super){__extends(RoomMediaRegionUnavailableError,_super);function RoomMediaRegionUnavailableError(){
53
+ var _this=_super.call(this,53116,"There are no media servers available in the MediaRegion")||this;Object.setPrototypeOf(_this,RoomMediaRegionUnavailableError.prototype);return _this}return RoomMediaRegionUnavailableError}(TwilioError);exports.RoomMediaRegionUnavailableError=RoomMediaRegionUnavailableError;Object.defineProperty(TwilioErrorByCode,53116,{value:RoomMediaRegionUnavailableError});var RoomSubscriptionOperationNotSupportedError=function(_super){__extends(RoomSubscriptionOperationNotSupportedError,_super);function RoomSubscriptionOperationNotSupportedError(){var _this=_super.call(this,53117,"The subscription operation requested is not supported for the Room type")||this;Object.setPrototypeOf(_this,RoomSubscriptionOperationNotSupportedError.prototype);return _this}return RoomSubscriptionOperationNotSupportedError}(TwilioError);exports.RoomSubscriptionOperationNotSupportedError=RoomSubscriptionOperationNotSupportedError;Object.defineProperty(TwilioErrorByCode,53117,{value:RoomSubscriptionOperationNotSupportedError});var RoomCompletedError=function(_super){__extends(RoomCompletedError,_super);function RoomCompletedError(){var _this=_super.call(this,53118,"Room completed")||this;Object.setPrototypeOf(_this,RoomCompletedError.prototype);return _this}return RoomCompletedError}(TwilioError);exports.RoomCompletedError=RoomCompletedError;Object.defineProperty(TwilioErrorByCode,53118,{value:RoomCompletedError});var RoomAudioOnlyFlagNotSupportedError=function(_super){__extends(RoomAudioOnlyFlagNotSupportedError,_super);function RoomAudioOnlyFlagNotSupportedError(){var _this=_super.call(this,53124,"The AudioOnly flag is not supported for the Room type")||this;Object.setPrototypeOf(_this,RoomAudioOnlyFlagNotSupportedError.prototype);return _this}return RoomAudioOnlyFlagNotSupportedError}(TwilioError);exports.RoomAudioOnlyFlagNotSupportedError=RoomAudioOnlyFlagNotSupportedError;Object.defineProperty(TwilioErrorByCode,53124,{value:RoomAudioOnlyFlagNotSupportedError});var RoomTrackKindNotSupportedError=function(_super){__extends(RoomTrackKindNotSupportedError,_super);function RoomTrackKindNotSupportedError(){var _this=_super.call(this,53125,"The track kind is not supported by the Room")||this;Object.setPrototypeOf(_this,RoomTrackKindNotSupportedError.prototype);return _this}return RoomTrackKindNotSupportedError}(TwilioError);exports.RoomTrackKindNotSupportedError=RoomTrackKindNotSupportedError;Object.defineProperty(TwilioErrorByCode,53125,{value:RoomTrackKindNotSupportedError});var ParticipantIdentityInvalidError=function(_super){__extends(ParticipantIdentityInvalidError,_super);function ParticipantIdentityInvalidError(){var _this=_super.call(this,53200,"Participant identity is invalid")||this;Object.setPrototypeOf(_this,ParticipantIdentityInvalidError.prototype);return _this}return ParticipantIdentityInvalidError}(TwilioError);exports.ParticipantIdentityInvalidError=ParticipantIdentityInvalidError;Object.defineProperty(TwilioErrorByCode,53200,{value:ParticipantIdentityInvalidError});var ParticipantIdentityTooLongError=function(_super){__extends(ParticipantIdentityTooLongError,_super);function ParticipantIdentityTooLongError(){var _this=_super.call(this,53201,"Participant identity is too long")||this;Object.setPrototypeOf(_this,ParticipantIdentityTooLongError.prototype);return _this}return ParticipantIdentityTooLongError}(TwilioError);exports.ParticipantIdentityTooLongError=ParticipantIdentityTooLongError;Object.defineProperty(TwilioErrorByCode,53201,{value:ParticipantIdentityTooLongError});var ParticipantIdentityCharsInvalidError=function(_super){__extends(ParticipantIdentityCharsInvalidError,_super);function ParticipantIdentityCharsInvalidError(){var _this=_super.call(this,53202,"Participant identity contains invalid characters")||this;Object.setPrototypeOf(_this,ParticipantIdentityCharsInvalidError.prototype);return _this}return ParticipantIdentityCharsInvalidError}(TwilioError);exports.ParticipantIdentityCharsInvalidError=ParticipantIdentityCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53202,{value:ParticipantIdentityCharsInvalidError});var ParticipantMaxTracksExceededError=function(_super){__extends(ParticipantMaxTracksExceededError,_super);function ParticipantMaxTracksExceededError(){var _this=_super.call(this,53203,"The maximum number of published tracks allowed in the Room at the same time has been reached")||this;Object.setPrototypeOf(_this,ParticipantMaxTracksExceededError.prototype);return _this}return ParticipantMaxTracksExceededError}(TwilioError);exports.ParticipantMaxTracksExceededError=ParticipantMaxTracksExceededError;Object.defineProperty(TwilioErrorByCode,53203,{value:ParticipantMaxTracksExceededError});var ParticipantNotFoundError=function(_super){__extends(ParticipantNotFoundError,_super);function ParticipantNotFoundError(){var _this=_super.call(this,53204,"Participant not found")||this;Object.setPrototypeOf(_this,ParticipantNotFoundError.prototype);return _this}return ParticipantNotFoundError}(TwilioError);exports.ParticipantNotFoundError=ParticipantNotFoundError;Object.defineProperty(TwilioErrorByCode,53204,{value:ParticipantNotFoundError});var ParticipantDuplicateIdentityError=function(_super){__extends(ParticipantDuplicateIdentityError,_super);function ParticipantDuplicateIdentityError(){var _this=_super.call(this,53205,"Participant disconnected because of duplicate identity")||this;Object.setPrototypeOf(_this,ParticipantDuplicateIdentityError.prototype);return _this}return ParticipantDuplicateIdentityError}(TwilioError);exports.ParticipantDuplicateIdentityError=ParticipantDuplicateIdentityError;Object.defineProperty(TwilioErrorByCode,53205,{value:ParticipantDuplicateIdentityError});var TrackInvalidError=function(_super){__extends(TrackInvalidError,_super);function TrackInvalidError(){var _this=_super.call(this,53300,"Track is invalid")||this;Object.setPrototypeOf(_this,TrackInvalidError.prototype);return _this}return TrackInvalidError}(TwilioError);exports.TrackInvalidError=TrackInvalidError;Object.defineProperty(TwilioErrorByCode,53300,{value:TrackInvalidError});var TrackNameInvalidError=function(_super){__extends(TrackNameInvalidError,_super);function TrackNameInvalidError(){var _this=_super.call(this,53301,"Track name is invalid")||this;Object.setPrototypeOf(_this,TrackNameInvalidError.prototype);return _this}return TrackNameInvalidError}(TwilioError);exports.TrackNameInvalidError=TrackNameInvalidError;Object.defineProperty(TwilioErrorByCode,53301,{value:TrackNameInvalidError});var TrackNameTooLongError=function(_super){__extends(TrackNameTooLongError,_super);function TrackNameTooLongError(){var _this=_super.call(this,53302,"Track name is too long")||this;Object.setPrototypeOf(_this,TrackNameTooLongError.prototype);return _this}return TrackNameTooLongError}(TwilioError);exports.TrackNameTooLongError=TrackNameTooLongError;Object.defineProperty(TwilioErrorByCode,53302,{value:TrackNameTooLongError});var TrackNameCharsInvalidError=function(_super){__extends(TrackNameCharsInvalidError,_super);function TrackNameCharsInvalidError(){var _this=_super.call(this,53303,"Track name contains invalid characters")||this;Object.setPrototypeOf(_this,TrackNameCharsInvalidError.prototype);return _this}return TrackNameCharsInvalidError}(TwilioError);exports.TrackNameCharsInvalidError=TrackNameCharsInvalidError;Object.defineProperty(TwilioErrorByCode,53303,{value:TrackNameCharsInvalidError});var TrackNameIsDuplicatedError=function(_super){__extends(TrackNameIsDuplicatedError,_super);function TrackNameIsDuplicatedError(){var _this=_super.call(this,53304,"Track name is duplicated")||this;Object.setPrototypeOf(_this,TrackNameIsDuplicatedError.prototype);return _this}return TrackNameIsDuplicatedError}(TwilioError);exports.TrackNameIsDuplicatedError=TrackNameIsDuplicatedError;Object.defineProperty(TwilioErrorByCode,53304,{value:TrackNameIsDuplicatedError});var TrackServerTrackCapacityReachedError=function(_super){__extends(TrackServerTrackCapacityReachedError,_super);function TrackServerTrackCapacityReachedError(){var _this=_super.call(this,53305,"The server has reached capacity and cannot fulfill this request")||this;Object.setPrototypeOf(_this,TrackServerTrackCapacityReachedError.prototype);return _this}return TrackServerTrackCapacityReachedError}(TwilioError);exports.TrackServerTrackCapacityReachedError=TrackServerTrackCapacityReachedError;Object.defineProperty(TwilioErrorByCode,53305,{value:TrackServerTrackCapacityReachedError});var MediaClientLocalDescFailedError=function(_super){__extends(MediaClientLocalDescFailedError,_super);function MediaClientLocalDescFailedError(){var _this=_super.call(this,53400,"Client is unable to create or apply a local media description")||this;Object.setPrototypeOf(_this,MediaClientLocalDescFailedError.prototype);return _this}return MediaClientLocalDescFailedError}(TwilioError);exports.MediaClientLocalDescFailedError=MediaClientLocalDescFailedError;Object.defineProperty(TwilioErrorByCode,53400,{value:MediaClientLocalDescFailedError});var MediaServerLocalDescFailedError=function(_super){__extends(MediaServerLocalDescFailedError,_super);function MediaServerLocalDescFailedError(){var _this=_super.call(this,53401,"Server is unable to create or apply a local media description")||this;Object.setPrototypeOf(_this,MediaServerLocalDescFailedError.prototype);return _this}return MediaServerLocalDescFailedError}(TwilioError);exports.MediaServerLocalDescFailedError=MediaServerLocalDescFailedError;Object.defineProperty(TwilioErrorByCode,53401,{value:MediaServerLocalDescFailedError});var MediaClientRemoteDescFailedError=function(_super){__extends(MediaClientRemoteDescFailedError,_super);function MediaClientRemoteDescFailedError(){var _this=_super.call(this,53402,"Client is unable to apply a remote media description")||this;Object.setPrototypeOf(_this,MediaClientRemoteDescFailedError.prototype);return _this}return MediaClientRemoteDescFailedError}(TwilioError);exports.MediaClientRemoteDescFailedError=MediaClientRemoteDescFailedError;Object.defineProperty(TwilioErrorByCode,53402,{value:MediaClientRemoteDescFailedError});var MediaServerRemoteDescFailedError=function(_super){__extends(MediaServerRemoteDescFailedError,_super);function MediaServerRemoteDescFailedError(){var _this=_super.call(this,53403,"Server is unable to apply a remote media description")||this;Object.setPrototypeOf(_this,MediaServerRemoteDescFailedError.prototype);return _this}return MediaServerRemoteDescFailedError}(TwilioError);exports.MediaServerRemoteDescFailedError=MediaServerRemoteDescFailedError;Object.defineProperty(TwilioErrorByCode,53403,{value:MediaServerRemoteDescFailedError});var MediaNoSupportedCodecError=function(_super){__extends(MediaNoSupportedCodecError,_super);function MediaNoSupportedCodecError(){var _this=_super.call(this,53404,"No supported codec")||this;Object.setPrototypeOf(_this,MediaNoSupportedCodecError.prototype);return _this}return MediaNoSupportedCodecError}(TwilioError);exports.MediaNoSupportedCodecError=MediaNoSupportedCodecError;Object.defineProperty(TwilioErrorByCode,53404,{value:MediaNoSupportedCodecError});var MediaConnectionError=function(_super){__extends(MediaConnectionError,_super);function MediaConnectionError(){var _this=_super.call(this,53405,"Media connection failed or Media activity ceased")||this;Object.setPrototypeOf(_this,MediaConnectionError.prototype);return _this}return MediaConnectionError}(TwilioError);exports.MediaConnectionError=MediaConnectionError;Object.defineProperty(TwilioErrorByCode,53405,{value:MediaConnectionError});var MediaDTLSTransportFailedError=function(_super){__extends(MediaDTLSTransportFailedError,_super);function MediaDTLSTransportFailedError(){var _this=_super.call(this,53407,"Media connection failed due to DTLS handshake failure")||this;Object.setPrototypeOf(_this,MediaDTLSTransportFailedError.prototype);return _this}return MediaDTLSTransportFailedError}(TwilioError);exports.MediaDTLSTransportFailedError=MediaDTLSTransportFailedError;Object.defineProperty(TwilioErrorByCode,53407,{value:MediaDTLSTransportFailedError});var ConfigurationAcquireFailedError=function(_super){__extends(ConfigurationAcquireFailedError,_super);function ConfigurationAcquireFailedError(){var _this=_super.call(this,53500,"Unable to acquire configuration")||this;Object.setPrototypeOf(_this,ConfigurationAcquireFailedError.prototype);return _this}return ConfigurationAcquireFailedError}(TwilioError);exports.ConfigurationAcquireFailedError=ConfigurationAcquireFailedError;Object.defineProperty(TwilioErrorByCode,53500,{value:ConfigurationAcquireFailedError});var ConfigurationAcquireTurnFailedError=function(_super){__extends(ConfigurationAcquireTurnFailedError,_super);function ConfigurationAcquireTurnFailedError(){var _this=_super.call(this,53501,"Unable to acquire TURN credentials")||this;Object.setPrototypeOf(_this,ConfigurationAcquireTurnFailedError.prototype);return _this}return ConfigurationAcquireTurnFailedError}(TwilioError);exports.ConfigurationAcquireTurnFailedError=ConfigurationAcquireTurnFailedError;Object.defineProperty(TwilioErrorByCode,53501,{value:ConfigurationAcquireTurnFailedError})},{"./twilioerror":144}],144:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __read=this&&this.__read||function(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar};var __spreadArray=this&&this.__spreadArray||function(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to};var TwilioError=function(_super){__extends(TwilioError,_super);function TwilioError(code){var _this=this;var args=[].slice.call(arguments,1);_this=_super.apply(this,__spreadArray([],__read(args)))||this;Object.setPrototypeOf(_this,TwilioError.prototype);var error=Error.apply(_this,args);error.name="TwilioError";Object.defineProperty(_this,"code",{value:code,enumerable:true});Object.getOwnPropertyNames(error).forEach(function(prop){Object.defineProperty(this,prop,{value:error[prop],enumerable:true})},_this);return _this}TwilioError.prototype.toString=function(){var message=this.message?": "+this.message:"";return this.name+" "+this.code+message};return TwilioError}(Error);module.exports=TwilioError},{}],145:[function(require,module,exports){"use strict";var isNonArrayObject=require("./").isNonArrayObject;var _a=require("./constants"),E=_a.typeErrors,clientTrackSwitchOffControl=_a.clientTrackSwitchOffControl,videoContentPreferencesMode=_a.videoContentPreferencesMode,subscriptionMode=_a.subscriptionMode,trackPriority=_a.trackPriority,trackSwitchOffMode=_a.trackSwitchOffMode;function validateBandwidthProfile(bandwidthProfile){var error=validateObject(bandwidthProfile,"options.bandwidthProfile");if(!bandwidthProfile||error){return error}error=validateObject(bandwidthProfile.video,"options.bandwidthProfile.video",[{prop:"contentPreferencesMode",values:Object.values(videoContentPreferencesMode)},{prop:"dominantSpeakerPriority",values:Object.values(trackPriority)},{prop:"maxSubscriptionBitrate",type:"number"},{prop:"maxTracks",type:"number"},{prop:"mode",values:Object.values(subscriptionMode)},{prop:"clientTrackSwitchOffControl",values:Object.values(clientTrackSwitchOffControl)},{prop:"trackSwitchOffMode",values:Object.values(trackSwitchOffMode)}]);if(error){return error}if(bandwidthProfile.video){if("maxTracks"in bandwidthProfile.video&&"clientTrackSwitchOffControl"in bandwidthProfile.video){return new TypeError("options.bandwidthProfile.video.maxTracks is deprecated. Use options.bandwidthProfile.video.clientTrackSwitchOffControl instead.")}if("renderDimensions"in bandwidthProfile.video&&"contentPreferencesMode"in bandwidthProfile.video){return new TypeError("options.bandwidthProfile.video.renderDimensions is deprecated. Use options.bandwidthProfile.video.contentPreferencesMode instead.")}return validateRenderDimensions(bandwidthProfile.video.renderDimensions)}return null}function validateLocalTrack(track,options){if(!(track instanceof options.LocalAudioTrack||track instanceof options.LocalDataTrack||track instanceof options.LocalVideoTrack||track instanceof options.MediaStreamTrack)){throw E.INVALID_TYPE("track","LocalAudioTrack, LocalVideoTrack, LocalDataTrack, or MediaStreamTrack")}}function validateObject(object,name,propChecks){if(propChecks===void 0){propChecks=[]}if(typeof object==="undefined"){return null}if(object===null||!isNonArrayObject(object)){return E.INVALID_TYPE(name,"object")}return propChecks.reduce(function(error,_a){var prop=_a.prop,type=_a.type,values=_a.values;if(error||!(prop in object)){return error}var value=object[prop];if(type&&typeof value!==type){return E.INVALID_TYPE(name+"."+prop,type)}if(type==="number"&&isNaN(value)){return E.INVALID_TYPE(name+"."+prop,type)}if(Array.isArray(values)&&!values.includes(value)){return E.INVALID_VALUE(name+"."+prop,values)}return error},null)}function validateRenderDimensions(renderDimensions){var name="options.bandwidthProfile.video.renderDimensions";var error=validateObject(renderDimensions,name);return renderDimensions?error||Object.values(trackPriority).reduce(function(error,prop){return error||validateObject(renderDimensions[prop],name+"."+prop,[{prop:"height",type:"number"},{prop:"width",type:"number"}])},null):error}exports.validateBandwidthProfile=validateBandwidthProfile;exports.validateLocalTrack=validateLocalTrack;exports.validateObject=validateObject},{"./":126,"./constants":120}],146:[function(require,module,exports){var noop=function(){};var undefinedType="undefined";var isIE=typeof window!==undefinedType&&typeof window.navigator!==undefinedType&&/Trident\/|MSIE /.test(window.navigator.userAgent);var logMethods=["trace","debug","info","warn","error"];function bindMethod(obj,methodName){var method=obj[methodName];if(typeof method.bind==="function"){return method.bind(obj)}else{try{return Function.prototype.bind.call(method,obj)}catch(e){return function(){return Function.prototype.apply.apply(method,[obj,arguments])}}}}function traceForIE(){if(console.log){if(console.log.apply){console.log.apply(console,arguments)}else{Function.prototype.apply.apply(console.log,[console,arguments])}}if(console.trace)console.trace()}function realMethod(methodName){if(methodName==="debug"){methodName="log"}if(typeof console===undefinedType){return false}else if(methodName==="trace"&&isIE){return traceForIE}else if(console[methodName]!==undefined){return bindMethod(console,methodName)}else if(console.log!==undefined){return bindMethod(console,"log")}else{return noop}}function replaceLoggingMethods(level,loggerName){for(var i=0;i<logMethods.length;i++){var methodName=logMethods[i];this[methodName]=i<level?noop:this.methodFactory(methodName,level,loggerName)}this.log=this.debug}function enableLoggingWhenConsoleArrives(methodName,level,loggerName){return function(){if(typeof console!==undefinedType){replaceLoggingMethods.call(this,level,loggerName);this[methodName].apply(this,arguments)}}}function defaultMethodFactory(methodName,level,loggerName){return realMethod(methodName)||enableLoggingWhenConsoleArrives.apply(this,arguments)}function Logger(name,defaultLevel,factory){var self=this;var currentLevel;var storageKey="loglevel";if(typeof name==="string"){storageKey+=":"+name}else if(typeof name==="symbol"){storageKey=undefined}function persistLevelIfPossible(levelNum){var levelName=(logMethods[levelNum]||"silent").toUpperCase();if(typeof window===undefinedType||!storageKey)return;try{window.localStorage[storageKey]=levelName;return}catch(ignore){}try{window.document.cookie=encodeURIComponent(storageKey)+"="+levelName+";"}catch(ignore){}}function getPersistedLevel(){var storedLevel;if(typeof window===undefinedType||!storageKey)return;try{storedLevel=window.localStorage[storageKey]}catch(ignore){}if(typeof storedLevel===undefinedType){try{var cookie=window.document.cookie;var location=cookie.indexOf(encodeURIComponent(storageKey)+"=");if(location!==-1){storedLevel=/^([^;]+)/.exec(cookie.slice(location))[1]}}catch(ignore){}}if(self.levels[storedLevel]===undefined){storedLevel=undefined}return storedLevel}self.name=name;self.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5};self.methodFactory=factory||defaultMethodFactory;self.getLevel=function(){return currentLevel};self.setLevel=function(level,persist){if(typeof level==="string"&&self.levels[level.toUpperCase()]!==undefined){level=self.levels[level.toUpperCase()]}if(typeof level==="number"&&level>=0&&level<=self.levels.SILENT){currentLevel=level;if(persist!==false){persistLevelIfPossible(level)}replaceLoggingMethods.call(self,level,name);if(typeof console===undefinedType&&level<self.levels.SILENT){return"No console available for logging"}}else{throw"log.setLevel() called with invalid level: "+level}};self.setDefaultLevel=function(level){if(!getPersistedLevel()){self.setLevel(level,false)}};self.enableAll=function(persist){self.setLevel(self.levels.TRACE,persist)};self.disableAll=function(persist){self.setLevel(self.levels.SILENT,persist)};var initialLevel=getPersistedLevel();if(initialLevel==null){initialLevel=defaultLevel==null?"WARN":defaultLevel}self.setLevel(initialLevel,false)}var defaultLogger=new Logger;var _loggersByName={};defaultLogger.getLogger=function getLogger(name){if(typeof name!=="symbol"&&typeof name!=="string"||name===""){throw new TypeError("You must supply a name when creating a logger.")}var logger=_loggersByName[name];if(!logger){logger=_loggersByName[name]=new Logger(name,defaultLogger.getLevel(),defaultLogger.methodFactory)}return logger};var _log=typeof window!==undefinedType?window.log:undefined;defaultLogger.noConflict=function(){if(typeof window!==undefinedType&&window.log===defaultLogger){window.log=_log}return defaultLogger};defaultLogger.getLoggers=function getLoggers(){return _loggersByName};defaultLogger["default"]=defaultLogger;module.exports=defaultLogger},{}],147:[function(require,module,exports){"use strict";var NativeAudioContext=typeof AudioContext!=="undefined"?AudioContext:typeof webkitAudioContext!=="undefined"?webkitAudioContext:null;var AudioContextFactory=function(){function AudioContextFactory(options){options=Object.assign({AudioContext:NativeAudioContext},options);Object.defineProperties(this,{_AudioContext:{value:options.AudioContext},_audioContext:{value:null,writable:true},_holders:{value:new Set},AudioContextFactory:{enumerable:true,value:AudioContextFactory}})}AudioContextFactory.prototype.getOrCreate=function(holder){if(!this._holders.has(holder)){this._holders.add(holder);if(this._AudioContext&&!this._audioContext){try{this._audioContext=new this._AudioContext}catch(error){}}}return this._audioContext};AudioContextFactory.prototype.release=function(holder){if(this._holders.has(holder)){this._holders.delete(holder);if(!this._holders.size&&this._audioContext){this._audioContext.close();this._audioContext=null}}};return AudioContextFactory}();module.exports=new AudioContextFactory},{}],148:[function(require,module,exports){"use strict";function delay(timeout){timeout=typeof timeout==="number"?timeout:0;return new Promise(function(resolve){return setTimeout(resolve,timeout)})}function detectSilence(audioContext,stream,timeout){timeout=typeof timeout==="number"?timeout:250;var source=audioContext.createMediaStreamSource(stream);var analyser=audioContext.createAnalyser();analyser.fftSize=2048;source.connect(analyser);var samples=new Uint8Array(analyser.fftSize);var timeoutDidFire=false;setTimeout(function(){timeoutDidFire=true},timeout);function doDetectSilence(){if(timeoutDidFire){return Promise.resolve(true)}analyser.getByteTimeDomainData(samples);return samples.some(function(sample){return sample!==128&&sample!==0})?Promise.resolve(false):delay().then(doDetectSilence)}return doDetectSilence().then(function(isSilent){source.disconnect();return isSilent},function(error){source.disconnect();throw error})}module.exports=detectSilence},{}],149:[function(require,module,exports){"use strict";var detectSilence=require("./detectsilence");function workaround(log,getUserMedia,constraints,n,timeout){n=typeof n==="number"?n:3;var retry=0;var AudioContextFactory=require("./audiocontext");var holder={};var audioContext=AudioContextFactory.getOrCreate(holder);function doWorkaround(){return getUserMedia(constraints).then(function(stream){var isSilentPromise=constraints.audio?detectSilence(audioContext,stream,timeout).catch(function(err){log.warn("Encountered an error while detecting silence",err);return true}):Promise.resolve(false);return isSilentPromise.then(function(isSilent){if(!isSilent){log.info("Got a non-silent audio MediaStreamTrack; returning it.");return stream}else if(n<=0){log.warn("Got a silent audio MediaStreamTrack. Normally we would try to get a new one, but we've run out of retries; returning it anyway.");return stream}log.warn("Got a silent audio MediaStreamTrack. Stopping all MediaStreamTracks and calling getUserMedia again. This is retry #"+ ++retry+".");stream.getTracks().forEach(function(track){return track.stop()});n--;return doWorkaround()})})}return doWorkaround().then(function(stream){AudioContextFactory.release(holder);return stream},function(error){AudioContextFactory.release(holder);throw error})}module.exports=workaround},{"./audiocontext":147,"./detectsilence":148}],150:[function(require,module,exports){"use strict";var flatMap=require("./util").flatMap;var guessBrowser=require("./util").guessBrowser;var guessBrowserVersion=require("./util").guessBrowserVersion;var getSdpFormat=require("./util/sdp").getSdpFormat;var guess=guessBrowser();var guessVersion=guessBrowserVersion();var isChrome=guess==="chrome";var isFirefox=guess==="firefox";var isSafari=guess==="safari";var chromeMajorVersion=isChrome?guessVersion.major:null;var CHROME_LEGACY_MAX_AUDIO_LEVEL=32767;function getStats(peerConnection,options){if(!(peerConnection&&typeof peerConnection.getStats==="function")){return Promise.reject(new Error("Given PeerConnection does not support getStats"))}return _getStats(peerConnection,options)}function _getStats(peerConnection,options){var localAudioTracks=getTracks(peerConnection,"audio","local");var localVideoTracks=getTracks(peerConnection,"video","local");var remoteAudioTracks=getTracks(peerConnection,"audio");var remoteVideoTracks=getTracks(peerConnection,"video");var statsResponse={activeIceCandidatePair:null,localAudioTrackStats:[],localVideoTrackStats:[],remoteAudioTrackStats:[],remoteVideoTrackStats:[]};var trackStatsPromises=flatMap([[localAudioTracks,"localAudioTrackStats",false],[localVideoTracks,"localVideoTrackStats",false],[remoteAudioTracks,"remoteAudioTrackStats",true],[remoteVideoTracks,"remoteVideoTrackStats",true]],function(triple){var tracks=triple[0];var statsArrayName=triple[1];var isRemote=triple[2];return tracks.map(function(track){return getTrackStats(peerConnection,track,Object.assign({isRemote:isRemote},options)).then(function(trackStatsArray){trackStatsArray.forEach(function(trackStats){trackStats.trackId=track.id;statsResponse[statsArrayName].push(trackStats)})})})});return Promise.all(trackStatsPromises).then(function(){return getActiveIceCandidatePairStats(peerConnection,options)}).then(function(activeIceCandidatePairStatsReport){statsResponse.activeIceCandidatePair=activeIceCandidatePairStatsReport;return statsResponse})}function getActiveIceCandidatePairStats(peerConnection,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome||typeof options.testForSafari!=="undefined"||isSafari){return peerConnection.getStats().then(standardizeChromeOrSafariActiveIceCandidatePairStats)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return peerConnection.getStats().then(standardizeFirefoxActiveIceCandidatePairStats)}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function standardizeChromeOrSafariActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",type:"string"},{key:"port",type:"number"},{key:"priority",type:"number"},{key:"protocol",type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",type:"string"}]);var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeLocalCandidateStats[keyInfo.key]===keyInfo.type?activeLocalCandidateStats[keyInfo.key]:keyInfo.key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeRemoteCandidateStats[keyInfo.key]===keyInfo.type?activeRemoteCandidateStats[keyInfo.key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string",fixup:function(state){return state==="inprogress"?"in-progress":state}},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?keyInfo.fixup?keyInfo.fixup(activeCandidatePairStats[keyInfo.key]):activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function standardizeFirefoxActiveIceCandidatePairStats(stats){var activeCandidatePairStats=Array.from(stats.values()).find(function(stat){return stat.type==="candidate-pair"&&stat.nominated});if(!activeCandidatePairStats){return null}var activeLocalCandidateStats=stats.get(activeCandidatePairStats.localCandidateId);var activeRemoteCandidateStats=stats.get(activeCandidatePairStats.remoteCandidateId);var standardizedCandidateStatsKeys=[{key:"candidateType",type:"string"},{key:"ip",ffKeys:["address","ipAddress"],type:"string"},{key:"port",ffKeys:["portNumber"],type:"number"},{key:"priority",type:"number"},{key:"protocol",ffKeys:["transport"],type:"string"},{key:"url",type:"string"}];var standardizedLocalCandidateStatsKeys=standardizedCandidateStatsKeys.concat([{key:"deleted",type:"boolean"},{key:"relayProtocol",
54
+ type:"string"}]);var candidateTypes={host:"host",peerreflexive:"prflx",relayed:"relay",serverreflexive:"srflx"};var standatdizedLocalCandidateStatsReport=activeLocalCandidateStats?standardizedLocalCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeLocalCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeLocalCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeLocalCandidateStats[key]]||activeLocalCandidateStats[key]:activeLocalCandidateStats[key]:key==="deleted"?false:null;return report},{}):null;var standardizedRemoteCandidateStatsReport=activeRemoteCandidateStats?standardizedCandidateStatsKeys.reduce(function(report,keyInfo){var key=keyInfo.ffKeys&&keyInfo.ffKeys.find(function(key){return key in activeRemoteCandidateStats})||keyInfo.key;report[keyInfo.key]=typeof activeRemoteCandidateStats[key]===keyInfo.type?key==="candidateType"?candidateTypes[activeRemoteCandidateStats[key]]||activeRemoteCandidateStats[key]:activeRemoteCandidateStats[key]:null;return report},{}):null;return[{key:"availableIncomingBitrate",type:"number"},{key:"availableOutgoingBitrate",type:"number"},{key:"bytesReceived",type:"number"},{key:"bytesSent",type:"number"},{key:"consentRequestsSent",type:"number"},{key:"currentRoundTripTime",type:"number"},{key:"lastPacketReceivedTimestamp",type:"number"},{key:"lastPacketSentTimestamp",type:"number"},{key:"nominated",type:"boolean"},{key:"priority",type:"number"},{key:"readable",type:"boolean"},{key:"requestsReceived",type:"number"},{key:"requestsSent",type:"number"},{key:"responsesReceived",type:"number"},{key:"responsesSent",type:"number"},{key:"retransmissionsReceived",type:"number"},{key:"retransmissionsSent",type:"number"},{key:"state",type:"string"},{key:"totalRoundTripTime",type:"number"},{key:"transportId",type:"string"},{key:"writable",type:"boolean"}].reduce(function(report,keyInfo){report[keyInfo.key]=typeof activeCandidatePairStats[keyInfo.key]===keyInfo.type?activeCandidatePairStats[keyInfo.key]:null;return report},{localCandidate:standatdizedLocalCandidateStatsReport,remoteCandidate:standardizedRemoteCandidateStatsReport})}function getTracks(peerConnection,kind,localOrRemote){var getSendersOrReceivers=localOrRemote==="local"?"getSenders":"getReceivers";if(peerConnection[getSendersOrReceivers]){return peerConnection[getSendersOrReceivers]().map(function(senderOrReceiver){return senderOrReceiver.track}).filter(function(track){return track&&track.kind===kind})}var getStreams=localOrRemote==="local"?"getLocalStreams":"getRemoteStreams";return flatMap(peerConnection[getStreams](),function(stream){var getTracks=kind==="audio"?"getAudioTracks":"getVideoTracks";return stream[getTracks]()})}function getTrackStats(peerConnection,track,options){options=options||{};if(typeof options.testForChrome!=="undefined"||isChrome){return chromeOrSafariGetTrackStats(peerConnection,track)}if(typeof options.testForFirefox!=="undefined"||isFirefox){return firefoxGetTrackStats(peerConnection,track,options.isRemote)}if(typeof options.testForSafari!=="undefined"||isSafari){if(typeof options.testForSafari!=="undefined"||getSdpFormat()==="unified"){return chromeOrSafariGetTrackStats(peerConnection,track)}return Promise.reject(new Error(["getStats() is not supported on this version of Safari","due to this bug: https://bugs.webkit.org/show_bug.cgi?id=192601"].join(" ")))}return Promise.reject(new Error("RTCPeerConnection#getStats() not supported"))}function chromeOrSafariGetTrackStats(peerConnection,track){return new Promise(function(resolve,reject){if(chromeMajorVersion&&chromeMajorVersion<67){peerConnection.getStats(function(response){resolve([standardizeChromeLegacyStats(response,track)])},null,reject);return}peerConnection.getStats(track).then(function(response){resolve(standardizeChromeOrSafariStats(response))},reject)})}function firefoxGetTrackStats(peerConnection,track,isRemote){return new Promise(function(resolve,reject){peerConnection.getStats(track).then(function(response){resolve([standardizeFirefoxStats(response,isRemote)])},reject)})}function standardizeChromeLegacyStats(response,track){var ssrcReport=response.result().find(function(report){return report.type==="ssrc"&&report.stat("googTrackId")===track.id});var standardizedStats={};if(ssrcReport){standardizedStats.timestamp=Math.round(Number(ssrcReport.timestamp));standardizedStats=ssrcReport.names().reduce(function(stats,name){switch(name){case"googCodecName":stats.codecName=ssrcReport.stat(name);break;case"googRtt":stats.roundTripTime=Number(ssrcReport.stat(name));break;case"googJitterReceived":stats.jitter=Number(ssrcReport.stat(name));break;case"googFrameWidthInput":stats.frameWidthInput=Number(ssrcReport.stat(name));break;case"googFrameHeightInput":stats.frameHeightInput=Number(ssrcReport.stat(name));break;case"googFrameWidthSent":stats.frameWidthSent=Number(ssrcReport.stat(name));break;case"googFrameHeightSent":stats.frameHeightSent=Number(ssrcReport.stat(name));break;case"googFrameWidthReceived":stats.frameWidthReceived=Number(ssrcReport.stat(name));break;case"googFrameHeightReceived":stats.frameHeightReceived=Number(ssrcReport.stat(name));break;case"googFrameRateInput":stats.frameRateInput=Number(ssrcReport.stat(name));break;case"googFrameRateSent":stats.frameRateSent=Number(ssrcReport.stat(name));break;case"googFrameRateReceived":stats.frameRateReceived=Number(ssrcReport.stat(name));break;case"ssrc":stats[name]=ssrcReport.stat(name);break;case"bytesReceived":case"bytesSent":case"packetsLost":case"packetsReceived":case"packetsSent":case"audioInputLevel":case"audioOutputLevel":stats[name]=Number(ssrcReport.stat(name));break}return stats},standardizedStats)}return standardizedStats}function standardizeChromeOrSafariStats(response){var inbound=null;var outbound=[];var remoteInbound=null;var remoteOutbound=null;var track=null;var codec=null;var localMedia=null;response.forEach(function(stat){switch(stat.type){case"inbound-rtp":inbound=stat;break;case"outbound-rtp":outbound.push(stat);break;case"media-source":localMedia=stat;break;case"track":track=stat;break;case"codec":codec=stat;break;case"remote-inbound-rtp":remoteInbound=stat;break;case"remote-outbound-rtp":remoteOutbound=stat;break}});var isRemote=track&&track.remoteSource;var mainSources=isRemote?[inbound]:outbound;var stats=[];var remoteSource=isRemote?remoteOutbound:remoteInbound;mainSources.forEach(function(source){var standardizedStats={};var statSources=[source,localMedia,track,codec,remoteSource&&remoteSource.ssrc===source.ssrc?remoteSource:null];function getStatValue(name){var sourceFound=statSources.find(function(statSource){return statSource&&typeof statSource[name]!=="undefined"})||null;return sourceFound?sourceFound[name]:null}var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var mimeType=getStatValue("mimeType");if(typeof mimeType==="string"){mimeType=mimeType.split("/");standardizedStats.codecName=mimeType[mimeType.length-1]}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameWidth=getStatValue("frameWidth");if(typeof frameWidth==="number"){if(isRemote){standardizedStats.frameWidthReceived=frameWidth}else{standardizedStats.frameWidthSent=frameWidth;standardizedStats.frameWidthInput=track.frameWidth}}var frameHeight=getStatValue("frameHeight");if(typeof frameHeight==="number"){if(isRemote){standardizedStats.frameHeightReceived=frameHeight}else{standardizedStats.frameHeightSent=frameHeight;standardizedStats.frameHeightInput=track.frameHeight}}var framesPerSecond=getStatValue("framesPerSecond");if(typeof framesPerSecond==="number"){standardizedStats[isRemote?"frameRateReceived":"frameRateSent"]=framesPerSecond}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var audioLevel=getStatValue("audioLevel");if(typeof audioLevel==="number"){audioLevel=Math.round(audioLevel*CHROME_LEGACY_MAX_AUDIO_LEVEL);if(isRemote){standardizedStats.audioOutputLevel=audioLevel}else{standardizedStats.audioInputLevel=audioLevel}}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}stats.push(standardizedStats)});return stats}function standardizeFirefoxStats(response,isRemote){response=response||new Map;var inbound=null;var outbound=null;response.forEach(function(stat){if(stat.isRemote){return}switch(stat.type){case"inbound-rtp":inbound=stat;outbound=response.get(stat.remoteId);break;case"outbound-rtp":outbound=stat;inbound=response.get(stat.remoteId);break}});var first=isRemote?inbound:outbound;var second=isRemote?outbound:inbound;function getStatValue(name){if(first&&typeof first[name]!=="undefined"){return first[name]}if(second&&typeof second[name]!=="undefined"){return second[name]}return null}var standardizedStats={};var timestamp=getStatValue("timestamp");standardizedStats.timestamp=Math.round(timestamp);var ssrc=getStatValue("ssrc");if(typeof ssrc==="number"){standardizedStats.ssrc=String(ssrc)}var bytesSent=getStatValue("bytesSent");if(typeof bytesSent==="number"){standardizedStats.bytesSent=bytesSent}var packetsLost=getStatValue("packetsLost");if(typeof packetsLost==="number"){standardizedStats.packetsLost=packetsLost}var packetsSent=getStatValue("packetsSent");if(typeof packetsSent==="number"){standardizedStats.packetsSent=packetsSent}var roundTripTime=getStatValue("roundTripTime");if(typeof roundTripTime==="number"){standardizedStats.roundTripTime=Math.round(roundTripTime*1e3)}var jitter=getStatValue("jitter");if(typeof jitter==="number"){standardizedStats.jitter=Math.round(jitter*1e3)}var frameRateSent=getStatValue("framerateMean");if(typeof frameRateSent==="number"){standardizedStats.frameRateSent=Math.round(frameRateSent)}var bytesReceived=getStatValue("bytesReceived");if(typeof bytesReceived==="number"){standardizedStats.bytesReceived=bytesReceived}var packetsReceived=getStatValue("packetsReceived");if(typeof packetsReceived==="number"){standardizedStats.packetsReceived=packetsReceived}var frameRateReceived=getStatValue("framerateMean");if(typeof frameRateReceived==="number"){standardizedStats.frameRateReceived=Math.round(frameRateReceived)}var totalPacketSendDalay=getStatValue("totalPacketSendDelay");if(typeof totalPacketSendDalay==="number"){standardizedStats.totalPacketSendDelay=totalPacketSendDalay}var totalEncodeTime=getStatValue("totalEncodeTime");if(typeof totalEncodeTime==="number"){standardizedStats.totalEncodeTime=totalEncodeTime}var framesEncoded=getStatValue("framesEncoded");if(typeof framesEncoded==="number"){standardizedStats.framesEncoded=framesEncoded}var estimatedPlayoutTimestamp=getStatValue("estimatedPlayoutTimestamp");if(typeof estimatedPlayoutTimestamp==="number"){standardizedStats.estimatedPlayoutTimestamp=estimatedPlayoutTimestamp}var totalDecodeTime=getStatValue("totalDecodeTime");if(typeof totalDecodeTime==="number"){standardizedStats.totalDecodeTime=totalDecodeTime}var framesDecoded=getStatValue("framesDecoded");if(typeof framesDecoded==="number"){standardizedStats.framesDecoded=framesDecoded}var jitterBufferDelay=getStatValue("jitterBufferDelay");if(typeof jitterBufferDelay==="number"){standardizedStats.jitterBufferDelay=jitterBufferDelay}var jitterBufferEmittedCount=getStatValue("jitterBufferEmittedCount");if(typeof jitterBufferEmittedCount==="number"){standardizedStats.jitterBufferEmittedCount=jitterBufferEmittedCount}return standardizedStats}module.exports=getStats},{"./util":165,"./util/sdp":167}],151:[function(require,module,exports){"use strict";function getUserMedia(constraints){if(typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"){constraints=constraints||{audio:true,video:true};return navigator.mediaDevices.getUserMedia(constraints)}return Promise.reject(new Error("getUserMedia is not supported"))}module.exports=getUserMedia},{}],152:[function(require,module,exports){"use strict";var WebRTC={};Object.defineProperties(WebRTC,{getStats:{enumerable:true,value:require("./getstats")},getUserMedia:{enumerable:true,value:require("./getusermedia")},MediaStream:{enumerable:true,value:require("./mediastream")},MediaStreamTrack:{enumerable:true,value:require("./mediastreamtrack")},RTCIceCandidate:{enumerable:true,value:require("./rtcicecandidate")},RTCPeerConnection:{enumerable:true,value:require("./rtcpeerconnection")},RTCSessionDescription:{enumerable:true,value:require("./rtcsessiondescription")},version:{enumerable:true,value:require("../package.json").version}});module.exports=WebRTC},{"../package.json":168,"./getstats":150,"./getusermedia":151,"./mediastream":153,"./mediastreamtrack":154,"./rtcicecandidate":155,"./rtcpeerconnection":158,"./rtcsessiondescription":163}],153:[function(require,module,exports){"use strict";if(typeof MediaStream==="function"){module.exports=MediaStream}else{module.exports=function MediaStream(){throw new Error("MediaStream is not supported")}}},{}],154:[function(require,module,exports){"use strict";if(typeof MediaStreamTrack==="function"){module.exports=MediaStreamTrack}else{module.exports=function MediaStreamTrack(){throw new Error("MediaStreamTrack is not supported")}}},{}],155:[function(require,module,exports){"use strict";if(typeof RTCIceCandidate==="function"){module.exports=RTCIceCandidate}else{module.exports=function RTCIceCandidate(){throw new Error("RTCIceCandidate is not supported")}}},{}],156:[function(require,module,exports){"use strict";var ChromeRTCSessionDescription=require("../rtcsessiondescription/chrome");var EventTarget=require("../util/eventtarget");var inherits=require("util").inherits;var Latch=require("../util/latch");var MediaStream=require("../mediastream");var RTCRtpSenderShim=require("../rtcrtpsender");var sdpUtils=require("../util/sdp");var util=require("../util");var isIOSChrome=require("../util").isIOSChrome;var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";function ChromeRTCPeerConnection(configuration,constraints){if(!(this instanceof ChromeRTCPeerConnection)){return new ChromeRTCPeerConnection(configuration,constraints)}EventTarget.call(this);configuration=configuration||{};var newConfiguration=Object.assign(configuration.iceTransportPolicy?{iceTransports:configuration.iceTransportPolicy}:{},configuration);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"signalingstatechange");var sdpFormat=sdpUtils.getSdpFormat(newConfiguration.sdpSemantics);var peerConnection=new RTCPeerConnection(newConfiguration,constraints);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_localStream:{value:new MediaStream},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_sdpFormat:{value:sdpFormat},_senders:{value:new Map},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer?this._pendingLocalOffer:peerConnection.localDescription}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer?this._pendingRemoteOffer:peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.ontrack=function ontrack(){};if(typeof RTCPeerConnection.prototype.addTrack!=="function"){peerConnection.addStream(this._localStream)}util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(ChromeRTCPeerConnection,EventTarget);if(typeof RTCPeerConnection.prototype.addTrack!=="function"){ChromeRTCPeerConnection.prototype.addTrack=function addTrack(){var args=[].slice.call(arguments);var track=args[0];if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection is closed")}var sender=this._senders.get(track);if(sender&&sender.track){throw new Error("Cannot add MediaStreamTrack ["+track.id+", "+track.kind+"]: RTCPeerConnection already has it")}this._peerConnection.removeStream(this._localStream);this._localStream.addTrack(track);this._peerConnection.addStream(this._localStream);sender=new RTCRtpSenderShim(track);this._senders.set(track,sender);return sender};ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}var track=sender.track;if(!track){return}sender=this._senders.get(track);if(sender&&sender.track){sender.track=null;this._peerConnection.removeStream(this._localStream);this._localStream.removeTrack(track);this._peerConnection.addStream(this._localStream)}};ChromeRTCPeerConnection.prototype.getSenders=function getSenders(){return Array.from(this._senders.values())}}else{ChromeRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){if(this._peerConnection.signalingState==="closed"){throw new Error("Cannot remove MediaStreamTrack: RTCPeerConnection is closed")}try{this._peerConnection.removeTrack(sender)}catch(e){}}}ChromeRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var args=[].slice.call(arguments);var promise;var self=this;if(this.signalingState==="have-remote-offer"){promise=this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}else{promise=this._peerConnection.addIceCandidate(candidate)}return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._pendingLocalOffer=null;this._pendingRemoteOffer=null;this._peerConnection.close()}};ChromeRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;if(this._pendingRemoteOffer){promise=this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}else{promise=this._peerConnection.createAnswer().then(function(answer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:"answer",sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,answer.sdp)})})}return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var self=this;if(isIOSChrome()){if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}}var promise=this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new ChromeRTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._sdpFormat,self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};ChromeRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){dataChannelDict=shimDataChannelInit(dataChannelDict);var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};ChromeRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}var promise=setDescription(this,true,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};ChromeRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];this._rolledBackTracksToSSRCs.clear();var promise=setDescription(this,false,description);return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};util.delegateMethods(RTCPeerConnection.prototype,ChromeRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";var promise;if(!local&&pendingRemoteOffer&&description.type==="answer"){promise=setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(unwrap(description));promise=Promise.resolve();if(peerConnection.signalingState!==previousSignalingState){promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){promise=Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}else{clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);promise=Promise.resolve();promise.then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}}return promise||peerConnection._peerConnection[setLocalDescription](unwrap(description))}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function unwrap(description){if(description instanceof ChromeRTCSessionDescription){if(description._description){return description._description}}return new RTCSessionDescription(description)}function needsMaxPacketLifeTimeShim(){return"maxRetransmitTime"in RTCDataChannel.prototype&&!("maxPacketLifeTime"in RTCDataChannel.prototype)}function shimDataChannelInit(dataChannelDict){dataChannelDict=Object.assign({},dataChannelDict);if(needsMaxPacketLifeTimeShim()&&"maxPacketLifeTime"in dataChannelDict){dataChannelDict.maxRetransmitTime=dataChannelDict.maxPacketLifeTime}return dataChannelDict}function shimDataChannel(dataChannel){Object.defineProperty(dataChannel,"maxRetransmits",{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits});if(needsMaxPacketLifeTimeShim()){Object.defineProperty(dataChannel,"maxPacketLifeTime",{value:dataChannel.maxRetransmitTime===65535?null:dataChannel.maxRetransmitTime})}return dataChannel}function updateTrackIdsToSSRCs(sdpFormat,tracksToSSRCs,sdp){return sdpFormat==="unified"?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs(tracksToSSRCs,sdp):sdpUtils.updatePlanBTrackIdsToSSRCs(tracksToSSRCs,sdp)}module.exports=ChromeRTCPeerConnection},{"../mediastream":153,"../rtcrtpsender":160,"../rtcsessiondescription/chrome":161,"../util":165,"../util/eventtarget":164,"../util/latch":166,"../util/sdp":167,util:198}],157:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var FirefoxRTCSessionDescription=require("../rtcsessiondescription/firefox");var inherits=require("util").inherits;var updateTracksToSSRCs=require("../util/sdp").updateUnifiedPlanTrackIdsToSSRCs;var util=require("../util");var needsWorkaroundForBug1480277=typeof navigator==="object"&&navigator.userAgent&&(navigator.userAgent.match(/Firefox\/61/)||navigator.userAgent.match(/Firefox\/62/));function FirefoxRTCPeerConnection(configuration){if(!(this instanceof FirefoxRTCPeerConnection)){return new FirefoxRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"signalingstatechange");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_initiallyNegotiatedDtlsRole:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_rollingBack:{value:false,writable:true},_tracksToSSRCs:{value:new Map},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},localDescription:{enumerable:true,get:function(){return overwriteWithInitiallyNegotiatedDtlsRole(this._peerConnection.localDescription,this._initiallyNegotiatedDtlsRole)}},signalingState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.signalingState}}});var self=this;var previousSignalingState;peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(!self._rollingBack&&self.signalingState!==previousSignalingState){previousSignalingState=self.signalingState;var dispatchEventToSelf=self.dispatchEvent.apply.bind(self.dispatchEvent,self,arguments);if(self._isClosed){setTimeout(dispatchEventToSelf)}else{dispatchEventToSelf()}}});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(FirefoxRTCPeerConnection,EventTarget);Object.defineProperty(FirefoxRTCPeerConnection.prototype,"peerIdentity",{enumerable:true,value:Promise.resolve({idp:"",name:""})});if(needsWorkaroundForBug1480277){FirefoxRTCPeerConnection.prototype.addTrack=function addTrack(){var track=arguments[0];var sender=this._peerConnection.addTrack.apply(this._peerConnection,arguments);sender.replaceTrack(track);return sender}}FirefoxRTCPeerConnection.prototype.createAnswer=function createAnswer(){var args=[].slice.call(arguments);var promise;var self=this;promise=this._peerConnection.createAnswer().then(function createAnswerSucceeded(answer){saveInitiallyNegotiatedDtlsRole(self,answer);return overwriteWithInitiallyNegotiatedDtlsRole(answer,self._initiallyNegotiatedDtlsRole)});return typeof args[0]==="function"?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.createOffer=function createOffer(){var args=[].slice.call(arguments);var options=(args.length>1?args[2]:args[0])||{};var promise;var self=this;if(this.signalingState==="have-local-offer"||this.signalingState==="have-remote-offer"){var local=this.signalingState==="have-local-offer";promise=rollback(this,local,function rollbackSucceeded(){return self.createOffer(options)})}else{promise=self._peerConnection.createOffer(options)}promise=promise.then(function(offer){return new FirefoxRTCSessionDescription({type:offer.type,sdp:updateTracksToSSRCs(self._tracksToSSRCs,offer.sdp)})});return args.length>1?util.legacyPromise(promise,args[0],args[1]):promise};FirefoxRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;if(description&&description.type==="answer"&&this.signalingState==="have-local-offer"){promise=Promise.reject(new Error("Cannot set local answer in state have-local-offer"))}if(promise){return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise}return this._peerConnection.setLocalDescription.apply(this._peerConnection,args)};FirefoxRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var args=[].slice.call(arguments);var description=args[0];var promise;var self=this;if(description&&this.signalingState==="have-remote-offer"){if(description.type==="answer"){promise=Promise.reject(new Error("Cannot set remote answer in state have-remote-offer"))
55
+ }else if(description.type==="offer"){promise=rollback(this,false,function rollbackSucceeded(){return self._peerConnection.setRemoteDescription(description)})}}if(!promise){promise=this._peerConnection.setRemoteDescription(description)}promise=promise.then(function setRemoteDescriptionSucceeded(){saveInitiallyNegotiatedDtlsRole(self,description,true)});return args.length>1?util.legacyPromise(promise,args[1],args[2]):promise};FirefoxRTCPeerConnection.prototype.close=function close(){if(this.signalingState!=="closed"){this._isClosed=true;this._peerConnection.close()}};util.delegateMethods(RTCPeerConnection.prototype,FirefoxRTCPeerConnection.prototype,"_peerConnection");function rollback(peerConnection,local,onceRolledBack){var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";peerConnection._rollingBack=true;return peerConnection._peerConnection[setLocalDescription](new FirefoxRTCSessionDescription({type:"rollback"})).then(onceRolledBack).then(function onceRolledBackSucceeded(result){peerConnection._rollingBack=false;return result},function rollbackOrOnceRolledBackFailed(error){peerConnection._rollingBack=false;throw error})}function saveInitiallyNegotiatedDtlsRole(peerConnection,description,remote){if(peerConnection._initiallyNegotiatedDtlsRole||description.type==="offer"){return}var match=description.sdp.match(/a=setup:([a-z]+)/);if(!match){return}var dtlsRole=match[1];peerConnection._initiallyNegotiatedDtlsRole=remote?{active:"passive",passive:"active"}[dtlsRole]:dtlsRole}function overwriteWithInitiallyNegotiatedDtlsRole(description,dtlsRole){if(description&&description.type==="answer"&&dtlsRole){return new FirefoxRTCSessionDescription({type:description.type,sdp:description.sdp.replace(/a=setup:[a-z]+/g,"a=setup:"+dtlsRole)})}return description}module.exports=FirefoxRTCPeerConnection},{"../rtcsessiondescription/firefox":162,"../util":165,"../util/eventtarget":164,"../util/sdp":167,util:198}],158:[function(require,module,exports){"use strict";if(typeof RTCPeerConnection==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;case"safari":module.exports=require("./safari");break;default:module.exports=RTCPeerConnection;break}}else{module.exports=function RTCPeerConnection(){throw new Error("RTCPeerConnection is not supported")}}},{"../util":165,"./chrome":156,"./firefox":157,"./safari":159}],159:[function(require,module,exports){"use strict";var EventTarget=require("../util/eventtarget");var inherits=require("util").inherits;var Latch=require("../util/latch");var sdpUtils=require("../util/sdp");var util=require("../util");var isUnifiedPlan=sdpUtils.getSdpFormat()==="unified";var updateTrackIdsToSSRCs=isUnifiedPlan?sdpUtils.updateUnifiedPlanTrackIdsToSSRCs:sdpUtils.updatePlanBTrackIdsToSSRCs;function SafariRTCPeerConnection(configuration){if(!(this instanceof SafariRTCPeerConnection)){return new SafariRTCPeerConnection(configuration)}EventTarget.call(this);util.interceptEvent(this,"datachannel");util.interceptEvent(this,"iceconnectionstatechange");util.interceptEvent(this,"signalingstatechange");util.interceptEvent(this,"track");var peerConnection=new RTCPeerConnection(configuration);Object.defineProperties(this,{_appliedTracksToSSRCs:{value:new Map,writable:true},_audioTransceiver:{value:null,writable:true},_isClosed:{value:false,writable:true},_peerConnection:{value:peerConnection},_pendingLocalOffer:{value:null,writable:true},_pendingRemoteOffer:{value:null,writable:true},_rolledBackTracksToSSRCs:{value:new Map,writable:true},_signalingStateLatch:{value:new Latch},_tracksToSSRCs:{value:new Map,writable:true},_videoTransceiver:{value:null,writable:true},localDescription:{enumerable:true,get:function(){return this._pendingLocalOffer||this._peerConnection.localDescription}},iceConnectionState:{enumerable:true,get:function(){return this._isClosed?"closed":this._peerConnection.iceConnectionState}},iceGatheringState:{enumerable:true,get:function(){return this._isClosed?"complete":this._peerConnection.iceGatheringState}},remoteDescription:{enumerable:true,get:function(){return this._pendingRemoteOffer||this._peerConnection.remoteDescription}},signalingState:{enumerable:true,get:function(){if(this._isClosed){return"closed"}else if(this._pendingLocalOffer){return"have-local-offer"}else if(this._pendingRemoteOffer){return"have-remote-offer"}return this._peerConnection.signalingState}}});var self=this;peerConnection.addEventListener("datachannel",function ondatachannel(event){shimDataChannel(event.channel);self.dispatchEvent(event)});peerConnection.addEventListener("iceconnectionstatechange",function oniceconnectionstatechange(){if(self._isClosed){return}self.dispatchEvent.apply(self,arguments)});peerConnection.addEventListener("signalingstatechange",function onsignalingstatechange(){if(self._isClosed){return}if(peerConnection.signalingState==="stable"){self._appliedTracksToSSRCs=new Map(self._tracksToSSRCs)}if(!self._pendingLocalOffer&&!self._pendingRemoteOffer){self.dispatchEvent.apply(self,arguments)}});peerConnection.addEventListener("track",function ontrack(event){self._pendingRemoteOffer=null;self.dispatchEvent(event)});util.proxyProperties(RTCPeerConnection.prototype,this,peerConnection)}inherits(SafariRTCPeerConnection,EventTarget);SafariRTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(candidate){var self=this;if(this.signalingState==="have-remote-offer"){return this._signalingStateLatch.when("low").then(function signalingStatesResolved(){return self._peerConnection.addIceCandidate(candidate)})}return this._peerConnection.addIceCandidate(candidate)};SafariRTCPeerConnection.prototype.createOffer=function createOffer(options){options=Object.assign({},options);var self=this;if(options.offerToReceiveVideo&&!this._audioTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"audio"))){delete options.offerToReceiveAudio;try{this._audioTransceiver=isUnifiedPlan?this.addTransceiver("audio",{direction:"recvonly"}):this.addTransceiver("audio")}catch(e){return Promise.reject(e)}}if(options.offerToReceiveVideo&&!this._videoTransceiver&&!(isUnifiedPlan&&hasReceiversForTracksOfKind(this,"video"))){delete options.offerToReceiveVideo;try{this._videoTransceiver=isUnifiedPlan?this.addTransceiver("video",{direction:"recvonly"}):this.addTransceiver("video")}catch(e){return Promise.reject(e)}}return this._peerConnection.createOffer(options).then(function(offer){self._rolledBackTracksToSSRCs.clear();return new RTCSessionDescription({type:offer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,offer.sdp)})})};SafariRTCPeerConnection.prototype.createAnswer=function createAnswer(options){var self=this;if(this._pendingRemoteOffer){return this._peerConnection.setRemoteDescription(this._pendingRemoteOffer).then(function setRemoteDescriptionSucceeded(){self._signalingStateLatch.lower();return self._peerConnection.createAnswer()}).then(function createAnswerSucceeded(answer){self._pendingRemoteOffer=null;self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer},function setRemoteDescriptionOrCreateAnswerFailed(error){self._pendingRemoteOffer=null;throw error})}return this._peerConnection.createAnswer(options).then(function createAnswerSucceeded(answer){self._rolledBackTracksToSSRCs.clear();return isUnifiedPlan?new RTCSessionDescription({type:answer.type,sdp:updateTrackIdsToSSRCs(self._tracksToSSRCs,answer.sdp)}):answer})};SafariRTCPeerConnection.prototype.createDataChannel=function createDataChannel(label,dataChannelDict){var dataChannel=this._peerConnection.createDataChannel(label,dataChannelDict);shimDataChannel(dataChannel);return dataChannel};SafariRTCPeerConnection.prototype.removeTrack=function removeTrack(sender){sender.replaceTrack(null);this._peerConnection.removeTrack(sender)};SafariRTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(description){if(this._rolledBackTracksToSSRCs.size>0){this._tracksToSSRCs=new Map(this._rolledBackTracksToSSRCs);this._rolledBackTracksToSSRCs.clear()}return setDescription(this,true,description)};SafariRTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(description){this._rolledBackTracksToSSRCs.clear();return setDescription(this,false,description)};SafariRTCPeerConnection.prototype.close=function close(){if(this._isClosed){return}this._isClosed=true;this._peerConnection.close();var self=this;setTimeout(function(){self.dispatchEvent(new Event("iceconnectionstatechange"));self.dispatchEvent(new Event("signalingstatechange"))})};util.delegateMethods(RTCPeerConnection.prototype,SafariRTCPeerConnection.prototype,"_peerConnection");function setDescription(peerConnection,local,description){function setPendingLocalOffer(offer){if(local){peerConnection._pendingLocalOffer=offer}else{peerConnection._pendingRemoteOffer=offer}}function clearPendingLocalOffer(){if(local){peerConnection._pendingLocalOffer=null}else{peerConnection._pendingRemoteOffer=null}}var pendingLocalOffer=local?peerConnection._pendingLocalOffer:peerConnection._pendingRemoteOffer;var pendingRemoteOffer=local?peerConnection._pendingRemoteOffer:peerConnection._pendingLocalOffer;var intermediateState=local?"have-local-offer":"have-remote-offer";var setLocalDescription=local?"setLocalDescription":"setRemoteDescription";if(!local&&pendingRemoteOffer&&description.type==="answer"){return setRemoteAnswer(peerConnection,description)}else if(description.type==="offer"){if(peerConnection.signalingState!==intermediateState&&peerConnection.signalingState!=="stable"){return Promise.reject(new Error("Cannot set "+(local?"local":"remote")+" offer in state "+peerConnection.signalingState))}if(!pendingLocalOffer&&peerConnection._signalingStateLatch.state==="low"){peerConnection._signalingStateLatch.raise()}var previousSignalingState=peerConnection.signalingState;setPendingLocalOffer(description);if(peerConnection.signalingState!==previousSignalingState){return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return Promise.resolve()}else if(description.type==="rollback"){if(peerConnection.signalingState!==intermediateState){return Promise.reject(new Error("Cannot rollback "+(local?"local":"remote")+" description in "+peerConnection.signalingState))}clearPendingLocalOffer();peerConnection._rolledBackTracksToSSRCs=new Map(peerConnection._tracksToSSRCs);peerConnection._tracksToSSRCs=new Map(peerConnection._appliedTracksToSSRCs);return Promise.resolve().then(function dispatchSignalingStateChangeEvent(){peerConnection.dispatchEvent(new Event("signalingstatechange"))})}return peerConnection._peerConnection[setLocalDescription](description)}function setRemoteAnswer(peerConnection,answer){var pendingLocalOffer=peerConnection._pendingLocalOffer;return peerConnection._peerConnection.setLocalDescription(pendingLocalOffer).then(function setLocalOfferSucceeded(){peerConnection._pendingLocalOffer=null;return peerConnection.setRemoteDescription(answer)}).then(function setRemoteAnswerSucceeded(){peerConnection._signalingStateLatch.lower()})}function hasReceiversForTracksOfKind(peerConnection,kind){return!!peerConnection.getTransceivers().find(function(transceiver){return transceiver.receiver&&transceiver.receiver.track&&transceiver.receiver.track.kind===kind})}function shimDataChannel(dataChannel){return Object.defineProperties(dataChannel,{maxPacketLifeTime:{value:dataChannel.maxPacketLifeTime===65535?null:dataChannel.maxPacketLifeTime},maxRetransmits:{value:dataChannel.maxRetransmits===65535?null:dataChannel.maxRetransmits}})}module.exports=SafariRTCPeerConnection},{"../util":165,"../util/eventtarget":164,"../util/latch":166,"../util/sdp":167,util:198}],160:[function(require,module,exports){"use strict";function RTCRtpSenderShim(track){Object.defineProperties(this,{track:{enumerable:true,value:track,writable:true}})}module.exports=RTCRtpSenderShim},{}],161:[function(require,module,exports){"use strict";function ChromeRTCSessionDescription(descriptionInitDict){if(!(this instanceof ChromeRTCSessionDescription)){return new ChromeRTCSessionDescription(descriptionInitDict)}var description=descriptionInitDict&&descriptionInitDict.type==="rollback"?null:new RTCSessionDescription(descriptionInitDict);Object.defineProperties(this,{_description:{get:function(){return description}},sdp:{enumerable:true,value:description?description.sdp:descriptionInitDict.sdp},type:{enumerable:true,value:description?description.type:descriptionInitDict.type}})}module.exports=ChromeRTCSessionDescription},{}],162:[function(require,module,exports){"use strict";module.exports=RTCSessionDescription},{}],163:[function(require,module,exports){"use strict";if(typeof RTCSessionDescription==="function"){var guessBrowser=require("../util").guessBrowser;switch(guessBrowser()){case"chrome":module.exports=require("./chrome");break;case"firefox":module.exports=require("./firefox");break;default:module.exports=RTCSessionDescription;break}}else{module.exports=function RTCSessionDescription(){throw new Error("RTCSessionDescription is not supported")}}},{"../util":165,"./chrome":161,"./firefox":162}],164:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter;function EventTarget(){Object.defineProperties(this,{_eventEmitter:{value:new EventEmitter}})}EventTarget.prototype.dispatchEvent=function dispatchEvent(event){return this._eventEmitter.emit(event.type,event)};EventTarget.prototype.addEventListener=function addEventListener(){return this._eventEmitter.addListener.apply(this._eventEmitter,arguments)};EventTarget.prototype.removeEventListener=function removeEventListener(){return this._eventEmitter.removeListener.apply(this._eventEmitter,arguments)};module.exports=EventTarget},{events:179}],165:[function(require,module,exports){"use strict";function defer(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject});return deferred}function delegateMethod(source,wrapper,target,methodName){if(methodName in wrapper){return}else if(methodName.match(/^on[a-z]+$/)){return}var isProperty=false;try{var propDesc=Object.getOwnPropertyDescriptor(source,methodName);isProperty=propDesc&&!!propDesc.get}catch(error){}if(isProperty){return}var type;try{type=typeof source[methodName]}catch(error){}if(type!=="function"){return}wrapper[methodName]=function(){return this[target][methodName].apply(this[target],arguments)}}function delegateMethods(source,wrapper,target){for(var methodName in source){delegateMethod(source,wrapper,target,methodName)}}function difference(list1,list2){list1=Array.isArray(list1)?new Set(list1):new Set(list1.values());list2=Array.isArray(list2)?new Set(list2):new Set(list2.values());var difference=new Set;list1.forEach(function(item){if(!list2.has(item)){difference.add(item)}});return difference}function flatMap(list,mapFn){var listArray=list instanceof Map||list instanceof Set?Array.from(list.values()):list;return listArray.reduce(function(flattened,item){var mapped=mapFn(item);return flattened.concat(mapped)},[])}function getUserAgent(){return typeof navigator!=="undefined"&&typeof navigator.userAgent==="string"?navigator.userAgent:null}function guessBrowser(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}if(/Chrome|CriOS/.test(userAgent)){return"chrome"}if(/Firefox|FxiOS/.test(userAgent)){return"firefox"}if(/Safari/.test(userAgent)){return"safari"}return null}function guessBrowserVersion(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}var prefix={chrome:"Chrome|CriOS",firefox:"Firefox|FxiOS",safari:"Version"}[guessBrowser(userAgent)];if(!prefix){return null}var regex=new RegExp("("+prefix+")/([^\\s]+)");var match=(userAgent.match(regex)||[])[2];if(!match){return null}var versions=match.split(".").map(Number);return{major:isNaN(versions[0])?null:versions[0],minor:isNaN(versions[1])?null:versions[1]}}function isIOSChrome(userAgent){if(typeof userAgent==="undefined"){userAgent=getUserAgent()}return/Mobi/.test(userAgent)&&guessBrowser()==="chrome"&&/iPad|iPhone|iPod/.test(userAgent)}function interceptEvent(target,type){var currentListener=null;Object.defineProperty(target,"on"+type,{get:function(){return currentListener},set:function(newListener){if(currentListener){this.removeEventListener(type,currentListener)}if(typeof newListener==="function"){currentListener=newListener;this.addEventListener(type,currentListener)}else{currentListener=null}}})}function legacyPromise(promise,onSuccess,onFailure){if(onSuccess){return promise.then(function(result){onSuccess(result)},function(error){onFailure(error)})}return promise}function makeUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0;var v=c==="x"?r:r&3|8;return v.toString(16)})}function proxyProperties(source,wrapper,target){Object.getOwnPropertyNames(source).forEach(function(propertyName){proxyProperty(source,wrapper,target,propertyName)})}function proxyProperty(source,wrapper,target,propertyName){if(propertyName in wrapper){return}else if(propertyName.match(/^on[a-z]+$/)){Object.defineProperty(wrapper,propertyName,{value:null,writable:true});target.addEventListener(propertyName.slice(2),function(){wrapper.dispatchEvent.apply(wrapper,arguments)});return}Object.defineProperty(wrapper,propertyName,{enumerable:true,get:function(){return target[propertyName]}})}function support(){return typeof navigator==="object"&&typeof navigator.mediaDevices==="object"&&typeof navigator.mediaDevices.getUserMedia==="function"&&typeof RTCPeerConnection==="function"}exports.defer=defer;exports.delegateMethods=delegateMethods;exports.difference=difference;exports.flatMap=flatMap;exports.guessBrowser=guessBrowser;exports.guessBrowserVersion=guessBrowserVersion;exports.isIOSChrome=isIOSChrome;exports.interceptEvent=interceptEvent;exports.legacyPromise=legacyPromise;exports.makeUUID=makeUUID;exports.proxyProperties=proxyProperties;exports.support=support},{}],166:[function(require,module,exports){"use strict";var defer=require("./").defer;var states={high:new Set(["low"]),low:new Set(["high"])};function Latch(initialState){if(!(this instanceof Latch)){return new Latch(initialState)}var state=initialState||"low";Object.defineProperties(this,{_state:{set:function(_state){if(state!==_state){state=_state;var whenDeferreds=this._whenDeferreds.get(state);whenDeferreds.forEach(function(deferred){deferred.resolve(this)},this);whenDeferreds.clear()}},get:function(){return state}},_whenDeferreds:{value:new Map([["high",new Set],["low",new Set]])},state:{enumerable:true,get:function(){return this._state}}})}Latch.prototype.lower=function lower(){return this.transition("low")};Latch.prototype.raise=function raise(){return this.transition("high")};Latch.prototype.transition=function transition(newState){if(!states[this.state].has(newState)){throw createUnreachableStateError(this.state,newState)}this._state=newState;return this};Latch.prototype.when=function when(state){if(this.state===state){return Promise.resolve(this)}if(!states[this.state].has(state)){return Promise.reject(createUnreachableStateError(this.state,state))}var deferred=defer();this._whenDeferreds.get(state).add(deferred);return deferred.promise};function createUnreachableStateError(from,to){return new Error('Cannot transition from "'+from+'" to "'+to+'"')}module.exports=Latch},{"./":165}],167:[function(require,module,exports){"use strict";var flatMap=require("./").flatMap;var guessBrowser=require("./").guessBrowser;var isSdpSemanticsSupported=null;function checkIfSdpSemanticsIsSupported(){if(typeof isSdpSemanticsSupported==="boolean"){return isSdpSemanticsSupported}if(typeof RTCPeerConnection==="undefined"){isSdpSemanticsSupported=false;return isSdpSemanticsSupported}try{new RTCPeerConnection({sdpSemantics:"foo"});isSdpSemanticsSupported=false}catch(e){isSdpSemanticsSupported=true}return isSdpSemanticsSupported}var chromeSdpFormat=null;function getChromeDefaultSdpFormat(){if(!chromeSdpFormat){if(typeof RTCPeerConnection!=="undefined"&&"addTransceiver"in RTCPeerConnection.prototype){try{(new RTCPeerConnection).addTransceiver("audio");chromeSdpFormat="unified"}catch(e){chromeSdpFormat="planb"}}else{chromeSdpFormat="planb"}}return chromeSdpFormat}function getChromeSdpFormat(sdpSemantics){if(!sdpSemantics||!checkIfSdpSemanticsIsSupported()){return getChromeDefaultSdpFormat()}return{"plan-b":"planb","unified-plan":"unified"}[sdpSemantics]}function getSafariSdpFormat(){return typeof RTCRtpTransceiver!=="undefined"&&"currentDirection"in RTCRtpTransceiver.prototype?"unified":"planb"}function getSdpFormat(sdpSemantics){return{chrome:getChromeSdpFormat(sdpSemantics),firefox:"unified",safari:getSafariSdpFormat()}[guessBrowser()]||null}function getMatches(pattern,lines){var matches=lines.match(new RegExp(pattern,"gm"))||[];return matches.reduce(function(results,line){var match=line.match(new RegExp(pattern));return match?results.add(match[1]):results},new Set)}function getTrackIds(pattern,sdp){return getMatches(pattern,sdp)}function getPlanBTrackIds(sdp){return getTrackIds("^a=ssrc:[0-9]+ +msid:.+ +(.+) *$",sdp)}function getUnifiedPlanTrackIds(sdp){return getTrackIds("^a=msid:.+ +(.+) *$",sdp)}function getPlanBSSRCs(sdp,trackId){var pattern="^a=ssrc:([0-9]+) +msid:[^ ]+ +"+trackId+" *$";return getMatches(pattern,sdp)}function getMediaSections(sdp,kind,direction){kind=kind||".*";direction=direction||".*";return sdp.split("\r\nm=").slice(1).map(function(mediaSection){return"m="+mediaSection}).filter(function(mediaSection){var kindPattern=new RegExp("m="+kind,"gm");var directionPattern=new RegExp("a="+direction,"gm");return kindPattern.test(mediaSection)&&directionPattern.test(mediaSection)})}function getMediaSectionSSRCs(mediaSection){return Array.from(getMatches("^a=ssrc:([0-9]+) +.*$",mediaSection))}function getUnifiedPlanSSRCs(sdp,trackId){var mediaSections=getMediaSections(sdp);var msidAttrRegExp=new RegExp("^a=msid:[^ ]+ +"+trackId+" *$","gm");var matchingMediaSections=mediaSections.filter(function(mediaSection){return mediaSection.match(msidAttrRegExp)});return new Set(flatMap(matchingMediaSections,getMediaSectionSSRCs))}function getTrackIdsToSSRCs(getTrackIds,getSSRCs,sdp){return new Map(Array.from(getTrackIds(sdp)).map(function(trackId){return[trackId,getSSRCs(sdp,trackId)]}))}function getPlanBTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getPlanBTrackIds,getPlanBSSRCs,sdp)}function getUnifiedPlanTrackIdsToSSRCs(sdp){return getTrackIdsToSSRCs(getUnifiedPlanTrackIds,getUnifiedPlanSSRCs,sdp)}function updateTrackIdsToSSRCs(getTrackIdsToSSRCs,trackIdsToSSRCs,sdp){var newTrackIdsToSSRCs=getTrackIdsToSSRCs(sdp);var newSSRCsToOldSSRCs=new Map;newTrackIdsToSSRCs.forEach(function(ssrcs,trackId){if(!trackIdsToSSRCs.has(trackId)){trackIdsToSSRCs.set(trackId,ssrcs);return}var oldSSRCs=Array.from(trackIdsToSSRCs.get(trackId));var newSSRCs=Array.from(ssrcs);oldSSRCs.forEach(function(oldSSRC,i){var newSSRC=newSSRCs[i];newSSRCsToOldSSRCs.set(newSSRC,oldSSRC);var pattern="^a=ssrc:"+newSSRC+" (.*)$";var replacement="a=ssrc:"+oldSSRC+" $1";sdp=sdp.replace(new RegExp(pattern,"gm"),replacement)})});var pattern="^(a=ssrc-group:[^ ]+ +)(.*)$";var matches=sdp.match(new RegExp(pattern,"gm"))||[];matches.forEach(function(line){var match=line.match(new RegExp(pattern));if(!match){return}var prefix=match[1];var newSSRCs=match[2];var oldSSRCs=newSSRCs.split(" ").map(function(newSSRC){var oldSSRC=newSSRCsToOldSSRCs.get(newSSRC);return oldSSRC?oldSSRC:newSSRC}).join(" ");sdp=sdp.replace(match[0],prefix+oldSSRCs)});return sdp}function updatePlanBTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getPlanBTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}function updateUnifiedPlanTrackIdsToSSRCs(trackIdsToSSRCs,sdp){return updateTrackIdsToSSRCs(getUnifiedPlanTrackIdsToSSRCs,trackIdsToSSRCs,sdp)}exports.getSdpFormat=getSdpFormat;exports.getMediaSections=getMediaSections;exports.getPlanBTrackIds=getPlanBTrackIds;exports.getUnifiedPlanTrackIds=getUnifiedPlanTrackIds;exports.getPlanBSSRCs=getPlanBSSRCs;exports.getUnifiedPlanSSRCs=getUnifiedPlanSSRCs;exports.updatePlanBTrackIdsToSSRCs=updatePlanBTrackIdsToSSRCs;exports.updateUnifiedPlanTrackIdsToSSRCs=updateUnifiedPlanTrackIdsToSSRCs},{"./":165}],168:[function(require,module,exports){module.exports={name:"@twilio/webrtc",version:"4.5.2",description:"WebRTC-related APIs and shims used by twilio-video.js",scripts:{build:"npm-run-all clean lint test",clean:"rimraf coverage",lint:"eslint ./lib","test:unit":"istanbul cover node_modules/mocha/bin/_mocha -- ./test/unit/index.js","test:integration:native":"karma start karma/integration.conf.js","test:integration:adapter":"karma start karma/integration.adapter.conf.js","test:integration":"npm-run-all test:integration:*",test:"npm-run-all test:*"},repository:{type:"git",url:"git+https://github.com/twilio/twilio-webrtc.js.git"},keywords:["shim","twilio","video","webrtc"],author:"Manjesh Malavalli <mmalavalli@twilio.com>",contributors:["Mark Roberts <mroberts@twilio.com>","Ryan Rowland <rrowland@twilio.com>","Makarand Patwardhan <mpatwardhan@twilio.com>"],license:"BSD-3-Clause",main:"./lib/index.js",bugs:{url:"https://github.com/twilio/twilio-webrtc.js/issues"},homepage:"https://github.com/twilio/twilio-webrtc.js#readme",devDependencies:{browserify:"^14.4.0",electron:"9.4.0",envify:"^4.1.0",eslint:"^4.4.1","is-docker":"^2.0.0",istanbul:"^0.4.5",karma:"^6.3.4","karma-browserify":"^8.1.0","karma-chrome-launcher":"^2.2.0","karma-edgium-launcher":"^4.0.0-0","karma-electron":"^6.1.0","karma-firefox-launcher":"^1.0.1","karma-htmlfile-reporter":"^0.3.8","karma-junit-reporter":"^1.2.0","karma-mocha":"^2.0.1","karma-safari-launcher":"~0.1","karma-spec-reporter":"0.0.31",mocha:"^9.1.1","npm-run-all":"^4.0.2",rimraf:"^2.6.1","simple-git":"^2.4.0","twilio-release-tool":"^1.0.0",watchify:"^4.0.0","webrtc-adapter":"^6.4.8"}}},{}],169:[function(require,module,exports){(function(global){(function(){"use strict";var possibleNames=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"];var g=typeof globalThis==="undefined"?global:globalThis;module.exports=function availableTypedArrays(){var out=[];for(var i=0;i<possibleNames.length;i++){if(typeof g[possibleNames[i]]==="function"){out[out.length]=possibleNames[i]}}return out}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],170:[function(require,module,exports){var Backoff=require("./lib/backoff");var ExponentialBackoffStrategy=require("./lib/strategy/exponential");var FibonacciBackoffStrategy=require("./lib/strategy/fibonacci");var FunctionCall=require("./lib/function_call.js");module.exports.Backoff=Backoff;module.exports.FunctionCall=FunctionCall;module.exports.FibonacciStrategy=FibonacciBackoffStrategy;module.exports.ExponentialStrategy=ExponentialBackoffStrategy;module.exports.fibonacci=function(options){return new Backoff(new FibonacciBackoffStrategy(options))};module.exports.exponential=function(options){return new Backoff(new ExponentialBackoffStrategy(options))};module.exports.call=function(fn,vargs,callback){var args=Array.prototype.slice.call(arguments);fn=args[0];vargs=args.slice(1,args.length-1);callback=args[args.length-1];return new FunctionCall(fn,vargs,callback)}},{"./lib/backoff":171,"./lib/function_call.js":172,"./lib/strategy/exponential":173,"./lib/strategy/fibonacci":174}],171:[function(require,module,exports){var events=require("events");var precond=require("precond");var util=require("util");function Backoff(backoffStrategy){events.EventEmitter.call(this);this.backoffStrategy_=backoffStrategy;this.maxNumberOfRetry_=-1;this.backoffNumber_=0;this.backoffDelay_=0;this.timeoutID_=-1;this.handlers={backoff:this.onBackoff_.bind(this)}}util.inherits(Backoff,events.EventEmitter);Backoff.prototype.failAfter=function(maxNumberOfRetry){precond.checkArgument(maxNumberOfRetry>0,"Expected a maximum number of retry greater than 0 but got %s.",maxNumberOfRetry);this.maxNumberOfRetry_=maxNumberOfRetry};Backoff.prototype.backoff=function(err){precond.checkState(this.timeoutID_===-1,"Backoff in progress.");if(this.backoffNumber_===this.maxNumberOfRetry_){this.emit("fail",err);this.reset()}else{this.backoffDelay_=this.backoffStrategy_.next();this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_);this.emit("backoff",this.backoffNumber_,this.backoffDelay_,err)}};Backoff.prototype.onBackoff_=function(){this.timeoutID_=-1;this.emit("ready",this.backoffNumber_,this.backoffDelay_);this.backoffNumber_++};Backoff.prototype.reset=function(){this.backoffNumber_=0;this.backoffStrategy_.reset();clearTimeout(this.timeoutID_);this.timeoutID_=-1};module.exports=Backoff},{events:179,precond:192,util:198}],172:[function(require,module,exports){var events=require("events");var precond=require("precond");var util=require("util");var Backoff=require("./backoff");var FibonacciBackoffStrategy=require("./strategy/fibonacci");function FunctionCall(fn,args,callback){events.EventEmitter.call(this);precond.checkIsFunction(fn,"Expected fn to be a function.");precond.checkIsArray(args,"Expected args to be an array.");precond.checkIsFunction(callback,"Expected callback to be a function.");this.function_=fn;this.arguments_=args;this.callback_=callback;this.lastResult_=[];this.numRetries_=0;this.backoff_=null;this.strategy_=null;this.failAfter_=-1;this.retryPredicate_=FunctionCall.DEFAULT_RETRY_PREDICATE_;this.state_=FunctionCall.State_.PENDING}util.inherits(FunctionCall,events.EventEmitter);FunctionCall.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3};FunctionCall.DEFAULT_RETRY_PREDICATE_=function(err){return true};FunctionCall.prototype.isPending=function(){return this.state_==FunctionCall.State_.PENDING};FunctionCall.prototype.isRunning=function(){return this.state_==FunctionCall.State_.RUNNING};FunctionCall.prototype.isCompleted=function(){return this.state_==FunctionCall.State_.COMPLETED};FunctionCall.prototype.isAborted=function(){return this.state_==FunctionCall.State_.ABORTED};FunctionCall.prototype.setStrategy=function(strategy){precond.checkState(this.isPending(),"FunctionCall in progress.");this.strategy_=strategy;return this};FunctionCall.prototype.retryIf=function(retryPredicate){precond.checkState(this.isPending(),"FunctionCall in progress.");this.retryPredicate_=retryPredicate;return this};FunctionCall.prototype.getLastResult=function(){return this.lastResult_.concat()};FunctionCall.prototype.getNumRetries=function(){return this.numRetries_};FunctionCall.prototype.failAfter=function(maxNumberOfRetry){precond.checkState(this.isPending(),"FunctionCall in progress.");this.failAfter_=maxNumberOfRetry;return this};FunctionCall.prototype.abort=function(){if(this.isCompleted()||this.isAborted()){return}if(this.isRunning()){this.backoff_.reset()}this.state_=FunctionCall.State_.ABORTED;this.lastResult_=[new Error("Backoff aborted.")];this.emit("abort");this.doCallback_()};FunctionCall.prototype.start=function(backoffFactory){precond.checkState(!this.isAborted(),"FunctionCall is aborted.");precond.checkState(this.isPending(),"FunctionCall already started.");var strategy=this.strategy_||new FibonacciBackoffStrategy;this.backoff_=backoffFactory?backoffFactory(strategy):new Backoff(strategy);this.backoff_.on("ready",this.doCall_.bind(this,true));this.backoff_.on("fail",this.doCallback_.bind(this));this.backoff_.on("backoff",this.handleBackoff_.bind(this));if(this.failAfter_>0){this.backoff_.failAfter(this.failAfter_)}this.state_=FunctionCall.State_.RUNNING;this.doCall_(false)}
56
+ ;FunctionCall.prototype.doCall_=function(isRetry){if(isRetry){this.numRetries_++}var eventArgs=["call"].concat(this.arguments_);events.EventEmitter.prototype.emit.apply(this,eventArgs);var callback=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(callback))};FunctionCall.prototype.doCallback_=function(){this.callback_.apply(null,this.lastResult_)};FunctionCall.prototype.handleFunctionCallback_=function(){if(this.isAborted()){return}var args=Array.prototype.slice.call(arguments);this.lastResult_=args;events.EventEmitter.prototype.emit.apply(this,["callback"].concat(args));var err=args[0];if(err&&this.retryPredicate_(err)){this.backoff_.backoff(err)}else{this.state_=FunctionCall.State_.COMPLETED;this.doCallback_()}};FunctionCall.prototype.handleBackoff_=function(number,delay,err){this.emit("backoff",number,delay,err)};module.exports=FunctionCall},{"./backoff":171,"./strategy/fibonacci":174,events:179,precond:192,util:198}],173:[function(require,module,exports){var util=require("util");var precond=require("precond");var BackoffStrategy=require("./strategy");function ExponentialBackoffStrategy(options){BackoffStrategy.call(this,options);this.backoffDelay_=0;this.nextBackoffDelay_=this.getInitialDelay();this.factor_=ExponentialBackoffStrategy.DEFAULT_FACTOR;if(options&&options.factor!==undefined){precond.checkArgument(options.factor>1,"Exponential factor should be greater than 1 but got %s.",options.factor);this.factor_=options.factor}}util.inherits(ExponentialBackoffStrategy,BackoffStrategy);ExponentialBackoffStrategy.DEFAULT_FACTOR=2;ExponentialBackoffStrategy.prototype.next_=function(){this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay());this.nextBackoffDelay_=this.backoffDelay_*this.factor_;return this.backoffDelay_};ExponentialBackoffStrategy.prototype.reset_=function(){this.backoffDelay_=0;this.nextBackoffDelay_=this.getInitialDelay()};module.exports=ExponentialBackoffStrategy},{"./strategy":175,precond:192,util:198}],174:[function(require,module,exports){var util=require("util");var BackoffStrategy=require("./strategy");function FibonacciBackoffStrategy(options){BackoffStrategy.call(this,options);this.backoffDelay_=0;this.nextBackoffDelay_=this.getInitialDelay()}util.inherits(FibonacciBackoffStrategy,BackoffStrategy);FibonacciBackoffStrategy.prototype.next_=function(){var backoffDelay=Math.min(this.nextBackoffDelay_,this.getMaxDelay());this.nextBackoffDelay_+=this.backoffDelay_;this.backoffDelay_=backoffDelay;return backoffDelay};FibonacciBackoffStrategy.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay();this.backoffDelay_=0};module.exports=FibonacciBackoffStrategy},{"./strategy":175,util:198}],175:[function(require,module,exports){var events=require("events");var util=require("util");function isDef(value){return value!==undefined&&value!==null}function BackoffStrategy(options){options=options||{};if(isDef(options.initialDelay)&&options.initialDelay<1){throw new Error("The initial timeout must be greater than 0.")}else if(isDef(options.maxDelay)&&options.maxDelay<1){throw new Error("The maximal timeout must be greater than 0.")}this.initialDelay_=options.initialDelay||100;this.maxDelay_=options.maxDelay||1e4;if(this.maxDelay_<=this.initialDelay_){throw new Error("The maximal backoff delay must be "+"greater than the initial backoff delay.")}if(isDef(options.randomisationFactor)&&(options.randomisationFactor<0||options.randomisationFactor>1)){throw new Error("The randomisation factor must be between 0 and 1.")}this.randomisationFactor_=options.randomisationFactor||0}BackoffStrategy.prototype.getMaxDelay=function(){return this.maxDelay_};BackoffStrategy.prototype.getInitialDelay=function(){return this.initialDelay_};BackoffStrategy.prototype.next=function(){var backoffDelay=this.next_();var randomisationMultiple=1+Math.random()*this.randomisationFactor_;var randomizedDelay=Math.round(backoffDelay*randomisationMultiple);return randomizedDelay};BackoffStrategy.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")};BackoffStrategy.prototype.reset=function(){this.reset_()};BackoffStrategy.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")};module.exports=BackoffStrategy},{events:179,util:198}],176:[function(require,module,exports){"use strict";var GetIntrinsic=require("get-intrinsic");var callBind=require("./");var $indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function callBoundIntrinsic(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);if(typeof intrinsic==="function"&&$indexOf(name,".prototype.")>-1){return callBind(intrinsic)}return intrinsic}},{"./":177,"get-intrinsic":183}],177:[function(require,module,exports){"use strict";var bind=require("function-bind");var GetIntrinsic=require("get-intrinsic");var $apply=GetIntrinsic("%Function.prototype.apply%");var $call=GetIntrinsic("%Function.prototype.call%");var $reflectApply=GetIntrinsic("%Reflect.apply%",true)||bind.call($call,$apply);var $gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",true);var $defineProperty=GetIntrinsic("%Object.defineProperty%",true);var $max=GetIntrinsic("%Math.max%");if($defineProperty){try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}}module.exports=function callBind(originalFunction){var func=$reflectApply(bind,$call,arguments);if($gOPD&&$defineProperty){var desc=$gOPD(func,"length");if(desc.configurable){$defineProperty(func,"length",{value:1+$max(0,originalFunction.length-(arguments.length-1))})}}return func};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments)};if($defineProperty){$defineProperty(module.exports,"apply",{value:applyBind})}else{module.exports.apply=applyBind}},{"function-bind":182,"get-intrinsic":183}],178:[function(require,module,exports){"use strict";var GetIntrinsic=require("get-intrinsic");var $gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",true);if($gOPD){try{$gOPD([],"length")}catch(e){$gOPD=null}}module.exports=$gOPD},{"get-intrinsic":183}],179:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i<arguments.length;i++)args.push(arguments[i]);var doError=type==="error";var events=this._events;if(events!==undefined)doError=doError&&events.error===undefined;else if(!doError)return false;if(doError){var er;if(args.length>0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)ReflectApply(listeners[i],this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;checkListener(listener);events=target._events;if(events===undefined){events=target._events=Object.create(null);target._eventsCount=0}else{if(events.newListener!==undefined){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(existing===undefined){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else if(prepend){existing.unshift(listener)}else{existing.push(listener)}m=_getMaxListeners(target);if(m>0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners!==undefined){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver);reject(err)}function resolver(){if(typeof emitter.removeListener==="function"){emitter.removeListener("error",errorListener)}resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:true});if(name!=="error"){addErrorHandlerIfEventEmitter(emitter,errorListener,{once:true})}})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){if(typeof emitter.on==="function"){eventTargetAgnosticAddListener(emitter,"error",handler,flags)}}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if(typeof emitter.on==="function"){if(flags.once){emitter.once(name,listener)}else{emitter.on(name,listener)}}else if(typeof emitter.addEventListener==="function"){emitter.addEventListener(name,function wrapListener(arg){if(flags.once){emitter.removeEventListener(name,wrapListener)}listener(arg)})}else{throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter)}}},{}],180:[function(require,module,exports){var hasOwn=Object.prototype.hasOwnProperty;var toString=Object.prototype.toString;module.exports=function forEach(obj,fn,ctx){if(toString.call(fn)!=="[object Function]"){throw new TypeError("iterator must be a function")}var l=obj.length;if(l===+l){for(var i=0;i<l;i++){fn.call(ctx,obj[i],i,obj)}}else{for(var k in obj){if(hasOwn.call(obj,k)){fn.call(ctx,obj[k],k,obj)}}}}},{}],181:[function(require,module,exports){"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ";var slice=Array.prototype.slice;var toStr=Object.prototype.toString;var funcType="[object Function]";module.exports=function bind(that){var target=this;if(typeof target!=="function"||toStr.call(target)!==funcType){throw new TypeError(ERROR_MESSAGE+target)}var args=slice.call(arguments,1);var bound;var binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));if(Object(result)===result){return result}return this}else{return target.apply(that,args.concat(slice.call(arguments)))}};var boundLength=Math.max(0,target.length-args.length);var boundArgs=[];for(var i=0;i<boundLength;i++){boundArgs.push("$"+i)}bound=Function("binder","return function ("+boundArgs.join(",")+"){ return binder.apply(this,arguments); }")(binder);if(target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype;bound.prototype=new Empty;Empty.prototype=null}return bound}},{}],182:[function(require,module,exports){"use strict";var implementation=require("./implementation");module.exports=Function.prototype.bind||implementation},{"./implementation":181}],183:[function(require,module,exports){"use strict";var undefined;var $SyntaxError=SyntaxError;var $Function=Function;var $TypeError=TypeError;var getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}};var $gOPD=Object.getOwnPropertyDescriptor;if($gOPD){try{$gOPD({},"")}catch(e){$gOPD=null}}var throwTypeError=function(){throw new $TypeError};var ThrowTypeError=$gOPD?function(){try{arguments.callee;return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError;var hasSymbols=require("has-symbols")();var getProto=Object.getPrototypeOf||function(x){return x.__proto__};var needsEval={};var TypedArray=typeof Uint8Array==="undefined"?undefined:getProto(Uint8Array);var INTRINSICS={"%AggregateError%":typeof AggregateError==="undefined"?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer==="undefined"?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":typeof Atomics==="undefined"?undefined:Atomics,"%BigInt%":typeof BigInt==="undefined"?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":typeof DataView==="undefined"?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array==="undefined"?undefined:Float32Array,"%Float64Array%":typeof Float64Array==="undefined"?undefined:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry==="undefined"?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":typeof Int8Array==="undefined"?undefined:Int8Array,"%Int16Array%":typeof Int16Array==="undefined"?undefined:Int16Array,"%Int32Array%":typeof Int32Array==="undefined"?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":typeof JSON==="object"?JSON:undefined,"%Map%":typeof Map==="undefined"?undefined:Map,"%MapIteratorPrototype%":typeof Map==="undefined"||!hasSymbols?undefined:getProto((new Map)[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise==="undefined"?undefined:Promise,"%Proxy%":typeof Proxy==="undefined"?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect==="undefined"?undefined:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set==="undefined"?undefined:Set,"%SetIteratorPrototype%":typeof Set==="undefined"||!hasSymbols?undefined:getProto((new Set)[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer==="undefined"?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":typeof Uint8Array==="undefined"?undefined:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray==="undefined"?undefined:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array==="undefined"?undefined:Uint16Array,"%Uint32Array%":typeof Uint32Array==="undefined"?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap==="undefined"?undefined:WeakMap,"%WeakRef%":typeof WeakRef==="undefined"?undefined:WeakRef,"%WeakSet%":typeof WeakSet==="undefined"?undefined:WeakSet};var doEval=function doEval(name){var value;if(name==="%AsyncFunction%"){value=getEvalledConstructor("async function () {}")}else if(name==="%GeneratorFunction%"){value=getEvalledConstructor("function* () {}")}else if(name==="%AsyncGeneratorFunction%"){value=getEvalledConstructor("async function* () {}")}else if(name==="%AsyncGenerator%"){var fn=doEval("%AsyncGeneratorFunction%");if(fn){value=fn.prototype}}else if(name==="%AsyncIteratorPrototype%"){var gen=doEval("%AsyncGenerator%");if(gen){value=getProto(gen.prototype)}}INTRINSICS[name]=value;return value};var LEGACY_ALIASES={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]};var bind=require("function-bind");var hasOwn=require("has");var $concat=bind.call(Function.call,Array.prototype.concat);var $spliceApply=bind.call(Function.apply,Array.prototype.splice);var $replace=bind.call(Function.call,String.prototype.replace);var $strSlice=bind.call(Function.call,String.prototype.slice);var rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;var reEscapeChar=/\\(\\)?/g;var stringToPath=function stringToPath(string){var first=$strSlice(string,0,1);var last=$strSlice(string,-1);if(first==="%"&&last!=="%"){throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`")}else if(last==="%"&&first!=="%"){throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`")}var result=[];$replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match});return result};var getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var intrinsicName=name;var alias;if(hasOwn(LEGACY_ALIASES,intrinsicName)){alias=LEGACY_ALIASES[intrinsicName];intrinsicName="%"+alias[0]+"%"}if(hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval){value=doEval(intrinsicName)}if(typeof value==="undefined"&&!allowMissing){throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!")}return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};module.exports=function GetIntrinsic(name,allowMissing){if(typeof name!=="string"||name.length===0){throw new $TypeError("intrinsic name must be a non-empty string")}if(arguments.length>1&&typeof allowMissing!=="boolean"){throw new $TypeError('"allowMissing" argument must be a boolean')}var parts=stringToPath(name);var intrinsicBaseName=parts.length>0?parts[0]:"";var intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing);var intrinsicRealName=intrinsic.name;var value=intrinsic.value;var skipFurtherCaching=false;var alias=intrinsic.alias;if(alias){intrinsicBaseName=alias[0];$spliceApply(parts,$concat([0,1],alias))}for(var i=1,isOwn=true;i<parts.length;i+=1){var part=parts[i];var first=$strSlice(part,0,1);var last=$strSlice(part,-1);if((first==='"'||first==="'"||first==="`"||(last==='"'||last==="'"||last==="`"))&&first!==last){throw new $SyntaxError("property names with quotes must have matching quotes")}if(part==="constructor"||!isOwn){skipFurtherCaching=true}intrinsicBaseName+="."+part;intrinsicRealName="%"+intrinsicBaseName+"%";if(hasOwn(INTRINSICS,intrinsicRealName)){value=INTRINSICS[intrinsicRealName]}else if(value!=null){if(!(part in value)){if(!allowMissing){throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.")}return void undefined}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);isOwn=!!desc;if(isOwn&&"get"in desc&&!("originalValue"in desc.get)){value=desc.get}else{value=value[part]}}else{isOwn=hasOwn(value,part);value=value[part]}if(isOwn&&!skipFurtherCaching){INTRINSICS[intrinsicRealName]=value}}}return value}},{"function-bind":182,has:187,"has-symbols":184}],184:[function(require,module,exports){"use strict";var origSymbol=typeof Symbol!=="undefined"&&Symbol;var hasSymbolSham=require("./shams");module.exports=function hasNativeSymbols(){if(typeof origSymbol!=="function"){return false}if(typeof Symbol!=="function"){return false}if(typeof origSymbol("foo")!=="symbol"){return false}if(typeof Symbol("bar")!=="symbol"){return false}return hasSymbolSham()}},{"./shams":185}],185:[function(require,module,exports){"use strict";module.exports=function hasSymbols(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function"){return false}if(typeof Symbol.iterator==="symbol"){return true}var obj={};var sym=Symbol("test");var symObj=Object(sym);if(typeof sym==="string"){return false}if(Object.prototype.toString.call(sym)!=="[object Symbol]"){return false}if(Object.prototype.toString.call(symObj)!=="[object Symbol]"){return false}var symVal=42;obj[sym]=symVal;for(sym in obj){return false}if(typeof Object.keys==="function"&&Object.keys(obj).length!==0){return false}if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(obj).length!==0){return false}var syms=Object.getOwnPropertySymbols(obj);if(syms.length!==1||syms[0]!==sym){return false}if(!Object.prototype.propertyIsEnumerable.call(obj,sym)){return false}if(typeof Object.getOwnPropertyDescriptor==="function"){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(descriptor.value!==symVal||descriptor.enumerable!==true){return false}}return true}},{}],186:[function(require,module,exports){"use strict";var hasSymbols=require("has-symbols/shams");module.exports=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}},{"has-symbols/shams":185}],187:[function(require,module,exports){"use strict";var bind=require("function-bind");module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":182}],188:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],189:[function(require,module,exports){"use strict";var hasToStringTag=require("has-tostringtag/shams")();var callBound=require("call-bind/callBound");var $toString=callBound("Object.prototype.toString");var isStandardArguments=function isArguments(value){if(hasToStringTag&&value&&typeof value==="object"&&Symbol.toStringTag in value){return false}return $toString(value)==="[object Arguments]"};var isLegacyArguments=function isArguments(value){if(isStandardArguments(value)){return true}return value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&$toString(value)!=="[object Array]"&&$toString(value.callee)==="[object Function]"};var supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments;module.exports=supportsStandardArguments?isStandardArguments:isLegacyArguments},{"call-bind/callBound":176,"has-tostringtag/shams":186}],190:[function(require,module,exports){"use strict";var toStr=Object.prototype.toString;var fnToStr=Function.prototype.toString;var isFnRegex=/^\s*(?:function)?\*/;var hasToStringTag=require("has-tostringtag/shams")();var getProto=Object.getPrototypeOf;var getGeneratorFunc=function(){if(!hasToStringTag){return false}try{return Function("return function*() {}")()}catch(e){}};var GeneratorFunction;module.exports=function isGeneratorFunction(fn){if(typeof fn!=="function"){return false}if(isFnRegex.test(fnToStr.call(fn))){return true}if(!hasToStringTag){var str=toStr.call(fn);return str==="[object GeneratorFunction]"}if(!getProto){return false}if(typeof GeneratorFunction==="undefined"){var generatorFunc=getGeneratorFunc();GeneratorFunction=generatorFunc?getProto(generatorFunc):false}return getProto(fn)===GeneratorFunction}},{"has-tostringtag/shams":186}],191:[function(require,module,exports){(function(global){(function(){"use strict";var forEach=require("foreach");var availableTypedArrays=require("available-typed-arrays");var callBound=require("call-bind/callBound");var $toString=callBound("Object.prototype.toString");var hasToStringTag=require("has-tostringtag/shams")();var g=typeof globalThis==="undefined"?global:globalThis;var typedArrays=availableTypedArrays();var $indexOf=callBound("Array.prototype.indexOf",true)||function indexOf(array,value){
57
+ for(var i=0;i<array.length;i+=1){if(array[i]===value){return i}}return-1};var $slice=callBound("String.prototype.slice");var toStrTags={};var gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor");var getPrototypeOf=Object.getPrototypeOf;if(hasToStringTag&&gOPD&&getPrototypeOf){forEach(typedArrays,function(typedArray){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr);var descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}})}var tryTypedArrays=function tryAllTypedArrays(value){var anyTrue=false;forEach(toStrTags,function(getter,typedArray){if(!anyTrue){try{anyTrue=getter.call(value)===typedArray}catch(e){}}});return anyTrue};module.exports=function isTypedArray(value){if(!value||typeof value!=="object"){return false}if(!hasToStringTag||!(Symbol.toStringTag in value)){var tag=$slice($toString(value),8,-1);return $indexOf(typedArrays,tag)>-1}if(!gOPD){return false}return tryTypedArrays(value)}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"available-typed-arrays":169,"call-bind/callBound":176,"es-abstract/helpers/getOwnPropertyDescriptor":178,foreach:180,"has-tostringtag/shams":186}],192:[function(require,module,exports){module.exports=require("./lib/checks")},{"./lib/checks":193}],193:[function(require,module,exports){var util=require("util");var errors=module.exports=require("./errors");function failCheck(ExceptionConstructor,callee,messageFormat,formatArgs){messageFormat=messageFormat||"";var message=util.format.apply(this,[messageFormat].concat(formatArgs));var error=new ExceptionConstructor(message);Error.captureStackTrace(error,callee);throw error}function failArgumentCheck(callee,message,formatArgs){failCheck(errors.IllegalArgumentError,callee,message,formatArgs)}function failStateCheck(callee,message,formatArgs){failCheck(errors.IllegalStateError,callee,message,formatArgs)}module.exports.checkArgument=function(value,message){if(!value){failArgumentCheck(arguments.callee,message,Array.prototype.slice.call(arguments,2))}};module.exports.checkState=function(value,message){if(!value){failStateCheck(arguments.callee,message,Array.prototype.slice.call(arguments,2))}};module.exports.checkIsDef=function(value,message){if(value!==undefined){return value}failArgumentCheck(arguments.callee,message||"Expected value to be defined but was undefined.",Array.prototype.slice.call(arguments,2))};module.exports.checkIsDefAndNotNull=function(value,message){if(value!=null){return value}failArgumentCheck(arguments.callee,message||'Expected value to be defined and not null but got "'+typeOf(value)+'".',Array.prototype.slice.call(arguments,2))};function typeOf(value){var s=typeof value;if(s=="object"){if(!value){return"null"}else if(value instanceof Array){return"array"}}return s}function typeCheck(expect){return function(value,message){var type=typeOf(value);if(type==expect){return value}failArgumentCheck(arguments.callee,message||'Expected "'+expect+'" but got "'+type+'".',Array.prototype.slice.call(arguments,2))}}module.exports.checkIsString=typeCheck("string");module.exports.checkIsArray=typeCheck("array");module.exports.checkIsNumber=typeCheck("number");module.exports.checkIsBoolean=typeCheck("boolean");module.exports.checkIsFunction=typeCheck("function");module.exports.checkIsObject=typeCheck("object")},{"./errors":194,util:198}],194:[function(require,module,exports){var util=require("util");function IllegalArgumentError(message){Error.call(this,message);this.message=message}util.inherits(IllegalArgumentError,Error);IllegalArgumentError.prototype.name="IllegalArgumentError";function IllegalStateError(message){Error.call(this,message);this.message=message}util.inherits(IllegalStateError,Error);IllegalStateError.prototype.name="IllegalStateError";module.exports.IllegalStateError=IllegalStateError;module.exports.IllegalArgumentError=IllegalArgumentError},{util:198}],195:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";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.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[]};process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],196:[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"}},{}],197:[function(require,module,exports){"use strict";var isArgumentsObject=require("is-arguments");var isGeneratorFunction=require("is-generator-function");var whichTypedArray=require("which-typed-array");var isTypedArray=require("is-typed-array");function uncurryThis(f){return f.call.bind(f)}var BigIntSupported=typeof BigInt!=="undefined";var SymbolSupported=typeof Symbol!=="undefined";var ObjectToString=uncurryThis(Object.prototype.toString);var numberValue=uncurryThis(Number.prototype.valueOf);var stringValue=uncurryThis(String.prototype.valueOf);var booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported){var bigIntValue=uncurryThis(BigInt.prototype.valueOf)}if(SymbolSupported){var symbolValue=uncurryThis(Symbol.prototype.valueOf)}function checkBoxedPrimitive(value,prototypeValueOf){if(typeof value!=="object"){return false}try{prototypeValueOf(value);return true}catch(e){return false}}exports.isArgumentsObject=isArgumentsObject;exports.isGeneratorFunction=isGeneratorFunction;exports.isTypedArray=isTypedArray;function isPromise(input){return typeof Promise!=="undefined"&&input instanceof Promise||input!==null&&typeof input==="object"&&typeof input.then==="function"&&typeof input.catch==="function"}exports.isPromise=isPromise;function isArrayBufferView(value){if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView){return ArrayBuffer.isView(value)}return isTypedArray(value)||isDataView(value)}exports.isArrayBufferView=isArrayBufferView;function isUint8Array(value){return whichTypedArray(value)==="Uint8Array"}exports.isUint8Array=isUint8Array;function isUint8ClampedArray(value){return whichTypedArray(value)==="Uint8ClampedArray"}exports.isUint8ClampedArray=isUint8ClampedArray;function isUint16Array(value){return whichTypedArray(value)==="Uint16Array"}exports.isUint16Array=isUint16Array;function isUint32Array(value){return whichTypedArray(value)==="Uint32Array"}exports.isUint32Array=isUint32Array;function isInt8Array(value){return whichTypedArray(value)==="Int8Array"}exports.isInt8Array=isInt8Array;function isInt16Array(value){return whichTypedArray(value)==="Int16Array"}exports.isInt16Array=isInt16Array;function isInt32Array(value){return whichTypedArray(value)==="Int32Array"}exports.isInt32Array=isInt32Array;function isFloat32Array(value){return whichTypedArray(value)==="Float32Array"}exports.isFloat32Array=isFloat32Array;function isFloat64Array(value){return whichTypedArray(value)==="Float64Array"}exports.isFloat64Array=isFloat64Array;function isBigInt64Array(value){return whichTypedArray(value)==="BigInt64Array"}exports.isBigInt64Array=isBigInt64Array;function isBigUint64Array(value){return whichTypedArray(value)==="BigUint64Array"}exports.isBigUint64Array=isBigUint64Array;function isMapToString(value){return ObjectToString(value)==="[object Map]"}isMapToString.working=typeof Map!=="undefined"&&isMapToString(new Map);function isMap(value){if(typeof Map==="undefined"){return false}return isMapToString.working?isMapToString(value):value instanceof Map}exports.isMap=isMap;function isSetToString(value){return ObjectToString(value)==="[object Set]"}isSetToString.working=typeof Set!=="undefined"&&isSetToString(new Set);function isSet(value){if(typeof Set==="undefined"){return false}return isSetToString.working?isSetToString(value):value instanceof Set}exports.isSet=isSet;function isWeakMapToString(value){return ObjectToString(value)==="[object WeakMap]"}isWeakMapToString.working=typeof WeakMap!=="undefined"&&isWeakMapToString(new WeakMap);function isWeakMap(value){if(typeof WeakMap==="undefined"){return false}return isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap}exports.isWeakMap=isWeakMap;function isWeakSetToString(value){return ObjectToString(value)==="[object WeakSet]"}isWeakSetToString.working=typeof WeakSet!=="undefined"&&isWeakSetToString(new WeakSet);function isWeakSet(value){return isWeakSetToString(value)}exports.isWeakSet=isWeakSet;function isArrayBufferToString(value){return ObjectToString(value)==="[object ArrayBuffer]"}isArrayBufferToString.working=typeof ArrayBuffer!=="undefined"&&isArrayBufferToString(new ArrayBuffer);function isArrayBuffer(value){if(typeof ArrayBuffer==="undefined"){return false}return isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer}exports.isArrayBuffer=isArrayBuffer;function isDataViewToString(value){return ObjectToString(value)==="[object DataView]"}isDataViewToString.working=typeof ArrayBuffer!=="undefined"&&typeof DataView!=="undefined"&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1));function isDataView(value){if(typeof DataView==="undefined"){return false}return isDataViewToString.working?isDataViewToString(value):value instanceof DataView}exports.isDataView=isDataView;var SharedArrayBufferCopy=typeof SharedArrayBuffer!=="undefined"?SharedArrayBuffer:undefined;function isSharedArrayBufferToString(value){return ObjectToString(value)==="[object SharedArrayBuffer]"}function isSharedArrayBuffer(value){if(typeof SharedArrayBufferCopy==="undefined"){return false}if(typeof isSharedArrayBufferToString.working==="undefined"){isSharedArrayBufferToString.working=isSharedArrayBufferToString(new SharedArrayBufferCopy)}return isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBufferCopy}exports.isSharedArrayBuffer=isSharedArrayBuffer;function isAsyncFunction(value){return ObjectToString(value)==="[object AsyncFunction]"}exports.isAsyncFunction=isAsyncFunction;function isMapIterator(value){return ObjectToString(value)==="[object Map Iterator]"}exports.isMapIterator=isMapIterator;function isSetIterator(value){return ObjectToString(value)==="[object Set Iterator]"}exports.isSetIterator=isSetIterator;function isGeneratorObject(value){return ObjectToString(value)==="[object Generator]"}exports.isGeneratorObject=isGeneratorObject;function isWebAssemblyCompiledModule(value){return ObjectToString(value)==="[object WebAssembly.Module]"}exports.isWebAssemblyCompiledModule=isWebAssemblyCompiledModule;function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}exports.isNumberObject=isNumberObject;function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}exports.isStringObject=isStringObject;function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}exports.isBooleanObject=isBooleanObject;function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}exports.isBigIntObject=isBigIntObject;function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}exports.isSymbolObject=isSymbolObject;function isBoxedPrimitive(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)}exports.isBoxedPrimitive=isBoxedPrimitive;function isAnyArrayBuffer(value){return typeof Uint8Array!=="undefined"&&(isArrayBuffer(value)||isSharedArrayBuffer(value))}exports.isAnyArrayBuffer=isAnyArrayBuffer;["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(method){Object.defineProperty(exports,method,{enumerable:false,value:function(){throw new Error(method+" is not supported in userland")}})})},{"is-arguments":189,"is-generator-function":190,"is-typed-array":191,"which-typed-array":199}],198:[function(require,module,exports){(function(process){(function(){var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function getOwnPropertyDescriptors(obj){var keys=Object.keys(obj);var descriptors={};for(var i=0;i<keys.length;i++){descriptors[keys[i]]=Object.getOwnPropertyDescriptor(obj,keys[i])}return descriptors};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};exports.deprecate=function(fn,msg){if(typeof process!=="undefined"&&process.noDeprecation===true){return fn}if(typeof process==="undefined"){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}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 debugEnvRegex=/^$/;if(process.env.NODE_DEBUG){var debugEnv=process.env.NODE_DEBUG;debugEnv=debugEnv.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase();debugEnvRegex=new RegExp("^"+debugEnv+"$","i")}exports.debuglog=function(set){set=set.toUpperCase();if(!debugs[set]){if(debugEnvRegex.test(set)){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]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}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;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]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"\x1b["+inspect.colors[style][0]+"m"+str+"\x1b["+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){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}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=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}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");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]}exports.types=require("./support/types");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;exports.types.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;exports.types.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;exports.types.isNativeError=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"||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"];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(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){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)}var kCustomPromisifiedSymbol=typeof Symbol!=="undefined"?Symbol("util.promisify.custom"):undefined;exports.promisify=function promisify(original){if(typeof original!=="function")throw new TypeError('The "original" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if(typeof fn!=="function"){throw new TypeError('The "util.promisify.custom" argument must be of type Function')}Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:false,writable:false,configurable:true});return fn}function fn(){var promiseResolve,promiseReject;var promise=new Promise(function(resolve,reject){promiseResolve=resolve;promiseReject=reject});var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i])}args.push(function(err,value){if(err){promiseReject(err)}else{promiseResolve(value)}});try{original.apply(this,args)}catch(err){promiseReject(err)}return promise}Object.setPrototypeOf(fn,Object.getPrototypeOf(original));if(kCustomPromisifiedSymbol)Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:false,writable:false,configurable:true});return Object.defineProperties(fn,getOwnPropertyDescriptors(original))};exports.promisify.custom=kCustomPromisifiedSymbol;function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason;reason=newReason}return cb(reason)}function callbackify(original){if(typeof original!=="function"){throw new TypeError('The "original" argument must be of type Function')}function callbackified(){var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i])}var maybeCb=args.pop();if(typeof maybeCb!=="function"){throw new TypeError("The last argument must be of type Function")}var self=this;var cb=function(){return maybeCb.apply(self,arguments)};original.apply(this,args).then(function(ret){process.nextTick(cb.bind(null,null,ret))},function(rej){process.nextTick(callbackifyOnRejected.bind(null,rej,cb))})}Object.setPrototypeOf(callbackified,Object.getPrototypeOf(original));Object.defineProperties(callbackified,getOwnPropertyDescriptors(original));return callbackified}exports.callbackify=callbackify}).call(this)}).call(this,require("_process"))},{"./support/isBuffer":196,"./support/types":197,_process:195,inherits:188}],199:[function(require,module,exports){(function(global){(function(){"use strict";var forEach=require("foreach");var availableTypedArrays=require("available-typed-arrays");var callBound=require("call-bind/callBound");var $toString=callBound("Object.prototype.toString");var hasToStringTag=require("has-tostringtag/shams")();var g=typeof globalThis==="undefined"?global:globalThis;var typedArrays=availableTypedArrays();var $slice=callBound("String.prototype.slice");var toStrTags={};var gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor");var getPrototypeOf=Object.getPrototypeOf;if(hasToStringTag&&gOPD&&getPrototypeOf){forEach(typedArrays,function(typedArray){if(typeof g[typedArray]==="function"){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr);var descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}}})}var tryTypedArrays=function tryAllTypedArrays(value){var foundName=false;forEach(toStrTags,function(getter,typedArray){if(!foundName){try{var name=getter.call(value);if(name===typedArray){foundName=name}}catch(e){}}});return foundName};var isTypedArray=require("is-typed-array");module.exports=function whichTypedArray(value){if(!isTypedArray(value)){return false}if(!hasToStringTag||!(Symbol.toStringTag in value)){return $slice($toString(value),8,-1)}return tryTypedArrays(value)}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"available-typed-arrays":169,"call-bind/callBound":176,"es-abstract/helpers/getOwnPropertyDescriptor":178,foreach:180,"has-tostringtag/shams":186,"is-typed-array":191}],200:[function(require,module,exports){module.exports={name:"twilio-video",title:"Twilio Video",description:"Twilio Video JavaScript Library",version:"2.18.3",homepage:"https://twilio.com",author:"Mark Andrus Roberts <mroberts@twilio.com>",contributors:["Ryan Rowland <rrowland@twilio.com>","Manjesh Malavalli <mmalavalli@twilio.com>","Makarand Patwardhan <mpatwardhan@twilio.com>"],keywords:["twilio","webrtc","library","javascript","video","rooms"],repository:{type:"git",url:"https://github.com/twilio/twilio-video.js.git"},devDependencies:{"@babel/core":"^7.14.2","@babel/preset-env":"^7.14.2","@babel/preset-typescript":"^7.13.0","@types/express":"^4.11.0","@types/node":"^8.5.1","@types/selenium-webdriver":"^3.0.8","@types/ws":"^3.2.1","@typescript-eslint/eslint-plugin":"^4.13.0","@typescript-eslint/parser":"^4.0.0","babel-cli":"^6.26.0","babel-preset-es2015":"^6.24.1",browserify:"^17.0.0",cheerio:"^0.22.0",cors:"^2.8.5",electron:"^9.1.0",envify:"^4.0.0",eslint:"^6.2.1","eslint-config-standard":"^14.0.0","eslint-plugin-import":"^2.18.2","eslint-plugin-node":"^9.1.0","eslint-plugin-promise":"^4.2.1","eslint-plugin-standard":"^4.0.1",express:"^4.16.2",glob:"^7.1.7","ink-docstrap":"^1.3.2",inquirer:"^7.0.0","is-docker":"^2.0.0",jsdoc:"^3.5.5","jsdoc-babel":"^0.5.0","json-loader":"^0.5.7",karma:"^5.0.2","karma-browserify":"^8.0.0","karma-chrome-launcher":"^2.0.0","karma-edgium-launcher":"^4.0.0-0","karma-electron":"^6.1.0","karma-firefox-launcher":"^1.3.0","karma-htmlfile-reporter":"^0.3.8","karma-junit-reporter":"^1.2.0","karma-mocha":"^1.3.0","karma-safari-launcher":"^1.0.0","karma-spec-reporter":"0.0.32","karma-typescript":"^5.5.1","karma-typescript-es6-transform":"^5.5.1",mocha:"^3.2.0","mock-require":"^3.0.3",ncp:"^2.0.0","node-http-server":"^8.1.2","npm-run-all":"^4.0.2",nyc:"^15.1.0",requirejs:"^2.3.3",rimraf:"^2.6.1","simple-git":"^1.126.0",sinon:"^4.0.1","ts-node":"4.0.1",tslint:"5.8.0",twilio:"^3.49.0","twilio-release-tool":"^1.0.2",typescript:"4.2.2","uglify-js":"^2.8.22","vinyl-fs":"^2.4.4","vinyl-source-stream":"^1.1.0",watchify:"^3.11.1","webrtc-adapter":"^7.7.1"},engines:{node:">=0.12"},license:"BSD-3-Clause",main:"./es5/index.js",types:"./tsdef/index.d.ts",scripts:{"lint:js":"eslint ./lib ./test/*.js ./docker/**/*.js ./test/framework/*.js ./test/lib/*.js ./test/integration/** ./test/unit/** ","lint:ts":"eslint ./tsdef/*.ts ./lib/**/*.ts",lint:"npm-run-all lint:js lint:ts",printVersion:"node --version && npm --version","test:unit":"npm-run-all printVersion build:es5 test:unit:js test:unit:ts","test:unit:js":"nyc --report-dir=./coverage/js --extension=.js --include=lib/**/* --reporter=html --reporter=lcov --reporter=text mocha ./test/unit/index.js","test:unit:ts":"nyc --report-dir=./coverage/ts --extension=.ts --include=lib/**/* --reporter=html --reporter=lcov --reporter=text mocha -r ts-node/register ./test/unit/index.ts","test:serversiderender":"mocha ./test/serversiderender/index.js","test:integration:adapter":"node ./scripts/karma.js karma/integration.adapter.conf.js","test:integration":"npm run build:es5 && node ./scripts/karma.js karma/integration.conf.js","test:umd:install":"npm install puppeteer@5.5.0","test:umd":"mocha ./test/umd/index.js","test:crossbrowser:build:clean":"rimraf ./test/crossbrowser/lib ./test/crossbrowser/src/browser/index.js","test:crossbrowser:build:lint":"cd ./test/crossbrowser && tslint --project tsconfig.json","test:crossbrowser:build:tsc":"cd ./test/crossbrowser && tsc","test:crossbrowser:build:browser":"cd ./test/crossbrowser && browserify lib/crossbrowser/src/browser/index.js > src/browser/index.js","test:crossbrowser:build":"npm-run-all test:crossbrowser:build:*",
58
+ "test:crossbrowser:test":"cd ./test/crossbrowser && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:crossbrowser":"npm-run-all test:crossbrowser:*","test:sdkdriver:build:clean":"rimraf ./test/lib/sdkdriver/lib ./test/lib/sdkdriver/test/integration/browser/index.js","test:sdkdriver:build:lint":"cd ./test/lib/sdkdriver && tslint --project tsconfig.json","test:sdkdriver:build:tsc":"cd ./test/lib/sdkdriver && tsc --rootDir src","test:sdkdriver:build":"npm-run-all test:sdkdriver:build:*","test:sdkdriver:test:unit":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/unit/spec/**/*.ts","test:sdkdriver:test:integration:browser":"cd ./test/lib/sdkdriver/test/integration && browserify browser/browser.js > browser/index.js","test:sdkdriver:test:integration:run":"cd ./test/lib/sdkdriver && mocha --compilers ts:ts-node/register test/integration/spec/**/*.ts","test:sdkdriver:test:integration":"npm-run-all test:sdkdriver:test:integration:*","test:sdkdriver:test":"npm-run-all test:sdkdriver:test:*","test:sdkdriver":"npm-run-all test:sdkdriver:*","test:framework:angular:install":"cd ./test/framework/twilio-video-angular && rimraf ./node_modules package-lock.json && npm install","test:framework:angular:run":"mocha ./test/framework/twilio-video-angular.js","test:framework:angular":"npm-run-all test:framework:angular:*","test:framework:no-framework:run":"mocha ./test/framework/twilio-video-no-framework.js","test:framework:no-framework":"npm-run-all test:framework:no-framework:*","test:framework:react:install":"cd ./test/framework/twilio-video-react && rimraf ./node_modules package-lock.json && npm install","test:framework:react:test":"node ./scripts/framework.js twilio-video-react","test:framework:react:build":"cd ./test/framework/twilio-video-react && npm run build","test:framework:react:run":"mocha ./test/framework/twilio-video-react.js","test:framework:react":"npm-run-all test:framework:react:*","test:framework:install":"npm install chromedriver && npm install selenium-webdriver && npm install geckodriver && npm install puppeteer","test:framework":"npm-run-all test:framework:install test:framework:no-framework test:framework:react",test:"npm-run-all test:unit test:integration","build:es5":"rimraf ./es5 && tsc tsdef/twilio-video-tests.ts --noEmit --lib es2018,dom && tsc ","build:js":"node ./scripts/build.js ./src/twilio-video.js ./LICENSE.md ./dist/twilio-video.js","build:min.js":'uglifyjs ./dist/twilio-video.js -o ./dist/twilio-video.min.js --comments "/^! twilio-video.js/" -b beautify=false,ascii_only=true',build:"npm-run-all clean lint docs test:unit test:integration build:es5 build:js build:min.js test:umd","build:quick":"npm-run-all clean lint docs build:es5 build:js build:min.js",docs:"node ./scripts/docs.js ./dist/docs",watch:"tsc -w",clean:"rimraf ./coverage ./es5 ./dist"},dependencies:{"@twilio/webrtc":"4.5.2",backoff:"^2.5.0",ws:"^7.4.6",xmlhttprequest:"^1.8.0"},browser:{ws:"./src/ws.js",xmlhttprequest:"./src/xmlhttprequest.js"}}},{}],201:[function(require,module,exports){module.exports=WebSocket},{}]},{},[11]);var Video=bundle(11);if(typeof define==="function"&&define.amd){define([],function(){return Video})}else{var Twilio=root.Twilio=root.Twilio||{};Twilio.Video=Twilio.Video||Video}})(typeof window!=="undefined"?window:typeof global!=="undefined"?global:this);