openvidu-browser 2.32.1 → 2.32.2
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 +1 @@
|
|
|
1
|
-
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[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)}}},{}],2:[function(require,module,exports){"use strict";var normalice=require("normalice");var freeice=function(opts){var servers={stun:(opts||{}).stun||require("./stun.json"),turn:(opts||{}).turn||require("./turn.json")};var stunCount=(opts||{}).stunCount||2;var turnCount=(opts||{}).turnCount||0;var selected;function getServers(type,count){var out=[];var input=[].concat(servers[type]);var idx;while(input.length&&out.length<count){idx=Math.random()*input.length|0;out=out.concat(input.splice(idx,1))}return out.map(function(url){if(typeof url!=="string"&&!(url instanceof String)){return url}else{return normalice(type+":"+url)}})}selected=[].concat(getServers("stun",stunCount));if(turnCount){selected=selected.concat(getServers("turn",turnCount))}return selected};module.exports=freeice},{"./stun.json":3,"./turn.json":4,normalice:12}],3:[function(require,module,exports){module.exports=["stun.l.google.com:19302","stun1.l.google.com:19302","stun2.l.google.com:19302","stun3.l.google.com:19302","stun4.l.google.com:19302","stun.ekiga.net","stun.ideasip.com","stun.schlund.de","stun.stunprotocol.org:3478","stun.voiparound.com","stun.voipbuster.com","stun.voipstunt.com","stun.voxgratia.org"]},{}],4:[function(require,module,exports){module.exports=[]},{}],5:[function(require,module,exports){var WildEmitter=require("wildemitter");function getMaxVolume(analyser,fftBins){var maxVolume=-Infinity;analyser.getFloatFrequencyData(fftBins);for(var i=4,ii=fftBins.length;i<ii;i++){if(fftBins[i]>maxVolume&&fftBins[i]<0){maxVolume=fftBins[i]}}return maxVolume}var audioContextType;if(typeof window!=="undefined"){audioContextType=window.AudioContext||window.webkitAudioContext}var audioContext=null;module.exports=function(stream,options){var harker=new WildEmitter;if(!audioContextType)return harker;var options=options||{},smoothing=options.smoothing||.1,interval=options.interval||50,threshold=options.threshold,play=options.play,history=options.history||10,running=true;audioContext=options.audioContext||audioContext||new audioContextType;var sourceNode,fftBins,analyser;analyser=audioContext.createAnalyser();analyser.fftSize=512;analyser.smoothingTimeConstant=smoothing;fftBins=new Float32Array(analyser.frequencyBinCount);if(stream.jquery)stream=stream[0];if(stream instanceof HTMLAudioElement||stream instanceof HTMLVideoElement){sourceNode=audioContext.createMediaElementSource(stream);if(typeof play==="undefined")play=true;threshold=threshold||-50}else{sourceNode=audioContext.createMediaStreamSource(stream);threshold=threshold||-50}sourceNode.connect(analyser);if(play)analyser.connect(audioContext.destination);harker.speaking=false;harker.suspend=function(){return audioContext.suspend()};harker.resume=function(){return audioContext.resume()};Object.defineProperty(harker,"state",{get:function(){return audioContext.state}});audioContext.onstatechange=function(){harker.emit("state_change",audioContext.state)};harker.setThreshold=function(t){threshold=t};harker.setInterval=function(i){interval=i};harker.stop=function(){running=false;harker.emit("volume_change",-100,threshold);if(harker.speaking){harker.speaking=false;harker.emit("stopped_speaking")}analyser.disconnect();sourceNode.disconnect()};harker.speakingHistory=[];for(var i=0;i<history;i++){harker.speakingHistory.push(0)}var looper=function(){setTimeout(function(){if(!running){return}var currentVolume=getMaxVolume(analyser,fftBins);harker.emit("volume_change",currentVolume,threshold);var history=0;if(currentVolume>threshold&&!harker.speaking){for(var i=harker.speakingHistory.length-3;i<harker.speakingHistory.length;i++){history+=harker.speakingHistory[i]}if(history>=2){harker.speaking=true;harker.emit("speaking")}}else if(currentVolume<threshold&&harker.speaking){for(var i=0;i<harker.speakingHistory.length;i++){history+=harker.speakingHistory[i]}if(history==0){harker.speaking=false;harker.emit("stopped_speaking")}}harker.speakingHistory.shift();harker.speakingHistory.push(0+(currentVolume>threshold));looper()},interval)};looper();return harker}},{wildemitter:38}],6:[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}}}},{}],7:[function(require,module,exports){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){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();function JL(loggerName){if(!loggerName){return JL.__}if(!Array.prototype.reduce){Array.prototype.reduce=function(callback,initialValue){var previousValue=initialValue;for(var i=0;i<this.length;i++){previousValue=callback(previousValue,this[i],i,this)}return previousValue}}var accumulatedLoggerName="";var logger=("."+loggerName).split(".").reduce(function(prev,curr,idx,arr){if(accumulatedLoggerName){accumulatedLoggerName+="."+curr}else{accumulatedLoggerName=curr}var currentLogger=prev["__"+accumulatedLoggerName];if(currentLogger===undefined){JL.Logger.prototype=prev;currentLogger=new JL.Logger(accumulatedLoggerName);prev["__"+accumulatedLoggerName]=currentLogger}return currentLogger},JL.__);return logger}(function(JL){JL.requestId="";JL.entryId=0;JL._createXMLHttpRequest=function(){return new XMLHttpRequest};JL._getTime=function(){return(new Date).getTime()};JL._console=console;JL._appenderNames=[];function copyProperty(propertyName,from,to){if(from[propertyName]===undefined){return}if(from[propertyName]===null){delete to[propertyName];return}to[propertyName]=from[propertyName]}function allow(filters){if(!(JL.enabled==null)){if(!JL.enabled){return false}}try{if(filters.userAgentRegex){if(!new RegExp(filters.userAgentRegex).test(navigator.userAgent)){return false}}}catch(e){}try{if(filters.ipRegex&&JL.clientIP){if(!new RegExp(filters.ipRegex).test(JL.clientIP)){return false}}}catch(e){}return true}function allowMessage(filters,message){try{if(filters.disallow){if(new RegExp(filters.disallow).test(message)){return false}}}catch(e){}return true}function stringifyLogObjectFunction(logObject){if(typeof logObject=="function"){if(logObject instanceof RegExp){return logObject.toString()}else{return logObject()}}return logObject}var StringifiedLogObject=function(){function StringifiedLogObject(msg,meta,finalString){this.msg=msg;this.meta=meta;this.finalString=finalString}return StringifiedLogObject}();function stringifyLogObject(logObject){var actualLogObject=stringifyLogObjectFunction(logObject);var finalString;switch(typeof actualLogObject){case"string":return new StringifiedLogObject(actualLogObject,null,actualLogObject);case"number":finalString=actualLogObject.toString();return new StringifiedLogObject(finalString,null,finalString);case"boolean":finalString=actualLogObject.toString();return new StringifiedLogObject(finalString,null,finalString);case"undefined":return new StringifiedLogObject("undefined",null,"undefined");case"object":if(actualLogObject instanceof RegExp||actualLogObject instanceof String||actualLogObject instanceof Number||actualLogObject instanceof Boolean){finalString=actualLogObject.toString();return new StringifiedLogObject(finalString,null,finalString)}else{if(typeof JL.serialize==="function"){finalString=JL.serialize.call(this,actualLogObject)}else{finalString=JSON.stringify(actualLogObject)}return new StringifiedLogObject("",actualLogObject,finalString)}default:return new StringifiedLogObject("unknown",null,"unknown")}}function setOptions(options){copyProperty("enabled",options,this);copyProperty("maxMessages",options,this);copyProperty("defaultAjaxUrl",options,this);copyProperty("clientIP",options,this);copyProperty("requestId",options,this);copyProperty("defaultBeforeSend",options,this);copyProperty("serialize",options,this);return this}JL.setOptions=setOptions;function getAllLevel(){return-2147483648}JL.getAllLevel=getAllLevel;function getTraceLevel(){return 1e3}JL.getTraceLevel=getTraceLevel;function getDebugLevel(){return 2e3}JL.getDebugLevel=getDebugLevel;function getInfoLevel(){return 3e3}JL.getInfoLevel=getInfoLevel;function getWarnLevel(){return 4e3}JL.getWarnLevel=getWarnLevel;function getErrorLevel(){return 5e3}JL.getErrorLevel=getErrorLevel;function getFatalLevel(){return 6e3}JL.getFatalLevel=getFatalLevel;function getOffLevel(){return 2147483647}JL.getOffLevel=getOffLevel;function levelToString(level){if(level<=1e3){return"trace"}if(level<=2e3){return"debug"}if(level<=3e3){return"info"}if(level<=4e3){return"warn"}if(level<=5e3){return"error"}return"fatal"}var Exception=function(){function Exception(data,inner){this.inner=inner;this.name="JL.Exception";this.message=stringifyLogObject(data).finalString}return Exception}();JL.Exception=Exception;Exception.prototype=new Error;var LogItem=function(){function LogItem(l,m,n,t,u){this.l=l;this.m=m;this.n=n;this.t=t;this.u=u}return LogItem}();JL.LogItem=LogItem;function newLogItem(levelNbr,message,loggerName){JL.entryId++;return new LogItem(levelNbr,message,loggerName,JL._getTime(),JL.entryId)}function clearTimer(timer){if(timer.id){clearTimeout(timer.id);timer.id=null}}function setTimer(timer,timeoutMs,callback){var that=this;if(!timer.id){timer.id=setTimeout(function(){callback.call(that)},timeoutMs)}}var Appender=function(){function Appender(appenderName,sendLogItems){this.appenderName=appenderName;this.sendLogItems=sendLogItems;this.level=JL.getTraceLevel();this.sendWithBufferLevel=2147483647;this.storeInBufferLevel=-2147483648;this.bufferSize=0;this.batchSize=1;this.maxBatchSize=20;this.batchTimeout=2147483647;this.sendTimeout=5e3;this.buffer=[];this.batchBuffer=[];this.batchTimeoutTimer={id:null};this.sendTimeoutTimer={id:null};this.nbrLogItemsSkipped=0;this.nbrLogItemsBeingSent=0;var emptyNameErrorMessage="Trying to create an appender without a name or with an empty name";if(appenderName==undefined){throw emptyNameErrorMessage}if(JL._appenderNames.indexOf(appenderName)!=-1){if(!appenderName){throw emptyNameErrorMessage}throw"Multiple appenders use the same name "+appenderName}JL._appenderNames.push(appenderName)}Appender.prototype.addLogItemsToBuffer=function(logItems){if(this.batchBuffer.length>=this.maxBatchSize){this.nbrLogItemsSkipped+=logItems.length;return}if(!(JL.maxMessages==null)){if(JL.maxMessages<1){return}JL.maxMessages-=logItems.length}this.batchBuffer=this.batchBuffer.concat(logItems);var that=this;setTimer(this.batchTimeoutTimer,this.batchTimeout,function(){that.sendBatch.call(that)})};Appender.prototype.batchBufferHasOverdueMessages=function(){for(var i=0;i<this.batchBuffer.length;i++){var messageAgeMs=JL._getTime()-this.batchBuffer[i].t;if(messageAgeMs>this.batchTimeout){return true}}return false};Appender.prototype.batchBufferHasStrandedMessage=function(){return!(JL.maxMessages==null)&&JL.maxMessages<1&&this.batchBuffer.length>0};Appender.prototype.sendBatchIfComplete=function(){if(this.batchBuffer.length>=this.batchSize||this.batchBufferHasOverdueMessages()||this.batchBufferHasStrandedMessage()){this.sendBatch()}};Appender.prototype.onSendingEnded=function(){clearTimer(this.sendTimeoutTimer);this.nbrLogItemsBeingSent=0;this.sendBatchIfComplete()};Appender.prototype.setOptions=function(options){copyProperty("level",options,this);copyProperty("ipRegex",options,this);copyProperty("userAgentRegex",options,this);copyProperty("disallow",options,this);copyProperty("sendWithBufferLevel",options,this);copyProperty("storeInBufferLevel",options,this);copyProperty("bufferSize",options,this);copyProperty("batchSize",options,this);copyProperty("maxBatchSize",options,this);copyProperty("batchTimeout",options,this);copyProperty("sendTimeout",options,this);if(this.bufferSize<this.buffer.length){this.buffer.length=this.bufferSize}if(this.maxBatchSize<this.batchSize){throw new JL.Exception({message:"maxBatchSize cannot be smaller than batchSize",maxBatchSize:this.maxBatchSize,batchSize:this.batchSize})}return this};Appender.prototype.log=function(level,msg,meta,callback,levelNbr,message,loggerName){var logItem;if(!allow(this)){return}if(!allowMessage(this,message)){return}if(levelNbr<this.storeInBufferLevel){return}logItem=newLogItem(levelNbr,message,loggerName);if(levelNbr<this.level){if(this.bufferSize>0){this.buffer.push(logItem);if(this.buffer.length>this.bufferSize){this.buffer.shift()}}return}this.addLogItemsToBuffer([logItem]);if(levelNbr>=this.sendWithBufferLevel){if(this.buffer.length){this.addLogItemsToBuffer(this.buffer);this.buffer.length=0}}this.sendBatchIfComplete()};Appender.prototype.sendBatch=function(){if(this.nbrLogItemsBeingSent>0){return}clearTimer(this.batchTimeoutTimer);if(this.batchBuffer.length==0){return}this.nbrLogItemsBeingSent=this.batchBuffer.length;var that=this;setTimer(this.sendTimeoutTimer,this.sendTimeout,function(){that.onSendingEnded.call(that)});this.sendLogItems(this.batchBuffer,function(){that.batchBuffer.splice(0,that.nbrLogItemsBeingSent);if(that.nbrLogItemsSkipped>0){that.batchBuffer.push(newLogItem(getWarnLevel(),"Lost "+that.nbrLogItemsSkipped+" messages. Either connection with the server was down or logging was disabled via the enabled option. Reduce lost messages by increasing the ajaxAppender option maxBatchSize.",that.appenderName));that.nbrLogItemsSkipped=0}that.onSendingEnded.call(that)})};return Appender}();JL.Appender=Appender;var AjaxAppender=function(_super){__extends(AjaxAppender,_super);function AjaxAppender(appenderName){return _super.call(this,appenderName,AjaxAppender.prototype.sendLogItemsAjax)||this}AjaxAppender.prototype.setOptions=function(options){copyProperty("url",options,this);copyProperty("beforeSend",options,this);_super.prototype.setOptions.call(this,options);return this};AjaxAppender.prototype.sendLogItemsAjax=function(logItems,successCallback){try{if(!allow(this)){return}if(this.xhr&&this.xhr.readyState!=0&&this.xhr.readyState!=4){this.xhr.abort()}this.xhr=JL._createXMLHttpRequest();var ajaxUrl="/jsnlog.logger";if(!(JL.defaultAjaxUrl==null)){ajaxUrl=JL.defaultAjaxUrl}if(this.url){ajaxUrl=this.url}this.xhr.open("POST",ajaxUrl);this.xhr.setRequestHeader("Content-Type","application/json");this.xhr.setRequestHeader("JSNLog-RequestId",JL.requestId);var that=this;this.xhr.onreadystatechange=function(){if(that.xhr.readyState==4&&(that.xhr.status>=200&&that.xhr.status<300)){successCallback()}};var json={r:JL.requestId,lg:logItems};if(typeof this.beforeSend==="function"){this.beforeSend.call(this,this.xhr,json)}else if(typeof JL.defaultBeforeSend==="function"){JL.defaultBeforeSend.call(this,this.xhr,json)}var finalmsg=JSON.stringify(json);this.xhr.send(finalmsg)}catch(e){}};return AjaxAppender}(Appender);JL.AjaxAppender=AjaxAppender;var ConsoleAppender=function(_super){__extends(ConsoleAppender,_super);function ConsoleAppender(appenderName){return _super.call(this,appenderName,ConsoleAppender.prototype.sendLogItemsConsole)||this}ConsoleAppender.prototype.clog=function(logEntry){JL._console.log(logEntry)};ConsoleAppender.prototype.cerror=function(logEntry){if(JL._console.error){JL._console.error(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cwarn=function(logEntry){if(JL._console.warn){JL._console.warn(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cinfo=function(logEntry){if(JL._console.info){JL._console.info(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cdebug=function(logEntry){if(JL._console.debug){JL._console.debug(logEntry)}else{this.cinfo(logEntry)}};ConsoleAppender.prototype.sendLogItemsConsole=function(logItems,successCallback){try{if(!allow(this)){return}if(!JL._console){return}var i;for(i=0;i<logItems.length;++i){var li=logItems[i];var msg=li.n+": "+li.m;if(typeof window==="undefined"){msg=new Date(li.t)+" | "+msg}if(li.l<=JL.getDebugLevel()){this.cdebug(msg)}else if(li.l<=JL.getInfoLevel()){this.cinfo(msg)}else if(li.l<=JL.getWarnLevel()){this.cwarn(msg)}else{this.cerror(msg)}}}catch(e){}successCallback()};return ConsoleAppender}(Appender);JL.ConsoleAppender=ConsoleAppender;var Logger=function(){function Logger(loggerName){this.loggerName=loggerName;this.seenRegexes=[]}Logger.prototype.setOptions=function(options){copyProperty("level",options,this);copyProperty("userAgentRegex",options,this);copyProperty("disallow",options,this);copyProperty("ipRegex",options,this);copyProperty("appenders",options,this);copyProperty("onceOnly",options,this);this.seenRegexes=[];return this};Logger.prototype.buildExceptionObject=function(e){var excObject={};if(e.stack){excObject.stack=e.stack}else{excObject.e=e}if(e.message){excObject.message=e.message}if(e.name){excObject.name=e.name}if(e.data){excObject.data=e.data}if(e.inner){excObject.inner=this.buildExceptionObject(e.inner)}return excObject};Logger.prototype.log=function(level,logObject,e){var i=0;var compositeMessage;var excObject;if(!this.appenders){return this}if(level>=this.level&&allow(this)){if(e){excObject=this.buildExceptionObject(e);excObject.logData=stringifyLogObjectFunction(logObject)}else{excObject=logObject}compositeMessage=stringifyLogObject(excObject);if(allowMessage(this,compositeMessage.finalString)){if(this.onceOnly){i=this.onceOnly.length-1;while(i>=0){if(new RegExp(this.onceOnly[i]).test(compositeMessage.finalString)){if(this.seenRegexes[i]){return this}this.seenRegexes[i]=true}i--}}compositeMessage.meta=compositeMessage.meta||{};i=this.appenders.length-1;while(i>=0){this.appenders[i].log(levelToString(level),compositeMessage.msg,compositeMessage.meta,function(){},level,compositeMessage.finalString,this.loggerName);i--}}}return this};Logger.prototype.trace=function(logObject){return this.log(getTraceLevel(),logObject)};Logger.prototype.debug=function(logObject){return this.log(getDebugLevel(),logObject)};Logger.prototype.info=function(logObject){return this.log(getInfoLevel(),logObject)};Logger.prototype.warn=function(logObject){return this.log(getWarnLevel(),logObject)};Logger.prototype.error=function(logObject){return this.log(getErrorLevel(),logObject)};Logger.prototype.fatal=function(logObject){return this.log(getFatalLevel(),logObject)};Logger.prototype.fatalException=function(logObject,e){return this.log(getFatalLevel(),logObject,e)};return Logger}();JL.Logger=Logger;function createAjaxAppender(appenderName){return new AjaxAppender(appenderName)}JL.createAjaxAppender=createAjaxAppender;function createConsoleAppender(appenderName){return new ConsoleAppender(appenderName)}JL.createConsoleAppender=createConsoleAppender;var defaultAppender;if(typeof window!=="undefined"){defaultAppender=new AjaxAppender("")}else{defaultAppender=new ConsoleAppender("")}JL.__=new JL.Logger("");JL.__.setOptions({level:JL.getDebugLevel(),appenders:[defaultAppender]})})(JL||(JL={}));if(typeof exports!=="undefined"){exports.__esModule=true;exports.JL=JL}var define;if(typeof define=="function"&&define.amd){define("jsnlog",[],function(){return JL})}if(typeof __jsnlog_configure=="function"){__jsnlog_configure(JL)}if(typeof window!=="undefined"&&!window.onerror){window.onerror=function(errorMsg,url,lineNumber,column,errorObj){JL("onerrorLogger").fatalException({msg:"Uncaught Exception",errorMsg:errorMsg?errorMsg.message||errorMsg:"",url:url,"line number":lineNumber,column:column},errorObj);return false}}if(typeof window!=="undefined"&&!window.onunhandledrejection){window.onunhandledrejection=function(event){JL("onerrorLogger").fatalException({msg:"unhandledrejection",errorMsg:event.reason?event.reason.message:event.message||null},event.reason)}}},{}],8:[function(require,module,exports){"use strict";function Mime(){this._types=Object.create(null);this._extensions=Object.create(null);for(let i=0;i<arguments.length;i++){this.define(arguments[i])}this.define=this.define.bind(this);this.getType=this.getType.bind(this);this.getExtension=this.getExtension.bind(this)}Mime.prototype.define=function(typeMap,force){for(let type in typeMap){let extensions=typeMap[type].map(function(t){return t.toLowerCase()});type=type.toLowerCase();for(let i=0;i<extensions.length;i++){const ext=extensions[i];if(ext[0]==="*"){continue}if(!force&&ext in this._types){throw new Error('Attempt to change mapping for "'+ext+'" extension from "'+this._types[ext]+'" to "'+type+'". Pass `force=true` to allow this, otherwise remove "'+ext+'" from the list of extensions for "'+type+'".')}this._types[ext]=type}if(force||!this._extensions[type]){const ext=extensions[0];this._extensions[type]=ext[0]!=="*"?ext:ext.substr(1)}}};Mime.prototype.getType=function(path){path=String(path);let last=path.replace(/^.*[/\\]/,"").toLowerCase();let ext=last.replace(/^.*\./,"").toLowerCase();let hasPath=last.length<path.length;let hasDot=ext.length<last.length-1;return(hasDot||!hasPath)&&this._types[ext]||null};Mime.prototype.getExtension=function(type){type=/^\s*([^;\s]*)/.test(type)&&RegExp.$1;return type&&this._extensions[type.toLowerCase()]||null};module.exports=Mime},{}],9:[function(require,module,exports){"use strict";let Mime=require("./Mime");module.exports=new Mime(require("./types/standard"),require("./types/other"))},{"./Mime":8,"./types/other":10,"./types/standard":11}],10:[function(require,module,exports){module.exports={"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}},{}],11:[function(require,module,exports){module.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}},{}],12:[function(require,module,exports){var protocols=["stun:","turn:"];module.exports=function(input){var url=(input||{}).url||input;var protocol;var parts;var output={};if(typeof url!="string"&&!(url instanceof String)){return input}url=url.trim();protocol=protocols[protocols.indexOf(url.slice(0,5))];if(!protocol){return input}url=url.slice(5);parts=url.split("@");output.username=input.username;output.credential=input.credential;if(parts.length>1){url=parts[1];parts=parts[0].split(":");output.username=parts[0];output.credential=(input||{}).credential||parts[1]||""}output.url=protocol+url;output.urls=[output.url];return output}},{}],13:[function(require,module,exports){(function(global){(function(){(function(){"use strict";var objectTypes={function:true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var maxSafeInteger=Math.pow(2,53)-1;var reOpera=/\bOpera/;var thisBinding=this;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var toString=objectProto.toString;function capitalize(string){string=String(string);return string.charAt(0).toUpperCase()+string.slice(1)}function cleanupOS(os,pattern,label){var data={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};if(pattern&&label&&/^Win/i.test(os)&&!/^Windows Phone /i.test(os)&&(data=data[/[\d.]+$/.exec(os)])){os="Windows "+data}os=String(os);if(pattern&&label){os=os.replace(RegExp(pattern,"i"),label)}os=format(os.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0]);return os}function each(object,callback){var index=-1,length=object?object.length:0;if(typeof length=="number"&&length>-1&&length<=maxSafeInteger){while(++index<length){callback(object[index],index,object)}}else{forOwn(object,callback)}}function format(string){string=trim(string);return/^(?:webOS|i(?:OS|P))/.test(string)?string:capitalize(string)}function forOwn(object,callback){for(var key in object){if(hasOwnProperty.call(object,key)){callback(object[key],key,object)}}}function getClassOf(value){return value==null?capitalize(value):toString.call(value).slice(8,-1)}function isHostType(object,property){var type=object!=null?typeof object[property]:"number";return!/^(?:boolean|number|string|undefined)$/.test(type)&&(type=="object"?!!object[property]:true)}function qualify(string){return String(string).replace(/([ -])(?!$)/g,"$1?")}function reduce(array,callback){var accumulator=null;each(array,function(value,index){accumulator=callback(accumulator,value,index,array)});return accumulator}function trim(string){return String(string).replace(/^ +| +$/g,"")}function parse(ua){var context=root;var isCustomContext=ua&&typeof ua=="object"&&getClassOf(ua)!="String";if(isCustomContext){context=ua;ua=null}var nav=context.navigator||{};var userAgent=nav.userAgent||"";ua||(ua=userAgent);var isModuleScope=isCustomContext||thisBinding==oldRoot;var likeChrome=isCustomContext?!!nav.likeChrome:/\bChrome\b/.test(ua)&&!/internal|\n/i.test(toString.toString());var objectClass="Object",airRuntimeClass=isCustomContext?objectClass:"ScriptBridgingProxyObject",enviroClass=isCustomContext?objectClass:"Environment",javaClass=isCustomContext&&context.java?"JavaPackage":getClassOf(context.java),phantomClass=isCustomContext?objectClass:"RuntimeObject";var java=/\bJava/.test(javaClass)&&context.java;var rhino=java&&getClassOf(context.environment)==enviroClass;var alpha=java?"a":"α";var beta=java?"b":"β";var doc=context.document||{};var opera=context.operamini||context.opera;var operaClass=reOpera.test(operaClass=isCustomContext&&opera?opera["[[Class]]"]:getClassOf(opera))?operaClass:opera=null;var data;var arch=ua;var description=[];var prerelease=null;var useFeatures=ua==userAgent;var version=useFeatures&&opera&&typeof opera.version=="function"&&opera.version();var isSpecialCasedOS;var layout=getLayout([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"]);var name=getName(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Electron","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel","K-Meleon","Konqueror","Lunascape","Maxthon",{label:"Microsoft Edge",pattern:"(?:Edge|Edg|EdgA|EdgiOS)"},"Midori","Nook Browser","PaleMoon","PhantomJS","Raven","Rekonq","RockMelt",{label:"Samsung Internet",pattern:"SamsungBrowser"},"SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser",{label:"SRWare Iron",pattern:"Iron"},"Sunrise","Swiftfox","Vivaldi","Waterfox","WebPositive",{label:"Yandex Browser",pattern:"YaBrowser"},{label:"UC Browser",pattern:"UCBrowser"},"Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chromium","Chrome",{label:"Chrome",pattern:"(?:HeadlessChrome)"},{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"Firefox for iOS",pattern:"FxiOS"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]);var product=getProduct([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},{label:"Galaxy S5",pattern:"SM-G900"},{label:"Galaxy S6",pattern:"SM-G920"},{label:"Galaxy S6 Edge",pattern:"SM-G925"},{label:"Galaxy S7",pattern:"SM-G930"},{label:"Galaxy S7 Edge",pattern:"SM-G935"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nexus","Nook","PlayBook","PlayStation Vita","PlayStation","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]);var manufacturer=getManufacturer({Apple:{iPad:1,iPhone:1,iPod:1},Alcatel:{},Archos:{},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1,Nexus:1},HP:{TouchPad:1},HTC:{},Huawei:{},Lenovo:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Oppo:{},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{PlayStation:1,"PlayStation Vita":1},Xiaomi:{Mi:1,Redmi:1}});var os=getOS(["Windows Phone","KaiOS","Android","CentOS",{label:"Chrome OS",pattern:"CrOS"},"Debian",{label:"DragonFly BSD",pattern:"DragonFly"},"Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","OpenBSD","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Tizen","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);function getLayout(guesses){return reduce(guesses,function(result,guess){return result||RegExp("\\b"+(guess.pattern||qualify(guess))+"\\b","i").exec(ua)&&(guess.label||guess)})}function getManufacturer(guesses){return reduce(guesses,function(result,value,key){return result||(value[product]||value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)]||RegExp("\\b"+qualify(key)+"(?:\\b|\\w*\\d)","i").exec(ua))&&key})}function getName(guesses){return reduce(guesses,function(result,guess){return result||RegExp("\\b"+(guess.pattern||qualify(guess))+"\\b","i").exec(ua)&&(guess.label||guess)})}function getOS(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);if(!result&&(result=RegExp("\\b"+pattern+"(?:/[\\d.]+|[ \\w.]*)","i").exec(ua))){result=cleanupOS(result,pattern,guess.label||guess)}return result})}function getProduct(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);if(!result&&(result=RegExp("\\b"+pattern+" *\\d+[.\\w_]*","i").exec(ua)||RegExp("\\b"+pattern+" *\\w+-[\\w]*","i").exec(ua)||RegExp("\\b"+pattern+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(ua))){if((result=String(guess.label&&!RegExp(pattern,"i").test(guess.label)?guess.label:result).split("/"))[1]&&!/[\d.]+/.test(result[0])){result[0]+=" "+result[1]}guess=guess.label||guess;result=format(result[0].replace(RegExp(pattern,"i"),guess).replace(RegExp("; *(?:"+guess+"[_-])?","i")," ").replace(RegExp("("+guess+")[-_.]?(\\w)","i"),"$1 $2"))}return result})}function getVersion(patterns){return reduce(patterns,function(result,pattern){return result||(RegExp(pattern+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(ua)||0)[1]||null})}function toStringPlatform(){return this.description||""}layout&&(layout=[layout]);if(/\bAndroid\b/.test(os)&&!product&&(data=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(ua))){product=trim(data[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null}if(manufacturer&&!product){product=getProduct([manufacturer])}else if(manufacturer&&product){product=product.replace(RegExp("^("+qualify(manufacturer)+")[-_.\\s]","i"),manufacturer+" ").replace(RegExp("^("+qualify(manufacturer)+")[-_.]?(\\w)","i"),manufacturer+" $2")}if(data=/\bGoogle TV\b/.exec(product)){product=data[0]}if(/\bSimulator\b/i.test(ua)){product=(product?product+" ":"")+"Simulator"}if(name=="Opera Mini"&&/\bOPiOS\b/.test(ua)){description.push("running in Turbo/Uncompressed mode")}if(name=="IE"&&/\blike iPhone OS\b/.test(ua)){data=parse(ua.replace(/like iPhone OS/,""));manufacturer=data.manufacturer;product=data.product}else if(/^iP/.test(product)){name||(name="Safari");os="iOS"+((data=/ OS ([\d_]+)/i.exec(ua))?" "+data[1].replace(/_/g,"."):"")}else if(name=="Konqueror"&&/^Linux\b/i.test(os)){os="Kubuntu"}else if(manufacturer&&manufacturer!="Google"&&(/Chrome/.test(name)&&!/\bMobile Safari\b/i.test(ua)||/\bVita\b/.test(product))||/\bAndroid\b/.test(os)&&/^Chrome/.test(name)&&/\bVersion\//i.test(ua)){name="Android Browser";os=/\bAndroid\b/.test(os)?os:"Android"}else if(name=="Silk"){if(!/\bMobi/i.test(ua)){os="Android";description.unshift("desktop mode")}if(/Accelerated *= *true/i.test(ua)){description.unshift("accelerated")}}else if(name=="UC Browser"&&/\bUCWEB\b/.test(ua)){description.push("speed mode")}else if(name=="PaleMoon"&&(data=/\bFirefox\/([\d.]+)\b/.exec(ua))){description.push("identifying as Firefox "+data[1])}else if(name=="Firefox"&&(data=/\b(Mobile|Tablet|TV)\b/i.exec(ua))){os||(os="Firefox OS");product||(product=data[1])}else if(!name||(data=!/\bMinefield\b/i.test(ua)&&/\b(?:Firefox|Safari)\b/.exec(name))){if(name&&!product&&/[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data+"/")+8))){name=null}if((data=product||manufacturer||os)&&(product||manufacturer||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))){name=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os)?os:data)+" Browser"}}else if(name=="Electron"&&(data=(/\bChrome\/([\d.]+)\b/.exec(ua)||0)[1])){description.push("Chromium "+data)}if(!version){version=getVersion(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",qualify(name),"(?:Firefox|Minefield|NetFront)"])}if(data=layout=="iCab"&&parseFloat(version)>3&&"WebKit"||/\bOpera\b/.test(name)&&(/\bOPR\b/.test(ua)?"Blink":"Presto")||/\b(?:Midori|Nook|Safari)\b/i.test(ua)&&!/^(?:Trident|EdgeHTML)$/.test(layout)&&"WebKit"||!layout&&/\bMSIE\b/i.test(ua)&&(os=="Mac OS"?"Tasman":"Trident")||layout=="WebKit"&&/\bPlayStation\b(?! Vita\b)/i.test(name)&&"NetFront"){layout=[data]}if(name=="IE"&&(data=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua)||0)[1])){name+=" Mobile";os="Windows Phone "+(/\+$/.test(data)?data:data+".x");description.unshift("desktop mode")}else if(/\bWPDesktop\b/i.test(ua)){name="IE Mobile";os="Windows Phone 8.x";description.unshift("desktop mode");version||(version=(/\brv:([\d.]+)/.exec(ua)||0)[1])}else if(name!="IE"&&layout=="Trident"&&(data=/\brv:([\d.]+)/.exec(ua))){if(name){description.push("identifying as "+name+(version?" "+version:""))}name="IE";version=data[1]}if(useFeatures){if(isHostType(context,"global")){if(java){data=java.lang.System;arch=data.getProperty("os.arch");os=os||data.getProperty("os.name")+" "+data.getProperty("os.version")}if(rhino){try{version=context.require("ringo/engine").version.join(".");name="RingoJS"}catch(e){if((data=context.system)&&data.global.system==context.system){name="Narwhal";os||(os=data[0].os||null)}}if(!name){name="Rhino"}}else if(typeof context.process=="object"&&!context.process.browser&&(data=context.process)){if(typeof data.versions=="object"){if(typeof data.versions.electron=="string"){description.push("Node "+data.versions.node);name="Electron";version=data.versions.electron}else if(typeof data.versions.nw=="string"){description.push("Chromium "+version,"Node "+data.versions.node);name="NW.js";version=data.versions.nw}}if(!name){name="Node.js";arch=data.arch;os=data.platform;version=/[\d.]+/.exec(data.version);version=version?version[0]:null}}}else if(getClassOf(data=context.runtime)==airRuntimeClass){name="Adobe AIR";os=data.flash.system.Capabilities.os}else if(getClassOf(data=context.phantom)==phantomClass){name="PhantomJS";version=(data=data.version||null)&&data.major+"."+data.minor+"."+data.patch}else if(typeof doc.documentMode=="number"&&(data=/\bTrident\/(\d+)/i.exec(ua))){version=[version,doc.documentMode];if((data=+data[1]+4)!=version[1]){description.push("IE "+version[1]+" mode");layout&&(layout[1]="");version[1]=data}version=name=="IE"?String(version[1].toFixed(1)):version[0]}else if(typeof doc.documentMode=="number"&&/^(?:Chrome|Firefox)\b/.test(name)){description.push("masking as "+name+" "+version);name="IE";version="11.0";layout=["Trident"];os="Windows"}os=os&&format(os)}if(version&&(data=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version)||/(?:alpha|beta)(?: ?\d)?/i.exec(ua+";"+(useFeatures&&nav.appMinorVersion))||/\bMinefield\b/i.test(ua)&&"a")){prerelease=/b/i.test(data)?"beta":"alpha";version=version.replace(RegExp(data+"\\+?$"),"")+(prerelease=="beta"?beta:alpha)+(/\d+\+?/.exec(data)||"")}if(name=="Fennec"||name=="Firefox"&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(os)){name="Firefox Mobile"}else if(name=="Maxthon"&&version){version=version.replace(/\.[\d.]+/,".x")}else if(/\bXbox\b/i.test(product)){if(product=="Xbox 360"){os=null}if(product=="Xbox 360"&&/\bIEMobile\b/.test(ua)){description.unshift("mobile mode")}}else if((/^(?:Chrome|IE|Opera)$/.test(name)||name&&!product&&!/Browser|Mobi/.test(name))&&(os=="Windows CE"||/Mobi/i.test(ua))){name+=" Mobile"}else if(name=="IE"&&useFeatures){try{if(context.external===null){description.unshift("platform preview")}}catch(e){description.unshift("embedded")}}else if((/\bBlackBerry\b/.test(product)||/\bBB10\b/.test(ua))&&(data=(RegExp(product.replace(/ +/g," *")+"/([.\\d]+)","i").exec(ua)||0)[1]||version)){data=[data,/BB10/.test(ua)];os=(data[1]?(product=null,manufacturer="BlackBerry"):"Device Software")+" "+data[0];version=null}else if(this!=forOwn&&product!="Wii"&&(useFeatures&&opera||/Opera/.test(name)&&/\b(?:MSIE|Firefox)\b/i.test(ua)||name=="Firefox"&&/\bOS X (?:\d+\.){2,}/.test(os)||name=="IE"&&(os&&!/^Win/.test(os)&&version>5.5||/\bWindows XP\b/.test(os)&&version>8||version==8&&!/\bTrident\b/.test(ua)))&&!reOpera.test(data=parse.call(forOwn,ua.replace(reOpera,"")+";"))&&data.name){data="ing as "+data.name+((data=data.version)?" "+data:"");if(reOpera.test(name)){if(/\bIE\b/.test(data)&&os=="Mac OS"){os=null}data="identify"+data}else{data="mask"+data;if(operaClass){name=format(operaClass.replace(/([a-z])([A-Z])/g,"$1 $2"))}else{name="Opera"}if(/\bIE\b/.test(data)){os=null}if(!useFeatures){version=null}}layout=["Presto"];description.push(data)}if(data=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua)||0)[1]){data=[parseFloat(data.replace(/\.(\d)$/,".0$1")),data];if(name=="Safari"&&data[1].slice(-1)=="+"){name="WebKit Nightly";prerelease="alpha";version=data[1].slice(0,-1)}else if(version==data[1]||version==(data[2]=(/\bSafari\/([\d.]+\+?)/i.exec(ua)||0)[1])){version=null}data[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(ua)||0)[1];if(data[0]==537.36&&data[2]==537.36&&parseFloat(data[1])>=28&&layout=="WebKit"){layout=["Blink"]}if(!useFeatures||!likeChrome&&!data[1]){layout&&(layout[1]="like Safari");data=(data=data[0],data<400?1:data<500?2:data<526?3:data<533?4:data<534?"4+":data<535?5:data<537?6:data<538?7:data<601?8:data<602?9:data<604?10:data<606?11:data<608?12:"12")}else{layout&&(layout[1]="like Chrome");data=data[1]||(data=data[0],data<530?1:data<532?2:data<532.05?3:data<533?4:data<534.03?5:data<534.07?6:data<534.1?7:data<534.13?8:data<534.16?9:data<534.24?10:data<534.3?11:data<535.01?12:data<535.02?"13+":data<535.07?15:data<535.11?16:data<535.19?17:data<536.05?18:data<536.1?19:data<537.01?20:data<537.11?"21+":data<537.13?23:data<537.18?24:data<537.24?25:data<537.36?26:layout!="Blink"?"27":"28")}layout&&(layout[1]+=" "+(data+=typeof data=="number"?".x":/[.+]/.test(data)?"":"+"));if(name=="Safari"&&(!version||parseInt(version)>45)){version=data}else if(name=="Chrome"&&/\bHeadlessChrome/i.test(ua)){description.unshift("headless")}}if(name=="Opera"&&(data=/\bzbov|zvav$/.exec(os))){name+=" ";description.unshift("desktop mode");if(data=="zvav"){name+="Mini";version=null}else{name+="Mobile"}os=os.replace(RegExp(" *"+data+"$"),"")}else if(name=="Safari"&&/\bChrome\b/.exec(layout&&layout[1])){description.unshift("desktop mode");name="Chrome Mobile";version=null;if(/\bOS X\b/.test(os)){manufacturer="Apple";os="iOS 4.3+"}else{os=null}}else if(/\bSRWare Iron\b/.test(name)&&!version){version=getVersion("Chrome")}if(version&&version.indexOf(data=/[\d.]+$/.exec(os))==0&&ua.indexOf("/"+data+"-")>-1){os=trim(os.replace(data,""))}if(os&&os.indexOf(name)!=-1&&!RegExp(name+" OS").test(os)){os=os.replace(RegExp(" *"+qualify(name)+" *"),"")}if(layout&&!/\b(?:Avant|Nook)\b/.test(name)&&(/Browser|Lunascape|Maxthon/.test(name)||name!="Safari"&&/^iOS/.test(os)&&/\bSafari\b/.test(layout[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(name)&&layout[1])){(data=layout[layout.length-1])&&description.push(data)}if(description.length){description=["("+description.join("; ")+")"]}if(manufacturer&&product&&product.indexOf(manufacturer)<0){description.push("on "+manufacturer)}if(product){description.push((/^on /.test(description[description.length-1])?"":"on ")+product)}if(os){data=/ ([\d.+]+)$/.exec(os);isSpecialCasedOS=data&&os.charAt(os.length-data[0].length-1)=="/";os={architecture:32,family:data&&!isSpecialCasedOS?os.replace(data[0],""):os,version:data?data[1]:null,toString:function(){var version=this.version;return this.family+(version&&!isSpecialCasedOS?" "+version:"")+(this.architecture==64?" 64-bit":"")}}}if((data=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch))&&!/\bi686\b/i.test(arch)){if(os){os.architecture=64;os.family=os.family.replace(RegExp(" *"+data),"")}if(name&&(/\bWOW64\b/i.test(ua)||useFeatures&&/\w(?:86|32)$/.test(nav.cpuClass||nav.platform)&&!/\bWin64; x64\b/i.test(ua))){description.unshift("32-bit")}}else if(os&&/^OS X/.test(os.family)&&name=="Chrome"&&parseFloat(version)>=39){os.architecture=64}ua||(ua=null);var platform={};platform.description=ua;platform.layout=layout&&layout[0];platform.manufacturer=manufacturer;platform.name=name;platform.prerelease=prerelease;platform.product=product;platform.ua=ua;platform.version=name&&version;platform.os=os||{architecture:null,family:null,version:null,toString:function(){return"null"}};platform.parse=parse;platform.toString=toStringPlatform;if(platform.version){description.unshift(version)}if(platform.name){description.unshift(name)}if(os&&name&&!(os==String(os).split(" ")[0]&&(os==name.split(" ")[0]||product))){description.push(product?"("+os+")":"on "+os)}if(description.length){platform.description=description.join(" ")}return platform}var platform=parse();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root.platform=platform;define(function(){return platform})}else if(freeExports&&freeModule){forOwn(platform,function(value,key){freeExports[key]=value})}else{root.platform=platform}}).call(this)}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],14:[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}},{}],15:[function(require,module,exports){"use strict";const debug=require("../internal/debug");const{MAX_LENGTH:MAX_LENGTH,MAX_SAFE_INTEGER:MAX_SAFE_INTEGER}=require("../internal/constants");const{safeRe:re,t:t}=require("../internal/re");const parseOptions=require("../internal/parse-options");const{compareIdentifiers:compareIdentifiers}=require("../internal/identifiers");class SemVer{constructor(version,options){options=parseOptions(options);if(version instanceof SemVer){if(version.loose===!!options.loose&&version.includePrerelease===!!options.includePrerelease){return version}else{version=version.version}}else if(typeof version!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)}if(version.length>MAX_LENGTH){throw new TypeError(`version is longer than ${MAX_LENGTH} characters`)}debug("SemVer",version,options);this.options=options;this.loose=!!options.loose;this.includePrerelease=!!options.includePrerelease;const m=version.trim().match(options.loose?re[t.LOOSE]:re[t.FULL]);if(!m){throw new TypeError(`Invalid Version: ${version}`)}this.raw=version;this.major=+m[1];this.minor=+m[2];this.patch=+m[3];if(this.major>MAX_SAFE_INTEGER||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>MAX_SAFE_INTEGER||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>MAX_SAFE_INTEGER||this.patch<0){throw new TypeError("Invalid patch version")}if(!m[4]){this.prerelease=[]}else{this.prerelease=m[4].split(".").map(id=>{if(/^[0-9]+$/.test(id)){const num=+id;if(num>=0&&num<MAX_SAFE_INTEGER){return num}}return id})}this.build=m[5]?m[5].split("."):[];this.format()}format(){this.version=`${this.major}.${this.minor}.${this.patch}`;if(this.prerelease.length){this.version+=`-${this.prerelease.join(".")}`}return this.version}toString(){return this.version}compare(other){debug("SemVer.compare",this.version,this.options,other);if(!(other instanceof SemVer)){if(typeof other==="string"&&other===this.version){return 0}other=new SemVer(other,this.options)}if(other.version===this.version){return 0}return this.compareMain(other)||this.comparePre(other)}compareMain(other){if(!(other instanceof SemVer)){other=new SemVer(other,this.options)}if(this.major<other.major){return-1}if(this.major>other.major){return 1}if(this.minor<other.minor){return-1}if(this.minor>other.minor){return 1}if(this.patch<other.patch){return-1}if(this.patch>other.patch){return 1}return 0}comparePre(other){if(!(other instanceof SemVer)){other=new SemVer(other,this.options)}if(this.prerelease.length&&!other.prerelease.length){return-1}else if(!this.prerelease.length&&other.prerelease.length){return 1}else if(!this.prerelease.length&&!other.prerelease.length){return 0}let i=0;do{const a=this.prerelease[i];const b=other.prerelease[i];debug("prerelease compare",i,a,b);if(a===undefined&&b===undefined){return 0}else if(b===undefined){return 1}else if(a===undefined){return-1}else if(a===b){continue}else{return compareIdentifiers(a,b)}}while(++i)}compareBuild(other){if(!(other instanceof SemVer)){other=new SemVer(other,this.options)}let i=0;do{const a=this.build[i];const b=other.build[i];debug("build compare",i,a,b);if(a===undefined&&b===undefined){return 0}else if(b===undefined){return 1}else if(a===undefined){return-1}else if(a===b){continue}else{return compareIdentifiers(a,b)}}while(++i)}inc(release,identifier,identifierBase){if(release.startsWith("pre")){if(!identifier&&identifierBase===false){throw new Error("invalid increment argument: identifier is empty")}if(identifier){const match=`-${identifier}`.match(this.options.loose?re[t.PRERELEASELOOSE]:re[t.PRERELEASE]);if(!match||match[1]!==identifier){throw new Error(`invalid identifier: ${identifier}`)}}}switch(release){case"premajor":this.prerelease.length=0;this.patch=0;this.minor=0;this.major++;this.inc("pre",identifier,identifierBase);break;case"preminor":this.prerelease.length=0;this.patch=0;this.minor++;this.inc("pre",identifier,identifierBase);break;case"prepatch":this.prerelease.length=0;this.inc("patch",identifier,identifierBase);this.inc("pre",identifier,identifierBase);break;case"prerelease":if(this.prerelease.length===0){this.inc("patch",identifier,identifierBase)}this.inc("pre",identifier,identifierBase);break;case"release":if(this.prerelease.length===0){throw new Error(`version ${this.raw} is not a prerelease`)}this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0){this.major++}this.minor=0;this.patch=0;this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0){this.minor++}this.patch=0;this.prerelease=[];break;case"patch":if(this.prerelease.length===0){this.patch++}this.prerelease=[];break;case"pre":{const base=Number(identifierBase)?1:0;if(this.prerelease.length===0){this.prerelease=[base]}else{let i=this.prerelease.length;while(--i>=0){if(typeof this.prerelease[i]==="number"){this.prerelease[i]++;i=-2}}if(i===-1){if(identifier===this.prerelease.join(".")&&identifierBase===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(base)}}if(identifier){let prerelease=[identifier,base];if(identifierBase===false){prerelease=[identifier]}if(compareIdentifiers(this.prerelease[0],identifier)===0){if(isNaN(this.prerelease[1])){this.prerelease=prerelease}}else{this.prerelease=prerelease}}break}default:throw new Error(`invalid increment argument: ${release}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}}module.exports=SemVer},{"../internal/constants":18,"../internal/debug":19,"../internal/identifiers":20,"../internal/parse-options":21,"../internal/re":22}],16:[function(require,module,exports){"use strict";const SemVer=require("../classes/semver");const major=(a,loose)=>new SemVer(a,loose).major;module.exports=major},{"../classes/semver":15}],17:[function(require,module,exports){"use strict";const SemVer=require("../classes/semver");const minor=(a,loose)=>new SemVer(a,loose).minor;module.exports=minor},{"../classes/semver":15}],18:[function(require,module,exports){"use strict";const SEMVER_SPEC_VERSION="2.0.0";const MAX_LENGTH=256;const MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;const MAX_SAFE_COMPONENT_LENGTH=16;const MAX_SAFE_BUILD_LENGTH=MAX_LENGTH-6;const RELEASE_TYPES=["major","premajor","minor","preminor","patch","prepatch","prerelease"];module.exports={MAX_LENGTH:MAX_LENGTH,MAX_SAFE_COMPONENT_LENGTH:MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH:MAX_SAFE_BUILD_LENGTH,MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,RELEASE_TYPES:RELEASE_TYPES,SEMVER_SPEC_VERSION:SEMVER_SPEC_VERSION,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},{}],19:[function(require,module,exports){(function(process){(function(){"use strict";const debug=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...args)=>console.error("SEMVER",...args):()=>{};module.exports=debug}).call(this)}).call(this,require("_process"))},{_process:14}],20:[function(require,module,exports){"use strict";const numeric=/^[0-9]+$/;const compareIdentifiers=(a,b)=>{if(typeof a==="number"&&typeof b==="number"){return a===b?0:a<b?-1:1}const anum=numeric.test(a);const bnum=numeric.test(b);if(anum&&bnum){a=+a;b=+b}return a===b?0:anum&&!bnum?-1:bnum&&!anum?1:a<b?-1:1};const rcompareIdentifiers=(a,b)=>compareIdentifiers(b,a);module.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},{}],21:[function(require,module,exports){"use strict";const looseOption=Object.freeze({loose:true});const emptyOpts=Object.freeze({});const parseOptions=options=>{if(!options){return emptyOpts}if(typeof options!=="object"){return looseOption}return options};module.exports=parseOptions},{}],22:[function(require,module,exports){"use strict";const{MAX_SAFE_COMPONENT_LENGTH:MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH:MAX_SAFE_BUILD_LENGTH,MAX_LENGTH:MAX_LENGTH}=require("./constants");const debug=require("./debug");exports=module.exports={};const re=exports.re=[];const safeRe=exports.safeRe=[];const src=exports.src=[];const safeSrc=exports.safeSrc=[];const t=exports.t={};let R=0;const LETTERDASHNUMBER="[a-zA-Z0-9-]";const safeRegexReplacements=[["\\s",1],["\\d",MAX_LENGTH],[LETTERDASHNUMBER,MAX_SAFE_BUILD_LENGTH]];const makeSafeRegex=value=>{for(const[token,max]of safeRegexReplacements){value=value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`)}return value};const createToken=(name,value,isGlobal)=>{const safe=makeSafeRegex(value);const index=R++;debug(name,index,value);t[name]=index;src[index]=value;safeSrc[index]=safe;re[index]=new RegExp(value,isGlobal?"g":undefined);safeRe[index]=new RegExp(safe,isGlobal?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);createToken("MAINVERSION",`(${src[t.NUMERICIDENTIFIER]})\\.`+`(${src[t.NUMERICIDENTIFIER]})\\.`+`(${src[t.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.`+`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.`+`(${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASE",`(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${LETTERDASHNUMBER}+`);createToken("BUILD",`(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);createToken("FULL",`^${src[t.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);createToken("LOOSE",`^${src[t.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${src[t.XRANGEIDENTIFIER]})`+`(?:\\.(${src[t.XRANGEIDENTIFIER]})`+`(?:\\.(${src[t.XRANGEIDENTIFIER]})`+`(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])"+"(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})`+`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`+`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);createToken("COERCE",`${src[t.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",src[t.COERCEPLAIN]+`(?:${src[t.PRERELEASE]})?`+`(?:${src[t.BUILD]})?`+`(?:$|[^\\d])`);createToken("COERCERTL",src[t.COERCE],true);createToken("COERCERTLFULL",src[t.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${src[t.LONETILDE]}\\s+`,true);exports.tildeTrimReplace="$1~";createToken("TILDE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${src[t.LONECARET]}\\s+`,true);exports.caretTrimReplace="$1^";createToken("CARET",`^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`,true);exports.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${src[t.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${src[t.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${src[t.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${src[t.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},{"./constants":18,"./debug":19}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"v1",{enumerable:true,get:function(){return _v.default}});Object.defineProperty(exports,"v3",{enumerable:true,get:function(){return _v2.default}});Object.defineProperty(exports,"v4",{enumerable:true,get:function(){return _v3.default}});Object.defineProperty(exports,"v5",{enumerable:true,get:function(){return _v4.default}});Object.defineProperty(exports,"NIL",{enumerable:true,get:function(){return _nil.default}});Object.defineProperty(exports,"version",{enumerable:true,get:function(){return _version.default}});Object.defineProperty(exports,"validate",{enumerable:true,get:function(){return _validate.default}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return _stringify.default}});Object.defineProperty(exports,"parse",{enumerable:true,get:function(){return _parse.default}});var _v=_interopRequireDefault(require("./v1.js"));var _v2=_interopRequireDefault(require("./v3.js"));var _v3=_interopRequireDefault(require("./v4.js"));var _v4=_interopRequireDefault(require("./v5.js"));var _nil=_interopRequireDefault(require("./nil.js"));var _version=_interopRequireDefault(require("./version.js"));var _validate=_interopRequireDefault(require("./validate.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":25,"./parse.js":26,"./stringify.js":30,"./v1.js":31,"./v3.js":32,"./v4.js":34,"./v5.js":35,"./validate.js":36,"./version.js":37}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;function md5(bytes){if(typeof bytes==="string"){const msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(let i=0;i<msg.length;++i){bytes[i]=msg.charCodeAt(i)}}return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes),bytes.length*8))}function md5ToHexEncodedArray(input){const output=[];const length32=input.length*32;const hexTab="0123456789abcdef";for(let i=0;i<length32;i+=8){const x=input[i>>5]>>>i%32&255;const hex=parseInt(hexTab.charAt(x>>>4&15)+hexTab.charAt(x&15),16);output.push(hex)}return output}function getOutputLength(inputLength8){return(inputLength8+64>>>9<<4)+14+1}function wordsToMd5(x,len){x[len>>5]|=128<<len%32;x[getOutputLength(len)-1]=len;let a=1732584193;let b=-271733879;let c=-1732584194;let d=271733878;for(let i=0;i<x.length;i+=16){const olda=a;const oldb=b;const oldc=c;const oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936);d=md5ff(d,a,b,c,x[i+1],12,-389564586);c=md5ff(c,d,a,b,x[i+2],17,606105819);b=md5ff(b,c,d,a,x[i+3],22,-1044525330);a=md5ff(a,b,c,d,x[i+4],7,-176418897);d=md5ff(d,a,b,c,x[i+5],12,1200080426);c=md5ff(c,d,a,b,x[i+6],17,-1473231341);b=md5ff(b,c,d,a,x[i+7],22,-45705983);a=md5ff(a,b,c,d,x[i+8],7,1770035416);d=md5ff(d,a,b,c,x[i+9],12,-1958414417);c=md5ff(c,d,a,b,x[i+10],17,-42063);b=md5ff(b,c,d,a,x[i+11],22,-1990404162);a=md5ff(a,b,c,d,x[i+12],7,1804603682);d=md5ff(d,a,b,c,x[i+13],12,-40341101);c=md5ff(c,d,a,b,x[i+14],17,-1502002290);b=md5ff(b,c,d,a,x[i+15],22,1236535329);a=md5gg(a,b,c,d,x[i+1],5,-165796510);d=md5gg(d,a,b,c,x[i+6],9,-1069501632);c=md5gg(c,d,a,b,x[i+11],14,643717713);b=md5gg(b,c,d,a,x[i],20,-373897302);a=md5gg(a,b,c,d,x[i+5],5,-701558691);d=md5gg(d,a,b,c,x[i+10],9,38016083);c=md5gg(c,d,a,b,x[i+15],14,-660478335);b=md5gg(b,c,d,a,x[i+4],20,-405537848);a=md5gg(a,b,c,d,x[i+9],5,568446438);d=md5gg(d,a,b,c,x[i+14],9,-1019803690);c=md5gg(c,d,a,b,x[i+3],14,-187363961);b=md5gg(b,c,d,a,x[i+8],20,1163531501);a=md5gg(a,b,c,d,x[i+13],5,-1444681467);d=md5gg(d,a,b,c,x[i+2],9,-51403784);c=md5gg(c,d,a,b,x[i+7],14,1735328473);b=md5gg(b,c,d,a,x[i+12],20,-1926607734);a=md5hh(a,b,c,d,x[i+5],4,-378558);d=md5hh(d,a,b,c,x[i+8],11,-2022574463);c=md5hh(c,d,a,b,x[i+11],16,1839030562);b=md5hh(b,c,d,a,x[i+14],23,-35309556);a=md5hh(a,b,c,d,x[i+1],4,-1530992060);d=md5hh(d,a,b,c,x[i+4],11,1272893353);c=md5hh(c,d,a,b,x[i+7],16,-155497632);b=md5hh(b,c,d,a,x[i+10],23,-1094730640);a=md5hh(a,b,c,d,x[i+13],4,681279174);d=md5hh(d,a,b,c,x[i],11,-358537222);c=md5hh(c,d,a,b,x[i+3],16,-722521979);b=md5hh(b,c,d,a,x[i+6],23,76029189);a=md5hh(a,b,c,d,x[i+9],4,-640364487);d=md5hh(d,a,b,c,x[i+12],11,-421815835);c=md5hh(c,d,a,b,x[i+15],16,530742520);b=md5hh(b,c,d,a,x[i+2],23,-995338651);a=md5ii(a,b,c,d,x[i],6,-198630844);d=md5ii(d,a,b,c,x[i+7],10,1126891415);c=md5ii(c,d,a,b,x[i+14],15,-1416354905);b=md5ii(b,c,d,a,x[i+5],21,-57434055);a=md5ii(a,b,c,d,x[i+12],6,1700485571);d=md5ii(d,a,b,c,x[i+3],10,-1894986606);c=md5ii(c,d,a,b,x[i+10],15,-1051523);b=md5ii(b,c,d,a,x[i+1],21,-2054922799);a=md5ii(a,b,c,d,x[i+8],6,1873313359);d=md5ii(d,a,b,c,x[i+15],10,-30611744);c=md5ii(c,d,a,b,x[i+6],15,-1560198380);b=md5ii(b,c,d,a,x[i+13],21,1309151649);a=md5ii(a,b,c,d,x[i+4],6,-145523070);d=md5ii(d,a,b,c,x[i+11],10,-1120210379);c=md5ii(c,d,a,b,x[i+2],15,718787259);b=md5ii(b,c,d,a,x[i+9],21,-343485551);a=safeAdd(a,olda);b=safeAdd(b,oldb);c=safeAdd(c,oldc);d=safeAdd(d,oldd)}return[a,b,c,d]}function bytesToWords(input){if(input.length===0){return[]}const length8=input.length*8;const output=new Uint32Array(getOutputLength(length8));for(let i=0;i<length8;i+=8){output[i>>5]|=(input[i/8]&255)<<i%32}return output}function safeAdd(x,y){const lsw=(x&65535)+(y&65535);const msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bitRotateLeft(num,cnt){return num<<cnt|num>>>32-cnt}function md5cmn(q,a,b,x,s,t){return safeAdd(bitRotateLeft(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b)}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}var _default=md5;exports.default=_default},{}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default="00000000-0000-0000-0000-000000000000";exports.default=_default},{}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function parse(uuid){if(!(0,_validate.default)(uuid)){throw TypeError("Invalid UUID")}let v;const arr=new Uint8Array(16);arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24;arr[1]=v>>>16&255;arr[2]=v>>>8&255;arr[3]=v&255;arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8;arr[5]=v&255;arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8;arr[7]=v&255;arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8;arr[9]=v&255;arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255;arr[11]=v/4294967296&255;arr[12]=v>>>24&255;arr[13]=v>>>16&255;arr[14]=v>>>8&255;arr[15]=v&255;return arr}var _default=parse;exports.default=_default},{"./validate.js":36}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;exports.default=_default},{}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=rng;let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){getRandomValues=typeof crypto!=="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!=="undefined"&&typeof msCrypto.getRandomValues==="function"&&msCrypto.getRandomValues.bind(msCrypto);if(!getRandomValues){throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported")}}return getRandomValues(rnds8)}},{}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}function sha1(bytes){const K=[1518500249,1859775393,2400959708,3395469782];const H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof bytes==="string"){const msg=unescape(encodeURIComponent(bytes));bytes=[];for(let i=0;i<msg.length;++i){bytes.push(msg.charCodeAt(i))}}else if(!Array.isArray(bytes)){bytes=Array.prototype.slice.call(bytes)}bytes.push(128);const l=bytes.length/4+2;const N=Math.ceil(l/16);const M=new Array(N);for(let i=0;i<N;++i){const arr=new Uint32Array(16);for(let j=0;j<16;++j){arr[j]=bytes[i*64+j*4]<<24|bytes[i*64+j*4+1]<<16|bytes[i*64+j*4+2]<<8|bytes[i*64+j*4+3]}M[i]=arr}M[N-1][14]=(bytes.length-1)*8/Math.pow(2,32);M[N-1][14]=Math.floor(M[N-1][14]);M[N-1][15]=(bytes.length-1)*8&4294967295;for(let i=0;i<N;++i){const W=new Uint32Array(80);for(let t=0;t<16;++t){W[t]=M[i][t]}for(let t=16;t<80;++t){W[t]=ROTL(W[t-3]^W[t-8]^W[t-14]^W[t-16],1)}let a=H[0];let b=H[1];let c=H[2];let d=H[3];let e=H[4];for(let t=0;t<80;++t){const s=Math.floor(t/20);const T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[t]>>>0;e=d;d=c;c=ROTL(b,30)>>>0;b=a;a=T}H[0]=H[0]+a>>>0;H[1]=H[1]+b>>>0;H[2]=H[2]+c>>>0;H[3]=H[3]+d>>>0;H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,H[0]&255,H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,H[1]&255,H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,H[2]&255,H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,H[3]&255,H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,H[4]&255]}var _default=sha1;exports.default=_default},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const byteToHex=[];for(let i=0;i<256;++i){byteToHex.push((i+256).toString(16).substr(1))}function stringify(arr,offset=0){const uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!(0,_validate.default)(uuid)){throw TypeError("Stringified UUID is invalid")}return uuid}var _default=stringify;exports.default=_default},{"./validate.js":36}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let _nodeId;let _clockseq;let _lastMSecs=0;let _lastNSecs=0;function v1(options,buf,offset){let i=buf&&offset||0;const b=buf||new Array(16);options=options||{};let node=options.node||_nodeId;let clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;if(node==null||clockseq==null){const seedBytes=options.random||(options.rng||_rng.default)();if(node==null){node=_nodeId=[seedBytes[0]|1,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]}if(clockseq==null){clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&16383}}let msecs=options.msecs!==undefined?options.msecs:Date.now();let nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;const dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&16383}if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0}if(nsecs>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=122192928e5;const tl=((msecs&268435455)*1e4+nsecs)%4294967296;b[i++]=tl>>>24&255;b[i++]=tl>>>16&255;b[i++]=tl>>>8&255;b[i++]=tl&255;const tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255;b[i++]=tmh&255;b[i++]=tmh>>>24&15|16;b[i++]=tmh>>>16&255;b[i++]=clockseq>>>8|128;b[i++]=clockseq&255;for(let n=0;n<6;++n){b[i+n]=node[n]}return buf||(0,_stringify.default)(b)}var _default=v1;exports.default=_default},{"./rng.js":28,"./stringify.js":30}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const v3=(0,_v.default)("v3",48,_md.default);var _default=v3;exports.default=_default},{"./md5.js":24,"./v35.js":33}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function stringToBytes(str){str=unescape(encodeURIComponent(str));const bytes=[];for(let i=0;i<str.length;++i){bytes.push(str.charCodeAt(i))}return bytes}const DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";exports.DNS=DNS;const URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";exports.URL=URL;function _default(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if(typeof value==="string"){value=stringToBytes(value)}if(typeof namespace==="string"){namespace=(0,_parse.default)(namespace)}if(namespace.length!==16){throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)")}let bytes=new Uint8Array(16+value.length);bytes.set(namespace);bytes.set(value,namespace.length);bytes=hashfunc(bytes);bytes[6]=bytes[6]&15|version;bytes[8]=bytes[8]&63|128;if(buf){offset=offset||0;for(let i=0;i<16;++i){buf[offset+i]=bytes[i]}return buf}return(0,_stringify.default)(bytes)}try{generateUUID.name=name}catch(err){}generateUUID.DNS=DNS;generateUUID.URL=URL;return generateUUID}},{"./parse.js":26,"./stringify.js":30}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function v4(options,buf,offset){options=options||{};const rnds=options.random||(options.rng||_rng.default)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){offset=offset||0;for(let i=0;i<16;++i){buf[offset+i]=rnds[i]}return buf}return(0,_stringify.default)(rnds)}var _default=v4;exports.default=_default},{"./rng.js":28,"./stringify.js":30}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const v5=(0,_v.default)("v5",80,_sha.default);var _default=v5;exports.default=_default},{"./sha1.js":29,"./v35.js":33}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _regex=_interopRequireDefault(require("./regex.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function validate(uuid){return typeof uuid==="string"&&_regex.default.test(uuid)}var _default=validate;exports.default=_default},{"./regex.js":27}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function version(uuid){if(!(0,_validate.default)(uuid)){throw TypeError("Invalid UUID")}return parseInt(uuid.substr(14,1),16)}var _default=version;exports.default=_default},{"./validate.js":36}],38:[function(require,module,exports){module.exports=WildEmitter;function WildEmitter(){}WildEmitter.mixin=function(constructor){var prototype=constructor.prototype||constructor;prototype.isWildEmitter=true;prototype.on=function(event,groupName,fn){this.callbacks=this.callbacks||{};var hasGroup=arguments.length===3,group=hasGroup?arguments[1]:undefined,func=hasGroup?arguments[2]:arguments[1];func._groupName=group;(this.callbacks[event]=this.callbacks[event]||[]).push(func);return this};prototype.once=function(event,groupName,fn){var self=this,hasGroup=arguments.length===3,group=hasGroup?arguments[1]:undefined,func=hasGroup?arguments[2]:arguments[1];function on(){self.off(event,on);func.apply(this,arguments)}this.on(event,group,on);return this};prototype.releaseGroup=function(groupName){this.callbacks=this.callbacks||{};var item,i,len,handlers;for(item in this.callbacks){handlers=this.callbacks[item];for(i=0,len=handlers.length;i<len;i++){if(handlers[i]._groupName===groupName){handlers.splice(i,1);i--;len--}}}return this};prototype.off=function(event,fn){this.callbacks=this.callbacks||{};var callbacks=this.callbacks[event],i;if(!callbacks)return this;if(arguments.length===1){delete this.callbacks[event];return this}i=callbacks.indexOf(fn);if(i!==-1){callbacks.splice(i,1);if(callbacks.length===0){delete this.callbacks[event]}}return this};prototype.emit=function(event){this.callbacks=this.callbacks||{};var args=[].slice.call(arguments,1),callbacks=this.callbacks[event],specialCallbacks=this.getWildcardCallbacks(event),i,len,item,listeners;if(callbacks){listeners=callbacks.slice();for(i=0,len=listeners.length;i<len;++i){if(!listeners[i]){break}listeners[i].apply(this,args)}}if(specialCallbacks){len=specialCallbacks.length;listeners=specialCallbacks.slice();for(i=0,len=listeners.length;i<len;++i){if(!listeners[i]){break}listeners[i].apply(this,[event].concat(args))}}return this};prototype.getWildcardCallbacks=function(eventName){this.callbacks=this.callbacks||{};var item,split,result=[];for(item in this.callbacks){split=item.split("*");if(item==="*"||split.length===2&&eventName.slice(0,split[0].length)===split[0]){result=result.concat(this.callbacks[item])}}return result}};WildEmitter.mixin(WildEmitter)},{}],39:[function(require,module,exports){(function(exports){"use strict";function EventEmitter(){}var proto=EventEmitter.prototype;var originalGlobalValue=exports.EventEmitter;function indexOfListener(listeners,listener){var i=listeners.length;while(i--){if(listeners[i].listener===listener){return i}}return-1}function alias(name){return function aliasClosure(){return this[name].apply(this,arguments)}}proto.getListeners=function getListeners(evt){var events=this._getEvents();var response;var key;if(evt instanceof RegExp){response={};for(key in events){if(events.hasOwnProperty(key)&&evt.test(key)){response[key]=events[key]}}}else{response=events[evt]||(events[evt]=[])}return response};proto.flattenListeners=function flattenListeners(listeners){var flatListeners=[];var i;for(i=0;i<listeners.length;i+=1){flatListeners.push(listeners[i].listener)}return flatListeners};proto.getListenersAsObject=function getListenersAsObject(evt){var listeners=this.getListeners(evt);var response;if(listeners instanceof Array){response={};response[evt]=listeners}return response||listeners};function isValidListener(listener){if(typeof listener==="function"||listener instanceof RegExp){return true}else if(listener&&typeof listener==="object"){return isValidListener(listener.listener)}else{return false}}proto.addListener=function addListener(evt,listener){if(!isValidListener(listener)){throw new TypeError("listener must be a function")}var listeners=this.getListenersAsObject(evt);var listenerIsWrapped=typeof listener==="object";var key;for(key in listeners){if(listeners.hasOwnProperty(key)&&indexOfListener(listeners[key],listener)===-1){listeners[key].push(listenerIsWrapped?listener:{listener:listener,once:false})}}return this};proto.on=alias("addListener");proto.addOnceListener=function addOnceListener(evt,listener){return this.addListener(evt,{listener:listener,once:true})};proto.once=alias("addOnceListener");proto.defineEvent=function defineEvent(evt){this.getListeners(evt);return this};proto.defineEvents=function defineEvents(evts){for(var i=0;i<evts.length;i+=1){this.defineEvent(evts[i])}return this};proto.removeListener=function removeListener(evt,listener){var listeners=this.getListenersAsObject(evt);var index;var key;for(key in listeners){if(listeners.hasOwnProperty(key)){index=indexOfListener(listeners[key],listener);if(index!==-1){listeners[key].splice(index,1)}}}return this};proto.off=alias("removeListener");proto.addListeners=function addListeners(evt,listeners){return this.manipulateListeners(false,evt,listeners)};proto.removeListeners=function removeListeners(evt,listeners){return this.manipulateListeners(true,evt,listeners)};proto.manipulateListeners=function manipulateListeners(remove,evt,listeners){var i;var value;var single=remove?this.removeListener:this.addListener;var multiple=remove?this.removeListeners:this.addListeners;if(typeof evt==="object"&&!(evt instanceof RegExp)){for(i in evt){if(evt.hasOwnProperty(i)&&(value=evt[i])){if(typeof value==="function"){single.call(this,i,value)}else{multiple.call(this,i,value)}}}}else{i=listeners.length;while(i--){single.call(this,evt,listeners[i])}}return this};proto.removeEvent=function removeEvent(evt){var type=typeof evt;var events=this._getEvents();var key;if(type==="string"){delete events[evt]}else if(evt instanceof RegExp){for(key in events){if(events.hasOwnProperty(key)&&evt.test(key)){delete events[key]}}}else{delete this._events}return this};proto.removeAllListeners=alias("removeEvent");proto.emitEvent=function emitEvent(evt,args){var listenersMap=this.getListenersAsObject(evt);var listeners;var listener;var i;var key;var response;for(key in listenersMap){if(listenersMap.hasOwnProperty(key)){listeners=listenersMap[key].slice(0);for(i=0;i<listeners.length;i++){listener=listeners[i];if(listener.once===true){this.removeListener(evt,listener.listener)}response=listener.listener.apply(this,args||[]);if(response===this._getOnceReturnValue()){this.removeListener(evt,listener.listener)}}}}return this};proto.trigger=alias("emitEvent");proto.emit=function emit(evt){var args=Array.prototype.slice.call(arguments,1);return this.emitEvent(evt,args)};proto.setOnceReturnValue=function setOnceReturnValue(value){this._onceReturnValue=value;return this};proto._getOnceReturnValue=function _getOnceReturnValue(){if(this.hasOwnProperty("_onceReturnValue")){return this._onceReturnValue}else{return true}};proto._getEvents=function _getEvents(){return this._events||(this._events={})};EventEmitter.noConflict=function noConflict(){exports.EventEmitter=originalGlobalValue;return EventEmitter};if(typeof define==="function"&&define.amd){define(function(){return EventEmitter})}else if(typeof module==="object"&&module.exports){module.exports=EventEmitter}else{exports.EventEmitter=EventEmitter}})(typeof window!=="undefined"?window:this||{})},{}],40:[function(require,module,exports){module.exports={author:"OpenVidu",dependencies:{events:"3.3.0",freeice:"2.2.2",hark:"1.2.3",inherits:"2.0.4",jsnlog:"2.30.0",mime:"2.6.0",platform:"1.3.6",semver:"7.7.3",uuid:"^8.3.2","wolfy87-eventemitter":"5.2.9"},description:"OpenVidu Browser",devDependencies:{"@types/node":"24.10.1","@types/platform":"1.3.6","@typescript-eslint/eslint-plugin":"8.47.0","@typescript-eslint/parser":"8.47.0",browserify:"17.0.1",eslint:"9.39.1","eslint-import-resolver-typescript":"4.4.4","eslint-plugin-import":"2.32.0","patch-package":"^8.0.1",prettier:"3.6.2",terser:"5.44.1",tsify:"5.0.4",typedoc:"0.28.14",typescript:"5.9.3","undici-types":"7.16.0"},license:"Apache-2.0",main:"lib/index.js",name:"openvidu-browser",repository:{type:"git",url:"git://github.com/OpenVidu/openvidu"},scripts:{browserify:"VERSION=${VERSION:-dev}; mkdir -p static/js/ && cd src && ../node_modules/browserify/bin/cmd.js Main.ts -p [ tsify ] --exclude kurento-browser-extensions --debug -o ../static/js/openvidu-browser-$VERSION.js -v","browserify-prod":"VERSION=${VERSION:-dev}; mkdir -p static/js/ && cd src && ../node_modules/browserify/bin/cmd.js --debug Main.ts -p [ tsify ] --exclude kurento-browser-extensions | ../node_modules/terser/bin/terser --source-map content=inline --output ../static/js/openvidu-browser-$VERSION.min.js",build:"npm run lint && npm run beautify && cd src/OpenVidu && ./../../node_modules/typescript/bin/tsc && cd ../.. && ./node_modules/typescript/bin/tsc --declaration src/index.ts --outDir ./lib --sourceMap --target es2015 --module commonjs --moduleResolution node --lib dom,es2015,scripthost && rm -rf ./ts4.4 && mkdir -p ./ts4.4/lib && cp -r ./lib ./ts4.4 && find ./ts4.4/lib -type f ! -iname '*.d.ts' -delete && ./config/replace_for_ts44.sh",docs:"./generate-docs.sh",lint:"eslint . --ext .ts",beautify:"prettier --write ."},types:"lib/index.d.ts",typesVersions:{"<4.4":{"*":["ts4.4/*"]}},version:"2.32.1"}},{}],41:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const OpenVidu_1=require("./OpenVidu/OpenVidu");const jsnlog_1=require("jsnlog");if(typeof globalThis!=="undefined"){globalThis["OpenVidu"]=OpenVidu_1.OpenVidu}jsnlog_1.JL.setOptions({enabled:false})},{"./OpenVidu/OpenVidu":46,jsnlog:7}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Connection=void 0;const Stream_1=require("./Stream");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class Connection{constructor(session,connectionOptions){this.session=session;this.disposed=false;let msg="'Connection' created ";if(!!connectionOptions.role){this.localOptions=connectionOptions;this.connectionId=this.localOptions.id;this.creationTime=this.localOptions.createdAt;this.data=this.localOptions.metadata;this.rpcSessionId=this.localOptions.sessionId;this.role=this.localOptions.role;this.record=this.localOptions.record;msg+="(local)"}else{this.remoteOptions=connectionOptions;this.connectionId=this.remoteOptions.id;this.creationTime=this.remoteOptions.createdAt;if(this.remoteOptions.metadata){this.data=this.remoteOptions.metadata}if(this.remoteOptions.streams){this.initRemoteStreams(this.remoteOptions.streams)}msg+="(remote) with 'connectionId' ["+this.remoteOptions.id+"]"}logger.info(msg)}sendIceCandidate(candidate){if(!this.disposed){logger.debug((!!this.stream.outboundStreamOpts?"Local":"Remote")+"candidate for"+this.connectionId,candidate);this.session.openvidu.sendRequest("onIceCandidate",{endpointName:this.connectionId,candidate:candidate.candidate,sdpMid:candidate.sdpMid,sdpMLineIndex:candidate.sdpMLineIndex},(error,response)=>{if(error){logger.error("Error sending ICE candidate: "+JSON.stringify(error));this.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.session,ExceptionEvent_1.ExceptionEventName.ICE_CANDIDATE_ERROR,this.session,"There was an unexpected error on the server-side processing an ICE candidate generated and sent by the client-side",error)])}})}else{logger.warn(`Connection ${this.connectionId} disposed when trying to send an ICE candidate. ICE candidate not sent`)}}initRemoteStreams(options){options.forEach(opts=>{const streamOptions={id:opts.id,createdAt:opts.createdAt,connection:this,hasAudio:opts.hasAudio,hasVideo:opts.hasVideo,audioActive:opts.audioActive,videoActive:opts.videoActive,typeOfVideo:opts.typeOfVideo,frameRate:opts.frameRate,videoDimensions:!!opts.videoDimensions?JSON.parse(opts.videoDimensions):undefined,filter:!!opts.filter?opts.filter:undefined};const stream=new Stream_1.Stream(this.session,streamOptions);this.addStream(stream)});logger.info("Remote 'Connection' with 'connectionId' ["+this.connectionId+"] is now configured for receiving Streams with options: ",this.stream.inboundStreamOpts)}addStream(stream){stream.connection=this;this.stream=stream}removeStream(){delete this.stream}dispose(){this.disposed=true;this.removeStream()}}exports.Connection=Connection},{"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Logger/OpenViduLogger":81,"./Stream":49}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventDispatcher=void 0;const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const EventEmitter=require("wolfy87-eventemitter");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class EventDispatcher{constructor(){this.userHandlerArrowHandler=new WeakMap;this.ee=new EventEmitter}onAux(type,message,handler){const arrowHandler=event=>{if(event){logger.debug(message,event)}else{logger.debug(message)}handler(event)};this.userHandlerArrowHandler.set(handler,arrowHandler);this.ee.on(type,arrowHandler);return this}onceAux(type,message,handler){const arrowHandler=event=>{if(event){logger.debug(message,event)}else{logger.debug(message)}handler(event);this.userHandlerArrowHandler.delete(handler)};this.userHandlerArrowHandler.set(handler,arrowHandler);this.ee.once(type,arrowHandler);return this}offAux(type,handler){if(!handler){this.ee.removeAllListeners(type)}else{const arrowHandler=this.userHandlerArrowHandler.get(handler);if(!!arrowHandler){this.ee.off(type,arrowHandler)}this.userHandlerArrowHandler.delete(handler)}return this}}exports.EventDispatcher=EventDispatcher},{"../OpenViduInternal/Logger/OpenViduLogger":81,"wolfy87-eventemitter":39}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Filter=void 0;const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class Filter{constructor(type,options){this.handlers=new Map;this.type=type;this.options=options}execMethod(method,params){return new Promise((resolve,reject)=>{var _a;logger.info("Executing filter method to stream "+this.stream.streamId);let finalParams;const successExecMethod=triggerEvent=>{logger.info("Filter method successfully executed on Stream "+this.stream.streamId);const oldValue=Object.assign({},this.stream.filter);this.stream.filter.lastExecMethod={method:method,params:finalParams};if(triggerEvent){this.stream.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.stream.session,this.stream,"filter",this.stream.filter,oldValue,"execFilterMethod")]);this.stream.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.stream.streamManager,this.stream,"filter",this.stream.filter,oldValue,"execFilterMethod")])}return resolve()};if(this.type.startsWith("VB:")){if(typeof params==="string"){try{params=JSON.parse(params)}catch(error){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"Wrong params syntax: "+error))}}finalParams=params;if(method==="update"){if(!((_a=this.stream.virtualBackgroundSinkElements)===null||_a===void 0?void 0:_a.VB)){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"There is no Virtual Background filter applied"))}else{this.stream.virtualBackgroundSinkElements.VB.updateValues(params).then(()=>successExecMethod(false)).catch(error=>{if(error.name===OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR){return reject(new OpenViduError_1.OpenViduError(error.name,error.message))}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"Error updating values on Virtual Background filter: "+error))}})}}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,`Unknown Virtual Background method "${method}"`))}}else{let stringParams;if(typeof params!=="string"){try{stringParams=JSON.stringify(params)}catch(error){const errorMsg="'params' property must be a JSON formatted object";logger.error(errorMsg);return reject(errorMsg)}}else{stringParams=params}finalParams=stringParams;this.stream.session.openvidu.sendRequest("execFilterMethod",{streamId:this.stream.streamId,method:method,params:stringParams},(error,response)=>{if(error){logger.error("Error executing filter method for Stream "+this.stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to execute a filter method"))}else{return reject(error)}}else{return successExecMethod(true)}})}})}addEventListener(eventType,handler){return new Promise((resolve,reject)=>{logger.info("Adding filter event listener to event "+eventType+" to stream "+this.stream.streamId);this.stream.session.openvidu.sendRequest("addFilterEventListener",{streamId:this.stream.streamId,eventType:eventType},(error,response)=>{if(error){logger.error("Error adding filter event listener to event "+eventType+"for Stream "+this.stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to add a filter event listener"))}else{return reject(error)}}else{this.handlers.set(eventType,handler);logger.info("Filter event listener to event "+eventType+" successfully applied on Stream "+this.stream.streamId);return resolve()}})})}removeEventListener(eventType){return new Promise((resolve,reject)=>{logger.info("Removing filter event listener to event "+eventType+" to stream "+this.stream.streamId);this.stream.session.openvidu.sendRequest("removeFilterEventListener",{streamId:this.stream.streamId,eventType:eventType},(error,response)=>{if(error){logger.error("Error removing filter event listener to event "+eventType+"for Stream "+this.stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to add a filter event listener"))}else{return reject(error)}}else{this.handlers.delete(eventType);logger.info("Filter event listener to event "+eventType+" successfully removed on Stream "+this.stream.streamId);return resolve()}})})}}exports.Filter=Filter},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81}],45:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.LocalRecorder=void 0;const LocalRecorderState_1=require("../OpenViduInternal/Enums/LocalRecorderState");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const mime_1=__importDefault(require("mime"));const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class LocalRecorder{constructor(stream){this.stream=stream;this.chunks=[];platform=Platform_1.PlatformUtils.getInstance();this.connectionId=!!this.stream.connection?this.stream.connection.connectionId:"default-connection";this.id=this.stream.streamId+"_"+this.connectionId+"_localrecord";this.state=LocalRecorderState_1.LocalRecorderState.READY}record(options){return new Promise((resolve,reject)=>{try{if(typeof options==="string"||options instanceof String){return reject(`When calling LocalRecorder.record(options) parameter 'options' cannot be a string. Must be an object like { mimeType: "${options}" }`)}if(typeof MediaRecorder==="undefined"){logger.error("MediaRecorder not supported on your device. See compatibility in https://caniuse.com/#search=MediaRecorder");throw Error("MediaRecorder not supported on your device. See compatibility in https://caniuse.com/#search=MediaRecorder")}if(this.state!==LocalRecorderState_1.LocalRecorderState.READY){throw Error("'LocalRecord.record()' needs 'LocalRecord.state' to be 'READY' (current value: '"+this.state+"'). Call 'LocalRecorder.clean()' or init a new LocalRecorder before")}logger.log("Starting local recording of stream '"+this.stream.streamId+"' of connection '"+this.connectionId+"'");if(!options){options={mimeType:"video/webm"}}else if(!options.mimeType){options.mimeType="video/webm"}this.mediaRecorder=new MediaRecorder(this.stream.getMediaStream(),options);this.mediaRecorder.start()}catch(err){return reject(err)}this.mediaRecorder.ondataavailable=e=>{if(e.data.size>0){this.chunks.push(e.data)}};this.mediaRecorder.onerror=e=>{logger.error("MediaRecorder error: ",e)};this.mediaRecorder.onstart=()=>{logger.log("MediaRecorder started (state="+this.mediaRecorder.state+")")};this.mediaRecorder.onstop=()=>{this.onStopDefault()};this.mediaRecorder.onpause=()=>{logger.log("MediaRecorder paused (state="+this.mediaRecorder.state+")")};this.mediaRecorder.onresume=()=>{logger.log("MediaRecorder resumed (state="+this.mediaRecorder.state+")")};this.state=LocalRecorderState_1.LocalRecorderState.RECORDING;return resolve()})}stop(){return new Promise((resolve,reject)=>{try{if(this.state===LocalRecorderState_1.LocalRecorderState.READY||this.state===LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.stop()' needs 'LocalRecord.state' to be 'RECORDING' or 'PAUSED' (current value: '"+this.state+"'). Call 'LocalRecorder.start()' before")}this.mediaRecorder.onstop=()=>{this.onStopDefault();return resolve()};this.mediaRecorder.stop()}catch(e){return reject(e)}})}pause(){return new Promise((resolve,reject)=>{try{if(this.state!==LocalRecorderState_1.LocalRecorderState.RECORDING){return reject(Error("'LocalRecord.pause()' needs 'LocalRecord.state' to be 'RECORDING' (current value: '"+this.state+"'). Call 'LocalRecorder.start()' or 'LocalRecorder.resume()' before"))}this.mediaRecorder.pause();this.state=LocalRecorderState_1.LocalRecorderState.PAUSED;return resolve()}catch(error){return reject(error)}})}resume(){return new Promise((resolve,reject)=>{try{if(this.state!==LocalRecorderState_1.LocalRecorderState.PAUSED){throw Error("'LocalRecord.resume()' needs 'LocalRecord.state' to be 'PAUSED' (current value: '"+this.state+"'). Call 'LocalRecorder.pause()' before")}this.mediaRecorder.resume();this.state=LocalRecorderState_1.LocalRecorderState.RECORDING;return resolve()}catch(error){return reject(error)}})}preview(parentElement){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.preview()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before")}this.videoPreview=document.createElement("video");this.videoPreview.id=this.id;this.videoPreview.autoplay=true;if(platform.isSafariBrowser()){this.videoPreview.playsInline=true}if(typeof parentElement==="string"){const parentElementDom=document.getElementById(parentElement);if(parentElementDom){this.videoPreview=parentElementDom.appendChild(this.videoPreview)}}else{this.videoPreview=parentElement.appendChild(this.videoPreview)}this.videoPreview.src=this.videoPreviewSrc;return this.videoPreview}clean(){const f=()=>{delete this.blob;this.chunks=[];this.state=LocalRecorderState_1.LocalRecorderState.READY};if(this.state===LocalRecorderState_1.LocalRecorderState.RECORDING||this.state===LocalRecorderState_1.LocalRecorderState.PAUSED){this.stop().then(()=>f()).catch(()=>f())}else{f()}}download(){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.download()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before")}else{const a=document.createElement("a");a.style.display="none";document.body.appendChild(a);const url=globalThis.URL.createObjectURL(this.blob);a.href=url;a.download=this.id+"."+mime_1.default.getExtension(this.blob.type);a.click();globalThis.URL.revokeObjectURL(url);document.body.removeChild(a)}}getBlob(){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("Call 'LocalRecord.stop()' before getting Blob file")}else{return this.blob}}uploadAsBinary(endpoint,headers){return new Promise((resolve,reject)=>{if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){return reject(Error("'LocalRecord.uploadAsBinary()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before"))}else{const http=new XMLHttpRequest;http.open("POST",endpoint,true);if(typeof headers==="object"){for(const key of Object.keys(headers)){http.setRequestHeader(key,headers[key])}}http.onreadystatechange=()=>{if(http.readyState===4){if(http.status.toString().charAt(0)==="2"){return resolve(http.responseText)}else{return reject(http.status)}}};http.send(this.blob)}})}uploadAsMultipartfile(endpoint,headers){return new Promise((resolve,reject)=>{if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){return reject(Error("'LocalRecord.uploadAsMultipartfile()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before"))}else{const http=new XMLHttpRequest;http.open("POST",endpoint,true);if(typeof headers==="object"){for(const key of Object.keys(headers)){http.setRequestHeader(key,headers[key])}}const sendable=new FormData;sendable.append("file",this.blob,this.id+"."+mime_1.default.getExtension(this.blob.type));http.onreadystatechange=()=>{if(http.readyState===4){if(http.status.toString().charAt(0)==="2"){return resolve(http.responseText)}else{return reject(http.status)}}};http.send(sendable)}})}onStopDefault(){logger.log("MediaRecorder stopped (state="+this.mediaRecorder.state+")");this.blob=new Blob(this.chunks,{type:this.mediaRecorder.mimeType});this.chunks=[];this.videoPreviewSrc=globalThis.URL.createObjectURL(this.blob);this.state=LocalRecorderState_1.LocalRecorderState.FINISHED}}exports.LocalRecorder=LocalRecorder},{"../OpenViduInternal/Enums/LocalRecorderState":52,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,mime:9}],46:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||function(){var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)if(Object.prototype.hasOwnProperty.call(o,k))ar[ar.length]=k;return ar};return ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k=ownKeys(mod),i=0;i<k.length;i++)if(k[i]!=="default")__createBinding(result,mod,k[i]);__setModuleDefault(result,mod);return result}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.OpenVidu=void 0;const LocalRecorder_1=require("./LocalRecorder");const Publisher_1=require("./Publisher");const Session_1=require("./Session");const SessionDisconnectedEvent_1=require("../OpenViduInternal/Events/SessionDisconnectedEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const screenSharingAuto=__importStar(require("../OpenViduInternal/ScreenSharing/Screen-Capturing-Auto"));const screenSharing=__importStar(require("../OpenViduInternal/ScreenSharing/Screen-Capturing"));const EventEmitter=require("wolfy87-eventemitter");const RpcBuilder=require("../OpenViduInternal/KurentoUtils/kurento-jsonrpc");const packageJson=require("../../package.json");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class OpenVidu{constructor(){this.masterNodeHasCrashed=false;this.publishers=[];this.secret="";this.recorder=false;this.stt=false;this.life=-1;this.advancedConfiguration={};this.webrtcStatsInterval=-1;this.sendBrowserLogs="disabled";this.isAtLeastPro=false;this.isEnterprise=false;this.ee=new EventEmitter;platform=Platform_1.PlatformUtils.getInstance();this.libraryVersion=packageJson.version;logger.info("OpenVidu initialized");logger.info("Platform detected: "+platform.getDescription());logger.info("openvidu-browser version: "+this.libraryVersion);if(platform.isMobileDevice()||platform.isReactNative()){this.onOrientationChanged(()=>{this.publishers.forEach(publisher=>{if(publisher.stream.isLocalStreamPublished&&!!publisher.stream&&!!publisher.stream.hasVideo){this.sendNewVideoDimensionsIfRequired(publisher,"deviceRotated",75,10)}})})}}initSession(){this.session=new Session_1.Session(this);return this.session}initPublisher(targetElement,param2,param3){let properties;if(!!param2&&typeof param2!=="function"){properties=param2;properties={audioSource:typeof properties.audioSource!=="undefined"?properties.audioSource:undefined,frameRate:typeof MediaStreamTrack!=="undefined"&&properties.videoSource instanceof MediaStreamTrack?undefined:typeof properties.frameRate!=="undefined"?properties.frameRate:undefined,insertMode:typeof properties.insertMode!=="undefined"?typeof properties.insertMode==="string"?VideoInsertMode_1.VideoInsertMode[properties.insertMode]:properties.insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,mirror:typeof properties.mirror!=="undefined"?properties.mirror:true,publishAudio:typeof properties.publishAudio!=="undefined"?properties.publishAudio:true,publishVideo:typeof properties.publishVideo!=="undefined"?properties.publishVideo:true,resolution:typeof MediaStreamTrack!=="undefined"&&properties.videoSource instanceof MediaStreamTrack?undefined:typeof properties.resolution!=="undefined"?properties.resolution:"640x480",videoSource:typeof properties.videoSource!=="undefined"?properties.videoSource:undefined,videoSimulcast:properties.videoSimulcast,filter:properties.filter}}else{properties={insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,mirror:true,publishAudio:true,publishVideo:true,resolution:"640x480"}}const publisher=new Publisher_1.Publisher(targetElement,properties,this);let completionHandler;if(!!param2&&typeof param2==="function"){completionHandler=param2}else if(!!param3){completionHandler=param3}publisher.initialize().then(()=>{if(completionHandler!==undefined){completionHandler(undefined)}publisher.emitEvent("accessAllowed",[])}).catch(error=>{if(completionHandler!==undefined){completionHandler(error)}publisher.emitEvent("accessDenied",[error])});this.publishers.push(publisher);return publisher}initPublisherAsync(targetElement,properties){return new Promise((resolve,reject)=>{let publisher;const callback=error=>{if(!!error){return reject(error)}else{return resolve(publisher)}};if(!!properties){publisher=this.initPublisher(targetElement,properties,callback)}else{publisher=this.initPublisher(targetElement,callback)}})}initLocalRecorder(stream){return new LocalRecorder_1.LocalRecorder(stream)}checkSystemRequirements(){if(platform.isIPhoneOrIPad()){return platform.isIOSWithSafari()||platform.isChromeMobileBrowser()||platform.isFirefoxMobileBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isIonicIos()}return platform.isChromeBrowser()||platform.isChromeMobileBrowser()||platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()||platform.isOperaBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeBrowser()||platform.isEdgeMobileBrowser()||platform.isSamsungBrowser()||platform.isSafariBrowser()||platform.isAndroidBrowser()||platform.isElectron()||platform.isNodeJs()||platform.isMotorolaEdgeDevice()}checkScreenSharingCapabilities(){return platform.canScreenShare()}getDevices(){return new Promise((resolve,reject)=>{navigator.mediaDevices.enumerateDevices().then(deviceInfos=>{var _a;const devices=[];if(platform.isIonicAndroid()&&typeof cordova!="undefined"&&((_a=cordova===null||cordova===void 0?void 0:cordova.plugins)===null||_a===void 0?void 0:_a.EnumerateDevicesPlugin)){cordova.plugins.EnumerateDevicesPlugin.getEnumerateDevices().then(pluginDevices=>{let pluginAudioDevices=[];let videoDevices=[];let audioDevices=[];pluginAudioDevices=pluginDevices.filter(device=>device.kind==="audioinput");videoDevices=deviceInfos.filter(device=>device.kind==="videoinput");audioDevices=deviceInfos.filter(device=>device.kind==="audioinput");videoDevices.forEach((deviceInfo,index)=>{if(!deviceInfo.label){let label="";if(index===0){label="Front Camera"}else if(index===1){label="Back Camera"}else{label="Unknown Camera"}devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:label})}else{devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:deviceInfo.label})}});audioDevices.forEach((deviceInfo,index)=>{if(!deviceInfo.label){let label="";switch(index){case 0:label="Default";break;case 1:const defaultMatch=pluginAudioDevices.filter(d=>d.label.includes("Built"))[0];label=defaultMatch?defaultMatch.label:"Built-in Microphone";break;case 2:const wiredMatch=pluginAudioDevices.filter(d=>d.label.includes("Wired"))[0];if(wiredMatch){label=wiredMatch.label}else{label="Headset earpiece"}break;case 3:const wirelessMatch=pluginAudioDevices.filter(d=>d.label.includes("Bluetooth"))[0];label=wirelessMatch?wirelessMatch.label:"Wireless";break;default:label="Unknown Microphone";break}devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:label})}else{devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:deviceInfo.label})}});return resolve(devices)})}else{deviceInfos.forEach(deviceInfo=>{if(deviceInfo.kind==="audioinput"||deviceInfo.kind==="videoinput"){devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:deviceInfo.label})}});return resolve(devices)}}).catch(error=>{logger.error("Error getting devices",error);return reject(error)})})}getUserMedia(options){return __awaiter(this,void 0,void 0,function*(){var _a,_b;const askForAudioStreamOnly=(previousMediaStream,constraints)=>__awaiter(this,void 0,void 0,function*(){const definedAudioConstraint=constraints.audio===undefined?true:constraints.audio;const constraintsAux={audio:definedAudioConstraint,video:false};try{const audioOnlyStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);previousMediaStream.addTrack(audioOnlyStream.getAudioTracks()[0]);return previousMediaStream}catch(error){previousMediaStream.getAudioTracks().forEach(track=>{track.stop()});previousMediaStream.getVideoTracks().forEach(track=>{track.stop()});throw this.generateAudioDeviceError(error,constraintsAux)}});try{const myConstraints=yield this.generateMediaConstraints(options);if(!!myConstraints.videoTrack&&!!myConstraints.audioTrack||!!myConstraints.audioTrack&&((_a=myConstraints.constraints)===null||_a===void 0?void 0:_a.video)===false||!!myConstraints.videoTrack&&((_b=myConstraints.constraints)===null||_b===void 0?void 0:_b.audio)===false){return this.addAlreadyProvidedTracks(myConstraints,new MediaStream)}else{if(!!myConstraints.videoTrack){delete myConstraints.constraints.video}if(!!myConstraints.audioTrack){delete myConstraints.constraints.audio}let mustAskForAudioTrackLater=false;if(typeof options.videoSource==="string"){if(options.videoSource==="screen"||options.videoSource==="window"||platform.isElectron()&&options.videoSource.startsWith("screen:")){mustAskForAudioTrackLater=!myConstraints.audioTrack&&options.audioSource!==null&&options.audioSource!==false;if(navigator.mediaDevices["getDisplayMedia"]&&!platform.isElectron()){try{const mediaStream=yield navigator.mediaDevices["getDisplayMedia"]({video:true,audio:options.audioSource==="screen"});this.addAlreadyProvidedTracks(myConstraints,mediaStream);if(mustAskForAudioTrackLater){return yield askForAudioStreamOnly(mediaStream,myConstraints.constraints)}else{return mediaStream}}catch(error){let errorName=OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED;const errorMessage=error.toString();throw new OpenViduError_1.OpenViduError(errorName,errorMessage)}}else{}}else{}}const constraintsAux=mustAskForAudioTrackLater?{video:myConstraints.constraints.video}:myConstraints.constraints;try{const mediaStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);this.addAlreadyProvidedTracks(myConstraints,mediaStream);if(mustAskForAudioTrackLater){return yield askForAudioStreamOnly(mediaStream,myConstraints.constraints)}else{return mediaStream}}catch(error){let errorName;const errorMessage=error.toString();if(!(options.videoSource==="screen")){errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED}else{errorName=OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED}throw new OpenViduError_1.OpenViduError(errorName,errorMessage)}}}catch(error){throw error}})}enableProdMode(){logger.enableProdMode()}setAdvancedConfiguration(configuration){this.advancedConfiguration=configuration}onOrientationChanged(handler){globalThis.addEventListener("orientationchange",handler)}sendNewVideoDimensionsIfRequired(publisher,reason,WAIT_INTERVAL,MAX_ATTEMPTS){var _a,_b,_c,_d;let attempts=0;const oldWidth=((_b=(_a=publisher===null||publisher===void 0?void 0:publisher.stream)===null||_a===void 0?void 0:_a.videoDimensions)===null||_b===void 0?void 0:_b.width)||0;const oldHeight=((_d=(_c=publisher===null||publisher===void 0?void 0:publisher.stream)===null||_c===void 0?void 0:_c.videoDimensions)===null||_d===void 0?void 0:_d.height)||0;const repeatUntilChangeOrMaxAttempts=setInterval(()=>{attempts++;if(attempts>MAX_ATTEMPTS){clearTimeout(repeatUntilChangeOrMaxAttempts)}publisher.getVideoDimensions().then(newDimensions=>{if(newDimensions.width!==oldWidth||newDimensions.height!==oldHeight){clearTimeout(repeatUntilChangeOrMaxAttempts);this.sendVideoDimensionsChangedEvent(publisher,reason,oldWidth,oldHeight,newDimensions.width,newDimensions.height)}})},WAIT_INTERVAL)}sendVideoDimensionsChangedEvent(publisher,reason,oldWidth,oldHeight,newWidth,newHeight){publisher.stream.videoDimensions={width:newWidth||0,height:newHeight||0};this.sendRequest("streamPropertyChanged",{streamId:publisher.stream.streamId,property:"videoDimensions",newValue:JSON.stringify(publisher.stream.videoDimensions),reason:reason},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,"videoDimensions",publisher.stream.videoDimensions,{width:oldWidth,height:oldHeight},reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,"videoDimensions",publisher.stream.videoDimensions,{width:oldWidth,height:oldHeight},reason)]);this.session.sendVideoData(publisher)}})}sendTrackChangedEvent(publisher,oldLabel,newLabel,propertyType){const oldValue={label:oldLabel};const newValue={label:newLabel};const reason="trackReplaced";if(publisher.stream.isLocalStreamPublished){this.sendRequest("streamPropertyChanged",{streamId:publisher.stream.streamId,property:propertyType,newValue:newValue,reason:reason},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,propertyType,newValue,oldValue,reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,propertyType,newValue,oldValue,reason)])}})}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,propertyType,newValue,oldValue,reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,propertyType,newValue,oldValue,reason)])}}generateMediaConstraints(publisherProperties){return new Promise((resolve,reject)=>{const myConstraints={audioTrack:undefined,videoTrack:undefined,constraints:{audio:undefined,video:undefined}};const audioSource=publisherProperties.audioSource;const videoSource=publisherProperties.videoSource;if(audioSource===null||audioSource===false){myConstraints.constraints.audio=false}if(videoSource===null||videoSource===false){myConstraints.constraints.video=false}if(myConstraints.constraints.audio===false&&myConstraints.constraints.video===false){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.NO_INPUT_SOURCE_SET,"Properties 'audioSource' and 'videoSource' cannot be set to false or null at the same time"))}if(typeof MediaStreamTrack!=="undefined"&&audioSource instanceof MediaStreamTrack){myConstraints.audioTrack=audioSource}if(typeof MediaStreamTrack!=="undefined"&&videoSource instanceof MediaStreamTrack){myConstraints.videoTrack=videoSource}if(audioSource===undefined){myConstraints.constraints.audio=true}if(videoSource===undefined){myConstraints.constraints.video={width:{ideal:640},height:{ideal:480}}}if(videoSource!==null&&videoSource!==false){if(!!publisherProperties.resolution){const widthAndHeight=publisherProperties.resolution.toLowerCase().split("x");const idealWidth=Number(widthAndHeight[0]);const idealHeight=Number(widthAndHeight[1]);myConstraints.constraints.video={width:{ideal:idealWidth},height:{ideal:idealHeight}}}if(!!publisherProperties.frameRate){myConstraints.constraints.video.frameRate={ideal:publisherProperties.frameRate}}}this.configureDeviceIdOrScreensharing(myConstraints,publisherProperties,resolve,reject);return resolve(myConstraints)})}startWs(onConnectSucces){const config={heartbeat:5e3,ws:{uri:this.wsUri+"?sessionId="+this.session.sessionId,onconnected:onConnectSucces,ondisconnect:this.disconnectCallback.bind(this),onreconnecting:this.reconnectingCallback.bind(this),onreconnected:this.reconnectedCallback.bind(this),ismasternodecrashed:this.isMasterNodeCrashed.bind(this)},rpc:{requestTimeout:1e4,heartbeatRequestTimeout:5e3,participantJoined:this.session.onParticipantJoined.bind(this.session),participantPublished:this.session.onParticipantPublished.bind(this.session),participantUnpublished:this.session.onParticipantUnpublished.bind(this.session),participantLeft:this.session.onParticipantLeft.bind(this.session),participantEvicted:this.session.onParticipantEvicted.bind(this.session),recordingStarted:this.session.onRecordingStarted.bind(this.session),recordingStopped:this.session.onRecordingStopped.bind(this.session),broadcastStarted:this.session.onBroadcastStarted.bind(this.session),broadcastStopped:this.session.onBroadcastStopped.bind(this.session),sendMessage:this.session.onNewMessage.bind(this.session),streamPropertyChanged:this.session.onStreamPropertyChanged.bind(this.session),connectionPropertyChanged:this.session.onConnectionPropertyChanged.bind(this.session),networkQualityLevelChanged:this.session.onNetworkQualityLevelChangedChanged.bind(this.session),filterEventDispatched:this.session.onFilterEventDispatched.bind(this.session),iceCandidate:this.session.recvIceCandidate.bind(this.session),mediaError:this.session.onMediaError.bind(this.session),masterNodeCrashedNotification:this.onMasterNodeCrashedNotification.bind(this),forciblyReconnectSubscriber:this.session.onForciblyReconnectSubscriber.bind(this.session),speechToTextMessage:this.session.onSpeechToTextMessage.bind(this.session),speechToTextDisconnected:this.session.onSpeechToTextDisconnected.bind(this.session)}};this.jsonRpcClient=new RpcBuilder.clients.JsonRpcClient(config)}onMasterNodeCrashedNotification(response){console.error("Master Node has crashed");this.masterNodeHasCrashed=true;this.session.onLostConnection("nodeCrashed");this.jsonRpcClient.close(4103,"Master Node has crashed")}getWsReadyState(){return this.jsonRpcClient.getReadyState()}closeWs(){this.jsonRpcClient.close(4102,"Connection closed by client")}sendRequest(method,params,callback){var _a;if(params&¶ms instanceof Function){callback=params;params={}}logger.debug('Sending request: {method:"'+method+'", params: '+JSON.stringify(params)+"}");(_a=this.jsonRpcClient)===null||_a===void 0?void 0:_a.send(method,params,callback)}getWsUri(){return this.wsUri}getSecret(){return this.secret}getRecorder(){return this.recorder}getStt(){return this.stt}generateAudioDeviceError(error,constraints){if(error.name==="Error"){error.name=error.constructor.name}let errorName,errorMessage;switch(error.name.toLowerCase()){case"notfounderror":errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"notallowederror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"overconstrainederror":if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage="Audio input device with deviceId '"+constraints.audio.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Audio input device doesn't support the value passed for constraint '"+error.constraint+"'"}return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"notreadableerror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ALREADY_IN_USE;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);default:return new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_GENERIC_ERROR,error.toString())}}addAlreadyProvidedTracks(myConstraints,mediaStream,stream){if(!!myConstraints.videoTrack){mediaStream.addTrack(myConstraints.videoTrack);if(!!stream){if(!!myConstraints.constraints.video){stream.lastVideoTrackConstraints=myConstraints.constraints.video}else{stream.lastVideoTrackConstraints=myConstraints.videoTrack.getConstraints()}}}if(!!myConstraints.audioTrack){mediaStream.addTrack(myConstraints.audioTrack)}return mediaStream}configureDeviceIdOrScreensharing(myConstraints,publisherProperties,resolve,reject){const audioSource=publisherProperties.audioSource;const videoSource=publisherProperties.videoSource;if(typeof audioSource==="string"&&audioSource!=="screen"){myConstraints.constraints.audio={deviceId:{exact:audioSource}}}if(typeof videoSource==="string"){if(!this.isScreenShare(videoSource)){this.setVideoSource(myConstraints,videoSource);if(audioSource==="screen"){logger.warn('Parameter "audioSource" is set to "screen", which means rquesting audio from screen sharing source. But "videoSource" is not set to "screen". No audio source will be requested');myConstraints.constraints.audio=false}}else{if(!this.checkScreenSharingCapabilities()){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_SHARING_NOT_SUPPORTED,"You can only screen share in desktop Chrome, Firefox, Opera, Safari (>=13.0), Edge (>= 80) or Electron. Detected client: "+platform.getName()+" "+platform.getVersion());logger.error(error);return reject(error)}else{if(platform.isElectron()){const prefix="screen:";const videoSourceString=videoSource;const electronScreenId=videoSourceString.substr(videoSourceString.indexOf(prefix)+prefix.length);myConstraints.constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:electronScreenId}};return resolve(myConstraints)}else{if(!!this.advancedConfiguration.screenShareChromeExtension&&!(platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser())&&!navigator.mediaDevices["getDisplayMedia"]){screenSharing.getScreenConstraints((error,screenConstraints)=>{if(!!error||!!screenConstraints.mandatory&&screenConstraints.mandatory.chromeMediaSource==="screen"){if(error==="permission-denied"||error==="PermissionDeniedError"){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED,"You must allow access to one window of your desktop");logger.error(error);return reject(error)}else{const extensionId=this.advancedConfiguration.screenShareChromeExtension.split("/").pop().trim();screenSharing.getChromeExtensionStatus(extensionId,status=>{if(status==="installed-disabled"){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_DISABLED,"You must enable the screen extension");logger.error(error);return reject(error)}if(status==="not-installed"){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED,this.advancedConfiguration.screenShareChromeExtension);logger.error(error);return reject(error)}});return}}else{myConstraints.constraints.video=screenConstraints;return resolve(myConstraints)}});return}else{if(navigator.mediaDevices["getDisplayMedia"]){return resolve(myConstraints)}else{const firefoxString=platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()?publisherProperties.videoSource:undefined;screenSharingAuto.getScreenId(firefoxString,(error,sourceId,screenConstraints)=>{if(!!error){if(error==="not-installed"){const extensionUrl=!!this.advancedConfiguration.screenShareChromeExtension?this.advancedConfiguration.screenShareChromeExtension:"https://chrome.google.com/webstore/detail/openvidu-screensharing/lfcgfepafnobdloecchnfaclibenjold";const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED,extensionUrl);logger.error(err);return reject(err)}else if(error==="installed-disabled"){const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_DISABLED,"You must enable the screen extension");logger.error(err);return reject(err)}else if(error==="permission-denied"){const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED,"You must allow access to one window of your desktop");logger.error(err);return reject(err)}else{const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"Unknown error when accessing screen share");logger.error(err);logger.error(error);return reject(err)}}else{myConstraints.constraints.video=screenConstraints.video;return resolve(myConstraints)}});return}}}}}}}setVideoSource(myConstraints,videoSource){if(!myConstraints.constraints.video){myConstraints.constraints.video={}}myConstraints.constraints.video["deviceId"]={exact:videoSource}}disconnectCallback(){logger.warn("Websocket connection lost");if(this.isRoomAvailable()){this.session.onLostConnection("networkDisconnect")}else{alert("Connection error. Please reload page.")}}reconnectingCallback(){logger.warn("Websocket connection lost (reconnecting)");if(!this.isRoomAvailable()){alert("Connection error. Please reload page.")}else{this.session.emitEvent("reconnecting",[])}}reconnectWebsocketThroughRpcConnectMethod(rpcSessionId){this.sendRequest("connect",{sessionId:rpcSessionId,reconnect:true},(error,response)=>{if(!!error){if(this.isMasterNodeCrashed()){logger.warn("Master Node has crashed!")}else{logger.error(error);const notifyLostConnection=(reason,errorMsg)=>{logger.warn(errorMsg);this.session.onLostConnection(reason);this.jsonRpcClient.close(4101,"Reconnection fault: "+errorMsg)};const rpcSessionStatus=()=>{if(this.life===-1){notifyLostConnection("networkDisconnect","WS successfully reconnected but the user was already evicted due to timeout")}else{this.sendRequest("sessionStatus",{sessionId:this.session.sessionId},(error,response)=>{if(error!=null){console.error("Error checking session status",error)}else{if(this.life===response.life){notifyLostConnection("networkDisconnect","WS successfully reconnected but the user was already evicted due to timeout")}else{notifyLostConnection("nodeCrashed","WS successfully reconnected to OpenVidu Server but your Master Node crashed")}}})}};if(error.code===40007&&error.message==="reconnection error"){console.error("Invalid RPC sessionId. Client network disconnection or Master Node crash");rpcSessionStatus()}else{rpcSessionStatus()}}}else{this.jsonRpcClient.resetPing();this.session.onRecoveredConnection()}})}reconnectedCallback(){logger.warn("Websocket reconnected");if(this.isRoomAvailable()){if(!!this.session.connection){this.reconnectWebsocketThroughRpcConnectMethod(this.session.connection.rpcSessionId)}else{logger.warn("There was no previous connection when running reconnection callback");const sessionDisconnectEvent=new SessionDisconnectedEvent_1.SessionDisconnectedEvent(this.session,"networkDisconnect");this.session.ee.emitEvent("sessionDisconnected",[sessionDisconnectEvent]);sessionDisconnectEvent.callDefaultBehavior()}}else{alert("Connection error. Please reload page.")}}isMasterNodeCrashed(){return this.masterNodeHasCrashed}isRoomAvailable(){if(this.session!==undefined&&this.session instanceof Session_1.Session){return true}else{logger.warn("Session instance not found");return false}}isScreenShare(videoSource){return videoSource==="screen"||videoSource==="window"||platform.isElectron()&&videoSource.startsWith("screen:")}}exports.OpenVidu=OpenVidu},{"../../package.json":40,"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/SessionDisconnectedEvent":64,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/KurentoUtils/kurento-jsonrpc":76,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/ScreenSharing/Screen-Capturing":84,"../OpenViduInternal/ScreenSharing/Screen-Capturing-Auto":83,"../OpenViduInternal/Utils/Platform":85,"./LocalRecorder":45,"./Publisher":47,"./Session":48,"wolfy87-eventemitter":39}],47:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.Publisher=void 0;const Session_1=require("./Session");const Stream_1=require("./Stream");const StreamManager_1=require("./StreamManager");const StreamEvent_1=require("../OpenViduInternal/Events/StreamEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const TypeOfVideo_1=require("../OpenViduInternal/Enums/TypeOfVideo");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class Publisher extends StreamManager_1.StreamManager{constructor(targEl,properties,openvidu){super(new Stream_1.Stream(!!openvidu.session?openvidu.session:new Session_1.Session(openvidu),{publisherProperties:properties,mediaConstraints:{}}),targEl);this.accessAllowed=false;this.isSubscribedToRemote=false;this.accessDenied=false;platform=Platform_1.PlatformUtils.getInstance();this.properties=properties;this.openvidu=openvidu;this.stream.ee.on("local-stream-destroyed",reason=>{this.stream.isLocalStreamPublished=false;const streamEvent=new StreamEvent_1.StreamEvent(true,this,"streamDestroyed",this.stream,reason);this.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior()})}publishAudio(enabled){if(this.stream.audioActive!==enabled){const affectedMediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();affectedMediaStream.getAudioTracks().forEach(track=>{track.enabled=enabled});if(!!this.session&&!!this.stream.streamId){this.session.openvidu.sendRequest("streamPropertyChanged",{streamId:this.stream.streamId,property:"audioActive",newValue:enabled,reason:"publishAudio"},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this.stream,"audioActive",enabled,!enabled,"publishAudio")]);this.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this,this.stream,"audioActive",enabled,!enabled,"publishAudio")]);this.session.sendVideoData(this.stream.streamManager)}})}this.stream.audioActive=enabled;logger.info("'Publisher' has "+(enabled?"published":"unpublished")+" its audio stream")}}publishVideo(enabled,resource){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){if(this.stream.videoActive!==enabled){const affectedMediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();let mustRestartMediaStream=false;affectedMediaStream.getVideoTracks().forEach(track=>{track.enabled=enabled;if(!enabled&&resource===true){track.stop()}else if(enabled&&track.readyState==="ended"){mustRestartMediaStream=true}});if(!enabled&&resource===true&&!!this.stream.filter&&this.stream.filter.type.startsWith("VB:")){this.stream.lastVBFilter=this.stream.filter;yield this.stream.removeFilterAux(true)}if(mustRestartMediaStream){const oldVideoTrack=affectedMediaStream.getVideoTracks()[0];affectedMediaStream.removeTrack(oldVideoTrack);const replaceVideoTrack=tr=>__awaiter(this,void 0,void 0,function*(){affectedMediaStream.addTrack(tr);if(this.stream.isLocalStreamPublished){yield this.replaceTrackInRtcRtpSender(tr)}if(!!this.stream.lastVBFilter){setTimeout(()=>__awaiter(this,void 0,void 0,function*(){let options=this.stream.lastVBFilter.options;const lastExecMethod=this.stream.lastVBFilter.lastExecMethod;if(!!lastExecMethod&&lastExecMethod.method==="update"){options=Object.assign({},options,lastExecMethod.params)}yield this.stream.applyFilter(this.stream.lastVBFilter.type,options);delete this.stream.lastVBFilter}),1)}});if(!!resource&&resource instanceof MediaStreamTrack){yield replaceVideoTrack(resource)}else{try{const mediaStream=yield navigator.mediaDevices.getUserMedia({audio:false,video:this.stream.lastVideoTrackConstraints});yield replaceVideoTrack(mediaStream.getVideoTracks()[0])}catch(error){return reject(error)}}}if(!!this.session&&!!this.stream.streamId){this.session.openvidu.sendRequest("streamPropertyChanged",{streamId:this.stream.streamId,property:"videoActive",newValue:enabled,reason:"publishVideo"},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this.stream,"videoActive",enabled,!enabled,"publishVideo")]);this.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this,this.stream,"videoActive",enabled,!enabled,"publishVideo")]);this.session.sendVideoData(this.stream.streamManager)}})}this.stream.videoActive=enabled;logger.info("'Publisher' has "+(enabled?"published":"unpublished")+" its video stream");return resolve()}}))}subscribeToRemote(value){value=value!==undefined?value:true;this.isSubscribedToRemote=value;this.stream.subscribeToMyRemote(value)}on(type,handler){super.on(type,handler);if(type==="streamCreated"){if(!!this.stream&&this.stream.isLocalStreamPublished){this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])}else{this.stream.ee.on("stream-created-by-publisher",()=>{this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])})}}if(type==="accessAllowed"){if(this.accessAllowed){this.emitEvent("accessAllowed",[])}}if(type==="accessDenied"){if(this.accessDenied){this.emitEvent("accessDenied",[])}}return this}once(type,handler){super.once(type,handler);if(type==="streamCreated"){if(!!this.stream&&this.stream.isLocalStreamPublished){this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])}else{this.stream.ee.once("stream-created-by-publisher",()=>{this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])})}}if(type==="accessAllowed"){if(this.accessAllowed){this.emitEvent("accessAllowed",[])}}if(type==="accessDenied"){if(this.accessDenied){this.emitEvent("accessDenied",[])}}return this}off(type,handler){super.off(type,handler);return this}replaceTrack(track){return __awaiter(this,void 0,void 0,function*(){return this.replaceTrackAux(track,true)})}initialize(){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){var _a,_b;let constraints={};let constraintsAux={};const timeForDialogEvent=2e3;let startTime;const errorCallback=openViduError=>{this.accessDenied=true;this.accessAllowed=false;logger.error(`Publisher initialization failed. ${openViduError.name}: ${openViduError.message}`);return reject(openViduError)};const successCallback=mediaStream=>{var _a,_b;this.accessAllowed=true;this.accessDenied=false;if(typeof MediaStreamTrack!=="undefined"&&this.properties.audioSource instanceof MediaStreamTrack){mediaStream.removeTrack(mediaStream.getAudioTracks()[0]);mediaStream.addTrack(this.properties.audioSource)}if(typeof MediaStreamTrack!=="undefined"&&this.properties.videoSource instanceof MediaStreamTrack){mediaStream.removeTrack(mediaStream.getVideoTracks()[0]);mediaStream.addTrack(this.properties.videoSource)}if(!!mediaStream.getAudioTracks()[0]){const enabled=this.stream.audioActive!==undefined&&this.stream.audioActive!==null?this.stream.audioActive:!!this.stream.outboundStreamOpts.publisherProperties.publishAudio;mediaStream.getAudioTracks()[0].enabled=enabled}if(!!mediaStream.getVideoTracks()[0]){const enabled=this.stream.videoActive!==undefined&&this.stream.videoActive!==null?this.stream.videoActive:!!this.stream.outboundStreamOpts.publisherProperties.publishVideo;mediaStream.getVideoTracks()[0].enabled=enabled}for(const track of mediaStream.getAudioTracks()){if(!((_a=track.contentHint)===null||_a===void 0?void 0:_a.length)){track.contentHint="";logger.info(`Audio track Content Hint set: '${track.contentHint}'`)}}for(const track of mediaStream.getVideoTracks()){if(!((_b=track.contentHint)===null||_b===void 0?void 0:_b.length)){switch(this.stream.typeOfVideo){case TypeOfVideo_1.TypeOfVideo.SCREEN:track.contentHint="detail";break;case TypeOfVideo_1.TypeOfVideo.CUSTOM:logger.warn("CUSTOM type video track was provided without Content Hint!");track.contentHint="motion";break;case TypeOfVideo_1.TypeOfVideo.CAMERA:case TypeOfVideo_1.TypeOfVideo.IPCAM:default:track.contentHint="motion";break}logger.info(`Video track Content Hint set: '${track.contentHint}'`)}}this.initializeVideoReference(mediaStream);if(!this.stream.displayMyRemote()){this.stream.updateMediaStreamInVideos()}delete this.firstVideoElement;if(this.stream.isSendVideo()){this.getVideoDimensions().then(dimensions=>{this.stream.videoDimensions={width:dimensions.width,height:dimensions.height};if(this.stream.isSendScreen()){if(this.stream.isSendAudio()&&mediaStream.getAudioTracks().length===0){this.stream.audioActive=false;this.stream.hasAudio=false;this.stream.outboundStreamOpts.publisherProperties.publishAudio=false;this.stream.outboundStreamOpts.publisherProperties.audioSource=false}this.screenShareResizeInterval=setInterval(()=>{const settings=mediaStream.getVideoTracks()[0].getSettings();const newWidth=settings.width;const newHeight=settings.height;const widthChanged=newWidth!=null&&newWidth!==this.stream.videoDimensions.width;const heightChanged=newHeight!=null&&newHeight!==this.stream.videoDimensions.height;if(this.stream.isLocalStreamPublished&&(widthChanged||heightChanged)){this.openvidu.sendVideoDimensionsChangedEvent(this,"screenResized",this.stream.videoDimensions.width,this.stream.videoDimensions.height,newWidth||0,newHeight||0)}},650)}this.stream.isLocalStreamReadyToPublish=true;this.stream.ee.emitEvent("stream-ready-to-publish",[])})}else{this.stream.isLocalStreamReadyToPublish=true;this.stream.ee.emitEvent("stream-ready-to-publish",[])}return resolve()};const getMediaSuccess=(mediaStream,definedAudioConstraint)=>__awaiter(this,void 0,void 0,function*(){this.clearPermissionDialogTimer(startTime,timeForDialogEvent);if(this.stream.isSendScreen()&&this.properties.audioSource!=="screen"&&this.stream.isSendAudio()){constraintsAux.audio=definedAudioConstraint;constraintsAux.video=false;startTime=Date.now();this.setPermissionDialogTimer(timeForDialogEvent);try{const audioOnlyStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);this.clearPermissionDialogTimer(startTime,timeForDialogEvent);mediaStream.addTrack(audioOnlyStream.getAudioTracks()[0]);successCallback(mediaStream)}catch(error){this.clearPermissionDialogTimer(startTime,timeForDialogEvent);mediaStream.getAudioTracks().forEach(track=>{track.stop()});mediaStream.getVideoTracks().forEach(track=>{track.stop()});errorCallback(this.openvidu.generateAudioDeviceError(error,constraints));return}}else{successCallback(mediaStream)}});const getMediaError=error=>__awaiter(this,void 0,void 0,function*(){logger.error(`getMediaError: ${error.toString()}`);this.clearPermissionDialogTimer(startTime,timeForDialogEvent);if(error.name==="Error"){error.name=error.constructor.name}let errorName,errorMessage;switch(error.name.toLowerCase()){case"notfounderror":try{const mediaStream=yield navigator.mediaDevices.getUserMedia({audio:false,video:constraints.video});mediaStream.getVideoTracks().forEach(track=>{track.stop()});errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}catch(error){errorName=OpenViduError_1.OpenViduErrorName.INPUT_VIDEO_DEVICE_NOT_FOUND;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}break;case"notallowederror":errorName=this.stream.isSendScreen()?OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED:OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage));break;case"overconstrainederror":try{const mediaStream=yield navigator.mediaDevices.getUserMedia({audio:false,video:constraints.video});mediaStream.getVideoTracks().forEach(track=>{track.stop()});if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage="Audio input device with deviceId '"+constraints.audio.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Audio input device doesn't support the value passed for constraint '"+error.constraint+"'"}errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}catch(error){if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_VIDEO_DEVICE_NOT_FOUND;errorMessage="Video input device with deviceId '"+constraints.video.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Video input device doesn't support the value passed for constraint '"+error.constraint+"'"}errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}break;case"aborterror":case"notreadableerror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ALREADY_IN_USE;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage));break;default:errorName=OpenViduError_1.OpenViduErrorName.GENERIC_ERROR;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage));break}});try{const myConstraints=yield this.openvidu.generateMediaConstraints(this.properties);if(!!myConstraints.videoTrack&&!!myConstraints.audioTrack||!!myConstraints.audioTrack&&((_a=myConstraints.constraints)===null||_a===void 0?void 0:_a.video)===false||!!myConstraints.videoTrack&&((_b=myConstraints.constraints)===null||_b===void 0?void 0:_b.audio)===false){successCallback(this.openvidu.addAlreadyProvidedTracks(myConstraints,new MediaStream,this.stream))}else{constraints=myConstraints.constraints;const outboundStreamOptions={mediaConstraints:constraints,publisherProperties:this.properties};this.stream.setOutboundStreamOptions(outboundStreamOptions);const definedAudioConstraint=constraints.audio===undefined?true:constraints.audio;constraintsAux.audio=this.stream.isSendScreen()?false:definedAudioConstraint;constraintsAux.video=constraints.video;startTime=Date.now();this.setPermissionDialogTimer(timeForDialogEvent);try{if(this.stream.isSendScreen()&&navigator.mediaDevices["getDisplayMedia"]&&!platform.isElectron()){const mediaStream=yield navigator.mediaDevices["getDisplayMedia"]({video:true,audio:this.properties.audioSource==="screen"});this.openvidu.addAlreadyProvidedTracks(myConstraints,mediaStream);yield getMediaSuccess(mediaStream,definedAudioConstraint)}else{this.stream.lastVideoTrackConstraints=constraintsAux.video;const mediaStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);this.openvidu.addAlreadyProvidedTracks(myConstraints,mediaStream,this.stream);yield getMediaSuccess(mediaStream,definedAudioConstraint)}}catch(error){yield getMediaError(error)}}}catch(error){errorCallback(error)}}))}replaceTrackAux(track,updateLastConstraints){return __awaiter(this,void 0,void 0,function*(){const trackOriginalEnabledValue=track.enabled;if(track.kind==="video"){track.enabled=this.stream.videoActive}else if(track.kind==="audio"){track.enabled=this.stream.audioActive}try{if(this.stream.isLocalStreamPublished){this.replaceTrackInMediaStream(track,updateLastConstraints);return yield this.replaceTrackInRtcRtpSender(track)}else{return this.replaceTrackInMediaStream(track,updateLastConstraints)}}catch(error){track.enabled=trackOriginalEnabledValue;throw error}})}getVideoDimensions(){return new Promise((resolve,reject)=>{const requiresDomInsertion=(platform.isIonicIos()||platform.isIOSWithSafari())&&this.videoReference.readyState<1;let loadedmetadataListener;const resolveDimensions=()=>{let width;let height;if(typeof this.stream.getMediaStream().getVideoTracks()[0].getSettings==="function"){const settings=this.stream.getMediaStream().getVideoTracks()[0].getSettings();width=settings.width||this.videoReference.videoWidth;height=settings.height||this.videoReference.videoHeight}else{logger.warn("MediaStreamTrack does not have getSettings method on "+platform.getDescription());width=this.videoReference.videoWidth;height=this.videoReference.videoHeight}if(loadedmetadataListener!=null){this.videoReference.removeEventListener("loadedmetadata",loadedmetadataListener)}if(requiresDomInsertion){document.body.removeChild(this.videoReference)}return resolve({width:width,height:height})};if(this.videoReference.readyState>=1){resolveDimensions()}else{loadedmetadataListener=()=>{if(!this.videoReference.videoWidth){let interval=setInterval(()=>{if(!!this.videoReference.videoWidth){clearInterval(interval);resolveDimensions()}},40)}else{resolveDimensions()}};this.videoReference.addEventListener("loadedmetadata",loadedmetadataListener);if(requiresDomInsertion){document.body.appendChild(this.videoReference)}}})}reestablishStreamPlayingEvent(){if(this.ee.getListeners("streamPlaying").length>0){this.addPlayEventToFirstVideo()}}initializeVideoReference(mediaStream){this.videoReference=document.createElement("video");this.videoReference.style.display="none";this.videoReference.muted=true;this.videoReference.autoplay=true;this.videoReference.controls=false;if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){this.videoReference.playsInline=true}this.stream.setMediaStream(mediaStream);if(!!this.firstVideoElement){this.createVideoElement(this.firstVideoElement.targetElement,this.properties.insertMode)}this.videoReference.srcObject=this.stream.getMediaStream()}replaceTrackInMediaStream(track,updateLastConstraints){const mediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();let removedTrack;if(track.kind==="video"){removedTrack=mediaStream.getVideoTracks()[0];if(updateLastConstraints){this.stream.lastVideoTrackConstraints=track.getConstraints()}}else{removedTrack=mediaStream.getAudioTracks()[0]}removedTrack.enabled=false;removedTrack.stop();mediaStream.removeTrack(removedTrack);mediaStream.addTrack(track);const trackInfo={oldLabel:(removedTrack===null||removedTrack===void 0?void 0:removedTrack.label)||"",newLabel:(track===null||track===void 0?void 0:track.label)||""};if(track.kind==="video"&&updateLastConstraints){this.openvidu.sendNewVideoDimensionsIfRequired(this,"trackReplaced",50,30);this.openvidu.sendTrackChangedEvent(this,trackInfo.oldLabel,trackInfo.newLabel,"videoTrack");if(this.stream.isLocalStreamPublished){this.session.sendVideoData(this.stream.streamManager,5,true,5)}}else if(track.kind==="audio"&&updateLastConstraints){this.openvidu.sendTrackChangedEvent(this,trackInfo.oldLabel,trackInfo.newLabel,"audioTrack")}if(track.kind==="audio"){this.stream.disableHarkSpeakingEvent(false);this.stream.disableHarkStoppedSpeakingEvent(false);this.stream.disableHarkVolumeChangeEvent(false);this.stream.initHarkEvents()}}setPermissionDialogTimer(waitTime){this.permissionDialogTimeout=setTimeout(()=>{this.emitEvent("accessDialogOpened",[])},waitTime)}clearPermissionDialogTimer(startTime,waitTime){clearTimeout(this.permissionDialogTimeout);if(Date.now()-startTime>waitTime){this.emitEvent("accessDialogClosed",[])}}replaceTrackInRtcRtpSender(track){return __awaiter(this,void 0,void 0,function*(){const senders=this.stream.getRTCPeerConnection().getSenders();let sender;if(track.kind==="video"){sender=senders.find(s=>!!s.track&&s.track.kind==="video");if(!sender){throw new Error("There's no replaceable track for that kind of MediaStreamTrack in this Publisher object")}}else if(track.kind==="audio"){sender=senders.find(s=>!!s.track&&s.track.kind==="audio");if(!sender){throw new Error("There's no replaceable track for that kind of MediaStreamTrack in this Publisher object")}}else{throw new Error("Unknown track kind "+track.kind)}yield sender.replaceTrack(track)})}}exports.Publisher=Publisher},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/TypeOfVideo":54,"../OpenViduInternal/Events/StreamEvent":67,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./Session":48,"./Stream":49,"./StreamManager":50}],48:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.Session=void 0;const Connection_1=require("./Connection");const Filter_1=require("./Filter");const Subscriber_1=require("./Subscriber");const EventDispatcher_1=require("./EventDispatcher");const ConnectionEvent_1=require("../OpenViduInternal/Events/ConnectionEvent");const FilterEvent_1=require("../OpenViduInternal/Events/FilterEvent");const RecordingEvent_1=require("../OpenViduInternal/Events/RecordingEvent");const SessionDisconnectedEvent_1=require("../OpenViduInternal/Events/SessionDisconnectedEvent");const SignalEvent_1=require("../OpenViduInternal/Events/SignalEvent");const SpeechToTextEvent_1=require("../OpenViduInternal/Events/SpeechToTextEvent");const StreamEvent_1=require("../OpenViduInternal/Events/StreamEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const ConnectionPropertyChangedEvent_1=require("../OpenViduInternal/Events/ConnectionPropertyChangedEvent");const NetworkQualityLevelChangedEvent_1=require("../OpenViduInternal/Events/NetworkQualityLevelChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const semverMajor=require("semver/functions/major");const semverMinor=require("semver/functions/minor");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class Session extends EventDispatcher_1.EventDispatcher{constructor(openvidu){super();this.streamManagers=[];this.remoteStreamsCreated=new Map;this.remoteConnections=new Map;platform=Platform_1.PlatformUtils.getInstance();this.openvidu=openvidu}connect(token,metadata){return new Promise((resolve,reject)=>{this.processToken(token);if(this.openvidu.checkSystemRequirements()){this.options={sessionId:this.sessionId,participantId:token,metadata:!!metadata?this.stringClientMetadata(metadata):""};this.connectAux(token).then(()=>resolve()).catch(error=>reject(error))}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.BROWSER_NOT_SUPPORTED,"Browser "+platform.getName()+" (version "+platform.getVersion()+") for "+platform.getFamily()+" is not supported in OpenVidu"))}})}disconnect(){this.leave(false,"disconnect")}subscribe(stream,targetElement,param3,param4){let properties={};if(!!param3&&typeof param3!=="function"){properties={insertMode:typeof param3.insertMode!=="undefined"?typeof param3.insertMode==="string"?VideoInsertMode_1.VideoInsertMode[param3.insertMode]:properties.insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,subscribeToAudio:typeof param3.subscribeToAudio!=="undefined"?param3.subscribeToAudio:true,subscribeToVideo:typeof param3.subscribeToVideo!=="undefined"?param3.subscribeToVideo:true}}else{properties={insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,subscribeToAudio:true,subscribeToVideo:true}}let completionHandler=undefined;if(!!param3&&typeof param3==="function"){completionHandler=param3}else if(!!param4){completionHandler=param4}if(!this.sessionConnected()){if(completionHandler!==undefined){completionHandler(this.notConnectedError())}throw this.notConnectedError()}logger.info("Subscribing to "+stream.connection.connectionId);stream.subscribe().then(()=>{logger.info("Subscribed correctly to "+stream.connection.connectionId);if(completionHandler!==undefined){completionHandler(undefined)}}).catch(error=>{if(completionHandler!==undefined){completionHandler(error)}});const subscriber=new Subscriber_1.Subscriber(stream,targetElement,properties);if(!!subscriber.targetElement){stream.streamManager.createVideoElement(subscriber.targetElement,properties.insertMode)}return subscriber}subscribeAsync(stream,targetElement,properties){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}let subscriber;const callback=error=>{if(!!error){return reject(error)}else{return resolve(subscriber)}};if(!!properties){subscriber=this.subscribe(stream,targetElement,properties,callback)}else{subscriber=this.subscribe(stream,targetElement,callback)}})}unsubscribe(subscriber){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}else{const connectionId=subscriber.stream.connection.connectionId;logger.info("Unsubscribing from "+connectionId);this.openvidu.sendRequest("unsubscribeFromVideo",{sender:subscriber.stream.connection.connectionId},(error,response)=>{if(error){logger.error("Error unsubscribing from "+connectionId);return reject(error)}else{logger.info("Unsubscribed correctly from "+connectionId);subscriber.stream.streamManager.removeAllVideos();subscriber.stream.disposeWebRtcPeer();subscriber.stream.disposeMediaStream();return resolve()}})}})}publish(publisher){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}publisher.session=this;publisher.stream.session=this;if(!publisher.stream.publishedOnce){this.connection.addStream(publisher.stream);publisher.stream.publish().then(()=>{this.sendVideoData(publisher,8,true,5);return resolve()}).catch(error=>reject(error))}else{publisher.initialize().then(()=>{this.connection.addStream(publisher.stream);publisher.reestablishStreamPlayingEvent();publisher.stream.publish().then(()=>{this.sendVideoData(publisher,8,true,5);return resolve()}).catch(error=>reject(error))}).catch(error=>reject(error))}})}unpublish(publisher){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){throw this.notConnectedError()}const stream=publisher.stream;if(!stream.connection){return reject(new Error("The associated Connection object of this Publisher is null"))}else if(stream.connection!==this.connection){return reject(new Error("The associated Connection object of this Publisher is not your local Connection. "+"Only moderators can force unpublish on remote Streams via 'forceUnpublish' method"))}else{logger.info("Unpublishing local media ("+stream.connection.connectionId+")");this.openvidu.sendRequest("unpublishVideo",(error,response)=>{if(error){return reject(error)}else{logger.info("Media unpublished correctly");stream.disposeWebRtcPeer();if(stream.connection.stream==stream){delete stream.connection.stream}const streamEvent=new StreamEvent_1.StreamEvent(true,publisher,"streamDestroyed",publisher.stream,"unpublish");publisher.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();return resolve()}})}})}forceDisconnect(connection){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}logger.info("Forcing disconnect for connection "+connection.connectionId);this.openvidu.sendRequest("forceDisconnect",{connectionId:connection.connectionId},(error,response)=>{if(error){logger.error("Error forcing disconnect for Connection "+connection.connectionId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to force a disconnection"))}else{return reject(error)}}else{logger.info("Forcing disconnect correctly for Connection "+connection.connectionId);return resolve()}})})}forceUnpublish(stream){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}logger.info("Forcing unpublish for stream "+stream.streamId);this.openvidu.sendRequest("forceUnpublish",{streamId:stream.streamId},(error,response)=>{if(error){logger.error("Error forcing unpublish for Stream "+stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to force an unpublishing"))}else{return reject(error)}}else{logger.info("Forcing unpublish correctly for Stream "+stream.streamId);return resolve()}})})}signal(signal){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}const signalMessage={};if(signal.to&&signal.to.length>0){const connectionIds=[];signal.to.forEach(connection=>{if(!!connection.connectionId){connectionIds.push(connection.connectionId)}});signalMessage["to"]=connectionIds}else{signalMessage["to"]=[]}signalMessage["data"]=signal.data?signal.data:"";let typeAux=signal.type?signal.type:"signal";if(!!typeAux){if(typeAux.substring(0,7)!=="signal:"){typeAux="signal:"+typeAux}}signalMessage["type"]=typeAux;this.openvidu.sendRequest("sendMessage",{message:JSON.stringify(signalMessage)},(error,response)=>{if(!!error){return reject(error)}else{return resolve()}})})}subscribeToSpeechToText(stream,lang){return new Promise((resolve,reject)=>{this.openvidu.sendRequest("subscribeToSpeechToText",{connectionId:stream.connection.connectionId,lang:lang},(error,response)=>{if(!!error){return reject(error)}else{return resolve()}})})}unsubscribeFromSpeechToText(stream){return new Promise((resolve,reject)=>{this.openvidu.sendRequest("unsubscribeFromSpeechToText",{connectionId:stream.connection.connectionId},(error,response)=>{if(!!error){return reject(error)}else{return resolve()}})})}on(type,handler){var _a,_b,_c,_d;super.onAux(type,"Event '"+type+"' triggered by 'Session'",handler);if(type==="publisherStartSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableHarkSpeakingEvent()}});if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.hasAudio)){this.connection.stream.enableHarkSpeakingEvent()}}if(type==="publisherStopSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableHarkStoppedSpeakingEvent()}});if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.hasAudio)){this.connection.stream.enableHarkStoppedSpeakingEvent()}}return this}once(type,handler){var _a,_b,_c,_d;super.onceAux(type,"Event '"+type+"' triggered once by 'Session'",handler);if(type==="publisherStartSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableOnceHarkSpeakingEvent()}});if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.hasAudio)){this.connection.stream.enableOnceHarkSpeakingEvent()}}if(type==="publisherStopSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableOnceHarkStoppedSpeakingEvent()}});if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.hasAudio)){this.connection.stream.enableOnceHarkStoppedSpeakingEvent()}}return this}off(type,handler){var _a,_b,_c,_d;super.offAux(type,handler);if(type==="publisherStartSpeaking"){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false)){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false,remoteConnection.stream.streamManager)){remoteConnection.stream.disableHarkSpeakingEvent(false)}}});if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false,this.connection.stream.streamManager)){this.connection.stream.disableHarkSpeakingEvent(false)}}}}if(type==="publisherStopSpeaking"){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false)){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false,remoteConnection.stream.streamManager)){remoteConnection.stream.disableHarkStoppedSpeakingEvent(false)}}});if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false,this.connection.stream.streamManager)){this.connection.stream.disableHarkStoppedSpeakingEvent(false)}}}}return this}onParticipantJoined(event){this.getConnection(event.id,"").then(connection=>{logger.warn("Connection "+connection.connectionId+" already exists in connections list")}).catch(openViduError=>{const connection=new Connection_1.Connection(this,event);this.remoteConnections.set(event.id,connection);this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionCreated",connection,"")])})}onParticipantLeft(event){this.getRemoteConnection(event.connectionId,"onParticipantLeft").then(connection=>{if(!!connection.stream){const stream=connection.stream;const streamEvent=new StreamEvent_1.StreamEvent(true,this,"streamDestroyed",stream,event.reason);this.ee.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();this.remoteStreamsCreated.delete(stream.streamId)}connection.dispose();this.remoteConnections.delete(connection.connectionId);this.ee.emitEvent("connectionDestroyed",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionDestroyed",connection,event.reason)])}).catch(openViduError=>{logger.error(openViduError)})}onParticipantPublished(event){const afterConnectionFound=connection=>{this.remoteConnections.set(connection.connectionId,connection);if(!this.remoteStreamsCreated.get(connection.stream.streamId)){this.ee.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",connection.stream,"")])}this.remoteStreamsCreated.set(connection.stream.streamId,true)};let connection;this.getRemoteConnection(event.id,"onParticipantPublished").then(con=>{connection=con;event.metadata=con.data;connection.remoteOptions=event;connection.initRemoteStreams(event.streams);afterConnectionFound(connection)}).catch(openViduError=>{connection=new Connection_1.Connection(this,event);afterConnectionFound(connection)})}onParticipantUnpublished(event){if(event.connectionId===this.connection.connectionId){this.stopPublisherStream(event.reason)}else{this.getRemoteConnection(event.connectionId,"onParticipantUnpublished").then(connection=>{const streamEvent=new StreamEvent_1.StreamEvent(true,this,"streamDestroyed",connection.stream,event.reason);this.ee.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();if(connection.stream!=null){const streamId=connection.stream.streamId;this.remoteStreamsCreated.delete(streamId);connection.removeStream()}}).catch(openViduError=>{logger.error(openViduError)})}}onParticipantEvicted(event){if(event.connectionId===this.connection.connectionId){if(!!this.sessionId&&!this.connection.disposed){this.leave(true,event.reason)}}}onNewMessage(event){logger.info("New signal: "+JSON.stringify(event));const strippedType=!!event.type?event.type.replace(/^(signal:)/,""):undefined;if(!!event.from){this.getConnection(event.from,"Connection '"+event.from+"' unknown when 'onNewMessage'. Existing remote connections: "+JSON.stringify(this.remoteConnections.keys())+". Existing local connection: "+this.connection.connectionId).then(connection=>{this.ee.emitEvent("signal",[new SignalEvent_1.SignalEvent(this,strippedType,event.data,connection)]);if(!!event.type&&event.type!=="signal"){this.ee.emitEvent(event.type,[new SignalEvent_1.SignalEvent(this,strippedType,event.data,connection)])}}).catch(openViduError=>{logger.error(openViduError)})}else{this.ee.emitEvent("signal",[new SignalEvent_1.SignalEvent(this,strippedType,event.data,undefined)]);if(!!event.type&&event.type!=="signal"){this.ee.emitEvent(event.type,[new SignalEvent_1.SignalEvent(this,strippedType,event.data,undefined)])}}}onStreamPropertyChanged(event){const callback=connection=>{var _a,_b;if(!!connection.stream&&connection.stream.streamId===event.streamId){const stream=connection.stream;let oldValue;switch(event.property){case"audioActive":oldValue=stream.audioActive;event.newValue=event.newValue==="true";stream.audioActive=event.newValue;break;case"videoActive":oldValue=stream.videoActive;event.newValue=event.newValue==="true";stream.videoActive=event.newValue;const videoTrack=(_b=(_a=stream===null||stream===void 0?void 0:stream.getMediaStream())===null||_a===void 0?void 0:_a.getVideoTracks())===null||_b===void 0?void 0:_b[0];if(videoTrack&&!videoTrack.enabled&&stream.videoActive){videoTrack.enabled=true}break;case"videoTrack":event.newValue=JSON.parse(event.newValue);break;case"audioTrack":event.newValue=JSON.parse(event.newValue);break;case"videoDimensions":oldValue=stream.videoDimensions;event.newValue=JSON.parse(JSON.parse(event.newValue));stream.videoDimensions=event.newValue;break;case"filter":oldValue=stream.filter;event.newValue=Object.keys(event.newValue).length>0?event.newValue:undefined;if(event.newValue!==undefined){stream.filter=new Filter_1.Filter(event.newValue.type,event.newValue.options);stream.filter.stream=stream;if(event.newValue.lastExecMethod){stream.filter.lastExecMethod=event.newValue.lastExecMethod}}else{delete stream.filter}event.newValue=stream.filter;break}this.ee.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this,stream,event.property,event.newValue,oldValue,event.reason)]);if(!!stream.streamManager){stream.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(stream.streamManager,stream,event.property,event.newValue,oldValue,event.reason)])}}else{logger.error("No stream with streamId '"+event.streamId+"' found for connection '"+event.connectionId+"' on 'streamPropertyChanged' event")}};if(event.connectionId===this.connection.connectionId){callback(this.connection)}else{this.getRemoteConnection(event.connectionId,"onStreamPropertyChanged").then(connection=>{callback(connection)}).catch(openViduError=>{logger.error(openViduError)})}}onConnectionPropertyChanged(event){let oldValue;switch(event.property){case"role":oldValue=this.connection.role.slice();this.connection.role=event.newValue;this.connection.localOptions.role=event.newValue;break;case"record":oldValue=this.connection.record;event.newValue=event.newValue==="true";this.connection.record=event.newValue;this.connection.localOptions.record=event.newValue;break}this.ee.emitEvent("connectionPropertyChanged",[new ConnectionPropertyChangedEvent_1.ConnectionPropertyChangedEvent(this,this.connection,event.property,event.newValue,oldValue)])}onNetworkQualityLevelChangedChanged(event){if(event.connectionId===this.connection.connectionId){this.ee.emitEvent("networkQualityLevelChanged",[new NetworkQualityLevelChangedEvent_1.NetworkQualityLevelChangedEvent(this,event.newValue,event.oldValue,this.connection)])}else{this.getConnection(event.connectionId,"Connection not found for connectionId "+event.connectionId).then(connection=>{this.ee.emitEvent("networkQualityLevelChanged",[new NetworkQualityLevelChangedEvent_1.NetworkQualityLevelChangedEvent(this,event.newValue,event.oldValue,connection)])}).catch(openViduError=>{logger.error(openViduError)})}}recvIceCandidate(event){const candidateInit={candidate:event.candidate,sdpMLineIndex:event.sdpMLineIndex,sdpMid:event.sdpMid};const iceCandidate=new RTCIceCandidate(candidateInit);this.getConnection(event.senderConnectionId,"Connection not found for connectionId "+event.senderConnectionId+" owning endpoint "+event.endpointName+". Ice candidate will be ignored: "+iceCandidate).then(connection=>{const stream=connection.stream;stream.getWebRtcPeer().addIceCandidate(iceCandidate).catch(error=>{logger.error("Error adding candidate for "+stream.streamId+" stream of endpoint "+event.endpointName+": "+error)})}).catch(openViduError=>{logger.error(openViduError)})}onSessionClosed(msg){logger.info("Session closed: "+JSON.stringify(msg));const s=msg.sessionId;if(s!==undefined){this.ee.emitEvent("session-closed",[{session:s}])}else{logger.warn("Session undefined on session closed",msg)}}onLostConnection(reason){logger.warn("Lost connection in Session "+this.sessionId);if(!!this.sessionId&&!!this.connection&&!this.connection.disposed){this.leave(true,reason)}}onRecoveredConnection(){logger.info("Recovered connection in Session "+this.sessionId);this.reconnectBrokenStreams();this.ee.emitEvent("reconnected",[])}onMediaError(event){logger.error("Media error: "+JSON.stringify(event));const err=event.error;if(err){this.ee.emitEvent("error-media",[{error:err}])}else{logger.warn("Received undefined media error:",event)}}onRecordingStarted(event){this.ee.emitEvent("recordingStarted",[new RecordingEvent_1.RecordingEvent(this,"recordingStarted",event.id,event.name)])}onRecordingStopped(event){this.ee.emitEvent("recordingStopped",[new RecordingEvent_1.RecordingEvent(this,"recordingStopped",event.id,event.name,event.reason)])}onBroadcastStarted(){this.ee.emitEvent("broadcastStarted",[])}onBroadcastStopped(){this.ee.emitEvent("broadcastStopped",[])}onFilterEventDispatched(event){const connectionId=event.connectionId;this.getConnection(connectionId,"No connection found for connectionId "+connectionId).then(connection=>{logger.info(`Filter event of type "${event.eventType}" dispatched`);const stream=connection.stream;if(!stream||!stream.filter){return logger.error(`Filter event of type "${event.eventType}" dispatched for stream ${stream.streamId} but there is no ${!stream?"stream":"filter"} defined`)}const eventHandler=stream.filter.handlers.get(event.eventType);if(!eventHandler||typeof eventHandler!=="function"){const actualHandlers=Array.from(stream.filter.handlers.keys());return logger.error(`Filter event of type "${event.eventType}" not handled or not a function! Active filter events: ${actualHandlers.join(",")}`)}else{eventHandler.call(this,new FilterEvent_1.FilterEvent(stream.filter,event.eventType,event.data))}})}onForciblyReconnectSubscriber(event){return new Promise((resolve,reject)=>{this.getRemoteConnection(event.connectionId,"onForciblyReconnectSubscriber").then(connection=>{if(!!connection.stream&&connection.stream.streamId===event.streamId){const stream=connection.stream;if(stream.setupReconnectionEventEmitter(resolve,reject)){if(stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]!=null){stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]=event;return reject("Ongoing forced subscriber reconnection")}else{stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]=event;const callback=()=>{const eventAux=stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"];delete stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"];this.onForciblyReconnectSubscriber(eventAux)};stream.reconnectionEventEmitter.once("success",()=>{callback()});stream.reconnectionEventEmitter.once("error",()=>{callback()})}return}stream.completeWebRtcPeerReceive(true,true,event.sdpOffer).then(()=>stream.finalResolveForSubscription(true,resolve)).catch(error=>stream.finalRejectForSubscription(true,`Error while forcibly reconnecting remote stream ${event.streamId}: ${error.toString()}`,reject))}else{const errMsg="No stream with streamId '"+event.streamId+"' found for connection '"+event.connectionId+"' on 'streamPropertyChanged' event";logger.error(errMsg);return reject(errMsg)}}).catch(openViduError=>{logger.error(openViduError);return reject(openViduError)})})}reconnectBrokenStreams(){logger.info("Re-establishing media connections...");let someReconnection=false;if(!!this.connection.stream&&this.connection.stream.streamIceConnectionStateBroken()){logger.warn("Re-establishing Publisher "+this.connection.stream.streamId);this.connection.stream.initWebRtcPeerSend(true);someReconnection=true}this.remoteConnections.forEach(remoteConnection=>{if(!!remoteConnection.stream&&remoteConnection.stream.streamIceConnectionStateBroken()){logger.warn("Re-establishing Subscriber "+remoteConnection.stream.streamId);remoteConnection.stream.initWebRtcPeerReceive(true);someReconnection=true}});if(!someReconnection){logger.info("There were no media streams in need of a reconnection")}}onSpeechToTextMessage(event){return __awaiter(this,void 0,void 0,function*(){const connection=yield this.getConnection(event.connectionId,"No connection found for connectionId "+event.connectionId);const ev=new SpeechToTextEvent_1.SpeechToTextEvent(this,connection,event.text,event.reason.toLowerCase(),event.raw,event.lang);this.ee.emitEvent("speechToTextMessage",[ev])})}onSpeechToTextDisconnected(event){return __awaiter(this,void 0,void 0,function*(){this.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this,ExceptionEvent_1.ExceptionEventName.SPEECH_TO_TEXT_DISCONNECTED,this,event.message)])})}emitEvent(type,eventArray){this.ee.emitEvent(type,eventArray)}leave(forced,reason){forced=!!forced;logger.info("Leaving Session (forced="+forced+")");this.stopVideoDataIntervals();if(!!this.connection){if(!this.connection.disposed&&!forced){this.openvidu.sendRequest("leaveRoom",(error,response)=>{if(error){logger.error(`leaveRoom error: ${JSON.stringify(error)}`)}this.openvidu.closeWs()})}else{this.openvidu.closeWs()}this.stopPublisherStream(reason);if(!this.connection.disposed){const sessionDisconnectEvent=new SessionDisconnectedEvent_1.SessionDisconnectedEvent(this,reason);this.ee.emitEvent("sessionDisconnected",[sessionDisconnectEvent]);sessionDisconnectEvent.callDefaultBehavior()}}else{logger.warn("You were not connected to the session "+this.sessionId)}logger.flush()}initializeParams(token){const joinParams={token:!!token?token:"",session:this.sessionId,platform:!!platform.getDescription()?platform.getDescription():"unknown",sdkVersion:this.openvidu.libraryVersion,metadata:!!this.options.metadata?this.options.metadata:"",secret:this.openvidu.getSecret(),recorder:this.openvidu.getRecorder(),stt:this.openvidu.getStt()};return joinParams}sendVideoData(streamManager,intervalSeconds=1,doInterval=false,maxLoops=1){var _a,_b;if(platform.isChromeBrowser()||platform.isChromeMobileBrowser()||platform.isOperaBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeBrowser()||platform.isEdgeMobileBrowser()||platform.isElectron()||platform.isSafariBrowser()&&!platform.isIonicIos()||platform.isAndroidBrowser()||platform.isSamsungBrowser()||platform.isIonicAndroid()||platform.isIOSWithSafari()){const obtainAndSendVideo=()=>__awaiter(this,void 0,void 0,function*(){const pc=streamManager.stream.getRTCPeerConnection();if(pc.connectionState==="connected"){const statsMap=yield pc.getStats();const arr=[];statsMap.forEach(stats=>{if("frameWidth"in stats&&"frameHeight"in stats&&arr.length===0){arr.push(stats)}});if(arr.length>0){this.openvidu.sendRequest("videoData",{height:arr[0].frameHeight,width:arr[0].frameWidth,videoActive:streamManager.stream.videoActive!=null?streamManager.stream.videoActive:false,audioActive:streamManager.stream.audioActive!=null?streamManager.stream.audioActive:false},(error,response)=>{if(error){logger.error("Error sending 'videoData' event",error)}})}}});if(doInterval){let loops=1;this.videoDataInterval=setInterval(()=>{if(loops<maxLoops){loops++;obtainAndSendVideo()}else{clearInterval(this.videoDataInterval)}},intervalSeconds*1e3)}else{this.videoDataTimeout=setTimeout(obtainAndSendVideo,intervalSeconds*1e3)}}else if(platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()||platform.isIonicIos()||platform.isReactNative()){this.openvidu.sendRequest("videoData",{height:((_a=streamManager.stream.videoDimensions)===null||_a===void 0?void 0:_a.height)||0,width:((_b=streamManager.stream.videoDimensions)===null||_b===void 0?void 0:_b.width)||0,videoActive:streamManager.stream.videoActive!=null?streamManager.stream.videoActive:false,audioActive:streamManager.stream.audioActive!=null?streamManager.stream.audioActive:false},(error,response)=>{if(error){logger.error("Error sending 'videoData' event",error)}})}else{logger.error("Browser "+platform.getName()+" (version "+platform.getVersion()+") for "+platform.getFamily()+" is not supported in OpenVidu for Network Quality")}}sessionConnected(){return this.connection!=null}notConnectedError(){return new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_NOT_CONNECTED,"There is no connection to the session. Method 'Session.connect' must be successfully completed first")}anySpeechEventListenerEnabled(event,onlyOnce,streamManager){let handlersInSession=this.ee.getListeners(event);if(onlyOnce){handlersInSession=handlersInSession.filter(h=>h.once)}let listenersInSession=handlersInSession.length;if(listenersInSession>0)return true;let listenersInStreamManager=0;if(!!streamManager){let handlersInStreamManager=streamManager.ee.getListeners(event);if(onlyOnce){handlersInStreamManager=handlersInStreamManager.filter(h=>h.once)}listenersInStreamManager=handlersInStreamManager.length}return listenersInStreamManager>0}getTokenParams(token){const match=token.match(/^(wss?)\:\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!!match){const url={protocol:match[1],host:match[2],hostname:match[3],port:match[4],pathname:match[5],search:match[6],hash:match[7]};const params=token.split("?");const queryParams=decodeURI(params[1]).split("&").map(param=>param.split("=")).reduce((values,[key,value])=>{values[key]=value;return values},{});return{sessionId:queryParams["sessionId"],secret:queryParams["secret"],recorder:queryParams["recorder"],stt:queryParams["stt"],webrtcStatsInterval:queryParams["webrtcStatsInterval"],sendBrowserLogs:queryParams["sendBrowserLogs"],edition:queryParams["edition"],wsUri:url.protocol+"://"+url.host+"/openvidu",httpUri:"https://"+url.host}}else{throw new Error(`Token not valid: "${token}"`)}}connectAux(token){return new Promise((resolve,reject)=>{this.openvidu.startWs(error=>{if(!!error){return reject(error)}else{const joinParams=this.initializeParams(token);this.openvidu.sendRequest("joinRoom",joinParams,(error,response)=>{if(!!error){return reject(error)}else{this.processJoinRoomResponse(response,token);this.connection=new Connection_1.Connection(this,response);const events={connections:new Array,streams:new Array};const existingParticipants=response.value;existingParticipants.forEach(remoteConnectionOptions=>{const connection=new Connection_1.Connection(this,remoteConnectionOptions);this.remoteConnections.set(connection.connectionId,connection);events.connections.push(connection);if(!!connection.stream){this.remoteStreamsCreated.set(connection.stream.streamId,true);events.streams.push(connection.stream)}});this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionCreated",this.connection,"")]);events.connections.forEach(connection=>{this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionCreated",connection,"")])});events.streams.forEach(stream=>{this.ee.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",stream,"")])});if(!!response.recordingId&&!!response.recordingName){this.ee.emitEvent("recordingStarted",[new RecordingEvent_1.RecordingEvent(this,"recordingStarted",response.recordingId,response.recordingName)])}return resolve()}})}})})}stopPublisherStream(reason){if(!!this.connection.stream){this.connection.stream.disposeWebRtcPeer();if(this.connection.stream.isLocalStreamPublished){this.connection.stream.ee.emitEvent("local-stream-destroyed",[reason])}}}stopVideoDataIntervals(){clearInterval(this.videoDataInterval);clearTimeout(this.videoDataTimeout)}stringClientMetadata(metadata){if(typeof metadata!=="string"){return JSON.stringify(metadata)}else{return metadata}}getConnection(connectionId,errorMessage){return new Promise((resolve,reject)=>{const connection=this.remoteConnections.get(connectionId);if(!!connection){return resolve(connection)}else{if(this.connection.connectionId===connectionId){return resolve(this.connection)}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,errorMessage))}}})}getRemoteConnection(connectionId,operation){return new Promise((resolve,reject)=>{const connection=this.remoteConnections.get(connectionId);if(!!connection){return resolve(connection)}else{const errorMessage="Remote connection "+connectionId+" unknown when '"+operation+"'. "+"Existing remote connections: "+JSON.stringify(this.remoteConnections.keys());return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,errorMessage))}})}processToken(token){const tokenParams=this.getTokenParams(token);this.sessionId=tokenParams.sessionId;if(!!tokenParams.secret){this.openvidu.secret=tokenParams.secret}if(!!tokenParams.recorder){this.openvidu.recorder=true}if(!!tokenParams.stt){this.openvidu.stt=true}if(!!tokenParams.webrtcStatsInterval){this.openvidu.webrtcStatsInterval=tokenParams.webrtcStatsInterval}if(!!tokenParams.sendBrowserLogs){this.openvidu.sendBrowserLogs=tokenParams.sendBrowserLogs}this.openvidu.isAtLeastPro=tokenParams.edition==="pro"||tokenParams.edition==="enterprise";this.openvidu.isEnterprise=tokenParams.edition==="enterprise";this.openvidu.wsUri=tokenParams.wsUri;this.openvidu.httpUri=tokenParams.httpUri}processJoinRoomResponse(opts,token){this.sessionId=opts.session;if(opts.customIceServers!=null&&opts.customIceServers.length>0){this.openvidu.iceServers=[];for(const iceServer of opts.customIceServers){let rtcIceServer={urls:[iceServer.url]};logger.log("STUN/TURN server IP: "+iceServer.url);if(iceServer.username!=null&&iceServer.credential!=null){rtcIceServer.username=iceServer.username;rtcIceServer.credential=iceServer.credential;logger.log("TURN credentials ["+iceServer.username+":"+iceServer.credential+"]")}this.openvidu.iceServers.push(rtcIceServer)}}this.openvidu.role=opts.role;this.openvidu.finalUserId=opts.finalUserId;this.openvidu.mediaServer=opts.mediaServer;this.openvidu.videoSimulcast=opts.videoSimulcast;this.capabilities={subscribe:true,publish:this.openvidu.role!=="SUBSCRIBER",forceUnpublish:this.openvidu.role==="MODERATOR",forceDisconnect:this.openvidu.role==="MODERATOR"};logger.info("openvidu-server version: "+opts.version);if(opts.life!=null){this.openvidu.life=opts.life}const minorDifference=semverMinor(opts.version)-semverMinor(this.openvidu.libraryVersion);if(semverMajor(opts.version)!==semverMajor(this.openvidu.libraryVersion)||!(minorDifference==0||minorDifference==1)){logger.error(`openvidu-browser (${this.openvidu.libraryVersion}) and openvidu-server (${opts.version}) versions are incompatible. `+"Errors are likely to occur. openvidu-browser SDK is only compatible with the same version or the immediately following minor version of an OpenVidu deployment")}else if(minorDifference==1){logger.warn(`openvidu-browser version ${this.openvidu.libraryVersion} does not match openvidu-server version ${opts.version}. `+`These versions are still compatible with each other, but openvidu-browser version must be updated as soon as possible to ${semverMajor(opts.version)}.${semverMinor(opts.version)}.x. `+`This client using openvidu-browser ${this.openvidu.libraryVersion} will become incompatible with the next release of openvidu-server`)}OpenViduLogger_1.OpenViduLogger.configureJSNLog(this.openvidu,token);this.token=token}}exports.Session=Session},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/ConnectionEvent":56,"../OpenViduInternal/Events/ConnectionPropertyChangedEvent":57,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/FilterEvent":60,"../OpenViduInternal/Events/NetworkQualityLevelChangedEvent":61,"../OpenViduInternal/Events/RecordingEvent":63,"../OpenViduInternal/Events/SessionDisconnectedEvent":64,"../OpenViduInternal/Events/SignalEvent":65,"../OpenViduInternal/Events/SpeechToTextEvent":66,"../OpenViduInternal/Events/StreamEvent":67,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./Connection":42,"./EventDispatcher":43,"./Filter":44,"./Subscriber":51,"semver/functions/major":16,"semver/functions/minor":17}],49:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.Stream=void 0;const Filter_1=require("./Filter");const Subscriber_1=require("./Subscriber");const WebRtcPeer_1=require("../OpenViduInternal/WebRtcPeer/WebRtcPeer");const WebRtcStats_1=require("../OpenViduInternal/WebRtcStats/WebRtcStats");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const PublisherSpeakingEvent_1=require("../OpenViduInternal/Events/PublisherSpeakingEvent");const StreamManagerEvent_1=require("../OpenViduInternal/Events/StreamManagerEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const TypeOfVideo_1=require("../OpenViduInternal/Enums/TypeOfVideo");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const uuid_1=require("uuid");const hark=require("hark");const EventEmitter=require("wolfy87-eventemitter");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class Stream{constructor(session,options){this.isSubscribeToRemote=false;this.isLocalStreamReadyToPublish=false;this.isLocalStreamPublished=false;this.publishedOnce=false;this.harkSpeakingEnabled=false;this.harkSpeakingEnabledOnce=false;this.harkStoppedSpeakingEnabled=false;this.harkStoppedSpeakingEnabledOnce=false;this.harkVolumeChangeEnabled=false;this.harkVolumeChangeEnabledOnce=false;this.ee=new EventEmitter;platform=Platform_1.PlatformUtils.getInstance();this.session=session;if(options.hasOwnProperty("id")){this.inboundStreamOpts=options;this.streamId=this.inboundStreamOpts.id;this.creationTime=this.inboundStreamOpts.createdAt;this.hasAudio=this.inboundStreamOpts.hasAudio;this.hasVideo=this.inboundStreamOpts.hasVideo;if(this.hasAudio){this.audioActive=this.inboundStreamOpts.audioActive}if(this.hasVideo){this.videoActive=this.inboundStreamOpts.videoActive;this.typeOfVideo=!this.inboundStreamOpts.typeOfVideo?undefined:this.inboundStreamOpts.typeOfVideo;this.frameRate=this.inboundStreamOpts.frameRate===-1?undefined:this.inboundStreamOpts.frameRate;this.videoDimensions=this.inboundStreamOpts.videoDimensions}if(!!this.inboundStreamOpts.filter&&Object.keys(this.inboundStreamOpts.filter).length>0){if(!!this.inboundStreamOpts.filter.lastExecMethod&&Object.keys(this.inboundStreamOpts.filter.lastExecMethod).length===0){delete this.inboundStreamOpts.filter.lastExecMethod}this.filter=this.inboundStreamOpts.filter}}else{this.outboundStreamOpts=options;this.hasAudio=this.isSendAudio();this.hasVideo=this.isSendVideo();if(this.hasAudio){this.audioActive=!!this.outboundStreamOpts.publisherProperties.publishAudio}if(this.hasVideo){this.videoActive=!!this.outboundStreamOpts.publisherProperties.publishVideo;this.frameRate=this.outboundStreamOpts.publisherProperties.frameRate;if(typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack){this.typeOfVideo=TypeOfVideo_1.TypeOfVideo.CUSTOM}else{this.typeOfVideo=this.isSendScreen()?TypeOfVideo_1.TypeOfVideo.SCREEN:TypeOfVideo_1.TypeOfVideo.CAMERA}}if(!!this.outboundStreamOpts.publisherProperties.filter){this.filter=this.outboundStreamOpts.publisherProperties.filter}}this.ee.on("mediastream-updated",()=>{var _a;this.streamManager.updateMediaStream(this.mediaStream);logger.debug("Video srcObject ["+((_a=this.mediaStream)===null||_a===void 0?void 0:_a.id)+"] updated in stream ["+this.streamId+"]")})}reconnect(){return this.reconnectStream("API")}applyFilter(type,options){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){if(!!this.filter){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"There is already a filter applied to Stream "+this.streamId))}const resolveApplyFilter=(error,triggerEvent)=>{if(error){logger.error("Error applying filter for Stream "+this.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to apply a filter"))}else{return reject(error)}}else{logger.info("Filter successfully applied on Stream "+this.streamId);const oldValue=this.filter;this.filter=new Filter_1.Filter(type,options);this.filter.stream=this;if(triggerEvent){this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this,"filter",this.filter,oldValue,"applyFilter")]);this.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.streamManager,this,"filter",this.filter,oldValue,"applyFilter")])}return resolve(this.filter)}};if(type.startsWith("VB:")){if(!this.hasVideo){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"The Virtual Background filter requires a video track to be applied"))}if(!this.mediaStream||this.streamManager.videos.length===0){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"The StreamManager requires some video element to be attached to it in order to apply a Virtual Background filter"))}let openviduToken;if(!!this.session.token){openviduToken=this.session.token}else{openviduToken=options["token"]}if(!openviduToken){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,'Virtual Background requires the client to be connected to a Session or to have a "token" property available in "options" parameter with a valid OpenVidu token'))}const tokenParams=this.session.getTokenParams(openviduToken);if(tokenParams.edition!=="pro"&&tokenParams.edition!=="enterprise"){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"OpenVidu Virtual Background API is available from OpenVidu Pro edition onwards"))}openviduToken=encodeURIComponent(btoa(openviduToken));logger.info("Applying Virtual Background to stream "+this.streamId);const afterScriptLoaded=()=>__awaiter(this,void 0,void 0,function*(){try{const id=this.streamId+"_"+(0,uuid_1.v4)();const mediaStreamClone=this.mediaStream.clone();const videoClone=this.streamManager.videos[0].video.cloneNode(false);videoClone.id=VirtualBackground.VirtualBackground.SOURCE_VIDEO_PREFIX+id;videoClone.srcObject=mediaStreamClone;videoClone.muted=true;this.virtualBackgroundSourceElements={videoClone:videoClone,mediaStreamClone:mediaStreamClone};VirtualBackground.VirtualBackground.hideHtmlElement(videoClone,false);VirtualBackground.VirtualBackground.appendHtmlElementToHiddenContainer(videoClone,id);yield videoClone.play();const VB=new VirtualBackground.VirtualBackground({id:id,openviduServerUrl:new URL(tokenParams.httpUri),openviduToken:openviduToken,inputVideo:videoClone,inputResolution:"160x96",outputFramerate:24});let filteredVideo;switch(type){case"VB:blur":{filteredVideo=yield VB.backgroundBlur(options);break}case"VB:image":{filteredVideo=yield VB.backgroundImage(options);break}default:throw new Error("Unknown Virtual Background filter: "+type)}this.virtualBackgroundSinkElements={VB:VB,video:filteredVideo};videoClone.style.display="none";if(this.streamManager.remote){this.streamManager.replaceTrackInMediaStream(this.virtualBackgroundSinkElements.video.srcObject.getVideoTracks()[0],false)}else{this.streamManager.replaceTrackAux(this.virtualBackgroundSinkElements.video.srcObject.getVideoTracks()[0],false)}resolveApplyFilter(undefined,false)}catch(error){if(error.name===OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR){resolveApplyFilter(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,error.message),false)}else{resolveApplyFilter(error,false)}}});if(typeof VirtualBackground==="undefined"){let script=document.createElement("script");script.type="text/javascript";script.src=tokenParams.httpUri+"/openvidu/virtual-background/openvidu-virtual-background.js?token="+openviduToken;script.onload=()=>__awaiter(this,void 0,void 0,function*(){try{yield afterScriptLoaded();resolve(new Filter_1.Filter(type,options))}catch(error){reject(error)}});document.body.appendChild(script)}else{afterScriptLoaded().then(()=>resolve(new Filter_1.Filter(type,options))).catch(error=>reject(error))}}else{if(!this.session.sessionConnected()){return reject(this.session.notConnectedError())}logger.info("Applying server filter to stream "+this.streamId);options=options!=null?options:{};let optionsString=options;if(typeof optionsString!=="string"){optionsString=JSON.stringify(optionsString)}this.session.openvidu.sendRequest("applyFilter",{streamId:this.streamId,type:type,options:optionsString},(error,response)=>{resolveApplyFilter(error,true)})}}))}removeFilter(){return __awaiter(this,void 0,void 0,function*(){return yield this.removeFilterAux(false)})}getRTCPeerConnection(){return this.webRtcPeer.pc}getMediaStream(){return this.mediaStream}removeFilterAux(isDisposing){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){var _a;const resolveRemoveFilter=(error,triggerEvent)=>{if(error){delete this.filter;logger.error("Error removing filter for Stream "+this.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to remove a filter"))}else{return reject(error)}}else{logger.info("Filter successfully removed from Stream "+this.streamId);const oldValue=this.filter;delete this.filter;if(triggerEvent){this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this,"filter",this.filter,oldValue,"applyFilter")]);this.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.streamManager,this,"filter",this.filter,oldValue,"applyFilter")])}return resolve()}};if(!!this.filter){if((_a=this.filter)===null||_a===void 0?void 0:_a.type.startsWith("VB:")){try{const mediaStreamClone=this.virtualBackgroundSourceElements.mediaStreamClone;if(!isDisposing){if(this.streamManager.remote){this.streamManager.replaceTrackInMediaStream(mediaStreamClone.getVideoTracks()[0],false)}else{yield this.streamManager.replaceTrackAux(mediaStreamClone.getVideoTracks()[0],false)}}else{mediaStreamClone.getTracks().forEach(track=>track.stop())}this.virtualBackgroundSinkElements.VB.cleanUp();delete this.virtualBackgroundSinkElements;delete this.virtualBackgroundSourceElements;return resolveRemoveFilter(undefined,false)}catch(error){return resolveRemoveFilter(error,false)}}else{if(!this.session.sessionConnected()){return reject(this.session.notConnectedError())}logger.info("Removing filter of stream "+this.streamId);this.session.openvidu.sendRequest("removeFilter",{streamId:this.streamId},(error,response)=>resolveRemoveFilter(error,true))}}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"Stream "+this.streamId+" has no filter applied"))}}))}setMediaStream(mediaStream){this.mediaStream=mediaStream}updateMediaStreamInVideos(){this.ee.emitEvent("mediastream-updated",[])}getWebRtcPeer(){return this.webRtcPeer}subscribeToMyRemote(value){this.isSubscribeToRemote=value}setOutboundStreamOptions(outboundStreamOpts){this.outboundStreamOpts=outboundStreamOpts}subscribe(){return new Promise((resolve,reject)=>{this.initWebRtcPeerReceive(false).then(()=>resolve()).catch(error=>reject(error))})}publish(){return new Promise((resolve,reject)=>{if(this.isLocalStreamReadyToPublish){this.initWebRtcPeerSend(false).then(()=>resolve()).catch(error=>reject(error))}else{this.ee.once("stream-ready-to-publish",()=>{this.publish().then(()=>resolve()).catch(error=>reject(error))})}})}disposeWebRtcPeer(){let webrtcId;if(!!this.webRtcPeer){this.webRtcPeer.dispose();webrtcId=this.webRtcPeer.getId()}this.stopWebRtcStats();logger.info((!!this.outboundStreamOpts?"Outbound ":"Inbound ")+"RTCPeerConnection with id ["+webrtcId+"] from 'Stream' with id ["+this.streamId+"] is now closed")}disposeMediaStream(){return __awaiter(this,void 0,void 0,function*(){if(!!this.filter&&this.filter.type.startsWith("VB:")){try{yield this.removeFilterAux(true);console.debug(`Success removing Virtual Background filter for stream ${this.streamId}`)}catch(error){console.error(`Error removing Virtual Background filter for stream ${this.streamId}`,error)}}if(this.mediaStream){this.mediaStream.getAudioTracks().forEach(track=>{track.stop()});this.mediaStream.getVideoTracks().forEach(track=>{track.stop()});delete this.mediaStream}if(this.localMediaStreamWhenSubscribedToRemote){this.localMediaStreamWhenSubscribedToRemote.getAudioTracks().forEach(track=>{track.stop()});this.localMediaStreamWhenSubscribedToRemote.getVideoTracks().forEach(track=>{track.stop()});delete this.localMediaStreamWhenSubscribedToRemote}if(!!this.speechEvent){if(!!this.speechEvent.stop){this.speechEvent.stop()}delete this.speechEvent}logger.info((!!this.outboundStreamOpts?"Local ":"Remote ")+"MediaStream from 'Stream' with id ["+this.streamId+"] is now disposed")})}displayMyRemote(){return this.isSubscribeToRemote}isSendAudio(){return!!this.outboundStreamOpts&&this.outboundStreamOpts.publisherProperties.audioSource!==null&&this.outboundStreamOpts.publisherProperties.audioSource!==false}isSendVideo(){return!!this.outboundStreamOpts&&this.outboundStreamOpts.publisherProperties.videoSource!==null&&this.outboundStreamOpts.publisherProperties.videoSource!==false}isSendScreen(){let screen=false;if(typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack){let trackSettings=this.outboundStreamOpts.publisherProperties.videoSource.getSettings();if(trackSettings.displaySurface){screen=["monitor","window","browser"].includes(trackSettings.displaySurface)}}if(!screen&&platform.isElectron()){screen=typeof this.outboundStreamOpts.publisherProperties.videoSource==="string"&&this.outboundStreamOpts.publisherProperties.videoSource.startsWith("screen:")}if(!screen){screen=this.outboundStreamOpts.publisherProperties.videoSource==="screen"}return!!this.outboundStreamOpts&&screen}enableHarkSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkSpeakingEnabled&&!!this.speechEvent){this.harkSpeakingEnabled=true;this.speechEvent.on("speaking",()=>{this.session.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStartSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStartSpeaking",this.connection,this.streamId)]);this.harkSpeakingEnabledOnce=false})}}enableOnceHarkSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkSpeakingEnabledOnce&&!!this.speechEvent){this.harkSpeakingEnabledOnce=true;this.speechEvent.once("speaking",()=>{if(this.harkSpeakingEnabledOnce){this.session.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStartSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStartSpeaking",this.connection,this.streamId)])}this.disableHarkSpeakingEvent(true)})}}disableHarkSpeakingEvent(disabledByOnce){if(!!this.speechEvent){this.harkSpeakingEnabledOnce=false;if(disabledByOnce){if(this.harkSpeakingEnabled){return}}else{this.harkSpeakingEnabled=false}if(this.harkVolumeChangeEnabled||this.harkVolumeChangeEnabledOnce||this.harkStoppedSpeakingEnabled||this.harkStoppedSpeakingEnabledOnce){this.speechEvent.off("speaking")}else{this.speechEvent.stop();delete this.speechEvent}}}enableHarkStoppedSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkStoppedSpeakingEnabled&&!!this.speechEvent){this.harkStoppedSpeakingEnabled=true;this.speechEvent.on("stopped_speaking",()=>{this.session.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStopSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStopSpeaking",this.connection,this.streamId)]);this.harkStoppedSpeakingEnabledOnce=false})}}enableOnceHarkStoppedSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkStoppedSpeakingEnabledOnce&&!!this.speechEvent){this.harkStoppedSpeakingEnabledOnce=true;this.speechEvent.once("stopped_speaking",()=>{if(this.harkStoppedSpeakingEnabledOnce){this.session.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStopSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStopSpeaking",this.connection,this.streamId)])}this.disableHarkStoppedSpeakingEvent(true)})}}disableHarkStoppedSpeakingEvent(disabledByOnce){if(!!this.speechEvent){this.harkStoppedSpeakingEnabledOnce=false;if(disabledByOnce){if(this.harkStoppedSpeakingEnabled){return}}else{this.harkStoppedSpeakingEnabled=false}if(this.harkVolumeChangeEnabled||this.harkVolumeChangeEnabledOnce||this.harkSpeakingEnabled||this.harkSpeakingEnabledOnce){this.speechEvent.off("stopped_speaking")}else{this.speechEvent.stop();delete this.speechEvent}}}enableHarkVolumeChangeEvent(force){if(this.setHarkListenerIfNotExists()){if(!this.harkVolumeChangeEnabled||force){this.harkVolumeChangeEnabled=true;this.speechEvent.on("volume_change",harkEvent=>{const oldValue=this.speechEvent.oldVolumeValue;const value={newValue:harkEvent,oldValue:oldValue};this.speechEvent.oldVolumeValue=harkEvent;this.streamManager.emitEvent("streamAudioVolumeChange",[new StreamManagerEvent_1.StreamManagerEvent(this.streamManager,"streamAudioVolumeChange",value)])})}}else{this.harkVolumeChangeEnabled=true}}enableOnceHarkVolumeChangeEvent(force){if(this.setHarkListenerIfNotExists()){if(!this.harkVolumeChangeEnabledOnce||force){this.harkVolumeChangeEnabledOnce=true;this.speechEvent.once("volume_change",harkEvent=>{const oldValue=this.speechEvent.oldVolumeValue;const value={newValue:harkEvent,oldValue:oldValue};this.speechEvent.oldVolumeValue=harkEvent;this.disableHarkVolumeChangeEvent(true);this.streamManager.emitEvent("streamAudioVolumeChange",[new StreamManagerEvent_1.StreamManagerEvent(this.streamManager,"streamAudioVolumeChange",value)])})}}else{this.harkVolumeChangeEnabledOnce=true}}disableHarkVolumeChangeEvent(disabledByOnce){if(!!this.speechEvent){this.harkVolumeChangeEnabledOnce=false;if(disabledByOnce){if(this.harkVolumeChangeEnabled){return}}else{this.harkVolumeChangeEnabled=false}if(this.harkSpeakingEnabled||this.harkSpeakingEnabledOnce||this.harkStoppedSpeakingEnabled||this.harkStoppedSpeakingEnabledOnce){this.speechEvent.off("volume_change")}else{this.speechEvent.stop();delete this.speechEvent}}}isLocal(){return!this.inboundStreamOpts&&!!this.outboundStreamOpts}getSelectedIceCandidate(){return new Promise((resolve,reject)=>{this.webRtcStats.getSelectedIceCandidateInfo().then(report=>resolve(report)).catch(error=>reject(error))})}getRemoteIceCandidateList(){return this.webRtcPeer.remoteCandidatesQueue}getLocalIceCandidateList(){return this.webRtcPeer.localCandidatesQueue}streamIceConnectionStateBroken(){if(!this.getWebRtcPeer()||!this.getRTCPeerConnection()){return false}if(!!this.session.openvidu.advancedConfiguration.forceMediaReconnectionAfterNetworkDrop){logger.warn(`OpenVidu Browser advanced configuration option "forceMediaReconnectionAfterNetworkDrop" is enabled. Stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) will force a reconnection`);return true}else{const iceConnectionState=this.getRTCPeerConnection().iceConnectionState;return iceConnectionState!=="connected"&&iceConnectionState!=="completed"}}setHarkListenerIfNotExists(){if(!!this.mediaStream){if(!this.speechEvent){const harkOptions=!!this.harkOptions?this.harkOptions:this.session.openvidu.advancedConfiguration.publisherSpeakingEventsOptions||{};harkOptions.interval=typeof harkOptions.interval==="number"?harkOptions.interval:100;harkOptions.threshold=typeof harkOptions.threshold==="number"?harkOptions.threshold:-50;this.speechEvent=hark(this.mediaStream,harkOptions)}return true}return false}setupReconnectionEventEmitter(resolve,reject){if(this.reconnectionEventEmitter==undefined){this.reconnectionEventEmitter=new EventEmitter;return false}else{console.warn(`Trying to reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) but an ongoing reconnection process is active. Waiting for response...`);this.reconnectionEventEmitter.once("success",()=>resolve());this.reconnectionEventEmitter.once("error",error=>reject(error));return true}}initWebRtcPeerSend(reconnect){return new Promise((resolve,reject)=>{var _a;if(reconnect){if(this.setupReconnectionEventEmitter(resolve,reject)){return}}else{this.initHarkEvents()}const finalResolve=()=>{var _a;if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("success");delete this.reconnectionEventEmitter}return resolve()};const finalReject=error=>{var _a;if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("error",[error]);delete this.reconnectionEventEmitter}return reject(error)};const successOfferCallback=sdpOfferParam=>{logger.debug("Sending SDP offer to publish as "+this.streamId,sdpOfferParam);const method=reconnect?"reconnectStream":"publishVideo";let params;if(reconnect){params={stream:this.streamId,sdpString:sdpOfferParam}}else{let typeOfVideo;if(this.isSendVideo()){typeOfVideo=typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack?TypeOfVideo_1.TypeOfVideo.CUSTOM:this.isSendScreen()?TypeOfVideo_1.TypeOfVideo.SCREEN:TypeOfVideo_1.TypeOfVideo.CAMERA}params={doLoopback:this.displayMyRemote()||false,hasAudio:this.isSendAudio(),hasVideo:this.isSendVideo(),audioActive:this.audioActive,videoActive:this.videoActive,typeOfVideo:typeOfVideo,frameRate:!!this.frameRate?this.frameRate:-1,videoDimensions:JSON.stringify(this.videoDimensions),filter:this.outboundStreamOpts.publisherProperties.filter,sdpOffer:sdpOfferParam}}this.session.openvidu.sendRequest(method,params,(error,response)=>{if(error){if(error.code===401){finalReject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to publish"))}else{finalReject("Error on publishVideo: "+JSON.stringify(error))}}else{this.webRtcPeer.processRemoteAnswer(response.sdpAnswer).then(()=>{this.streamId=response.id;this.creationTime=response.createdAt;this.isLocalStreamPublished=true;this.publishedOnce=true;if(this.displayMyRemote()){this.localMediaStreamWhenSubscribedToRemote=this.mediaStream;this.remotePeerSuccessfullyEstablished(reconnect)}if(reconnect){this.ee.emitEvent("stream-reconnected-by-publisher",[])}else{this.ee.emitEvent("stream-created-by-publisher",[])}this.initWebRtcStats();logger.info("'Publisher' ("+this.streamId+") successfully "+(reconnect?"reconnected":"published")+" to session");finalResolve()}).catch(error=>{finalReject(error)})}})};const config={mediaConstraints:{audio:this.hasAudio,video:this.hasVideo},simulcast:(_a=this.outboundStreamOpts.publisherProperties.videoSimulcast)!==null&&_a!==void 0?_a:this.session.openvidu.videoSimulcast,onIceCandidate:this.connection.sendIceCandidate.bind(this.connection),onIceConnectionStateException:this.onIceConnectionStateExceptionHandler.bind(this),iceServers:this.getIceServersConf(),rtcConfiguration:this.session.openvidu.advancedConfiguration.rtcConfiguration,mediaStream:this.mediaStream,mediaServer:this.session.openvidu.mediaServer,typeOfVideo:this.typeOfVideo?TypeOfVideo_1.TypeOfVideo[this.typeOfVideo]:undefined};if(this.session.openvidu.mediaServer!=="mediasoup"){config.simulcast=false}if(reconnect){this.disposeWebRtcPeer()}if(this.displayMyRemote()){this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerSendrecv(config)}else{this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerSendonly(config)}this.webRtcPeer.addIceConnectionStateChangeListener("publisher of "+this.connection.connectionId);this.webRtcPeer.createOffer().then(sdpOffer=>{this.webRtcPeer.processLocalOffer(sdpOffer).then(()=>{successOfferCallback(sdpOffer.sdp)}).catch(error=>{finalReject(new Error("(publish) SDP process local offer error: "+JSON.stringify(error)))})}).catch(error=>{finalReject(new Error("(publish) SDP create offer error: "+JSON.stringify(error)))})})}finalResolveForSubscription(reconnect,resolve){var _a;logger.info("'Subscriber' ("+this.streamId+") successfully "+(reconnect?"reconnected":"subscribed"));this.remotePeerSuccessfullyEstablished(reconnect);this.initWebRtcStats();if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("success");delete this.reconnectionEventEmitter}return resolve()}finalRejectForSubscription(reconnect,error,reject){var _a;logger.error("Error for 'Subscriber' ("+this.streamId+") while trying to "+(reconnect?"reconnect":"subscribe")+": "+error.toString());if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("error",[error]);delete this.reconnectionEventEmitter}return reject(error)}initWebRtcPeerReceive(reconnect){return new Promise((resolve,reject)=>{if(reconnect){if(this.setupReconnectionEventEmitter(resolve,reject)){return}}if(this.session.openvidu.mediaServer==="mediasoup"){this.initWebRtcPeerReceiveFromServer(reconnect).then(()=>this.finalResolveForSubscription(reconnect,resolve)).catch(error=>this.finalRejectForSubscription(reconnect,error,reject))}else{this.initWebRtcPeerReceiveFromClient(reconnect).then(()=>this.finalResolveForSubscription(reconnect,resolve)).catch(error=>this.finalRejectForSubscription(reconnect,error,reject))}})}initWebRtcPeerReceiveFromClient(reconnect){return new Promise((resolve,reject)=>{this.completeWebRtcPeerReceive(reconnect,false).then(response=>{this.webRtcPeer.processRemoteAnswer(response.sdpAnswer).then(()=>resolve()).catch(error=>reject(error))}).catch(error=>reject(error))})}initWebRtcPeerReceiveFromServer(reconnect){return new Promise((resolve,reject)=>{this.session.openvidu.sendRequest("prepareReceiveVideoFrom",{sender:this.streamId,reconnect:reconnect},(error,response)=>{if(error){return reject(new Error("Error on prepareReceiveVideoFrom: "+JSON.stringify(error)))}else{this.completeWebRtcPeerReceive(reconnect,false,response.sdpOffer).then(()=>resolve()).catch(error=>reject(error))}})})}completeWebRtcPeerReceive(reconnect,forciblyReconnect,sdpOfferByServer){return new Promise((resolve,reject)=>{logger.debug("'Session.subscribe(Stream)' called");const sendSdpToServer=sdpString=>{logger.debug(`Sending local SDP ${!!sdpOfferByServer?"answer":"offer"} to subscribe to ${this.streamId}`,sdpString);const method=reconnect?"reconnectStream":"receiveVideoFrom";const params={};params[reconnect?"stream":"sender"]=this.streamId;if(!!sdpOfferByServer){params[reconnect?"sdpString":"sdpAnswer"]=sdpString}else{params["sdpOffer"]=sdpString}if(reconnect){params["forciblyReconnect"]=forciblyReconnect}this.session.openvidu.sendRequest(method,params,(error,response)=>{if(error){return reject(new Error("Error on "+method+" : "+JSON.stringify(error)))}else{return resolve(response)}})};const config={mediaConstraints:{audio:this.hasAudio,video:this.hasVideo},simulcast:false,onIceCandidate:this.connection.sendIceCandidate.bind(this.connection),onIceConnectionStateException:this.onIceConnectionStateExceptionHandler.bind(this),iceServers:this.getIceServersConf(),rtcConfiguration:this.session.openvidu.advancedConfiguration.rtcConfiguration,mediaServer:this.session.openvidu.mediaServer,typeOfVideo:this.typeOfVideo?TypeOfVideo_1.TypeOfVideo[this.typeOfVideo]:undefined};if(reconnect){this.disposeWebRtcPeer()}this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerRecvonly(config);this.webRtcPeer.addIceConnectionStateChangeListener(this.streamId);if(!!sdpOfferByServer){this.webRtcPeer.processRemoteOffer(sdpOfferByServer).then(()=>{this.webRtcPeer.createAnswer().then(sdpAnswer=>{this.webRtcPeer.processLocalAnswer(sdpAnswer).then(()=>{sendSdpToServer(sdpAnswer.sdp)}).catch(error=>reject(new Error("(subscribe) SDP process local answer error: "+JSON.stringify(error))))}).catch(error=>reject(new Error("(subscribe) SDP create answer error: "+JSON.stringify(error))))}).catch(error=>reject(new Error("(subscribe) SDP process remote offer error: "+JSON.stringify(error))))}else{this.webRtcPeer.createOffer().then(sdpOffer=>{this.webRtcPeer.processLocalOffer(sdpOffer).then(()=>{sendSdpToServer(sdpOffer.sdp)}).catch(error=>reject(new Error("(subscribe) SDP process local offer error: "+JSON.stringify(error))))}).catch(error=>reject(new Error("(subscribe) SDP create offer error: "+JSON.stringify(error))))}})}remotePeerSuccessfullyEstablished(reconnect){if(reconnect&&this.mediaStream!=null){this.disposeMediaStream()}this.mediaStream=new MediaStream;let receiver;for(receiver of this.webRtcPeer.pc.getReceivers()){if(!!receiver.track){this.mediaStream.addTrack(receiver.track)}}logger.debug("Peer remote stream",this.mediaStream);if(!!this.mediaStream){if(this.streamManager instanceof Subscriber_1.Subscriber){if(!!this.mediaStream.getAudioTracks()[0]){const enabled=reconnect?this.audioActive:!!this.streamManager.properties.subscribeToAudio;this.mediaStream.getAudioTracks()[0].enabled=enabled}if(!!this.mediaStream.getVideoTracks()[0]){const enabled=reconnect?this.videoActive:!!this.videoActive&&!!this.streamManager.properties.subscribeToVideo;this.mediaStream.getVideoTracks()[0].enabled=enabled}}this.updateMediaStreamInVideos();this.initHarkEvents()}}initHarkEvents(){if(!!this.mediaStream.getAudioTracks()[0]){if(this.session.anySpeechEventListenerEnabled("publisherStartSpeaking",true,this.streamManager)){this.enableOnceHarkSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStartSpeaking",false,this.streamManager)){this.enableHarkSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStopSpeaking",true,this.streamManager)){this.enableOnceHarkStoppedSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStopSpeaking",false,this.streamManager)){this.enableHarkStoppedSpeakingEvent()}if(this.harkVolumeChangeEnabledOnce){this.enableOnceHarkVolumeChangeEvent(true)}if(this.harkVolumeChangeEnabled){this.enableHarkVolumeChangeEvent(true)}}}onIceConnectionStateExceptionHandler(exceptionName,message,data){switch(exceptionName){case ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED:this.onIceConnectionFailed();break;case ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED:this.onIceConnectionDisconnected();break}this.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.session,exceptionName,this,message,data)])}onIceConnectionFailed(){logger.log(`[ICE_CONNECTION_FAILED] Handling ICE_CONNECTION_FAILED event. Reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"})`);this.reconnectStreamAndLogResultingIceConnectionState(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED)}onIceConnectionDisconnected(){logger.log(`[ICE_CONNECTION_DISCONNECTED] Handling ICE_CONNECTION_DISCONNECTED event. Waiting for ICE to be restored and reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) if not possible`);const timeout=this.session.openvidu.advancedConfiguration.iceConnectionDisconnectedExceptionTimeout||4e3;this.awaitWebRtcPeerConnectionState(timeout).then(state=>{switch(state){case"failed":logger.warn(`[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) is now failed after ICE_CONNECTION_DISCONNECTED`);break;case"connected":case"completed":logger.log(`[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) automatically restored after ICE_CONNECTION_DISCONNECTED. Current ICE connection state: ${state}`);break;case"closed":case"checking":case"new":case"disconnected":logger.warn(`[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) couldn't be restored after ICE_CONNECTION_DISCONNECTED event. Current ICE connection state after ${timeout} ms: ${state}`);this.reconnectStreamAndLogResultingIceConnectionState(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED);break}})}reconnectStreamAndLogResultingIceConnectionState(event){return __awaiter(this,void 0,void 0,function*(){try{const finalIceStateAfterReconnection=yield this.reconnectStreamAndReturnIceConnectionState(event);switch(finalIceStateAfterReconnection){case"connected":case"completed":logger.log(`[${event}] Stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) successfully reconnected after ${event}. Current ICE connection state: ${finalIceStateAfterReconnection}`);break;default:logger.error(`[${event}] Stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) failed to reconnect after ${event}. Current ICE connection state: ${finalIceStateAfterReconnection}`);break}}catch(error){logger.error(`[${event}] Error reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) after ${event}: ${error}`)}})}reconnectStreamAndReturnIceConnectionState(event){return __awaiter(this,void 0,void 0,function*(){logger.log(`[${event}] Reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) after event ${event}`);try{yield this.reconnectStream(event);const timeout=this.session.openvidu.advancedConfiguration.iceConnectionDisconnectedExceptionTimeout||4e3;return this.awaitWebRtcPeerConnectionState(timeout)}catch(error){logger.warn(`[${event}] Error reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}). Reason: ${error}`);return this.awaitWebRtcPeerConnectionState(1)}})}awaitWebRtcPeerConnectionState(timeout){return __awaiter(this,void 0,void 0,function*(){let state=this.getRTCPeerConnection().iceConnectionState;const interval=150;const intervals=Math.ceil(timeout/interval);for(let i=0;i<intervals;i++){state=this.getRTCPeerConnection().iceConnectionState;if(state==="connected"||state==="completed"){break}yield new Promise(resolve=>setTimeout(resolve,interval))}return state})}reconnectStream(event){return __awaiter(this,void 0,void 0,function*(){const isWsConnected=yield this.isWebsocketConnected(event,3e3);if(isWsConnected){logger.log(`[${event}] Trying to reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) and the websocket is opened`);if(this.isLocal()){return this.initWebRtcPeerSend(true)}else{return this.initWebRtcPeerReceive(true)}}else{const errorMsg=`[${event}] Trying to reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) but the websocket wasn't opened`;logger.error(errorMsg);throw Error(errorMsg)}})}isWebsocketConnected(event,msResponseTimeout){return new Promise((resolve,reject)=>{const wsReadyState=this.session.openvidu.getWsReadyState();if(wsReadyState===1){const responseTimeout=setTimeout(()=>{console.warn(`[${event}] Websocket timeout of ${msResponseTimeout}ms`);return resolve(false)},msResponseTimeout);this.session.openvidu.sendRequest("echo",{},(error,response)=>{clearTimeout(responseTimeout);if(!!error){console.warn(`[${event}] Websocket 'echo' returned error: ${error}`);return resolve(false)}else{return resolve(true)}})}else{console.warn(`[${event}] Websocket readyState is ${wsReadyState}`);return resolve(false)}})}initWebRtcStats(){this.webRtcStats=new WebRtcStats_1.WebRtcStats(this);this.webRtcStats.initWebRtcStats()}stopWebRtcStats(){if(!!this.webRtcStats&&this.webRtcStats.isEnabled()){this.webRtcStats.stopWebRtcStats()}}getIceServersConf(){var _a;let returnValue;if(!!this.session.openvidu.advancedConfiguration.iceServers){returnValue=this.session.openvidu.advancedConfiguration.iceServers==="freeice"?undefined:this.session.openvidu.advancedConfiguration.iceServers}else if(!!((_a=this.session.openvidu.advancedConfiguration.rtcConfiguration)===null||_a===void 0?void 0:_a.iceServers)){returnValue=this.session.openvidu.advancedConfiguration.rtcConfiguration.iceServers}else if(this.session.openvidu.iceServers){returnValue=this.session.openvidu.iceServers}else{returnValue=undefined}return returnValue}gatherStatsForPeer(){return new Promise((resolve,reject)=>{if(this.isLocal()){this.getRTCPeerConnection().getSenders().forEach(sender=>sender.getStats().then(response=>{response.forEach(report=>{if(this.isReportWanted(report)){const finalReport={};finalReport["type"]=report.type;finalReport["timestamp"]=report.timestamp;finalReport["id"]=report.id;if(report.type==="outbound-rtp"){finalReport["ssrc"]=report.ssrc;finalReport["firCount"]=report.firCount;finalReport["pliCount"]=report.pliCount;finalReport["nackCount"]=report.nackCount;finalReport["qpSum"]=report.qpSum;if(!!report.kind){finalReport["mediaType"]=report.kind}else if(!!report.mediaType){finalReport["mediaType"]=report.mediaType}else{finalReport["mediaType"]=report.id.indexOf("VideoStream")!==-1?"video":"audio"}if(finalReport["mediaType"]==="video"){finalReport["framesEncoded"]=report.framesEncoded}finalReport["packetsSent"]=report.packetsSent;finalReport["bytesSent"]=report.bytesSent}if(report.type==="candidate-pair"&&report.totalRoundTripTime!==undefined){finalReport["availableOutgoingBitrate"]=report.availableOutgoingBitrate;finalReport["rtt"]=report.currentRoundTripTime;finalReport["averageRtt"]=report.totalRoundTripTime/report.responsesReceived}if(report.type==="remote-inbound-rtp"||report.type==="remote-outbound-rtp"){}logger.log(finalReport)}})}))}else{this.getRTCPeerConnection().getReceivers().forEach(receiver=>receiver.getStats().then(response=>{response.forEach(report=>{if(this.isReportWanted(report)){const finalReport={};finalReport["type"]=report.type;finalReport["timestamp"]=report.timestamp;finalReport["id"]=report.id;if(report.type==="inbound-rtp"){finalReport["ssrc"]=report.ssrc;finalReport["firCount"]=report.firCount;finalReport["pliCount"]=report.pliCount;finalReport["nackCount"]=report.nackCount;finalReport["qpSum"]=report.qpSum;if(!!report.kind){finalReport["mediaType"]=report.kind}else if(!!report.mediaType){finalReport["mediaType"]=report.mediaType}else{finalReport["mediaType"]=report.id.indexOf("VideoStream")!==-1?"video":"audio"}if(finalReport["mediaType"]==="video"){finalReport["framesDecoded"]=report.framesDecoded}finalReport["packetsReceived"]=report.packetsReceived;finalReport["packetsLost"]=report.packetsLost;finalReport["jitter"]=report.jitter;finalReport["bytesReceived"]=report.bytesReceived}if(report.type==="candidate-pair"&&report.totalRoundTripTime!==undefined){finalReport["availableIncomingBitrate"]=report.availableIncomingBitrate;finalReport["rtt"]=report.currentRoundTripTime;finalReport["averageRtt"]=report.totalRoundTripTime/report.responsesReceived}if(report.type==="remote-inbound-rtp"||report.type==="remote-outbound-rtp"){}logger.log(finalReport)}})}))}})}isReportWanted(report){return report.type==="inbound-rtp"&&!this.isLocal()||report.type==="outbound-rtp"&&this.isLocal()||report.type==="candidate-pair"&&report.nominated&&report.bytesSent>0}}exports.Stream=Stream},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/TypeOfVideo":54,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/PublisherSpeakingEvent":62,"../OpenViduInternal/Events/StreamManagerEvent":68,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"../OpenViduInternal/WebRtcPeer/WebRtcPeer":86,"../OpenViduInternal/WebRtcStats/WebRtcStats":87,"./Filter":44,"./Subscriber":51,hark:5,uuid:23,"wolfy87-eventemitter":39}],50:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamManager=void 0;const EventDispatcher_1=require("./EventDispatcher");const StreamManagerEvent_1=require("../OpenViduInternal/Events/StreamManagerEvent");const VideoElementEvent_1=require("../OpenViduInternal/Events/VideoElementEvent");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class StreamManager extends EventDispatcher_1.EventDispatcher{constructor(stream,targetElement){super();this.videos=[];this.lazyLaunchVideoElementCreatedEvent=false;platform=Platform_1.PlatformUtils.getInstance();this.stream=stream;this.stream.streamManager=this;this.remote=!this.stream.isLocal();if(!!targetElement){let targEl;if(typeof targetElement==="string"){targEl=document.getElementById(targetElement)}else if(targetElement instanceof HTMLElement){targEl=targetElement}if(!!targEl){this.firstVideoElement={targetElement:targEl,video:document.createElement("video"),id:"",canplayListenerAdded:false};if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){this.firstVideoElement.video.playsInline=true}this.targetElement=targEl;this.element=targEl}}this.canPlayListener=()=>{this.deactivateStreamPlayingEventExceptionTimeout();this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}on(type,handler){super.onAux(type,"Event '"+type+"' triggered by '"+(this.remote?"Subscriber":"Publisher")+"'",handler);if(type==="videoElementCreated"){if(!!this.stream&&this.lazyLaunchVideoElementCreatedEvent){this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(this.videos[0].video,this,"videoElementCreated")]);this.lazyLaunchVideoElementCreatedEvent=false}}if(type==="streamPlaying"){if(this.videos[0]&&this.videos[0].video&&this.videos[0].video.currentTime>0&&this.videos[0].video.paused===false&&this.videos[0].video.ended===false&&this.videos[0].video.readyState===4){this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}if(this.stream.hasAudio){if(type==="publisherStartSpeaking"){this.stream.enableHarkSpeakingEvent()}if(type==="publisherStopSpeaking"){this.stream.enableHarkStoppedSpeakingEvent()}if(type==="streamAudioVolumeChange"){this.stream.enableHarkVolumeChangeEvent(false)}}return this}once(type,handler){super.onceAux(type,"Event '"+type+"' triggered once by '"+(this.remote?"Subscriber":"Publisher")+"'",handler);if(type==="videoElementCreated"){if(!!this.stream&&this.lazyLaunchVideoElementCreatedEvent){this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(this.videos[0].video,this,"videoElementCreated")])}}if(type==="streamPlaying"){if(this.videos[0]&&this.videos[0].video&&this.videos[0].video.currentTime>0&&this.videos[0].video.paused===false&&this.videos[0].video.ended===false&&this.videos[0].video.readyState===4){this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}if(this.stream.hasAudio){if(type==="publisherStartSpeaking"){this.stream.enableOnceHarkSpeakingEvent()}if(type==="publisherStopSpeaking"){this.stream.enableOnceHarkStoppedSpeakingEvent()}if(type==="streamAudioVolumeChange"){this.stream.enableOnceHarkVolumeChangeEvent(false)}}return this}off(type,handler){super.offAux(type,handler);if(type==="publisherStartSpeaking"){const remainingStartSpeakingEventListeners=this.ee.getListeners(type).length+this.stream.session.ee.getListeners(type).length;if(remainingStartSpeakingEventListeners===0){this.stream.disableHarkSpeakingEvent(false)}}if(type==="publisherStopSpeaking"){const remainingStopSpeakingEventListeners=this.ee.getListeners(type).length+this.stream.session.ee.getListeners(type).length;if(remainingStopSpeakingEventListeners===0){this.stream.disableHarkStoppedSpeakingEvent(false)}}if(type==="streamAudioVolumeChange"){const remainingVolumeEventListeners=this.ee.getListeners(type).length;if(remainingVolumeEventListeners===0){this.stream.disableHarkVolumeChangeEvent(false)}}return this}addVideoElement(video){this.initializeVideoProperties(video);if(!this.remote&&this.stream.displayMyRemote()){if(video.srcObject!==this.stream.getMediaStream()){video.srcObject=this.stream.getMediaStream()}}for(const v of this.videos){if(v.video===video){return 0}}let returnNumber=1;for(const streamManager of this.stream.session.streamManagers){if(streamManager.disassociateVideo(video)){returnNumber=-1;break}}this.stream.session.streamManagers.forEach(streamManager=>{streamManager.disassociateVideo(video)});this.pushNewStreamManagerVideo({video:video,id:video.id,canplayListenerAdded:false});logger.info("New video element associated to ",this);return returnNumber}createVideoElement(targetElement,insertMode){let targEl;if(typeof targetElement==="string"){targEl=document.getElementById(targetElement);if(!targEl){throw new Error("The provided 'targetElement' couldn't be resolved to any HTML element: "+targetElement)}}else if(targetElement instanceof HTMLElement){targEl=targetElement}else{throw new Error("The provided 'targetElement' couldn't be resolved to any HTML element: "+targetElement)}const video=this.createVideo();this.initializeVideoProperties(video);let insMode=!!insertMode?insertMode:VideoInsertMode_1.VideoInsertMode.APPEND;switch(insMode){case VideoInsertMode_1.VideoInsertMode.AFTER:targEl.parentNode.insertBefore(video,targEl.nextSibling);break;case VideoInsertMode_1.VideoInsertMode.APPEND:targEl.appendChild(video);break;case VideoInsertMode_1.VideoInsertMode.BEFORE:targEl.parentNode.insertBefore(video,targEl);break;case VideoInsertMode_1.VideoInsertMode.PREPEND:targEl.insertBefore(video,targEl.childNodes[0]);break;case VideoInsertMode_1.VideoInsertMode.REPLACE:targEl.parentNode.replaceChild(video,targEl);break;default:insMode=VideoInsertMode_1.VideoInsertMode.APPEND;targEl.appendChild(video);break}const v={targetElement:targEl,video:video,insertMode:insMode,id:video.id,canplayListenerAdded:false};this.pushNewStreamManagerVideo(v);this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(v.video,this,"videoElementCreated")]);this.lazyLaunchVideoElementCreatedEvent=!!this.firstVideoElement;return video}updatePublisherSpeakingEventsOptions(publisherSpeakingEventsOptions){const currentHarkOptions=!!this.stream.harkOptions?this.stream.harkOptions:this.stream.session.openvidu.advancedConfiguration.publisherSpeakingEventsOptions||{};const newInterval=typeof publisherSpeakingEventsOptions.interval==="number"?publisherSpeakingEventsOptions.interval:typeof currentHarkOptions.interval==="number"?currentHarkOptions.interval:100;const newThreshold=typeof publisherSpeakingEventsOptions.threshold==="number"?publisherSpeakingEventsOptions.threshold:typeof currentHarkOptions.threshold==="number"?currentHarkOptions.threshold:-50;this.stream.harkOptions={interval:newInterval,threshold:newThreshold};if(!!this.stream.speechEvent){this.stream.speechEvent.setInterval(newInterval);this.stream.speechEvent.setThreshold(newThreshold)}}initializeVideoProperties(video){if(!(!this.remote&&this.stream.displayMyRemote())){if(video.srcObject!==this.stream.getMediaStream()){video.srcObject=this.stream.getMediaStream()}}video.autoplay=true;video.controls=false;if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){video.playsInline=true}if(!video.id){video.id=(this.remote?"remote-":"local-")+"video-"+this.stream.streamId;if(!this.id&&!!this.targetElement){this.id=video.id}}if(this.remote&&this.isMirroredVideo(video)){this.removeMirrorVideo(video)}else if(!this.remote&&!this.stream.displayMyRemote()){video.muted=true;if(this.isMirroredVideo(video)&&!this.stream.outboundStreamOpts.publisherProperties.mirror){this.removeMirrorVideo(video)}else if(this.stream.outboundStreamOpts.publisherProperties.mirror&&!this.stream.isSendScreen()){this.mirrorVideo(video)}}}removeAllVideos(){for(let i=this.stream.session.streamManagers.length-1;i>=0;--i){if(this.stream.session.streamManagers[i]===this){this.stream.session.streamManagers.splice(i,1)}}this.videos.forEach(streamManagerVideo=>{if(!!streamManagerVideo.video&&!!streamManagerVideo.video.removeEventListener){streamManagerVideo.video.removeEventListener("canplay",this.canPlayListener)}streamManagerVideo.canplayListenerAdded=false;if(!!streamManagerVideo.targetElement){streamManagerVideo.video.parentNode.removeChild(streamManagerVideo.video);this.ee.emitEvent("videoElementDestroyed",[new VideoElementEvent_1.VideoElementEvent(streamManagerVideo.video,this,"videoElementDestroyed")])}this.removeSrcObject(streamManagerVideo);this.videos=this.videos.filter(v=>!v.targetElement)})}disassociateVideo(video){let disassociated=false;for(let i=0;i<this.videos.length;i++){if(this.videos[i].video===video){this.videos[i].video.removeEventListener("canplay",this.canPlayListener);this.videos.splice(i,1);disassociated=true;logger.info("Video element disassociated from ",this);break}}return disassociated}addPlayEventToFirstVideo(){if(!!this.videos[0]&&!!this.videos[0].video&&!this.videos[0].canplayListenerAdded){this.activateStreamPlayingEventExceptionTimeout();this.videos[0].video.addEventListener("canplay",this.canPlayListener);this.videos[0].canplayListenerAdded=true}}updateMediaStream(mediaStream){this.videos.forEach(streamManagerVideo=>{streamManagerVideo.video.srcObject=mediaStream;if(platform.isIonicIos()){const vParent=streamManagerVideo.video.parentElement;const newVideo=streamManagerVideo.video;vParent.replaceChild(newVideo,streamManagerVideo.video);streamManagerVideo.video=newVideo}})}emitEvent(type,eventArray){this.ee.emitEvent(type,eventArray)}createVideo(){return document.createElement("video")}removeSrcObject(streamManagerVideo){streamManagerVideo.video.srcObject=null;this.deactivateStreamPlayingEventExceptionTimeout()}pushNewStreamManagerVideo(streamManagerVideo){this.videos.push(streamManagerVideo);this.addPlayEventToFirstVideo();if(this.stream.session.streamManagers.indexOf(this)===-1){this.stream.session.streamManagers.push(this)}}mirrorVideo(video){if(!platform.isIonicIos()){video.style.transform="rotateY(180deg)";video.style.webkitTransform="rotateY(180deg)"}}removeMirrorVideo(video){video.style.transform="unset";video.style.webkitTransform="unset"}isMirroredVideo(video){return video.style.transform==="rotateY(180deg)"||video.style.webkitTransform==="rotateY(180deg)"}activateStreamPlayingEventExceptionTimeout(){if(!this.remote){return}if(this.streamPlayingEventExceptionTimeout!=null){return}const msTimeout=this.stream.session.openvidu.advancedConfiguration.noStreamPlayingEventExceptionTimeout||4e3;this.streamPlayingEventExceptionTimeout=setTimeout(()=>{const msg="StreamManager of Stream "+this.stream.streamId+" ("+(this.remote?"Subscriber":"Publisher")+') did not trigger "streamPlaying" event in '+msTimeout+" ms";logger.warn(msg);this.stream.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.stream.session,ExceptionEvent_1.ExceptionEventName.NO_STREAM_PLAYING_EVENT,this,msg)]);delete this.streamPlayingEventExceptionTimeout},msTimeout)}deactivateStreamPlayingEventExceptionTimeout(){clearTimeout(this.streamPlayingEventExceptionTimeout);delete this.streamPlayingEventExceptionTimeout}}exports.StreamManager=StreamManager},{"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/StreamManagerEvent":68,"../OpenViduInternal/Events/VideoElementEvent":70,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./EventDispatcher":43}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Subscriber=void 0;const StreamManager_1=require("./StreamManager");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class Subscriber extends StreamManager_1.StreamManager{constructor(stream,targEl,properties){super(stream,targEl);this.element=this.targetElement;this.stream=stream;this.properties=properties}subscribeToAudio(value){this.stream.getMediaStream().getAudioTracks().forEach(track=>{track.enabled=value});this.stream.audioActive=value;logger.info("'Subscriber' has "+(value?"subscribed to":"unsubscribed from")+" its audio stream");return this}subscribeToVideo(value){this.stream.getMediaStream().getVideoTracks().forEach(track=>{track.enabled=value});this.stream.videoActive=value;logger.info("'Subscriber' has "+(value?"subscribed to":"unsubscribed from")+" its video stream");return this}replaceTrackInMediaStream(track,updateLastConstraints){const mediaStream=this.stream.getMediaStream();let removedTrack;if(track.kind==="video"){removedTrack=mediaStream.getVideoTracks()[0];if(updateLastConstraints){this.stream.lastVideoTrackConstraints=track.getConstraints()}}else{removedTrack=mediaStream.getAudioTracks()[0]}mediaStream.removeTrack(removedTrack);removedTrack.stop();mediaStream.addTrack(track)}}exports.Subscriber=Subscriber},{"../OpenViduInternal/Logger/OpenViduLogger":81,"./StreamManager":50}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LocalRecorderState=void 0;var LocalRecorderState;(function(LocalRecorderState){LocalRecorderState["READY"]="READY";LocalRecorderState["RECORDING"]="RECORDING";LocalRecorderState["PAUSED"]="PAUSED";LocalRecorderState["FINISHED"]="FINISHED"})(LocalRecorderState||(exports.LocalRecorderState=LocalRecorderState={}))},{}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OpenViduError=exports.OpenViduErrorName=void 0;var OpenViduErrorName;(function(OpenViduErrorName){OpenViduErrorName["BROWSER_NOT_SUPPORTED"]="BROWSER_NOT_SUPPORTED";OpenViduErrorName["DEVICE_ACCESS_DENIED"]="DEVICE_ACCESS_DENIED";OpenViduErrorName["DEVICE_ALREADY_IN_USE"]="DEVICE_ALREADY_IN_USE";OpenViduErrorName["SCREEN_CAPTURE_DENIED"]="SCREEN_CAPTURE_DENIED";OpenViduErrorName["SCREEN_SHARING_NOT_SUPPORTED"]="SCREEN_SHARING_NOT_SUPPORTED";OpenViduErrorName["SCREEN_EXTENSION_NOT_INSTALLED"]="SCREEN_EXTENSION_NOT_INSTALLED";OpenViduErrorName["SCREEN_EXTENSION_DISABLED"]="SCREEN_EXTENSION_DISABLED";OpenViduErrorName["INPUT_VIDEO_DEVICE_NOT_FOUND"]="INPUT_VIDEO_DEVICE_NOT_FOUND";OpenViduErrorName["INPUT_AUDIO_DEVICE_NOT_FOUND"]="INPUT_AUDIO_DEVICE_NOT_FOUND";OpenViduErrorName["INPUT_AUDIO_DEVICE_GENERIC_ERROR"]="INPUT_AUDIO_DEVICE_GENERIC_ERROR";OpenViduErrorName["NO_INPUT_SOURCE_SET"]="NO_INPUT_SOURCE_SET";OpenViduErrorName["PUBLISHER_PROPERTIES_ERROR"]="PUBLISHER_PROPERTIES_ERROR";OpenViduErrorName["OPENVIDU_PERMISSION_DENIED"]="OPENVIDU_PERMISSION_DENIED";OpenViduErrorName["OPENVIDU_NOT_CONNECTED"]="OPENVIDU_NOT_CONNECTED";OpenViduErrorName["VIRTUAL_BACKGROUND_ERROR"]="VIRTUAL_BACKGROUND_ERROR";OpenViduErrorName["GENERIC_ERROR"]="GENERIC_ERROR"})(OpenViduErrorName||(exports.OpenViduErrorName=OpenViduErrorName={}));class OpenViduError{constructor(name,message){this.name=name;this.message=message}}exports.OpenViduError=OpenViduError},{}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TypeOfVideo=void 0;var TypeOfVideo;(function(TypeOfVideo){TypeOfVideo["CAMERA"]="CAMERA";TypeOfVideo["SCREEN"]="SCREEN";TypeOfVideo["CUSTOM"]="CUSTOM";TypeOfVideo["IPCAM"]="IPCAM"})(TypeOfVideo||(exports.TypeOfVideo=TypeOfVideo={}))},{}],55:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VideoInsertMode=void 0;var VideoInsertMode;(function(VideoInsertMode){VideoInsertMode["AFTER"]="AFTER";VideoInsertMode["APPEND"]="APPEND";VideoInsertMode["BEFORE"]="BEFORE";VideoInsertMode["PREPEND"]="PREPEND";VideoInsertMode["REPLACE"]="REPLACE"})(VideoInsertMode||(exports.VideoInsertMode=VideoInsertMode={}))},{}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConnectionEvent=void 0;const Event_1=require("./Event");class ConnectionEvent extends Event_1.Event{constructor(cancelable,target,type,connection,reason){super(cancelable,target,type);this.connection=connection;this.reason=reason}callDefaultBehavior(){}}exports.ConnectionEvent=ConnectionEvent},{"./Event":58}],57:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConnectionPropertyChangedEvent=void 0;const Event_1=require("./Event");class ConnectionPropertyChangedEvent extends Event_1.Event{constructor(target,connection,changedProperty,newValue,oldValue){super(false,target,"connectionPropertyChanged");this.connection=connection;this.changedProperty=changedProperty;this.newValue=newValue;this.oldValue=oldValue}callDefaultBehavior(){}}exports.ConnectionPropertyChangedEvent=ConnectionPropertyChangedEvent},{"./Event":58}],58:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Event=void 0;class Event{constructor(cancelable,target,type){this.hasBeenPrevented=false;this.cancelable=cancelable;this.target=target;this.type=type}isDefaultPrevented(){return this.hasBeenPrevented}preventDefault(){this.callDefaultBehavior=()=>{};this.hasBeenPrevented=true}}exports.Event=Event},{}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExceptionEvent=exports.ExceptionEventName=void 0;const Event_1=require("./Event");var ExceptionEventName;(function(ExceptionEventName){ExceptionEventName["ICE_CANDIDATE_ERROR"]="ICE_CANDIDATE_ERROR";ExceptionEventName["ICE_CONNECTION_FAILED"]="ICE_CONNECTION_FAILED";ExceptionEventName["ICE_CONNECTION_DISCONNECTED"]="ICE_CONNECTION_DISCONNECTED";ExceptionEventName["NO_STREAM_PLAYING_EVENT"]="NO_STREAM_PLAYING_EVENT";ExceptionEventName["SPEECH_TO_TEXT_DISCONNECTED"]="SPEECH_TO_TEXT_DISCONNECTED"})(ExceptionEventName||(exports.ExceptionEventName=ExceptionEventName={}));class ExceptionEvent extends Event_1.Event{constructor(session,name,origin,message,data){super(false,session,"exception");this.name=name;this.origin=origin;this.message=message;this.data=data}callDefaultBehavior(){}}exports.ExceptionEvent=ExceptionEvent},{"./Event":58}],60:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FilterEvent=void 0;const Event_1=require("./Event");class FilterEvent extends Event_1.Event{constructor(target,eventType,data){super(false,target,eventType);this.data=data}callDefaultBehavior(){}}exports.FilterEvent=FilterEvent},{"./Event":58}],61:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NetworkQualityLevelChangedEvent=void 0;const Event_1=require("./Event");class NetworkQualityLevelChangedEvent extends Event_1.Event{constructor(target,newValue,oldValue,connection){super(false,target,"networkQualityLevelChanged");this.newValue=newValue;this.oldValue=oldValue;this.connection=connection}callDefaultBehavior(){}}exports.NetworkQualityLevelChangedEvent=NetworkQualityLevelChangedEvent},{"./Event":58}],62:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PublisherSpeakingEvent=void 0;const Event_1=require("./Event");class PublisherSpeakingEvent extends Event_1.Event{constructor(target,type,connection,streamId){super(false,target,type);this.type=type;this.connection=connection;this.streamId=streamId}callDefaultBehavior(){}}exports.PublisherSpeakingEvent=PublisherSpeakingEvent},{"./Event":58}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RecordingEvent=void 0;const Event_1=require("./Event");class RecordingEvent extends Event_1.Event{constructor(target,type,id,name,reason){super(false,target,type);this.id=id;if(name!==id){this.name=name}this.reason=reason}callDefaultBehavior(){}}exports.RecordingEvent=RecordingEvent},{"./Event":58}],64:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SessionDisconnectedEvent=void 0;const Event_1=require("./Event");const OpenViduLogger_1=require("../Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class SessionDisconnectedEvent extends Event_1.Event{constructor(target,reason){super(true,target,"sessionDisconnected");this.reason=reason}callDefaultBehavior(){logger.info("Calling default behavior upon '"+this.type+"' event dispatched by 'Session'");const session=this.target;session.remoteConnections.forEach(remoteConnection=>{var _a,_b,_c,_d,_e,_f,_g,_h;const connectionId=remoteConnection.connectionId;if(!!((_a=session.remoteConnections.get(connectionId))===null||_a===void 0?void 0:_a.stream)){(_b=session.remoteConnections.get(connectionId))===null||_b===void 0?void 0:_b.stream.disposeWebRtcPeer();(_c=session.remoteConnections.get(connectionId))===null||_c===void 0?void 0:_c.stream.disposeMediaStream();if((_d=session.remoteConnections.get(connectionId))===null||_d===void 0?void 0:_d.stream.streamManager){(_e=session.remoteConnections.get(connectionId))===null||_e===void 0?void 0:_e.stream.streamManager.removeAllVideos()}const streamId=(_g=(_f=session.remoteConnections.get(connectionId))===null||_f===void 0?void 0:_f.stream)===null||_g===void 0?void 0:_g.streamId;if(!!streamId){session.remoteStreamsCreated.delete(streamId)}(_h=session.remoteConnections.get(connectionId))===null||_h===void 0?void 0:_h.dispose()}session.remoteConnections.delete(connectionId)})}}exports.SessionDisconnectedEvent=SessionDisconnectedEvent},{"../Logger/OpenViduLogger":81,"./Event":58}],65:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SignalEvent=void 0;const Event_1=require("./Event");class SignalEvent extends Event_1.Event{constructor(target,type,data,from){super(false,target,"signal");if(!!type){this.type="signal:"+type}this.data=data;this.from=from}callDefaultBehavior(){}}exports.SignalEvent=SignalEvent},{"./Event":58}],66:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SpeechToTextEvent=void 0;const Event_1=require("./Event");class SpeechToTextEvent extends Event_1.Event{constructor(target,connection,text,reason,raw,lang){super(false,target,"speechToTextMessage");this.connection=connection;this.text=text;this.reason=reason;this.raw=raw;this.lang=lang}callDefaultBehavior(){}}exports.SpeechToTextEvent=SpeechToTextEvent},{"./Event":58}],67:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamEvent=void 0;const Event_1=require("./Event");const Publisher_1=require("../../OpenVidu/Publisher");const Session_1=require("../../OpenVidu/Session");const OpenViduLogger_1=require("../Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class StreamEvent extends Event_1.Event{constructor(cancelable,target,type,stream,reason){super(cancelable,target,type);this.stream=stream;this.reason=reason}callDefaultBehavior(){if(this.type==="streamDestroyed"){if(this.target instanceof Session_1.Session){logger.info("Calling default behavior upon '"+this.type+"' event dispatched by 'Session'");this.stream.disposeWebRtcPeer()}else if(this.target instanceof Publisher_1.Publisher){logger.info("Calling default behavior upon '"+this.type+"' event dispatched by 'Publisher'");clearInterval(this.target.screenShareResizeInterval);this.stream.isLocalStreamReadyToPublish=false;const openviduPublishers=this.target.openvidu.publishers;for(let i=0;i<openviduPublishers.length;i++){if(openviduPublishers[i]===this.target){openviduPublishers.splice(i,1);break}}}this.stream.disposeMediaStream();if(this.stream.streamManager)this.stream.streamManager.removeAllVideos();this.stream.session.remoteStreamsCreated.delete(this.stream.streamId);const remoteConnection=this.stream.session.remoteConnections.get(this.stream.connection.connectionId);if(!!remoteConnection&&!!remoteConnection.remoteOptions){const streamOptionsServer=remoteConnection.remoteOptions.streams;for(let i=streamOptionsServer.length-1;i>=0;--i){if(streamOptionsServer[i].id===this.stream.streamId){streamOptionsServer.splice(i,1)}}}}}}exports.StreamEvent=StreamEvent},{"../../OpenVidu/Publisher":47,"../../OpenVidu/Session":48,"../Logger/OpenViduLogger":81,"./Event":58}],68:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamManagerEvent=void 0;const Event_1=require("./Event");class StreamManagerEvent extends Event_1.Event{constructor(target,type,value){super(false,target,type);this.value=value}callDefaultBehavior(){}}exports.StreamManagerEvent=StreamManagerEvent},{"./Event":58}],69:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamPropertyChangedEvent=void 0;const Event_1=require("./Event");class StreamPropertyChangedEvent extends Event_1.Event{constructor(target,stream,changedProperty,newValue,oldValue,reason){super(false,target,"streamPropertyChanged");this.stream=stream;this.changedProperty=changedProperty;this.newValue=newValue;this.oldValue=oldValue;this.reason=reason}callDefaultBehavior(){}}exports.StreamPropertyChangedEvent=StreamPropertyChangedEvent},{"./Event":58}],70:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VideoElementEvent=void 0;const Event_1=require("./Event");class VideoElementEvent extends Event_1.Event{constructor(element,target,type){super(false,target,type);this.element=element}callDefaultBehavior(){}}exports.VideoElementEvent=VideoElementEvent},{"./Event":58}],71:[function(require,module,exports){function Mapper(){var sources={};this.forEach=function(callback){for(var key in sources){var source=sources[key];for(var key2 in source)callback(source[key2])}};this.get=function(id,source){var ids=sources[source];if(ids==undefined)return undefined;return ids[id]};this.remove=function(id,source){var ids=sources[source];if(ids==undefined)return;delete ids[id];for(var i in ids){return false}delete sources[source]};this.set=function(value,id,source){if(value==undefined)return this.remove(id,source);var ids=sources[source];if(ids==undefined)sources[source]=ids={};ids[id]=value}}Mapper.prototype.pop=function(id,source){var value=this.get(id,source);if(value==undefined)return undefined;this.remove(id,source);return value};module.exports=Mapper},{}],72:[function(require,module,exports){var JsonRpcClient=require("./jsonrpcclient");exports.JsonRpcClient=JsonRpcClient},{"./jsonrpcclient":73}],73:[function(require,module,exports){var RpcBuilder=require("../");var WebSocketWithReconnection=require("./transports/webSocketWithReconnection");var OpenViduLogger=require("../../../Logger/OpenViduLogger").OpenViduLogger;Date.now=Date.now||function(){return+new Date};var PING_INTERVAL=5e3;var RECONNECTING="RECONNECTING";var CONNECTED="CONNECTED";var DISCONNECTED="DISCONNECTED";var Logger=OpenViduLogger.getInstance();function JsonRpcClient(configuration){var self=this;var wsConfig=configuration.ws;var notReconnectIfNumLessThan=-1;var pingNextNum=0;var enabledPings=true;var pingPongStarted=false;var pingInterval;var status=DISCONNECTED;var onreconnecting=wsConfig.onreconnecting;var onreconnected=wsConfig.onreconnected;var onconnected=wsConfig.onconnected;var onerror=wsConfig.onerror;configuration.rpc.pull=function(params,request){request.reply(null,"push")};wsConfig.onreconnecting=function(){Logger.debug("--------- ONRECONNECTING -----------");if(status===RECONNECTING){Logger.error("Websocket already in RECONNECTING state when receiving a new ONRECONNECTING message. Ignoring it");return}stopPing();status=RECONNECTING;if(onreconnecting){onreconnecting()}};wsConfig.onreconnected=function(){Logger.debug("--------- ONRECONNECTED -----------");if(status===CONNECTED){Logger.error("Websocket already in CONNECTED state when receiving a new ONRECONNECTED message. Ignoring it");return}status=CONNECTED;updateNotReconnectIfLessThan();if(onreconnected){onreconnected()}};wsConfig.onconnected=function(){Logger.debug("--------- ONCONNECTED -----------");if(status===CONNECTED){Logger.error("Websocket already in CONNECTED state when receiving a new ONCONNECTED message. Ignoring it");return}status=CONNECTED;enabledPings=true;usePing();if(onconnected){onconnected()}};wsConfig.onerror=function(error){Logger.debug("--------- ONERROR -----------");status=DISCONNECTED;stopPing();if(onerror){onerror(error)}};var ws=new WebSocketWithReconnection(wsConfig);Logger.debug("Connecting websocket to URI: "+wsConfig.uri);var rpcBuilderOptions={request_timeout:configuration.rpc.requestTimeout,ping_request_timeout:configuration.rpc.heartbeatRequestTimeout};var rpc=new RpcBuilder(RpcBuilder.packers.JsonRPC,rpcBuilderOptions,ws,function(request){Logger.debug("Received request: "+JSON.stringify(request));try{var func=configuration.rpc[request.method];if(func===undefined){Logger.error("Method "+request.method+" not registered in client")}else{func(request.params,request)}}catch(err){Logger.error("Exception processing request: "+JSON.stringify(request));Logger.error(err)}});this.send=function(method,params,callback){var requestTime=Date.now();rpc.encode(method,params,function(error,result){if(error){try{Logger.error("ERROR:"+error.message+" in Request: method:"+method+" params:"+JSON.stringify(params)+" request:"+error.request);if(error.data){Logger.error("ERROR DATA:"+JSON.stringify(error.data))}}catch(e){}error.requestTime=requestTime}if(callback){if(result!=undefined&&result.value!=="pong"){Logger.debug("Response: "+JSON.stringify(result))}callback(error,result)}})};function updateNotReconnectIfLessThan(){Logger.debug("notReconnectIfNumLessThan = "+pingNextNum+" (old="+notReconnectIfNumLessThan+")");notReconnectIfNumLessThan=pingNextNum}function sendPing(){if(enabledPings){var params=null;if(pingNextNum==0||pingNextNum==notReconnectIfNumLessThan){params={interval:configuration.heartbeat||PING_INTERVAL}}pingNextNum++;self.send("ping",params,function(pingNum){return function(error,result){if(error){Logger.debug("Error in ping request #"+pingNum+" ("+error.message+")");if(pingNum>notReconnectIfNumLessThan){enabledPings=false;updateNotReconnectIfLessThan();Logger.debug("Server did not respond to ping message #"+pingNum+". Reconnecting... ");ws.reconnectWs()}}}}(pingNextNum))}else{Logger.debug("Trying to send ping, but ping is not enabled")}}function usePing(){if(!pingPongStarted){Logger.debug("Starting ping (if configured)");pingPongStarted=true;if(configuration.heartbeat!=undefined){pingInterval=setInterval(sendPing,configuration.heartbeat);sendPing()}}}function stopPing(){clearInterval(pingInterval);pingPongStarted=false;enabledPings=false;pingNextNum=-1;rpc.cancel()}this.close=function(code,reason){Logger.debug("Closing with code: "+code+" because: "+reason);if(pingInterval!=undefined){Logger.debug("Clearing ping interval");clearInterval(pingInterval)}pingPongStarted=false;enabledPings=false;ws.close(code,reason)};this.reconnect=function(){ws.reconnectWs()};this.resetPing=function(){enabledPings=true;pingNextNum=0;usePing()};this.getReadyState=function(){return ws.getReadyState()}}module.exports=JsonRpcClient},{"../":76,"../../../Logger/OpenViduLogger":81,"./transports/webSocketWithReconnection":75}],74:[function(require,module,exports){var WebSocketWithReconnection=require("./webSocketWithReconnection");exports.WebSocketWithReconnection=WebSocketWithReconnection},{"./webSocketWithReconnection":75}],75:[function(require,module,exports){"use strict";var OpenViduLogger=require("../../../../Logger/OpenViduLogger").OpenViduLogger;var Logger=OpenViduLogger.getInstance();var MAX_RETRIES=2e3;var RETRY_TIME_MS=3e3;var CONNECTING=0;var OPEN=1;var CLOSING=2;var CLOSED=3;function WebSocketWithReconnection(config){var closing=false;var registerMessageHandler;var wsUri=config.uri;var reconnecting=false;var ws=new WebSocket(wsUri);ws.onopen=()=>{Logger.debug("WebSocket connected to "+wsUri);if(config.onconnected){config.onconnected()}};ws.onerror=error=>{Logger.error("Could not connect to "+wsUri+" (invoking onerror if defined)",error);if(config.onerror){config.onerror(error)}};var reconnectionOnClose=()=>{if(ws.readyState===CLOSED){if(closing){Logger.debug("Connection closed by user")}else{if(config.ismasternodecrashed()){Logger.error("Master Node has crashed. Stopping reconnection process")}else{Logger.debug("Connection closed unexpectedly. Reconnecting...");reconnect(MAX_RETRIES,1)}}}else{Logger.debug("Close callback from previous websocket. Ignoring it")}};ws.onclose=reconnectionOnClose;function reconnect(maxRetries,numRetries){Logger.debug("reconnect (attempt #"+numRetries+", max="+maxRetries+")");if(numRetries===1){if(reconnecting){Logger.warn("Trying to reconnect when already reconnecting... Ignoring this reconnection.");return}else{reconnecting=true}if(config.onreconnecting){config.onreconnecting()}}reconnectAux(maxRetries,numRetries)}function addReconnectionQueryParamsIfMissing(uriString){var searchParams=new URLSearchParams(new URL(uriString).search);if(!searchParams.has("reconnect")){uriString=Array.from(searchParams).length>0?uriString+"&reconnect=true":uriString+"?reconnect=true"}return uriString}function reconnectAux(maxRetries,numRetries){Logger.debug("Reconnection attempt #"+numRetries);ws.close(4104,"Connection closed for reconnection");wsUri=addReconnectionQueryParamsIfMissing(wsUri);ws=new WebSocket(wsUri);ws.onopen=()=>{Logger.debug("Reconnected to "+wsUri+" after "+numRetries+" attempts...");reconnecting=false;registerMessageHandler();if(config.onreconnected){config.onreconnected()}ws.onclose=reconnectionOnClose};ws.onerror=error=>{Logger.warn("Reconnection error: ",error);if(numRetries===maxRetries){if(config.ondisconnect){config.ondisconnect()}}else{setTimeout(()=>{reconnect(maxRetries,numRetries+1)},RETRY_TIME_MS)}}}this.close=(code,reason)=>{closing=true;ws.close(code,reason)};this.reconnectWs=()=>{Logger.debug("reconnectWs");reconnect(MAX_RETRIES,1)};this.send=message=>{ws.send(message)};this.addEventListener=(type,callback)=>{registerMessageHandler=()=>{ws.addEventListener(type,callback)};registerMessageHandler()};this.getReadyState=()=>ws.readyState}module.exports=WebSocketWithReconnection},{"../../../../Logger/OpenViduLogger":81}],76:[function(require,module,exports){var defineProperty_IE8=false;if(Object.defineProperty){try{Object.defineProperty({},"x",{})}catch(e){defineProperty_IE8=true}}if(!Function.prototype.bind){Function.prototype.bind=function(oThis){if(typeof this!=="function"){throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable")}var aArgs=Array.prototype.slice.call(arguments,1),fToBind=this,fNOP=function(){},fBound=function(){return fToBind.apply(this instanceof fNOP&&oThis?this:oThis,aArgs.concat(Array.prototype.slice.call(arguments)))};fNOP.prototype=this.prototype;fBound.prototype=new fNOP;return fBound}}var EventEmitter=require("events").EventEmitter;var inherits=require("inherits");var packers=require("./packers");var Mapper=require("./Mapper");var BASE_TIMEOUT=5e3;function unifyResponseMethods(responseMethods){if(!responseMethods)return{};for(var key in responseMethods){var value=responseMethods[key];if(typeof value=="string")responseMethods[key]={response:value}}return responseMethods}function unifyTransport(transport){if(!transport)return;if(transport instanceof Function)return{send:transport};if(transport.send instanceof Function)return transport;if(transport.postMessage instanceof Function){transport.send=transport.postMessage;return transport}if(transport.write instanceof Function){transport.send=transport.write;return transport}if(transport.onmessage!==undefined)return;if(transport.pause instanceof Function)return;throw new SyntaxError("Transport is not a function nor a valid object")}function RpcNotification(method,params){if(defineProperty_IE8){this.method=method;this.params=params}else{Object.defineProperty(this,"method",{value:method,enumerable:true});Object.defineProperty(this,"params",{value:params,enumerable:true})}}function RpcBuilder(packer,options,transport,onRequest){var self=this;if(!packer)throw new SyntaxError("Packer is not defined");if(!packer.pack||!packer.unpack)throw new SyntaxError("Packer is invalid");var responseMethods=unifyResponseMethods(packer.responseMethods);if(options instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after onRequest");onRequest=options;transport=undefined;options=undefined}if(options&&options.send instanceof Function){if(transport&&!(transport instanceof Function))throw new SyntaxError("Only a function can be after transport");onRequest=transport;transport=options;options=undefined}if(transport instanceof Function){if(onRequest!=undefined)throw new SyntaxError("There can't be parameters after onRequest");onRequest=transport;transport=undefined}if(transport&&transport.send instanceof Function)if(onRequest&&!(onRequest instanceof Function))throw new SyntaxError("Only a function can be after transport");options=options||{};EventEmitter.call(this);if(onRequest)this.on("request",onRequest);if(defineProperty_IE8)this.peerID=options.peerID;else Object.defineProperty(this,"peerID",{value:options.peerID});var max_retries=options.max_retries||0;function transportMessage(event){self.decode(event.data||event)}this.getTransport=function(){return transport};this.setTransport=function(value){if(transport){if(transport.removeEventListener)transport.removeEventListener("message",transportMessage);else if(transport.removeListener)transport.removeListener("data",transportMessage)}if(value){if(value.addEventListener)value.addEventListener("message",transportMessage);else if(value.addListener)value.addListener("data",transportMessage)}transport=unifyTransport(value)};if(!defineProperty_IE8)Object.defineProperty(this,"transport",{get:this.getTransport.bind(this),set:this.setTransport.bind(this)});this.setTransport(transport);var request_timeout=options.request_timeout||BASE_TIMEOUT;var ping_request_timeout=options.ping_request_timeout||request_timeout;var response_timeout=options.response_timeout||BASE_TIMEOUT;var duplicates_timeout=options.duplicates_timeout||BASE_TIMEOUT;var requestID=0;var requests=new Mapper;var responses=new Mapper;var processedResponses=new Mapper;var message2Key={};function storeResponse(message,id,dest){var response={message:message,timeout:setTimeout(function(){responses.remove(id,dest)},response_timeout)};responses.set(response,id,dest)}function storeProcessedResponse(ack,from){var timeout=setTimeout(function(){processedResponses.remove(ack,from)},duplicates_timeout);processedResponses.set(timeout,ack,from)}function RpcRequest(method,params,id,from,transport){RpcNotification.call(this,method,params);this.getTransport=function(){return transport};this.setTransport=function(value){transport=unifyTransport(value)};if(!defineProperty_IE8)Object.defineProperty(this,"transport",{get:this.getTransport.bind(this),set:this.setTransport.bind(this)});var response=responses.get(id,from);if(!(transport||self.getTransport())){if(defineProperty_IE8)this.duplicated=Boolean(response);else Object.defineProperty(this,"duplicated",{value:Boolean(response)})}var responseMethod=responseMethods[method];this.pack=packer.pack.bind(packer,this,id);this.reply=function(error,result,transport){if(error instanceof Function||error&&error.send instanceof Function){if(result!=undefined)throw new SyntaxError("There can't be parameters after callback");transport=error;result=null;error=undefined}else if(result instanceof Function||result&&result.send instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after callback");transport=result;result=null}transport=unifyTransport(transport);if(response)clearTimeout(response.timeout);if(from!=undefined){if(error)error.dest=from;if(result)result.dest=from}var message;if(error||result!=undefined){if(self.peerID!=undefined){if(error)error.from=self.peerID;else result.from=self.peerID}if(responseMethod){if(responseMethod.error==undefined&&error)message={error:error};else{var method=error?responseMethod.error:responseMethod.response;message={method:method,params:error||result}}}else message={error:error,result:result};message=packer.pack(message,id)}else if(response)message=response.message;else message=packer.pack({result:null},id);storeResponse(message,id,from);transport=transport||this.getTransport()||self.getTransport();if(transport)return transport.send(message);return message}}inherits(RpcRequest,RpcNotification);function cancel(message){var key=message2Key[message];if(!key)return;delete message2Key[message];var request=requests.pop(key.id,key.dest);if(!request)return;clearTimeout(request.timeout);storeProcessedResponse(key.id,key.dest)}this.cancel=function(message){if(message)return cancel(message);for(var message in message2Key)cancel(message)};this.close=function(){var transport=this.getTransport();if(transport&&transport.close)transport.close(4003,"Cancel request");this.cancel();processedResponses.forEach(clearTimeout);responses.forEach(function(response){clearTimeout(response.timeout)})};this.encode=function(method,params,dest,transport,callback){if(params instanceof Function){if(dest!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=params;transport=undefined;dest=undefined;params=undefined}else if(dest instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=dest;transport=undefined;dest=undefined}else if(transport instanceof Function){if(callback!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=transport;transport=undefined}if(self.peerID!=undefined){params=params||{};params.from=self.peerID}if(dest!=undefined){params=params||{};params.dest=dest}var message={method:method,params:params};if(callback){var id=requestID++;var retried=0;message=packer.pack(message,id);function dispatchCallback(error,result){self.cancel(message);callback(error,result)}var request={message:message,callback:dispatchCallback,responseMethods:responseMethods[method]||{}};var encode_transport=unifyTransport(transport);function sendRequest(transport){var rt=method==="ping"?ping_request_timeout:request_timeout;request.timeout=setTimeout(timeout,rt*Math.pow(2,retried++));message2Key[message]={id:id,dest:dest};requests.set(request,id,dest);transport=transport||encode_transport||self.getTransport();if(transport)return transport.send(message);return message}function retry(transport){transport=unifyTransport(transport);console.warn(retried+" retry for request message:",message);var timeout=processedResponses.pop(id,dest);clearTimeout(timeout);return sendRequest(transport)}function timeout(){if(retried<max_retries)return retry(transport);var error=new Error("Request has timed out");error.request=message;error.retry=retry;dispatchCallback(error)}return sendRequest(transport)}message=packer.pack(message);transport=transport||this.getTransport();if(transport)return transport.send(message);return message};this.decode=function(message,transport){if(!message)throw new TypeError("Message is not defined");try{message=packer.unpack(message)}catch(e){return console.debug(e,message)}var id=message.id;var ack=message.ack;var method=message.method;var params=message.params||{};var from=params.from;var dest=params.dest;if(self.peerID!=undefined&&from==self.peerID)return;if(id==undefined&&ack==undefined){var notification=new RpcNotification(method,params);if(self.emit("request",notification))return;return notification}function processRequest(){transport=unifyTransport(transport)||self.getTransport();if(transport){var response=responses.get(id,from);if(response)return transport.send(response.message)}var idAck=id!=undefined?id:ack;var request=new RpcRequest(method,params,idAck,from,transport);if(self.emit("request",request))return;return request}function processResponse(request,error,result){request.callback(error,result)}function duplicatedResponse(timeout){console.warn("Response already processed",message);clearTimeout(timeout);storeProcessedResponse(ack,from)}if(method){if(dest==undefined||dest==self.peerID){var request=requests.get(ack,from);if(request){var responseMethods=request.responseMethods;if(method==responseMethods.error)return processResponse(request,params);if(method==responseMethods.response)return processResponse(request,null,params);return processRequest()}var processed=processedResponses.get(ack,from);if(processed)return duplicatedResponse(processed)}return processRequest()}var error=message.error;var result=message.result;if(error&&error.dest&&error.dest!=self.peerID)return;if(result&&result.dest&&result.dest!=self.peerID)return;var request=requests.get(ack,from);if(!request){var processed=processedResponses.get(ack,from);if(processed)return duplicatedResponse(processed);return console.warn("No callback was defined for this message",message)}processResponse(request,error,result)}}inherits(RpcBuilder,EventEmitter);RpcBuilder.RpcNotification=RpcNotification;module.exports=RpcBuilder;var clients=require("./clients");var transports=require("./clients/transports");RpcBuilder.clients=clients;RpcBuilder.clients.transports=transports;RpcBuilder.packers=packers},{"./Mapper":71,"./clients":72,"./clients/transports":74,"./packers":79,events:1,inherits:6}],77:[function(require,module,exports){function pack(message,id){var result={jsonrpc:"2.0"};if(message.method){result.method=message.method;if(message.params)result.params=message.params;if(id!=undefined)result.id=id}else if(id!=undefined){if(message.error){if(message.result!==undefined)throw new TypeError("Both result and error are defined");result.error=message.error}else if(message.result!==undefined)result.result=message.result;else throw new TypeError("No result or error is defined");result.id=id}return JSON.stringify(result)}function unpack(message){var result=message;if(typeof message==="string"||message instanceof String){result=JSON.parse(message)}var version=result.jsonrpc;if(version!=="2.0")throw new TypeError("Invalid JsonRPC version '"+version+"': "+message);if(result.method==undefined){if(result.id==undefined)throw new TypeError("Invalid message: "+message);var result_defined=result.result!==undefined;var error_defined=result.error!==undefined;if(result_defined&&error_defined)throw new TypeError("Both result and error are defined: "+message);if(!result_defined&&!error_defined)throw new TypeError("No result or error is defined: "+message);result.ack=result.id;delete result.id}return result}exports.pack=pack;exports.unpack=unpack},{}],78:[function(require,module,exports){function pack(message){throw new TypeError("Not yet implemented")}function unpack(message){throw new TypeError("Not yet implemented")}exports.pack=pack;exports.unpack=unpack},{}],79:[function(require,module,exports){var JsonRPC=require("./JsonRPC");var XmlRPC=require("./XmlRPC");exports.JsonRPC=JsonRPC;exports.XmlRPC=XmlRPC},{"./JsonRPC":77,"./XmlRPC":78}],80:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=void 0;class ConsoleLogger{constructor(console){this.logger=console;this.log=console.log,this.info=console.info,this.debug=console.debug,this.warn=console.warn,this.error=console.error}}exports.ConsoleLogger=ConsoleLogger},{}],81:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OpenViduLogger=void 0;const jsnlog_1=require("jsnlog");const ConsoleLogger_1=require("./ConsoleLogger");const OpenViduLoggerConfiguration_1=require("./OpenViduLoggerConfiguration");class OpenViduLogger{constructor(){this.JSNLOG_URL="/openvidu/elk/openvidu-browser-logs";this.MAX_JSNLOG_BATCH_LOG_MESSAGES=100;this.MAX_MSECONDS_BATCH_MESSAGES=5e3;this.MAX_LENGTH_STRING_JSON=1e3;this.defaultConsoleLogger=new ConsoleLogger_1.ConsoleLogger(globalThis.console);this.isProdMode=false;this.isJSNLogSetup=false}static configureJSNLog(openVidu,token){try{if(globalThis["LOG_JSNLOG_RESULTS"]||this.instance&&openVidu.isAtLeastPro&&this.instance.isOpenViduBrowserLogsDebugActive(openVidu)&&this.instance.canConfigureJSNLog(openVidu,this.instance)){if(openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug_app){this.instance.replaceWindowConsole()}this.instance.isJSNLogSetup=false;this.instance.info("Configuring JSNLogs.");const finalUserId=openVidu.finalUserId;const sessionId=openVidu.session.sessionId;const beforeSendCallback=xhr=>{const parentReadyStateFunction=xhr.onreadystatechange;xhr.onreadystatechange=()=>{if(this.isInvalidResponse(xhr)){Object.defineProperty(xhr,"readyState",{value:4});Object.defineProperty(xhr,"status",{value:200});this.instance.disableLogger()}parentReadyStateFunction()};xhr.setRequestHeader("Authorization","Basic "+btoa(`${finalUserId}%/%${sessionId}`+":"+token));xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("OV-Final-User-Id",finalUserId);xhr.setRequestHeader("OV-Session-Id",sessionId);xhr.setRequestHeader("OV-Token",token)};this.instance.currentAppender=jsnlog_1.JL.createAjaxAppender(`appender-${finalUserId}-${sessionId}`);this.instance.currentAppender.setOptions({beforeSend:beforeSendCallback,maxBatchSize:1e3,batchSize:this.instance.MAX_JSNLOG_BATCH_LOG_MESSAGES,batchTimeout:this.instance.MAX_MSECONDS_BATCH_MESSAGES});const logSerializer=obj=>{const getCircularReplacer=()=>{const seen=new WeakSet;return(key,value)=>{if(typeof value==="object"&&value!=null){if(seen.has(value)||globalThis.HTMLElement&&value instanceof HTMLElement){return}seen.add(value)}return value}};let stringifyJson=JSON.stringify(obj,getCircularReplacer());if(stringifyJson.length>this.instance.MAX_LENGTH_STRING_JSON){stringifyJson=`${stringifyJson.substring(0,this.instance.MAX_LENGTH_STRING_JSON)}...`}if(globalThis["LOG_JSNLOG_RESULTS"]){console.log(stringifyJson)}return stringifyJson};jsnlog_1.JL.setOptions({defaultAjaxUrl:openVidu.httpUri+this.instance.JSNLOG_URL,serialize:logSerializer,enabled:true});(0,jsnlog_1.JL)().setOptions({appenders:[this.instance.currentAppender]});this.instance.isJSNLogSetup=true;this.instance.loggingSessionId=sessionId;this.instance.info("JSNLog configured.")}}catch(e){console.error("Error configuring JSNLog: ");console.error(e);this.instance.disableLogger()}}static getInstance(){if(!OpenViduLogger.instance){OpenViduLogger.instance=new OpenViduLogger}return OpenViduLogger.instance}static isInvalidResponse(xhr){return xhr.status==401||xhr.status==403||xhr.status==404||xhr.status==0}canConfigureJSNLog(openVidu,logger){return openVidu.session.sessionId!=logger.loggingSessionId}isOpenViduBrowserLogsDebugActive(openVidu){return openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug||openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug_app}getConsoleWithJSNLog(){return function(openViduLogger){return{log:function(...args){openViduLogger.defaultConsoleLogger.log.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}},info:function(...args){openViduLogger.defaultConsoleLogger.info.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}},debug:function(...args){openViduLogger.defaultConsoleLogger.debug.apply(openViduLogger.defaultConsoleLogger.logger,arguments)},warn:function(...args){openViduLogger.defaultConsoleLogger.warn.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().warn(arguments)}},error:function(...args){openViduLogger.defaultConsoleLogger.error.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().error(arguments)}}}}(this)}replaceWindowConsole(){globalThis.console=this.defaultConsoleLogger.logger;globalThis.console.log=this.getConsoleWithJSNLog().log;globalThis.console.info=this.getConsoleWithJSNLog().info;globalThis.console.debug=this.getConsoleWithJSNLog().debug;globalThis.console.warn=this.getConsoleWithJSNLog().warn;globalThis.console.error=this.getConsoleWithJSNLog().error}disableLogger(){jsnlog_1.JL.setOptions({enabled:false});this.isJSNLogSetup=false;this.loggingSessionId=undefined;this.currentAppender=undefined;globalThis.console=this.defaultConsoleLogger.logger;globalThis.console.log=this.defaultConsoleLogger.log;globalThis.console.info=this.defaultConsoleLogger.info;globalThis.console.debug=this.defaultConsoleLogger.debug;globalThis.console.warn=this.defaultConsoleLogger.warn;globalThis.console.error=this.defaultConsoleLogger.error}log(...args){if(!this.isProdMode){this.defaultConsoleLogger.log.apply(this.defaultConsoleLogger.logger,arguments)}if(this.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}}debug(...args){if(!this.isProdMode){this.defaultConsoleLogger.debug.apply(this.defaultConsoleLogger.logger,arguments)}}info(...args){if(!this.isProdMode){this.defaultConsoleLogger.info.apply(this.defaultConsoleLogger.logger,arguments)}if(this.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}}warn(...args){this.defaultConsoleLogger.warn.apply(this.defaultConsoleLogger.logger,arguments);if(this.isJSNLogSetup){(0,jsnlog_1.JL)().warn(arguments)}}error(...args){this.defaultConsoleLogger.error.apply(this.defaultConsoleLogger.logger,arguments);if(this.isJSNLogSetup){(0,jsnlog_1.JL)().error(arguments)}}flush(){if(this.isJSNLogSetup&&this.currentAppender!=null){this.currentAppender.sendBatch()}}enableProdMode(){this.isProdMode=true}}exports.OpenViduLogger=OpenViduLogger},{"./ConsoleLogger":80,"./OpenViduLoggerConfiguration":82,jsnlog:7}],82:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OpenViduLoggerConfiguration=void 0;var OpenViduLoggerConfiguration;(function(OpenViduLoggerConfiguration){OpenViduLoggerConfiguration["disabled"]="disabled";OpenViduLoggerConfiguration["debug"]="debug";OpenViduLoggerConfiguration["debug_app"]="debug_app"})(OpenViduLoggerConfiguration||(exports.OpenViduLoggerConfiguration=OpenViduLoggerConfiguration={}))},{}],83:[function(require,module,exports){globalThis.getScreenId=function(firefoxString,callback,custom_parameter){if(navigator.userAgent.indexOf("Edge")!==-1&&(!!navigator.msSaveOrOpenBlob||!!navigator.msSaveBlob)){callback({video:true});return}if(!!navigator.mozGetUserMedia){callback(null,"firefox",{video:{mozMediaSource:firefoxString,mediaSource:firefoxString}});return}globalThis.addEventListener("message",onIFrameCallback);function onIFrameCallback(event){if(!event.data)return;if(event.data.chromeMediaSourceId){if(event.data.chromeMediaSourceId==="PermissionDeniedError"){callback("permission-denied")}else{callback(null,event.data.chromeMediaSourceId,getScreenConstraints(null,event.data.chromeMediaSourceId,event.data.canRequestAudioTrack))}globalThis.removeEventListener("message",onIFrameCallback)}if(event.data.chromeExtensionStatus){callback(event.data.chromeExtensionStatus,null,getScreenConstraints(event.data.chromeExtensionStatus));globalThis.removeEventListener("message",onIFrameCallback)}}if(!custom_parameter){setTimeout(postGetSourceIdMessage,100)}else{setTimeout(function(){postGetSourceIdMessage(custom_parameter)},100)}};function getScreenConstraints(error,sourceId,canRequestAudioTrack){var screen_constraints={audio:false,video:{mandatory:{chromeMediaSource:error?"screen":"desktop",maxWidth:globalThis.screen.width>1920?globalThis.screen.width:1920,maxHeight:globalThis.screen.height>1080?globalThis.screen.height:1080},optional:[]}};if(!!canRequestAudioTrack){screen_constraints.audio={mandatory:{chromeMediaSource:error?"screen":"desktop"},optional:[]}}if(sourceId){screen_constraints.video.mandatory.chromeMediaSourceId=sourceId;if(screen_constraints.audio&&screen_constraints.audio.mandatory){screen_constraints.audio.mandatory.chromeMediaSourceId=sourceId}}return screen_constraints}function postGetSourceIdMessage(custom_parameter){if(!iframe){loadIFrame(function(){postGetSourceIdMessage(custom_parameter)});return}if(!iframe.isLoaded){setTimeout(function(){postGetSourceIdMessage(custom_parameter)},100);return}if(!custom_parameter){iframe.contentWindow.postMessage({captureSourceId:true},"*")}else if(!!custom_parameter.forEach){iframe.contentWindow.postMessage({captureCustomSourceId:custom_parameter},"*")}else{iframe.contentWindow.postMessage({captureSourceIdWithAudio:true},"*")}}var iframe;globalThis.getScreenConstraints=function(callback){loadIFrame(function(){getScreenId(function(error,sourceId,screen_constraints){if(!screen_constraints){screen_constraints={video:true}}callback(error,screen_constraints.video)})})};function loadIFrame(loadCallback){if(iframe){loadCallback();return}iframe=document.createElement("iframe");iframe.onload=function(){iframe.isLoaded=true;loadCallback()};iframe.src="https://openvidu.github.io/openvidu-screen-sharing-chrome-extension/";iframe.style.display="none";(document.body||document.documentElement).appendChild(iframe)}globalThis.getChromeExtensionStatus=function(callback){if(!!navigator.mozGetUserMedia){callback("installed-enabled");return}globalThis.addEventListener("message",onIFrameCallback);function onIFrameCallback(event){if(!event.data)return;if(event.data.chromeExtensionStatus){callback(event.data.chromeExtensionStatus);globalThis.removeEventListener("message",onIFrameCallback)}}setTimeout(postGetChromeExtensionStatusMessage,100)};function postGetChromeExtensionStatusMessage(){if(!iframe){loadIFrame(postGetChromeExtensionStatusMessage);return}if(!iframe.isLoaded){setTimeout(postGetChromeExtensionStatusMessage,100);return}iframe.contentWindow.postMessage({getChromeExtensionStatus:true},"*")}exports.getScreenId=globalThis.getScreenId},{}],84:[function(require,module,exports){var chromeMediaSource="screen";var sourceId;var screenCallback;if(typeof window!=="undefined"&&typeof navigator!=="undefined"&&typeof navigator.userAgent!=="undefined"){var isFirefox=typeof window.InstallTrigger!=="undefined";var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0;var isChrome=!!window.chrome&&!isOpera;window.addEventListener("message",function(event){if(event.origin!=window.location.origin){return}onMessageCallback(event.data)})}function onMessageCallback(data){if(data=="PermissionDeniedError"){if(screenCallback)return screenCallback("PermissionDeniedError");else throw new Error("PermissionDeniedError")}if(data=="rtcmulticonnection-extension-loaded"){chromeMediaSource="desktop"}if(data.sourceId&&screenCallback){screenCallback(sourceId=data.sourceId,data.canRequestAudioTrack===true)}}function isChromeExtensionAvailable(callback){if(!callback)return;if(chromeMediaSource=="desktop")return callback(true);window.postMessage("are-you-there","*");setTimeout(function(){if(chromeMediaSource=="screen"){callback(false)}else callback(true)},2e3)}function getSourceId(callback){if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage("get-sourceId","*")}function getCustomSourceId(arr,callback){if(!arr||!arr.forEach)throw'"arr" parameter is mandatory and it must be an array.';if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage({"get-custom-sourceId":arr},"*")}function getSourceIdWithAudio(callback){if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage("audio-plus-tab","*")}function getChromeExtensionStatus(extensionid,callback){if(isFirefox)return callback("not-chrome");if(arguments.length!=2){callback=extensionid;extensionid="lfcgfepafnobdloecchnfaclibenjold"}var image=document.createElement("img");image.src="chrome-extension://"+extensionid+"/icon.png";image.onload=function(){chromeMediaSource="screen";window.postMessage("are-you-there","*");setTimeout(function(){if(chromeMediaSource=="screen"){callback("installed-disabled")}else callback("installed-enabled")},2e3)};image.onerror=function(){callback("not-installed")}}function getScreenConstraintsWithAudio(callback){getScreenConstraints(callback,true)}function getScreenConstraints(callback,captureSourceIdWithAudio){sourceId="";var firefoxScreenConstraints={mozMediaSource:"window",mediaSource:"window"};if(isFirefox)return callback(null,firefoxScreenConstraints);var screen_constraints={mandatory:{chromeMediaSource:chromeMediaSource,maxWidth:screen.width>1920?screen.width:1920,maxHeight:screen.height>1080?screen.height:1080},optional:[]};if(chromeMediaSource=="desktop"&&!sourceId){if(captureSourceIdWithAudio){getSourceIdWithAudio(function(sourceId,canRequestAudioTrack){screen_constraints.mandatory.chromeMediaSourceId=sourceId;if(canRequestAudioTrack){screen_constraints.canRequestAudioTrack=true}callback(sourceId=="PermissionDeniedError"?sourceId:null,screen_constraints)})}else{getSourceId(function(sourceId){screen_constraints.mandatory.chromeMediaSourceId=sourceId;callback(sourceId=="PermissionDeniedError"?sourceId:null,screen_constraints)})}return}if(chromeMediaSource=="desktop"){screen_constraints.mandatory.chromeMediaSourceId=sourceId}callback(null,screen_constraints)}exports.getScreenConstraints=getScreenConstraints;exports.getScreenConstraintsWithAudio=getScreenConstraintsWithAudio;exports.isChromeExtensionAvailable=isChromeExtensionAvailable;exports.getChromeExtensionStatus=getChromeExtensionStatus;exports.getSourceId=getSourceId},{}],85:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PlatformUtils=void 0;const platform=require("platform");class PlatformUtils{constructor(){}static getInstance(){if(!this.instance){this.instance=new PlatformUtils}return PlatformUtils.instance}isChromeBrowser(){return platform.name==="Chrome"}isSafariBrowser(){return platform.name==="Safari"}isChromeMobileBrowser(){return platform.name==="Chrome Mobile"}isFirefoxBrowser(){return platform.name==="Firefox"}isFirefoxMobileBrowser(){return platform.name==="Firefox Mobile"||platform.name==="Firefox for iOS"}isOperaBrowser(){return platform.name==="Opera"}isOperaMobileBrowser(){return platform.name==="Opera Mobile"}isEdgeBrowser(){const version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;return platform.name==="Microsoft Edge"&&version>=80}isEdgeMobileBrowser(){var _a,_b;const version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;return platform.name==="Microsoft Edge"&&(((_a=platform.os)===null||_a===void 0?void 0:_a.family)==="Android"||((_b=platform.os)===null||_b===void 0?void 0:_b.family)==="iOS")&&version>45}isAndroidBrowser(){return platform.name==="Android Browser"}isElectron(){return platform.name==="Electron"}isNodeJs(){return platform.name==="Node.js"}isSamsungBrowser(){return platform.name==="Samsung Internet Mobile"||platform.name==="Samsung Internet"}isMotorolaEdgeDevice(){var _a;return((_a=platform.product)===null||_a===void 0?void 0:_a.toLowerCase().includes("motorola edge"))||false}isIPhoneOrIPad(){const userAgent=!!platform.ua?platform.ua:navigator.userAgent;const isTouchable="ontouchend"in document;const isIPad=/\b(\w*Macintosh\w*)\b/.test(userAgent)&&isTouchable;const isIPhone=/\b(\w*iPhone\w*)\b/.test(userAgent)&&/\b(\w*Mobile\w*)\b/.test(userAgent)&&isTouchable;return isIPad||isIPhone}isIOSWithSafari(){const userAgent=!!platform.ua?platform.ua:navigator.userAgent;return this.isIPhoneOrIPad()&&/\b(\w*Apple\w*)\b/.test(navigator.vendor)&&/\b(\w*Safari\w*)\b/.test(userAgent)&&!/\b(\w*CriOS\w*)\b/.test(userAgent)&&!/\b(\w*FxiOS\w*)\b/.test(userAgent)}isIonicIos(){return this.isIPhoneOrIPad()&&platform.ua.indexOf("Safari")===-1}isIonicAndroid(){return platform.os.family==="Android"&&platform.name=="Android Browser"}isMobileDevice(){return platform.os.family==="iOS"||platform.os.family==="Android"}isReactNative(){return false}isChromium(){return this.isChromeBrowser()||this.isChromeMobileBrowser()||this.isOperaBrowser()||this.isOperaMobileBrowser()||this.isEdgeBrowser()||this.isEdgeMobileBrowser()||this.isSamsungBrowser()||this.isIonicAndroid()||this.isIonicIos()||this.isElectron()||this.isMotorolaEdgeDevice()}canScreenShare(){const version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;if(this.isMobileDevice()){return false}return this.isChromeBrowser()||this.isFirefoxBrowser()||this.isOperaBrowser()||this.isElectron()||this.isEdgeBrowser()||this.isSafariBrowser()&&version>=13}getName(){return platform.name||""}getVersion(){return platform.version||""}getFamily(){return platform.os.family||""}getDescription(){return platform.description||""}}exports.PlatformUtils=PlatformUtils},{platform:13}],86:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.WebRtcPeerSendrecv=exports.WebRtcPeerSendonly=exports.WebRtcPeerRecvonly=exports.WebRtcPeer=void 0;const freeice=require("freeice");const uuid_1=require("uuid");const ExceptionEvent_1=require("../Events/ExceptionEvent");const OpenViduLogger_1=require("../Logger/OpenViduLogger");const Platform_1=require("../Utils/Platform");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class WebRtcPeer{constructor(configuration){this.remoteCandidatesQueue=[];this.localCandidatesQueue=[];this.iceCandidateList=[];platform=Platform_1.PlatformUtils.getInstance();this.configuration=Object.assign(Object.assign({},configuration),{iceServers:!!configuration.iceServers&&configuration.iceServers.length>0?configuration.iceServers:freeice(),rtcConfiguration:configuration.rtcConfiguration!==undefined?configuration.rtcConfiguration:{},mediaStream:configuration.mediaStream!==undefined?configuration.mediaStream:null,mode:!!configuration.mode?configuration.mode:"sendrecv",id:!!configuration.id?configuration.id:this.generateUniqueId()});logger.debug(`[WebRtcPeer] configuration:\n${JSON.stringify(this.configuration,null,2)}`);let rtcConfiguration=this.configuration.rtcConfiguration?this.configuration.rtcConfiguration:{iceServers:this.configuration.iceServers};if(!rtcConfiguration.iceServers&&this.configuration.iceServers){rtcConfiguration.iceServers=this.configuration.iceServers}this.pc=new RTCPeerConnection(rtcConfiguration);this.pc.addEventListener("icecandidate",event=>{if(event.candidate!==null){const candidateInit=event.candidate;const iceCandidate=new RTCIceCandidate(candidateInit);this.configuration.onIceCandidate(iceCandidate);if(iceCandidate.candidate!==""){this.localCandidatesQueue.push(iceCandidate)}}});this.pc.addEventListener("signalingstatechange",()=>__awaiter(this,void 0,void 0,function*(){if(this.pc.signalingState==="stable"){while(this.iceCandidateList.length>0){let candidate=this.iceCandidateList.shift();try{yield this.pc.addIceCandidate(candidate)}catch(error){logger.error("Error when calling RTCPeerConnection#addIceCandidate for RTCPeerConnection "+this.getId(),error)}}}}))}getId(){return this.configuration.id}dispose(){logger.debug("Disposing WebRtcPeer");if(this.pc){if(this.pc.signalingState==="closed"){return}this.pc.close();this.remoteCandidatesQueue=[];this.localCandidatesQueue=[]}}createOfferLegacy(){if(!!this.configuration.mediaStream){this.deprecatedPeerConnectionTrackApi()}const hasAudio=this.configuration.mediaConstraints.audio;const hasVideo=this.configuration.mediaConstraints.video;const options={offerToReceiveAudio:this.configuration.mode!=="sendonly"&&hasAudio,offerToReceiveVideo:this.configuration.mode!=="sendonly"&&hasVideo};logger.debug("[createOfferLegacy] RTCPeerConnection.createOffer() options:",JSON.stringify(options));return this.pc.createOffer(options)}createOffer(){return __awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g,_h;if(!("addTransceiver"in this.pc)){logger.warn("[createOffer] Method RTCPeerConnection.addTransceiver() is NOT available; using LEGACY offerToReceive{Audio,Video}");return this.createOfferLegacy()}else{logger.debug("[createOffer] Method RTCPeerConnection.addTransceiver() is available; using it")}if(this.configuration.mode!=="recvonly"){if(!this.configuration.mediaStream){throw new Error(`[WebRtcPeer.createOffer] Direction is '${this.configuration.mode}', but no stream was configured to be sent`)}for(const track of this.configuration.mediaStream.getTracks()){const tcInit={direction:this.configuration.mode,streams:[this.configuration.mediaStream]};if(track.kind==="video"&&this.configuration.simulcast){const trackSettings=track.getSettings();const trackConsts=track.getConstraints();const trackWidth=(_c=(_b=(_a=trackSettings.width)!==null&&_a!==void 0?_a:trackConsts.width.ideal)!==null&&_b!==void 0?_b:trackConsts.width)!==null&&_c!==void 0?_c:0;const trackHeight=(_f=(_e=(_d=trackSettings.height)!==null&&_d!==void 0?_d:trackConsts.height.ideal)!==null&&_e!==void 0?_e:trackConsts.height)!==null&&_f!==void 0?_f:0;logger.info(`[createOffer] Video track dimensions: ${trackWidth}x${trackHeight}`);const trackPixels=trackWidth*trackHeight;let maxLayers=0;if(trackPixels>=960*540){maxLayers=3}else if(trackPixels>=480*270){maxLayers=2}else{maxLayers=1}tcInit.sendEncodings=[];for(let l=0;l<maxLayers;l++){const layerDiv=Math.pow(2,maxLayers-l-1);const encoding={rid:"rdiv"+layerDiv.toString(),scalabilityMode:"L1T1"};if(["detail","text"].includes(track.contentHint)){encoding.scaleResolutionDownBy=1;encoding.maxFramerate=Math.floor(30/layerDiv)}else{encoding.scaleResolutionDownBy=layerDiv}tcInit.sendEncodings.push(encoding)}}const tc=this.pc.addTransceiver(track,tcInit);if(track.kind==="video"){let sendParams=tc.sender.getParameters();let needSetParams=false;if(!((_g=sendParams.degradationPreference)===null||_g===void 0?void 0:_g.length)){if(["detail","text"].includes(track.contentHint)){sendParams.degradationPreference="maintain-resolution"}else{sendParams.degradationPreference="balanced"}logger.info(`[createOffer] Video sender Degradation Preference set: ${sendParams.degradationPreference}`);needSetParams=true}if(this.configuration.simulcast){if(((_h=sendParams.encodings)===null||_h===void 0?void 0:_h.length)!==tcInit.sendEncodings.length){sendParams.encodings=tcInit.sendEncodings;needSetParams=true}}if(needSetParams){logger.debug(`[createOffer] Setting new RTCRtpSendParameters to video sender`);try{yield tc.sender.setParameters(sendParams)}catch(error){let message=`[WebRtcPeer.createOffer] Cannot set RTCRtpSendParameters to video sender`;if(error instanceof Error){message+=`: ${error.message}`}throw new Error(message)}}}}}else{for(const kind of["audio","video"]){if(!this.configuration.mediaConstraints[kind]){continue}this.configuration.mediaStream=new MediaStream;this.pc.addTransceiver(kind,{direction:this.configuration.mode,streams:[this.configuration.mediaStream]})}}let sdpOffer;try{sdpOffer=yield this.pc.createOffer()}catch(error){let message=`[WebRtcPeer.createOffer] Browser failed creating an SDP Offer`;if(error instanceof Error){message+=`: ${error.message}`}throw new Error(message)}return sdpOffer})}deprecatedPeerConnectionTrackApi(){for(const track of this.configuration.mediaStream.getTracks()){this.pc.addTrack(track,this.configuration.mediaStream)}}createAnswer(){return new Promise((resolve,reject)=>{if("getTransceivers"in this.pc){logger.debug("[createAnswer] Method RTCPeerConnection.getTransceivers() is available; using it");for(const kind of["audio","video"]){if(!this.configuration.mediaConstraints[kind]){continue}let tc=this.pc.getTransceivers().find(tc=>tc.receiver.track.kind===kind);if(tc){tc.direction=this.configuration.mode}else{return reject(new Error(`${kind} requested, but no transceiver was created from remote description`))}}this.pc.createAnswer().then(sdpAnswer=>resolve(sdpAnswer)).catch(error=>reject(error))}else{let offerAudio,offerVideo=true;if(!!this.configuration.mediaConstraints){offerAudio=typeof this.configuration.mediaConstraints.audio==="boolean"?this.configuration.mediaConstraints.audio:true;offerVideo=typeof this.configuration.mediaConstraints.video==="boolean"?this.configuration.mediaConstraints.video:true;const constraints={offerToReceiveAudio:offerAudio,offerToReceiveVideo:offerVideo};this.pc.createAnswer(constraints).then(sdpAnswer=>resolve(sdpAnswer)).catch(error=>reject(error))}}})}processLocalOffer(offer){return new Promise((resolve,reject)=>{this.pc.setLocalDescription(offer).then(()=>{const localDescription=this.pc.localDescription;if(!!localDescription){logger.debug("Local description set",localDescription.sdp);return resolve()}else{return reject("Local description is not defined")}}).catch(error=>reject(error))})}processRemoteOffer(sdpOffer){return new Promise((resolve,reject)=>{const offer={type:"offer",sdp:sdpOffer};logger.debug("SDP offer received, setting remote description",offer);if(this.pc.signalingState==="closed"){return reject("RTCPeerConnection is closed when trying to set remote description")}this.setRemoteDescription(offer).then(()=>resolve()).catch(error=>reject(error))})}processLocalAnswer(answer){return new Promise((resolve,reject)=>{logger.debug("SDP answer created, setting local description");if(this.pc.signalingState==="closed"){return reject("RTCPeerConnection is closed when trying to set local description")}this.pc.setLocalDescription(answer).then(()=>resolve()).catch(error=>reject(error))})}processRemoteAnswer(sdpAnswer){return new Promise((resolve,reject)=>{const answer={type:"answer",sdp:sdpAnswer};logger.debug("SDP answer received, setting remote description");if(this.pc.signalingState==="closed"){return reject("RTCPeerConnection is closed when trying to set remote description")}this.setRemoteDescription(answer).then(()=>{resolve()}).catch(error=>reject(error))})}setRemoteDescription(sdp){return __awaiter(this,void 0,void 0,function*(){return this.pc.setRemoteDescription(sdp)})}addIceCandidate(iceCandidate){return new Promise((resolve,reject)=>{logger.debug("Remote ICE candidate received",iceCandidate);this.remoteCandidatesQueue.push(iceCandidate);switch(this.pc.signalingState){case"closed":reject(new Error("PeerConnection object is closed"));break;case"stable":if(!!this.pc.remoteDescription){this.pc.addIceCandidate(iceCandidate).then(()=>resolve()).catch(error=>reject(error))}else{this.iceCandidateList.push(iceCandidate);resolve()}break;default:this.iceCandidateList.push(iceCandidate);resolve()}})}addIceConnectionStateChangeListener(otherId){this.pc.addEventListener("iceconnectionstatechange",()=>{const iceConnectionState=this.pc.iceConnectionState;switch(iceConnectionState){case"disconnected":const msg1="IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "disconnected". Possible network disconnection';logger.warn(msg1);this.configuration.onIceConnectionStateException(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED,msg1);break;case"failed":const msg2="IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') to "failed"';logger.error(msg2);this.configuration.onIceConnectionStateException(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED,msg2);break;case"closed":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "closed"');break;case"new":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "new"');break;case"checking":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "checking"');break;case"connected":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "connected"');break;case"completed":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "completed"');break}})}generateUniqueId(){return(0,uuid_1.v4)()}}exports.WebRtcPeer=WebRtcPeer;class WebRtcPeerRecvonly extends WebRtcPeer{constructor(configuration){configuration.mode="recvonly";super(configuration)}}exports.WebRtcPeerRecvonly=WebRtcPeerRecvonly;class WebRtcPeerSendonly extends WebRtcPeer{constructor(configuration){configuration.mode="sendonly";super(configuration)}}exports.WebRtcPeerSendonly=WebRtcPeerSendonly;class WebRtcPeerSendrecv extends WebRtcPeer{constructor(configuration){configuration.mode="sendrecv";super(configuration)}}exports.WebRtcPeerSendrecv=WebRtcPeerSendrecv},{"../Events/ExceptionEvent":59,"../Logger/OpenViduLogger":81,"../Utils/Platform":85,freeice:2,uuid:23}],87:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.WebRtcStats=void 0;const OpenViduLogger_1=require("../Logger/OpenViduLogger");const Platform_1=require("../Utils/Platform");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class WebRtcStats{constructor(stream){this.stream=stream;this.STATS_ITEM_NAME="webrtc-stats-config";this.webRtcStatsEnabled=false;this.statsInterval=1;platform=Platform_1.PlatformUtils.getInstance()}isEnabled(){return this.webRtcStatsEnabled}initWebRtcStats(){let webrtcObj;try{webrtcObj=localStorage.getItem(this.STATS_ITEM_NAME)}catch(e){}if(!!webrtcObj){this.webRtcStatsEnabled=true;const webrtcStatsConfig=JSON.parse(webrtcObj);logger.warn("WebRtc stats enabled for stream "+this.stream.streamId+" of connection "+this.stream.connection.connectionId);logger.warn("localStorage item: "+JSON.stringify(webrtcStatsConfig));this.POST_URL=webrtcStatsConfig.httpEndpoint;this.statsInterval=webrtcStatsConfig.interval;this.webRtcStatsIntervalId=setInterval(()=>__awaiter(this,void 0,void 0,function*(){yield this.sendStatsToHttpEndpoint()}),this.statsInterval*1e3)}else{logger.debug("WebRtc stats not enabled")}}getSelectedIceCandidateInfo(){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){const statsReport=yield this.stream.getRTCPeerConnection().getStats();let transportStat;const candidatePairs=new Map;const localCandidates=new Map;const remoteCandidates=new Map;statsReport.forEach(stat=>{if(stat.type==="transport"&&(platform.isChromium()||platform.isSafariBrowser()||platform.isReactNative())){transportStat=stat}switch(stat.type){case"candidate-pair":candidatePairs.set(stat.id,stat);break;case"local-candidate":localCandidates.set(stat.id,stat);break;case"remote-candidate":remoteCandidates.set(stat.id,stat);break}});let selectedCandidatePair;if(transportStat!=null){const selectedCandidatePairId=transportStat.selectedCandidatePairId;selectedCandidatePair=candidatePairs.get(selectedCandidatePairId)}else{const length=candidatePairs.size;const iterator=candidatePairs.values();for(let i=0;i<length;i++){const candidatePair=iterator.next().value;if(candidatePair["selected"]){selectedCandidatePair=candidatePair;break}}}const localCandidateId=selectedCandidatePair.localCandidateId;const remoteCandidateId=selectedCandidatePair.remoteCandidateId;let finalLocalCandidate=localCandidates.get(localCandidateId);if(!!finalLocalCandidate){const candList=this.stream.getLocalIceCandidateList();const cand=candList.filter(c=>!!c.candidate&&(c.candidate.indexOf(finalLocalCandidate.ip)>=0||c.candidate.indexOf(finalLocalCandidate.address)>=0)&&c.candidate.indexOf(finalLocalCandidate.port)>=0);finalLocalCandidate.raw=[];for(let c of cand){finalLocalCandidate.raw.push(c.candidate)}}else{finalLocalCandidate="ERROR: No active local ICE candidate. Probably ICE-TCP is being used"}let finalRemoteCandidate=remoteCandidates.get(remoteCandidateId);if(!!finalRemoteCandidate){const candList=this.stream.getRemoteIceCandidateList();const cand=candList.filter(c=>!!c.candidate&&(c.candidate.indexOf(finalRemoteCandidate.ip)>=0||c.candidate.indexOf(finalRemoteCandidate.address)>=0)&&c.candidate.indexOf(finalRemoteCandidate.port)>=0);finalRemoteCandidate.raw=[];for(let c of cand){finalRemoteCandidate.raw.push(c.candidate)}}else{finalRemoteCandidate="ERROR: No active remote ICE candidate. Probably ICE-TCP is being used"}return resolve({localCandidate:finalLocalCandidate,remoteCandidate:finalRemoteCandidate})}))}stopWebRtcStats(){if(this.webRtcStatsEnabled){clearInterval(this.webRtcStatsIntervalId);logger.warn("WebRtc stats stopped for disposed stream "+this.stream.streamId+" of connection "+this.stream.connection.connectionId)}}sendStats(url,response){return __awaiter(this,void 0,void 0,function*(){try{const configuration={headers:{"Content-type":"application/json"},body:JSON.stringify(response),method:"POST"};yield fetch(url,configuration)}catch(error){logger.error(`sendStats error: ${JSON.stringify(error)}`)}})}sendStatsToHttpEndpoint(){return __awaiter(this,void 0,void 0,function*(){try{const webrtcStats=yield this.getCommonStats();const response=this.generateJSONStatsResponse(webrtcStats);yield this.sendStats(this.POST_URL,response)}catch(error){logger.log(error)}})}getCommonStats(){return __awaiter(this,void 0,void 0,function*(){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){try{const statsReport=yield this.stream.getRTCPeerConnection().getStats();const response=this.getWebRtcStatsResponseOutline();const videoTrackStats=["framesReceived","framesDropped","framesSent","frameHeight","frameWidth"];const candidatePairStats=["availableOutgoingBitrate","currentRoundTripTime"];statsReport.forEach(stat=>{let mediaType=stat.mediaType!=null?stat.mediaType:stat.kind;const addStat=(direction,key)=>{if(stat[key]!=null&&response[direction]!=null){if(!mediaType&&videoTrackStats.indexOf(key)>-1){mediaType="video"}if(direction!=null&&mediaType!=null&&key!=null&&response[direction][mediaType]!=null){response[direction][mediaType][key]=Number(stat[key])}else if(direction!=null&&key!=null&&candidatePairStats.includes(key)){response[direction][key]=Number(stat[key])}}};switch(stat.type){case"outbound-rtp":addStat("outbound","bytesSent");addStat("outbound","packetsSent");addStat("outbound","framesEncoded");addStat("outbound","nackCount");addStat("outbound","firCount");addStat("outbound","pliCount");addStat("outbound","qpSum");break;case"inbound-rtp":addStat("inbound","bytesReceived");addStat("inbound","packetsReceived");addStat("inbound","packetsLost");addStat("inbound","jitter");addStat("inbound","framesDecoded");addStat("inbound","nackCount");addStat("inbound","firCount");addStat("inbound","pliCount");break;case"track":addStat("inbound","jitterBufferDelay");addStat("inbound","framesReceived");addStat("outbound","framesDropped");addStat("outbound","framesSent");addStat(this.stream.isLocal()?"outbound":"inbound","frameHeight");addStat(this.stream.isLocal()?"outbound":"inbound","frameWidth");break;case"candidate-pair":addStat("candidatepair","currentRoundTripTime");addStat("candidatepair","availableOutgoingBitrate");break}});if(!(response===null||response===void 0?void 0:response.candidatepair)||Object.keys(response.candidatepair).length===0){delete response.candidatepair}return resolve(response)}catch(error){logger.error("Error getting common stats: ",error);return reject(error)}}))})}generateJSONStatsResponse(stats){return{"@timestamp":(new Date).toISOString(),participant_id:this.stream.connection.data,session_id:this.stream.session.sessionId,platform:platform.getName(),platform_description:platform.getDescription(),stream:"webRTC",webrtc_stats:stats}}getWebRtcStatsResponseOutline(){if(this.stream.isLocal()){return{outbound:{audio:{},video:{}},candidatepair:{}}}else{return{inbound:{audio:{},video:{}}}}}}exports.WebRtcStats=WebRtcStats},{"../Logger/OpenViduLogger":81,"../Utils/Platform":85}]},{},[41]);
|
|
1
|
+
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[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)}}},{}],2:[function(require,module,exports){"use strict";var normalice=require("normalice");var freeice=function(opts){var servers={stun:(opts||{}).stun||require("./stun.json"),turn:(opts||{}).turn||require("./turn.json")};var stunCount=(opts||{}).stunCount||2;var turnCount=(opts||{}).turnCount||0;var selected;function getServers(type,count){var out=[];var input=[].concat(servers[type]);var idx;while(input.length&&out.length<count){idx=Math.random()*input.length|0;out=out.concat(input.splice(idx,1))}return out.map(function(url){if(typeof url!=="string"&&!(url instanceof String)){return url}else{return normalice(type+":"+url)}})}selected=[].concat(getServers("stun",stunCount));if(turnCount){selected=selected.concat(getServers("turn",turnCount))}return selected};module.exports=freeice},{"./stun.json":3,"./turn.json":4,normalice:12}],3:[function(require,module,exports){module.exports=["stun.l.google.com:19302","stun1.l.google.com:19302","stun2.l.google.com:19302","stun3.l.google.com:19302","stun4.l.google.com:19302","stun.ekiga.net","stun.ideasip.com","stun.schlund.de","stun.stunprotocol.org:3478","stun.voiparound.com","stun.voipbuster.com","stun.voipstunt.com","stun.voxgratia.org"]},{}],4:[function(require,module,exports){module.exports=[]},{}],5:[function(require,module,exports){var WildEmitter=require("wildemitter");function getMaxVolume(analyser,fftBins){var maxVolume=-Infinity;analyser.getFloatFrequencyData(fftBins);for(var i=4,ii=fftBins.length;i<ii;i++){if(fftBins[i]>maxVolume&&fftBins[i]<0){maxVolume=fftBins[i]}}return maxVolume}var audioContextType;if(typeof window!=="undefined"){audioContextType=window.AudioContext||window.webkitAudioContext}var audioContext=null;module.exports=function(stream,options){var harker=new WildEmitter;if(!audioContextType)return harker;var options=options||{},smoothing=options.smoothing||.1,interval=options.interval||50,threshold=options.threshold,play=options.play,history=options.history||10,running=true;audioContext=options.audioContext||audioContext||new audioContextType;var sourceNode,fftBins,analyser;analyser=audioContext.createAnalyser();analyser.fftSize=512;analyser.smoothingTimeConstant=smoothing;fftBins=new Float32Array(analyser.frequencyBinCount);if(stream.jquery)stream=stream[0];if(stream instanceof HTMLAudioElement||stream instanceof HTMLVideoElement){sourceNode=audioContext.createMediaElementSource(stream);if(typeof play==="undefined")play=true;threshold=threshold||-50}else{sourceNode=audioContext.createMediaStreamSource(stream);threshold=threshold||-50}sourceNode.connect(analyser);if(play)analyser.connect(audioContext.destination);harker.speaking=false;harker.suspend=function(){return audioContext.suspend()};harker.resume=function(){return audioContext.resume()};Object.defineProperty(harker,"state",{get:function(){return audioContext.state}});audioContext.onstatechange=function(){harker.emit("state_change",audioContext.state)};harker.setThreshold=function(t){threshold=t};harker.setInterval=function(i){interval=i};harker.stop=function(){running=false;harker.emit("volume_change",-100,threshold);if(harker.speaking){harker.speaking=false;harker.emit("stopped_speaking")}analyser.disconnect();sourceNode.disconnect()};harker.speakingHistory=[];for(var i=0;i<history;i++){harker.speakingHistory.push(0)}var looper=function(){setTimeout(function(){if(!running){return}var currentVolume=getMaxVolume(analyser,fftBins);harker.emit("volume_change",currentVolume,threshold);var history=0;if(currentVolume>threshold&&!harker.speaking){for(var i=harker.speakingHistory.length-3;i<harker.speakingHistory.length;i++){history+=harker.speakingHistory[i]}if(history>=2){harker.speaking=true;harker.emit("speaking")}}else if(currentVolume<threshold&&harker.speaking){for(var i=0;i<harker.speakingHistory.length;i++){history+=harker.speakingHistory[i]}if(history==0){harker.speaking=false;harker.emit("stopped_speaking")}}harker.speakingHistory.shift();harker.speakingHistory.push(0+(currentVolume>threshold));looper()},interval)};looper();return harker}},{wildemitter:38}],6:[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}}}},{}],7:[function(require,module,exports){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){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();function JL(loggerName){if(!loggerName){return JL.__}if(!Array.prototype.reduce){Array.prototype.reduce=function(callback,initialValue){var previousValue=initialValue;for(var i=0;i<this.length;i++){previousValue=callback(previousValue,this[i],i,this)}return previousValue}}var accumulatedLoggerName="";var logger=("."+loggerName).split(".").reduce(function(prev,curr,idx,arr){if(accumulatedLoggerName){accumulatedLoggerName+="."+curr}else{accumulatedLoggerName=curr}var currentLogger=prev["__"+accumulatedLoggerName];if(currentLogger===undefined){JL.Logger.prototype=prev;currentLogger=new JL.Logger(accumulatedLoggerName);prev["__"+accumulatedLoggerName]=currentLogger}return currentLogger},JL.__);return logger}(function(JL){JL.requestId="";JL.entryId=0;JL._createXMLHttpRequest=function(){return new XMLHttpRequest};JL._getTime=function(){return(new Date).getTime()};JL._console=console;JL._appenderNames=[];function copyProperty(propertyName,from,to){if(from[propertyName]===undefined){return}if(from[propertyName]===null){delete to[propertyName];return}to[propertyName]=from[propertyName]}function allow(filters){if(!(JL.enabled==null)){if(!JL.enabled){return false}}try{if(filters.userAgentRegex){if(!new RegExp(filters.userAgentRegex).test(navigator.userAgent)){return false}}}catch(e){}try{if(filters.ipRegex&&JL.clientIP){if(!new RegExp(filters.ipRegex).test(JL.clientIP)){return false}}}catch(e){}return true}function allowMessage(filters,message){try{if(filters.disallow){if(new RegExp(filters.disallow).test(message)){return false}}}catch(e){}return true}function stringifyLogObjectFunction(logObject){if(typeof logObject=="function"){if(logObject instanceof RegExp){return logObject.toString()}else{return logObject()}}return logObject}var StringifiedLogObject=function(){function StringifiedLogObject(msg,meta,finalString){this.msg=msg;this.meta=meta;this.finalString=finalString}return StringifiedLogObject}();function stringifyLogObject(logObject){var actualLogObject=stringifyLogObjectFunction(logObject);var finalString;switch(typeof actualLogObject){case"string":return new StringifiedLogObject(actualLogObject,null,actualLogObject);case"number":finalString=actualLogObject.toString();return new StringifiedLogObject(finalString,null,finalString);case"boolean":finalString=actualLogObject.toString();return new StringifiedLogObject(finalString,null,finalString);case"undefined":return new StringifiedLogObject("undefined",null,"undefined");case"object":if(actualLogObject instanceof RegExp||actualLogObject instanceof String||actualLogObject instanceof Number||actualLogObject instanceof Boolean){finalString=actualLogObject.toString();return new StringifiedLogObject(finalString,null,finalString)}else{if(typeof JL.serialize==="function"){finalString=JL.serialize.call(this,actualLogObject)}else{finalString=JSON.stringify(actualLogObject)}return new StringifiedLogObject("",actualLogObject,finalString)}default:return new StringifiedLogObject("unknown",null,"unknown")}}function setOptions(options){copyProperty("enabled",options,this);copyProperty("maxMessages",options,this);copyProperty("defaultAjaxUrl",options,this);copyProperty("clientIP",options,this);copyProperty("requestId",options,this);copyProperty("defaultBeforeSend",options,this);copyProperty("serialize",options,this);return this}JL.setOptions=setOptions;function getAllLevel(){return-2147483648}JL.getAllLevel=getAllLevel;function getTraceLevel(){return 1e3}JL.getTraceLevel=getTraceLevel;function getDebugLevel(){return 2e3}JL.getDebugLevel=getDebugLevel;function getInfoLevel(){return 3e3}JL.getInfoLevel=getInfoLevel;function getWarnLevel(){return 4e3}JL.getWarnLevel=getWarnLevel;function getErrorLevel(){return 5e3}JL.getErrorLevel=getErrorLevel;function getFatalLevel(){return 6e3}JL.getFatalLevel=getFatalLevel;function getOffLevel(){return 2147483647}JL.getOffLevel=getOffLevel;function levelToString(level){if(level<=1e3){return"trace"}if(level<=2e3){return"debug"}if(level<=3e3){return"info"}if(level<=4e3){return"warn"}if(level<=5e3){return"error"}return"fatal"}var Exception=function(){function Exception(data,inner){this.inner=inner;this.name="JL.Exception";this.message=stringifyLogObject(data).finalString}return Exception}();JL.Exception=Exception;Exception.prototype=new Error;var LogItem=function(){function LogItem(l,m,n,t,u){this.l=l;this.m=m;this.n=n;this.t=t;this.u=u}return LogItem}();JL.LogItem=LogItem;function newLogItem(levelNbr,message,loggerName){JL.entryId++;return new LogItem(levelNbr,message,loggerName,JL._getTime(),JL.entryId)}function clearTimer(timer){if(timer.id){clearTimeout(timer.id);timer.id=null}}function setTimer(timer,timeoutMs,callback){var that=this;if(!timer.id){timer.id=setTimeout(function(){callback.call(that)},timeoutMs)}}var Appender=function(){function Appender(appenderName,sendLogItems){this.appenderName=appenderName;this.sendLogItems=sendLogItems;this.level=JL.getTraceLevel();this.sendWithBufferLevel=2147483647;this.storeInBufferLevel=-2147483648;this.bufferSize=0;this.batchSize=1;this.maxBatchSize=20;this.batchTimeout=2147483647;this.sendTimeout=5e3;this.buffer=[];this.batchBuffer=[];this.batchTimeoutTimer={id:null};this.sendTimeoutTimer={id:null};this.nbrLogItemsSkipped=0;this.nbrLogItemsBeingSent=0;var emptyNameErrorMessage="Trying to create an appender without a name or with an empty name";if(appenderName==undefined){throw emptyNameErrorMessage}if(JL._appenderNames.indexOf(appenderName)!=-1){if(!appenderName){throw emptyNameErrorMessage}throw"Multiple appenders use the same name "+appenderName}JL._appenderNames.push(appenderName)}Appender.prototype.addLogItemsToBuffer=function(logItems){if(this.batchBuffer.length>=this.maxBatchSize){this.nbrLogItemsSkipped+=logItems.length;return}if(!(JL.maxMessages==null)){if(JL.maxMessages<1){return}JL.maxMessages-=logItems.length}this.batchBuffer=this.batchBuffer.concat(logItems);var that=this;setTimer(this.batchTimeoutTimer,this.batchTimeout,function(){that.sendBatch.call(that)})};Appender.prototype.batchBufferHasOverdueMessages=function(){for(var i=0;i<this.batchBuffer.length;i++){var messageAgeMs=JL._getTime()-this.batchBuffer[i].t;if(messageAgeMs>this.batchTimeout){return true}}return false};Appender.prototype.batchBufferHasStrandedMessage=function(){return!(JL.maxMessages==null)&&JL.maxMessages<1&&this.batchBuffer.length>0};Appender.prototype.sendBatchIfComplete=function(){if(this.batchBuffer.length>=this.batchSize||this.batchBufferHasOverdueMessages()||this.batchBufferHasStrandedMessage()){this.sendBatch()}};Appender.prototype.onSendingEnded=function(){clearTimer(this.sendTimeoutTimer);this.nbrLogItemsBeingSent=0;this.sendBatchIfComplete()};Appender.prototype.setOptions=function(options){copyProperty("level",options,this);copyProperty("ipRegex",options,this);copyProperty("userAgentRegex",options,this);copyProperty("disallow",options,this);copyProperty("sendWithBufferLevel",options,this);copyProperty("storeInBufferLevel",options,this);copyProperty("bufferSize",options,this);copyProperty("batchSize",options,this);copyProperty("maxBatchSize",options,this);copyProperty("batchTimeout",options,this);copyProperty("sendTimeout",options,this);if(this.bufferSize<this.buffer.length){this.buffer.length=this.bufferSize}if(this.maxBatchSize<this.batchSize){throw new JL.Exception({message:"maxBatchSize cannot be smaller than batchSize",maxBatchSize:this.maxBatchSize,batchSize:this.batchSize})}return this};Appender.prototype.log=function(level,msg,meta,callback,levelNbr,message,loggerName){var logItem;if(!allow(this)){return}if(!allowMessage(this,message)){return}if(levelNbr<this.storeInBufferLevel){return}logItem=newLogItem(levelNbr,message,loggerName);if(levelNbr<this.level){if(this.bufferSize>0){this.buffer.push(logItem);if(this.buffer.length>this.bufferSize){this.buffer.shift()}}return}this.addLogItemsToBuffer([logItem]);if(levelNbr>=this.sendWithBufferLevel){if(this.buffer.length){this.addLogItemsToBuffer(this.buffer);this.buffer.length=0}}this.sendBatchIfComplete()};Appender.prototype.sendBatch=function(){if(this.nbrLogItemsBeingSent>0){return}clearTimer(this.batchTimeoutTimer);if(this.batchBuffer.length==0){return}this.nbrLogItemsBeingSent=this.batchBuffer.length;var that=this;setTimer(this.sendTimeoutTimer,this.sendTimeout,function(){that.onSendingEnded.call(that)});this.sendLogItems(this.batchBuffer,function(){that.batchBuffer.splice(0,that.nbrLogItemsBeingSent);if(that.nbrLogItemsSkipped>0){that.batchBuffer.push(newLogItem(getWarnLevel(),"Lost "+that.nbrLogItemsSkipped+" messages. Either connection with the server was down or logging was disabled via the enabled option. Reduce lost messages by increasing the ajaxAppender option maxBatchSize.",that.appenderName));that.nbrLogItemsSkipped=0}that.onSendingEnded.call(that)})};return Appender}();JL.Appender=Appender;var AjaxAppender=function(_super){__extends(AjaxAppender,_super);function AjaxAppender(appenderName){return _super.call(this,appenderName,AjaxAppender.prototype.sendLogItemsAjax)||this}AjaxAppender.prototype.setOptions=function(options){copyProperty("url",options,this);copyProperty("beforeSend",options,this);_super.prototype.setOptions.call(this,options);return this};AjaxAppender.prototype.sendLogItemsAjax=function(logItems,successCallback){try{if(!allow(this)){return}if(this.xhr&&this.xhr.readyState!=0&&this.xhr.readyState!=4){this.xhr.abort()}this.xhr=JL._createXMLHttpRequest();var ajaxUrl="/jsnlog.logger";if(!(JL.defaultAjaxUrl==null)){ajaxUrl=JL.defaultAjaxUrl}if(this.url){ajaxUrl=this.url}this.xhr.open("POST",ajaxUrl);this.xhr.setRequestHeader("Content-Type","application/json");this.xhr.setRequestHeader("JSNLog-RequestId",JL.requestId);var that=this;this.xhr.onreadystatechange=function(){if(that.xhr.readyState==4&&(that.xhr.status>=200&&that.xhr.status<300)){successCallback()}};var json={r:JL.requestId,lg:logItems};if(typeof this.beforeSend==="function"){this.beforeSend.call(this,this.xhr,json)}else if(typeof JL.defaultBeforeSend==="function"){JL.defaultBeforeSend.call(this,this.xhr,json)}var finalmsg=JSON.stringify(json);this.xhr.send(finalmsg)}catch(e){}};return AjaxAppender}(Appender);JL.AjaxAppender=AjaxAppender;var ConsoleAppender=function(_super){__extends(ConsoleAppender,_super);function ConsoleAppender(appenderName){return _super.call(this,appenderName,ConsoleAppender.prototype.sendLogItemsConsole)||this}ConsoleAppender.prototype.clog=function(logEntry){JL._console.log(logEntry)};ConsoleAppender.prototype.cerror=function(logEntry){if(JL._console.error){JL._console.error(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cwarn=function(logEntry){if(JL._console.warn){JL._console.warn(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cinfo=function(logEntry){if(JL._console.info){JL._console.info(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cdebug=function(logEntry){if(JL._console.debug){JL._console.debug(logEntry)}else{this.cinfo(logEntry)}};ConsoleAppender.prototype.sendLogItemsConsole=function(logItems,successCallback){try{if(!allow(this)){return}if(!JL._console){return}var i;for(i=0;i<logItems.length;++i){var li=logItems[i];var msg=li.n+": "+li.m;if(typeof window==="undefined"){msg=new Date(li.t)+" | "+msg}if(li.l<=JL.getDebugLevel()){this.cdebug(msg)}else if(li.l<=JL.getInfoLevel()){this.cinfo(msg)}else if(li.l<=JL.getWarnLevel()){this.cwarn(msg)}else{this.cerror(msg)}}}catch(e){}successCallback()};return ConsoleAppender}(Appender);JL.ConsoleAppender=ConsoleAppender;var Logger=function(){function Logger(loggerName){this.loggerName=loggerName;this.seenRegexes=[]}Logger.prototype.setOptions=function(options){copyProperty("level",options,this);copyProperty("userAgentRegex",options,this);copyProperty("disallow",options,this);copyProperty("ipRegex",options,this);copyProperty("appenders",options,this);copyProperty("onceOnly",options,this);this.seenRegexes=[];return this};Logger.prototype.buildExceptionObject=function(e){var excObject={};if(e.stack){excObject.stack=e.stack}else{excObject.e=e}if(e.message){excObject.message=e.message}if(e.name){excObject.name=e.name}if(e.data){excObject.data=e.data}if(e.inner){excObject.inner=this.buildExceptionObject(e.inner)}return excObject};Logger.prototype.log=function(level,logObject,e){var i=0;var compositeMessage;var excObject;if(!this.appenders){return this}if(level>=this.level&&allow(this)){if(e){excObject=this.buildExceptionObject(e);excObject.logData=stringifyLogObjectFunction(logObject)}else{excObject=logObject}compositeMessage=stringifyLogObject(excObject);if(allowMessage(this,compositeMessage.finalString)){if(this.onceOnly){i=this.onceOnly.length-1;while(i>=0){if(new RegExp(this.onceOnly[i]).test(compositeMessage.finalString)){if(this.seenRegexes[i]){return this}this.seenRegexes[i]=true}i--}}compositeMessage.meta=compositeMessage.meta||{};i=this.appenders.length-1;while(i>=0){this.appenders[i].log(levelToString(level),compositeMessage.msg,compositeMessage.meta,function(){},level,compositeMessage.finalString,this.loggerName);i--}}}return this};Logger.prototype.trace=function(logObject){return this.log(getTraceLevel(),logObject)};Logger.prototype.debug=function(logObject){return this.log(getDebugLevel(),logObject)};Logger.prototype.info=function(logObject){return this.log(getInfoLevel(),logObject)};Logger.prototype.warn=function(logObject){return this.log(getWarnLevel(),logObject)};Logger.prototype.error=function(logObject){return this.log(getErrorLevel(),logObject)};Logger.prototype.fatal=function(logObject){return this.log(getFatalLevel(),logObject)};Logger.prototype.fatalException=function(logObject,e){return this.log(getFatalLevel(),logObject,e)};return Logger}();JL.Logger=Logger;function createAjaxAppender(appenderName){return new AjaxAppender(appenderName)}JL.createAjaxAppender=createAjaxAppender;function createConsoleAppender(appenderName){return new ConsoleAppender(appenderName)}JL.createConsoleAppender=createConsoleAppender;var defaultAppender;if(typeof window!=="undefined"){defaultAppender=new AjaxAppender("")}else{defaultAppender=new ConsoleAppender("")}JL.__=new JL.Logger("");JL.__.setOptions({level:JL.getDebugLevel(),appenders:[defaultAppender]})})(JL||(JL={}));if(typeof exports!=="undefined"){exports.__esModule=true;exports.JL=JL}var define;if(typeof define=="function"&&define.amd){define("jsnlog",[],function(){return JL})}if(typeof __jsnlog_configure=="function"){__jsnlog_configure(JL)}if(typeof window!=="undefined"&&!window.onerror){window.onerror=function(errorMsg,url,lineNumber,column,errorObj){JL("onerrorLogger").fatalException({msg:"Uncaught Exception",errorMsg:errorMsg?errorMsg.message||errorMsg:"",url:url,"line number":lineNumber,column:column},errorObj);return false}}if(typeof window!=="undefined"&&!window.onunhandledrejection){window.onunhandledrejection=function(event){JL("onerrorLogger").fatalException({msg:"unhandledrejection",errorMsg:event.reason?event.reason.message:event.message||null},event.reason)}}},{}],8:[function(require,module,exports){"use strict";function Mime(){this._types=Object.create(null);this._extensions=Object.create(null);for(let i=0;i<arguments.length;i++){this.define(arguments[i])}this.define=this.define.bind(this);this.getType=this.getType.bind(this);this.getExtension=this.getExtension.bind(this)}Mime.prototype.define=function(typeMap,force){for(let type in typeMap){let extensions=typeMap[type].map(function(t){return t.toLowerCase()});type=type.toLowerCase();for(let i=0;i<extensions.length;i++){const ext=extensions[i];if(ext[0]==="*"){continue}if(!force&&ext in this._types){throw new Error('Attempt to change mapping for "'+ext+'" extension from "'+this._types[ext]+'" to "'+type+'". Pass `force=true` to allow this, otherwise remove "'+ext+'" from the list of extensions for "'+type+'".')}this._types[ext]=type}if(force||!this._extensions[type]){const ext=extensions[0];this._extensions[type]=ext[0]!=="*"?ext:ext.substr(1)}}};Mime.prototype.getType=function(path){path=String(path);let last=path.replace(/^.*[/\\]/,"").toLowerCase();let ext=last.replace(/^.*\./,"").toLowerCase();let hasPath=last.length<path.length;let hasDot=ext.length<last.length-1;return(hasDot||!hasPath)&&this._types[ext]||null};Mime.prototype.getExtension=function(type){type=/^\s*([^;\s]*)/.test(type)&&RegExp.$1;return type&&this._extensions[type.toLowerCase()]||null};module.exports=Mime},{}],9:[function(require,module,exports){"use strict";let Mime=require("./Mime");module.exports=new Mime(require("./types/standard"),require("./types/other"))},{"./Mime":8,"./types/other":10,"./types/standard":11}],10:[function(require,module,exports){module.exports={"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}},{}],11:[function(require,module,exports){module.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}},{}],12:[function(require,module,exports){var protocols=["stun:","turn:"];module.exports=function(input){var url=(input||{}).url||input;var protocol;var parts;var output={};if(typeof url!="string"&&!(url instanceof String)){return input}url=url.trim();protocol=protocols[protocols.indexOf(url.slice(0,5))];if(!protocol){return input}url=url.slice(5);parts=url.split("@");output.username=input.username;output.credential=input.credential;if(parts.length>1){url=parts[1];parts=parts[0].split(":");output.username=parts[0];output.credential=(input||{}).credential||parts[1]||""}output.url=protocol+url;output.urls=[output.url];return output}},{}],13:[function(require,module,exports){(function(global){(function(){(function(){"use strict";var objectTypes={function:true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var maxSafeInteger=Math.pow(2,53)-1;var reOpera=/\bOpera/;var thisBinding=this;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var toString=objectProto.toString;function capitalize(string){string=String(string);return string.charAt(0).toUpperCase()+string.slice(1)}function cleanupOS(os,pattern,label){var data={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};if(pattern&&label&&/^Win/i.test(os)&&!/^Windows Phone /i.test(os)&&(data=data[/[\d.]+$/.exec(os)])){os="Windows "+data}os=String(os);if(pattern&&label){os=os.replace(RegExp(pattern,"i"),label)}os=format(os.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0]);return os}function each(object,callback){var index=-1,length=object?object.length:0;if(typeof length=="number"&&length>-1&&length<=maxSafeInteger){while(++index<length){callback(object[index],index,object)}}else{forOwn(object,callback)}}function format(string){string=trim(string);return/^(?:webOS|i(?:OS|P))/.test(string)?string:capitalize(string)}function forOwn(object,callback){for(var key in object){if(hasOwnProperty.call(object,key)){callback(object[key],key,object)}}}function getClassOf(value){return value==null?capitalize(value):toString.call(value).slice(8,-1)}function isHostType(object,property){var type=object!=null?typeof object[property]:"number";return!/^(?:boolean|number|string|undefined)$/.test(type)&&(type=="object"?!!object[property]:true)}function qualify(string){return String(string).replace(/([ -])(?!$)/g,"$1?")}function reduce(array,callback){var accumulator=null;each(array,function(value,index){accumulator=callback(accumulator,value,index,array)});return accumulator}function trim(string){return String(string).replace(/^ +| +$/g,"")}function parse(ua){var context=root;var isCustomContext=ua&&typeof ua=="object"&&getClassOf(ua)!="String";if(isCustomContext){context=ua;ua=null}var nav=context.navigator||{};var userAgent=nav.userAgent||"";ua||(ua=userAgent);var isModuleScope=isCustomContext||thisBinding==oldRoot;var likeChrome=isCustomContext?!!nav.likeChrome:/\bChrome\b/.test(ua)&&!/internal|\n/i.test(toString.toString());var objectClass="Object",airRuntimeClass=isCustomContext?objectClass:"ScriptBridgingProxyObject",enviroClass=isCustomContext?objectClass:"Environment",javaClass=isCustomContext&&context.java?"JavaPackage":getClassOf(context.java),phantomClass=isCustomContext?objectClass:"RuntimeObject";var java=/\bJava/.test(javaClass)&&context.java;var rhino=java&&getClassOf(context.environment)==enviroClass;var alpha=java?"a":"α";var beta=java?"b":"β";var doc=context.document||{};var opera=context.operamini||context.opera;var operaClass=reOpera.test(operaClass=isCustomContext&&opera?opera["[[Class]]"]:getClassOf(opera))?operaClass:opera=null;var data;var arch=ua;var description=[];var prerelease=null;var useFeatures=ua==userAgent;var version=useFeatures&&opera&&typeof opera.version=="function"&&opera.version();var isSpecialCasedOS;var layout=getLayout([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"]);var name=getName(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Electron","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel","K-Meleon","Konqueror","Lunascape","Maxthon",{label:"Microsoft Edge",pattern:"(?:Edge|Edg|EdgA|EdgiOS)"},"Midori","Nook Browser","PaleMoon","PhantomJS","Raven","Rekonq","RockMelt",{label:"Samsung Internet",pattern:"SamsungBrowser"},"SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser",{label:"SRWare Iron",pattern:"Iron"},"Sunrise","Swiftfox","Vivaldi","Waterfox","WebPositive",{label:"Yandex Browser",pattern:"YaBrowser"},{label:"UC Browser",pattern:"UCBrowser"},"Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chromium","Chrome",{label:"Chrome",pattern:"(?:HeadlessChrome)"},{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"Firefox for iOS",pattern:"FxiOS"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]);var product=getProduct([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},{label:"Galaxy S5",pattern:"SM-G900"},{label:"Galaxy S6",pattern:"SM-G920"},{label:"Galaxy S6 Edge",pattern:"SM-G925"},{label:"Galaxy S7",pattern:"SM-G930"},{label:"Galaxy S7 Edge",pattern:"SM-G935"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nexus","Nook","PlayBook","PlayStation Vita","PlayStation","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]);var manufacturer=getManufacturer({Apple:{iPad:1,iPhone:1,iPod:1},Alcatel:{},Archos:{},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1,Nexus:1},HP:{TouchPad:1},HTC:{},Huawei:{},Lenovo:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Oppo:{},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{PlayStation:1,"PlayStation Vita":1},Xiaomi:{Mi:1,Redmi:1}});var os=getOS(["Windows Phone","KaiOS","Android","CentOS",{label:"Chrome OS",pattern:"CrOS"},"Debian",{label:"DragonFly BSD",pattern:"DragonFly"},"Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","OpenBSD","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Tizen","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);function getLayout(guesses){return reduce(guesses,function(result,guess){return result||RegExp("\\b"+(guess.pattern||qualify(guess))+"\\b","i").exec(ua)&&(guess.label||guess)})}function getManufacturer(guesses){return reduce(guesses,function(result,value,key){return result||(value[product]||value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)]||RegExp("\\b"+qualify(key)+"(?:\\b|\\w*\\d)","i").exec(ua))&&key})}function getName(guesses){return reduce(guesses,function(result,guess){return result||RegExp("\\b"+(guess.pattern||qualify(guess))+"\\b","i").exec(ua)&&(guess.label||guess)})}function getOS(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);if(!result&&(result=RegExp("\\b"+pattern+"(?:/[\\d.]+|[ \\w.]*)","i").exec(ua))){result=cleanupOS(result,pattern,guess.label||guess)}return result})}function getProduct(guesses){return reduce(guesses,function(result,guess){var pattern=guess.pattern||qualify(guess);if(!result&&(result=RegExp("\\b"+pattern+" *\\d+[.\\w_]*","i").exec(ua)||RegExp("\\b"+pattern+" *\\w+-[\\w]*","i").exec(ua)||RegExp("\\b"+pattern+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(ua))){if((result=String(guess.label&&!RegExp(pattern,"i").test(guess.label)?guess.label:result).split("/"))[1]&&!/[\d.]+/.test(result[0])){result[0]+=" "+result[1]}guess=guess.label||guess;result=format(result[0].replace(RegExp(pattern,"i"),guess).replace(RegExp("; *(?:"+guess+"[_-])?","i")," ").replace(RegExp("("+guess+")[-_.]?(\\w)","i"),"$1 $2"))}return result})}function getVersion(patterns){return reduce(patterns,function(result,pattern){return result||(RegExp(pattern+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(ua)||0)[1]||null})}function toStringPlatform(){return this.description||""}layout&&(layout=[layout]);if(/\bAndroid\b/.test(os)&&!product&&(data=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(ua))){product=trim(data[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null}if(manufacturer&&!product){product=getProduct([manufacturer])}else if(manufacturer&&product){product=product.replace(RegExp("^("+qualify(manufacturer)+")[-_.\\s]","i"),manufacturer+" ").replace(RegExp("^("+qualify(manufacturer)+")[-_.]?(\\w)","i"),manufacturer+" $2")}if(data=/\bGoogle TV\b/.exec(product)){product=data[0]}if(/\bSimulator\b/i.test(ua)){product=(product?product+" ":"")+"Simulator"}if(name=="Opera Mini"&&/\bOPiOS\b/.test(ua)){description.push("running in Turbo/Uncompressed mode")}if(name=="IE"&&/\blike iPhone OS\b/.test(ua)){data=parse(ua.replace(/like iPhone OS/,""));manufacturer=data.manufacturer;product=data.product}else if(/^iP/.test(product)){name||(name="Safari");os="iOS"+((data=/ OS ([\d_]+)/i.exec(ua))?" "+data[1].replace(/_/g,"."):"")}else if(name=="Konqueror"&&/^Linux\b/i.test(os)){os="Kubuntu"}else if(manufacturer&&manufacturer!="Google"&&(/Chrome/.test(name)&&!/\bMobile Safari\b/i.test(ua)||/\bVita\b/.test(product))||/\bAndroid\b/.test(os)&&/^Chrome/.test(name)&&/\bVersion\//i.test(ua)){name="Android Browser";os=/\bAndroid\b/.test(os)?os:"Android"}else if(name=="Silk"){if(!/\bMobi/i.test(ua)){os="Android";description.unshift("desktop mode")}if(/Accelerated *= *true/i.test(ua)){description.unshift("accelerated")}}else if(name=="UC Browser"&&/\bUCWEB\b/.test(ua)){description.push("speed mode")}else if(name=="PaleMoon"&&(data=/\bFirefox\/([\d.]+)\b/.exec(ua))){description.push("identifying as Firefox "+data[1])}else if(name=="Firefox"&&(data=/\b(Mobile|Tablet|TV)\b/i.exec(ua))){os||(os="Firefox OS");product||(product=data[1])}else if(!name||(data=!/\bMinefield\b/i.test(ua)&&/\b(?:Firefox|Safari)\b/.exec(name))){if(name&&!product&&/[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data+"/")+8))){name=null}if((data=product||manufacturer||os)&&(product||manufacturer||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))){name=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os)?os:data)+" Browser"}}else if(name=="Electron"&&(data=(/\bChrome\/([\d.]+)\b/.exec(ua)||0)[1])){description.push("Chromium "+data)}if(!version){version=getVersion(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",qualify(name),"(?:Firefox|Minefield|NetFront)"])}if(data=layout=="iCab"&&parseFloat(version)>3&&"WebKit"||/\bOpera\b/.test(name)&&(/\bOPR\b/.test(ua)?"Blink":"Presto")||/\b(?:Midori|Nook|Safari)\b/i.test(ua)&&!/^(?:Trident|EdgeHTML)$/.test(layout)&&"WebKit"||!layout&&/\bMSIE\b/i.test(ua)&&(os=="Mac OS"?"Tasman":"Trident")||layout=="WebKit"&&/\bPlayStation\b(?! Vita\b)/i.test(name)&&"NetFront"){layout=[data]}if(name=="IE"&&(data=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua)||0)[1])){name+=" Mobile";os="Windows Phone "+(/\+$/.test(data)?data:data+".x");description.unshift("desktop mode")}else if(/\bWPDesktop\b/i.test(ua)){name="IE Mobile";os="Windows Phone 8.x";description.unshift("desktop mode");version||(version=(/\brv:([\d.]+)/.exec(ua)||0)[1])}else if(name!="IE"&&layout=="Trident"&&(data=/\brv:([\d.]+)/.exec(ua))){if(name){description.push("identifying as "+name+(version?" "+version:""))}name="IE";version=data[1]}if(useFeatures){if(isHostType(context,"global")){if(java){data=java.lang.System;arch=data.getProperty("os.arch");os=os||data.getProperty("os.name")+" "+data.getProperty("os.version")}if(rhino){try{version=context.require("ringo/engine").version.join(".");name="RingoJS"}catch(e){if((data=context.system)&&data.global.system==context.system){name="Narwhal";os||(os=data[0].os||null)}}if(!name){name="Rhino"}}else if(typeof context.process=="object"&&!context.process.browser&&(data=context.process)){if(typeof data.versions=="object"){if(typeof data.versions.electron=="string"){description.push("Node "+data.versions.node);name="Electron";version=data.versions.electron}else if(typeof data.versions.nw=="string"){description.push("Chromium "+version,"Node "+data.versions.node);name="NW.js";version=data.versions.nw}}if(!name){name="Node.js";arch=data.arch;os=data.platform;version=/[\d.]+/.exec(data.version);version=version?version[0]:null}}}else if(getClassOf(data=context.runtime)==airRuntimeClass){name="Adobe AIR";os=data.flash.system.Capabilities.os}else if(getClassOf(data=context.phantom)==phantomClass){name="PhantomJS";version=(data=data.version||null)&&data.major+"."+data.minor+"."+data.patch}else if(typeof doc.documentMode=="number"&&(data=/\bTrident\/(\d+)/i.exec(ua))){version=[version,doc.documentMode];if((data=+data[1]+4)!=version[1]){description.push("IE "+version[1]+" mode");layout&&(layout[1]="");version[1]=data}version=name=="IE"?String(version[1].toFixed(1)):version[0]}else if(typeof doc.documentMode=="number"&&/^(?:Chrome|Firefox)\b/.test(name)){description.push("masking as "+name+" "+version);name="IE";version="11.0";layout=["Trident"];os="Windows"}os=os&&format(os)}if(version&&(data=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version)||/(?:alpha|beta)(?: ?\d)?/i.exec(ua+";"+(useFeatures&&nav.appMinorVersion))||/\bMinefield\b/i.test(ua)&&"a")){prerelease=/b/i.test(data)?"beta":"alpha";version=version.replace(RegExp(data+"\\+?$"),"")+(prerelease=="beta"?beta:alpha)+(/\d+\+?/.exec(data)||"")}if(name=="Fennec"||name=="Firefox"&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(os)){name="Firefox Mobile"}else if(name=="Maxthon"&&version){version=version.replace(/\.[\d.]+/,".x")}else if(/\bXbox\b/i.test(product)){if(product=="Xbox 360"){os=null}if(product=="Xbox 360"&&/\bIEMobile\b/.test(ua)){description.unshift("mobile mode")}}else if((/^(?:Chrome|IE|Opera)$/.test(name)||name&&!product&&!/Browser|Mobi/.test(name))&&(os=="Windows CE"||/Mobi/i.test(ua))){name+=" Mobile"}else if(name=="IE"&&useFeatures){try{if(context.external===null){description.unshift("platform preview")}}catch(e){description.unshift("embedded")}}else if((/\bBlackBerry\b/.test(product)||/\bBB10\b/.test(ua))&&(data=(RegExp(product.replace(/ +/g," *")+"/([.\\d]+)","i").exec(ua)||0)[1]||version)){data=[data,/BB10/.test(ua)];os=(data[1]?(product=null,manufacturer="BlackBerry"):"Device Software")+" "+data[0];version=null}else if(this!=forOwn&&product!="Wii"&&(useFeatures&&opera||/Opera/.test(name)&&/\b(?:MSIE|Firefox)\b/i.test(ua)||name=="Firefox"&&/\bOS X (?:\d+\.){2,}/.test(os)||name=="IE"&&(os&&!/^Win/.test(os)&&version>5.5||/\bWindows XP\b/.test(os)&&version>8||version==8&&!/\bTrident\b/.test(ua)))&&!reOpera.test(data=parse.call(forOwn,ua.replace(reOpera,"")+";"))&&data.name){data="ing as "+data.name+((data=data.version)?" "+data:"");if(reOpera.test(name)){if(/\bIE\b/.test(data)&&os=="Mac OS"){os=null}data="identify"+data}else{data="mask"+data;if(operaClass){name=format(operaClass.replace(/([a-z])([A-Z])/g,"$1 $2"))}else{name="Opera"}if(/\bIE\b/.test(data)){os=null}if(!useFeatures){version=null}}layout=["Presto"];description.push(data)}if(data=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua)||0)[1]){data=[parseFloat(data.replace(/\.(\d)$/,".0$1")),data];if(name=="Safari"&&data[1].slice(-1)=="+"){name="WebKit Nightly";prerelease="alpha";version=data[1].slice(0,-1)}else if(version==data[1]||version==(data[2]=(/\bSafari\/([\d.]+\+?)/i.exec(ua)||0)[1])){version=null}data[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(ua)||0)[1];if(data[0]==537.36&&data[2]==537.36&&parseFloat(data[1])>=28&&layout=="WebKit"){layout=["Blink"]}if(!useFeatures||!likeChrome&&!data[1]){layout&&(layout[1]="like Safari");data=(data=data[0],data<400?1:data<500?2:data<526?3:data<533?4:data<534?"4+":data<535?5:data<537?6:data<538?7:data<601?8:data<602?9:data<604?10:data<606?11:data<608?12:"12")}else{layout&&(layout[1]="like Chrome");data=data[1]||(data=data[0],data<530?1:data<532?2:data<532.05?3:data<533?4:data<534.03?5:data<534.07?6:data<534.1?7:data<534.13?8:data<534.16?9:data<534.24?10:data<534.3?11:data<535.01?12:data<535.02?"13+":data<535.07?15:data<535.11?16:data<535.19?17:data<536.05?18:data<536.1?19:data<537.01?20:data<537.11?"21+":data<537.13?23:data<537.18?24:data<537.24?25:data<537.36?26:layout!="Blink"?"27":"28")}layout&&(layout[1]+=" "+(data+=typeof data=="number"?".x":/[.+]/.test(data)?"":"+"));if(name=="Safari"&&(!version||parseInt(version)>45)){version=data}else if(name=="Chrome"&&/\bHeadlessChrome/i.test(ua)){description.unshift("headless")}}if(name=="Opera"&&(data=/\bzbov|zvav$/.exec(os))){name+=" ";description.unshift("desktop mode");if(data=="zvav"){name+="Mini";version=null}else{name+="Mobile"}os=os.replace(RegExp(" *"+data+"$"),"")}else if(name=="Safari"&&/\bChrome\b/.exec(layout&&layout[1])){description.unshift("desktop mode");name="Chrome Mobile";version=null;if(/\bOS X\b/.test(os)){manufacturer="Apple";os="iOS 4.3+"}else{os=null}}else if(/\bSRWare Iron\b/.test(name)&&!version){version=getVersion("Chrome")}if(version&&version.indexOf(data=/[\d.]+$/.exec(os))==0&&ua.indexOf("/"+data+"-")>-1){os=trim(os.replace(data,""))}if(os&&os.indexOf(name)!=-1&&!RegExp(name+" OS").test(os)){os=os.replace(RegExp(" *"+qualify(name)+" *"),"")}if(layout&&!/\b(?:Avant|Nook)\b/.test(name)&&(/Browser|Lunascape|Maxthon/.test(name)||name!="Safari"&&/^iOS/.test(os)&&/\bSafari\b/.test(layout[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(name)&&layout[1])){(data=layout[layout.length-1])&&description.push(data)}if(description.length){description=["("+description.join("; ")+")"]}if(manufacturer&&product&&product.indexOf(manufacturer)<0){description.push("on "+manufacturer)}if(product){description.push((/^on /.test(description[description.length-1])?"":"on ")+product)}if(os){data=/ ([\d.+]+)$/.exec(os);isSpecialCasedOS=data&&os.charAt(os.length-data[0].length-1)=="/";os={architecture:32,family:data&&!isSpecialCasedOS?os.replace(data[0],""):os,version:data?data[1]:null,toString:function(){var version=this.version;return this.family+(version&&!isSpecialCasedOS?" "+version:"")+(this.architecture==64?" 64-bit":"")}}}if((data=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch))&&!/\bi686\b/i.test(arch)){if(os){os.architecture=64;os.family=os.family.replace(RegExp(" *"+data),"")}if(name&&(/\bWOW64\b/i.test(ua)||useFeatures&&/\w(?:86|32)$/.test(nav.cpuClass||nav.platform)&&!/\bWin64; x64\b/i.test(ua))){description.unshift("32-bit")}}else if(os&&/^OS X/.test(os.family)&&name=="Chrome"&&parseFloat(version)>=39){os.architecture=64}ua||(ua=null);var platform={};platform.description=ua;platform.layout=layout&&layout[0];platform.manufacturer=manufacturer;platform.name=name;platform.prerelease=prerelease;platform.product=product;platform.ua=ua;platform.version=name&&version;platform.os=os||{architecture:null,family:null,version:null,toString:function(){return"null"}};platform.parse=parse;platform.toString=toStringPlatform;if(platform.version){description.unshift(version)}if(platform.name){description.unshift(name)}if(os&&name&&!(os==String(os).split(" ")[0]&&(os==name.split(" ")[0]||product))){description.push(product?"("+os+")":"on "+os)}if(description.length){platform.description=description.join(" ")}return platform}var platform=parse();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root.platform=platform;define(function(){return platform})}else if(freeExports&&freeModule){forOwn(platform,function(value,key){freeExports[key]=value})}else{root.platform=platform}}).call(this)}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],14:[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}},{}],15:[function(require,module,exports){"use strict";const debug=require("../internal/debug");const{MAX_LENGTH:MAX_LENGTH,MAX_SAFE_INTEGER:MAX_SAFE_INTEGER}=require("../internal/constants");const{safeRe:re,t:t}=require("../internal/re");const parseOptions=require("../internal/parse-options");const{compareIdentifiers:compareIdentifiers}=require("../internal/identifiers");class SemVer{constructor(version,options){options=parseOptions(options);if(version instanceof SemVer){if(version.loose===!!options.loose&&version.includePrerelease===!!options.includePrerelease){return version}else{version=version.version}}else if(typeof version!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)}if(version.length>MAX_LENGTH){throw new TypeError(`version is longer than ${MAX_LENGTH} characters`)}debug("SemVer",version,options);this.options=options;this.loose=!!options.loose;this.includePrerelease=!!options.includePrerelease;const m=version.trim().match(options.loose?re[t.LOOSE]:re[t.FULL]);if(!m){throw new TypeError(`Invalid Version: ${version}`)}this.raw=version;this.major=+m[1];this.minor=+m[2];this.patch=+m[3];if(this.major>MAX_SAFE_INTEGER||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>MAX_SAFE_INTEGER||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>MAX_SAFE_INTEGER||this.patch<0){throw new TypeError("Invalid patch version")}if(!m[4]){this.prerelease=[]}else{this.prerelease=m[4].split(".").map(id=>{if(/^[0-9]+$/.test(id)){const num=+id;if(num>=0&&num<MAX_SAFE_INTEGER){return num}}return id})}this.build=m[5]?m[5].split("."):[];this.format()}format(){this.version=`${this.major}.${this.minor}.${this.patch}`;if(this.prerelease.length){this.version+=`-${this.prerelease.join(".")}`}return this.version}toString(){return this.version}compare(other){debug("SemVer.compare",this.version,this.options,other);if(!(other instanceof SemVer)){if(typeof other==="string"&&other===this.version){return 0}other=new SemVer(other,this.options)}if(other.version===this.version){return 0}return this.compareMain(other)||this.comparePre(other)}compareMain(other){if(!(other instanceof SemVer)){other=new SemVer(other,this.options)}if(this.major<other.major){return-1}if(this.major>other.major){return 1}if(this.minor<other.minor){return-1}if(this.minor>other.minor){return 1}if(this.patch<other.patch){return-1}if(this.patch>other.patch){return 1}return 0}comparePre(other){if(!(other instanceof SemVer)){other=new SemVer(other,this.options)}if(this.prerelease.length&&!other.prerelease.length){return-1}else if(!this.prerelease.length&&other.prerelease.length){return 1}else if(!this.prerelease.length&&!other.prerelease.length){return 0}let i=0;do{const a=this.prerelease[i];const b=other.prerelease[i];debug("prerelease compare",i,a,b);if(a===undefined&&b===undefined){return 0}else if(b===undefined){return 1}else if(a===undefined){return-1}else if(a===b){continue}else{return compareIdentifiers(a,b)}}while(++i)}compareBuild(other){if(!(other instanceof SemVer)){other=new SemVer(other,this.options)}let i=0;do{const a=this.build[i];const b=other.build[i];debug("build compare",i,a,b);if(a===undefined&&b===undefined){return 0}else if(b===undefined){return 1}else if(a===undefined){return-1}else if(a===b){continue}else{return compareIdentifiers(a,b)}}while(++i)}inc(release,identifier,identifierBase){if(release.startsWith("pre")){if(!identifier&&identifierBase===false){throw new Error("invalid increment argument: identifier is empty")}if(identifier){const match=`-${identifier}`.match(this.options.loose?re[t.PRERELEASELOOSE]:re[t.PRERELEASE]);if(!match||match[1]!==identifier){throw new Error(`invalid identifier: ${identifier}`)}}}switch(release){case"premajor":this.prerelease.length=0;this.patch=0;this.minor=0;this.major++;this.inc("pre",identifier,identifierBase);break;case"preminor":this.prerelease.length=0;this.patch=0;this.minor++;this.inc("pre",identifier,identifierBase);break;case"prepatch":this.prerelease.length=0;this.inc("patch",identifier,identifierBase);this.inc("pre",identifier,identifierBase);break;case"prerelease":if(this.prerelease.length===0){this.inc("patch",identifier,identifierBase)}this.inc("pre",identifier,identifierBase);break;case"release":if(this.prerelease.length===0){throw new Error(`version ${this.raw} is not a prerelease`)}this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0){this.major++}this.minor=0;this.patch=0;this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0){this.minor++}this.patch=0;this.prerelease=[];break;case"patch":if(this.prerelease.length===0){this.patch++}this.prerelease=[];break;case"pre":{const base=Number(identifierBase)?1:0;if(this.prerelease.length===0){this.prerelease=[base]}else{let i=this.prerelease.length;while(--i>=0){if(typeof this.prerelease[i]==="number"){this.prerelease[i]++;i=-2}}if(i===-1){if(identifier===this.prerelease.join(".")&&identifierBase===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(base)}}if(identifier){let prerelease=[identifier,base];if(identifierBase===false){prerelease=[identifier]}if(compareIdentifiers(this.prerelease[0],identifier)===0){if(isNaN(this.prerelease[1])){this.prerelease=prerelease}}else{this.prerelease=prerelease}}break}default:throw new Error(`invalid increment argument: ${release}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}}module.exports=SemVer},{"../internal/constants":18,"../internal/debug":19,"../internal/identifiers":20,"../internal/parse-options":21,"../internal/re":22}],16:[function(require,module,exports){"use strict";const SemVer=require("../classes/semver");const major=(a,loose)=>new SemVer(a,loose).major;module.exports=major},{"../classes/semver":15}],17:[function(require,module,exports){"use strict";const SemVer=require("../classes/semver");const minor=(a,loose)=>new SemVer(a,loose).minor;module.exports=minor},{"../classes/semver":15}],18:[function(require,module,exports){"use strict";const SEMVER_SPEC_VERSION="2.0.0";const MAX_LENGTH=256;const MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;const MAX_SAFE_COMPONENT_LENGTH=16;const MAX_SAFE_BUILD_LENGTH=MAX_LENGTH-6;const RELEASE_TYPES=["major","premajor","minor","preminor","patch","prepatch","prerelease"];module.exports={MAX_LENGTH:MAX_LENGTH,MAX_SAFE_COMPONENT_LENGTH:MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH:MAX_SAFE_BUILD_LENGTH,MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,RELEASE_TYPES:RELEASE_TYPES,SEMVER_SPEC_VERSION:SEMVER_SPEC_VERSION,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},{}],19:[function(require,module,exports){(function(process){(function(){"use strict";const debug=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...args)=>console.error("SEMVER",...args):()=>{};module.exports=debug}).call(this)}).call(this,require("_process"))},{_process:14}],20:[function(require,module,exports){"use strict";const numeric=/^[0-9]+$/;const compareIdentifiers=(a,b)=>{if(typeof a==="number"&&typeof b==="number"){return a===b?0:a<b?-1:1}const anum=numeric.test(a);const bnum=numeric.test(b);if(anum&&bnum){a=+a;b=+b}return a===b?0:anum&&!bnum?-1:bnum&&!anum?1:a<b?-1:1};const rcompareIdentifiers=(a,b)=>compareIdentifiers(b,a);module.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},{}],21:[function(require,module,exports){"use strict";const looseOption=Object.freeze({loose:true});const emptyOpts=Object.freeze({});const parseOptions=options=>{if(!options){return emptyOpts}if(typeof options!=="object"){return looseOption}return options};module.exports=parseOptions},{}],22:[function(require,module,exports){"use strict";const{MAX_SAFE_COMPONENT_LENGTH:MAX_SAFE_COMPONENT_LENGTH,MAX_SAFE_BUILD_LENGTH:MAX_SAFE_BUILD_LENGTH,MAX_LENGTH:MAX_LENGTH}=require("./constants");const debug=require("./debug");exports=module.exports={};const re=exports.re=[];const safeRe=exports.safeRe=[];const src=exports.src=[];const safeSrc=exports.safeSrc=[];const t=exports.t={};let R=0;const LETTERDASHNUMBER="[a-zA-Z0-9-]";const safeRegexReplacements=[["\\s",1],["\\d",MAX_LENGTH],[LETTERDASHNUMBER,MAX_SAFE_BUILD_LENGTH]];const makeSafeRegex=value=>{for(const[token,max]of safeRegexReplacements){value=value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`)}return value};const createToken=(name,value,isGlobal)=>{const safe=makeSafeRegex(value);const index=R++;debug(name,index,value);t[name]=index;src[index]=value;safeSrc[index]=safe;re[index]=new RegExp(value,isGlobal?"g":undefined);safeRe[index]=new RegExp(safe,isGlobal?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);createToken("MAINVERSION",`(${src[t.NUMERICIDENTIFIER]})\\.`+`(${src[t.NUMERICIDENTIFIER]})\\.`+`(${src[t.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.`+`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.`+`(${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASE",`(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${LETTERDASHNUMBER}+`);createToken("BUILD",`(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);createToken("FULL",`^${src[t.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);createToken("LOOSE",`^${src[t.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${src[t.XRANGEIDENTIFIER]})`+`(?:\\.(${src[t.XRANGEIDENTIFIER]})`+`(?:\\.(${src[t.XRANGEIDENTIFIER]})`+`(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])"+"(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})`+`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`+`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);createToken("COERCE",`${src[t.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",src[t.COERCEPLAIN]+`(?:${src[t.PRERELEASE]})?`+`(?:${src[t.BUILD]})?`+`(?:$|[^\\d])`);createToken("COERCERTL",src[t.COERCE],true);createToken("COERCERTLFULL",src[t.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${src[t.LONETILDE]}\\s+`,true);exports.tildeTrimReplace="$1~";createToken("TILDE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${src[t.LONECARET]}\\s+`,true);exports.caretTrimReplace="$1^";createToken("CARET",`^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`,true);exports.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${src[t.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${src[t.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${src[t.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${src[t.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},{"./constants":18,"./debug":19}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"v1",{enumerable:true,get:function(){return _v.default}});Object.defineProperty(exports,"v3",{enumerable:true,get:function(){return _v2.default}});Object.defineProperty(exports,"v4",{enumerable:true,get:function(){return _v3.default}});Object.defineProperty(exports,"v5",{enumerable:true,get:function(){return _v4.default}});Object.defineProperty(exports,"NIL",{enumerable:true,get:function(){return _nil.default}});Object.defineProperty(exports,"version",{enumerable:true,get:function(){return _version.default}});Object.defineProperty(exports,"validate",{enumerable:true,get:function(){return _validate.default}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return _stringify.default}});Object.defineProperty(exports,"parse",{enumerable:true,get:function(){return _parse.default}});var _v=_interopRequireDefault(require("./v1.js"));var _v2=_interopRequireDefault(require("./v3.js"));var _v3=_interopRequireDefault(require("./v4.js"));var _v4=_interopRequireDefault(require("./v5.js"));var _nil=_interopRequireDefault(require("./nil.js"));var _version=_interopRequireDefault(require("./version.js"));var _validate=_interopRequireDefault(require("./validate.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":25,"./parse.js":26,"./stringify.js":30,"./v1.js":31,"./v3.js":32,"./v4.js":34,"./v5.js":35,"./validate.js":36,"./version.js":37}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;function md5(bytes){if(typeof bytes==="string"){const msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(let i=0;i<msg.length;++i){bytes[i]=msg.charCodeAt(i)}}return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes),bytes.length*8))}function md5ToHexEncodedArray(input){const output=[];const length32=input.length*32;const hexTab="0123456789abcdef";for(let i=0;i<length32;i+=8){const x=input[i>>5]>>>i%32&255;const hex=parseInt(hexTab.charAt(x>>>4&15)+hexTab.charAt(x&15),16);output.push(hex)}return output}function getOutputLength(inputLength8){return(inputLength8+64>>>9<<4)+14+1}function wordsToMd5(x,len){x[len>>5]|=128<<len%32;x[getOutputLength(len)-1]=len;let a=1732584193;let b=-271733879;let c=-1732584194;let d=271733878;for(let i=0;i<x.length;i+=16){const olda=a;const oldb=b;const oldc=c;const oldd=d;a=md5ff(a,b,c,d,x[i],7,-680876936);d=md5ff(d,a,b,c,x[i+1],12,-389564586);c=md5ff(c,d,a,b,x[i+2],17,606105819);b=md5ff(b,c,d,a,x[i+3],22,-1044525330);a=md5ff(a,b,c,d,x[i+4],7,-176418897);d=md5ff(d,a,b,c,x[i+5],12,1200080426);c=md5ff(c,d,a,b,x[i+6],17,-1473231341);b=md5ff(b,c,d,a,x[i+7],22,-45705983);a=md5ff(a,b,c,d,x[i+8],7,1770035416);d=md5ff(d,a,b,c,x[i+9],12,-1958414417);c=md5ff(c,d,a,b,x[i+10],17,-42063);b=md5ff(b,c,d,a,x[i+11],22,-1990404162);a=md5ff(a,b,c,d,x[i+12],7,1804603682);d=md5ff(d,a,b,c,x[i+13],12,-40341101);c=md5ff(c,d,a,b,x[i+14],17,-1502002290);b=md5ff(b,c,d,a,x[i+15],22,1236535329);a=md5gg(a,b,c,d,x[i+1],5,-165796510);d=md5gg(d,a,b,c,x[i+6],9,-1069501632);c=md5gg(c,d,a,b,x[i+11],14,643717713);b=md5gg(b,c,d,a,x[i],20,-373897302);a=md5gg(a,b,c,d,x[i+5],5,-701558691);d=md5gg(d,a,b,c,x[i+10],9,38016083);c=md5gg(c,d,a,b,x[i+15],14,-660478335);b=md5gg(b,c,d,a,x[i+4],20,-405537848);a=md5gg(a,b,c,d,x[i+9],5,568446438);d=md5gg(d,a,b,c,x[i+14],9,-1019803690);c=md5gg(c,d,a,b,x[i+3],14,-187363961);b=md5gg(b,c,d,a,x[i+8],20,1163531501);a=md5gg(a,b,c,d,x[i+13],5,-1444681467);d=md5gg(d,a,b,c,x[i+2],9,-51403784);c=md5gg(c,d,a,b,x[i+7],14,1735328473);b=md5gg(b,c,d,a,x[i+12],20,-1926607734);a=md5hh(a,b,c,d,x[i+5],4,-378558);d=md5hh(d,a,b,c,x[i+8],11,-2022574463);c=md5hh(c,d,a,b,x[i+11],16,1839030562);b=md5hh(b,c,d,a,x[i+14],23,-35309556);a=md5hh(a,b,c,d,x[i+1],4,-1530992060);d=md5hh(d,a,b,c,x[i+4],11,1272893353);c=md5hh(c,d,a,b,x[i+7],16,-155497632);b=md5hh(b,c,d,a,x[i+10],23,-1094730640);a=md5hh(a,b,c,d,x[i+13],4,681279174);d=md5hh(d,a,b,c,x[i],11,-358537222);c=md5hh(c,d,a,b,x[i+3],16,-722521979);b=md5hh(b,c,d,a,x[i+6],23,76029189);a=md5hh(a,b,c,d,x[i+9],4,-640364487);d=md5hh(d,a,b,c,x[i+12],11,-421815835);c=md5hh(c,d,a,b,x[i+15],16,530742520);b=md5hh(b,c,d,a,x[i+2],23,-995338651);a=md5ii(a,b,c,d,x[i],6,-198630844);d=md5ii(d,a,b,c,x[i+7],10,1126891415);c=md5ii(c,d,a,b,x[i+14],15,-1416354905);b=md5ii(b,c,d,a,x[i+5],21,-57434055);a=md5ii(a,b,c,d,x[i+12],6,1700485571);d=md5ii(d,a,b,c,x[i+3],10,-1894986606);c=md5ii(c,d,a,b,x[i+10],15,-1051523);b=md5ii(b,c,d,a,x[i+1],21,-2054922799);a=md5ii(a,b,c,d,x[i+8],6,1873313359);d=md5ii(d,a,b,c,x[i+15],10,-30611744);c=md5ii(c,d,a,b,x[i+6],15,-1560198380);b=md5ii(b,c,d,a,x[i+13],21,1309151649);a=md5ii(a,b,c,d,x[i+4],6,-145523070);d=md5ii(d,a,b,c,x[i+11],10,-1120210379);c=md5ii(c,d,a,b,x[i+2],15,718787259);b=md5ii(b,c,d,a,x[i+9],21,-343485551);a=safeAdd(a,olda);b=safeAdd(b,oldb);c=safeAdd(c,oldc);d=safeAdd(d,oldd)}return[a,b,c,d]}function bytesToWords(input){if(input.length===0){return[]}const length8=input.length*8;const output=new Uint32Array(getOutputLength(length8));for(let i=0;i<length8;i+=8){output[i>>5]|=(input[i/8]&255)<<i%32}return output}function safeAdd(x,y){const lsw=(x&65535)+(y&65535);const msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bitRotateLeft(num,cnt){return num<<cnt|num>>>32-cnt}function md5cmn(q,a,b,x,s,t){return safeAdd(bitRotateLeft(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b)}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}var _default=md5;exports.default=_default},{}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default="00000000-0000-0000-0000-000000000000";exports.default=_default},{}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function parse(uuid){if(!(0,_validate.default)(uuid)){throw TypeError("Invalid UUID")}let v;const arr=new Uint8Array(16);arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24;arr[1]=v>>>16&255;arr[2]=v>>>8&255;arr[3]=v&255;arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8;arr[5]=v&255;arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8;arr[7]=v&255;arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8;arr[9]=v&255;arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255;arr[11]=v/4294967296&255;arr[12]=v>>>24&255;arr[13]=v>>>16&255;arr[14]=v>>>8&255;arr[15]=v&255;return arr}var _default=parse;exports.default=_default},{"./validate.js":36}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;exports.default=_default},{}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=rng;let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){getRandomValues=typeof crypto!=="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!=="undefined"&&typeof msCrypto.getRandomValues==="function"&&msCrypto.getRandomValues.bind(msCrypto);if(!getRandomValues){throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported")}}return getRandomValues(rnds8)}},{}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<<n|x>>>32-n}function sha1(bytes){const K=[1518500249,1859775393,2400959708,3395469782];const H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof bytes==="string"){const msg=unescape(encodeURIComponent(bytes));bytes=[];for(let i=0;i<msg.length;++i){bytes.push(msg.charCodeAt(i))}}else if(!Array.isArray(bytes)){bytes=Array.prototype.slice.call(bytes)}bytes.push(128);const l=bytes.length/4+2;const N=Math.ceil(l/16);const M=new Array(N);for(let i=0;i<N;++i){const arr=new Uint32Array(16);for(let j=0;j<16;++j){arr[j]=bytes[i*64+j*4]<<24|bytes[i*64+j*4+1]<<16|bytes[i*64+j*4+2]<<8|bytes[i*64+j*4+3]}M[i]=arr}M[N-1][14]=(bytes.length-1)*8/Math.pow(2,32);M[N-1][14]=Math.floor(M[N-1][14]);M[N-1][15]=(bytes.length-1)*8&4294967295;for(let i=0;i<N;++i){const W=new Uint32Array(80);for(let t=0;t<16;++t){W[t]=M[i][t]}for(let t=16;t<80;++t){W[t]=ROTL(W[t-3]^W[t-8]^W[t-14]^W[t-16],1)}let a=H[0];let b=H[1];let c=H[2];let d=H[3];let e=H[4];for(let t=0;t<80;++t){const s=Math.floor(t/20);const T=ROTL(a,5)+f(s,b,c,d)+e+K[s]+W[t]>>>0;e=d;d=c;c=ROTL(b,30)>>>0;b=a;a=T}H[0]=H[0]+a>>>0;H[1]=H[1]+b>>>0;H[2]=H[2]+c>>>0;H[3]=H[3]+d>>>0;H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,H[0]&255,H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,H[1]&255,H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,H[2]&255,H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,H[3]&255,H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,H[4]&255]}var _default=sha1;exports.default=_default},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const byteToHex=[];for(let i=0;i<256;++i){byteToHex.push((i+256).toString(16).substr(1))}function stringify(arr,offset=0){const uuid=(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();if(!(0,_validate.default)(uuid)){throw TypeError("Stringified UUID is invalid")}return uuid}var _default=stringify;exports.default=_default},{"./validate.js":36}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let _nodeId;let _clockseq;let _lastMSecs=0;let _lastNSecs=0;function v1(options,buf,offset){let i=buf&&offset||0;const b=buf||new Array(16);options=options||{};let node=options.node||_nodeId;let clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;if(node==null||clockseq==null){const seedBytes=options.random||(options.rng||_rng.default)();if(node==null){node=_nodeId=[seedBytes[0]|1,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]}if(clockseq==null){clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&16383}}let msecs=options.msecs!==undefined?options.msecs:Date.now();let nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;const dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&16383}if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0}if(nsecs>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=122192928e5;const tl=((msecs&268435455)*1e4+nsecs)%4294967296;b[i++]=tl>>>24&255;b[i++]=tl>>>16&255;b[i++]=tl>>>8&255;b[i++]=tl&255;const tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255;b[i++]=tmh&255;b[i++]=tmh>>>24&15|16;b[i++]=tmh>>>16&255;b[i++]=clockseq>>>8|128;b[i++]=clockseq&255;for(let n=0;n<6;++n){b[i+n]=node[n]}return buf||(0,_stringify.default)(b)}var _default=v1;exports.default=_default},{"./rng.js":28,"./stringify.js":30}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const v3=(0,_v.default)("v3",48,_md.default);var _default=v3;exports.default=_default},{"./md5.js":24,"./v35.js":33}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=_default;exports.URL=exports.DNS=void 0;var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function stringToBytes(str){str=unescape(encodeURIComponent(str));const bytes=[];for(let i=0;i<str.length;++i){bytes.push(str.charCodeAt(i))}return bytes}const DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8";exports.DNS=DNS;const URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";exports.URL=URL;function _default(name,version,hashfunc){function generateUUID(value,namespace,buf,offset){if(typeof value==="string"){value=stringToBytes(value)}if(typeof namespace==="string"){namespace=(0,_parse.default)(namespace)}if(namespace.length!==16){throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)")}let bytes=new Uint8Array(16+value.length);bytes.set(namespace);bytes.set(value,namespace.length);bytes=hashfunc(bytes);bytes[6]=bytes[6]&15|version;bytes[8]=bytes[8]&63|128;if(buf){offset=offset||0;for(let i=0;i<16;++i){buf[offset+i]=bytes[i]}return buf}return(0,_stringify.default)(bytes)}try{generateUUID.name=name}catch(err){}generateUUID.DNS=DNS;generateUUID.URL=URL;return generateUUID}},{"./parse.js":26,"./stringify.js":30}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function v4(options,buf,offset){options=options||{};const rnds=options.random||(options.rng||_rng.default)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){offset=offset||0;for(let i=0;i<16;++i){buf[offset+i]=rnds[i]}return buf}return(0,_stringify.default)(rnds)}var _default=v4;exports.default=_default},{"./rng.js":28,"./stringify.js":30}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _sha=_interopRequireDefault(require("./sha1.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const v5=(0,_v.default)("v5",80,_sha.default);var _default=v5;exports.default=_default},{"./sha1.js":29,"./v35.js":33}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _regex=_interopRequireDefault(require("./regex.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function validate(uuid){return typeof uuid==="string"&&_regex.default.test(uuid)}var _default=validate;exports.default=_default},{"./regex.js":27}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function version(uuid){if(!(0,_validate.default)(uuid)){throw TypeError("Invalid UUID")}return parseInt(uuid.substr(14,1),16)}var _default=version;exports.default=_default},{"./validate.js":36}],38:[function(require,module,exports){module.exports=WildEmitter;function WildEmitter(){}WildEmitter.mixin=function(constructor){var prototype=constructor.prototype||constructor;prototype.isWildEmitter=true;prototype.on=function(event,groupName,fn){this.callbacks=this.callbacks||{};var hasGroup=arguments.length===3,group=hasGroup?arguments[1]:undefined,func=hasGroup?arguments[2]:arguments[1];func._groupName=group;(this.callbacks[event]=this.callbacks[event]||[]).push(func);return this};prototype.once=function(event,groupName,fn){var self=this,hasGroup=arguments.length===3,group=hasGroup?arguments[1]:undefined,func=hasGroup?arguments[2]:arguments[1];function on(){self.off(event,on);func.apply(this,arguments)}this.on(event,group,on);return this};prototype.releaseGroup=function(groupName){this.callbacks=this.callbacks||{};var item,i,len,handlers;for(item in this.callbacks){handlers=this.callbacks[item];for(i=0,len=handlers.length;i<len;i++){if(handlers[i]._groupName===groupName){handlers.splice(i,1);i--;len--}}}return this};prototype.off=function(event,fn){this.callbacks=this.callbacks||{};var callbacks=this.callbacks[event],i;if(!callbacks)return this;if(arguments.length===1){delete this.callbacks[event];return this}i=callbacks.indexOf(fn);if(i!==-1){callbacks.splice(i,1);if(callbacks.length===0){delete this.callbacks[event]}}return this};prototype.emit=function(event){this.callbacks=this.callbacks||{};var args=[].slice.call(arguments,1),callbacks=this.callbacks[event],specialCallbacks=this.getWildcardCallbacks(event),i,len,item,listeners;if(callbacks){listeners=callbacks.slice();for(i=0,len=listeners.length;i<len;++i){if(!listeners[i]){break}listeners[i].apply(this,args)}}if(specialCallbacks){len=specialCallbacks.length;listeners=specialCallbacks.slice();for(i=0,len=listeners.length;i<len;++i){if(!listeners[i]){break}listeners[i].apply(this,[event].concat(args))}}return this};prototype.getWildcardCallbacks=function(eventName){this.callbacks=this.callbacks||{};var item,split,result=[];for(item in this.callbacks){split=item.split("*");if(item==="*"||split.length===2&&eventName.slice(0,split[0].length)===split[0]){result=result.concat(this.callbacks[item])}}return result}};WildEmitter.mixin(WildEmitter)},{}],39:[function(require,module,exports){(function(exports){"use strict";function EventEmitter(){}var proto=EventEmitter.prototype;var originalGlobalValue=exports.EventEmitter;function indexOfListener(listeners,listener){var i=listeners.length;while(i--){if(listeners[i].listener===listener){return i}}return-1}function alias(name){return function aliasClosure(){return this[name].apply(this,arguments)}}proto.getListeners=function getListeners(evt){var events=this._getEvents();var response;var key;if(evt instanceof RegExp){response={};for(key in events){if(events.hasOwnProperty(key)&&evt.test(key)){response[key]=events[key]}}}else{response=events[evt]||(events[evt]=[])}return response};proto.flattenListeners=function flattenListeners(listeners){var flatListeners=[];var i;for(i=0;i<listeners.length;i+=1){flatListeners.push(listeners[i].listener)}return flatListeners};proto.getListenersAsObject=function getListenersAsObject(evt){var listeners=this.getListeners(evt);var response;if(listeners instanceof Array){response={};response[evt]=listeners}return response||listeners};function isValidListener(listener){if(typeof listener==="function"||listener instanceof RegExp){return true}else if(listener&&typeof listener==="object"){return isValidListener(listener.listener)}else{return false}}proto.addListener=function addListener(evt,listener){if(!isValidListener(listener)){throw new TypeError("listener must be a function")}var listeners=this.getListenersAsObject(evt);var listenerIsWrapped=typeof listener==="object";var key;for(key in listeners){if(listeners.hasOwnProperty(key)&&indexOfListener(listeners[key],listener)===-1){listeners[key].push(listenerIsWrapped?listener:{listener:listener,once:false})}}return this};proto.on=alias("addListener");proto.addOnceListener=function addOnceListener(evt,listener){return this.addListener(evt,{listener:listener,once:true})};proto.once=alias("addOnceListener");proto.defineEvent=function defineEvent(evt){this.getListeners(evt);return this};proto.defineEvents=function defineEvents(evts){for(var i=0;i<evts.length;i+=1){this.defineEvent(evts[i])}return this};proto.removeListener=function removeListener(evt,listener){var listeners=this.getListenersAsObject(evt);var index;var key;for(key in listeners){if(listeners.hasOwnProperty(key)){index=indexOfListener(listeners[key],listener);if(index!==-1){listeners[key].splice(index,1)}}}return this};proto.off=alias("removeListener");proto.addListeners=function addListeners(evt,listeners){return this.manipulateListeners(false,evt,listeners)};proto.removeListeners=function removeListeners(evt,listeners){return this.manipulateListeners(true,evt,listeners)};proto.manipulateListeners=function manipulateListeners(remove,evt,listeners){var i;var value;var single=remove?this.removeListener:this.addListener;var multiple=remove?this.removeListeners:this.addListeners;if(typeof evt==="object"&&!(evt instanceof RegExp)){for(i in evt){if(evt.hasOwnProperty(i)&&(value=evt[i])){if(typeof value==="function"){single.call(this,i,value)}else{multiple.call(this,i,value)}}}}else{i=listeners.length;while(i--){single.call(this,evt,listeners[i])}}return this};proto.removeEvent=function removeEvent(evt){var type=typeof evt;var events=this._getEvents();var key;if(type==="string"){delete events[evt]}else if(evt instanceof RegExp){for(key in events){if(events.hasOwnProperty(key)&&evt.test(key)){delete events[key]}}}else{delete this._events}return this};proto.removeAllListeners=alias("removeEvent");proto.emitEvent=function emitEvent(evt,args){var listenersMap=this.getListenersAsObject(evt);var listeners;var listener;var i;var key;var response;for(key in listenersMap){if(listenersMap.hasOwnProperty(key)){listeners=listenersMap[key].slice(0);for(i=0;i<listeners.length;i++){listener=listeners[i];if(listener.once===true){this.removeListener(evt,listener.listener)}response=listener.listener.apply(this,args||[]);if(response===this._getOnceReturnValue()){this.removeListener(evt,listener.listener)}}}}return this};proto.trigger=alias("emitEvent");proto.emit=function emit(evt){var args=Array.prototype.slice.call(arguments,1);return this.emitEvent(evt,args)};proto.setOnceReturnValue=function setOnceReturnValue(value){this._onceReturnValue=value;return this};proto._getOnceReturnValue=function _getOnceReturnValue(){if(this.hasOwnProperty("_onceReturnValue")){return this._onceReturnValue}else{return true}};proto._getEvents=function _getEvents(){return this._events||(this._events={})};EventEmitter.noConflict=function noConflict(){exports.EventEmitter=originalGlobalValue;return EventEmitter};if(typeof define==="function"&&define.amd){define(function(){return EventEmitter})}else if(typeof module==="object"&&module.exports){module.exports=EventEmitter}else{exports.EventEmitter=EventEmitter}})(typeof window!=="undefined"?window:this||{})},{}],40:[function(require,module,exports){module.exports={author:"OpenVidu",dependencies:{events:"3.3.0",freeice:"2.2.2",hark:"1.2.3",inherits:"2.0.4",jsnlog:"2.30.0",mime:"2.6.0",platform:"1.3.6",semver:"7.7.3",uuid:"^8.3.2","wolfy87-eventemitter":"5.2.9"},description:"OpenVidu Browser",devDependencies:{"@types/node":"24.10.1","@types/platform":"1.3.6","@typescript-eslint/eslint-plugin":"8.47.0","@typescript-eslint/parser":"8.47.0",browserify:"17.0.1",eslint:"9.39.1","eslint-import-resolver-typescript":"4.4.4","eslint-plugin-import":"2.32.0","patch-package":"^8.0.1",prettier:"3.6.2",terser:"5.44.1",tsify:"5.0.4",typedoc:"0.28.14",typescript:"5.9.3","undici-types":"7.16.0"},license:"Apache-2.0",main:"lib/index.js",name:"openvidu-browser",repository:{type:"git",url:"git://github.com/OpenVidu/openvidu"},scripts:{browserify:"VERSION=${VERSION:-dev}; mkdir -p static/js/ && cd src && ../node_modules/browserify/bin/cmd.js Main.ts -p [ tsify ] --exclude kurento-browser-extensions --debug -o ../static/js/openvidu-browser-$VERSION.js -v","browserify-prod":"VERSION=${VERSION:-dev}; mkdir -p static/js/ && cd src && ../node_modules/browserify/bin/cmd.js --debug Main.ts -p [ tsify ] --exclude kurento-browser-extensions | ../node_modules/terser/bin/terser --source-map content=inline --output ../static/js/openvidu-browser-$VERSION.min.js",build:"npm run lint && npm run beautify && cd src/OpenVidu && ./../../node_modules/typescript/bin/tsc && cd ../.. && ./node_modules/typescript/bin/tsc --declaration src/index.ts --outDir ./lib --sourceMap --target es2015 --module commonjs --moduleResolution node --lib dom,es2015,scripthost && rm -rf ./ts4.4 && mkdir -p ./ts4.4/lib && cp -r ./lib ./ts4.4 && find ./ts4.4/lib -type f ! -iname '*.d.ts' -delete && ./config/replace_for_ts44.sh",docs:"./generate-docs.sh",lint:"eslint . --ext .ts",beautify:"prettier --write ."},types:"lib/index.d.ts",typesVersions:{"<4.4":{"*":["ts4.4/*"]}},version:"2.32.2"}},{}],41:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const OpenVidu_1=require("./OpenVidu/OpenVidu");const jsnlog_1=require("jsnlog");if(typeof globalThis!=="undefined"){globalThis["OpenVidu"]=OpenVidu_1.OpenVidu}jsnlog_1.JL.setOptions({enabled:false})},{"./OpenVidu/OpenVidu":46,jsnlog:7}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Connection=void 0;const Stream_1=require("./Stream");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class Connection{constructor(session,connectionOptions){this.session=session;this.disposed=false;let msg="'Connection' created ";if(!!connectionOptions.role){this.localOptions=connectionOptions;this.connectionId=this.localOptions.id;this.creationTime=this.localOptions.createdAt;this.data=this.localOptions.metadata;this.rpcSessionId=this.localOptions.sessionId;this.role=this.localOptions.role;this.record=this.localOptions.record;msg+="(local)"}else{this.remoteOptions=connectionOptions;this.connectionId=this.remoteOptions.id;this.creationTime=this.remoteOptions.createdAt;if(this.remoteOptions.metadata){this.data=this.remoteOptions.metadata}if(this.remoteOptions.streams){this.initRemoteStreams(this.remoteOptions.streams)}msg+="(remote) with 'connectionId' ["+this.remoteOptions.id+"]"}logger.info(msg)}sendIceCandidate(candidate){if(!this.disposed){logger.debug((!!this.stream.outboundStreamOpts?"Local":"Remote")+"candidate for"+this.connectionId,candidate);this.session.openvidu.sendRequest("onIceCandidate",{endpointName:this.connectionId,candidate:candidate.candidate,sdpMid:candidate.sdpMid,sdpMLineIndex:candidate.sdpMLineIndex},(error,response)=>{if(error){logger.error("Error sending ICE candidate: "+JSON.stringify(error));this.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.session,ExceptionEvent_1.ExceptionEventName.ICE_CANDIDATE_ERROR,this.session,"There was an unexpected error on the server-side processing an ICE candidate generated and sent by the client-side",error)])}})}else{logger.warn(`Connection ${this.connectionId} disposed when trying to send an ICE candidate. ICE candidate not sent`)}}initRemoteStreams(options){options.forEach(opts=>{const streamOptions={id:opts.id,createdAt:opts.createdAt,connection:this,hasAudio:opts.hasAudio,hasVideo:opts.hasVideo,audioActive:opts.audioActive,videoActive:opts.videoActive,typeOfVideo:opts.typeOfVideo,frameRate:opts.frameRate,videoDimensions:!!opts.videoDimensions?JSON.parse(opts.videoDimensions):undefined,filter:!!opts.filter?opts.filter:undefined};const stream=new Stream_1.Stream(this.session,streamOptions);this.addStream(stream)});logger.info("Remote 'Connection' with 'connectionId' ["+this.connectionId+"] is now configured for receiving Streams with options: ",this.stream.inboundStreamOpts)}addStream(stream){stream.connection=this;this.stream=stream}removeStream(){delete this.stream}dispose(){this.disposed=true;this.removeStream()}}exports.Connection=Connection},{"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Logger/OpenViduLogger":81,"./Stream":49}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventDispatcher=void 0;const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const EventEmitter=require("wolfy87-eventemitter");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class EventDispatcher{constructor(){this.userHandlerArrowHandler=new WeakMap;this.ee=new EventEmitter}onAux(type,message,handler){const arrowHandler=event=>{if(event){logger.debug(message,event)}else{logger.debug(message)}handler(event)};this.userHandlerArrowHandler.set(handler,arrowHandler);this.ee.on(type,arrowHandler);return this}onceAux(type,message,handler){const arrowHandler=event=>{if(event){logger.debug(message,event)}else{logger.debug(message)}handler(event);this.userHandlerArrowHandler.delete(handler)};this.userHandlerArrowHandler.set(handler,arrowHandler);this.ee.once(type,arrowHandler);return this}offAux(type,handler){if(!handler){this.ee.removeAllListeners(type)}else{const arrowHandler=this.userHandlerArrowHandler.get(handler);if(!!arrowHandler){this.ee.off(type,arrowHandler)}this.userHandlerArrowHandler.delete(handler)}return this}}exports.EventDispatcher=EventDispatcher},{"../OpenViduInternal/Logger/OpenViduLogger":81,"wolfy87-eventemitter":39}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Filter=void 0;const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class Filter{constructor(type,options){this.handlers=new Map;this.type=type;this.options=options}execMethod(method,params){return new Promise((resolve,reject)=>{var _a;logger.info("Executing filter method to stream "+this.stream.streamId);let finalParams;const successExecMethod=triggerEvent=>{logger.info("Filter method successfully executed on Stream "+this.stream.streamId);const oldValue=Object.assign({},this.stream.filter);this.stream.filter.lastExecMethod={method:method,params:finalParams};if(triggerEvent){this.stream.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.stream.session,this.stream,"filter",this.stream.filter,oldValue,"execFilterMethod")]);this.stream.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.stream.streamManager,this.stream,"filter",this.stream.filter,oldValue,"execFilterMethod")])}return resolve()};if(this.type.startsWith("VB:")){if(typeof params==="string"){try{params=JSON.parse(params)}catch(error){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"Wrong params syntax: "+error))}}finalParams=params;if(method==="update"){if(!((_a=this.stream.virtualBackgroundSinkElements)===null||_a===void 0?void 0:_a.VB)){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"There is no Virtual Background filter applied"))}else{this.stream.virtualBackgroundSinkElements.VB.updateValues(params).then(()=>successExecMethod(false)).catch(error=>{if(error.name===OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR){return reject(new OpenViduError_1.OpenViduError(error.name,error.message))}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"Error updating values on Virtual Background filter: "+error))}})}}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,`Unknown Virtual Background method "${method}"`))}}else{let stringParams;if(typeof params!=="string"){try{stringParams=JSON.stringify(params)}catch(error){const errorMsg="'params' property must be a JSON formatted object";logger.error(errorMsg);return reject(errorMsg)}}else{stringParams=params}finalParams=stringParams;this.stream.session.openvidu.sendRequest("execFilterMethod",{streamId:this.stream.streamId,method:method,params:stringParams},(error,response)=>{if(error){logger.error("Error executing filter method for Stream "+this.stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to execute a filter method"))}else{return reject(error)}}else{return successExecMethod(true)}})}})}addEventListener(eventType,handler){return new Promise((resolve,reject)=>{logger.info("Adding filter event listener to event "+eventType+" to stream "+this.stream.streamId);this.stream.session.openvidu.sendRequest("addFilterEventListener",{streamId:this.stream.streamId,eventType:eventType},(error,response)=>{if(error){logger.error("Error adding filter event listener to event "+eventType+"for Stream "+this.stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to add a filter event listener"))}else{return reject(error)}}else{this.handlers.set(eventType,handler);logger.info("Filter event listener to event "+eventType+" successfully applied on Stream "+this.stream.streamId);return resolve()}})})}removeEventListener(eventType){return new Promise((resolve,reject)=>{logger.info("Removing filter event listener to event "+eventType+" to stream "+this.stream.streamId);this.stream.session.openvidu.sendRequest("removeFilterEventListener",{streamId:this.stream.streamId,eventType:eventType},(error,response)=>{if(error){logger.error("Error removing filter event listener to event "+eventType+"for Stream "+this.stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to add a filter event listener"))}else{return reject(error)}}else{this.handlers.delete(eventType);logger.info("Filter event listener to event "+eventType+" successfully removed on Stream "+this.stream.streamId);return resolve()}})})}}exports.Filter=Filter},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81}],45:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.LocalRecorder=void 0;const LocalRecorderState_1=require("../OpenViduInternal/Enums/LocalRecorderState");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const mime_1=__importDefault(require("mime"));const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class LocalRecorder{constructor(stream){this.stream=stream;this.chunks=[];platform=Platform_1.PlatformUtils.getInstance();this.connectionId=!!this.stream.connection?this.stream.connection.connectionId:"default-connection";this.id=this.stream.streamId+"_"+this.connectionId+"_localrecord";this.state=LocalRecorderState_1.LocalRecorderState.READY}record(options){return new Promise((resolve,reject)=>{try{if(typeof options==="string"||options instanceof String){return reject(`When calling LocalRecorder.record(options) parameter 'options' cannot be a string. Must be an object like { mimeType: "${options}" }`)}if(typeof MediaRecorder==="undefined"){logger.error("MediaRecorder not supported on your device. See compatibility in https://caniuse.com/#search=MediaRecorder");throw Error("MediaRecorder not supported on your device. See compatibility in https://caniuse.com/#search=MediaRecorder")}if(this.state!==LocalRecorderState_1.LocalRecorderState.READY){throw Error("'LocalRecord.record()' needs 'LocalRecord.state' to be 'READY' (current value: '"+this.state+"'). Call 'LocalRecorder.clean()' or init a new LocalRecorder before")}logger.log("Starting local recording of stream '"+this.stream.streamId+"' of connection '"+this.connectionId+"'");if(!options){options={mimeType:"video/webm"}}else if(!options.mimeType){options.mimeType="video/webm"}this.mediaRecorder=new MediaRecorder(this.stream.getMediaStream(),options);this.mediaRecorder.start()}catch(err){return reject(err)}this.mediaRecorder.ondataavailable=e=>{if(e.data.size>0){this.chunks.push(e.data)}};this.mediaRecorder.onerror=e=>{logger.error("MediaRecorder error: ",e)};this.mediaRecorder.onstart=()=>{logger.log("MediaRecorder started (state="+this.mediaRecorder.state+")")};this.mediaRecorder.onstop=()=>{this.onStopDefault()};this.mediaRecorder.onpause=()=>{logger.log("MediaRecorder paused (state="+this.mediaRecorder.state+")")};this.mediaRecorder.onresume=()=>{logger.log("MediaRecorder resumed (state="+this.mediaRecorder.state+")")};this.state=LocalRecorderState_1.LocalRecorderState.RECORDING;return resolve()})}stop(){return new Promise((resolve,reject)=>{try{if(this.state===LocalRecorderState_1.LocalRecorderState.READY||this.state===LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.stop()' needs 'LocalRecord.state' to be 'RECORDING' or 'PAUSED' (current value: '"+this.state+"'). Call 'LocalRecorder.start()' before")}this.mediaRecorder.onstop=()=>{this.onStopDefault();return resolve()};this.mediaRecorder.stop()}catch(e){return reject(e)}})}pause(){return new Promise((resolve,reject)=>{try{if(this.state!==LocalRecorderState_1.LocalRecorderState.RECORDING){return reject(Error("'LocalRecord.pause()' needs 'LocalRecord.state' to be 'RECORDING' (current value: '"+this.state+"'). Call 'LocalRecorder.start()' or 'LocalRecorder.resume()' before"))}this.mediaRecorder.pause();this.state=LocalRecorderState_1.LocalRecorderState.PAUSED;return resolve()}catch(error){return reject(error)}})}resume(){return new Promise((resolve,reject)=>{try{if(this.state!==LocalRecorderState_1.LocalRecorderState.PAUSED){throw Error("'LocalRecord.resume()' needs 'LocalRecord.state' to be 'PAUSED' (current value: '"+this.state+"'). Call 'LocalRecorder.pause()' before")}this.mediaRecorder.resume();this.state=LocalRecorderState_1.LocalRecorderState.RECORDING;return resolve()}catch(error){return reject(error)}})}preview(parentElement){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.preview()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before")}this.videoPreview=document.createElement("video");this.videoPreview.id=this.id;this.videoPreview.autoplay=true;if(platform.isSafariBrowser()){this.videoPreview.playsInline=true}if(typeof parentElement==="string"){const parentElementDom=document.getElementById(parentElement);if(parentElementDom){this.videoPreview=parentElementDom.appendChild(this.videoPreview)}}else{this.videoPreview=parentElement.appendChild(this.videoPreview)}this.videoPreview.src=this.videoPreviewSrc;return this.videoPreview}clean(){const f=()=>{delete this.blob;this.chunks=[];this.state=LocalRecorderState_1.LocalRecorderState.READY};if(this.state===LocalRecorderState_1.LocalRecorderState.RECORDING||this.state===LocalRecorderState_1.LocalRecorderState.PAUSED){this.stop().then(()=>f()).catch(()=>f())}else{f()}}download(){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.download()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before")}else{const a=document.createElement("a");a.style.display="none";document.body.appendChild(a);const url=globalThis.URL.createObjectURL(this.blob);a.href=url;a.download=this.id+"."+mime_1.default.getExtension(this.blob.type);a.click();globalThis.URL.revokeObjectURL(url);document.body.removeChild(a)}}getBlob(){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("Call 'LocalRecord.stop()' before getting Blob file")}else{return this.blob}}uploadAsBinary(endpoint,headers){return new Promise((resolve,reject)=>{if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){return reject(Error("'LocalRecord.uploadAsBinary()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before"))}else{const http=new XMLHttpRequest;http.open("POST",endpoint,true);if(typeof headers==="object"){for(const key of Object.keys(headers)){http.setRequestHeader(key,headers[key])}}http.onreadystatechange=()=>{if(http.readyState===4){if(http.status.toString().charAt(0)==="2"){return resolve(http.responseText)}else{return reject(http.status)}}};http.send(this.blob)}})}uploadAsMultipartfile(endpoint,headers){return new Promise((resolve,reject)=>{if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){return reject(Error("'LocalRecord.uploadAsMultipartfile()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before"))}else{const http=new XMLHttpRequest;http.open("POST",endpoint,true);if(typeof headers==="object"){for(const key of Object.keys(headers)){http.setRequestHeader(key,headers[key])}}const sendable=new FormData;sendable.append("file",this.blob,this.id+"."+mime_1.default.getExtension(this.blob.type));http.onreadystatechange=()=>{if(http.readyState===4){if(http.status.toString().charAt(0)==="2"){return resolve(http.responseText)}else{return reject(http.status)}}};http.send(sendable)}})}onStopDefault(){logger.log("MediaRecorder stopped (state="+this.mediaRecorder.state+")");this.blob=new Blob(this.chunks,{type:this.mediaRecorder.mimeType});this.chunks=[];this.videoPreviewSrc=globalThis.URL.createObjectURL(this.blob);this.state=LocalRecorderState_1.LocalRecorderState.FINISHED}}exports.LocalRecorder=LocalRecorder},{"../OpenViduInternal/Enums/LocalRecorderState":52,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,mime:9}],46:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||function(){var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)if(Object.prototype.hasOwnProperty.call(o,k))ar[ar.length]=k;return ar};return ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k=ownKeys(mod),i=0;i<k.length;i++)if(k[i]!=="default")__createBinding(result,mod,k[i]);__setModuleDefault(result,mod);return result}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.OpenVidu=void 0;const LocalRecorder_1=require("./LocalRecorder");const Publisher_1=require("./Publisher");const Session_1=require("./Session");const SessionDisconnectedEvent_1=require("../OpenViduInternal/Events/SessionDisconnectedEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const screenSharingAuto=__importStar(require("../OpenViduInternal/ScreenSharing/Screen-Capturing-Auto"));const screenSharing=__importStar(require("../OpenViduInternal/ScreenSharing/Screen-Capturing"));const EventEmitter=require("wolfy87-eventemitter");const RpcBuilder=require("../OpenViduInternal/KurentoUtils/kurento-jsonrpc");const packageJson=require("../../package.json");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class OpenVidu{constructor(){this.masterNodeHasCrashed=false;this.publishers=[];this.secret="";this.recorder=false;this.stt=false;this.life=-1;this.advancedConfiguration={};this.webrtcStatsInterval=-1;this.sendBrowserLogs="disabled";this.isAtLeastPro=false;this.isEnterprise=false;this.ee=new EventEmitter;platform=Platform_1.PlatformUtils.getInstance();this.libraryVersion=packageJson.version;logger.info("OpenVidu initialized");logger.info("Platform detected: "+platform.getDescription());logger.info("openvidu-browser version: "+this.libraryVersion);if(platform.isMobileDevice()||platform.isReactNative()){this.onOrientationChanged(()=>{this.publishers.forEach(publisher=>{if(publisher.stream.isLocalStreamPublished&&!!publisher.stream&&!!publisher.stream.hasVideo){this.sendNewVideoDimensionsIfRequired(publisher,"deviceRotated",75,10)}})})}}initSession(){this.session=new Session_1.Session(this);return this.session}initPublisher(targetElement,param2,param3){let properties;if(!!param2&&typeof param2!=="function"){properties=param2;properties={audioSource:typeof properties.audioSource!=="undefined"?properties.audioSource:undefined,frameRate:typeof MediaStreamTrack!=="undefined"&&properties.videoSource instanceof MediaStreamTrack?undefined:typeof properties.frameRate!=="undefined"?properties.frameRate:undefined,insertMode:typeof properties.insertMode!=="undefined"?typeof properties.insertMode==="string"?VideoInsertMode_1.VideoInsertMode[properties.insertMode]:properties.insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,mirror:typeof properties.mirror!=="undefined"?properties.mirror:true,publishAudio:typeof properties.publishAudio!=="undefined"?properties.publishAudio:true,publishVideo:typeof properties.publishVideo!=="undefined"?properties.publishVideo:true,resolution:typeof MediaStreamTrack!=="undefined"&&properties.videoSource instanceof MediaStreamTrack?undefined:typeof properties.resolution!=="undefined"?properties.resolution:"640x480",videoSource:typeof properties.videoSource!=="undefined"?properties.videoSource:undefined,videoSimulcast:properties.videoSimulcast,filter:properties.filter}}else{properties={insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,mirror:true,publishAudio:true,publishVideo:true,resolution:"640x480"}}const publisher=new Publisher_1.Publisher(targetElement,properties,this);let completionHandler;if(!!param2&&typeof param2==="function"){completionHandler=param2}else if(!!param3){completionHandler=param3}publisher.initialize().then(()=>{if(completionHandler!==undefined){completionHandler(undefined)}publisher.emitEvent("accessAllowed",[])}).catch(error=>{if(completionHandler!==undefined){completionHandler(error)}publisher.emitEvent("accessDenied",[error])});this.publishers.push(publisher);return publisher}initPublisherAsync(targetElement,properties){return new Promise((resolve,reject)=>{let publisher;const callback=error=>{if(!!error){return reject(error)}else{return resolve(publisher)}};if(!!properties){publisher=this.initPublisher(targetElement,properties,callback)}else{publisher=this.initPublisher(targetElement,callback)}})}initLocalRecorder(stream){return new LocalRecorder_1.LocalRecorder(stream)}checkSystemRequirements(){if(platform.isIPhoneOrIPad()){return platform.isIOSWithSafari()||platform.isChromeMobileBrowser()||platform.isFirefoxMobileBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isIonicIos()}return platform.isChromeBrowser()||platform.isChromeMobileBrowser()||platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()||platform.isOperaBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeBrowser()||platform.isEdgeMobileBrowser()||platform.isSamsungBrowser()||platform.isSafariBrowser()||platform.isAndroidBrowser()||platform.isElectron()||platform.isNodeJs()||platform.isMotorolaEdgeDevice()}checkScreenSharingCapabilities(){return platform.canScreenShare()}getDevices(){return new Promise((resolve,reject)=>{navigator.mediaDevices.enumerateDevices().then(deviceInfos=>{var _a;const devices=[];if(platform.isIonicAndroid()&&typeof cordova!="undefined"&&((_a=cordova===null||cordova===void 0?void 0:cordova.plugins)===null||_a===void 0?void 0:_a.EnumerateDevicesPlugin)){cordova.plugins.EnumerateDevicesPlugin.getEnumerateDevices().then(pluginDevices=>{let pluginAudioDevices=[];let videoDevices=[];let audioDevices=[];pluginAudioDevices=pluginDevices.filter(device=>device.kind==="audioinput");videoDevices=deviceInfos.filter(device=>device.kind==="videoinput");audioDevices=deviceInfos.filter(device=>device.kind==="audioinput");videoDevices.forEach((deviceInfo,index)=>{if(!deviceInfo.label){let label="";if(index===0){label="Front Camera"}else if(index===1){label="Back Camera"}else{label="Unknown Camera"}devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:label})}else{devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:deviceInfo.label})}});audioDevices.forEach((deviceInfo,index)=>{if(!deviceInfo.label){let label="";switch(index){case 0:label="Default";break;case 1:const defaultMatch=pluginAudioDevices.filter(d=>d.label.includes("Built"))[0];label=defaultMatch?defaultMatch.label:"Built-in Microphone";break;case 2:const wiredMatch=pluginAudioDevices.filter(d=>d.label.includes("Wired"))[0];if(wiredMatch){label=wiredMatch.label}else{label="Headset earpiece"}break;case 3:const wirelessMatch=pluginAudioDevices.filter(d=>d.label.includes("Bluetooth"))[0];label=wirelessMatch?wirelessMatch.label:"Wireless";break;default:label="Unknown Microphone";break}devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:label})}else{devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:deviceInfo.label})}});return resolve(devices)})}else{deviceInfos.forEach(deviceInfo=>{if(deviceInfo.kind==="audioinput"||deviceInfo.kind==="videoinput"){devices.push({kind:deviceInfo.kind,deviceId:deviceInfo.deviceId,label:deviceInfo.label})}});return resolve(devices)}}).catch(error=>{logger.error("Error getting devices",error);return reject(error)})})}getUserMedia(options){return __awaiter(this,void 0,void 0,function*(){var _a,_b;const askForAudioStreamOnly=(previousMediaStream,constraints)=>__awaiter(this,void 0,void 0,function*(){const definedAudioConstraint=constraints.audio===undefined?true:constraints.audio;const constraintsAux={audio:definedAudioConstraint,video:false};try{const audioOnlyStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);previousMediaStream.addTrack(audioOnlyStream.getAudioTracks()[0]);return previousMediaStream}catch(error){previousMediaStream.getAudioTracks().forEach(track=>{track.stop()});previousMediaStream.getVideoTracks().forEach(track=>{track.stop()});throw this.generateAudioDeviceError(error,constraintsAux)}});try{const myConstraints=yield this.generateMediaConstraints(options);if(!!myConstraints.videoTrack&&!!myConstraints.audioTrack||!!myConstraints.audioTrack&&((_a=myConstraints.constraints)===null||_a===void 0?void 0:_a.video)===false||!!myConstraints.videoTrack&&((_b=myConstraints.constraints)===null||_b===void 0?void 0:_b.audio)===false){return this.addAlreadyProvidedTracks(myConstraints,new MediaStream)}else{if(!!myConstraints.videoTrack){delete myConstraints.constraints.video}if(!!myConstraints.audioTrack){delete myConstraints.constraints.audio}let mustAskForAudioTrackLater=false;if(typeof options.videoSource==="string"){if(options.videoSource==="screen"||options.videoSource==="window"||platform.isElectron()&&options.videoSource.startsWith("screen:")){mustAskForAudioTrackLater=!myConstraints.audioTrack&&options.audioSource!==null&&options.audioSource!==false;if(navigator.mediaDevices["getDisplayMedia"]&&!platform.isElectron()){try{const mediaStream=yield navigator.mediaDevices["getDisplayMedia"]({video:true,audio:options.audioSource==="screen"});this.addAlreadyProvidedTracks(myConstraints,mediaStream);if(mustAskForAudioTrackLater){return yield askForAudioStreamOnly(mediaStream,myConstraints.constraints)}else{return mediaStream}}catch(error){let errorName=OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED;const errorMessage=error.toString();throw new OpenViduError_1.OpenViduError(errorName,errorMessage)}}else{}}else{}}const constraintsAux=mustAskForAudioTrackLater?{video:myConstraints.constraints.video}:myConstraints.constraints;try{const mediaStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);this.addAlreadyProvidedTracks(myConstraints,mediaStream);if(mustAskForAudioTrackLater){return yield askForAudioStreamOnly(mediaStream,myConstraints.constraints)}else{return mediaStream}}catch(error){let errorName;const errorMessage=error.toString();if(!(options.videoSource==="screen")){errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED}else{errorName=OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED}throw new OpenViduError_1.OpenViduError(errorName,errorMessage)}}}catch(error){throw error}})}enableProdMode(){logger.enableProdMode()}setAdvancedConfiguration(configuration){this.advancedConfiguration=configuration}onOrientationChanged(handler){globalThis.addEventListener("orientationchange",handler)}sendNewVideoDimensionsIfRequired(publisher,reason,WAIT_INTERVAL,MAX_ATTEMPTS){var _a,_b,_c,_d;let attempts=0;const oldWidth=((_b=(_a=publisher===null||publisher===void 0?void 0:publisher.stream)===null||_a===void 0?void 0:_a.videoDimensions)===null||_b===void 0?void 0:_b.width)||0;const oldHeight=((_d=(_c=publisher===null||publisher===void 0?void 0:publisher.stream)===null||_c===void 0?void 0:_c.videoDimensions)===null||_d===void 0?void 0:_d.height)||0;const repeatUntilChangeOrMaxAttempts=setInterval(()=>{attempts++;if(attempts>MAX_ATTEMPTS){clearTimeout(repeatUntilChangeOrMaxAttempts)}publisher.getVideoDimensions().then(newDimensions=>{if(newDimensions.width!==oldWidth||newDimensions.height!==oldHeight){clearTimeout(repeatUntilChangeOrMaxAttempts);this.sendVideoDimensionsChangedEvent(publisher,reason,oldWidth,oldHeight,newDimensions.width,newDimensions.height)}})},WAIT_INTERVAL)}sendVideoDimensionsChangedEvent(publisher,reason,oldWidth,oldHeight,newWidth,newHeight){publisher.stream.videoDimensions={width:newWidth||0,height:newHeight||0};this.sendRequest("streamPropertyChanged",{streamId:publisher.stream.streamId,property:"videoDimensions",newValue:JSON.stringify(publisher.stream.videoDimensions),reason:reason},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,"videoDimensions",publisher.stream.videoDimensions,{width:oldWidth,height:oldHeight},reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,"videoDimensions",publisher.stream.videoDimensions,{width:oldWidth,height:oldHeight},reason)]);this.session.sendVideoData(publisher)}})}sendTrackChangedEvent(publisher,oldLabel,newLabel,propertyType){const oldValue={label:oldLabel};const newValue={label:newLabel};const reason="trackReplaced";if(publisher.stream.isLocalStreamPublished){this.sendRequest("streamPropertyChanged",{streamId:publisher.stream.streamId,property:propertyType,newValue:newValue,reason:reason},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,propertyType,newValue,oldValue,reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,propertyType,newValue,oldValue,reason)])}})}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,propertyType,newValue,oldValue,reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,propertyType,newValue,oldValue,reason)])}}generateMediaConstraints(publisherProperties){return new Promise((resolve,reject)=>{const myConstraints={audioTrack:undefined,videoTrack:undefined,constraints:{audio:undefined,video:undefined}};const audioSource=publisherProperties.audioSource;const videoSource=publisherProperties.videoSource;if(audioSource===null||audioSource===false){myConstraints.constraints.audio=false}if(videoSource===null||videoSource===false){myConstraints.constraints.video=false}if(myConstraints.constraints.audio===false&&myConstraints.constraints.video===false){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.NO_INPUT_SOURCE_SET,"Properties 'audioSource' and 'videoSource' cannot be set to false or null at the same time"))}if(typeof MediaStreamTrack!=="undefined"&&audioSource instanceof MediaStreamTrack){myConstraints.audioTrack=audioSource}if(typeof MediaStreamTrack!=="undefined"&&videoSource instanceof MediaStreamTrack){myConstraints.videoTrack=videoSource}if(audioSource===undefined){myConstraints.constraints.audio=true}if(videoSource===undefined){myConstraints.constraints.video={width:{ideal:640},height:{ideal:480}}}if(videoSource!==null&&videoSource!==false){if(!!publisherProperties.resolution){const widthAndHeight=publisherProperties.resolution.toLowerCase().split("x");const idealWidth=Number(widthAndHeight[0]);const idealHeight=Number(widthAndHeight[1]);myConstraints.constraints.video={width:{ideal:idealWidth},height:{ideal:idealHeight}}}if(!!publisherProperties.frameRate){myConstraints.constraints.video.frameRate={ideal:publisherProperties.frameRate}}}this.configureDeviceIdOrScreensharing(myConstraints,publisherProperties,resolve,reject);return resolve(myConstraints)})}startWs(onConnectSucces){const config={heartbeat:5e3,ws:{uri:this.wsUri+"?sessionId="+this.session.sessionId,onconnected:onConnectSucces,ondisconnect:this.disconnectCallback.bind(this),onreconnecting:this.reconnectingCallback.bind(this),onreconnected:this.reconnectedCallback.bind(this),ismasternodecrashed:this.isMasterNodeCrashed.bind(this)},rpc:{requestTimeout:1e4,heartbeatRequestTimeout:5e3,participantJoined:this.session.onParticipantJoined.bind(this.session),participantPublished:this.session.onParticipantPublished.bind(this.session),participantUnpublished:this.session.onParticipantUnpublished.bind(this.session),participantLeft:this.session.onParticipantLeft.bind(this.session),participantEvicted:this.session.onParticipantEvicted.bind(this.session),recordingStarted:this.session.onRecordingStarted.bind(this.session),recordingStopped:this.session.onRecordingStopped.bind(this.session),broadcastStarted:this.session.onBroadcastStarted.bind(this.session),broadcastStopped:this.session.onBroadcastStopped.bind(this.session),sendMessage:this.session.onNewMessage.bind(this.session),streamPropertyChanged:this.session.onStreamPropertyChanged.bind(this.session),connectionPropertyChanged:this.session.onConnectionPropertyChanged.bind(this.session),networkQualityLevelChanged:this.session.onNetworkQualityLevelChangedChanged.bind(this.session),filterEventDispatched:this.session.onFilterEventDispatched.bind(this.session),iceCandidate:this.session.recvIceCandidate.bind(this.session),mediaError:this.session.onMediaError.bind(this.session),masterNodeCrashedNotification:this.onMasterNodeCrashedNotification.bind(this),forciblyReconnectSubscriber:this.session.onForciblyReconnectSubscriber.bind(this.session),speechToTextMessage:this.session.onSpeechToTextMessage.bind(this.session),speechToTextDisconnected:this.session.onSpeechToTextDisconnected.bind(this.session)}};this.jsonRpcClient=new RpcBuilder.clients.JsonRpcClient(config)}onMasterNodeCrashedNotification(response){console.error("Master Node has crashed");this.masterNodeHasCrashed=true;this.session.onLostConnection("nodeCrashed");this.jsonRpcClient.close(4103,"Master Node has crashed")}getWsReadyState(){return this.jsonRpcClient.getReadyState()}closeWs(){this.jsonRpcClient.close(4102,"Connection closed by client")}sendRequest(method,params,callback){var _a;if(params&¶ms instanceof Function){callback=params;params={}}logger.debug('Sending request: {method:"'+method+'", params: '+JSON.stringify(params)+"}");(_a=this.jsonRpcClient)===null||_a===void 0?void 0:_a.send(method,params,callback)}getWsUri(){return this.wsUri}getSecret(){return this.secret}getRecorder(){return this.recorder}getStt(){return this.stt}generateAudioDeviceError(error,constraints){if(error.name==="Error"){error.name=error.constructor.name}let errorName,errorMessage;switch(error.name.toLowerCase()){case"notfounderror":errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"notallowederror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"overconstrainederror":if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage="Audio input device with deviceId '"+constraints.audio.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Audio input device doesn't support the value passed for constraint '"+error.constraint+"'"}return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"notreadableerror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ALREADY_IN_USE;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);default:return new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_GENERIC_ERROR,error.toString())}}addAlreadyProvidedTracks(myConstraints,mediaStream,stream){if(!!myConstraints.videoTrack){mediaStream.addTrack(myConstraints.videoTrack);if(!!stream){if(!!myConstraints.constraints.video){stream.lastVideoTrackConstraints=myConstraints.constraints.video}else{stream.lastVideoTrackConstraints=myConstraints.videoTrack.getConstraints()}}}if(!!myConstraints.audioTrack){mediaStream.addTrack(myConstraints.audioTrack)}return mediaStream}configureDeviceIdOrScreensharing(myConstraints,publisherProperties,resolve,reject){const audioSource=publisherProperties.audioSource;const videoSource=publisherProperties.videoSource;if(typeof audioSource==="string"&&audioSource!=="screen"){myConstraints.constraints.audio={deviceId:{exact:audioSource}}}if(typeof videoSource==="string"){if(!this.isScreenShare(videoSource)){this.setVideoSource(myConstraints,videoSource);if(audioSource==="screen"){logger.warn('Parameter "audioSource" is set to "screen", which means rquesting audio from screen sharing source. But "videoSource" is not set to "screen". No audio source will be requested');myConstraints.constraints.audio=false}}else{if(!this.checkScreenSharingCapabilities()){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_SHARING_NOT_SUPPORTED,"You can only screen share in desktop Chrome, Firefox, Opera, Safari (>=13.0), Edge (>= 80) or Electron. Detected client: "+platform.getName()+" "+platform.getVersion());logger.error(error);return reject(error)}else{if(platform.isElectron()){const prefix="screen:";const videoSourceString=videoSource;const electronScreenId=videoSourceString.substr(videoSourceString.indexOf(prefix)+prefix.length);myConstraints.constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:electronScreenId}};return resolve(myConstraints)}else{if(!!this.advancedConfiguration.screenShareChromeExtension&&!(platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser())&&!navigator.mediaDevices["getDisplayMedia"]){screenSharing.getScreenConstraints((error,screenConstraints)=>{if(!!error||!!screenConstraints.mandatory&&screenConstraints.mandatory.chromeMediaSource==="screen"){if(error==="permission-denied"||error==="PermissionDeniedError"){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED,"You must allow access to one window of your desktop");logger.error(error);return reject(error)}else{const extensionId=this.advancedConfiguration.screenShareChromeExtension.split("/").pop().trim();screenSharing.getChromeExtensionStatus(extensionId,status=>{if(status==="installed-disabled"){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_DISABLED,"You must enable the screen extension");logger.error(error);return reject(error)}if(status==="not-installed"){const error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED,this.advancedConfiguration.screenShareChromeExtension);logger.error(error);return reject(error)}});return}}else{myConstraints.constraints.video=screenConstraints;return resolve(myConstraints)}});return}else{if(navigator.mediaDevices["getDisplayMedia"]){return resolve(myConstraints)}else{const firefoxString=platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()?publisherProperties.videoSource:undefined;screenSharingAuto.getScreenId(firefoxString,(error,sourceId,screenConstraints)=>{if(!!error){if(error==="not-installed"){const extensionUrl=!!this.advancedConfiguration.screenShareChromeExtension?this.advancedConfiguration.screenShareChromeExtension:"https://chrome.google.com/webstore/detail/openvidu-screensharing/lfcgfepafnobdloecchnfaclibenjold";const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED,extensionUrl);logger.error(err);return reject(err)}else if(error==="installed-disabled"){const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_DISABLED,"You must enable the screen extension");logger.error(err);return reject(err)}else if(error==="permission-denied"){const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED,"You must allow access to one window of your desktop");logger.error(err);return reject(err)}else{const err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"Unknown error when accessing screen share");logger.error(err);logger.error(error);return reject(err)}}else{myConstraints.constraints.video=screenConstraints.video;return resolve(myConstraints)}});return}}}}}}}setVideoSource(myConstraints,videoSource){if(!myConstraints.constraints.video){myConstraints.constraints.video={}}myConstraints.constraints.video["deviceId"]={exact:videoSource}}disconnectCallback(){logger.warn("Websocket connection lost");if(this.isRoomAvailable()){this.session.onLostConnection("networkDisconnect")}else{alert("Connection error. Please reload page.")}}reconnectingCallback(){logger.warn("Websocket connection lost (reconnecting)");if(!this.isRoomAvailable()){alert("Connection error. Please reload page.")}else{this.session.emitEvent("reconnecting",[])}}reconnectWebsocketThroughRpcConnectMethod(rpcSessionId){this.sendRequest("connect",{sessionId:rpcSessionId,reconnect:true},(error,response)=>{if(!!error){if(this.isMasterNodeCrashed()){logger.warn("Master Node has crashed!")}else{logger.error(error);const notifyLostConnection=(reason,errorMsg)=>{logger.warn(errorMsg);this.session.onLostConnection(reason);this.jsonRpcClient.close(4101,"Reconnection fault: "+errorMsg)};const rpcSessionStatus=()=>{if(this.life===-1){notifyLostConnection("networkDisconnect","WS successfully reconnected but the user was already evicted due to timeout")}else{this.sendRequest("sessionStatus",{sessionId:this.session.sessionId},(error,response)=>{if(error!=null){console.error("Error checking session status",error)}else{if(this.life===response.life){notifyLostConnection("networkDisconnect","WS successfully reconnected but the user was already evicted due to timeout")}else{notifyLostConnection("nodeCrashed","WS successfully reconnected to OpenVidu Server but your Master Node crashed")}}})}};if(error.code===40007&&error.message==="reconnection error"){console.error("Invalid RPC sessionId. Client network disconnection or Master Node crash");rpcSessionStatus()}else{rpcSessionStatus()}}}else{this.jsonRpcClient.resetPing();this.session.onRecoveredConnection()}})}reconnectedCallback(){logger.warn("Websocket reconnected");if(this.isRoomAvailable()){if(!!this.session.connection){this.reconnectWebsocketThroughRpcConnectMethod(this.session.connection.rpcSessionId)}else{logger.warn("There was no previous connection when running reconnection callback");const sessionDisconnectEvent=new SessionDisconnectedEvent_1.SessionDisconnectedEvent(this.session,"networkDisconnect");this.session.ee.emitEvent("sessionDisconnected",[sessionDisconnectEvent]);sessionDisconnectEvent.callDefaultBehavior()}}else{alert("Connection error. Please reload page.")}}isMasterNodeCrashed(){return this.masterNodeHasCrashed}isRoomAvailable(){if(this.session!==undefined&&this.session instanceof Session_1.Session){return true}else{logger.warn("Session instance not found");return false}}isScreenShare(videoSource){return videoSource==="screen"||videoSource==="window"||platform.isElectron()&&videoSource.startsWith("screen:")}}exports.OpenVidu=OpenVidu},{"../../package.json":40,"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/SessionDisconnectedEvent":64,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/KurentoUtils/kurento-jsonrpc":76,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/ScreenSharing/Screen-Capturing":84,"../OpenViduInternal/ScreenSharing/Screen-Capturing-Auto":83,"../OpenViduInternal/Utils/Platform":85,"./LocalRecorder":45,"./Publisher":47,"./Session":48,"wolfy87-eventemitter":39}],47:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.Publisher=void 0;const Session_1=require("./Session");const Stream_1=require("./Stream");const StreamManager_1=require("./StreamManager");const StreamEvent_1=require("../OpenViduInternal/Events/StreamEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const TypeOfVideo_1=require("../OpenViduInternal/Enums/TypeOfVideo");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class Publisher extends StreamManager_1.StreamManager{constructor(targEl,properties,openvidu){super(new Stream_1.Stream(!!openvidu.session?openvidu.session:new Session_1.Session(openvidu),{publisherProperties:properties,mediaConstraints:{}}),targEl);this.accessAllowed=false;this.isSubscribedToRemote=false;this.accessDenied=false;platform=Platform_1.PlatformUtils.getInstance();this.properties=properties;this.openvidu=openvidu;this.stream.ee.on("local-stream-destroyed",reason=>{this.stream.isLocalStreamPublished=false;const streamEvent=new StreamEvent_1.StreamEvent(true,this,"streamDestroyed",this.stream,reason);this.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior()})}publishAudio(enabled){if(this.stream.audioActive!==enabled){const affectedMediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();affectedMediaStream.getAudioTracks().forEach(track=>{track.enabled=enabled});if(!!this.session&&!!this.stream.streamId){this.session.openvidu.sendRequest("streamPropertyChanged",{streamId:this.stream.streamId,property:"audioActive",newValue:enabled,reason:"publishAudio"},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this.stream,"audioActive",enabled,!enabled,"publishAudio")]);this.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this,this.stream,"audioActive",enabled,!enabled,"publishAudio")]);this.session.sendVideoData(this.stream.streamManager)}})}this.stream.audioActive=enabled;logger.info("'Publisher' has "+(enabled?"published":"unpublished")+" its audio stream")}}publishVideo(enabled,resource){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){if(this.stream.videoActive!==enabled){const affectedMediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();let mustRestartMediaStream=false;affectedMediaStream.getVideoTracks().forEach(track=>{track.enabled=enabled;if(!enabled&&resource===true){track.stop()}else if(enabled&&track.readyState==="ended"){mustRestartMediaStream=true}});if(!enabled&&resource===true&&!!this.stream.filter&&this.stream.filter.type.startsWith("VB:")){this.stream.lastVBFilter=this.stream.filter;yield this.stream.removeFilterAux(true)}if(mustRestartMediaStream){const oldVideoTrack=affectedMediaStream.getVideoTracks()[0];affectedMediaStream.removeTrack(oldVideoTrack);const replaceVideoTrack=tr=>__awaiter(this,void 0,void 0,function*(){affectedMediaStream.addTrack(tr);if(this.stream.isLocalStreamPublished){yield this.replaceTrackInRtcRtpSender(tr)}if(!!this.stream.lastVBFilter){setTimeout(()=>__awaiter(this,void 0,void 0,function*(){let options=this.stream.lastVBFilter.options;const lastExecMethod=this.stream.lastVBFilter.lastExecMethod;if(!!lastExecMethod&&lastExecMethod.method==="update"){options=Object.assign({},options,lastExecMethod.params)}yield this.stream.applyFilter(this.stream.lastVBFilter.type,options);delete this.stream.lastVBFilter}),1)}});if(!!resource&&resource instanceof MediaStreamTrack){yield replaceVideoTrack(resource)}else{try{const mediaStream=yield navigator.mediaDevices.getUserMedia({audio:false,video:this.stream.lastVideoTrackConstraints});yield replaceVideoTrack(mediaStream.getVideoTracks()[0])}catch(error){return reject(error)}}}if(!!this.session&&!!this.stream.streamId){this.session.openvidu.sendRequest("streamPropertyChanged",{streamId:this.stream.streamId,property:"videoActive",newValue:enabled,reason:"publishVideo"},(error,response)=>{if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this.stream,"videoActive",enabled,!enabled,"publishVideo")]);this.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this,this.stream,"videoActive",enabled,!enabled,"publishVideo")]);this.session.sendVideoData(this.stream.streamManager)}})}this.stream.videoActive=enabled;logger.info("'Publisher' has "+(enabled?"published":"unpublished")+" its video stream");return resolve()}}))}subscribeToRemote(value){value=value!==undefined?value:true;this.isSubscribedToRemote=value;this.stream.subscribeToMyRemote(value)}on(type,handler){super.on(type,handler);if(type==="streamCreated"){if(!!this.stream&&this.stream.isLocalStreamPublished){this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])}else{this.stream.ee.on("stream-created-by-publisher",()=>{this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])})}}if(type==="accessAllowed"){if(this.accessAllowed){this.emitEvent("accessAllowed",[])}}if(type==="accessDenied"){if(this.accessDenied){this.emitEvent("accessDenied",[])}}return this}once(type,handler){super.once(type,handler);if(type==="streamCreated"){if(!!this.stream&&this.stream.isLocalStreamPublished){this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])}else{this.stream.ee.once("stream-created-by-publisher",()=>{this.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",this.stream,"")])})}}if(type==="accessAllowed"){if(this.accessAllowed){this.emitEvent("accessAllowed",[])}}if(type==="accessDenied"){if(this.accessDenied){this.emitEvent("accessDenied",[])}}return this}off(type,handler){super.off(type,handler);return this}replaceTrack(track){return __awaiter(this,void 0,void 0,function*(){return this.replaceTrackAux(track,true)})}initialize(){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){var _a,_b;let constraints={};let constraintsAux={};const timeForDialogEvent=2e3;let startTime;const errorCallback=openViduError=>{this.accessDenied=true;this.accessAllowed=false;logger.error(`Publisher initialization failed. ${openViduError.name}: ${openViduError.message}`);return reject(openViduError)};const successCallback=mediaStream=>{var _a,_b;this.accessAllowed=true;this.accessDenied=false;if(typeof MediaStreamTrack!=="undefined"&&this.properties.audioSource instanceof MediaStreamTrack){mediaStream.removeTrack(mediaStream.getAudioTracks()[0]);mediaStream.addTrack(this.properties.audioSource)}if(typeof MediaStreamTrack!=="undefined"&&this.properties.videoSource instanceof MediaStreamTrack){mediaStream.removeTrack(mediaStream.getVideoTracks()[0]);mediaStream.addTrack(this.properties.videoSource)}if(!!mediaStream.getAudioTracks()[0]){const enabled=this.stream.audioActive!==undefined&&this.stream.audioActive!==null?this.stream.audioActive:!!this.stream.outboundStreamOpts.publisherProperties.publishAudio;mediaStream.getAudioTracks()[0].enabled=enabled}if(!!mediaStream.getVideoTracks()[0]){const enabled=this.stream.videoActive!==undefined&&this.stream.videoActive!==null?this.stream.videoActive:!!this.stream.outboundStreamOpts.publisherProperties.publishVideo;mediaStream.getVideoTracks()[0].enabled=enabled}for(const track of mediaStream.getAudioTracks()){if(!((_a=track.contentHint)===null||_a===void 0?void 0:_a.length)){track.contentHint="";logger.info(`Audio track Content Hint set: '${track.contentHint}'`)}}for(const track of mediaStream.getVideoTracks()){if(!((_b=track.contentHint)===null||_b===void 0?void 0:_b.length)){switch(this.stream.typeOfVideo){case TypeOfVideo_1.TypeOfVideo.SCREEN:track.contentHint="detail";break;case TypeOfVideo_1.TypeOfVideo.CUSTOM:logger.warn("CUSTOM type video track was provided without Content Hint!");track.contentHint="motion";break;case TypeOfVideo_1.TypeOfVideo.CAMERA:case TypeOfVideo_1.TypeOfVideo.IPCAM:default:track.contentHint="motion";break}logger.info(`Video track Content Hint set: '${track.contentHint}'`)}}this.initializeVideoReference(mediaStream);if(!this.stream.displayMyRemote()){this.stream.updateMediaStreamInVideos()}delete this.firstVideoElement;if(this.stream.isSendVideo()){this.getVideoDimensions().then(dimensions=>{this.stream.videoDimensions={width:dimensions.width,height:dimensions.height};if(this.stream.isSendScreen()){if(this.stream.isSendAudio()&&mediaStream.getAudioTracks().length===0){this.stream.audioActive=false;this.stream.hasAudio=false;this.stream.outboundStreamOpts.publisherProperties.publishAudio=false;this.stream.outboundStreamOpts.publisherProperties.audioSource=false}this.screenShareResizeInterval=setInterval(()=>{const settings=mediaStream.getVideoTracks()[0].getSettings();const newWidth=settings.width;const newHeight=settings.height;const widthChanged=newWidth!=null&&newWidth!==this.stream.videoDimensions.width;const heightChanged=newHeight!=null&&newHeight!==this.stream.videoDimensions.height;if(this.stream.isLocalStreamPublished&&(widthChanged||heightChanged)){this.openvidu.sendVideoDimensionsChangedEvent(this,"screenResized",this.stream.videoDimensions.width,this.stream.videoDimensions.height,newWidth||0,newHeight||0)}},650)}this.stream.isLocalStreamReadyToPublish=true;this.stream.ee.emitEvent("stream-ready-to-publish",[])})}else{this.stream.isLocalStreamReadyToPublish=true;this.stream.ee.emitEvent("stream-ready-to-publish",[])}return resolve()};const getMediaSuccess=(mediaStream,definedAudioConstraint)=>__awaiter(this,void 0,void 0,function*(){this.clearPermissionDialogTimer(startTime,timeForDialogEvent);if(this.stream.isSendScreen()&&this.properties.audioSource!=="screen"&&this.stream.isSendAudio()){constraintsAux.audio=definedAudioConstraint;constraintsAux.video=false;startTime=Date.now();this.setPermissionDialogTimer(timeForDialogEvent);try{const audioOnlyStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);this.clearPermissionDialogTimer(startTime,timeForDialogEvent);mediaStream.addTrack(audioOnlyStream.getAudioTracks()[0]);successCallback(mediaStream)}catch(error){this.clearPermissionDialogTimer(startTime,timeForDialogEvent);mediaStream.getAudioTracks().forEach(track=>{track.stop()});mediaStream.getVideoTracks().forEach(track=>{track.stop()});errorCallback(this.openvidu.generateAudioDeviceError(error,constraints));return}}else{successCallback(mediaStream)}});const getMediaError=error=>__awaiter(this,void 0,void 0,function*(){logger.error(`getMediaError: ${error.toString()}`);this.clearPermissionDialogTimer(startTime,timeForDialogEvent);if(error.name==="Error"){error.name=error.constructor.name}let errorName,errorMessage;switch(error.name.toLowerCase()){case"notfounderror":try{const mediaStream=yield navigator.mediaDevices.getUserMedia({audio:false,video:constraints.video});mediaStream.getVideoTracks().forEach(track=>{track.stop()});errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}catch(error){errorName=OpenViduError_1.OpenViduErrorName.INPUT_VIDEO_DEVICE_NOT_FOUND;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}break;case"notallowederror":errorName=this.stream.isSendScreen()?OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED:OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage));break;case"overconstrainederror":try{const mediaStream=yield navigator.mediaDevices.getUserMedia({audio:false,video:constraints.video});mediaStream.getVideoTracks().forEach(track=>{track.stop()});if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage="Audio input device with deviceId '"+constraints.audio.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Audio input device doesn't support the value passed for constraint '"+error.constraint+"'"}errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}catch(error){if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_VIDEO_DEVICE_NOT_FOUND;errorMessage="Video input device with deviceId '"+constraints.video.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Video input device doesn't support the value passed for constraint '"+error.constraint+"'"}errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage))}break;case"aborterror":case"notreadableerror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ALREADY_IN_USE;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage));break;default:errorName=OpenViduError_1.OpenViduErrorName.GENERIC_ERROR;errorMessage=error.toString();errorCallback(new OpenViduError_1.OpenViduError(errorName,errorMessage));break}});try{const myConstraints=yield this.openvidu.generateMediaConstraints(this.properties);if(!!myConstraints.videoTrack&&!!myConstraints.audioTrack||!!myConstraints.audioTrack&&((_a=myConstraints.constraints)===null||_a===void 0?void 0:_a.video)===false||!!myConstraints.videoTrack&&((_b=myConstraints.constraints)===null||_b===void 0?void 0:_b.audio)===false){successCallback(this.openvidu.addAlreadyProvidedTracks(myConstraints,new MediaStream,this.stream))}else{constraints=myConstraints.constraints;const outboundStreamOptions={mediaConstraints:constraints,publisherProperties:this.properties};this.stream.setOutboundStreamOptions(outboundStreamOptions);const definedAudioConstraint=constraints.audio===undefined?true:constraints.audio;constraintsAux.audio=this.stream.isSendScreen()?false:definedAudioConstraint;constraintsAux.video=constraints.video;startTime=Date.now();this.setPermissionDialogTimer(timeForDialogEvent);try{if(this.stream.isSendScreen()&&navigator.mediaDevices["getDisplayMedia"]&&!platform.isElectron()){const mediaStream=yield navigator.mediaDevices["getDisplayMedia"]({video:true,audio:this.properties.audioSource==="screen"});this.openvidu.addAlreadyProvidedTracks(myConstraints,mediaStream);yield getMediaSuccess(mediaStream,definedAudioConstraint)}else{this.stream.lastVideoTrackConstraints=constraintsAux.video;const mediaStream=yield navigator.mediaDevices.getUserMedia(constraintsAux);this.openvidu.addAlreadyProvidedTracks(myConstraints,mediaStream,this.stream);yield getMediaSuccess(mediaStream,definedAudioConstraint)}}catch(error){yield getMediaError(error)}}}catch(error){errorCallback(error)}}))}replaceTrackAux(track,updateLastConstraints){return __awaiter(this,void 0,void 0,function*(){const trackOriginalEnabledValue=track.enabled;if(track.kind==="video"){track.enabled=this.stream.videoActive}else if(track.kind==="audio"){track.enabled=this.stream.audioActive}try{if(this.stream.isLocalStreamPublished){this.replaceTrackInMediaStream(track,updateLastConstraints);return yield this.replaceTrackInRtcRtpSender(track)}else{return this.replaceTrackInMediaStream(track,updateLastConstraints)}}catch(error){track.enabled=trackOriginalEnabledValue;throw error}})}getVideoDimensions(){return new Promise((resolve,reject)=>{const requiresDomInsertion=(platform.isIonicIos()||platform.isIOSWithSafari())&&this.videoReference.readyState<1;let loadedmetadataListener;const resolveDimensions=()=>{let width;let height;if(typeof this.stream.getMediaStream().getVideoTracks()[0].getSettings==="function"){const settings=this.stream.getMediaStream().getVideoTracks()[0].getSettings();width=settings.width||this.videoReference.videoWidth;height=settings.height||this.videoReference.videoHeight}else{logger.warn("MediaStreamTrack does not have getSettings method on "+platform.getDescription());width=this.videoReference.videoWidth;height=this.videoReference.videoHeight}if(loadedmetadataListener!=null){this.videoReference.removeEventListener("loadedmetadata",loadedmetadataListener)}if(requiresDomInsertion){document.body.removeChild(this.videoReference)}return resolve({width:width,height:height})};if(this.videoReference.readyState>=1){resolveDimensions()}else{loadedmetadataListener=()=>{if(!this.videoReference.videoWidth){let interval=setInterval(()=>{if(!!this.videoReference.videoWidth){clearInterval(interval);resolveDimensions()}},40)}else{resolveDimensions()}};this.videoReference.addEventListener("loadedmetadata",loadedmetadataListener);if(requiresDomInsertion){document.body.appendChild(this.videoReference)}}})}reestablishStreamPlayingEvent(){if(this.ee.getListeners("streamPlaying").length>0){this.addPlayEventToFirstVideo()}}initializeVideoReference(mediaStream){this.videoReference=document.createElement("video");this.videoReference.style.display="none";this.videoReference.muted=true;this.videoReference.autoplay=true;this.videoReference.controls=false;if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){this.videoReference.playsInline=true}this.stream.setMediaStream(mediaStream);if(!!this.firstVideoElement){this.createVideoElement(this.firstVideoElement.targetElement,this.properties.insertMode)}this.videoReference.srcObject=this.stream.getMediaStream()}replaceTrackInMediaStream(track,updateLastConstraints){const mediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();let removedTrack;if(track.kind==="video"){removedTrack=mediaStream.getVideoTracks()[0];if(updateLastConstraints){this.stream.lastVideoTrackConstraints=track.getConstraints()}}else{removedTrack=mediaStream.getAudioTracks()[0]}removedTrack.enabled=false;removedTrack.stop();mediaStream.removeTrack(removedTrack);mediaStream.addTrack(track);const trackInfo={oldLabel:(removedTrack===null||removedTrack===void 0?void 0:removedTrack.label)||"",newLabel:(track===null||track===void 0?void 0:track.label)||""};if(track.kind==="video"&&updateLastConstraints){this.openvidu.sendNewVideoDimensionsIfRequired(this,"trackReplaced",50,30);this.openvidu.sendTrackChangedEvent(this,trackInfo.oldLabel,trackInfo.newLabel,"videoTrack");if(this.stream.isLocalStreamPublished){this.session.sendVideoData(this.stream.streamManager,5,true,5)}}else if(track.kind==="audio"&&updateLastConstraints){this.openvidu.sendTrackChangedEvent(this,trackInfo.oldLabel,trackInfo.newLabel,"audioTrack")}if(track.kind==="audio"){this.stream.disableHarkSpeakingEvent(false);this.stream.disableHarkStoppedSpeakingEvent(false);this.stream.disableHarkVolumeChangeEvent(false);this.stream.initHarkEvents()}}setPermissionDialogTimer(waitTime){this.permissionDialogTimeout=setTimeout(()=>{this.emitEvent("accessDialogOpened",[])},waitTime)}clearPermissionDialogTimer(startTime,waitTime){clearTimeout(this.permissionDialogTimeout);if(Date.now()-startTime>waitTime){this.emitEvent("accessDialogClosed",[])}}replaceTrackInRtcRtpSender(track){return __awaiter(this,void 0,void 0,function*(){const senders=this.stream.getRTCPeerConnection().getSenders();let sender;if(track.kind==="video"){sender=senders.find(s=>!!s.track&&s.track.kind==="video");if(!sender){throw new Error("There's no replaceable track for that kind of MediaStreamTrack in this Publisher object")}}else if(track.kind==="audio"){sender=senders.find(s=>!!s.track&&s.track.kind==="audio");if(!sender){throw new Error("There's no replaceable track for that kind of MediaStreamTrack in this Publisher object")}}else{throw new Error("Unknown track kind "+track.kind)}yield sender.replaceTrack(track)})}}exports.Publisher=Publisher},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/TypeOfVideo":54,"../OpenViduInternal/Events/StreamEvent":67,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./Session":48,"./Stream":49,"./StreamManager":50}],48:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.Session=void 0;const Connection_1=require("./Connection");const Filter_1=require("./Filter");const Subscriber_1=require("./Subscriber");const EventDispatcher_1=require("./EventDispatcher");const ConnectionEvent_1=require("../OpenViduInternal/Events/ConnectionEvent");const FilterEvent_1=require("../OpenViduInternal/Events/FilterEvent");const RecordingEvent_1=require("../OpenViduInternal/Events/RecordingEvent");const SessionDisconnectedEvent_1=require("../OpenViduInternal/Events/SessionDisconnectedEvent");const SignalEvent_1=require("../OpenViduInternal/Events/SignalEvent");const SpeechToTextEvent_1=require("../OpenViduInternal/Events/SpeechToTextEvent");const StreamEvent_1=require("../OpenViduInternal/Events/StreamEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const ConnectionPropertyChangedEvent_1=require("../OpenViduInternal/Events/ConnectionPropertyChangedEvent");const NetworkQualityLevelChangedEvent_1=require("../OpenViduInternal/Events/NetworkQualityLevelChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const semverMajor=require("semver/functions/major");const semverMinor=require("semver/functions/minor");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class Session extends EventDispatcher_1.EventDispatcher{constructor(openvidu){super();this.streamManagers=[];this.remoteStreamsCreated=new Map;this.remoteConnections=new Map;platform=Platform_1.PlatformUtils.getInstance();this.openvidu=openvidu}connect(token,metadata){return new Promise((resolve,reject)=>{this.processToken(token);if(this.openvidu.checkSystemRequirements()){this.options={sessionId:this.sessionId,participantId:token,metadata:!!metadata?this.stringClientMetadata(metadata):""};this.connectAux(token).then(()=>resolve()).catch(error=>reject(error))}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.BROWSER_NOT_SUPPORTED,"Browser "+platform.getName()+" (version "+platform.getVersion()+") for "+platform.getFamily()+" is not supported in OpenVidu"))}})}disconnect(){this.leave(false,"disconnect")}subscribe(stream,targetElement,param3,param4){let properties={};if(!!param3&&typeof param3!=="function"){properties={insertMode:typeof param3.insertMode!=="undefined"?typeof param3.insertMode==="string"?VideoInsertMode_1.VideoInsertMode[param3.insertMode]:properties.insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,subscribeToAudio:typeof param3.subscribeToAudio!=="undefined"?param3.subscribeToAudio:true,subscribeToVideo:typeof param3.subscribeToVideo!=="undefined"?param3.subscribeToVideo:true}}else{properties={insertMode:VideoInsertMode_1.VideoInsertMode.APPEND,subscribeToAudio:true,subscribeToVideo:true}}let completionHandler=undefined;if(!!param3&&typeof param3==="function"){completionHandler=param3}else if(!!param4){completionHandler=param4}if(!this.sessionConnected()){if(completionHandler!==undefined){completionHandler(this.notConnectedError())}throw this.notConnectedError()}logger.info("Subscribing to "+stream.connection.connectionId);stream.subscribe().then(()=>{logger.info("Subscribed correctly to "+stream.connection.connectionId);if(completionHandler!==undefined){completionHandler(undefined)}}).catch(error=>{if(completionHandler!==undefined){completionHandler(error)}});const subscriber=new Subscriber_1.Subscriber(stream,targetElement,properties);if(!!subscriber.targetElement){stream.streamManager.createVideoElement(subscriber.targetElement,properties.insertMode)}return subscriber}subscribeAsync(stream,targetElement,properties){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}let subscriber;const callback=error=>{if(!!error){return reject(error)}else{return resolve(subscriber)}};if(!!properties){subscriber=this.subscribe(stream,targetElement,properties,callback)}else{subscriber=this.subscribe(stream,targetElement,callback)}})}unsubscribe(subscriber){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}else{const connectionId=subscriber.stream.connection.connectionId;logger.info("Unsubscribing from "+connectionId);this.openvidu.sendRequest("unsubscribeFromVideo",{sender:subscriber.stream.connection.connectionId},(error,response)=>{if(error){logger.error("Error unsubscribing from "+connectionId);return reject(error)}else{logger.info("Unsubscribed correctly from "+connectionId);subscriber.stream.streamManager.removeAllVideos();subscriber.stream.disposeWebRtcPeer();subscriber.stream.disposeMediaStream();return resolve()}})}})}publish(publisher){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}publisher.session=this;publisher.stream.session=this;if(!publisher.stream.publishedOnce){this.connection.addStream(publisher.stream);publisher.stream.publish().then(()=>{this.sendVideoData(publisher,8,true,5);return resolve()}).catch(error=>reject(error))}else{publisher.initialize().then(()=>{this.connection.addStream(publisher.stream);publisher.reestablishStreamPlayingEvent();publisher.stream.publish().then(()=>{this.sendVideoData(publisher,8,true,5);return resolve()}).catch(error=>reject(error))}).catch(error=>reject(error))}})}unpublish(publisher){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){throw this.notConnectedError()}const stream=publisher.stream;if(!stream.connection){return reject(new Error("The associated Connection object of this Publisher is null"))}else if(stream.connection!==this.connection){return reject(new Error("The associated Connection object of this Publisher is not your local Connection. "+"Only moderators can force unpublish on remote Streams via 'forceUnpublish' method"))}else{logger.info("Unpublishing local media ("+stream.connection.connectionId+")");this.openvidu.sendRequest("unpublishVideo",(error,response)=>{if(error){return reject(error)}else{logger.info("Media unpublished correctly");stream.disposeWebRtcPeer();if(stream.connection.stream==stream){delete stream.connection.stream}const streamEvent=new StreamEvent_1.StreamEvent(true,publisher,"streamDestroyed",publisher.stream,"unpublish");publisher.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();return resolve()}})}})}forceDisconnect(connection){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}logger.info("Forcing disconnect for connection "+connection.connectionId);this.openvidu.sendRequest("forceDisconnect",{connectionId:connection.connectionId},(error,response)=>{if(error){logger.error("Error forcing disconnect for Connection "+connection.connectionId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to force a disconnection"))}else{return reject(error)}}else{logger.info("Forcing disconnect correctly for Connection "+connection.connectionId);return resolve()}})})}forceUnpublish(stream){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}logger.info("Forcing unpublish for stream "+stream.streamId);this.openvidu.sendRequest("forceUnpublish",{streamId:stream.streamId},(error,response)=>{if(error){logger.error("Error forcing unpublish for Stream "+stream.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to force an unpublishing"))}else{return reject(error)}}else{logger.info("Forcing unpublish correctly for Stream "+stream.streamId);return resolve()}})})}signal(signal){return new Promise((resolve,reject)=>{if(!this.sessionConnected()){return reject(this.notConnectedError())}const signalMessage={};if(signal.to&&signal.to.length>0){const connectionIds=[];signal.to.forEach(connection=>{if(!!connection.connectionId){connectionIds.push(connection.connectionId)}});signalMessage["to"]=connectionIds}else{signalMessage["to"]=[]}signalMessage["data"]=signal.data?signal.data:"";let typeAux=signal.type?signal.type:"signal";if(!!typeAux){if(typeAux.substring(0,7)!=="signal:"){typeAux="signal:"+typeAux}}signalMessage["type"]=typeAux;this.openvidu.sendRequest("sendMessage",{message:JSON.stringify(signalMessage)},(error,response)=>{if(!!error){return reject(error)}else{return resolve()}})})}subscribeToSpeechToText(stream,lang){return new Promise((resolve,reject)=>{this.openvidu.sendRequest("subscribeToSpeechToText",{connectionId:stream.connection.connectionId,lang:lang},(error,response)=>{if(!!error){return reject(error)}else{return resolve()}})})}unsubscribeFromSpeechToText(stream){return new Promise((resolve,reject)=>{this.openvidu.sendRequest("unsubscribeFromSpeechToText",{connectionId:stream.connection.connectionId},(error,response)=>{if(!!error){return reject(error)}else{return resolve()}})})}on(type,handler){var _a,_b,_c,_d;super.onAux(type,"Event '"+type+"' triggered by 'Session'",handler);if(type==="publisherStartSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableHarkSpeakingEvent()}});if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.hasAudio)){this.connection.stream.enableHarkSpeakingEvent()}}if(type==="publisherStopSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableHarkStoppedSpeakingEvent()}});if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.hasAudio)){this.connection.stream.enableHarkStoppedSpeakingEvent()}}return this}once(type,handler){var _a,_b,_c,_d;super.onceAux(type,"Event '"+type+"' triggered once by 'Session'",handler);if(type==="publisherStartSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableOnceHarkSpeakingEvent()}});if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.hasAudio)){this.connection.stream.enableOnceHarkSpeakingEvent()}}if(type==="publisherStopSpeaking"){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableOnceHarkStoppedSpeakingEvent()}});if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.hasAudio)){this.connection.stream.enableOnceHarkStoppedSpeakingEvent()}}return this}off(type,handler){var _a,_b,_c,_d;super.offAux(type,handler);if(type==="publisherStartSpeaking"){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false)){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false,remoteConnection.stream.streamManager)){remoteConnection.stream.disableHarkSpeakingEvent(false)}}});if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false,this.connection.stream.streamManager)){this.connection.stream.disableHarkSpeakingEvent(false)}}}}if(type==="publisherStopSpeaking"){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false)){this.remoteConnections.forEach(remoteConnection=>{var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false,remoteConnection.stream.streamManager)){remoteConnection.stream.disableHarkStoppedSpeakingEvent(false)}}});if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false,this.connection.stream.streamManager)){this.connection.stream.disableHarkStoppedSpeakingEvent(false)}}}}return this}onParticipantJoined(event){this.getConnection(event.id,"").then(connection=>{logger.warn("Connection "+connection.connectionId+" already exists in connections list")}).catch(openViduError=>{const connection=new Connection_1.Connection(this,event);this.remoteConnections.set(event.id,connection);this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionCreated",connection,"")])})}onParticipantLeft(event){this.getRemoteConnection(event.connectionId,"onParticipantLeft").then(connection=>{if(!!connection.stream){const stream=connection.stream;const streamEvent=new StreamEvent_1.StreamEvent(true,this,"streamDestroyed",stream,event.reason);this.ee.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();this.remoteStreamsCreated.delete(stream.streamId)}connection.dispose();this.remoteConnections.delete(connection.connectionId);this.ee.emitEvent("connectionDestroyed",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionDestroyed",connection,event.reason)])}).catch(openViduError=>{logger.error(openViduError)})}onParticipantPublished(event){const afterConnectionFound=connection=>{this.remoteConnections.set(connection.connectionId,connection);if(!this.remoteStreamsCreated.get(connection.stream.streamId)){this.ee.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",connection.stream,"")])}this.remoteStreamsCreated.set(connection.stream.streamId,true)};let connection;this.getRemoteConnection(event.id,"onParticipantPublished").then(con=>{connection=con;event.metadata=con.data;connection.remoteOptions=event;connection.initRemoteStreams(event.streams);afterConnectionFound(connection)}).catch(openViduError=>{connection=new Connection_1.Connection(this,event);afterConnectionFound(connection)})}onParticipantUnpublished(event){if(event.connectionId===this.connection.connectionId){this.stopPublisherStream(event.reason)}else{this.getRemoteConnection(event.connectionId,"onParticipantUnpublished").then(connection=>{const streamEvent=new StreamEvent_1.StreamEvent(true,this,"streamDestroyed",connection.stream,event.reason);this.ee.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();if(connection.stream!=null){const streamId=connection.stream.streamId;this.remoteStreamsCreated.delete(streamId);connection.removeStream()}}).catch(openViduError=>{logger.error(openViduError)})}}onParticipantEvicted(event){if(event.connectionId===this.connection.connectionId){if(!!this.sessionId&&!this.connection.disposed){this.leave(true,event.reason)}}}onNewMessage(event){logger.info("New signal: "+JSON.stringify(event));const strippedType=!!event.type?event.type.replace(/^(signal:)/,""):undefined;if(!!event.from){this.getConnection(event.from,"Connection '"+event.from+"' unknown when 'onNewMessage'. Existing remote connections: "+JSON.stringify(this.remoteConnections.keys())+". Existing local connection: "+this.connection.connectionId).then(connection=>{this.ee.emitEvent("signal",[new SignalEvent_1.SignalEvent(this,strippedType,event.data,connection)]);if(!!event.type&&event.type!=="signal"){this.ee.emitEvent(event.type,[new SignalEvent_1.SignalEvent(this,strippedType,event.data,connection)])}}).catch(openViduError=>{logger.error(openViduError)})}else{this.ee.emitEvent("signal",[new SignalEvent_1.SignalEvent(this,strippedType,event.data,undefined)]);if(!!event.type&&event.type!=="signal"){this.ee.emitEvent(event.type,[new SignalEvent_1.SignalEvent(this,strippedType,event.data,undefined)])}}}onStreamPropertyChanged(event){const callback=connection=>{var _a,_b;if(!!connection.stream&&connection.stream.streamId===event.streamId){const stream=connection.stream;let oldValue;switch(event.property){case"audioActive":oldValue=stream.audioActive;event.newValue=event.newValue==="true";stream.audioActive=event.newValue;break;case"videoActive":oldValue=stream.videoActive;event.newValue=event.newValue==="true";stream.videoActive=event.newValue;const videoTrack=(_b=(_a=stream===null||stream===void 0?void 0:stream.getMediaStream())===null||_a===void 0?void 0:_a.getVideoTracks())===null||_b===void 0?void 0:_b[0];if(videoTrack&&!videoTrack.enabled&&stream.videoActive){videoTrack.enabled=true}break;case"videoTrack":event.newValue=JSON.parse(event.newValue);break;case"audioTrack":event.newValue=JSON.parse(event.newValue);break;case"videoDimensions":oldValue=stream.videoDimensions;event.newValue=JSON.parse(JSON.parse(event.newValue));stream.videoDimensions=event.newValue;break;case"filter":oldValue=stream.filter;event.newValue=Object.keys(event.newValue).length>0?event.newValue:undefined;if(event.newValue!==undefined){stream.filter=new Filter_1.Filter(event.newValue.type,event.newValue.options);stream.filter.stream=stream;if(event.newValue.lastExecMethod){stream.filter.lastExecMethod=event.newValue.lastExecMethod}}else{delete stream.filter}event.newValue=stream.filter;break}this.ee.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this,stream,event.property,event.newValue,oldValue,event.reason)]);if(!!stream.streamManager){stream.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(stream.streamManager,stream,event.property,event.newValue,oldValue,event.reason)])}}else{logger.error("No stream with streamId '"+event.streamId+"' found for connection '"+event.connectionId+"' on 'streamPropertyChanged' event")}};if(event.connectionId===this.connection.connectionId){callback(this.connection)}else{this.getRemoteConnection(event.connectionId,"onStreamPropertyChanged").then(connection=>{callback(connection)}).catch(openViduError=>{logger.error(openViduError)})}}onConnectionPropertyChanged(event){let oldValue;switch(event.property){case"role":oldValue=this.connection.role.slice();this.connection.role=event.newValue;this.connection.localOptions.role=event.newValue;break;case"record":oldValue=this.connection.record;event.newValue=event.newValue==="true";this.connection.record=event.newValue;this.connection.localOptions.record=event.newValue;break}this.ee.emitEvent("connectionPropertyChanged",[new ConnectionPropertyChangedEvent_1.ConnectionPropertyChangedEvent(this,this.connection,event.property,event.newValue,oldValue)])}onNetworkQualityLevelChangedChanged(event){if(event.connectionId===this.connection.connectionId){this.ee.emitEvent("networkQualityLevelChanged",[new NetworkQualityLevelChangedEvent_1.NetworkQualityLevelChangedEvent(this,event.newValue,event.oldValue,this.connection)])}else{this.getConnection(event.connectionId,"Connection not found for connectionId "+event.connectionId).then(connection=>{this.ee.emitEvent("networkQualityLevelChanged",[new NetworkQualityLevelChangedEvent_1.NetworkQualityLevelChangedEvent(this,event.newValue,event.oldValue,connection)])}).catch(openViduError=>{logger.error(openViduError)})}}recvIceCandidate(event){const candidateInit={candidate:event.candidate,sdpMLineIndex:event.sdpMLineIndex,sdpMid:event.sdpMid};const iceCandidate=new RTCIceCandidate(candidateInit);this.getConnection(event.senderConnectionId,"Connection not found for connectionId "+event.senderConnectionId+" owning endpoint "+event.endpointName+". Ice candidate will be ignored: "+iceCandidate).then(connection=>{const stream=connection.stream;stream.getWebRtcPeer().addIceCandidate(iceCandidate).catch(error=>{logger.error("Error adding candidate for "+stream.streamId+" stream of endpoint "+event.endpointName+": "+error)})}).catch(openViduError=>{logger.error(openViduError)})}onSessionClosed(msg){logger.info("Session closed: "+JSON.stringify(msg));const s=msg.sessionId;if(s!==undefined){this.ee.emitEvent("session-closed",[{session:s}])}else{logger.warn("Session undefined on session closed",msg)}}onLostConnection(reason){logger.warn("Lost connection in Session "+this.sessionId);if(!!this.sessionId&&!!this.connection&&!this.connection.disposed){this.leave(true,reason)}}onRecoveredConnection(){logger.info("Recovered connection in Session "+this.sessionId);this.reconnectBrokenStreams();this.ee.emitEvent("reconnected",[])}onMediaError(event){logger.error("Media error: "+JSON.stringify(event));const err=event.error;if(err){this.ee.emitEvent("error-media",[{error:err}])}else{logger.warn("Received undefined media error:",event)}}onRecordingStarted(event){this.ee.emitEvent("recordingStarted",[new RecordingEvent_1.RecordingEvent(this,"recordingStarted",event.id,event.name)])}onRecordingStopped(event){this.ee.emitEvent("recordingStopped",[new RecordingEvent_1.RecordingEvent(this,"recordingStopped",event.id,event.name,event.reason)])}onBroadcastStarted(){this.ee.emitEvent("broadcastStarted",[])}onBroadcastStopped(){this.ee.emitEvent("broadcastStopped",[])}onFilterEventDispatched(event){const connectionId=event.connectionId;this.getConnection(connectionId,"No connection found for connectionId "+connectionId).then(connection=>{logger.info(`Filter event of type "${event.eventType}" dispatched`);const stream=connection.stream;if(!stream||!stream.filter){return logger.error(`Filter event of type "${event.eventType}" dispatched for stream ${stream.streamId} but there is no ${!stream?"stream":"filter"} defined`)}const eventHandler=stream.filter.handlers.get(event.eventType);if(!eventHandler||typeof eventHandler!=="function"){const actualHandlers=Array.from(stream.filter.handlers.keys());return logger.error(`Filter event of type "${event.eventType}" not handled or not a function! Active filter events: ${actualHandlers.join(",")}`)}else{eventHandler.call(this,new FilterEvent_1.FilterEvent(stream.filter,event.eventType,event.data))}})}onForciblyReconnectSubscriber(event){return new Promise((resolve,reject)=>{this.getRemoteConnection(event.connectionId,"onForciblyReconnectSubscriber").then(connection=>{if(!!connection.stream&&connection.stream.streamId===event.streamId){const stream=connection.stream;if(stream.setupReconnectionEventEmitter(resolve,reject)){if(stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]!=null){stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]=event;return reject("Ongoing forced subscriber reconnection")}else{stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]=event;const callback=()=>{const eventAux=stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"];delete stream.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"];this.onForciblyReconnectSubscriber(eventAux)};stream.reconnectionEventEmitter.once("success",()=>{callback()});stream.reconnectionEventEmitter.once("error",()=>{callback()})}return}stream.completeWebRtcPeerReceive(true,true,event.sdpOffer).then(()=>stream.finalResolveForSubscription(true,resolve)).catch(error=>stream.finalRejectForSubscription(true,`Error while forcibly reconnecting remote stream ${event.streamId}: ${error.toString()}`,reject))}else{const errMsg="No stream with streamId '"+event.streamId+"' found for connection '"+event.connectionId+"' on 'streamPropertyChanged' event";logger.error(errMsg);return reject(errMsg)}}).catch(openViduError=>{logger.error(openViduError);return reject(openViduError)})})}reconnectBrokenStreams(){logger.info("Re-establishing media connections...");let someReconnection=false;if(!!this.connection.stream&&this.connection.stream.streamIceConnectionStateBroken()){logger.warn("Re-establishing Publisher "+this.connection.stream.streamId);this.connection.stream.initWebRtcPeerSend(true);someReconnection=true}this.remoteConnections.forEach(remoteConnection=>{if(!!remoteConnection.stream&&remoteConnection.stream.streamIceConnectionStateBroken()){logger.warn("Re-establishing Subscriber "+remoteConnection.stream.streamId);remoteConnection.stream.initWebRtcPeerReceive(true);someReconnection=true}});if(!someReconnection){logger.info("There were no media streams in need of a reconnection")}}onSpeechToTextMessage(event){return __awaiter(this,void 0,void 0,function*(){const connection=yield this.getConnection(event.connectionId,"No connection found for connectionId "+event.connectionId);const ev=new SpeechToTextEvent_1.SpeechToTextEvent(this,connection,event.text,event.reason.toLowerCase(),event.raw,event.lang);this.ee.emitEvent("speechToTextMessage",[ev])})}onSpeechToTextDisconnected(event){return __awaiter(this,void 0,void 0,function*(){this.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this,ExceptionEvent_1.ExceptionEventName.SPEECH_TO_TEXT_DISCONNECTED,this,event.message)])})}emitEvent(type,eventArray){this.ee.emitEvent(type,eventArray)}leave(forced,reason){forced=!!forced;logger.info("Leaving Session (forced="+forced+")");this.stopVideoDataIntervals();if(!!this.connection){if(!this.connection.disposed&&!forced){this.openvidu.sendRequest("leaveRoom",(error,response)=>{if(error){logger.error(`leaveRoom error: ${JSON.stringify(error)}`)}this.openvidu.closeWs()})}else{this.openvidu.closeWs()}this.stopPublisherStream(reason);if(!this.connection.disposed){const sessionDisconnectEvent=new SessionDisconnectedEvent_1.SessionDisconnectedEvent(this,reason);this.ee.emitEvent("sessionDisconnected",[sessionDisconnectEvent]);sessionDisconnectEvent.callDefaultBehavior()}}else{logger.warn("You were not connected to the session "+this.sessionId)}logger.flush()}initializeParams(token){const joinParams={token:!!token?token:"",session:this.sessionId,platform:!!platform.getDescription()?platform.getDescription():"unknown",sdkVersion:this.openvidu.libraryVersion,metadata:!!this.options.metadata?this.options.metadata:"",secret:this.openvidu.getSecret(),recorder:this.openvidu.getRecorder(),stt:this.openvidu.getStt()};return joinParams}sendVideoData(streamManager,intervalSeconds=1,doInterval=false,maxLoops=1){var _a,_b;if(platform.isChromeBrowser()||platform.isChromeMobileBrowser()||platform.isOperaBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeBrowser()||platform.isEdgeMobileBrowser()||platform.isElectron()||platform.isSafariBrowser()&&!platform.isIonicIos()||platform.isAndroidBrowser()||platform.isSamsungBrowser()||platform.isIonicAndroid()||platform.isIOSWithSafari()){const obtainAndSendVideo=()=>__awaiter(this,void 0,void 0,function*(){const pc=streamManager.stream.getRTCPeerConnection();if(pc.connectionState==="connected"){const statsMap=yield pc.getStats();const arr=[];statsMap.forEach(stats=>{if("frameWidth"in stats&&"frameHeight"in stats&&arr.length===0){arr.push(stats)}});if(arr.length>0){this.openvidu.sendRequest("videoData",{height:arr[0].frameHeight,width:arr[0].frameWidth,videoActive:streamManager.stream.videoActive!=null?streamManager.stream.videoActive:false,audioActive:streamManager.stream.audioActive!=null?streamManager.stream.audioActive:false},(error,response)=>{if(error){logger.error("Error sending 'videoData' event",error)}})}}});if(doInterval){let loops=1;this.videoDataInterval=setInterval(()=>{if(loops<maxLoops){loops++;obtainAndSendVideo()}else{clearInterval(this.videoDataInterval)}},intervalSeconds*1e3)}else{this.videoDataTimeout=setTimeout(obtainAndSendVideo,intervalSeconds*1e3)}}else if(platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()||platform.isIonicIos()||platform.isReactNative()){this.openvidu.sendRequest("videoData",{height:((_a=streamManager.stream.videoDimensions)===null||_a===void 0?void 0:_a.height)||0,width:((_b=streamManager.stream.videoDimensions)===null||_b===void 0?void 0:_b.width)||0,videoActive:streamManager.stream.videoActive!=null?streamManager.stream.videoActive:false,audioActive:streamManager.stream.audioActive!=null?streamManager.stream.audioActive:false},(error,response)=>{if(error){logger.error("Error sending 'videoData' event",error)}})}else{logger.error("Browser "+platform.getName()+" (version "+platform.getVersion()+") for "+platform.getFamily()+" is not supported in OpenVidu for Network Quality")}}sessionConnected(){return this.connection!=null}notConnectedError(){return new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_NOT_CONNECTED,"There is no connection to the session. Method 'Session.connect' must be successfully completed first")}anySpeechEventListenerEnabled(event,onlyOnce,streamManager){let handlersInSession=this.ee.getListeners(event);if(onlyOnce){handlersInSession=handlersInSession.filter(h=>h.once)}let listenersInSession=handlersInSession.length;if(listenersInSession>0)return true;let listenersInStreamManager=0;if(!!streamManager){let handlersInStreamManager=streamManager.ee.getListeners(event);if(onlyOnce){handlersInStreamManager=handlersInStreamManager.filter(h=>h.once)}listenersInStreamManager=handlersInStreamManager.length}return listenersInStreamManager>0}getTokenParams(token){const match=token.match(/^(wss?)\:\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!!match){const url={protocol:match[1],host:match[2],hostname:match[3],port:match[4],pathname:match[5],search:match[6],hash:match[7]};const params=token.split("?");const queryParams=decodeURI(params[1]).split("&").map(param=>param.split("=")).reduce((values,[key,value])=>{values[key]=value;return values},{});return{sessionId:queryParams["sessionId"],secret:queryParams["secret"],recorder:queryParams["recorder"],stt:queryParams["stt"],webrtcStatsInterval:queryParams["webrtcStatsInterval"],sendBrowserLogs:queryParams["sendBrowserLogs"],edition:queryParams["edition"],wsUri:url.protocol+"://"+url.host+"/openvidu",httpUri:"https://"+url.host}}else{throw new Error(`Token not valid: "${token}"`)}}connectAux(token){return new Promise((resolve,reject)=>{this.openvidu.startWs(error=>{if(!!error){return reject(error)}else{const joinParams=this.initializeParams(token);this.openvidu.sendRequest("joinRoom",joinParams,(error,response)=>{if(!!error){return reject(error)}else{this.processJoinRoomResponse(response,token);this.connection=new Connection_1.Connection(this,response);const events={connections:new Array,streams:new Array};const existingParticipants=response.value;existingParticipants.forEach(remoteConnectionOptions=>{const connection=new Connection_1.Connection(this,remoteConnectionOptions);this.remoteConnections.set(connection.connectionId,connection);events.connections.push(connection);if(!!connection.stream){this.remoteStreamsCreated.set(connection.stream.streamId,true);events.streams.push(connection.stream)}});this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionCreated",this.connection,"")]);events.connections.forEach(connection=>{this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,this,"connectionCreated",connection,"")])});events.streams.forEach(stream=>{this.ee.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,this,"streamCreated",stream,"")])});if(!!response.recordingId&&!!response.recordingName){this.ee.emitEvent("recordingStarted",[new RecordingEvent_1.RecordingEvent(this,"recordingStarted",response.recordingId,response.recordingName)])}return resolve()}})}})})}stopPublisherStream(reason){if(!!this.connection.stream){this.connection.stream.disposeWebRtcPeer();if(this.connection.stream.isLocalStreamPublished){this.connection.stream.ee.emitEvent("local-stream-destroyed",[reason])}}}stopVideoDataIntervals(){clearInterval(this.videoDataInterval);clearTimeout(this.videoDataTimeout)}stringClientMetadata(metadata){if(typeof metadata!=="string"){return JSON.stringify(metadata)}else{return metadata}}getConnection(connectionId,errorMessage){return new Promise((resolve,reject)=>{const connection=this.remoteConnections.get(connectionId);if(!!connection){return resolve(connection)}else{if(this.connection.connectionId===connectionId){return resolve(this.connection)}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,errorMessage))}}})}getRemoteConnection(connectionId,operation){return new Promise((resolve,reject)=>{const connection=this.remoteConnections.get(connectionId);if(!!connection){return resolve(connection)}else{const errorMessage="Remote connection "+connectionId+" unknown when '"+operation+"'. "+"Existing remote connections: "+JSON.stringify(this.remoteConnections.keys());return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,errorMessage))}})}processToken(token){const tokenParams=this.getTokenParams(token);this.sessionId=tokenParams.sessionId;if(!!tokenParams.secret){this.openvidu.secret=tokenParams.secret}if(!!tokenParams.recorder){this.openvidu.recorder=true}if(!!tokenParams.stt){this.openvidu.stt=true}if(!!tokenParams.webrtcStatsInterval){this.openvidu.webrtcStatsInterval=tokenParams.webrtcStatsInterval}if(!!tokenParams.sendBrowserLogs){this.openvidu.sendBrowserLogs=tokenParams.sendBrowserLogs}this.openvidu.isAtLeastPro=tokenParams.edition==="pro"||tokenParams.edition==="enterprise";this.openvidu.isEnterprise=tokenParams.edition==="enterprise";this.openvidu.wsUri=tokenParams.wsUri;this.openvidu.httpUri=tokenParams.httpUri}processJoinRoomResponse(opts,token){this.sessionId=opts.session;if(opts.customIceServers!=null&&opts.customIceServers.length>0){this.openvidu.iceServers=[];for(const iceServer of opts.customIceServers){let rtcIceServer={urls:[iceServer.url]};logger.log("STUN/TURN server IP: "+iceServer.url);if(iceServer.username!=null&&iceServer.credential!=null){rtcIceServer.username=iceServer.username;rtcIceServer.credential=iceServer.credential;logger.log("TURN credentials ["+iceServer.username+":"+iceServer.credential+"]")}this.openvidu.iceServers.push(rtcIceServer)}}this.openvidu.role=opts.role;this.openvidu.finalUserId=opts.finalUserId;this.openvidu.mediaServer=opts.mediaServer;this.openvidu.videoSimulcast=opts.videoSimulcast;this.capabilities={subscribe:true,publish:this.openvidu.role!=="SUBSCRIBER",forceUnpublish:this.openvidu.role==="MODERATOR",forceDisconnect:this.openvidu.role==="MODERATOR"};logger.info("openvidu-server version: "+opts.version);if(opts.life!=null){this.openvidu.life=opts.life}const minorDifference=semverMinor(opts.version)-semverMinor(this.openvidu.libraryVersion);if(semverMajor(opts.version)!==semverMajor(this.openvidu.libraryVersion)||!(minorDifference==0||minorDifference==1)){logger.error(`openvidu-browser (${this.openvidu.libraryVersion}) and openvidu-server (${opts.version}) versions are incompatible. `+"Errors are likely to occur. openvidu-browser SDK is only compatible with the same version or the immediately following minor version of an OpenVidu deployment")}else if(minorDifference==1){logger.warn(`openvidu-browser version ${this.openvidu.libraryVersion} does not match openvidu-server version ${opts.version}. `+`These versions are still compatible with each other, but openvidu-browser version must be updated as soon as possible to ${semverMajor(opts.version)}.${semverMinor(opts.version)}.x. `+`This client using openvidu-browser ${this.openvidu.libraryVersion} will become incompatible with the next release of openvidu-server`)}OpenViduLogger_1.OpenViduLogger.configureJSNLog(this.openvidu,token);this.token=token}}exports.Session=Session},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/ConnectionEvent":56,"../OpenViduInternal/Events/ConnectionPropertyChangedEvent":57,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/FilterEvent":60,"../OpenViduInternal/Events/NetworkQualityLevelChangedEvent":61,"../OpenViduInternal/Events/RecordingEvent":63,"../OpenViduInternal/Events/SessionDisconnectedEvent":64,"../OpenViduInternal/Events/SignalEvent":65,"../OpenViduInternal/Events/SpeechToTextEvent":66,"../OpenViduInternal/Events/StreamEvent":67,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./Connection":42,"./EventDispatcher":43,"./Filter":44,"./Subscriber":51,"semver/functions/major":16,"semver/functions/minor":17}],49:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.Stream=void 0;const Filter_1=require("./Filter");const Subscriber_1=require("./Subscriber");const WebRtcPeer_1=require("../OpenViduInternal/WebRtcPeer/WebRtcPeer");const WebRtcStats_1=require("../OpenViduInternal/WebRtcStats/WebRtcStats");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const PublisherSpeakingEvent_1=require("../OpenViduInternal/Events/PublisherSpeakingEvent");const StreamManagerEvent_1=require("../OpenViduInternal/Events/StreamManagerEvent");const StreamPropertyChangedEvent_1=require("../OpenViduInternal/Events/StreamPropertyChangedEvent");const OpenViduError_1=require("../OpenViduInternal/Enums/OpenViduError");const TypeOfVideo_1=require("../OpenViduInternal/Enums/TypeOfVideo");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const uuid_1=require("uuid");const hark=require("hark");const EventEmitter=require("wolfy87-eventemitter");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class Stream{constructor(session,options){this.isSubscribeToRemote=false;this.isLocalStreamReadyToPublish=false;this.isLocalStreamPublished=false;this.publishedOnce=false;this.harkSpeakingEnabled=false;this.harkSpeakingEnabledOnce=false;this.harkStoppedSpeakingEnabled=false;this.harkStoppedSpeakingEnabledOnce=false;this.harkVolumeChangeEnabled=false;this.harkVolumeChangeEnabledOnce=false;this.ee=new EventEmitter;platform=Platform_1.PlatformUtils.getInstance();this.session=session;if(options.hasOwnProperty("id")){this.inboundStreamOpts=options;this.streamId=this.inboundStreamOpts.id;this.creationTime=this.inboundStreamOpts.createdAt;this.hasAudio=this.inboundStreamOpts.hasAudio;this.hasVideo=this.inboundStreamOpts.hasVideo;if(this.hasAudio){this.audioActive=this.inboundStreamOpts.audioActive}if(this.hasVideo){this.videoActive=this.inboundStreamOpts.videoActive;this.typeOfVideo=!this.inboundStreamOpts.typeOfVideo?undefined:this.inboundStreamOpts.typeOfVideo;this.frameRate=this.inboundStreamOpts.frameRate===-1?undefined:this.inboundStreamOpts.frameRate;this.videoDimensions=this.inboundStreamOpts.videoDimensions}if(!!this.inboundStreamOpts.filter&&Object.keys(this.inboundStreamOpts.filter).length>0){if(!!this.inboundStreamOpts.filter.lastExecMethod&&Object.keys(this.inboundStreamOpts.filter.lastExecMethod).length===0){delete this.inboundStreamOpts.filter.lastExecMethod}this.filter=this.inboundStreamOpts.filter}}else{this.outboundStreamOpts=options;this.hasAudio=this.isSendAudio();this.hasVideo=this.isSendVideo();if(this.hasAudio){this.audioActive=!!this.outboundStreamOpts.publisherProperties.publishAudio}if(this.hasVideo){this.videoActive=!!this.outboundStreamOpts.publisherProperties.publishVideo;this.frameRate=this.outboundStreamOpts.publisherProperties.frameRate;if(typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack){this.typeOfVideo=TypeOfVideo_1.TypeOfVideo.CUSTOM}else{this.typeOfVideo=this.isSendScreen()?TypeOfVideo_1.TypeOfVideo.SCREEN:TypeOfVideo_1.TypeOfVideo.CAMERA}}if(!!this.outboundStreamOpts.publisherProperties.filter){this.filter=this.outboundStreamOpts.publisherProperties.filter}}this.ee.on("mediastream-updated",()=>{var _a;this.streamManager.updateMediaStream(this.mediaStream);logger.debug("Video srcObject ["+((_a=this.mediaStream)===null||_a===void 0?void 0:_a.id)+"] updated in stream ["+this.streamId+"]")})}reconnect(){return this.reconnectStream("API")}applyFilter(type,options){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){if(!!this.filter){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"There is already a filter applied to Stream "+this.streamId))}const resolveApplyFilter=(error,triggerEvent)=>{if(error){logger.error("Error applying filter for Stream "+this.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to apply a filter"))}else{return reject(error)}}else{logger.info("Filter successfully applied on Stream "+this.streamId);const oldValue=this.filter;this.filter=new Filter_1.Filter(type,options);this.filter.stream=this;if(triggerEvent){this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this,"filter",this.filter,oldValue,"applyFilter")]);this.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.streamManager,this,"filter",this.filter,oldValue,"applyFilter")])}return resolve(this.filter)}};if(type.startsWith("VB:")){if(!this.hasVideo){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"The Virtual Background filter requires a video track to be applied"))}if(!this.mediaStream||this.streamManager.videos.length===0){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"The StreamManager requires some video element to be attached to it in order to apply a Virtual Background filter"))}let openviduToken;if(!!this.session.token){openviduToken=this.session.token}else{openviduToken=options["token"]}if(!openviduToken){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,'Virtual Background requires the client to be connected to a Session or to have a "token" property available in "options" parameter with a valid OpenVidu token'))}const tokenParams=this.session.getTokenParams(openviduToken);if(tokenParams.edition!=="pro"&&tokenParams.edition!=="enterprise"){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"OpenVidu Virtual Background API is available from OpenVidu Pro edition onwards"))}openviduToken=encodeURIComponent(btoa(openviduToken));logger.info("Applying Virtual Background to stream "+this.streamId);const afterScriptLoaded=()=>__awaiter(this,void 0,void 0,function*(){try{const id=this.streamId+"_"+(0,uuid_1.v4)();const mediaStreamClone=this.mediaStream.clone();const videoClone=this.streamManager.videos[0].video.cloneNode(false);videoClone.id=VirtualBackground.VirtualBackground.SOURCE_VIDEO_PREFIX+id;videoClone.srcObject=mediaStreamClone;videoClone.muted=true;this.virtualBackgroundSourceElements={videoClone:videoClone,mediaStreamClone:mediaStreamClone};VirtualBackground.VirtualBackground.hideHtmlElement(videoClone,false);VirtualBackground.VirtualBackground.appendHtmlElementToHiddenContainer(videoClone,id);yield videoClone.play();const VB=new VirtualBackground.VirtualBackground({id:id,openviduServerUrl:new URL(tokenParams.httpUri),openviduToken:openviduToken,inputVideo:videoClone,inputResolution:"160x96",outputFramerate:24});let filteredVideo;switch(type){case"VB:blur":{filteredVideo=yield VB.backgroundBlur(options);break}case"VB:image":{filteredVideo=yield VB.backgroundImage(options);break}default:throw new Error("Unknown Virtual Background filter: "+type)}this.virtualBackgroundSinkElements={VB:VB,video:filteredVideo};videoClone.style.display="none";if(this.streamManager.remote){this.streamManager.replaceTrackInMediaStream(this.virtualBackgroundSinkElements.video.srcObject.getVideoTracks()[0],false)}else{this.streamManager.replaceTrackAux(this.virtualBackgroundSinkElements.video.srcObject.getVideoTracks()[0],false)}resolveApplyFilter(undefined,false)}catch(error){if(error.name===OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR){resolveApplyFilter(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,error.message),false)}else{resolveApplyFilter(error,false)}}});if(typeof VirtualBackground==="undefined"){let script=document.createElement("script");script.type="text/javascript";script.src=tokenParams.httpUri+"/openvidu/virtual-background/openvidu-virtual-background.js?token="+openviduToken;script.onload=()=>__awaiter(this,void 0,void 0,function*(){try{yield afterScriptLoaded();resolve(new Filter_1.Filter(type,options))}catch(error){reject(error)}});document.body.appendChild(script)}else{afterScriptLoaded().then(()=>resolve(new Filter_1.Filter(type,options))).catch(error=>reject(error))}}else{if(!this.session.sessionConnected()){return reject(this.session.notConnectedError())}logger.info("Applying server filter to stream "+this.streamId);options=options!=null?options:{};let optionsString=options;if(typeof optionsString!=="string"){optionsString=JSON.stringify(optionsString)}this.session.openvidu.sendRequest("applyFilter",{streamId:this.streamId,type:type,options:optionsString},(error,response)=>{resolveApplyFilter(error,true)})}}))}removeFilter(){return __awaiter(this,void 0,void 0,function*(){return yield this.removeFilterAux(false)})}getRTCPeerConnection(){return this.webRtcPeer.pc}getMediaStream(){return this.mediaStream}removeFilterAux(isDisposing){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){var _a;const resolveRemoveFilter=(error,triggerEvent)=>{if(error){delete this.filter;logger.error("Error removing filter for Stream "+this.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to remove a filter"))}else{return reject(error)}}else{logger.info("Filter successfully removed from Stream "+this.streamId);const oldValue=this.filter;delete this.filter;if(triggerEvent){this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,this,"filter",this.filter,oldValue,"applyFilter")]);this.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.streamManager,this,"filter",this.filter,oldValue,"applyFilter")])}return resolve()}};if(!!this.filter){if((_a=this.filter)===null||_a===void 0?void 0:_a.type.startsWith("VB:")){try{const mediaStreamClone=this.virtualBackgroundSourceElements.mediaStreamClone;if(!isDisposing){if(this.streamManager.remote){this.streamManager.replaceTrackInMediaStream(mediaStreamClone.getVideoTracks()[0],false)}else{yield this.streamManager.replaceTrackAux(mediaStreamClone.getVideoTracks()[0],false)}}else{mediaStreamClone.getTracks().forEach(track=>track.stop())}this.virtualBackgroundSinkElements.VB.cleanUp();delete this.virtualBackgroundSinkElements;delete this.virtualBackgroundSourceElements;return resolveRemoveFilter(undefined,false)}catch(error){return resolveRemoveFilter(error,false)}}else{if(!this.session.sessionConnected()){return reject(this.session.notConnectedError())}logger.info("Removing filter of stream "+this.streamId);this.session.openvidu.sendRequest("removeFilter",{streamId:this.streamId},(error,response)=>resolveRemoveFilter(error,true))}}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"Stream "+this.streamId+" has no filter applied"))}}))}setMediaStream(mediaStream){this.mediaStream=mediaStream}updateMediaStreamInVideos(){this.ee.emitEvent("mediastream-updated",[])}getWebRtcPeer(){return this.webRtcPeer}subscribeToMyRemote(value){this.isSubscribeToRemote=value}setOutboundStreamOptions(outboundStreamOpts){this.outboundStreamOpts=outboundStreamOpts}subscribe(){return new Promise((resolve,reject)=>{this.initWebRtcPeerReceive(false).then(()=>resolve()).catch(error=>reject(error))})}publish(){return new Promise((resolve,reject)=>{if(this.isLocalStreamReadyToPublish){this.initWebRtcPeerSend(false).then(()=>resolve()).catch(error=>reject(error))}else{this.ee.once("stream-ready-to-publish",()=>{this.publish().then(()=>resolve()).catch(error=>reject(error))})}})}disposeWebRtcPeer(){let webrtcId;if(!!this.webRtcPeer){this.webRtcPeer.dispose();webrtcId=this.webRtcPeer.getId()}this.stopWebRtcStats();logger.info((!!this.outboundStreamOpts?"Outbound ":"Inbound ")+"RTCPeerConnection with id ["+webrtcId+"] from 'Stream' with id ["+this.streamId+"] is now closed")}disposeMediaStream(){return __awaiter(this,void 0,void 0,function*(){if(!!this.filter&&this.filter.type.startsWith("VB:")){try{yield this.removeFilterAux(true);console.debug(`Success removing Virtual Background filter for stream ${this.streamId}`)}catch(error){console.error(`Error removing Virtual Background filter for stream ${this.streamId}`,error)}}if(this.mediaStream){this.mediaStream.getAudioTracks().forEach(track=>{track.stop()});this.mediaStream.getVideoTracks().forEach(track=>{track.stop()});delete this.mediaStream}if(this.localMediaStreamWhenSubscribedToRemote){this.localMediaStreamWhenSubscribedToRemote.getAudioTracks().forEach(track=>{track.stop()});this.localMediaStreamWhenSubscribedToRemote.getVideoTracks().forEach(track=>{track.stop()});delete this.localMediaStreamWhenSubscribedToRemote}if(!!this.speechEvent){if(!!this.speechEvent.stop){this.speechEvent.stop()}delete this.speechEvent}logger.info((!!this.outboundStreamOpts?"Local ":"Remote ")+"MediaStream from 'Stream' with id ["+this.streamId+"] is now disposed")})}displayMyRemote(){return this.isSubscribeToRemote}isSendAudio(){return!!this.outboundStreamOpts&&this.outboundStreamOpts.publisherProperties.audioSource!==null&&this.outboundStreamOpts.publisherProperties.audioSource!==false}isSendVideo(){return!!this.outboundStreamOpts&&this.outboundStreamOpts.publisherProperties.videoSource!==null&&this.outboundStreamOpts.publisherProperties.videoSource!==false}isSendScreen(){let screen=false;if(typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack){let trackSettings=this.outboundStreamOpts.publisherProperties.videoSource.getSettings();if(trackSettings.displaySurface){screen=["monitor","window","browser"].includes(trackSettings.displaySurface)}}if(!screen&&platform.isElectron()){screen=typeof this.outboundStreamOpts.publisherProperties.videoSource==="string"&&this.outboundStreamOpts.publisherProperties.videoSource.startsWith("screen:")}if(!screen){screen=this.outboundStreamOpts.publisherProperties.videoSource==="screen"}return!!this.outboundStreamOpts&&screen}enableHarkSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkSpeakingEnabled&&!!this.speechEvent){this.harkSpeakingEnabled=true;this.speechEvent.on("speaking",()=>{this.session.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStartSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStartSpeaking",this.connection,this.streamId)]);this.harkSpeakingEnabledOnce=false})}}enableOnceHarkSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkSpeakingEnabledOnce&&!!this.speechEvent){this.harkSpeakingEnabledOnce=true;this.speechEvent.once("speaking",()=>{if(this.harkSpeakingEnabledOnce){this.session.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStartSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStartSpeaking",this.connection,this.streamId)])}this.disableHarkSpeakingEvent(true)})}}disableHarkSpeakingEvent(disabledByOnce){if(!!this.speechEvent){this.harkSpeakingEnabledOnce=false;if(disabledByOnce){if(this.harkSpeakingEnabled){return}}else{this.harkSpeakingEnabled=false}if(this.harkVolumeChangeEnabled||this.harkVolumeChangeEnabledOnce||this.harkStoppedSpeakingEnabled||this.harkStoppedSpeakingEnabledOnce){this.speechEvent.off("speaking")}else{this.speechEvent.stop();delete this.speechEvent}}}enableHarkStoppedSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkStoppedSpeakingEnabled&&!!this.speechEvent){this.harkStoppedSpeakingEnabled=true;this.speechEvent.on("stopped_speaking",()=>{this.session.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStopSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStopSpeaking",this.connection,this.streamId)]);this.harkStoppedSpeakingEnabledOnce=false})}}enableOnceHarkStoppedSpeakingEvent(){this.setHarkListenerIfNotExists();if(!this.harkStoppedSpeakingEnabledOnce&&!!this.speechEvent){this.harkStoppedSpeakingEnabledOnce=true;this.speechEvent.once("stopped_speaking",()=>{if(this.harkStoppedSpeakingEnabledOnce){this.session.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.session,"publisherStopSpeaking",this.connection,this.streamId)]);this.streamManager.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(this.streamManager,"publisherStopSpeaking",this.connection,this.streamId)])}this.disableHarkStoppedSpeakingEvent(true)})}}disableHarkStoppedSpeakingEvent(disabledByOnce){if(!!this.speechEvent){this.harkStoppedSpeakingEnabledOnce=false;if(disabledByOnce){if(this.harkStoppedSpeakingEnabled){return}}else{this.harkStoppedSpeakingEnabled=false}if(this.harkVolumeChangeEnabled||this.harkVolumeChangeEnabledOnce||this.harkSpeakingEnabled||this.harkSpeakingEnabledOnce){this.speechEvent.off("stopped_speaking")}else{this.speechEvent.stop();delete this.speechEvent}}}enableHarkVolumeChangeEvent(force){if(this.setHarkListenerIfNotExists()){if(!this.harkVolumeChangeEnabled||force){this.harkVolumeChangeEnabled=true;this.speechEvent.on("volume_change",harkEvent=>{const oldValue=this.speechEvent.oldVolumeValue;const value={newValue:harkEvent,oldValue:oldValue};this.speechEvent.oldVolumeValue=harkEvent;this.streamManager.emitEvent("streamAudioVolumeChange",[new StreamManagerEvent_1.StreamManagerEvent(this.streamManager,"streamAudioVolumeChange",value)])})}}else{this.harkVolumeChangeEnabled=true}}enableOnceHarkVolumeChangeEvent(force){if(this.setHarkListenerIfNotExists()){if(!this.harkVolumeChangeEnabledOnce||force){this.harkVolumeChangeEnabledOnce=true;this.speechEvent.once("volume_change",harkEvent=>{const oldValue=this.speechEvent.oldVolumeValue;const value={newValue:harkEvent,oldValue:oldValue};this.speechEvent.oldVolumeValue=harkEvent;this.disableHarkVolumeChangeEvent(true);this.streamManager.emitEvent("streamAudioVolumeChange",[new StreamManagerEvent_1.StreamManagerEvent(this.streamManager,"streamAudioVolumeChange",value)])})}}else{this.harkVolumeChangeEnabledOnce=true}}disableHarkVolumeChangeEvent(disabledByOnce){if(!!this.speechEvent){this.harkVolumeChangeEnabledOnce=false;if(disabledByOnce){if(this.harkVolumeChangeEnabled){return}}else{this.harkVolumeChangeEnabled=false}if(this.harkSpeakingEnabled||this.harkSpeakingEnabledOnce||this.harkStoppedSpeakingEnabled||this.harkStoppedSpeakingEnabledOnce){this.speechEvent.off("volume_change")}else{this.speechEvent.stop();delete this.speechEvent}}}isLocal(){return!this.inboundStreamOpts&&!!this.outboundStreamOpts}getSelectedIceCandidate(){return new Promise((resolve,reject)=>{this.webRtcStats.getSelectedIceCandidateInfo().then(report=>resolve(report)).catch(error=>reject(error))})}getRemoteIceCandidateList(){return this.webRtcPeer.remoteCandidatesQueue}getLocalIceCandidateList(){return this.webRtcPeer.localCandidatesQueue}streamIceConnectionStateBroken(){if(!this.getWebRtcPeer()||!this.getRTCPeerConnection()){return false}if(!!this.session.openvidu.advancedConfiguration.forceMediaReconnectionAfterNetworkDrop){logger.warn(`OpenVidu Browser advanced configuration option "forceMediaReconnectionAfterNetworkDrop" is enabled. Stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) will force a reconnection`);return true}else{const iceConnectionState=this.getRTCPeerConnection().iceConnectionState;return iceConnectionState!=="connected"&&iceConnectionState!=="completed"}}setHarkListenerIfNotExists(){if(!!this.mediaStream){if(!this.speechEvent){const harkOptions=!!this.harkOptions?this.harkOptions:this.session.openvidu.advancedConfiguration.publisherSpeakingEventsOptions||{};harkOptions.interval=typeof harkOptions.interval==="number"?harkOptions.interval:100;harkOptions.threshold=typeof harkOptions.threshold==="number"?harkOptions.threshold:-50;this.speechEvent=hark(this.mediaStream,harkOptions)}return true}return false}setupReconnectionEventEmitter(resolve,reject){if(this.reconnectionEventEmitter==undefined){this.reconnectionEventEmitter=new EventEmitter;return false}else{console.warn(`Trying to reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) but an ongoing reconnection process is active. Waiting for response...`);this.reconnectionEventEmitter.once("success",()=>resolve());this.reconnectionEventEmitter.once("error",error=>reject(error));return true}}initWebRtcPeerSend(reconnect){return new Promise((resolve,reject)=>{var _a;if(reconnect){if(this.setupReconnectionEventEmitter(resolve,reject)){return}}else{this.initHarkEvents()}const finalResolve=()=>{var _a;if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("success");delete this.reconnectionEventEmitter}return resolve()};const finalReject=error=>{var _a;if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("error",[error]);delete this.reconnectionEventEmitter}return reject(error)};const successOfferCallback=sdpOfferParam=>{logger.debug("Sending SDP offer to publish as "+this.streamId,sdpOfferParam);const method=reconnect?"reconnectStream":"publishVideo";let params;if(reconnect){params={stream:this.streamId,sdpString:sdpOfferParam}}else{let typeOfVideo;if(this.isSendVideo()){typeOfVideo=typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack?TypeOfVideo_1.TypeOfVideo.CUSTOM:this.isSendScreen()?TypeOfVideo_1.TypeOfVideo.SCREEN:TypeOfVideo_1.TypeOfVideo.CAMERA}params={doLoopback:this.displayMyRemote()||false,hasAudio:this.isSendAudio(),hasVideo:this.isSendVideo(),audioActive:this.audioActive,videoActive:this.videoActive,typeOfVideo:typeOfVideo,frameRate:!!this.frameRate?this.frameRate:-1,videoDimensions:JSON.stringify(this.videoDimensions),filter:this.outboundStreamOpts.publisherProperties.filter,sdpOffer:sdpOfferParam}}this.session.openvidu.sendRequest(method,params,(error,response)=>{if(error){if(error.code===401){finalReject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to publish"))}else{finalReject("Error on publishVideo: "+JSON.stringify(error))}}else{this.webRtcPeer.processRemoteAnswer(response.sdpAnswer).then(()=>{this.streamId=response.id;this.creationTime=response.createdAt;this.isLocalStreamPublished=true;this.publishedOnce=true;if(this.displayMyRemote()){this.localMediaStreamWhenSubscribedToRemote=this.mediaStream;this.remotePeerSuccessfullyEstablished(reconnect)}if(reconnect){this.ee.emitEvent("stream-reconnected-by-publisher",[])}else{this.ee.emitEvent("stream-created-by-publisher",[])}this.initWebRtcStats();logger.info("'Publisher' ("+this.streamId+") successfully "+(reconnect?"reconnected":"published")+" to session");finalResolve()}).catch(error=>{finalReject(error)})}})};const config={mediaConstraints:{audio:this.hasAudio,video:this.hasVideo},simulcast:(_a=this.outboundStreamOpts.publisherProperties.videoSimulcast)!==null&&_a!==void 0?_a:this.session.openvidu.videoSimulcast,onIceCandidate:this.connection.sendIceCandidate.bind(this.connection),onIceConnectionStateException:this.onIceConnectionStateExceptionHandler.bind(this),iceServers:this.getIceServersConf(),rtcConfiguration:this.session.openvidu.advancedConfiguration.rtcConfiguration,mediaStream:this.mediaStream,mediaServer:this.session.openvidu.mediaServer,typeOfVideo:this.typeOfVideo?TypeOfVideo_1.TypeOfVideo[this.typeOfVideo]:undefined};if(this.session.openvidu.mediaServer!=="mediasoup"){config.simulcast=false}if(reconnect){this.disposeWebRtcPeer()}if(this.displayMyRemote()){this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerSendrecv(config)}else{this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerSendonly(config)}this.webRtcPeer.addIceConnectionStateChangeListener("publisher of "+this.connection.connectionId);this.webRtcPeer.createOffer().then(sdpOffer=>{this.webRtcPeer.processLocalOffer(sdpOffer).then(()=>{successOfferCallback(sdpOffer.sdp)}).catch(error=>{finalReject(new Error("(publish) SDP process local offer error: "+JSON.stringify(error)))})}).catch(error=>{finalReject(new Error("(publish) SDP create offer error: "+JSON.stringify(error)))})})}finalResolveForSubscription(reconnect,resolve){var _a;logger.info("'Subscriber' ("+this.streamId+") successfully "+(reconnect?"reconnected":"subscribed"));this.remotePeerSuccessfullyEstablished(reconnect);this.initWebRtcStats();if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("success");delete this.reconnectionEventEmitter}return resolve()}finalRejectForSubscription(reconnect,error,reject){var _a;logger.error("Error for 'Subscriber' ("+this.streamId+") while trying to "+(reconnect?"reconnect":"subscribe")+": "+error.toString());if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("error",[error]);delete this.reconnectionEventEmitter}return reject(error)}initWebRtcPeerReceive(reconnect){return new Promise((resolve,reject)=>{if(reconnect){if(this.setupReconnectionEventEmitter(resolve,reject)){return}}if(this.session.openvidu.mediaServer==="mediasoup"){this.initWebRtcPeerReceiveFromServer(reconnect).then(()=>this.finalResolveForSubscription(reconnect,resolve)).catch(error=>this.finalRejectForSubscription(reconnect,error,reject))}else{this.initWebRtcPeerReceiveFromClient(reconnect).then(()=>this.finalResolveForSubscription(reconnect,resolve)).catch(error=>this.finalRejectForSubscription(reconnect,error,reject))}})}initWebRtcPeerReceiveFromClient(reconnect){return new Promise((resolve,reject)=>{this.completeWebRtcPeerReceive(reconnect,false).then(response=>{this.webRtcPeer.processRemoteAnswer(response.sdpAnswer).then(()=>resolve()).catch(error=>reject(error))}).catch(error=>reject(error))})}initWebRtcPeerReceiveFromServer(reconnect){return new Promise((resolve,reject)=>{this.session.openvidu.sendRequest("prepareReceiveVideoFrom",{sender:this.streamId,reconnect:reconnect},(error,response)=>{if(error){return reject(new Error("Error on prepareReceiveVideoFrom: "+JSON.stringify(error)))}else{this.completeWebRtcPeerReceive(reconnect,false,response.sdpOffer).then(()=>resolve()).catch(error=>reject(error))}})})}completeWebRtcPeerReceive(reconnect,forciblyReconnect,sdpOfferByServer){return new Promise((resolve,reject)=>{logger.debug("'Session.subscribe(Stream)' called");const sendSdpToServer=sdpString=>{logger.debug(`Sending local SDP ${!!sdpOfferByServer?"answer":"offer"} to subscribe to ${this.streamId}`,sdpString);const method=reconnect?"reconnectStream":"receiveVideoFrom";const params={};params[reconnect?"stream":"sender"]=this.streamId;if(!!sdpOfferByServer){params[reconnect?"sdpString":"sdpAnswer"]=sdpString}else{params["sdpOffer"]=sdpString}if(reconnect){params["forciblyReconnect"]=forciblyReconnect}this.session.openvidu.sendRequest(method,params,(error,response)=>{if(error){return reject(new Error("Error on "+method+" : "+JSON.stringify(error)))}else{return resolve(response)}})};const config={mediaConstraints:{audio:this.hasAudio,video:this.hasVideo},simulcast:false,onIceCandidate:this.connection.sendIceCandidate.bind(this.connection),onIceConnectionStateException:this.onIceConnectionStateExceptionHandler.bind(this),iceServers:this.getIceServersConf(),rtcConfiguration:this.session.openvidu.advancedConfiguration.rtcConfiguration,mediaServer:this.session.openvidu.mediaServer,typeOfVideo:this.typeOfVideo?TypeOfVideo_1.TypeOfVideo[this.typeOfVideo]:undefined};if(reconnect){this.disposeWebRtcPeer()}this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerRecvonly(config);this.webRtcPeer.addIceConnectionStateChangeListener(this.streamId);if(!!sdpOfferByServer){this.webRtcPeer.processRemoteOffer(sdpOfferByServer).then(()=>{this.webRtcPeer.createAnswer().then(sdpAnswer=>{this.webRtcPeer.processLocalAnswer(sdpAnswer).then(()=>{sendSdpToServer(sdpAnswer.sdp)}).catch(error=>reject(new Error("(subscribe) SDP process local answer error: "+JSON.stringify(error))))}).catch(error=>reject(new Error("(subscribe) SDP create answer error: "+JSON.stringify(error))))}).catch(error=>reject(new Error("(subscribe) SDP process remote offer error: "+JSON.stringify(error))))}else{this.webRtcPeer.createOffer().then(sdpOffer=>{this.webRtcPeer.processLocalOffer(sdpOffer).then(()=>{sendSdpToServer(sdpOffer.sdp)}).catch(error=>reject(new Error("(subscribe) SDP process local offer error: "+JSON.stringify(error))))}).catch(error=>reject(new Error("(subscribe) SDP create offer error: "+JSON.stringify(error))))}})}remotePeerSuccessfullyEstablished(reconnect){if(reconnect&&this.mediaStream!=null){this.disposeMediaStream()}this.mediaStream=new MediaStream;let receiver;for(receiver of this.webRtcPeer.pc.getReceivers()){if(!!receiver.track){this.mediaStream.addTrack(receiver.track)}}logger.debug("Peer remote stream",this.mediaStream);if(!!this.mediaStream){if(this.streamManager instanceof Subscriber_1.Subscriber){if(!!this.mediaStream.getAudioTracks()[0]){const enabled=reconnect?this.audioActive:!!this.streamManager.properties.subscribeToAudio;this.mediaStream.getAudioTracks()[0].enabled=enabled}if(!!this.mediaStream.getVideoTracks()[0]){const enabled=reconnect?this.videoActive:!!this.videoActive&&!!this.streamManager.properties.subscribeToVideo;this.mediaStream.getVideoTracks()[0].enabled=enabled}}this.updateMediaStreamInVideos();this.initHarkEvents()}}initHarkEvents(){if(!!this.mediaStream.getAudioTracks()[0]){if(this.session.anySpeechEventListenerEnabled("publisherStartSpeaking",true,this.streamManager)){this.enableOnceHarkSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStartSpeaking",false,this.streamManager)){this.enableHarkSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStopSpeaking",true,this.streamManager)){this.enableOnceHarkStoppedSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStopSpeaking",false,this.streamManager)){this.enableHarkStoppedSpeakingEvent()}if(this.harkVolumeChangeEnabledOnce){this.enableOnceHarkVolumeChangeEvent(true)}if(this.harkVolumeChangeEnabled){this.enableHarkVolumeChangeEvent(true)}}}onIceConnectionStateExceptionHandler(exceptionName,message,data){switch(exceptionName){case ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED:this.onIceConnectionFailed();break;case ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED:this.onIceConnectionDisconnected();break}this.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.session,exceptionName,this,message,data)])}onIceConnectionFailed(){logger.log(`[ICE_CONNECTION_FAILED] Handling ICE_CONNECTION_FAILED event. Reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"})`);this.reconnectStreamAndLogResultingIceConnectionState(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED)}onIceConnectionDisconnected(){logger.log(`[ICE_CONNECTION_DISCONNECTED] Handling ICE_CONNECTION_DISCONNECTED event. Waiting for ICE to be restored and reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) if not possible`);const timeout=this.session.openvidu.advancedConfiguration.iceConnectionDisconnectedExceptionTimeout||4e3;this.awaitWebRtcPeerConnectionState(timeout).then(state=>{switch(state){case"failed":logger.warn(`[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) is now failed after ICE_CONNECTION_DISCONNECTED`);break;case"connected":case"completed":logger.log(`[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) automatically restored after ICE_CONNECTION_DISCONNECTED. Current ICE connection state: ${state}`);break;case"closed":case"checking":case"new":case"disconnected":logger.warn(`[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) couldn't be restored after ICE_CONNECTION_DISCONNECTED event. Current ICE connection state after ${timeout} ms: ${state}`);this.reconnectStreamAndLogResultingIceConnectionState(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED);break}})}reconnectStreamAndLogResultingIceConnectionState(event){return __awaiter(this,void 0,void 0,function*(){try{const finalIceStateAfterReconnection=yield this.reconnectStreamAndReturnIceConnectionState(event);switch(finalIceStateAfterReconnection){case"connected":case"completed":logger.log(`[${event}] Stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) successfully reconnected after ${event}. Current ICE connection state: ${finalIceStateAfterReconnection}`);break;default:logger.error(`[${event}] Stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) failed to reconnect after ${event}. Current ICE connection state: ${finalIceStateAfterReconnection}`);break}}catch(error){logger.error(`[${event}] Error reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) after ${event}: ${error}`)}})}reconnectStreamAndReturnIceConnectionState(event){return __awaiter(this,void 0,void 0,function*(){logger.log(`[${event}] Reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) after event ${event}`);try{yield this.reconnectStream(event);const timeout=this.session.openvidu.advancedConfiguration.iceConnectionDisconnectedExceptionTimeout||4e3;return this.awaitWebRtcPeerConnectionState(timeout)}catch(error){logger.warn(`[${event}] Error reconnecting stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}). Reason: ${error}`);return this.awaitWebRtcPeerConnectionState(1)}})}awaitWebRtcPeerConnectionState(timeout){return __awaiter(this,void 0,void 0,function*(){let state=this.getRTCPeerConnection().iceConnectionState;const interval=150;const intervals=Math.ceil(timeout/interval);for(let i=0;i<intervals;i++){state=this.getRTCPeerConnection().iceConnectionState;if(state==="connected"||state==="completed"){break}yield new Promise(resolve=>setTimeout(resolve,interval))}return state})}reconnectStream(event){return __awaiter(this,void 0,void 0,function*(){const isWsConnected=yield this.isWebsocketConnected(event,3e3);if(isWsConnected){logger.log(`[${event}] Trying to reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) and the websocket is opened`);if(this.isLocal()){return this.initWebRtcPeerSend(true)}else{return this.initWebRtcPeerReceive(true)}}else{const errorMsg=`[${event}] Trying to reconnect stream ${this.streamId} (${this.isLocal()?"Publisher":"Subscriber"}) but the websocket wasn't opened`;logger.error(errorMsg);throw Error(errorMsg)}})}isWebsocketConnected(event,msResponseTimeout){return new Promise((resolve,reject)=>{const wsReadyState=this.session.openvidu.getWsReadyState();if(wsReadyState===1){const responseTimeout=setTimeout(()=>{console.warn(`[${event}] Websocket timeout of ${msResponseTimeout}ms`);return resolve(false)},msResponseTimeout);this.session.openvidu.sendRequest("echo",{},(error,response)=>{clearTimeout(responseTimeout);if(!!error){console.warn(`[${event}] Websocket 'echo' returned error: ${error}`);return resolve(false)}else{return resolve(true)}})}else{console.warn(`[${event}] Websocket readyState is ${wsReadyState}`);return resolve(false)}})}initWebRtcStats(){this.webRtcStats=new WebRtcStats_1.WebRtcStats(this);this.webRtcStats.initWebRtcStats()}stopWebRtcStats(){if(!!this.webRtcStats&&this.webRtcStats.isEnabled()){this.webRtcStats.stopWebRtcStats()}}getIceServersConf(){var _a;let returnValue;if(!!this.session.openvidu.advancedConfiguration.iceServers){returnValue=this.session.openvidu.advancedConfiguration.iceServers==="freeice"?undefined:this.session.openvidu.advancedConfiguration.iceServers}else if(!!((_a=this.session.openvidu.advancedConfiguration.rtcConfiguration)===null||_a===void 0?void 0:_a.iceServers)){returnValue=this.session.openvidu.advancedConfiguration.rtcConfiguration.iceServers}else if(this.session.openvidu.iceServers){returnValue=this.session.openvidu.iceServers}else{returnValue=undefined}return returnValue}gatherStatsForPeer(){return new Promise((resolve,reject)=>{if(this.isLocal()){this.getRTCPeerConnection().getSenders().forEach(sender=>sender.getStats().then(response=>{response.forEach(report=>{if(this.isReportWanted(report)){const finalReport={};finalReport["type"]=report.type;finalReport["timestamp"]=report.timestamp;finalReport["id"]=report.id;if(report.type==="outbound-rtp"){finalReport["ssrc"]=report.ssrc;finalReport["firCount"]=report.firCount;finalReport["pliCount"]=report.pliCount;finalReport["nackCount"]=report.nackCount;finalReport["qpSum"]=report.qpSum;if(!!report.kind){finalReport["mediaType"]=report.kind}else if(!!report.mediaType){finalReport["mediaType"]=report.mediaType}else{finalReport["mediaType"]=report.id.indexOf("VideoStream")!==-1?"video":"audio"}if(finalReport["mediaType"]==="video"){finalReport["framesEncoded"]=report.framesEncoded}finalReport["packetsSent"]=report.packetsSent;finalReport["bytesSent"]=report.bytesSent}if(report.type==="candidate-pair"&&report.totalRoundTripTime!==undefined){finalReport["availableOutgoingBitrate"]=report.availableOutgoingBitrate;finalReport["rtt"]=report.currentRoundTripTime;finalReport["averageRtt"]=report.totalRoundTripTime/report.responsesReceived}if(report.type==="remote-inbound-rtp"||report.type==="remote-outbound-rtp"){}logger.log(finalReport)}})}))}else{this.getRTCPeerConnection().getReceivers().forEach(receiver=>receiver.getStats().then(response=>{response.forEach(report=>{if(this.isReportWanted(report)){const finalReport={};finalReport["type"]=report.type;finalReport["timestamp"]=report.timestamp;finalReport["id"]=report.id;if(report.type==="inbound-rtp"){finalReport["ssrc"]=report.ssrc;finalReport["firCount"]=report.firCount;finalReport["pliCount"]=report.pliCount;finalReport["nackCount"]=report.nackCount;finalReport["qpSum"]=report.qpSum;if(!!report.kind){finalReport["mediaType"]=report.kind}else if(!!report.mediaType){finalReport["mediaType"]=report.mediaType}else{finalReport["mediaType"]=report.id.indexOf("VideoStream")!==-1?"video":"audio"}if(finalReport["mediaType"]==="video"){finalReport["framesDecoded"]=report.framesDecoded}finalReport["packetsReceived"]=report.packetsReceived;finalReport["packetsLost"]=report.packetsLost;finalReport["jitter"]=report.jitter;finalReport["bytesReceived"]=report.bytesReceived}if(report.type==="candidate-pair"&&report.totalRoundTripTime!==undefined){finalReport["availableIncomingBitrate"]=report.availableIncomingBitrate;finalReport["rtt"]=report.currentRoundTripTime;finalReport["averageRtt"]=report.totalRoundTripTime/report.responsesReceived}if(report.type==="remote-inbound-rtp"||report.type==="remote-outbound-rtp"){}logger.log(finalReport)}})}))}})}isReportWanted(report){return report.type==="inbound-rtp"&&!this.isLocal()||report.type==="outbound-rtp"&&this.isLocal()||report.type==="candidate-pair"&&report.nominated&&report.bytesSent>0}}exports.Stream=Stream},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/TypeOfVideo":54,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/PublisherSpeakingEvent":62,"../OpenViduInternal/Events/StreamManagerEvent":68,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"../OpenViduInternal/WebRtcPeer/WebRtcPeer":86,"../OpenViduInternal/WebRtcStats/WebRtcStats":87,"./Filter":44,"./Subscriber":51,hark:5,uuid:23,"wolfy87-eventemitter":39}],50:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamManager=void 0;const EventDispatcher_1=require("./EventDispatcher");const StreamManagerEvent_1=require("../OpenViduInternal/Events/StreamManagerEvent");const VideoElementEvent_1=require("../OpenViduInternal/Events/VideoElementEvent");const ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");const VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const Platform_1=require("../OpenViduInternal/Utils/Platform");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class StreamManager extends EventDispatcher_1.EventDispatcher{constructor(stream,targetElement){super();this.videos=[];this.lazyLaunchVideoElementCreatedEvent=false;platform=Platform_1.PlatformUtils.getInstance();this.stream=stream;this.stream.streamManager=this;this.remote=!this.stream.isLocal();if(!!targetElement){let targEl;if(typeof targetElement==="string"){targEl=document.getElementById(targetElement)}else if(targetElement instanceof HTMLElement){targEl=targetElement}if(!!targEl){this.firstVideoElement={targetElement:targEl,video:document.createElement("video"),id:"",canplayListenerAdded:false};if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){this.firstVideoElement.video.playsInline=true}this.targetElement=targEl;this.element=targEl}}this.canPlayListener=()=>{this.deactivateStreamPlayingEventExceptionTimeout();this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}on(type,handler){super.onAux(type,"Event '"+type+"' triggered by '"+(this.remote?"Subscriber":"Publisher")+"'",handler);if(type==="videoElementCreated"){if(!!this.stream&&this.lazyLaunchVideoElementCreatedEvent){this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(this.videos[0].video,this,"videoElementCreated")]);this.lazyLaunchVideoElementCreatedEvent=false}}if(type==="streamPlaying"){if(this.videos[0]&&this.videos[0].video&&this.videos[0].video.currentTime>0&&this.videos[0].video.paused===false&&this.videos[0].video.ended===false&&this.videos[0].video.readyState===4){this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}if(this.stream.hasAudio){if(type==="publisherStartSpeaking"){this.stream.enableHarkSpeakingEvent()}if(type==="publisherStopSpeaking"){this.stream.enableHarkStoppedSpeakingEvent()}if(type==="streamAudioVolumeChange"){this.stream.enableHarkVolumeChangeEvent(false)}}return this}once(type,handler){super.onceAux(type,"Event '"+type+"' triggered once by '"+(this.remote?"Subscriber":"Publisher")+"'",handler);if(type==="videoElementCreated"){if(!!this.stream&&this.lazyLaunchVideoElementCreatedEvent){this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(this.videos[0].video,this,"videoElementCreated")])}}if(type==="streamPlaying"){if(this.videos[0]&&this.videos[0].video&&this.videos[0].video.currentTime>0&&this.videos[0].video.paused===false&&this.videos[0].video.ended===false&&this.videos[0].video.readyState===4){this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}if(this.stream.hasAudio){if(type==="publisherStartSpeaking"){this.stream.enableOnceHarkSpeakingEvent()}if(type==="publisherStopSpeaking"){this.stream.enableOnceHarkStoppedSpeakingEvent()}if(type==="streamAudioVolumeChange"){this.stream.enableOnceHarkVolumeChangeEvent(false)}}return this}off(type,handler){super.offAux(type,handler);if(type==="publisherStartSpeaking"){const remainingStartSpeakingEventListeners=this.ee.getListeners(type).length+this.stream.session.ee.getListeners(type).length;if(remainingStartSpeakingEventListeners===0){this.stream.disableHarkSpeakingEvent(false)}}if(type==="publisherStopSpeaking"){const remainingStopSpeakingEventListeners=this.ee.getListeners(type).length+this.stream.session.ee.getListeners(type).length;if(remainingStopSpeakingEventListeners===0){this.stream.disableHarkStoppedSpeakingEvent(false)}}if(type==="streamAudioVolumeChange"){const remainingVolumeEventListeners=this.ee.getListeners(type).length;if(remainingVolumeEventListeners===0){this.stream.disableHarkVolumeChangeEvent(false)}}return this}addVideoElement(video){this.initializeVideoProperties(video);if(!this.remote&&this.stream.displayMyRemote()){if(video.srcObject!==this.stream.getMediaStream()){video.srcObject=this.stream.getMediaStream()}}for(const v of this.videos){if(v.video===video){return 0}}let returnNumber=1;for(const streamManager of this.stream.session.streamManagers){if(streamManager.disassociateVideo(video)){returnNumber=-1;break}}this.stream.session.streamManagers.forEach(streamManager=>{streamManager.disassociateVideo(video)});this.pushNewStreamManagerVideo({video:video,id:video.id,canplayListenerAdded:false});logger.info("New video element associated to ",this);return returnNumber}createVideoElement(targetElement,insertMode){let targEl;if(typeof targetElement==="string"){targEl=document.getElementById(targetElement);if(!targEl){throw new Error("The provided 'targetElement' couldn't be resolved to any HTML element: "+targetElement)}}else if(targetElement instanceof HTMLElement){targEl=targetElement}else{throw new Error("The provided 'targetElement' couldn't be resolved to any HTML element: "+targetElement)}const video=this.createVideo();this.initializeVideoProperties(video);let insMode=!!insertMode?insertMode:VideoInsertMode_1.VideoInsertMode.APPEND;switch(insMode){case VideoInsertMode_1.VideoInsertMode.AFTER:targEl.parentNode.insertBefore(video,targEl.nextSibling);break;case VideoInsertMode_1.VideoInsertMode.APPEND:targEl.appendChild(video);break;case VideoInsertMode_1.VideoInsertMode.BEFORE:targEl.parentNode.insertBefore(video,targEl);break;case VideoInsertMode_1.VideoInsertMode.PREPEND:targEl.insertBefore(video,targEl.childNodes[0]);break;case VideoInsertMode_1.VideoInsertMode.REPLACE:targEl.parentNode.replaceChild(video,targEl);break;default:insMode=VideoInsertMode_1.VideoInsertMode.APPEND;targEl.appendChild(video);break}const v={targetElement:targEl,video:video,insertMode:insMode,id:video.id,canplayListenerAdded:false};this.pushNewStreamManagerVideo(v);this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(v.video,this,"videoElementCreated")]);this.lazyLaunchVideoElementCreatedEvent=!!this.firstVideoElement;return video}updatePublisherSpeakingEventsOptions(publisherSpeakingEventsOptions){const currentHarkOptions=!!this.stream.harkOptions?this.stream.harkOptions:this.stream.session.openvidu.advancedConfiguration.publisherSpeakingEventsOptions||{};const newInterval=typeof publisherSpeakingEventsOptions.interval==="number"?publisherSpeakingEventsOptions.interval:typeof currentHarkOptions.interval==="number"?currentHarkOptions.interval:100;const newThreshold=typeof publisherSpeakingEventsOptions.threshold==="number"?publisherSpeakingEventsOptions.threshold:typeof currentHarkOptions.threshold==="number"?currentHarkOptions.threshold:-50;this.stream.harkOptions={interval:newInterval,threshold:newThreshold};if(!!this.stream.speechEvent){this.stream.speechEvent.setInterval(newInterval);this.stream.speechEvent.setThreshold(newThreshold)}}initializeVideoProperties(video){if(!(!this.remote&&this.stream.displayMyRemote())){if(video.srcObject!==this.stream.getMediaStream()){video.srcObject=this.stream.getMediaStream()}}video.autoplay=true;video.controls=false;if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){video.playsInline=true}if(!video.id){video.id=(this.remote?"remote-":"local-")+"video-"+this.stream.streamId;if(!this.id&&!!this.targetElement){this.id=video.id}}if(this.remote&&this.isMirroredVideo(video)){this.removeMirrorVideo(video)}else if(!this.remote&&!this.stream.displayMyRemote()){video.muted=true;if(this.isMirroredVideo(video)&&!this.stream.outboundStreamOpts.publisherProperties.mirror){this.removeMirrorVideo(video)}else if(this.stream.outboundStreamOpts.publisherProperties.mirror&&!this.stream.isSendScreen()){this.mirrorVideo(video)}}}removeAllVideos(){for(let i=this.stream.session.streamManagers.length-1;i>=0;--i){if(this.stream.session.streamManagers[i]===this){this.stream.session.streamManagers.splice(i,1)}}this.videos.forEach(streamManagerVideo=>{if(!!streamManagerVideo.video&&!!streamManagerVideo.video.removeEventListener){streamManagerVideo.video.removeEventListener("canplay",this.canPlayListener)}streamManagerVideo.canplayListenerAdded=false;if(!!streamManagerVideo.targetElement){streamManagerVideo.video.parentNode.removeChild(streamManagerVideo.video);this.ee.emitEvent("videoElementDestroyed",[new VideoElementEvent_1.VideoElementEvent(streamManagerVideo.video,this,"videoElementDestroyed")])}this.removeSrcObject(streamManagerVideo);this.videos=this.videos.filter(v=>!v.targetElement)})}disassociateVideo(video){let disassociated=false;for(let i=0;i<this.videos.length;i++){if(this.videos[i].video===video){this.videos[i].video.removeEventListener("canplay",this.canPlayListener);this.videos.splice(i,1);disassociated=true;logger.info("Video element disassociated from ",this);break}}return disassociated}addPlayEventToFirstVideo(){if(!!this.videos[0]&&!!this.videos[0].video&&!this.videos[0].canplayListenerAdded){this.activateStreamPlayingEventExceptionTimeout();this.videos[0].video.addEventListener("canplay",this.canPlayListener);this.videos[0].canplayListenerAdded=true}}updateMediaStream(mediaStream){this.videos.forEach(streamManagerVideo=>{streamManagerVideo.video.srcObject=mediaStream;if(platform.isIonicIos()){const vParent=streamManagerVideo.video.parentElement;const newVideo=streamManagerVideo.video;vParent.replaceChild(newVideo,streamManagerVideo.video);streamManagerVideo.video=newVideo}})}emitEvent(type,eventArray){this.ee.emitEvent(type,eventArray)}createVideo(){return document.createElement("video")}removeSrcObject(streamManagerVideo){streamManagerVideo.video.srcObject=null;this.deactivateStreamPlayingEventExceptionTimeout()}pushNewStreamManagerVideo(streamManagerVideo){this.videos.push(streamManagerVideo);this.addPlayEventToFirstVideo();if(this.stream.session.streamManagers.indexOf(this)===-1){this.stream.session.streamManagers.push(this)}}mirrorVideo(video){if(!platform.isIonicIos()){video.style.transform="rotateY(180deg)";video.style.webkitTransform="rotateY(180deg)"}}removeMirrorVideo(video){video.style.transform="unset";video.style.webkitTransform="unset"}isMirroredVideo(video){return video.style.transform==="rotateY(180deg)"||video.style.webkitTransform==="rotateY(180deg)"}activateStreamPlayingEventExceptionTimeout(){if(!this.remote){return}if(this.streamPlayingEventExceptionTimeout!=null){return}const msTimeout=this.stream.session.openvidu.advancedConfiguration.noStreamPlayingEventExceptionTimeout||4e3;this.streamPlayingEventExceptionTimeout=setTimeout(()=>{const msg="StreamManager of Stream "+this.stream.streamId+" ("+(this.remote?"Subscriber":"Publisher")+') did not trigger "streamPlaying" event in '+msTimeout+" ms";logger.warn(msg);this.stream.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.stream.session,ExceptionEvent_1.ExceptionEventName.NO_STREAM_PLAYING_EVENT,this,msg)]);delete this.streamPlayingEventExceptionTimeout},msTimeout)}deactivateStreamPlayingEventExceptionTimeout(){clearTimeout(this.streamPlayingEventExceptionTimeout);delete this.streamPlayingEventExceptionTimeout}}exports.StreamManager=StreamManager},{"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/StreamManagerEvent":68,"../OpenViduInternal/Events/VideoElementEvent":70,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./EventDispatcher":43}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Subscriber=void 0;const StreamManager_1=require("./StreamManager");const OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class Subscriber extends StreamManager_1.StreamManager{constructor(stream,targEl,properties){super(stream,targEl);this.element=this.targetElement;this.stream=stream;this.properties=properties}subscribeToAudio(value){this.stream.getMediaStream().getAudioTracks().forEach(track=>{track.enabled=value});this.stream.audioActive=value;logger.info("'Subscriber' has "+(value?"subscribed to":"unsubscribed from")+" its audio stream");return this}subscribeToVideo(value){this.stream.getMediaStream().getVideoTracks().forEach(track=>{track.enabled=value});this.stream.videoActive=value;logger.info("'Subscriber' has "+(value?"subscribed to":"unsubscribed from")+" its video stream");return this}replaceTrackInMediaStream(track,updateLastConstraints){const mediaStream=this.stream.getMediaStream();let removedTrack;if(track.kind==="video"){removedTrack=mediaStream.getVideoTracks()[0];if(updateLastConstraints){this.stream.lastVideoTrackConstraints=track.getConstraints()}}else{removedTrack=mediaStream.getAudioTracks()[0]}mediaStream.removeTrack(removedTrack);removedTrack.stop();mediaStream.addTrack(track)}}exports.Subscriber=Subscriber},{"../OpenViduInternal/Logger/OpenViduLogger":81,"./StreamManager":50}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LocalRecorderState=void 0;var LocalRecorderState;(function(LocalRecorderState){LocalRecorderState["READY"]="READY";LocalRecorderState["RECORDING"]="RECORDING";LocalRecorderState["PAUSED"]="PAUSED";LocalRecorderState["FINISHED"]="FINISHED"})(LocalRecorderState||(exports.LocalRecorderState=LocalRecorderState={}))},{}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OpenViduError=exports.OpenViduErrorName=void 0;var OpenViduErrorName;(function(OpenViduErrorName){OpenViduErrorName["BROWSER_NOT_SUPPORTED"]="BROWSER_NOT_SUPPORTED";OpenViduErrorName["DEVICE_ACCESS_DENIED"]="DEVICE_ACCESS_DENIED";OpenViduErrorName["DEVICE_ALREADY_IN_USE"]="DEVICE_ALREADY_IN_USE";OpenViduErrorName["SCREEN_CAPTURE_DENIED"]="SCREEN_CAPTURE_DENIED";OpenViduErrorName["SCREEN_SHARING_NOT_SUPPORTED"]="SCREEN_SHARING_NOT_SUPPORTED";OpenViduErrorName["SCREEN_EXTENSION_NOT_INSTALLED"]="SCREEN_EXTENSION_NOT_INSTALLED";OpenViduErrorName["SCREEN_EXTENSION_DISABLED"]="SCREEN_EXTENSION_DISABLED";OpenViduErrorName["INPUT_VIDEO_DEVICE_NOT_FOUND"]="INPUT_VIDEO_DEVICE_NOT_FOUND";OpenViduErrorName["INPUT_AUDIO_DEVICE_NOT_FOUND"]="INPUT_AUDIO_DEVICE_NOT_FOUND";OpenViduErrorName["INPUT_AUDIO_DEVICE_GENERIC_ERROR"]="INPUT_AUDIO_DEVICE_GENERIC_ERROR";OpenViduErrorName["NO_INPUT_SOURCE_SET"]="NO_INPUT_SOURCE_SET";OpenViduErrorName["PUBLISHER_PROPERTIES_ERROR"]="PUBLISHER_PROPERTIES_ERROR";OpenViduErrorName["OPENVIDU_PERMISSION_DENIED"]="OPENVIDU_PERMISSION_DENIED";OpenViduErrorName["OPENVIDU_NOT_CONNECTED"]="OPENVIDU_NOT_CONNECTED";OpenViduErrorName["VIRTUAL_BACKGROUND_ERROR"]="VIRTUAL_BACKGROUND_ERROR";OpenViduErrorName["GENERIC_ERROR"]="GENERIC_ERROR"})(OpenViduErrorName||(exports.OpenViduErrorName=OpenViduErrorName={}));class OpenViduError{constructor(name,message){this.name=name;this.message=message}}exports.OpenViduError=OpenViduError},{}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TypeOfVideo=void 0;var TypeOfVideo;(function(TypeOfVideo){TypeOfVideo["CAMERA"]="CAMERA";TypeOfVideo["SCREEN"]="SCREEN";TypeOfVideo["CUSTOM"]="CUSTOM";TypeOfVideo["IPCAM"]="IPCAM"})(TypeOfVideo||(exports.TypeOfVideo=TypeOfVideo={}))},{}],55:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VideoInsertMode=void 0;var VideoInsertMode;(function(VideoInsertMode){VideoInsertMode["AFTER"]="AFTER";VideoInsertMode["APPEND"]="APPEND";VideoInsertMode["BEFORE"]="BEFORE";VideoInsertMode["PREPEND"]="PREPEND";VideoInsertMode["REPLACE"]="REPLACE"})(VideoInsertMode||(exports.VideoInsertMode=VideoInsertMode={}))},{}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConnectionEvent=void 0;const Event_1=require("./Event");class ConnectionEvent extends Event_1.Event{constructor(cancelable,target,type,connection,reason){super(cancelable,target,type);this.connection=connection;this.reason=reason}callDefaultBehavior(){}}exports.ConnectionEvent=ConnectionEvent},{"./Event":58}],57:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConnectionPropertyChangedEvent=void 0;const Event_1=require("./Event");class ConnectionPropertyChangedEvent extends Event_1.Event{constructor(target,connection,changedProperty,newValue,oldValue){super(false,target,"connectionPropertyChanged");this.connection=connection;this.changedProperty=changedProperty;this.newValue=newValue;this.oldValue=oldValue}callDefaultBehavior(){}}exports.ConnectionPropertyChangedEvent=ConnectionPropertyChangedEvent},{"./Event":58}],58:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Event=void 0;class Event{constructor(cancelable,target,type){this.hasBeenPrevented=false;this.cancelable=cancelable;this.target=target;this.type=type}isDefaultPrevented(){return this.hasBeenPrevented}preventDefault(){this.callDefaultBehavior=()=>{};this.hasBeenPrevented=true}}exports.Event=Event},{}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExceptionEvent=exports.ExceptionEventName=void 0;const Event_1=require("./Event");var ExceptionEventName;(function(ExceptionEventName){ExceptionEventName["ICE_CANDIDATE_ERROR"]="ICE_CANDIDATE_ERROR";ExceptionEventName["ICE_CONNECTION_FAILED"]="ICE_CONNECTION_FAILED";ExceptionEventName["ICE_CONNECTION_DISCONNECTED"]="ICE_CONNECTION_DISCONNECTED";ExceptionEventName["NO_STREAM_PLAYING_EVENT"]="NO_STREAM_PLAYING_EVENT";ExceptionEventName["SPEECH_TO_TEXT_DISCONNECTED"]="SPEECH_TO_TEXT_DISCONNECTED"})(ExceptionEventName||(exports.ExceptionEventName=ExceptionEventName={}));class ExceptionEvent extends Event_1.Event{constructor(session,name,origin,message,data){super(false,session,"exception");this.name=name;this.origin=origin;this.message=message;this.data=data}callDefaultBehavior(){}}exports.ExceptionEvent=ExceptionEvent},{"./Event":58}],60:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FilterEvent=void 0;const Event_1=require("./Event");class FilterEvent extends Event_1.Event{constructor(target,eventType,data){super(false,target,eventType);this.data=data}callDefaultBehavior(){}}exports.FilterEvent=FilterEvent},{"./Event":58}],61:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NetworkQualityLevelChangedEvent=void 0;const Event_1=require("./Event");class NetworkQualityLevelChangedEvent extends Event_1.Event{constructor(target,newValue,oldValue,connection){super(false,target,"networkQualityLevelChanged");this.newValue=newValue;this.oldValue=oldValue;this.connection=connection}callDefaultBehavior(){}}exports.NetworkQualityLevelChangedEvent=NetworkQualityLevelChangedEvent},{"./Event":58}],62:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PublisherSpeakingEvent=void 0;const Event_1=require("./Event");class PublisherSpeakingEvent extends Event_1.Event{constructor(target,type,connection,streamId){super(false,target,type);this.type=type;this.connection=connection;this.streamId=streamId}callDefaultBehavior(){}}exports.PublisherSpeakingEvent=PublisherSpeakingEvent},{"./Event":58}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RecordingEvent=void 0;const Event_1=require("./Event");class RecordingEvent extends Event_1.Event{constructor(target,type,id,name,reason){super(false,target,type);this.id=id;if(name!==id){this.name=name}this.reason=reason}callDefaultBehavior(){}}exports.RecordingEvent=RecordingEvent},{"./Event":58}],64:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SessionDisconnectedEvent=void 0;const Event_1=require("./Event");const OpenViduLogger_1=require("../Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class SessionDisconnectedEvent extends Event_1.Event{constructor(target,reason){super(true,target,"sessionDisconnected");this.reason=reason}callDefaultBehavior(){logger.info("Calling default behavior upon '"+this.type+"' event dispatched by 'Session'");const session=this.target;session.remoteConnections.forEach(remoteConnection=>{var _a,_b,_c,_d,_e,_f,_g,_h;const connectionId=remoteConnection.connectionId;if(!!((_a=session.remoteConnections.get(connectionId))===null||_a===void 0?void 0:_a.stream)){(_b=session.remoteConnections.get(connectionId))===null||_b===void 0?void 0:_b.stream.disposeWebRtcPeer();(_c=session.remoteConnections.get(connectionId))===null||_c===void 0?void 0:_c.stream.disposeMediaStream();if((_d=session.remoteConnections.get(connectionId))===null||_d===void 0?void 0:_d.stream.streamManager){(_e=session.remoteConnections.get(connectionId))===null||_e===void 0?void 0:_e.stream.streamManager.removeAllVideos()}const streamId=(_g=(_f=session.remoteConnections.get(connectionId))===null||_f===void 0?void 0:_f.stream)===null||_g===void 0?void 0:_g.streamId;if(!!streamId){session.remoteStreamsCreated.delete(streamId)}(_h=session.remoteConnections.get(connectionId))===null||_h===void 0?void 0:_h.dispose()}session.remoteConnections.delete(connectionId)})}}exports.SessionDisconnectedEvent=SessionDisconnectedEvent},{"../Logger/OpenViduLogger":81,"./Event":58}],65:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SignalEvent=void 0;const Event_1=require("./Event");class SignalEvent extends Event_1.Event{constructor(target,type,data,from){super(false,target,"signal");if(!!type){this.type="signal:"+type}this.data=data;this.from=from}callDefaultBehavior(){}}exports.SignalEvent=SignalEvent},{"./Event":58}],66:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SpeechToTextEvent=void 0;const Event_1=require("./Event");class SpeechToTextEvent extends Event_1.Event{constructor(target,connection,text,reason,raw,lang){super(false,target,"speechToTextMessage");this.connection=connection;this.text=text;this.reason=reason;this.raw=raw;this.lang=lang}callDefaultBehavior(){}}exports.SpeechToTextEvent=SpeechToTextEvent},{"./Event":58}],67:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamEvent=void 0;const Event_1=require("./Event");const Publisher_1=require("../../OpenVidu/Publisher");const Session_1=require("../../OpenVidu/Session");const OpenViduLogger_1=require("../Logger/OpenViduLogger");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();class StreamEvent extends Event_1.Event{constructor(cancelable,target,type,stream,reason){super(cancelable,target,type);this.stream=stream;this.reason=reason}callDefaultBehavior(){if(this.type==="streamDestroyed"){if(this.target instanceof Session_1.Session){logger.info("Calling default behavior upon '"+this.type+"' event dispatched by 'Session'");this.stream.disposeWebRtcPeer()}else if(this.target instanceof Publisher_1.Publisher){logger.info("Calling default behavior upon '"+this.type+"' event dispatched by 'Publisher'");clearInterval(this.target.screenShareResizeInterval);this.stream.isLocalStreamReadyToPublish=false;const openviduPublishers=this.target.openvidu.publishers;for(let i=0;i<openviduPublishers.length;i++){if(openviduPublishers[i]===this.target){openviduPublishers.splice(i,1);break}}}this.stream.disposeMediaStream();if(this.stream.streamManager)this.stream.streamManager.removeAllVideos();this.stream.session.remoteStreamsCreated.delete(this.stream.streamId);const remoteConnection=this.stream.session.remoteConnections.get(this.stream.connection.connectionId);if(!!remoteConnection&&!!remoteConnection.remoteOptions){const streamOptionsServer=remoteConnection.remoteOptions.streams;for(let i=streamOptionsServer.length-1;i>=0;--i){if(streamOptionsServer[i].id===this.stream.streamId){streamOptionsServer.splice(i,1)}}}}}}exports.StreamEvent=StreamEvent},{"../../OpenVidu/Publisher":47,"../../OpenVidu/Session":48,"../Logger/OpenViduLogger":81,"./Event":58}],68:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamManagerEvent=void 0;const Event_1=require("./Event");class StreamManagerEvent extends Event_1.Event{constructor(target,type,value){super(false,target,type);this.value=value}callDefaultBehavior(){}}exports.StreamManagerEvent=StreamManagerEvent},{"./Event":58}],69:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StreamPropertyChangedEvent=void 0;const Event_1=require("./Event");class StreamPropertyChangedEvent extends Event_1.Event{constructor(target,stream,changedProperty,newValue,oldValue,reason){super(false,target,"streamPropertyChanged");this.stream=stream;this.changedProperty=changedProperty;this.newValue=newValue;this.oldValue=oldValue;this.reason=reason}callDefaultBehavior(){}}exports.StreamPropertyChangedEvent=StreamPropertyChangedEvent},{"./Event":58}],70:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VideoElementEvent=void 0;const Event_1=require("./Event");class VideoElementEvent extends Event_1.Event{constructor(element,target,type){super(false,target,type);this.element=element}callDefaultBehavior(){}}exports.VideoElementEvent=VideoElementEvent},{"./Event":58}],71:[function(require,module,exports){function Mapper(){var sources={};this.forEach=function(callback){for(var key in sources){var source=sources[key];for(var key2 in source)callback(source[key2])}};this.get=function(id,source){var ids=sources[source];if(ids==undefined)return undefined;return ids[id]};this.remove=function(id,source){var ids=sources[source];if(ids==undefined)return;delete ids[id];for(var i in ids){return false}delete sources[source]};this.set=function(value,id,source){if(value==undefined)return this.remove(id,source);var ids=sources[source];if(ids==undefined)sources[source]=ids={};ids[id]=value}}Mapper.prototype.pop=function(id,source){var value=this.get(id,source);if(value==undefined)return undefined;this.remove(id,source);return value};module.exports=Mapper},{}],72:[function(require,module,exports){var JsonRpcClient=require("./jsonrpcclient");exports.JsonRpcClient=JsonRpcClient},{"./jsonrpcclient":73}],73:[function(require,module,exports){var RpcBuilder=require("../");var WebSocketWithReconnection=require("./transports/webSocketWithReconnection");var OpenViduLogger=require("../../../Logger/OpenViduLogger").OpenViduLogger;Date.now=Date.now||function(){return+new Date};var PING_INTERVAL=5e3;var RECONNECTING="RECONNECTING";var CONNECTED="CONNECTED";var DISCONNECTED="DISCONNECTED";var Logger=OpenViduLogger.getInstance();function JsonRpcClient(configuration){var self=this;var wsConfig=configuration.ws;var notReconnectIfNumLessThan=-1;var pingNextNum=0;var enabledPings=true;var pingPongStarted=false;var pingInterval;var status=DISCONNECTED;var onreconnecting=wsConfig.onreconnecting;var onreconnected=wsConfig.onreconnected;var onconnected=wsConfig.onconnected;var onerror=wsConfig.onerror;configuration.rpc.pull=function(params,request){request.reply(null,"push")};wsConfig.onreconnecting=function(){Logger.debug("--------- ONRECONNECTING -----------");if(status===RECONNECTING){Logger.error("Websocket already in RECONNECTING state when receiving a new ONRECONNECTING message. Ignoring it");return}stopPing();status=RECONNECTING;if(onreconnecting){onreconnecting()}};wsConfig.onreconnected=function(){Logger.debug("--------- ONRECONNECTED -----------");if(status===CONNECTED){Logger.error("Websocket already in CONNECTED state when receiving a new ONRECONNECTED message. Ignoring it");return}status=CONNECTED;updateNotReconnectIfLessThan();if(onreconnected){onreconnected()}};wsConfig.onconnected=function(){Logger.debug("--------- ONCONNECTED -----------");if(status===CONNECTED){Logger.error("Websocket already in CONNECTED state when receiving a new ONCONNECTED message. Ignoring it");return}status=CONNECTED;enabledPings=true;usePing();if(onconnected){onconnected()}};wsConfig.onerror=function(error){Logger.debug("--------- ONERROR -----------");status=DISCONNECTED;stopPing();if(onerror){onerror(error)}};var ws=new WebSocketWithReconnection(wsConfig);Logger.debug("Connecting websocket to URI: "+wsConfig.uri);var rpcBuilderOptions={request_timeout:configuration.rpc.requestTimeout,ping_request_timeout:configuration.rpc.heartbeatRequestTimeout};var rpc=new RpcBuilder(RpcBuilder.packers.JsonRPC,rpcBuilderOptions,ws,function(request){Logger.debug("Received request: "+JSON.stringify(request));try{var func=configuration.rpc[request.method];if(func===undefined){Logger.error("Method "+request.method+" not registered in client")}else{func(request.params,request)}}catch(err){Logger.error("Exception processing request: "+JSON.stringify(request));Logger.error(err)}});this.send=function(method,params,callback){var requestTime=Date.now();rpc.encode(method,params,function(error,result){if(error){try{Logger.error("ERROR:"+error.message+" in Request: method:"+method+" params:"+JSON.stringify(params)+" request:"+error.request);if(error.data){Logger.error("ERROR DATA:"+JSON.stringify(error.data))}}catch(e){}error.requestTime=requestTime}if(callback){if(result!=undefined&&result.value!=="pong"){Logger.debug("Response: "+JSON.stringify(result))}callback(error,result)}})};function updateNotReconnectIfLessThan(){Logger.debug("notReconnectIfNumLessThan = "+pingNextNum+" (old="+notReconnectIfNumLessThan+")");notReconnectIfNumLessThan=pingNextNum}function sendPing(){if(enabledPings){var params=null;if(pingNextNum==0||pingNextNum==notReconnectIfNumLessThan){params={interval:configuration.heartbeat||PING_INTERVAL}}pingNextNum++;self.send("ping",params,function(pingNum){return function(error,result){if(error){Logger.debug("Error in ping request #"+pingNum+" ("+error.message+")");if(pingNum>notReconnectIfNumLessThan){enabledPings=false;updateNotReconnectIfLessThan();Logger.debug("Server did not respond to ping message #"+pingNum+". Reconnecting... ");ws.reconnectWs()}}}}(pingNextNum))}else{Logger.debug("Trying to send ping, but ping is not enabled")}}function usePing(){if(!pingPongStarted){Logger.debug("Starting ping (if configured)");pingPongStarted=true;if(configuration.heartbeat!=undefined){pingInterval=setInterval(sendPing,configuration.heartbeat);sendPing()}}}function stopPing(){clearInterval(pingInterval);pingPongStarted=false;enabledPings=false;pingNextNum=-1;rpc.cancel()}this.close=function(code,reason){Logger.debug("Closing with code: "+code+" because: "+reason);if(pingInterval!=undefined){Logger.debug("Clearing ping interval");clearInterval(pingInterval)}pingPongStarted=false;enabledPings=false;ws.close(code,reason)};this.reconnect=function(){ws.reconnectWs()};this.resetPing=function(){enabledPings=true;pingNextNum=0;usePing()};this.getReadyState=function(){return ws.getReadyState()}}module.exports=JsonRpcClient},{"../":76,"../../../Logger/OpenViduLogger":81,"./transports/webSocketWithReconnection":75}],74:[function(require,module,exports){var WebSocketWithReconnection=require("./webSocketWithReconnection");exports.WebSocketWithReconnection=WebSocketWithReconnection},{"./webSocketWithReconnection":75}],75:[function(require,module,exports){"use strict";var OpenViduLogger=require("../../../../Logger/OpenViduLogger").OpenViduLogger;var Logger=OpenViduLogger.getInstance();var MAX_RETRIES=2e3;var RETRY_TIME_MS=3e3;var CONNECTING=0;var OPEN=1;var CLOSING=2;var CLOSED=3;function WebSocketWithReconnection(config){var closing=false;var registerMessageHandler;var wsUri=config.uri;var reconnecting=false;var ws=new WebSocket(wsUri);ws.onopen=()=>{Logger.debug("WebSocket connected to "+wsUri);if(config.onconnected){config.onconnected()}};ws.onerror=error=>{Logger.error("Could not connect to "+wsUri+" (invoking onerror if defined)",error);if(config.onerror){config.onerror(error)}};var reconnectionOnClose=()=>{if(ws.readyState===CLOSED){if(closing){Logger.debug("Connection closed by user")}else{if(config.ismasternodecrashed()){Logger.error("Master Node has crashed. Stopping reconnection process")}else{Logger.debug("Connection closed unexpectedly. Reconnecting...");reconnect(MAX_RETRIES,1)}}}else{Logger.debug("Close callback from previous websocket. Ignoring it")}};ws.onclose=reconnectionOnClose;function reconnect(maxRetries,numRetries){Logger.debug("reconnect (attempt #"+numRetries+", max="+maxRetries+")");if(numRetries===1){if(reconnecting){Logger.warn("Trying to reconnect when already reconnecting... Ignoring this reconnection.");return}else{reconnecting=true}if(config.onreconnecting){config.onreconnecting()}}reconnectAux(maxRetries,numRetries)}function addReconnectionQueryParamsIfMissing(uriString){var searchParams=new URLSearchParams(new URL(uriString).search);if(!searchParams.has("reconnect")){uriString=Array.from(searchParams).length>0?uriString+"&reconnect=true":uriString+"?reconnect=true"}return uriString}function reconnectAux(maxRetries,numRetries){Logger.debug("Reconnection attempt #"+numRetries);ws.close(4104,"Connection closed for reconnection");wsUri=addReconnectionQueryParamsIfMissing(wsUri);ws=new WebSocket(wsUri);ws.onopen=()=>{Logger.debug("Reconnected to "+wsUri+" after "+numRetries+" attempts...");reconnecting=false;registerMessageHandler();if(config.onreconnected){config.onreconnected()}ws.onclose=reconnectionOnClose};ws.onerror=error=>{Logger.warn("Reconnection error: ",error);if(numRetries===maxRetries){if(config.ondisconnect){config.ondisconnect()}}else{setTimeout(()=>{reconnect(maxRetries,numRetries+1)},RETRY_TIME_MS)}}}this.close=(code,reason)=>{closing=true;ws.close(code,reason)};this.reconnectWs=()=>{Logger.debug("reconnectWs");reconnect(MAX_RETRIES,1)};this.send=message=>{ws.send(message)};this.addEventListener=(type,callback)=>{registerMessageHandler=()=>{ws.addEventListener(type,callback)};registerMessageHandler()};this.getReadyState=()=>ws.readyState}module.exports=WebSocketWithReconnection},{"../../../../Logger/OpenViduLogger":81}],76:[function(require,module,exports){var defineProperty_IE8=false;if(Object.defineProperty){try{Object.defineProperty({},"x",{})}catch(e){defineProperty_IE8=true}}if(!Function.prototype.bind){Function.prototype.bind=function(oThis){if(typeof this!=="function"){throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable")}var aArgs=Array.prototype.slice.call(arguments,1),fToBind=this,fNOP=function(){},fBound=function(){return fToBind.apply(this instanceof fNOP&&oThis?this:oThis,aArgs.concat(Array.prototype.slice.call(arguments)))};fNOP.prototype=this.prototype;fBound.prototype=new fNOP;return fBound}}var EventEmitter=require("events").EventEmitter;var inherits=require("inherits");var packers=require("./packers");var Mapper=require("./Mapper");var BASE_TIMEOUT=5e3;function unifyResponseMethods(responseMethods){if(!responseMethods)return{};for(var key in responseMethods){var value=responseMethods[key];if(typeof value=="string")responseMethods[key]={response:value}}return responseMethods}function unifyTransport(transport){if(!transport)return;if(transport instanceof Function)return{send:transport};if(transport.send instanceof Function)return transport;if(transport.postMessage instanceof Function){transport.send=transport.postMessage;return transport}if(transport.write instanceof Function){transport.send=transport.write;return transport}if(transport.onmessage!==undefined)return;if(transport.pause instanceof Function)return;throw new SyntaxError("Transport is not a function nor a valid object")}function RpcNotification(method,params){if(defineProperty_IE8){this.method=method;this.params=params}else{Object.defineProperty(this,"method",{value:method,enumerable:true});Object.defineProperty(this,"params",{value:params,enumerable:true})}}function RpcBuilder(packer,options,transport,onRequest){var self=this;if(!packer)throw new SyntaxError("Packer is not defined");if(!packer.pack||!packer.unpack)throw new SyntaxError("Packer is invalid");var responseMethods=unifyResponseMethods(packer.responseMethods);if(options instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after onRequest");onRequest=options;transport=undefined;options=undefined}if(options&&options.send instanceof Function){if(transport&&!(transport instanceof Function))throw new SyntaxError("Only a function can be after transport");onRequest=transport;transport=options;options=undefined}if(transport instanceof Function){if(onRequest!=undefined)throw new SyntaxError("There can't be parameters after onRequest");onRequest=transport;transport=undefined}if(transport&&transport.send instanceof Function)if(onRequest&&!(onRequest instanceof Function))throw new SyntaxError("Only a function can be after transport");options=options||{};EventEmitter.call(this);if(onRequest)this.on("request",onRequest);if(defineProperty_IE8)this.peerID=options.peerID;else Object.defineProperty(this,"peerID",{value:options.peerID});var max_retries=options.max_retries||0;function transportMessage(event){self.decode(event.data||event)}this.getTransport=function(){return transport};this.setTransport=function(value){if(transport){if(transport.removeEventListener)transport.removeEventListener("message",transportMessage);else if(transport.removeListener)transport.removeListener("data",transportMessage)}if(value){if(value.addEventListener)value.addEventListener("message",transportMessage);else if(value.addListener)value.addListener("data",transportMessage)}transport=unifyTransport(value)};if(!defineProperty_IE8)Object.defineProperty(this,"transport",{get:this.getTransport.bind(this),set:this.setTransport.bind(this)});this.setTransport(transport);var request_timeout=options.request_timeout||BASE_TIMEOUT;var ping_request_timeout=options.ping_request_timeout||request_timeout;var response_timeout=options.response_timeout||BASE_TIMEOUT;var duplicates_timeout=options.duplicates_timeout||BASE_TIMEOUT;var requestID=0;var requests=new Mapper;var responses=new Mapper;var processedResponses=new Mapper;var message2Key={};function storeResponse(message,id,dest){var response={message:message,timeout:setTimeout(function(){responses.remove(id,dest)},response_timeout)};responses.set(response,id,dest)}function storeProcessedResponse(ack,from){var timeout=setTimeout(function(){processedResponses.remove(ack,from)},duplicates_timeout);processedResponses.set(timeout,ack,from)}function RpcRequest(method,params,id,from,transport){RpcNotification.call(this,method,params);this.getTransport=function(){return transport};this.setTransport=function(value){transport=unifyTransport(value)};if(!defineProperty_IE8)Object.defineProperty(this,"transport",{get:this.getTransport.bind(this),set:this.setTransport.bind(this)});var response=responses.get(id,from);if(!(transport||self.getTransport())){if(defineProperty_IE8)this.duplicated=Boolean(response);else Object.defineProperty(this,"duplicated",{value:Boolean(response)})}var responseMethod=responseMethods[method];this.pack=packer.pack.bind(packer,this,id);this.reply=function(error,result,transport){if(error instanceof Function||error&&error.send instanceof Function){if(result!=undefined)throw new SyntaxError("There can't be parameters after callback");transport=error;result=null;error=undefined}else if(result instanceof Function||result&&result.send instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after callback");transport=result;result=null}transport=unifyTransport(transport);if(response)clearTimeout(response.timeout);if(from!=undefined){if(error)error.dest=from;if(result)result.dest=from}var message;if(error||result!=undefined){if(self.peerID!=undefined){if(error)error.from=self.peerID;else result.from=self.peerID}if(responseMethod){if(responseMethod.error==undefined&&error)message={error:error};else{var method=error?responseMethod.error:responseMethod.response;message={method:method,params:error||result}}}else message={error:error,result:result};message=packer.pack(message,id)}else if(response)message=response.message;else message=packer.pack({result:null},id);storeResponse(message,id,from);transport=transport||this.getTransport()||self.getTransport();if(transport)return transport.send(message);return message}}inherits(RpcRequest,RpcNotification);function cancel(message){var key=message2Key[message];if(!key)return;delete message2Key[message];var request=requests.pop(key.id,key.dest);if(!request)return;clearTimeout(request.timeout);storeProcessedResponse(key.id,key.dest)}this.cancel=function(message){if(message)return cancel(message);for(var message in message2Key)cancel(message)};this.close=function(){var transport=this.getTransport();if(transport&&transport.close)transport.close(4003,"Cancel request");this.cancel();processedResponses.forEach(clearTimeout);responses.forEach(function(response){clearTimeout(response.timeout)})};this.encode=function(method,params,dest,transport,callback){if(params instanceof Function){if(dest!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=params;transport=undefined;dest=undefined;params=undefined}else if(dest instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=dest;transport=undefined;dest=undefined}else if(transport instanceof Function){if(callback!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=transport;transport=undefined}if(self.peerID!=undefined){params=params||{};params.from=self.peerID}if(dest!=undefined){params=params||{};params.dest=dest}var message={method:method,params:params};if(callback){var id=requestID++;var retried=0;message=packer.pack(message,id);function dispatchCallback(error,result){self.cancel(message);callback(error,result)}var request={message:message,callback:dispatchCallback,responseMethods:responseMethods[method]||{}};var encode_transport=unifyTransport(transport);function sendRequest(transport){var rt=method==="ping"?ping_request_timeout:request_timeout;request.timeout=setTimeout(timeout,rt*Math.pow(2,retried++));message2Key[message]={id:id,dest:dest};requests.set(request,id,dest);transport=transport||encode_transport||self.getTransport();if(transport)return transport.send(message);return message}function retry(transport){transport=unifyTransport(transport);console.warn(retried+" retry for request message:",message);var timeout=processedResponses.pop(id,dest);clearTimeout(timeout);return sendRequest(transport)}function timeout(){if(retried<max_retries)return retry(transport);var error=new Error("Request has timed out");error.request=message;error.retry=retry;dispatchCallback(error)}return sendRequest(transport)}message=packer.pack(message);transport=transport||this.getTransport();if(transport)return transport.send(message);return message};this.decode=function(message,transport){if(!message)throw new TypeError("Message is not defined");try{message=packer.unpack(message)}catch(e){return console.debug(e,message)}var id=message.id;var ack=message.ack;var method=message.method;var params=message.params||{};var from=params.from;var dest=params.dest;if(self.peerID!=undefined&&from==self.peerID)return;if(id==undefined&&ack==undefined){var notification=new RpcNotification(method,params);if(self.emit("request",notification))return;return notification}function processRequest(){transport=unifyTransport(transport)||self.getTransport();if(transport){var response=responses.get(id,from);if(response)return transport.send(response.message)}var idAck=id!=undefined?id:ack;var request=new RpcRequest(method,params,idAck,from,transport);if(self.emit("request",request))return;return request}function processResponse(request,error,result){request.callback(error,result)}function duplicatedResponse(timeout){console.warn("Response already processed",message);clearTimeout(timeout);storeProcessedResponse(ack,from)}if(method){if(dest==undefined||dest==self.peerID){var request=requests.get(ack,from);if(request){var responseMethods=request.responseMethods;if(method==responseMethods.error)return processResponse(request,params);if(method==responseMethods.response)return processResponse(request,null,params);return processRequest()}var processed=processedResponses.get(ack,from);if(processed)return duplicatedResponse(processed)}return processRequest()}var error=message.error;var result=message.result;if(error&&error.dest&&error.dest!=self.peerID)return;if(result&&result.dest&&result.dest!=self.peerID)return;var request=requests.get(ack,from);if(!request){var processed=processedResponses.get(ack,from);if(processed)return duplicatedResponse(processed);return console.warn("No callback was defined for this message",message)}processResponse(request,error,result)}}inherits(RpcBuilder,EventEmitter);RpcBuilder.RpcNotification=RpcNotification;module.exports=RpcBuilder;var clients=require("./clients");var transports=require("./clients/transports");RpcBuilder.clients=clients;RpcBuilder.clients.transports=transports;RpcBuilder.packers=packers},{"./Mapper":71,"./clients":72,"./clients/transports":74,"./packers":79,events:1,inherits:6}],77:[function(require,module,exports){function pack(message,id){var result={jsonrpc:"2.0"};if(message.method){result.method=message.method;if(message.params)result.params=message.params;if(id!=undefined)result.id=id}else if(id!=undefined){if(message.error){if(message.result!==undefined)throw new TypeError("Both result and error are defined");result.error=message.error}else if(message.result!==undefined)result.result=message.result;else throw new TypeError("No result or error is defined");result.id=id}return JSON.stringify(result)}function unpack(message){var result=message;if(typeof message==="string"||message instanceof String){result=JSON.parse(message)}var version=result.jsonrpc;if(version!=="2.0")throw new TypeError("Invalid JsonRPC version '"+version+"': "+message);if(result.method==undefined){if(result.id==undefined)throw new TypeError("Invalid message: "+message);var result_defined=result.result!==undefined;var error_defined=result.error!==undefined;if(result_defined&&error_defined)throw new TypeError("Both result and error are defined: "+message);if(!result_defined&&!error_defined)throw new TypeError("No result or error is defined: "+message);result.ack=result.id;delete result.id}return result}exports.pack=pack;exports.unpack=unpack},{}],78:[function(require,module,exports){function pack(message){throw new TypeError("Not yet implemented")}function unpack(message){throw new TypeError("Not yet implemented")}exports.pack=pack;exports.unpack=unpack},{}],79:[function(require,module,exports){var JsonRPC=require("./JsonRPC");var XmlRPC=require("./XmlRPC");exports.JsonRPC=JsonRPC;exports.XmlRPC=XmlRPC},{"./JsonRPC":77,"./XmlRPC":78}],80:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=void 0;class ConsoleLogger{constructor(console){this.logger=console;this.log=console.log,this.info=console.info,this.debug=console.debug,this.warn=console.warn,this.error=console.error}}exports.ConsoleLogger=ConsoleLogger},{}],81:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OpenViduLogger=void 0;const jsnlog_1=require("jsnlog");const ConsoleLogger_1=require("./ConsoleLogger");const OpenViduLoggerConfiguration_1=require("./OpenViduLoggerConfiguration");class OpenViduLogger{constructor(){this.JSNLOG_URL="/openvidu/elk/openvidu-browser-logs";this.MAX_JSNLOG_BATCH_LOG_MESSAGES=100;this.MAX_MSECONDS_BATCH_MESSAGES=5e3;this.MAX_LENGTH_STRING_JSON=1e3;this.defaultConsoleLogger=new ConsoleLogger_1.ConsoleLogger(globalThis.console);this.isProdMode=false;this.isJSNLogSetup=false}static configureJSNLog(openVidu,token){try{if(globalThis["LOG_JSNLOG_RESULTS"]||this.instance&&openVidu.isAtLeastPro&&this.instance.isOpenViduBrowserLogsDebugActive(openVidu)&&this.instance.canConfigureJSNLog(openVidu,this.instance)){if(openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug_app){this.instance.replaceWindowConsole()}this.instance.isJSNLogSetup=false;this.instance.info("Configuring JSNLogs.");const finalUserId=openVidu.finalUserId;const sessionId=openVidu.session.sessionId;const beforeSendCallback=xhr=>{const parentReadyStateFunction=xhr.onreadystatechange;xhr.onreadystatechange=()=>{if(this.isInvalidResponse(xhr)){Object.defineProperty(xhr,"readyState",{value:4});Object.defineProperty(xhr,"status",{value:200});this.instance.disableLogger()}parentReadyStateFunction()};xhr.setRequestHeader("Authorization","Basic "+btoa(`${finalUserId}%/%${sessionId}`+":"+token));xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("OV-Final-User-Id",finalUserId);xhr.setRequestHeader("OV-Session-Id",sessionId);xhr.setRequestHeader("OV-Token",token)};this.instance.currentAppender=jsnlog_1.JL.createAjaxAppender(`appender-${finalUserId}-${sessionId}`);this.instance.currentAppender.setOptions({beforeSend:beforeSendCallback,maxBatchSize:1e3,batchSize:this.instance.MAX_JSNLOG_BATCH_LOG_MESSAGES,batchTimeout:this.instance.MAX_MSECONDS_BATCH_MESSAGES});const logSerializer=obj=>{const getCircularReplacer=()=>{const seen=new WeakSet;return(key,value)=>{if(typeof value==="object"&&value!=null){if(seen.has(value)||globalThis.HTMLElement&&value instanceof HTMLElement){return}seen.add(value)}return value}};let stringifyJson=JSON.stringify(obj,getCircularReplacer());if(stringifyJson.length>this.instance.MAX_LENGTH_STRING_JSON){stringifyJson=`${stringifyJson.substring(0,this.instance.MAX_LENGTH_STRING_JSON)}...`}if(globalThis["LOG_JSNLOG_RESULTS"]){console.log(stringifyJson)}return stringifyJson};jsnlog_1.JL.setOptions({defaultAjaxUrl:openVidu.httpUri+this.instance.JSNLOG_URL,serialize:logSerializer,enabled:true});(0,jsnlog_1.JL)().setOptions({appenders:[this.instance.currentAppender]});this.instance.isJSNLogSetup=true;this.instance.loggingSessionId=sessionId;this.instance.info("JSNLog configured.")}}catch(e){console.error("Error configuring JSNLog: ");console.error(e);this.instance.disableLogger()}}static getInstance(){if(!OpenViduLogger.instance){OpenViduLogger.instance=new OpenViduLogger}return OpenViduLogger.instance}static isInvalidResponse(xhr){return xhr.status==401||xhr.status==403||xhr.status==404||xhr.status==0}canConfigureJSNLog(openVidu,logger){return openVidu.session.sessionId!=logger.loggingSessionId}isOpenViduBrowserLogsDebugActive(openVidu){return openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug||openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug_app}getConsoleWithJSNLog(){return function(openViduLogger){return{log:function(...args){openViduLogger.defaultConsoleLogger.log.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}},info:function(...args){openViduLogger.defaultConsoleLogger.info.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}},debug:function(...args){openViduLogger.defaultConsoleLogger.debug.apply(openViduLogger.defaultConsoleLogger.logger,arguments)},warn:function(...args){openViduLogger.defaultConsoleLogger.warn.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().warn(arguments)}},error:function(...args){openViduLogger.defaultConsoleLogger.error.apply(openViduLogger.defaultConsoleLogger.logger,arguments);if(openViduLogger.isJSNLogSetup){(0,jsnlog_1.JL)().error(arguments)}}}}(this)}replaceWindowConsole(){globalThis.console=this.defaultConsoleLogger.logger;globalThis.console.log=this.getConsoleWithJSNLog().log;globalThis.console.info=this.getConsoleWithJSNLog().info;globalThis.console.debug=this.getConsoleWithJSNLog().debug;globalThis.console.warn=this.getConsoleWithJSNLog().warn;globalThis.console.error=this.getConsoleWithJSNLog().error}disableLogger(){jsnlog_1.JL.setOptions({enabled:false});this.isJSNLogSetup=false;this.loggingSessionId=undefined;this.currentAppender=undefined;globalThis.console=this.defaultConsoleLogger.logger;globalThis.console.log=this.defaultConsoleLogger.log;globalThis.console.info=this.defaultConsoleLogger.info;globalThis.console.debug=this.defaultConsoleLogger.debug;globalThis.console.warn=this.defaultConsoleLogger.warn;globalThis.console.error=this.defaultConsoleLogger.error}log(...args){if(!this.isProdMode){this.defaultConsoleLogger.log.apply(this.defaultConsoleLogger.logger,arguments)}if(this.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}}debug(...args){if(!this.isProdMode){this.defaultConsoleLogger.debug.apply(this.defaultConsoleLogger.logger,arguments)}}info(...args){if(!this.isProdMode){this.defaultConsoleLogger.info.apply(this.defaultConsoleLogger.logger,arguments)}if(this.isJSNLogSetup){(0,jsnlog_1.JL)().info(arguments)}}warn(...args){this.defaultConsoleLogger.warn.apply(this.defaultConsoleLogger.logger,arguments);if(this.isJSNLogSetup){(0,jsnlog_1.JL)().warn(arguments)}}error(...args){this.defaultConsoleLogger.error.apply(this.defaultConsoleLogger.logger,arguments);if(this.isJSNLogSetup){(0,jsnlog_1.JL)().error(arguments)}}flush(){if(this.isJSNLogSetup&&this.currentAppender!=null){this.currentAppender.sendBatch()}}enableProdMode(){this.isProdMode=true}}exports.OpenViduLogger=OpenViduLogger},{"./ConsoleLogger":80,"./OpenViduLoggerConfiguration":82,jsnlog:7}],82:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OpenViduLoggerConfiguration=void 0;var OpenViduLoggerConfiguration;(function(OpenViduLoggerConfiguration){OpenViduLoggerConfiguration["disabled"]="disabled";OpenViduLoggerConfiguration["debug"]="debug";OpenViduLoggerConfiguration["debug_app"]="debug_app"})(OpenViduLoggerConfiguration||(exports.OpenViduLoggerConfiguration=OpenViduLoggerConfiguration={}))},{}],83:[function(require,module,exports){globalThis.getScreenId=function(firefoxString,callback,custom_parameter){if(navigator.userAgent.indexOf("Edge")!==-1&&(!!navigator.msSaveOrOpenBlob||!!navigator.msSaveBlob)){callback({video:true});return}if(!!navigator.mozGetUserMedia){callback(null,"firefox",{video:{mozMediaSource:firefoxString,mediaSource:firefoxString}});return}globalThis.addEventListener("message",onIFrameCallback);function onIFrameCallback(event){if(!event.data)return;if(event.data.chromeMediaSourceId){if(event.data.chromeMediaSourceId==="PermissionDeniedError"){callback("permission-denied")}else{callback(null,event.data.chromeMediaSourceId,getScreenConstraints(null,event.data.chromeMediaSourceId,event.data.canRequestAudioTrack))}globalThis.removeEventListener("message",onIFrameCallback)}if(event.data.chromeExtensionStatus){callback(event.data.chromeExtensionStatus,null,getScreenConstraints(event.data.chromeExtensionStatus));globalThis.removeEventListener("message",onIFrameCallback)}}if(!custom_parameter){setTimeout(postGetSourceIdMessage,100)}else{setTimeout(function(){postGetSourceIdMessage(custom_parameter)},100)}};function getScreenConstraints(error,sourceId,canRequestAudioTrack){var screen_constraints={audio:false,video:{mandatory:{chromeMediaSource:error?"screen":"desktop",maxWidth:globalThis.screen.width>1920?globalThis.screen.width:1920,maxHeight:globalThis.screen.height>1080?globalThis.screen.height:1080},optional:[]}};if(!!canRequestAudioTrack){screen_constraints.audio={mandatory:{chromeMediaSource:error?"screen":"desktop"},optional:[]}}if(sourceId){screen_constraints.video.mandatory.chromeMediaSourceId=sourceId;if(screen_constraints.audio&&screen_constraints.audio.mandatory){screen_constraints.audio.mandatory.chromeMediaSourceId=sourceId}}return screen_constraints}function postGetSourceIdMessage(custom_parameter){if(!iframe){loadIFrame(function(){postGetSourceIdMessage(custom_parameter)});return}if(!iframe.isLoaded){setTimeout(function(){postGetSourceIdMessage(custom_parameter)},100);return}if(!custom_parameter){iframe.contentWindow.postMessage({captureSourceId:true},"*")}else if(!!custom_parameter.forEach){iframe.contentWindow.postMessage({captureCustomSourceId:custom_parameter},"*")}else{iframe.contentWindow.postMessage({captureSourceIdWithAudio:true},"*")}}var iframe;globalThis.getScreenConstraints=function(callback){loadIFrame(function(){getScreenId(function(error,sourceId,screen_constraints){if(!screen_constraints){screen_constraints={video:true}}callback(error,screen_constraints.video)})})};function loadIFrame(loadCallback){if(iframe){loadCallback();return}iframe=document.createElement("iframe");iframe.onload=function(){iframe.isLoaded=true;loadCallback()};iframe.src="https://openvidu.github.io/openvidu-screen-sharing-chrome-extension/";iframe.style.display="none";(document.body||document.documentElement).appendChild(iframe)}globalThis.getChromeExtensionStatus=function(callback){if(!!navigator.mozGetUserMedia){callback("installed-enabled");return}globalThis.addEventListener("message",onIFrameCallback);function onIFrameCallback(event){if(!event.data)return;if(event.data.chromeExtensionStatus){callback(event.data.chromeExtensionStatus);globalThis.removeEventListener("message",onIFrameCallback)}}setTimeout(postGetChromeExtensionStatusMessage,100)};function postGetChromeExtensionStatusMessage(){if(!iframe){loadIFrame(postGetChromeExtensionStatusMessage);return}if(!iframe.isLoaded){setTimeout(postGetChromeExtensionStatusMessage,100);return}iframe.contentWindow.postMessage({getChromeExtensionStatus:true},"*")}exports.getScreenId=globalThis.getScreenId},{}],84:[function(require,module,exports){var chromeMediaSource="screen";var sourceId;var screenCallback;if(typeof window!=="undefined"&&typeof navigator!=="undefined"&&typeof navigator.userAgent!=="undefined"){var isFirefox=typeof window.InstallTrigger!=="undefined";var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0;var isChrome=!!window.chrome&&!isOpera;window.addEventListener("message",function(event){if(event.origin!=window.location.origin){return}onMessageCallback(event.data)})}function onMessageCallback(data){if(data=="PermissionDeniedError"){if(screenCallback)return screenCallback("PermissionDeniedError");else throw new Error("PermissionDeniedError")}if(data=="rtcmulticonnection-extension-loaded"){chromeMediaSource="desktop"}if(data.sourceId&&screenCallback){screenCallback(sourceId=data.sourceId,data.canRequestAudioTrack===true)}}function isChromeExtensionAvailable(callback){if(!callback)return;if(chromeMediaSource=="desktop")return callback(true);window.postMessage("are-you-there","*");setTimeout(function(){if(chromeMediaSource=="screen"){callback(false)}else callback(true)},2e3)}function getSourceId(callback){if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage("get-sourceId","*")}function getCustomSourceId(arr,callback){if(!arr||!arr.forEach)throw'"arr" parameter is mandatory and it must be an array.';if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage({"get-custom-sourceId":arr},"*")}function getSourceIdWithAudio(callback){if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage("audio-plus-tab","*")}function getChromeExtensionStatus(extensionid,callback){if(isFirefox)return callback("not-chrome");if(arguments.length!=2){callback=extensionid;extensionid="lfcgfepafnobdloecchnfaclibenjold"}var image=document.createElement("img");image.src="chrome-extension://"+extensionid+"/icon.png";image.onload=function(){chromeMediaSource="screen";window.postMessage("are-you-there","*");setTimeout(function(){if(chromeMediaSource=="screen"){callback("installed-disabled")}else callback("installed-enabled")},2e3)};image.onerror=function(){callback("not-installed")}}function getScreenConstraintsWithAudio(callback){getScreenConstraints(callback,true)}function getScreenConstraints(callback,captureSourceIdWithAudio){sourceId="";var firefoxScreenConstraints={mozMediaSource:"window",mediaSource:"window"};if(isFirefox)return callback(null,firefoxScreenConstraints);var screen_constraints={mandatory:{chromeMediaSource:chromeMediaSource,maxWidth:screen.width>1920?screen.width:1920,maxHeight:screen.height>1080?screen.height:1080},optional:[]};if(chromeMediaSource=="desktop"&&!sourceId){if(captureSourceIdWithAudio){getSourceIdWithAudio(function(sourceId,canRequestAudioTrack){screen_constraints.mandatory.chromeMediaSourceId=sourceId;if(canRequestAudioTrack){screen_constraints.canRequestAudioTrack=true}callback(sourceId=="PermissionDeniedError"?sourceId:null,screen_constraints)})}else{getSourceId(function(sourceId){screen_constraints.mandatory.chromeMediaSourceId=sourceId;callback(sourceId=="PermissionDeniedError"?sourceId:null,screen_constraints)})}return}if(chromeMediaSource=="desktop"){screen_constraints.mandatory.chromeMediaSourceId=sourceId}callback(null,screen_constraints)}exports.getScreenConstraints=getScreenConstraints;exports.getScreenConstraintsWithAudio=getScreenConstraintsWithAudio;exports.isChromeExtensionAvailable=isChromeExtensionAvailable;exports.getChromeExtensionStatus=getChromeExtensionStatus;exports.getSourceId=getSourceId},{}],85:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PlatformUtils=void 0;const platform=require("platform");class PlatformUtils{constructor(){}static getInstance(){if(!this.instance){this.instance=new PlatformUtils}return PlatformUtils.instance}isChromeBrowser(){return platform.name==="Chrome"}isSafariBrowser(){return platform.name==="Safari"}isChromeMobileBrowser(){return platform.name==="Chrome Mobile"}isFirefoxBrowser(){return platform.name==="Firefox"}isFirefoxMobileBrowser(){return platform.name==="Firefox Mobile"||platform.name==="Firefox for iOS"}isOperaBrowser(){return platform.name==="Opera"}isOperaMobileBrowser(){return platform.name==="Opera Mobile"}isEdgeBrowser(){const version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;return platform.name==="Microsoft Edge"&&version>=80}isEdgeMobileBrowser(){var _a,_b;const version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;return platform.name==="Microsoft Edge"&&(((_a=platform.os)===null||_a===void 0?void 0:_a.family)==="Android"||((_b=platform.os)===null||_b===void 0?void 0:_b.family)==="iOS")&&version>45}isAndroidBrowser(){return platform.name==="Android Browser"}isElectron(){return platform.name==="Electron"}isNodeJs(){return platform.name==="Node.js"}isSamsungBrowser(){return platform.name==="Samsung Internet Mobile"||platform.name==="Samsung Internet"}isMotorolaEdgeDevice(){var _a;return((_a=platform.product)===null||_a===void 0?void 0:_a.toLowerCase().includes("motorola edge"))||false}isIPhoneOrIPad(){const userAgent=!!platform.ua?platform.ua:navigator.userAgent;const isTouchable="ontouchend"in document;const isIPad=/\b(\w*Macintosh\w*)\b/.test(userAgent)&&isTouchable;const isIPhone=/\b(\w*iPhone\w*)\b/.test(userAgent)&&/\b(\w*Mobile\w*)\b/.test(userAgent)&&isTouchable;return isIPad||isIPhone}isIOSWithSafari(){const userAgent=!!platform.ua?platform.ua:navigator.userAgent;return this.isIPhoneOrIPad()&&/\b(\w*Apple\w*)\b/.test(navigator.vendor)&&/\b(\w*Safari\w*)\b/.test(userAgent)&&!/\b(\w*CriOS\w*)\b/.test(userAgent)&&!/\b(\w*FxiOS\w*)\b/.test(userAgent)}isIonicIos(){return this.isIPhoneOrIPad()&&platform.ua.indexOf("Safari")===-1}isIonicAndroid(){return platform.os.family==="Android"&&platform.name=="Android Browser"}isMobileDevice(){return platform.os.family==="iOS"||platform.os.family==="Android"}isReactNative(){return false}isChromium(){return this.isChromeBrowser()||this.isChromeMobileBrowser()||this.isOperaBrowser()||this.isOperaMobileBrowser()||this.isEdgeBrowser()||this.isEdgeMobileBrowser()||this.isSamsungBrowser()||this.isIonicAndroid()||this.isIonicIos()||this.isElectron()||this.isMotorolaEdgeDevice()}canScreenShare(){const version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;if(this.isMobileDevice()){return false}return this.isChromeBrowser()||this.isFirefoxBrowser()||this.isOperaBrowser()||this.isElectron()||this.isEdgeBrowser()||this.isSafariBrowser()&&version>=13}getName(){return platform.name||""}getVersion(){return platform.version||""}getFamily(){return platform.os.family||""}getDescription(){return platform.description||""}}exports.PlatformUtils=PlatformUtils},{platform:13}],86:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.WebRtcPeerSendrecv=exports.WebRtcPeerSendonly=exports.WebRtcPeerRecvonly=exports.WebRtcPeer=void 0;const freeice=require("freeice");const uuid_1=require("uuid");const ExceptionEvent_1=require("../Events/ExceptionEvent");const OpenViduLogger_1=require("../Logger/OpenViduLogger");const Platform_1=require("../Utils/Platform");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class WebRtcPeer{constructor(configuration){this.remoteCandidatesQueue=[];this.localCandidatesQueue=[];this.iceCandidateList=[];platform=Platform_1.PlatformUtils.getInstance();this.configuration=Object.assign(Object.assign({},configuration),{iceServers:!!configuration.iceServers&&configuration.iceServers.length>0?configuration.iceServers:freeice(),rtcConfiguration:configuration.rtcConfiguration!==undefined?configuration.rtcConfiguration:{},mediaStream:configuration.mediaStream!==undefined?configuration.mediaStream:null,mode:!!configuration.mode?configuration.mode:"sendrecv",id:!!configuration.id?configuration.id:this.generateUniqueId()});logger.debug(`[WebRtcPeer] configuration:\n${JSON.stringify(this.configuration,null,2)}`);let rtcConfiguration=this.configuration.rtcConfiguration?this.configuration.rtcConfiguration:{iceServers:this.configuration.iceServers};if(!rtcConfiguration.iceServers&&this.configuration.iceServers){rtcConfiguration.iceServers=this.configuration.iceServers}this.pc=new RTCPeerConnection(rtcConfiguration);this.pc.addEventListener("icecandidate",event=>{if(event.candidate!==null){const candidateInit=event.candidate;const iceCandidate=new RTCIceCandidate(candidateInit);this.configuration.onIceCandidate(iceCandidate);if(iceCandidate.candidate!==""){this.localCandidatesQueue.push(iceCandidate)}}});this.pc.addEventListener("signalingstatechange",()=>__awaiter(this,void 0,void 0,function*(){if(this.pc.signalingState==="stable"){while(this.iceCandidateList.length>0){let candidate=this.iceCandidateList.shift();try{yield this.pc.addIceCandidate(candidate)}catch(error){logger.error("Error when calling RTCPeerConnection#addIceCandidate for RTCPeerConnection "+this.getId(),error)}}}}))}getId(){return this.configuration.id}dispose(){logger.debug("Disposing WebRtcPeer");if(this.pc){if(this.pc.signalingState==="closed"){return}this.pc.close();this.remoteCandidatesQueue=[];this.localCandidatesQueue=[]}}createOfferLegacy(){if(!!this.configuration.mediaStream){this.deprecatedPeerConnectionTrackApi()}const hasAudio=this.configuration.mediaConstraints.audio;const hasVideo=this.configuration.mediaConstraints.video;const options={offerToReceiveAudio:this.configuration.mode!=="sendonly"&&hasAudio,offerToReceiveVideo:this.configuration.mode!=="sendonly"&&hasVideo};logger.debug("[createOfferLegacy] RTCPeerConnection.createOffer() options:",JSON.stringify(options));return this.pc.createOffer(options)}createOffer(){return __awaiter(this,void 0,void 0,function*(){var _a,_b,_c,_d,_e,_f,_g,_h;if(!("addTransceiver"in this.pc)){logger.warn("[createOffer] Method RTCPeerConnection.addTransceiver() is NOT available; using LEGACY offerToReceive{Audio,Video}");return this.createOfferLegacy()}else{logger.debug("[createOffer] Method RTCPeerConnection.addTransceiver() is available; using it")}if(this.configuration.mode!=="recvonly"){if(!this.configuration.mediaStream){throw new Error(`[WebRtcPeer.createOffer] Direction is '${this.configuration.mode}', but no stream was configured to be sent`)}for(const track of this.configuration.mediaStream.getTracks()){const tcInit={direction:this.configuration.mode,streams:[this.configuration.mediaStream]};if(track.kind==="video"&&this.configuration.simulcast){const trackSettings=track.getSettings();const trackConsts=track.getConstraints();const trackWidth=(_c=(_b=(_a=trackSettings.width)!==null&&_a!==void 0?_a:trackConsts.width.ideal)!==null&&_b!==void 0?_b:trackConsts.width)!==null&&_c!==void 0?_c:0;const trackHeight=(_f=(_e=(_d=trackSettings.height)!==null&&_d!==void 0?_d:trackConsts.height.ideal)!==null&&_e!==void 0?_e:trackConsts.height)!==null&&_f!==void 0?_f:0;logger.info(`[createOffer] Video track dimensions: ${trackWidth}x${trackHeight}`);const trackPixels=trackWidth*trackHeight;let maxLayers=0;if(trackPixels>=960*540){maxLayers=3}else if(trackPixels>=480*270){maxLayers=2}else{maxLayers=1}tcInit.sendEncodings=[];for(let l=0;l<maxLayers;l++){const layerDiv=Math.pow(2,maxLayers-l-1);const encoding={rid:"rdiv"+layerDiv.toString(),scalabilityMode:"L1T1"};if(["detail","text"].includes(track.contentHint)){encoding.scaleResolutionDownBy=1;encoding.maxFramerate=Math.floor(30/layerDiv)}else{encoding.scaleResolutionDownBy=layerDiv}tcInit.sendEncodings.push(encoding)}}const tc=this.pc.addTransceiver(track,tcInit);if(track.kind==="video"){let sendParams=tc.sender.getParameters();let needSetParams=false;if(!((_g=sendParams.degradationPreference)===null||_g===void 0?void 0:_g.length)){if(["detail","text"].includes(track.contentHint)){sendParams.degradationPreference="maintain-resolution"}else{sendParams.degradationPreference="balanced"}logger.info(`[createOffer] Video sender Degradation Preference set: ${sendParams.degradationPreference}`);needSetParams=true}if(this.configuration.simulcast){if(((_h=sendParams.encodings)===null||_h===void 0?void 0:_h.length)!==tcInit.sendEncodings.length){sendParams.encodings=tcInit.sendEncodings;needSetParams=true}}if(needSetParams){logger.debug(`[createOffer] Setting new RTCRtpSendParameters to video sender`);try{yield tc.sender.setParameters(sendParams)}catch(error){let message=`[WebRtcPeer.createOffer] Cannot set RTCRtpSendParameters to video sender`;if(error instanceof Error){message+=`: ${error.message}`}throw new Error(message)}}}}}else{for(const kind of["audio","video"]){if(!this.configuration.mediaConstraints[kind]){continue}this.configuration.mediaStream=new MediaStream;this.pc.addTransceiver(kind,{direction:this.configuration.mode,streams:[this.configuration.mediaStream]})}}let sdpOffer;try{sdpOffer=yield this.pc.createOffer()}catch(error){let message=`[WebRtcPeer.createOffer] Browser failed creating an SDP Offer`;if(error instanceof Error){message+=`: ${error.message}`}throw new Error(message)}return sdpOffer})}deprecatedPeerConnectionTrackApi(){for(const track of this.configuration.mediaStream.getTracks()){this.pc.addTrack(track,this.configuration.mediaStream)}}createAnswer(){return new Promise((resolve,reject)=>{if("getTransceivers"in this.pc){logger.debug("[createAnswer] Method RTCPeerConnection.getTransceivers() is available; using it");for(const kind of["audio","video"]){if(!this.configuration.mediaConstraints[kind]){continue}let tc=this.pc.getTransceivers().find(tc=>tc.receiver.track.kind===kind);if(tc){tc.direction=this.configuration.mode}else{return reject(new Error(`${kind} requested, but no transceiver was created from remote description`))}}this.pc.createAnswer().then(sdpAnswer=>resolve(sdpAnswer)).catch(error=>reject(error))}else{let offerAudio,offerVideo=true;if(!!this.configuration.mediaConstraints){offerAudio=typeof this.configuration.mediaConstraints.audio==="boolean"?this.configuration.mediaConstraints.audio:true;offerVideo=typeof this.configuration.mediaConstraints.video==="boolean"?this.configuration.mediaConstraints.video:true;const constraints={offerToReceiveAudio:offerAudio,offerToReceiveVideo:offerVideo};this.pc.createAnswer(constraints).then(sdpAnswer=>resolve(sdpAnswer)).catch(error=>reject(error))}}})}processLocalOffer(offer){return new Promise((resolve,reject)=>{this.pc.setLocalDescription(offer).then(()=>{const localDescription=this.pc.localDescription;if(!!localDescription){logger.debug("Local description set",localDescription.sdp);return resolve()}else{return reject("Local description is not defined")}}).catch(error=>reject(error))})}processRemoteOffer(sdpOffer){return new Promise((resolve,reject)=>{const offer={type:"offer",sdp:sdpOffer};logger.debug("SDP offer received, setting remote description",offer);if(this.pc.signalingState==="closed"){return reject("RTCPeerConnection is closed when trying to set remote description")}this.setRemoteDescription(offer).then(()=>resolve()).catch(error=>reject(error))})}processLocalAnswer(answer){return new Promise((resolve,reject)=>{logger.debug("SDP answer created, setting local description");if(this.pc.signalingState==="closed"){return reject("RTCPeerConnection is closed when trying to set local description")}this.pc.setLocalDescription(answer).then(()=>resolve()).catch(error=>reject(error))})}processRemoteAnswer(sdpAnswer){return new Promise((resolve,reject)=>{const answer={type:"answer",sdp:sdpAnswer};logger.debug("SDP answer received, setting remote description");if(this.pc.signalingState==="closed"){return reject("RTCPeerConnection is closed when trying to set remote description")}this.setRemoteDescription(answer).then(()=>{resolve()}).catch(error=>reject(error))})}setRemoteDescription(sdp){return __awaiter(this,void 0,void 0,function*(){return this.pc.setRemoteDescription(sdp)})}addIceCandidate(iceCandidate){return new Promise((resolve,reject)=>{logger.debug("Remote ICE candidate received",iceCandidate);this.remoteCandidatesQueue.push(iceCandidate);switch(this.pc.signalingState){case"closed":reject(new Error("PeerConnection object is closed"));break;case"stable":if(!!this.pc.remoteDescription){this.pc.addIceCandidate(iceCandidate).then(()=>resolve()).catch(error=>reject(error))}else{this.iceCandidateList.push(iceCandidate);resolve()}break;default:this.iceCandidateList.push(iceCandidate);resolve()}})}addIceConnectionStateChangeListener(otherId){this.pc.addEventListener("iceconnectionstatechange",()=>{const iceConnectionState=this.pc.iceConnectionState;switch(iceConnectionState){case"disconnected":const msg1="IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "disconnected". Possible network disconnection';logger.warn(msg1);this.configuration.onIceConnectionStateException(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED,msg1);break;case"failed":const msg2="IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') to "failed"';logger.error(msg2);this.configuration.onIceConnectionStateException(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED,msg2);break;case"closed":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "closed"');break;case"new":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "new"');break;case"checking":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "checking"');break;case"connected":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "connected"');break;case"completed":logger.log("IceConnectionState of RTCPeerConnection "+this.configuration.id+" ("+otherId+') change to "completed"');break}})}generateUniqueId(){return(0,uuid_1.v4)()}}exports.WebRtcPeer=WebRtcPeer;class WebRtcPeerRecvonly extends WebRtcPeer{constructor(configuration){configuration.mode="recvonly";super(configuration)}}exports.WebRtcPeerRecvonly=WebRtcPeerRecvonly;class WebRtcPeerSendonly extends WebRtcPeer{constructor(configuration){configuration.mode="sendonly";super(configuration)}}exports.WebRtcPeerSendonly=WebRtcPeerSendonly;class WebRtcPeerSendrecv extends WebRtcPeer{constructor(configuration){configuration.mode="sendrecv";super(configuration)}}exports.WebRtcPeerSendrecv=WebRtcPeerSendrecv},{"../Events/ExceptionEvent":59,"../Logger/OpenViduLogger":81,"../Utils/Platform":85,freeice:2,uuid:23}],87:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:true});exports.WebRtcStats=void 0;const OpenViduLogger_1=require("../Logger/OpenViduLogger");const Platform_1=require("../Utils/Platform");const logger=OpenViduLogger_1.OpenViduLogger.getInstance();let platform;class WebRtcStats{constructor(stream){this.stream=stream;this.STATS_ITEM_NAME="webrtc-stats-config";this.webRtcStatsEnabled=false;this.statsInterval=1;platform=Platform_1.PlatformUtils.getInstance()}isEnabled(){return this.webRtcStatsEnabled}initWebRtcStats(){let webrtcObj;try{webrtcObj=localStorage.getItem(this.STATS_ITEM_NAME)}catch(e){}if(!!webrtcObj){this.webRtcStatsEnabled=true;const webrtcStatsConfig=JSON.parse(webrtcObj);logger.warn("WebRtc stats enabled for stream "+this.stream.streamId+" of connection "+this.stream.connection.connectionId);logger.warn("localStorage item: "+JSON.stringify(webrtcStatsConfig));this.POST_URL=webrtcStatsConfig.httpEndpoint;this.statsInterval=webrtcStatsConfig.interval;this.webRtcStatsIntervalId=setInterval(()=>__awaiter(this,void 0,void 0,function*(){yield this.sendStatsToHttpEndpoint()}),this.statsInterval*1e3)}else{logger.debug("WebRtc stats not enabled")}}getSelectedIceCandidateInfo(){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){const statsReport=yield this.stream.getRTCPeerConnection().getStats();let transportStat;const candidatePairs=new Map;const localCandidates=new Map;const remoteCandidates=new Map;statsReport.forEach(stat=>{if(stat.type==="transport"&&(platform.isChromium()||platform.isSafariBrowser()||platform.isReactNative())){transportStat=stat}switch(stat.type){case"candidate-pair":candidatePairs.set(stat.id,stat);break;case"local-candidate":localCandidates.set(stat.id,stat);break;case"remote-candidate":remoteCandidates.set(stat.id,stat);break}});let selectedCandidatePair;if(transportStat!=null){const selectedCandidatePairId=transportStat.selectedCandidatePairId;selectedCandidatePair=candidatePairs.get(selectedCandidatePairId)}else{const length=candidatePairs.size;const iterator=candidatePairs.values();for(let i=0;i<length;i++){const candidatePair=iterator.next().value;if(candidatePair["selected"]){selectedCandidatePair=candidatePair;break}}}const localCandidateId=selectedCandidatePair.localCandidateId;const remoteCandidateId=selectedCandidatePair.remoteCandidateId;let finalLocalCandidate=localCandidates.get(localCandidateId);if(!!finalLocalCandidate){const candList=this.stream.getLocalIceCandidateList();const cand=candList.filter(c=>!!c.candidate&&(c.candidate.indexOf(finalLocalCandidate.ip)>=0||c.candidate.indexOf(finalLocalCandidate.address)>=0)&&c.candidate.indexOf(finalLocalCandidate.port)>=0);finalLocalCandidate.raw=[];for(let c of cand){finalLocalCandidate.raw.push(c.candidate)}}else{finalLocalCandidate="ERROR: No active local ICE candidate. Probably ICE-TCP is being used"}let finalRemoteCandidate=remoteCandidates.get(remoteCandidateId);if(!!finalRemoteCandidate){const candList=this.stream.getRemoteIceCandidateList();const cand=candList.filter(c=>!!c.candidate&&(c.candidate.indexOf(finalRemoteCandidate.ip)>=0||c.candidate.indexOf(finalRemoteCandidate.address)>=0)&&c.candidate.indexOf(finalRemoteCandidate.port)>=0);finalRemoteCandidate.raw=[];for(let c of cand){finalRemoteCandidate.raw.push(c.candidate)}}else{finalRemoteCandidate="ERROR: No active remote ICE candidate. Probably ICE-TCP is being used"}return resolve({localCandidate:finalLocalCandidate,remoteCandidate:finalRemoteCandidate})}))}stopWebRtcStats(){if(this.webRtcStatsEnabled){clearInterval(this.webRtcStatsIntervalId);logger.warn("WebRtc stats stopped for disposed stream "+this.stream.streamId+" of connection "+this.stream.connection.connectionId)}}sendStats(url,response){return __awaiter(this,void 0,void 0,function*(){try{const configuration={headers:{"Content-type":"application/json"},body:JSON.stringify(response),method:"POST"};yield fetch(url,configuration)}catch(error){logger.error(`sendStats error: ${JSON.stringify(error)}`)}})}sendStatsToHttpEndpoint(){return __awaiter(this,void 0,void 0,function*(){try{const webrtcStats=yield this.getCommonStats();const response=this.generateJSONStatsResponse(webrtcStats);yield this.sendStats(this.POST_URL,response)}catch(error){logger.log(error)}})}getCommonStats(){return __awaiter(this,void 0,void 0,function*(){return new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){try{const statsReport=yield this.stream.getRTCPeerConnection().getStats();const response=this.getWebRtcStatsResponseOutline();const videoTrackStats=["framesReceived","framesDropped","framesSent","frameHeight","frameWidth"];const candidatePairStats=["availableOutgoingBitrate","currentRoundTripTime"];statsReport.forEach(stat=>{let mediaType=stat.mediaType!=null?stat.mediaType:stat.kind;const addStat=(direction,key)=>{if(stat[key]!=null&&response[direction]!=null){if(!mediaType&&videoTrackStats.indexOf(key)>-1){mediaType="video"}if(direction!=null&&mediaType!=null&&key!=null&&response[direction][mediaType]!=null){response[direction][mediaType][key]=Number(stat[key])}else if(direction!=null&&key!=null&&candidatePairStats.includes(key)){response[direction][key]=Number(stat[key])}}};switch(stat.type){case"outbound-rtp":addStat("outbound","bytesSent");addStat("outbound","packetsSent");addStat("outbound","framesEncoded");addStat("outbound","nackCount");addStat("outbound","firCount");addStat("outbound","pliCount");addStat("outbound","qpSum");break;case"inbound-rtp":addStat("inbound","bytesReceived");addStat("inbound","packetsReceived");addStat("inbound","packetsLost");addStat("inbound","jitter");addStat("inbound","framesDecoded");addStat("inbound","nackCount");addStat("inbound","firCount");addStat("inbound","pliCount");break;case"track":addStat("inbound","jitterBufferDelay");addStat("inbound","framesReceived");addStat("outbound","framesDropped");addStat("outbound","framesSent");addStat(this.stream.isLocal()?"outbound":"inbound","frameHeight");addStat(this.stream.isLocal()?"outbound":"inbound","frameWidth");break;case"candidate-pair":addStat("candidatepair","currentRoundTripTime");addStat("candidatepair","availableOutgoingBitrate");break}});if(!(response===null||response===void 0?void 0:response.candidatepair)||Object.keys(response.candidatepair).length===0){delete response.candidatepair}return resolve(response)}catch(error){logger.error("Error getting common stats: ",error);return reject(error)}}))})}generateJSONStatsResponse(stats){return{"@timestamp":(new Date).toISOString(),participant_id:this.stream.connection.data,session_id:this.stream.session.sessionId,platform:platform.getName(),platform_description:platform.getDescription(),stream:"webRTC",webrtc_stats:stats}}getWebRtcStatsResponseOutline(){if(this.stream.isLocal()){return{outbound:{audio:{},video:{}},candidatepair:{}}}else{return{inbound:{audio:{},video:{}}}}}}exports.WebRtcStats=WebRtcStats},{"../Logger/OpenViduLogger":81,"../Utils/Platform":85}]},{},[41]);
|