From 8cd592eecfc3c9b0a77a6be4c974baceae2012ae Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 28 Oct 2022 12:55:57 +0000 Subject: chore(release): 1.9.1 ## [1.9.1](https://github.com/webtorrent/webtorrent/compare/v1.9.0...v1.9.1) (2022-10-28) ### Bug Fixes * **deps:** update dependency streamx to ^2.12.5 ([#2366](https://github.com/webtorrent/webtorrent/issues/2366)) ([457a2d3](https://github.com/webtorrent/webtorrent/commit/457a2d3d5def6bb75d2551f34ab9fa350ec4a4e5)) --- CHANGELOG.md | 7 +++++++ package.json | 2 +- webtorrent.chromeapp.js | 2 +- webtorrent.min.js | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc24fca..ba2fb04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [1.9.1](https://github.com/webtorrent/webtorrent/compare/v1.9.0...v1.9.1) (2022-10-28) + + +### Bug Fixes + +* **deps:** update dependency streamx to ^2.12.5 ([#2366](https://github.com/webtorrent/webtorrent/issues/2366)) ([457a2d3](https://github.com/webtorrent/webtorrent/commit/457a2d3d5def6bb75d2551f34ab9fa350ec4a4e5)) + # [1.9.0](https://github.com/webtorrent/webtorrent/compare/v1.8.32...v1.9.0) (2022-10-28) diff --git a/package.json b/package.json index 06f514c..0b1511a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webtorrent", "description": "Streaming torrent client", - "version": "1.9.0", + "version": "1.9.1", "author": { "name": "WebTorrent LLC", "email": "feross@webtorrent.io", diff --git a/webtorrent.chromeapp.js b/webtorrent.chromeapp.js index 031ce81..127c643 100644 --- a/webtorrent.chromeapp.js +++ b/webtorrent.chromeapp.js @@ -50,4 +50,4 @@ object-assign * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015-2016 Douglas Christopher Wilson * MIT Licensed - */"use strict";function rangeParser(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;isize-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;icurrent.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=rangeParser},{}],265:[function(require,module,exports){const{Writable,PassThrough}=require("readable-stream");class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;!0;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}module.exports=RangeSliceStream},{"readable-stream":281}],266:[function(require,module,exports){"use strict";function isInteger(n){return parseInt(n,10)===n}function createRC4(N){function identityPermutation(){for(var s=Array(N),i=0;in?_StringfromCharCode(48+n):_StringfromCharCode(97+n-10)}function fromHex(c){return parseInt(c,16)}var RC4=createRC4(256);RC4.prototype.randomByte=RC4.prototype.randomNative;var RC4small=createRC4(16);RC4small.prototype.randomByte=function(){var a=this.randomNative(),b=this.randomNative();return 16*a+b};var ordA=97,ord0=48;RC4small.prototype.currentStateString=function(){var state=this.currentState(),i=toHex(state.i),j=toHex(state.j),res=i+j+state.s.map(toHex).join("");return res},RC4small.prototype.setStateString=function(stateString){if(!stateString.match(/^[0-9a-f]{18}$/))throw new TypeError("RC4small stateString should be 18 hex character string");var i=fromHex(stateString[0]),j=fromHex(stateString[1]),s=stateString.split("").slice(2).map(fromHex);this.setState({i:i,j:j,s:s})},RC4.RC4small=RC4small,module.exports=RC4},{}],267:[function(require,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],268:[function(require,module,exports){(function(process){(function(){"use strict";function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:101,util:66}],275:[function(require,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)}function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require("_process"))},{_process:246}],276:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function onlegacyfinish(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function onfinish(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function onend(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function onerror(err){callback.call(stream,err)},onclose=function onclose(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function onrequest(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":267}],277:[function(require,module,exports){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],278:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}function pipeline(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":267}],280:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:156}],281:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":268,"./lib/_stream_passthrough.js":269,"./lib/_stream_readable.js":270,"./lib/_stream_transform.js":271,"./lib/_stream_writable.js":272,"./lib/internal/streams/end-of-stream.js":276,"./lib/internal/streams/pipeline.js":278}],282:[function(require,module,exports){function RecordSet(){this.list=[],this.map=new Map}function RecordStore(){this.records=new Map,this.size=0}function RecordCache(opts){if(!(this instanceof RecordCache))return new RecordCache(opts);if(opts||(opts={}),this.maxSize=opts.maxSize||1/0,this.maxAge=opts.maxAge||0,this._onstale=opts.onStale||opts.onstale||null,this._fresh=new RecordStore,this._stale=new RecordStore,this._interval=null,this._gced=!1,this.maxAge&&this.maxAge<1/0){var tick=_Mathceil(2/3*this.maxAge);this._interval=setInterval(this._gcAuto.bind(this),tick),this._interval.unref&&this._interval.unref()}}function toString(record){return b4a.isBuffer(record)?b4a.toString(record,"hex"):record}function swap(list,a,b){var tmp=list[a];tmp.index=b,list[b].index=a,list[a]=list[b],list[b]=tmp}const b4a=require("b4a");var EMPTY=[];module.exports=RecordCache,RecordSet.prototype.add=function(record,value){var k=toString(record),r=this.map.get(k);return!r&&(r={index:this.list.length,record:value||record},this.list.push(r),this.map.set(k,r),!0)},RecordSet.prototype.remove=function(record){var k=toString(record),r=this.map.get(k);return!!r&&(swap(this.list,r.index,this.list.length-1),this.list.pop(),this.map.delete(k),!0)},RecordStore.prototype.add=function(name,record,value){var r=this.records.get(name);return r||(r=new RecordSet,this.records.set(name,r)),!!r.add(record,value)&&(this.size++,!0)},RecordStore.prototype.remove=function(name,record,value){var r=this.records.get(name);return!!r&&!!r.remove(record,value)&&(this.size--,r.map.size||this.records.delete(name),!0)},RecordStore.prototype.get=function(name){var r=this.records.get(name);return r?r.list:EMPTY},Object.defineProperty(RecordCache.prototype,"size",{get:function(){return this._fresh.size+this._stale.size}}),RecordCache.prototype.add=function(name,record,value){this._stale.remove(name,record,value),this._fresh.add(name,record,value)&&this._fresh.size>this.maxSize&&this._gc()},RecordCache.prototype.remove=function(name,record,value){this._fresh.remove(name,record,value),this._stale.remove(name,record,value)},RecordCache.prototype.get=function(name,n){var a=this._fresh.get(name),b=this._stale.get(name),aLen=a.length,bLen=b.length,len=aLen+bLen;(n>len||!n)&&(n=len);for(var result=Array(n),i=0,j;i{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)}function append(file,rootElem,opts,cb){function getElem(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)}function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,getElem,opts,done)}function renderMedia(file,getElem,opts,cb){function renderMediaSource(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),elem.src=url)))}function onLoadStart(){if(elem.removeEventListener("loadstart",onLoadStart),opts.autoplay){const playPromise=elem.play();"undefined"!=typeof playPromise&&playPromise.catch(fatalError)}}function onLoadedMetadata(){elem.removeEventListener("loadedmetadata",onLoadedMetadata),cb(null,elem)}function renderImage(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function tryRenderIframe(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?renderMediaSource():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?renderImage():IFRAME_EXTS.includes(extname)?renderIframe():tryRenderIframe()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=render,exports.append=append,exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_AUDIO_EXTS=[".m4a",".m4b",".m4p",".mp3"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,MEDIASOURCE_AUDIO_EXTS),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":284,debug:122,"is-ascii":193,mediasource:212,path:238,"stream-to-blob-url":316,videostream:340}],284:[function(require,module,exports){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],285:[function(require,module,exports){"use strict";function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^c^d)+m+k,s)+e}function fn2(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&c|~b&d)+m+k,s)+e}function fn3(a,b,c,d,e,m,k,s){return 0|rotl(0|a+((b|~c)^d)+m+k,s)+e}function fn4(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&d|c&~d)+m+k,s)+e}function fn5(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^(c|~d))+m+k,s)+e}var Buffer=require("buffer").Buffer,inherits=require("inherits"),HashBase=require("hash-base"),ARRAY16=Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;16>j;++j)words[j]=this._block.readInt32LE(4*j);for(var al=0|this._a,bl=0|this._b,cl=0|this._c,dl=0|this._d,el=0|this._e,ar=0|this._a,br=0|this._b,cr=0|this._c,dr=0|this._d,er=0|this._e,i=0;80>i;i+=1){var tl,tr;16>i?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):32>i?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):48>i?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):64>i?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=0|this._b+cl+dr;this._b=0|this._c+dl+er,this._c=0|this._d+el+ar,this._d=0|this._e+al+br,this._e=0|this._a+bl+cr,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,56=tasks.length||err?done(err):tasks[current](each)}var current=0,results=[],isSync=!0;0 */module.exports=runSeries}).call(this)}).call(this,require("_process"))},{_process:246}],289:[function(require,module,exports){(function webpackUniversalModuleDefinition(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?exports.Rusha=factory():root.Rusha=factory()})("undefined"==typeof self?this:self,function(){return function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=3)}([function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var RushaCore=__webpack_require__(5),_require=__webpack_require__(1),toHex=_require.toHex,ceilHeapSize=_require.ceilHeapSize,conv=__webpack_require__(6),padlen=function(len){for(len+=9;0>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function _write(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function _coreCall(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function rawDigest(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function digest(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function digestFromString(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function digestFromBuffer(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function digestFromArrayBuffer(str){return this.digest(str)},Rusha.prototype.resetState=function resetState(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function append(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$851=0|H$843[x$846+324>>2],y2$853=0|H$843[x$846+328>>2],y3$855=0|H$843[x$846+332>>2],y4$857=0|H$843[x$846+336>>2],i$847=0;(0|i$847)<(0|k$845);i$847=0|i$847+64){for(z0$850=y0$849,z1$852=y1$851,z2$854=y2$853,z3$856=y3$855,z4$858=y4$857,j$848=0;64>(0|j$848);j$848=0|j$848+4)t1$860=0|H$843[i$847+j$848>>2],t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[k$845+j$848>>2]=t1$860;for(j$848=0|k$845+64;(0|j$848)<(0|k$845+80);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+80;(0|j$848)<(0|k$845+160);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)+1859775393),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+160;(0|j$848)<(0|k$845+240);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|y1$851&y3$855|y2$853&y3$855))+(0|(0|t1$860+y4$857)-1894007588),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+240;(0|j$848)<(0|k$845+320);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)-899497514),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;y0$849=0|y0$849+z0$850,y1$851=0|y1$851+z1$852,y2$853=0|y2$853+z2$854,y3$855=0|y3$855+z3$856,y4$857=0|y4$857+z4$858}H$843[x$846+320>>2]=y0$849,H$843[x$846+324>>2]=y1$851,H$843[x$846+328>>2]=y2$853,H$843[x$846+332>>2]=y3$855,H$843[x$846+336>>2]=y4$857}var H$843=new stdlib$840.Int32Array(heap$842);return{hash:hash$844}}},function(module,exports){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:101}],291:[function(require,module,exports){(function(process){(function(){"use strict";var buffer=require("buffer"),Buffer=buffer.Buffer,safer={},key;for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw new TypeError("The \"value\" argument must not be of type number. Received type "+typeof value);if(value&&"undefined"==typeof value.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("The \"size\" argument must be of type number. Received type "+typeof size);if(0>size||2147483648<=size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"");var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}).call(this)}).call(this,require("_process"))},{_process:246,buffer:101}],292:[function(require,module,exports){function Hash(blockSize,finalSize){this._block=Buffer.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}var Buffer=require("safe-buffer").Buffer;Hash.prototype.update=function(data,enc){"string"==typeof data&&(enc=enc||"utf8",data=Buffer.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=8*this._len;if(4294967295>=bits)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(4294967295&bits)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")},module.exports=Hash},{"safe-buffer":290}],293:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha"),exports.sha1=require("./sha1"),exports.sha224=require("./sha224"),exports.sha256=require("./sha256"),exports.sha384=require("./sha384"),exports.sha512=require("./sha512")},{"./sha":294,"./sha1":295,"./sha224":296,"./sha256":297,"./sha384":298,"./sha512":299}],294:[function(require,module,exports){function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha},{"./hash":292,inherits:190,"safe-buffer":290}],295:[function(require,module,exports){function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha1.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha1.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha1},{"./hash":292,inherits:190,"safe-buffer":290}],296:[function(require,module,exports){function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}var inherits=require("inherits"),Sha256=require("./sha256"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(64);inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224},{"./hash":292,"./sha256":297,inherits:190,"safe-buffer":290}],297:[function(require,module,exports){function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=Array(64);inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},Sha256.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;64>i;++i)W[i]=0|gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16];for(var j=0;64>j;++j){var T1=0|h+sigma1(e)+ch(e,f,g)+K[j]+W[j],T2=0|sigma0(a)+maj(a,b,c);h=g,g=f,f=e,e=0|d+T1,d=c,c=b,b=a,a=0|T1+T2}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e,this._f=0|f+this._f,this._g=0|g+this._g,this._h=0|h+this._h},Sha256.prototype._hash=function(){var H=Buffer.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256},{"./hash":292,inherits:190,"safe-buffer":290}],298:[function(require,module,exports){function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}var inherits=require("inherits"),SHA512=require("./sha512"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(160);inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(48);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384},{"./hash":292,"./sha512":299,inherits:190,"safe-buffer":290}],299:[function(require,module,exports){function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=Array(160);inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Sha512.prototype._update=function(M){for(var W=this._w,ah=0|this._ah,bh=0|this._bh,ch=0|this._ch,dh=0|this._dh,eh=0|this._eh,fh=0|this._fh,gh=0|this._gh,hh=0|this._hh,al=0|this._al,bl=0|this._bl,cl=0|this._cl,dl=0|this._dl,el=0|this._el,fl=0|this._fl,gl=0|this._gl,hl=0|this._hl,i=0;32>i;i+=2)W[i]=M.readInt32BE(4*i),W[i+1]=M.readInt32BE(4*i+4);for(;160>i;i+=2){var xh=W[i-30],xl=W[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W[i-4],xl=W[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W[i-14],Wi7l=W[i-14+1],Wi16h=W[i-32],Wi16l=W[i-32+1],Wil=0|gamma0l+Wi7l,Wih=0|gamma0+Wi7h+getCarry(Wil,gamma0l);Wil=0|Wil+gamma1l,Wih=0|Wih+gamma1+getCarry(Wil,gamma1l),Wil=0|Wil+Wi16l,Wih=0|Wih+Wi16h+getCarry(Wil,Wi16l),W[i]=Wih,W[i+1]=Wil}for(var j=0;160>j;j+=2){Wih=W[j],Wil=W[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=0|hl+sigma1l,t1h=0|hh+sigma1h+getCarry(t1l,hl);t1l=0|t1l+chl,t1h=0|t1h+chh+getCarry(t1l,chl),t1l=0|t1l+Kil,t1h=0|t1h+Kih+getCarry(t1l,Kil),t1l=0|t1l+Wil,t1h=0|t1h+Wih+getCarry(t1l,Wil);var t2l=0|sigma0l+majl,t2h=0|sigma0h+majh+getCarry(t2l,sigma0l);hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=0|dl+t1l,eh=0|dh+t1h+getCarry(el,dl),dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=0|t1l+t2l,ah=0|t1h+t2h+getCarry(al,t1l)}this._al=0|this._al+al,this._bl=0|this._bl+bl,this._cl=0|this._cl+cl,this._dl=0|this._dl+dl,this._el=0|this._el+el,this._fl=0|this._fl+fl,this._gl=0|this._gl+gl,this._hl=0|this._hl+hl,this._ah=0|this._ah+ah+getCarry(this._al,al),this._bh=0|this._bh+bh+getCarry(this._bl,bl),this._ch=0|this._ch+ch+getCarry(this._cl,cl),this._dh=0|this._dh+dh+getCarry(this._dl,dl),this._eh=0|this._eh+eh+getCarry(this._el,el),this._fh=0|this._fh+fh+getCarry(this._fl,fl),this._gh=0|this._gh+gh+getCarry(this._gl,gl),this._hh=0|this._hh+hh+getCarry(this._hl,hl)},Sha512.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(64);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512},{"./hash":292,inherits:190,"safe-buffer":290}],300:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],301:[function(require,module,exports){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const originalHost=opts.hostname,protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location){opts.url=res.headers.location,delete opts.headers.host,res.resume();const redirectHost=url.parse(opts.url).hostname;return null!==redirectHost&&redirectHost!==originalHost&&(delete opts.headers.cookie,delete opts.headers.authorization),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb)}const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"decompress-response":66,http:312,https:187,once:231,querystring:258,"simple-concat":300,url:331}],302:[function(require,module,exports){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5000,CHANNEL_CLOSING_TIMEOUT=5000;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(err=>{this.destroy(errCode(err,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(chunk)}}addTransceiver(kind,init){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}}addStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}}addTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=event=>{const err=event.error instanceof Error?event.error:new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`);this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}},onSuccess=()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(offer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}},onSuccess=()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(answer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:101,debug:122,"err-code":153,"get-browser-rtc":166,"queue-microtask":259,randombytes:262,"readable-stream":281}],303:[function(require,module,exports){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function succeed(result){cb(hex(new Uint8Array(result)))},function fail(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function onRushaWorkerSha1(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){const l=s.length,array=new Uint8Array(l);for(let i=0;i>>4).toString(16)),chars.push((15&bite).toString(16))}return chars.join("")}const Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{};let subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":304,rusha:289}],304:[function(require,module,exports){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function onRushaMessage(e){const taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}const Rusha=require("rusha");let worker,nextTaskId,cbs;module.exports=sha1},{rusha:289}],305:[function(require,module,exports){(function(Buffer){(function(){/*! simple-websocket. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,null,{...opts,encoding:void 0}):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",opts.socket&&this.connected?queueMicrotask(()=>this._handleOpen()):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=event=>this._handleMessage(event),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=err=>this._handleError(err),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}this._ws=null,err&&this.emit("error",err),this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_handleOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(_){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,debug:122,"queue-microtask":259,randombytes:262,"readable-stream":281,ws:66}],306:[function(require,module,exports){const Throttle=require("./lib/throttle"),ThrottleGroup=require("./lib/throttle-group");module.exports={Throttle,ThrottleGroup}},{"./lib/throttle":308,"./lib/throttle-group":307}],307:[function(require,module,exports){const{TokenBucket}=require("limiter"),Throttle=require("./throttle");class ThrottleGroup{constructor(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");this.throttles=[],this.setEnabled(opts.enabled),this.setRate(opts.rate,opts.chunksize)}getEnabled(){return this._enabled}getRate(){return this.bucket.tokensPerInterval}getChunksize(){return this.chunksize}setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val;for(const throttle of this.throttles)throttle.setEnabled(val)}setRate(rate,chunksize=null){if(!_NumberisInteger(rate)||0>rate)throw new Error("Rate must be an integer bigger than zero");if(rate=parseInt(rate),chunksize&&("number"!=typeof chunksize||0>=chunksize))throw new Error("Chunksize must be bigger than zero");if(chunksize=chunksize||_Mathmax(parseInt(rate/10),1),chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.bucket||(this.bucket=new TokenBucket(rate,rate,"second",null)),this.bucket.bucketSize=rate,this.bucket.tokensPerInterval=rate,this.chunksize=chunksize}setChunksize(chunksize){if(!_NumberisInteger(chunksize)||0>=chunksize)throw new Error("Chunk size must be an integer bigger than zero");const rate=this.getRate();if(chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.chunksize=chunksize}throttle(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");const newThrottle=new Throttle({...opts,group:this});return newThrottle}destroy(){for(const throttle of this.throttles)throttle.destroy();this.throttles=[]}_addThrottle(throttle){if(!(throttle instanceof Throttle))throw new Error("Throttle must be an instance of Throttle");this.throttles.push(throttle)}_removeThrottle(throttle){const index=this.throttles.indexOf(throttle);-1{function isDone(err){if(self._emitter.removeListener("disabled",isDone),self._emitter.removeListener("destroyed",isDone),!done)return done=!0,err?reject(err):void resolve()}let done=!1;const self=this;this._emitter.once("disabled",isDone),this._emitter.once("destroyed",isDone),this._group.bucket.removeTokens(amount,isDone)})}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(chunk,done){if(!this._areBothEnabled())return done(null,chunk);let pos=0,chunksize=this._group.getChunksize(),slice=chunk.slice(pos,pos+chunksize);for(;0setTimeout(resolve,time))}module.exports={wait}},{}],310:[function(require,module,exports){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){resetTimers(!0),self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&(resetTimers(!0),self.push(null))}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":313,_process:246,buffer:101,inherits:190,"readable-stream":281}],316:[function(require,module,exports){async function getBlobURL(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url}module.exports=getBlobURL;const getBlob=require("stream-to-blob")},{"stream-to-blob":317}],317:[function(require,module,exports){function streamToBlob(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=streamToBlob},{}],318:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function getBuffer(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,once:231}],319:[function(require,module,exports){function afterDrain(){this.stream._duplexState|=READ_PIPE_DRAINED,0==(this.stream._duplexState&READ_ACTIVE_AND_SYNC)?this.updateNextTick():this.drain()}function afterFinal(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROY_STATUS)&&(stream._duplexState|=WRITE_DONE,stream.emit("finish")),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),stream._duplexState&=WRITE_NOT_ACTIVE,this.update()}function afterDestroy(err){const stream=this.stream;err||this.error===STREAM_DESTROYED||(err=this.error),err&&stream.emit("error",err),stream._duplexState|=DESTROYED,stream.emit("close");const rs=stream._readableState,ws=stream._writableState;null!==rs&&null!==rs.pipeline&&rs.pipeline.done(stream,err),null!==ws&&null!==ws.pipeline&&ws.pipeline.done(stream,err)}function afterWrite(err){const stream=this.stream;err&&stream.destroy(err),stream._duplexState&=WRITE_NOT_ACTIVE,(stream._duplexState&WRITE_DRAIN_STATUS)===WRITE_UNDRAINED&&(stream._duplexState&=WRITE_DRAINED,(stream._duplexState&WRITE_EMIT_DRAIN)===WRITE_EMIT_DRAIN&&stream.emit("drain")),0==(stream._duplexState&WRITE_SYNC)&&this.update()}function afterRead(err){err&&this.stream.destroy(err),this.stream._duplexState&=READ_NOT_ACTIVE,0==(this.stream._duplexState&READ_SYNC)&&this.update()}function updateReadNT(){this.stream._duplexState&=READ_NOT_NEXT_TICK,this.update()}function updateWriteNT(){this.stream._duplexState&=WRITE_NOT_NEXT_TICK,this.update()}function afterOpen(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROYING)&&(0==(stream._duplexState&READ_PRIMARY_STATUS)&&(stream._duplexState|=READ_PRIMARY),0==(stream._duplexState&WRITE_PRIMARY_STATUS)&&(stream._duplexState|=WRITE_PRIMARY),stream.emit("open")),stream._duplexState&=NOT_ACTIVE,null!==stream._writableState&&stream._writableState.update(),null!==stream._readableState&&stream._readableState.update()}function afterTransform(err,data){data!==void 0&&null!==data&&this.push(data),this._writableState.afterWrite(err)}function transformAfterFlush(err,data){const cb=this._transformState.afterFinal;return err?cb(err):void(null!==data&&data!==void 0&&this.push(data),this.push(null),cb(null))}function pipelinePromise(...streams){return new Promise((resolve,reject)=>pipeline(...streams,err=>err?reject(err):void resolve()))}function pipeline(stream,...streams){function errorHandle(s,rd,wr,onerror){function onclose(){return rd&&s._readableState&&!s._readableState.ended?onerror(PREMATURE_CLOSE):wr&&s._writableState&&!s._writableState.ended?onerror(PREMATURE_CLOSE):void 0}s.on("error",onerror),s.on("close",onclose)}function onerror(err){if(err&&!error){error=err;for(const s of all)s.destroy(err)}}const all=Array.isArray(stream)?[...stream,...streams]:[stream,...streams],done=all.length&&"function"==typeof all[all.length-1]?all.pop():null;if(2>all.length)throw new Error("Pipeline requires at least 2 streams");let src=all[0],dest=null,error=null;for(let i=1;i{fin=!0}),dest.on("error",err=>{error=error||err}),dest.on("close",()=>done(error||(fin?null:PREMATURE_CLOSE)))}return dest}function isStream(stream){return!!stream._readableState||!!stream._writableState}function isStreamx(stream){return"number"==typeof stream._duplexState&&isStream(stream)}function isReadStreamx(stream){return isStreamx(stream)&&stream.readable}function isTypedArray(data){return"object"==typeof data&&null!==data&&"number"==typeof data.byteLength}function defaultByteLength(data){return isTypedArray(data)?data.byteLength:1024}function noop(){}function abort(){this.destroy(new Error("Stream aborted."))}const{EventEmitter}=require("events"),STREAM_DESTROYED=new Error("Stream was destroyed"),PREMATURE_CLOSE=new Error("Premature close"),queueTick=require("queue-tick"),FIFO=require("fast-fifo"),MAX=33554431,OPENING=1,DESTROYING=2,DESTROYED=4,NOT_OPENING=MAX^OPENING,READ_ACTIVE=8,READ_PRIMARY=16,READ_SYNC=32,READ_QUEUED=64,READ_RESUMED=128,READ_PIPE_DRAINED=256,READ_ENDING=512,READ_EMIT_DATA=1024,READ_EMIT_READABLE=2048,READ_EMITTED_READABLE=4096,READ_DONE=8192,READ_NEXT_TICK=16392,READ_NEEDS_PUSH=32768,READ_NOT_ACTIVE=MAX^READ_ACTIVE,READ_NON_PRIMARY=MAX^READ_PRIMARY,READ_NON_PRIMARY_AND_PUSHED=MAX^(READ_PRIMARY|READ_NEEDS_PUSH),READ_NOT_SYNC=MAX^READ_SYNC,READ_PUSHED=MAX^READ_NEEDS_PUSH,READ_PAUSED=MAX^READ_RESUMED,READ_NOT_QUEUED=MAX^(READ_QUEUED|READ_EMITTED_READABLE),READ_NOT_ENDING=MAX^READ_ENDING,READ_PIPE_NOT_DRAINED=MAX^(READ_RESUMED|READ_PIPE_DRAINED),READ_NOT_NEXT_TICK=MAX^READ_NEXT_TICK,WRITE_ACTIVE=65536,WRITE_PRIMARY=131072,WRITE_SYNC=262144,WRITE_QUEUED=524288,WRITE_UNDRAINED=1048576,WRITE_DONE=2097152,WRITE_EMIT_DRAIN=4194304,WRITE_NEXT_TICK=8454144,WRITE_FINISHING=16777216,WRITE_NOT_ACTIVE=MAX^WRITE_ACTIVE,WRITE_NOT_SYNC=MAX^WRITE_SYNC,WRITE_NON_PRIMARY=MAX^WRITE_PRIMARY,WRITE_NOT_FINISHING=MAX^WRITE_FINISHING,WRITE_DRAINED=MAX^WRITE_UNDRAINED,WRITE_NOT_QUEUED=MAX^WRITE_QUEUED,WRITE_NOT_NEXT_TICK=MAX^WRITE_NEXT_TICK,ACTIVE=READ_ACTIVE|WRITE_ACTIVE,NOT_ACTIVE=MAX^ACTIVE,DONE=READ_DONE|WRITE_DONE,DESTROY_STATUS=DESTROYING|DESTROYED,OPEN_STATUS=DESTROY_STATUS|OPENING,AUTO_DESTROY=DESTROY_STATUS|DONE,NON_PRIMARY=WRITE_NON_PRIMARY&READ_NON_PRIMARY,TICKING=(WRITE_NEXT_TICK|READ_NEXT_TICK)&NOT_ACTIVE,ACTIVE_OR_TICKING=ACTIVE|TICKING,IS_OPENING=OPEN_STATUS|TICKING,READ_PRIMARY_STATUS=OPEN_STATUS|READ_ENDING|READ_DONE,READ_STATUS=OPEN_STATUS|READ_DONE|READ_QUEUED,READ_FLOWING=READ_RESUMED|READ_PIPE_DRAINED,READ_ACTIVE_AND_SYNC=READ_ACTIVE|READ_SYNC,READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH=READ_ACTIVE|READ_SYNC|READ_NEEDS_PUSH,READ_PRIMARY_AND_ACTIVE=READ_PRIMARY|READ_ACTIVE,READ_ENDING_STATUS=OPEN_STATUS|READ_ENDING|READ_QUEUED,READ_EMIT_READABLE_AND_QUEUED=READ_EMIT_READABLE|READ_QUEUED,READ_READABLE_STATUS=OPEN_STATUS|READ_EMIT_READABLE|READ_QUEUED|READ_EMITTED_READABLE,SHOULD_NOT_READ=OPEN_STATUS|READ_ACTIVE|READ_ENDING|READ_DONE|READ_NEEDS_PUSH,READ_BACKPRESSURE_STATUS=DESTROY_STATUS|READ_ENDING|READ_DONE,WRITE_PRIMARY_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_DONE,WRITE_QUEUED_AND_UNDRAINED=WRITE_QUEUED|WRITE_UNDRAINED,WRITE_QUEUED_AND_ACTIVE=WRITE_QUEUED|WRITE_ACTIVE,WRITE_DRAIN_STATUS=WRITE_QUEUED|WRITE_UNDRAINED|OPEN_STATUS|WRITE_ACTIVE,WRITE_STATUS=OPEN_STATUS|WRITE_ACTIVE|WRITE_QUEUED,WRITE_PRIMARY_AND_ACTIVE=WRITE_PRIMARY|WRITE_ACTIVE,WRITE_ACTIVE_AND_SYNC=WRITE_ACTIVE|WRITE_SYNC,WRITE_FINISHING_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_QUEUED_AND_ACTIVE|WRITE_DONE,WRITE_BACKPRESSURE_STATUS=WRITE_UNDRAINED|DESTROY_STATUS|WRITE_FINISHING|WRITE_DONE,asyncIterator=Symbol.asyncIterator||Symbol("asyncIterator");class WritableState{constructor(stream,{highWaterMark=16384,map=null,mapWritable,byteLength,byteLengthWritable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthWritable||byteLength||defaultByteLength,this.map=mapWritable||map,this.afterWrite=afterWrite.bind(this),this.afterUpdateNextTick=updateWriteNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&WRITE_DONE)}push(data){return(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),this.buffered=rs._readableState.highWaterMark}static isPaused(rs){return 0==(rs._duplexState&READ_RESUMED)}[asyncIterator](){function onreadable(){null!==promiseResolve&&ondata(stream.read())}function onclose(){null!==promiseResolve&&ondata(null)}function ondata(data){null===promiseReject||(error?promiseReject(error):null===data&&0==(stream._duplexState&READ_DONE)?promiseReject(STREAM_DESTROYED):promiseResolve({value:data,done:null==data}),promiseReject=promiseResolve=null)}function destroy(err){return stream.destroy(err),new Promise((resolve,reject)=>stream._duplexState&DESTROYED?resolve({value:void 0,done:!0}):void stream.once("close",function(){err?reject(err):resolve({value:void 0,done:!0})}))}const stream=this;let error=null,promiseResolve=null,promiseReject=null;return this.on("error",err=>{error=err}),this.on("readable",onreadable),this.on("close",onclose),{[asyncIterator](){return this},next(){return new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject;const data=stream.read();null===data?0!=(stream._duplexState&DESTROYED)&&ondata(null):ondata(data)})},return(){return destroy(null)},throw(err){return destroy(err)}}}}class Writable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|READ_DONE,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}static isBackpressured(ws){return 0!=(ws._duplexState&WRITE_BACKPRESSURE_STATUS)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Duplex extends Readable{constructor(opts){super(opts),this._duplexState=OPENING,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Transform extends Duplex{constructor(opts){super(opts),this._transformState=new TransformState(this),opts&&(opts.transform&&(this._transform=opts.transform),opts.flush&&(this._flush=opts.flush))}_write(data,cb){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=data:this._transform(data,this._transformState.afterTransform)}_read(cb){if(null!==this._transformState.data){const data=this._transformState.data;this._transformState.data=null,cb(null),this._transform(data,this._transformState.afterTransform)}else cb(null)}_transform(data,cb){cb(null,data)}_flush(cb){cb(null)}_final(cb){this._transformState.afterFinal=cb,this._flush(transformAfterFlush.bind(this))}}class PassThrough extends Transform{}module.exports={pipeline,pipelinePromise,isStream,isStreamx,Stream,Writable,Readable,Duplex,Transform,PassThrough}},{events:156,"fast-fifo":160,"queue-tick":260}],320:[function(require,module,exports){(function(Buffer){(function(){const addrToIPPort=require("addr-to-ip-port"),ipaddr=require("ipaddr.js");module.exports=addrs=>("string"==typeof addrs&&(addrs=[addrs]),Buffer.concat(addrs.map(addr=>{const s=addrToIPPort(addr);if(2!==s.length)throw new Error("invalid address format, expecting: 10.10.10.5:128");const ip=ipaddr.parse(s[0]),ipBuf=Buffer.from(ip.toByteArray()),port=s[1],portBuf=Buffer.allocUnsafe(2);return portBuf.writeUInt16BE(port,0),Buffer.concat([ipBuf,portBuf])}))),module.exports.multi=module.exports,module.exports.multi6=module.exports}).call(this)}).call(this,require("buffer").Buffer)},{"addr-to-ip-port":16,buffer:101,"ipaddr.js":191}],321:[function(require,module,exports){arguments[4][96][0].apply(exports,arguments)},{dup:96,"safe-buffer":290}],322:[function(require,module,exports){var base32=require("./thirty-two");exports.encode=base32.encode,exports.decode=base32.decode},{"./thirty-two":323}],323:[function(require,module,exports){(function(Buffer){(function(){"use strict";function quintetCount(buff){var quintets=_Mathfloor(buff.length/5);return 0==buff.length%5?quintets:quintets+1}var charTable="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",byteTable=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];exports.encode=function(plain){Buffer.isBuffer(plain)||(plain=new Buffer(plain));for(var i=0,j=0,shiftIndex=0,digit=0,encoded=new Buffer(8*quintetCount(plain));i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],324:[function(require,module,exports){function getTick(start){return 65535&(+Date.now()-start)/timeDiff}const maxTick=65535,resolution=10,timeDiff=1e3/resolution;module.exports=function(seconds){const start=+Date.now(),size=resolution*(seconds||5),buffer=[0];let pointer=1,last=getTick(start)-1&maxTick;return function(delta){const tick=getTick(start);let dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);const top=buffer[pointer-1],btm=buffer.lengtharguments.length)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function onNextTick(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":246,timers:325}],326:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=(peer,infoHash)=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}module.exports=Discovery}).call(this)}).call(this,require("_process"))},{_process:246,"bittorrent-dht/client":52,"bittorrent-lsd":53,"bittorrent-tracker/client":55,debug:122,events:156,"run-parallel":287}],328:[function(require,module,exports){(function(Buffer){(function(){/*! torrent-piece. MIT License. WebTorrent LLC */const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),MAX_METADATA_SIZE=1E7,BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash,peerId,extensions){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||MAX_METADATA_SIZE=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf,totalSize){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0 */const EventEmitter=require("events").EventEmitter,compact2string=require("compact2string"),string2compact=require("string2compact"),bencode=require("bencode"),PEX_INTERVAL=65e3,PEX_MAX_PEERS=50,PEX_MIN_ALLOWED_INTERVAL=6e4,FLAGS={prefersEncryption:1,isSender:2,supportsUtp:4,supportsUtHolepunch:8,isReachable:16};module.exports=()=>{class utPex extends EventEmitter{constructor(wire){super(),this._wire=wire,this._intervalId=null,this._lastMessageTimestamp=0,this.reset()}start(){clearInterval(this._intervalId),this._intervalId=setInterval(()=>this._sendMessage(),PEX_INTERVAL),this._intervalId.unref&&this._intervalId.unref()}stop(){clearInterval(this._intervalId),this._intervalId=null}reset(){this._remoteAddedPeers={},this._remoteDroppedPeers={},this._localAddedPeers={},this._localDroppedPeers={},this.stop()}addPeer(peer,flags={}){this._addPeer(peer,this._encodeFlags(flags),4)}addPeer6(peer,flags={}){this._addPeer(peer,this._encodeFlags(flags),6)}_addPeer(peer,flags,version){!peer.includes(":")||peer in this._remoteAddedPeers||(peer in this._localDroppedPeers&&delete this._localDroppedPeers[peer],this._localAddedPeers[peer]={ip:version,flags:flags})}dropPeer(peer){this._dropPeer(peer,4)}dropPeer6(peer){this._dropPeer(peer,6)}_dropPeer(peer,version){!peer.includes(":")||peer in this._remoteDroppedPeers||(peer in this._localAddedPeers&&delete this._localAddedPeers[peer],this._localDroppedPeers[peer]={ip:version})}onExtendedHandshake(handshake){if(!handshake.m||!handshake.m.ut_pex)return this.emit("warning",new Error("Peer does not support ut_pex"))}onMessage(buf){const currentMessageTimestamp=Date.now();if(currentMessageTimestamp-this._lastMessageTimestamp{if(delete this._remoteDroppedPeers[peer],!(peer in this._remoteAddedPeers)){const flags=message["added.f"][idx];this._remoteAddedPeers[peer]={ip:4,flags:flags},this.emit("peer",peer,this._decodeFlags(flags))}}),message.added6&&compact2string.multi6(message.added6).forEach((peer,idx)=>{if(delete this._remoteDroppedPeers[peer],!(peer in this._remoteAddedPeers)){const flags=message["added6.f"][idx];this._remoteAddedPeers[peer]={ip:6,flags:flags},this.emit("peer",peer,this._decodeFlags(flags))}}),message.dropped&&compact2string.multi(message.dropped).forEach(peer=>{delete this._remoteAddedPeers[peer],peer in this._remoteDroppedPeers||(this._remoteDroppedPeers[peer]={ip:4},this.emit("dropped",peer))}),message.dropped6&&compact2string.multi6(message.dropped6).forEach(peer=>{delete this._remoteAddedPeers[peer],peer in this._remoteDroppedPeers||(this._remoteDroppedPeers[peer]={ip:6},this.emit("dropped",peer))})}catch(err){}}_decodeFlags(flags){return{prefersEncryption:!!(flags&FLAGS.prefersEncryption),isSender:!!(flags&FLAGS.isSender),supportsUtp:!!(flags&FLAGS.supportsUtp),supportsUtHolepunch:!!(flags&FLAGS.supportsUtHolepunch),isReachable:!!(flags&FLAGS.isReachable)}}_encodeFlags(flags){return Object.keys(flags).reduce((acc,cur)=>!0===flags[cur]?acc|FLAGS[cur]:acc,0)}_sendMessage(){const localAdded=Object.keys(this._localAddedPeers).slice(0,PEX_MAX_PEERS),localDropped=Object.keys(this._localDroppedPeers).slice(0,PEX_MAX_PEERS),_isIPv4=(peers,addr)=>4===peers[addr].ip,_isIPv6=(peers,addr)=>6===peers[addr].ip,_flags=(peers,addr)=>peers[addr].flags,added=string2compact(localAdded.filter(k=>_isIPv4(this._localAddedPeers,k))),added6=string2compact(localAdded.filter(k=>_isIPv6(this._localAddedPeers,k))),dropped=string2compact(localDropped.filter(k=>_isIPv4(this._localDroppedPeers,k))),dropped6=string2compact(localDropped.filter(k=>_isIPv6(this._localDroppedPeers,k))),addedFlags=Buffer.from(localAdded.filter(k=>_isIPv4(this._localAddedPeers,k)).map(k=>_flags(this._localAddedPeers,k))),added6Flags=Buffer.from(localAdded.filter(k=>_isIPv6(this._localAddedPeers,k)).map(k=>_flags(this._localAddedPeers,k)));localAdded.forEach(peer=>delete this._localAddedPeers[peer]),localDropped.forEach(peer=>delete this._localDroppedPeers[peer]),this._wire.extended("ut_pex",{added:added,"added.f":addedFlags,dropped:dropped,added6:added6,"added6.f":added6Flags,dropped6:dropped6})}}return utPex.prototype.name="ut_pex",utPex}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:47,buffer:101,compact2string:112,events:156,string2compact:320}],335:[function(require,module,exports){(function(global){(function(){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);else config("traceDeprecation")?console.trace(msg):console.warn(msg);warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===(val+"").toLowerCase()}module.exports=deprecate}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],336:[function(require,module,exports){arguments[4][34][0].apply(exports,arguments)},{dup:34}],337:[function(require,module,exports){"use strict";function uncurryThis(f){return f.call.bind(f)}function checkBoxedPrimitive(value,prototypeValueOf){if("object"!=typeof value)return!1;try{return prototypeValueOf(value),!0}catch(e){return!1}}function isPromise(input){return"undefined"!=typeof Promise&&input instanceof Promise||null!==input&&"object"==typeof input&&"function"==typeof input.then&&"function"==typeof input.catch}function isArrayBufferView(value){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(value):isTypedArray(value)||isDataView(value)}function isUint8Array(value){return"Uint8Array"===whichTypedArray(value)}function isUint8ClampedArray(value){return"Uint8ClampedArray"===whichTypedArray(value)}function isUint16Array(value){return"Uint16Array"===whichTypedArray(value)}function isUint32Array(value){return"Uint32Array"===whichTypedArray(value)}function isInt8Array(value){return"Int8Array"===whichTypedArray(value)}function isInt16Array(value){return"Int16Array"===whichTypedArray(value)}function isInt32Array(value){return"Int32Array"===whichTypedArray(value)}function isFloat32Array(value){return"Float32Array"===whichTypedArray(value)}function isFloat64Array(value){return"Float64Array"===whichTypedArray(value)}function isBigInt64Array(value){return"BigInt64Array"===whichTypedArray(value)}function isBigUint64Array(value){return"BigUint64Array"===whichTypedArray(value)}function isMapToString(value){return"[object Map]"===ObjectToString(value)}function isMap(value){return"undefined"!=typeof Map&&(isMapToString.working?isMapToString(value):value instanceof Map)}function isSetToString(value){return"[object Set]"===ObjectToString(value)}function isSet(value){return"undefined"!=typeof Set&&(isSetToString.working?isSetToString(value):value instanceof Set)}function isWeakMapToString(value){return"[object WeakMap]"===ObjectToString(value)}function isWeakMap(value){return"undefined"!=typeof WeakMap&&(isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap)}function isWeakSetToString(value){return"[object WeakSet]"===ObjectToString(value)}function isWeakSet(value){return isWeakSetToString(value)}function isArrayBufferToString(value){return"[object ArrayBuffer]"===ObjectToString(value)}function isArrayBuffer(value){return"undefined"!=typeof ArrayBuffer&&(isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer)}function isDataViewToString(value){return"[object DataView]"===ObjectToString(value)}function isDataView(value){return"undefined"!=typeof DataView&&(isDataViewToString.working?isDataViewToString(value):value instanceof DataView)}function isSharedArrayBufferToString(value){return"[object SharedArrayBuffer]"===ObjectToString(value)}function isSharedArrayBuffer(value){return"undefined"!=typeof SharedArrayBufferCopy&&("undefined"==typeof isSharedArrayBufferToString.working&&(isSharedArrayBufferToString.working=isSharedArrayBufferToString(new SharedArrayBufferCopy)),isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBufferCopy)}function isAsyncFunction(value){return"[object AsyncFunction]"===ObjectToString(value)}function isMapIterator(value){return"[object Map Iterator]"===ObjectToString(value)}function isSetIterator(value){return"[object Set Iterator]"===ObjectToString(value)}function isGeneratorObject(value){return"[object Generator]"===ObjectToString(value)}function isWebAssemblyCompiledModule(value){return"[object WebAssembly.Module]"===ObjectToString(value)}function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}function isBoxedPrimitive(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)}function isAnyArrayBuffer(value){return"undefined"!=typeof Uint8Array&&(isArrayBuffer(value)||isSharedArrayBuffer(value))}var isArgumentsObject=require("is-arguments"),isGeneratorFunction=require("is-generator-function"),whichTypedArray=require("which-typed-array"),isTypedArray=require("is-typed-array"),BigIntSupported="undefined"!=typeof BigInt,SymbolSupported="undefined"!=typeof Symbol,ObjectToString=uncurryThis(Object.prototype.toString),numberValue=uncurryThis(Number.prototype.valueOf),stringValue=uncurryThis(_Stringprototype.valueOf),booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported)var bigIntValue=uncurryThis(BigInt.prototype.valueOf);if(SymbolSupported)var symbolValue=uncurryThis(Symbol.prototype.valueOf);exports.isArgumentsObject=isArgumentsObject,exports.isGeneratorFunction=isGeneratorFunction,exports.isTypedArray=isTypedArray,exports.isPromise=isPromise,exports.isArrayBufferView=isArrayBufferView,exports.isUint8Array=isUint8Array,exports.isUint8ClampedArray=isUint8ClampedArray,exports.isUint16Array=isUint16Array,exports.isUint32Array=isUint32Array,exports.isInt8Array=isInt8Array,exports.isInt16Array=isInt16Array,exports.isInt32Array=isInt32Array,exports.isFloat32Array=isFloat32Array,exports.isFloat64Array=isFloat64Array,exports.isBigInt64Array=isBigInt64Array,exports.isBigUint64Array=isBigUint64Array,isMapToString.working="undefined"!=typeof Map&&isMapToString(new Map),exports.isMap=isMap,isSetToString.working="undefined"!=typeof Set&&isSetToString(new Set),exports.isSet=isSet,isWeakMapToString.working="undefined"!=typeof WeakMap&&isWeakMapToString(new WeakMap),exports.isWeakMap=isWeakMap,isWeakSetToString.working="undefined"!=typeof WeakSet&&isWeakSetToString(new WeakSet),exports.isWeakSet=isWeakSet,isArrayBufferToString.working="undefined"!=typeof ArrayBuffer&&isArrayBufferToString(new ArrayBuffer),exports.isArrayBuffer=isArrayBuffer,isDataViewToString.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1)),exports.isDataView=isDataView;var SharedArrayBufferCopy="undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer;exports.isSharedArrayBuffer=isSharedArrayBuffer,exports.isAsyncFunction=isAsyncFunction,exports.isMapIterator=isMapIterator,exports.isSetIterator=isSetIterator,exports.isGeneratorObject=isGeneratorObject,exports.isWebAssemblyCompiledModule=isWebAssemblyCompiledModule,exports.isNumberObject=isNumberObject,exports.isStringObject=isStringObject,exports.isBooleanObject=isBooleanObject,exports.isBigIntObject=isBigIntObject,exports.isSymbolObject=isSymbolObject,exports.isBoxedPrimitive=isBoxedPrimitive,exports.isAnyArrayBuffer=isAnyArrayBuffer,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(method){Object.defineProperty(exports,method,{enumerable:!1,value:function(){throw new Error(method+" is not supported in userland")}})})},{"is-arguments":192,"is-generator-function":196,"is-typed-array":197,"which-typed-array":341}],338:[function(require,module,exports){(function(process){(function(){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return 3<=arguments.length&&(ctx.depth=arguments[2]),4<=arguments.length&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"\x1B["+inspect.colors[style][0]+"m"+str+"\x1B["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(0<=keys.indexOf("message")||0<=keys.indexOf("description")))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,"\"")+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;ictx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason,reason=newReason}return cb(reason)}function callbackify(original){function callbackified(){for(var args=[],i=0;i=len)return x;switch(x){case"%s":return args[i++]+"";case"%d":return+args[i++];case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x;}}),x=args[i];i{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*MIN_FRAGMENT_DURATION)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}const MIN_FRAGMENT_DURATION=1;module.exports=MP4Remuxer}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":50,buffer:101,events:156,"mp4-box-encoding":224,"mp4-stream":227,"range-slice-stream":265}],340:[function(require,module,exports){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":339,mediasource:212,pump:254}],341:[function(require,module,exports){(function(global){(function(){"use strict";var forEach=require("for-each"),availableTypedArrays=require("available-typed-arrays"),callBound=require("call-bind/callBound"),$toString=callBound("Object.prototype.toString"),hasToStringTag=require("has-tostringtag/shams")(),g="undefined"==typeof globalThis?global:globalThis,typedArrays=availableTypedArrays(),$slice=callBound("String.prototype.slice"),toStrTags={},gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor"),getPrototypeOf=Object.getPrototypeOf;hasToStringTag&&gOPD&&getPrototypeOf&&forEach(typedArrays,function(typedArray){if("function"==typeof g[typedArray]){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr),descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}}});var tryTypedArrays=function tryAllTypedArrays(value){var foundName=!1;return forEach(toStrTags,function(getter,typedArray){if(!foundName)try{var name=getter.call(value);name===typedArray&&(foundName=name)}catch(e){}}),foundName},isTypedArray=require("is-typed-array");module.exports=function whichTypedArray(value){return!!isTypedArray(value)&&(hasToStringTag&&Symbol.toStringTag in value?tryTypedArrays(value):$slice($toString(value),8,-1))}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"available-typed-arrays":36,"call-bind/callBound":104,"es-abstract/helpers/getOwnPropertyDescriptor":154,"for-each":162,"has-tostringtag/shams":170,"is-typed-array":197}],342:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const EventEmitter=require("events"),path=require("path"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debugFactory=require("debug"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),randombytes=require("randombytes"),sha1=require("simple-sha1"),throughput=require("throughput"),{ThrottleGroup}=require("speed-limiter"),ConnPool=require("./lib/conn-pool.js"),Torrent=require("./lib/torrent.js"),{version:VERSION}=require("./package.json"),debug=debugFactory("webtorrent"),VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4),VERSION_PREFIX=`-WW${VERSION_STR}-`;class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(VERSION_PREFIX+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=WebTorrent.UTP_SUPPORT&&!1!==opts.utp,this._downloadLimit=_Mathmax("number"==typeof opts.downloadLimit?opts.downloadLimit:-1,-1),this._uploadLimit=_Mathmax("number"==typeof opts.uploadLimit?opts.uploadLimit:-1,-1),this.serviceWorker=null,this.workerKeepAliveInterval=null,this.workerPortCount=0,!0===opts.secure&&require("./lib/peer").enableSecure(),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new ThrottleGroup({rate:_Mathmax(this._downloadLimit,0),enabled:0<=this._downloadLimit}),up:new ThrottleGroup({rate:_Mathmax(this._uploadLimit,0),enabled:0<=this._uploadLimit})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):queueMicrotask(()=>{this._onListening()}),this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?console.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):queueMicrotask(ready)}loadWorker(controller,cb=()=>{}){if(!(controller instanceof ServiceWorker))throw new Error("Invalid worker registration");if("activated"!==controller.state)throw new Error("Worker isn't activated");const keepAliveTime=2e4;this.serviceWorker=controller,navigator.serviceWorker.addEventListener("message",event=>{const{data}=event;if(!data.type||"webtorrent"===!data.type||!data.url)return null;let[infoHash,...filePath]=data.url.slice(data.url.indexOf(data.scope+"webtorrent/")+11+data.scope.length).split("/");if(filePath=decodeURI(filePath.join("/")),!infoHash||!filePath)return null;const[port]=event.ports,file=this.get(infoHash)&&this.get(infoHash).files.find(file=>file.path===filePath);if(!file)return null;const[response,stream,raw]=file._serve(data),asyncIterator=stream&&stream[Symbol.asyncIterator](),cleanup=()=>{port.onmessage=null,stream&&stream.destroy(),raw&&raw.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};port.onmessage=async msg=>{if(msg.data){let chunk;try{chunk=(await asyncIterator.next()).value}catch(e){}port.postMessage(chunk),chunk||cleanup(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval(()=>fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/keepalive/`),keepAliveTime))}else cleanup()},this.workerPortCount++,port.postMessage(response)}),fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/cancel/`).then(res=>{res.body.cancel()}),cb(null,this.serviceWorker)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`)),void ontorrent(t)},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const onTorrent=torrent=>{const tasks=[cb=>isFilePath||opts.preloadedStore?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))},_onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,onTorrent);let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{!opts.preloadedStore&&isReadable(item)?concat(item,(err,buf)=>err?cb(err):void(buf.name=item.name,cb(null,buf))):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?(console.warn("A torrent with the same id is already being seeded"),torrent._destroy(),"function"==typeof onseed&&onseed(existingTorrent)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb),this.dht&&this.dht._tables.remove(torrent.infoHash))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._downloadLimit=rate,0>this._downloadLimit?this.throttleGroups.down.setEnabled(!1):void(this.throttleGroups.down.setEnabled(!0),this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._uploadLimit=rate,0>this._uploadLimit?this.throttleGroups.up.setEnabled(!1):void(this.throttleGroups.up.setEnabled(!0),this.throttleGroups.up.setRate(this._uploadLimit)))}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_getByHash(infoHashHash){for(const torrent of this.torrents)if(torrent.infoHashHash||(torrent.infoHashHash=sha1.sync(Buffer.from("72657132"+torrent.infoHash,"hex"))),infoHashHash===torrent.infoHashHash)return torrent;return null}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.UTP_SUPPORT=ConnPool.UTP_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("buffer").Buffer)},{"./lib/conn-pool.js":1,"./lib/peer":4,"./lib/torrent.js":7,"./package.json":344,"bittorrent-dht/client":52,buffer:101,"create-torrent":120,debug:122,events:156,"load-ip-set":66,"parse-torrent":237,path:238,"queue-microtask":259,randombytes:262,"run-parallel":287,"simple-concat":300,"simple-peer":302,"simple-sha1":303,"speed-limiter":306,throughput:324}]},{},[345])(345)}); \ No newline at end of file + */"use strict";function rangeParser(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;isize-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;icurrent.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=rangeParser},{}],265:[function(require,module,exports){const{Writable,PassThrough}=require("readable-stream");class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;!0;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}module.exports=RangeSliceStream},{"readable-stream":281}],266:[function(require,module,exports){"use strict";function isInteger(n){return parseInt(n,10)===n}function createRC4(N){function identityPermutation(){for(var s=Array(N),i=0;in?_StringfromCharCode(48+n):_StringfromCharCode(97+n-10)}function fromHex(c){return parseInt(c,16)}var RC4=createRC4(256);RC4.prototype.randomByte=RC4.prototype.randomNative;var RC4small=createRC4(16);RC4small.prototype.randomByte=function(){var a=this.randomNative(),b=this.randomNative();return 16*a+b};var ordA=97,ord0=48;RC4small.prototype.currentStateString=function(){var state=this.currentState(),i=toHex(state.i),j=toHex(state.j),res=i+j+state.s.map(toHex).join("");return res},RC4small.prototype.setStateString=function(stateString){if(!stateString.match(/^[0-9a-f]{18}$/))throw new TypeError("RC4small stateString should be 18 hex character string");var i=fromHex(stateString[0]),j=fromHex(stateString[1]),s=stateString.split("").slice(2).map(fromHex);this.setState({i:i,j:j,s:s})},RC4.RC4small=RC4small,module.exports=RC4},{}],267:[function(require,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],268:[function(require,module,exports){(function(process){(function(){"use strict";function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:101,util:66}],275:[function(require,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)}function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require("_process"))},{_process:246}],276:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function onlegacyfinish(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function onfinish(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function onend(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function onerror(err){callback.call(stream,err)},onclose=function onclose(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function onrequest(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":267}],277:[function(require,module,exports){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],278:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}function pipeline(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":267}],280:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:156}],281:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":268,"./lib/_stream_passthrough.js":269,"./lib/_stream_readable.js":270,"./lib/_stream_transform.js":271,"./lib/_stream_writable.js":272,"./lib/internal/streams/end-of-stream.js":276,"./lib/internal/streams/pipeline.js":278}],282:[function(require,module,exports){function RecordSet(){this.list=[],this.map=new Map}function RecordStore(){this.records=new Map,this.size=0}function RecordCache(opts){if(!(this instanceof RecordCache))return new RecordCache(opts);if(opts||(opts={}),this.maxSize=opts.maxSize||1/0,this.maxAge=opts.maxAge||0,this._onstale=opts.onStale||opts.onstale||null,this._fresh=new RecordStore,this._stale=new RecordStore,this._interval=null,this._gced=!1,this.maxAge&&this.maxAge<1/0){var tick=_Mathceil(2/3*this.maxAge);this._interval=setInterval(this._gcAuto.bind(this),tick),this._interval.unref&&this._interval.unref()}}function toString(record){return b4a.isBuffer(record)?b4a.toString(record,"hex"):record}function swap(list,a,b){var tmp=list[a];tmp.index=b,list[b].index=a,list[a]=list[b],list[b]=tmp}const b4a=require("b4a");var EMPTY=[];module.exports=RecordCache,RecordSet.prototype.add=function(record,value){var k=toString(record),r=this.map.get(k);return!r&&(r={index:this.list.length,record:value||record},this.list.push(r),this.map.set(k,r),!0)},RecordSet.prototype.remove=function(record){var k=toString(record),r=this.map.get(k);return!!r&&(swap(this.list,r.index,this.list.length-1),this.list.pop(),this.map.delete(k),!0)},RecordStore.prototype.add=function(name,record,value){var r=this.records.get(name);return r||(r=new RecordSet,this.records.set(name,r)),!!r.add(record,value)&&(this.size++,!0)},RecordStore.prototype.remove=function(name,record,value){var r=this.records.get(name);return!!r&&!!r.remove(record,value)&&(this.size--,r.map.size||this.records.delete(name),!0)},RecordStore.prototype.get=function(name){var r=this.records.get(name);return r?r.list:EMPTY},Object.defineProperty(RecordCache.prototype,"size",{get:function(){return this._fresh.size+this._stale.size}}),RecordCache.prototype.add=function(name,record,value){this._stale.remove(name,record,value),this._fresh.add(name,record,value)&&this._fresh.size>this.maxSize&&this._gc()},RecordCache.prototype.remove=function(name,record,value){this._fresh.remove(name,record,value),this._stale.remove(name,record,value)},RecordCache.prototype.get=function(name,n){var a=this._fresh.get(name),b=this._stale.get(name),aLen=a.length,bLen=b.length,len=aLen+bLen;(n>len||!n)&&(n=len);for(var result=Array(n),i=0,j;i{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)}function append(file,rootElem,opts,cb){function getElem(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)}function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,getElem,opts,done)}function renderMedia(file,getElem,opts,cb){function renderMediaSource(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),elem.src=url)))}function onLoadStart(){if(elem.removeEventListener("loadstart",onLoadStart),opts.autoplay){const playPromise=elem.play();"undefined"!=typeof playPromise&&playPromise.catch(fatalError)}}function onLoadedMetadata(){elem.removeEventListener("loadedmetadata",onLoadedMetadata),cb(null,elem)}function renderImage(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function tryRenderIframe(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?renderMediaSource():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?renderImage():IFRAME_EXTS.includes(extname)?renderIframe():tryRenderIframe()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=render,exports.append=append,exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_AUDIO_EXTS=[".m4a",".m4b",".m4p",".mp3"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,MEDIASOURCE_AUDIO_EXTS),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":284,debug:122,"is-ascii":193,mediasource:212,path:238,"stream-to-blob-url":316,videostream:340}],284:[function(require,module,exports){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],285:[function(require,module,exports){"use strict";function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^c^d)+m+k,s)+e}function fn2(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&c|~b&d)+m+k,s)+e}function fn3(a,b,c,d,e,m,k,s){return 0|rotl(0|a+((b|~c)^d)+m+k,s)+e}function fn4(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&d|c&~d)+m+k,s)+e}function fn5(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^(c|~d))+m+k,s)+e}var Buffer=require("buffer").Buffer,inherits=require("inherits"),HashBase=require("hash-base"),ARRAY16=Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;16>j;++j)words[j]=this._block.readInt32LE(4*j);for(var al=0|this._a,bl=0|this._b,cl=0|this._c,dl=0|this._d,el=0|this._e,ar=0|this._a,br=0|this._b,cr=0|this._c,dr=0|this._d,er=0|this._e,i=0;80>i;i+=1){var tl,tr;16>i?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):32>i?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):48>i?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):64>i?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=0|this._b+cl+dr;this._b=0|this._c+dl+er,this._c=0|this._d+el+ar,this._d=0|this._e+al+br,this._e=0|this._a+bl+cr,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,56=tasks.length||err?done(err):tasks[current](each)}var current=0,results=[],isSync=!0;0 */module.exports=runSeries}).call(this)}).call(this,require("_process"))},{_process:246}],289:[function(require,module,exports){(function webpackUniversalModuleDefinition(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?exports.Rusha=factory():root.Rusha=factory()})("undefined"==typeof self?this:self,function(){return function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=3)}([function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var RushaCore=__webpack_require__(5),_require=__webpack_require__(1),toHex=_require.toHex,ceilHeapSize=_require.ceilHeapSize,conv=__webpack_require__(6),padlen=function(len){for(len+=9;0>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function _write(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function _coreCall(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function rawDigest(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function digest(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function digestFromString(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function digestFromBuffer(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function digestFromArrayBuffer(str){return this.digest(str)},Rusha.prototype.resetState=function resetState(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function append(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$851=0|H$843[x$846+324>>2],y2$853=0|H$843[x$846+328>>2],y3$855=0|H$843[x$846+332>>2],y4$857=0|H$843[x$846+336>>2],i$847=0;(0|i$847)<(0|k$845);i$847=0|i$847+64){for(z0$850=y0$849,z1$852=y1$851,z2$854=y2$853,z3$856=y3$855,z4$858=y4$857,j$848=0;64>(0|j$848);j$848=0|j$848+4)t1$860=0|H$843[i$847+j$848>>2],t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[k$845+j$848>>2]=t1$860;for(j$848=0|k$845+64;(0|j$848)<(0|k$845+80);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+80;(0|j$848)<(0|k$845+160);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)+1859775393),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+160;(0|j$848)<(0|k$845+240);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|y1$851&y3$855|y2$853&y3$855))+(0|(0|t1$860+y4$857)-1894007588),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+240;(0|j$848)<(0|k$845+320);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)-899497514),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;y0$849=0|y0$849+z0$850,y1$851=0|y1$851+z1$852,y2$853=0|y2$853+z2$854,y3$855=0|y3$855+z3$856,y4$857=0|y4$857+z4$858}H$843[x$846+320>>2]=y0$849,H$843[x$846+324>>2]=y1$851,H$843[x$846+328>>2]=y2$853,H$843[x$846+332>>2]=y3$855,H$843[x$846+336>>2]=y4$857}var H$843=new stdlib$840.Int32Array(heap$842);return{hash:hash$844}}},function(module,exports){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:101}],291:[function(require,module,exports){(function(process){(function(){"use strict";var buffer=require("buffer"),Buffer=buffer.Buffer,safer={},key;for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw new TypeError("The \"value\" argument must not be of type number. Received type "+typeof value);if(value&&"undefined"==typeof value.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("The \"size\" argument must be of type number. Received type "+typeof size);if(0>size||2147483648<=size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"");var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}).call(this)}).call(this,require("_process"))},{_process:246,buffer:101}],292:[function(require,module,exports){function Hash(blockSize,finalSize){this._block=Buffer.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}var Buffer=require("safe-buffer").Buffer;Hash.prototype.update=function(data,enc){"string"==typeof data&&(enc=enc||"utf8",data=Buffer.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=8*this._len;if(4294967295>=bits)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(4294967295&bits)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")},module.exports=Hash},{"safe-buffer":290}],293:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha"),exports.sha1=require("./sha1"),exports.sha224=require("./sha224"),exports.sha256=require("./sha256"),exports.sha384=require("./sha384"),exports.sha512=require("./sha512")},{"./sha":294,"./sha1":295,"./sha224":296,"./sha256":297,"./sha384":298,"./sha512":299}],294:[function(require,module,exports){function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha},{"./hash":292,inherits:190,"safe-buffer":290}],295:[function(require,module,exports){function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha1.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha1.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha1},{"./hash":292,inherits:190,"safe-buffer":290}],296:[function(require,module,exports){function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}var inherits=require("inherits"),Sha256=require("./sha256"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(64);inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224},{"./hash":292,"./sha256":297,inherits:190,"safe-buffer":290}],297:[function(require,module,exports){function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=Array(64);inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},Sha256.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;64>i;++i)W[i]=0|gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16];for(var j=0;64>j;++j){var T1=0|h+sigma1(e)+ch(e,f,g)+K[j]+W[j],T2=0|sigma0(a)+maj(a,b,c);h=g,g=f,f=e,e=0|d+T1,d=c,c=b,b=a,a=0|T1+T2}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e,this._f=0|f+this._f,this._g=0|g+this._g,this._h=0|h+this._h},Sha256.prototype._hash=function(){var H=Buffer.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256},{"./hash":292,inherits:190,"safe-buffer":290}],298:[function(require,module,exports){function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}var inherits=require("inherits"),SHA512=require("./sha512"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(160);inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(48);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384},{"./hash":292,"./sha512":299,inherits:190,"safe-buffer":290}],299:[function(require,module,exports){function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=Array(160);inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Sha512.prototype._update=function(M){for(var W=this._w,ah=0|this._ah,bh=0|this._bh,ch=0|this._ch,dh=0|this._dh,eh=0|this._eh,fh=0|this._fh,gh=0|this._gh,hh=0|this._hh,al=0|this._al,bl=0|this._bl,cl=0|this._cl,dl=0|this._dl,el=0|this._el,fl=0|this._fl,gl=0|this._gl,hl=0|this._hl,i=0;32>i;i+=2)W[i]=M.readInt32BE(4*i),W[i+1]=M.readInt32BE(4*i+4);for(;160>i;i+=2){var xh=W[i-30],xl=W[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W[i-4],xl=W[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W[i-14],Wi7l=W[i-14+1],Wi16h=W[i-32],Wi16l=W[i-32+1],Wil=0|gamma0l+Wi7l,Wih=0|gamma0+Wi7h+getCarry(Wil,gamma0l);Wil=0|Wil+gamma1l,Wih=0|Wih+gamma1+getCarry(Wil,gamma1l),Wil=0|Wil+Wi16l,Wih=0|Wih+Wi16h+getCarry(Wil,Wi16l),W[i]=Wih,W[i+1]=Wil}for(var j=0;160>j;j+=2){Wih=W[j],Wil=W[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=0|hl+sigma1l,t1h=0|hh+sigma1h+getCarry(t1l,hl);t1l=0|t1l+chl,t1h=0|t1h+chh+getCarry(t1l,chl),t1l=0|t1l+Kil,t1h=0|t1h+Kih+getCarry(t1l,Kil),t1l=0|t1l+Wil,t1h=0|t1h+Wih+getCarry(t1l,Wil);var t2l=0|sigma0l+majl,t2h=0|sigma0h+majh+getCarry(t2l,sigma0l);hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=0|dl+t1l,eh=0|dh+t1h+getCarry(el,dl),dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=0|t1l+t2l,ah=0|t1h+t2h+getCarry(al,t1l)}this._al=0|this._al+al,this._bl=0|this._bl+bl,this._cl=0|this._cl+cl,this._dl=0|this._dl+dl,this._el=0|this._el+el,this._fl=0|this._fl+fl,this._gl=0|this._gl+gl,this._hl=0|this._hl+hl,this._ah=0|this._ah+ah+getCarry(this._al,al),this._bh=0|this._bh+bh+getCarry(this._bl,bl),this._ch=0|this._ch+ch+getCarry(this._cl,cl),this._dh=0|this._dh+dh+getCarry(this._dl,dl),this._eh=0|this._eh+eh+getCarry(this._el,el),this._fh=0|this._fh+fh+getCarry(this._fl,fl),this._gh=0|this._gh+gh+getCarry(this._gl,gl),this._hh=0|this._hh+hh+getCarry(this._hl,hl)},Sha512.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(64);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512},{"./hash":292,inherits:190,"safe-buffer":290}],300:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],301:[function(require,module,exports){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const originalHost=opts.hostname,protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location){opts.url=res.headers.location,delete opts.headers.host,res.resume();const redirectHost=url.parse(opts.url).hostname;return null!==redirectHost&&redirectHost!==originalHost&&(delete opts.headers.cookie,delete opts.headers.authorization),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb)}const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"decompress-response":66,http:312,https:187,once:231,querystring:258,"simple-concat":300,url:331}],302:[function(require,module,exports){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5000,CHANNEL_CLOSING_TIMEOUT=5000;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(err=>{this.destroy(errCode(err,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(chunk)}}addTransceiver(kind,init){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}}addStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}}addTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=event=>{const err=event.error instanceof Error?event.error:new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`);this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}},onSuccess=()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(offer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}},onSuccess=()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(answer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:101,debug:122,"err-code":153,"get-browser-rtc":166,"queue-microtask":259,randombytes:262,"readable-stream":281}],303:[function(require,module,exports){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function succeed(result){cb(hex(new Uint8Array(result)))},function fail(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function onRushaWorkerSha1(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){const l=s.length,array=new Uint8Array(l);for(let i=0;i>>4).toString(16)),chars.push((15&bite).toString(16))}return chars.join("")}const Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{};let subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":304,rusha:289}],304:[function(require,module,exports){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function onRushaMessage(e){const taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}const Rusha=require("rusha");let worker,nextTaskId,cbs;module.exports=sha1},{rusha:289}],305:[function(require,module,exports){(function(Buffer){(function(){/*! simple-websocket. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,null,{...opts,encoding:void 0}):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",opts.socket&&this.connected?queueMicrotask(()=>this._handleOpen()):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=event=>this._handleMessage(event),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=err=>this._handleError(err),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}this._ws=null,err&&this.emit("error",err),this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_handleOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(_){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,debug:122,"queue-microtask":259,randombytes:262,"readable-stream":281,ws:66}],306:[function(require,module,exports){const Throttle=require("./lib/throttle"),ThrottleGroup=require("./lib/throttle-group");module.exports={Throttle,ThrottleGroup}},{"./lib/throttle":308,"./lib/throttle-group":307}],307:[function(require,module,exports){const{TokenBucket}=require("limiter"),Throttle=require("./throttle");class ThrottleGroup{constructor(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");this.throttles=[],this.setEnabled(opts.enabled),this.setRate(opts.rate,opts.chunksize)}getEnabled(){return this._enabled}getRate(){return this.bucket.tokensPerInterval}getChunksize(){return this.chunksize}setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val;for(const throttle of this.throttles)throttle.setEnabled(val)}setRate(rate,chunksize=null){if(!_NumberisInteger(rate)||0>rate)throw new Error("Rate must be an integer bigger than zero");if(rate=parseInt(rate),chunksize&&("number"!=typeof chunksize||0>=chunksize))throw new Error("Chunksize must be bigger than zero");if(chunksize=chunksize||_Mathmax(parseInt(rate/10),1),chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.bucket||(this.bucket=new TokenBucket(rate,rate,"second",null)),this.bucket.bucketSize=rate,this.bucket.tokensPerInterval=rate,this.chunksize=chunksize}setChunksize(chunksize){if(!_NumberisInteger(chunksize)||0>=chunksize)throw new Error("Chunk size must be an integer bigger than zero");const rate=this.getRate();if(chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.chunksize=chunksize}throttle(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");const newThrottle=new Throttle({...opts,group:this});return newThrottle}destroy(){for(const throttle of this.throttles)throttle.destroy();this.throttles=[]}_addThrottle(throttle){if(!(throttle instanceof Throttle))throw new Error("Throttle must be an instance of Throttle");this.throttles.push(throttle)}_removeThrottle(throttle){const index=this.throttles.indexOf(throttle);-1{function isDone(err){if(self._emitter.removeListener("disabled",isDone),self._emitter.removeListener("destroyed",isDone),!done)return done=!0,err?reject(err):void resolve()}let done=!1;const self=this;this._emitter.once("disabled",isDone),this._emitter.once("destroyed",isDone),this._group.bucket.removeTokens(amount,isDone)})}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(chunk,done){if(!this._areBothEnabled())return done(null,chunk);let pos=0,chunksize=this._group.getChunksize(),slice=chunk.slice(pos,pos+chunksize);for(;0setTimeout(resolve,time))}module.exports={wait}},{}],310:[function(require,module,exports){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){resetTimers(!0),self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&(resetTimers(!0),self.push(null))}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":313,_process:246,buffer:101,inherits:190,"readable-stream":281}],316:[function(require,module,exports){async function getBlobURL(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url}module.exports=getBlobURL;const getBlob=require("stream-to-blob")},{"stream-to-blob":317}],317:[function(require,module,exports){function streamToBlob(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=streamToBlob},{}],318:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function getBuffer(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,once:231}],319:[function(require,module,exports){function afterDrain(){this.stream._duplexState|=READ_PIPE_DRAINED,0==(this.stream._duplexState&READ_ACTIVE_AND_SYNC)?this.updateNextTick():this.drain()}function afterFinal(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROY_STATUS)&&(stream._duplexState|=WRITE_DONE,stream.emit("finish")),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),stream._duplexState&=WRITE_NOT_ACTIVE,this.update()}function afterDestroy(err){const stream=this.stream;err||this.error===STREAM_DESTROYED||(err=this.error),err&&stream.emit("error",err),stream._duplexState|=DESTROYED,stream.emit("close");const rs=stream._readableState,ws=stream._writableState;null!==rs&&null!==rs.pipeline&&rs.pipeline.done(stream,err),null!==ws&&null!==ws.pipeline&&ws.pipeline.done(stream,err)}function afterWrite(err){const stream=this.stream;err&&stream.destroy(err),stream._duplexState&=WRITE_NOT_ACTIVE,(stream._duplexState&WRITE_DRAIN_STATUS)===WRITE_UNDRAINED&&(stream._duplexState&=WRITE_DRAINED,(stream._duplexState&WRITE_EMIT_DRAIN)===WRITE_EMIT_DRAIN&&stream.emit("drain")),0==(stream._duplexState&WRITE_SYNC)&&this.update()}function afterRead(err){err&&this.stream.destroy(err),this.stream._duplexState&=READ_NOT_ACTIVE,0==(this.stream._duplexState&READ_SYNC)&&this.update()}function updateReadNT(){this.stream._duplexState&=READ_NOT_NEXT_TICK,this.update()}function updateWriteNT(){this.stream._duplexState&=WRITE_NOT_NEXT_TICK,this.update()}function afterOpen(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROYING)&&(0==(stream._duplexState&READ_PRIMARY_STATUS)&&(stream._duplexState|=READ_PRIMARY),0==(stream._duplexState&WRITE_PRIMARY_STATUS)&&(stream._duplexState|=WRITE_PRIMARY),stream.emit("open")),stream._duplexState&=NOT_ACTIVE,null!==stream._writableState&&stream._writableState.update(),null!==stream._readableState&&stream._readableState.update()}function afterTransform(err,data){data!==void 0&&null!==data&&this.push(data),this._writableState.afterWrite(err)}function transformAfterFlush(err,data){const cb=this._transformState.afterFinal;return err?cb(err):void(null!==data&&data!==void 0&&this.push(data),this.push(null),cb(null))}function pipelinePromise(...streams){return new Promise((resolve,reject)=>pipeline(...streams,err=>err?reject(err):void resolve()))}function pipeline(stream,...streams){function errorHandle(s,rd,wr,onerror){function onclose(){return rd&&s._readableState&&!s._readableState.ended?onerror(PREMATURE_CLOSE):wr&&s._writableState&&!s._writableState.ended?onerror(PREMATURE_CLOSE):void 0}s.on("error",onerror),s.on("close",onclose)}function onerror(err){if(err&&!error){error=err;for(const s of all)s.destroy(err)}}const all=Array.isArray(stream)?[...stream,...streams]:[stream,...streams],done=all.length&&"function"==typeof all[all.length-1]?all.pop():null;if(2>all.length)throw new Error("Pipeline requires at least 2 streams");let src=all[0],dest=null,error=null;for(let i=1;i{fin=!0}),dest.on("error",err=>{error=error||err}),dest.on("close",()=>done(error||(fin?null:PREMATURE_CLOSE)))}return dest}function isStream(stream){return!!stream._readableState||!!stream._writableState}function isStreamx(stream){return"number"==typeof stream._duplexState&&isStream(stream)}function isReadStreamx(stream){return isStreamx(stream)&&stream.readable}function isTypedArray(data){return"object"==typeof data&&null!==data&&"number"==typeof data.byteLength}function defaultByteLength(data){return isTypedArray(data)?data.byteLength:1024}function noop(){}function abort(){this.destroy(new Error("Stream aborted."))}const{EventEmitter}=require("events"),STREAM_DESTROYED=new Error("Stream was destroyed"),PREMATURE_CLOSE=new Error("Premature close"),queueTick=require("queue-tick"),FIFO=require("fast-fifo"),MAX=33554431,OPENING=1,DESTROYING=2,DESTROYED=4,NOT_OPENING=MAX^OPENING,READ_ACTIVE=8,READ_PRIMARY=16,READ_SYNC=32,READ_QUEUED=64,READ_RESUMED=128,READ_PIPE_DRAINED=256,READ_ENDING=512,READ_EMIT_DATA=1024,READ_EMIT_READABLE=2048,READ_EMITTED_READABLE=4096,READ_DONE=8192,READ_NEXT_TICK=16392,READ_NEEDS_PUSH=32768,READ_NOT_ACTIVE=MAX^READ_ACTIVE,READ_NON_PRIMARY=MAX^READ_PRIMARY,READ_NON_PRIMARY_AND_PUSHED=MAX^(READ_PRIMARY|READ_NEEDS_PUSH),READ_NOT_SYNC=MAX^READ_SYNC,READ_PUSHED=MAX^READ_NEEDS_PUSH,READ_PAUSED=MAX^READ_RESUMED,READ_NOT_QUEUED=MAX^(READ_QUEUED|READ_EMITTED_READABLE),READ_NOT_ENDING=MAX^READ_ENDING,READ_PIPE_NOT_DRAINED=MAX^(READ_RESUMED|READ_PIPE_DRAINED),READ_NOT_NEXT_TICK=MAX^READ_NEXT_TICK,WRITE_ACTIVE=65536,WRITE_PRIMARY=131072,WRITE_SYNC=262144,WRITE_QUEUED=524288,WRITE_UNDRAINED=1048576,WRITE_DONE=2097152,WRITE_EMIT_DRAIN=4194304,WRITE_NEXT_TICK=8454144,WRITE_FINISHING=16777216,WRITE_NOT_ACTIVE=MAX^WRITE_ACTIVE,WRITE_NOT_SYNC=MAX^WRITE_SYNC,WRITE_NON_PRIMARY=MAX^WRITE_PRIMARY,WRITE_NOT_FINISHING=MAX^WRITE_FINISHING,WRITE_DRAINED=MAX^WRITE_UNDRAINED,WRITE_NOT_QUEUED=MAX^WRITE_QUEUED,WRITE_NOT_NEXT_TICK=MAX^WRITE_NEXT_TICK,ACTIVE=READ_ACTIVE|WRITE_ACTIVE,NOT_ACTIVE=MAX^ACTIVE,DONE=READ_DONE|WRITE_DONE,DESTROY_STATUS=DESTROYING|DESTROYED,OPEN_STATUS=DESTROY_STATUS|OPENING,AUTO_DESTROY=DESTROY_STATUS|DONE,NON_PRIMARY=WRITE_NON_PRIMARY&READ_NON_PRIMARY,TICKING=(WRITE_NEXT_TICK|READ_NEXT_TICK)&NOT_ACTIVE,ACTIVE_OR_TICKING=ACTIVE|TICKING,IS_OPENING=OPEN_STATUS|TICKING,READ_PRIMARY_STATUS=OPEN_STATUS|READ_ENDING|READ_DONE,READ_STATUS=OPEN_STATUS|READ_DONE|READ_QUEUED,READ_FLOWING=READ_RESUMED|READ_PIPE_DRAINED,READ_ACTIVE_AND_SYNC=READ_ACTIVE|READ_SYNC,READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH=READ_ACTIVE|READ_SYNC|READ_NEEDS_PUSH,READ_PRIMARY_AND_ACTIVE=READ_PRIMARY|READ_ACTIVE,READ_ENDING_STATUS=OPEN_STATUS|READ_ENDING|READ_QUEUED,READ_EMIT_READABLE_AND_QUEUED=READ_EMIT_READABLE|READ_QUEUED,READ_READABLE_STATUS=OPEN_STATUS|READ_EMIT_READABLE|READ_QUEUED|READ_EMITTED_READABLE,SHOULD_NOT_READ=OPEN_STATUS|READ_ACTIVE|READ_ENDING|READ_DONE|READ_NEEDS_PUSH,READ_BACKPRESSURE_STATUS=DESTROY_STATUS|READ_ENDING|READ_DONE,WRITE_PRIMARY_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_DONE,WRITE_QUEUED_AND_UNDRAINED=WRITE_QUEUED|WRITE_UNDRAINED,WRITE_QUEUED_AND_ACTIVE=WRITE_QUEUED|WRITE_ACTIVE,WRITE_DRAIN_STATUS=WRITE_QUEUED|WRITE_UNDRAINED|OPEN_STATUS|WRITE_ACTIVE,WRITE_STATUS=OPEN_STATUS|WRITE_ACTIVE|WRITE_QUEUED,WRITE_PRIMARY_AND_ACTIVE=WRITE_PRIMARY|WRITE_ACTIVE,WRITE_ACTIVE_AND_SYNC=WRITE_ACTIVE|WRITE_SYNC,WRITE_FINISHING_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_QUEUED_AND_ACTIVE|WRITE_DONE,WRITE_BACKPRESSURE_STATUS=WRITE_UNDRAINED|DESTROY_STATUS|WRITE_FINISHING|WRITE_DONE,asyncIterator=Symbol.asyncIterator||Symbol("asyncIterator");class WritableState{constructor(stream,{highWaterMark=16384,map=null,mapWritable,byteLength,byteLengthWritable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthWritable||byteLength||defaultByteLength,this.map=mapWritable||map,this.afterWrite=afterWrite.bind(this),this.afterUpdateNextTick=updateWriteNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&WRITE_DONE)}push(data){return(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),this.buffered=rs._readableState.highWaterMark}static isPaused(rs){return 0==(rs._duplexState&READ_RESUMED)}[asyncIterator](){function onreadable(){null!==promiseResolve&&ondata(stream.read())}function onclose(){null!==promiseResolve&&ondata(null)}function ondata(data){null===promiseReject||(error?promiseReject(error):null===data&&0==(stream._duplexState&READ_DONE)?promiseReject(STREAM_DESTROYED):promiseResolve({value:data,done:null==data}),promiseReject=promiseResolve=null)}function destroy(err){return stream.destroy(err),new Promise((resolve,reject)=>stream._duplexState&DESTROYED?resolve({value:void 0,done:!0}):void stream.once("close",function(){err?reject(err):resolve({value:void 0,done:!0})}))}const stream=this;let error=null,promiseResolve=null,promiseReject=null;return this.on("error",err=>{error=err}),this.on("readable",onreadable),this.on("close",onclose),{[asyncIterator](){return this},next(){return new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject;const data=stream.read();null===data?0!=(stream._duplexState&DESTROYED)&&ondata(null):ondata(data)})},return(){return destroy(null)},throw(err){return destroy(err)}}}}class Writable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|READ_DONE,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}static isBackpressured(ws){return 0!=(ws._duplexState&WRITE_BACKPRESSURE_STATUS)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Duplex extends Readable{constructor(opts){super(opts),this._duplexState=OPENING,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Transform extends Duplex{constructor(opts){super(opts),this._transformState=new TransformState(this),opts&&(opts.transform&&(this._transform=opts.transform),opts.flush&&(this._flush=opts.flush))}_write(data,cb){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=data:this._transform(data,this._transformState.afterTransform)}_read(cb){if(null!==this._transformState.data){const data=this._transformState.data;this._transformState.data=null,cb(null),this._transform(data,this._transformState.afterTransform)}else cb(null)}_transform(data,cb){cb(null,data)}_flush(cb){cb(null)}_final(cb){this._transformState.afterFinal=cb,this._flush(transformAfterFlush.bind(this))}}class PassThrough extends Transform{}module.exports={pipeline,pipelinePromise,isStream,isStreamx,Stream,Writable,Readable,Duplex,Transform,PassThrough}},{events:156,"fast-fifo":160,"queue-tick":260}],320:[function(require,module,exports){(function(Buffer){(function(){const addrToIPPort=require("addr-to-ip-port"),ipaddr=require("ipaddr.js");module.exports=addrs=>("string"==typeof addrs&&(addrs=[addrs]),Buffer.concat(addrs.map(addr=>{const s=addrToIPPort(addr);if(2!==s.length)throw new Error("invalid address format, expecting: 10.10.10.5:128");const ip=ipaddr.parse(s[0]),ipBuf=Buffer.from(ip.toByteArray()),port=s[1],portBuf=Buffer.allocUnsafe(2);return portBuf.writeUInt16BE(port,0),Buffer.concat([ipBuf,portBuf])}))),module.exports.multi=module.exports,module.exports.multi6=module.exports}).call(this)}).call(this,require("buffer").Buffer)},{"addr-to-ip-port":16,buffer:101,"ipaddr.js":191}],321:[function(require,module,exports){arguments[4][96][0].apply(exports,arguments)},{dup:96,"safe-buffer":290}],322:[function(require,module,exports){var base32=require("./thirty-two");exports.encode=base32.encode,exports.decode=base32.decode},{"./thirty-two":323}],323:[function(require,module,exports){(function(Buffer){(function(){"use strict";function quintetCount(buff){var quintets=_Mathfloor(buff.length/5);return 0==buff.length%5?quintets:quintets+1}var charTable="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",byteTable=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];exports.encode=function(plain){Buffer.isBuffer(plain)||(plain=new Buffer(plain));for(var i=0,j=0,shiftIndex=0,digit=0,encoded=new Buffer(8*quintetCount(plain));i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],324:[function(require,module,exports){function getTick(start){return 65535&(+Date.now()-start)/timeDiff}const maxTick=65535,resolution=10,timeDiff=1e3/resolution;module.exports=function(seconds){const start=+Date.now(),size=resolution*(seconds||5),buffer=[0];let pointer=1,last=getTick(start)-1&maxTick;return function(delta){const tick=getTick(start);let dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);const top=buffer[pointer-1],btm=buffer.lengtharguments.length)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function onNextTick(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":246,timers:325}],326:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=(peer,infoHash)=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}module.exports=Discovery}).call(this)}).call(this,require("_process"))},{_process:246,"bittorrent-dht/client":52,"bittorrent-lsd":53,"bittorrent-tracker/client":55,debug:122,events:156,"run-parallel":287}],328:[function(require,module,exports){(function(Buffer){(function(){/*! torrent-piece. MIT License. WebTorrent LLC */const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),MAX_METADATA_SIZE=1E7,BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash,peerId,extensions){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||MAX_METADATA_SIZE=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf,totalSize){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0 */const EventEmitter=require("events").EventEmitter,compact2string=require("compact2string"),string2compact=require("string2compact"),bencode=require("bencode"),PEX_INTERVAL=65e3,PEX_MAX_PEERS=50,PEX_MIN_ALLOWED_INTERVAL=6e4,FLAGS={prefersEncryption:1,isSender:2,supportsUtp:4,supportsUtHolepunch:8,isReachable:16};module.exports=()=>{class utPex extends EventEmitter{constructor(wire){super(),this._wire=wire,this._intervalId=null,this._lastMessageTimestamp=0,this.reset()}start(){clearInterval(this._intervalId),this._intervalId=setInterval(()=>this._sendMessage(),PEX_INTERVAL),this._intervalId.unref&&this._intervalId.unref()}stop(){clearInterval(this._intervalId),this._intervalId=null}reset(){this._remoteAddedPeers={},this._remoteDroppedPeers={},this._localAddedPeers={},this._localDroppedPeers={},this.stop()}addPeer(peer,flags={}){this._addPeer(peer,this._encodeFlags(flags),4)}addPeer6(peer,flags={}){this._addPeer(peer,this._encodeFlags(flags),6)}_addPeer(peer,flags,version){!peer.includes(":")||peer in this._remoteAddedPeers||(peer in this._localDroppedPeers&&delete this._localDroppedPeers[peer],this._localAddedPeers[peer]={ip:version,flags:flags})}dropPeer(peer){this._dropPeer(peer,4)}dropPeer6(peer){this._dropPeer(peer,6)}_dropPeer(peer,version){!peer.includes(":")||peer in this._remoteDroppedPeers||(peer in this._localAddedPeers&&delete this._localAddedPeers[peer],this._localDroppedPeers[peer]={ip:version})}onExtendedHandshake(handshake){if(!handshake.m||!handshake.m.ut_pex)return this.emit("warning",new Error("Peer does not support ut_pex"))}onMessage(buf){const currentMessageTimestamp=Date.now();if(currentMessageTimestamp-this._lastMessageTimestamp{if(delete this._remoteDroppedPeers[peer],!(peer in this._remoteAddedPeers)){const flags=message["added.f"][idx];this._remoteAddedPeers[peer]={ip:4,flags:flags},this.emit("peer",peer,this._decodeFlags(flags))}}),message.added6&&compact2string.multi6(message.added6).forEach((peer,idx)=>{if(delete this._remoteDroppedPeers[peer],!(peer in this._remoteAddedPeers)){const flags=message["added6.f"][idx];this._remoteAddedPeers[peer]={ip:6,flags:flags},this.emit("peer",peer,this._decodeFlags(flags))}}),message.dropped&&compact2string.multi(message.dropped).forEach(peer=>{delete this._remoteAddedPeers[peer],peer in this._remoteDroppedPeers||(this._remoteDroppedPeers[peer]={ip:4},this.emit("dropped",peer))}),message.dropped6&&compact2string.multi6(message.dropped6).forEach(peer=>{delete this._remoteAddedPeers[peer],peer in this._remoteDroppedPeers||(this._remoteDroppedPeers[peer]={ip:6},this.emit("dropped",peer))})}catch(err){}}_decodeFlags(flags){return{prefersEncryption:!!(flags&FLAGS.prefersEncryption),isSender:!!(flags&FLAGS.isSender),supportsUtp:!!(flags&FLAGS.supportsUtp),supportsUtHolepunch:!!(flags&FLAGS.supportsUtHolepunch),isReachable:!!(flags&FLAGS.isReachable)}}_encodeFlags(flags){return Object.keys(flags).reduce((acc,cur)=>!0===flags[cur]?acc|FLAGS[cur]:acc,0)}_sendMessage(){const localAdded=Object.keys(this._localAddedPeers).slice(0,PEX_MAX_PEERS),localDropped=Object.keys(this._localDroppedPeers).slice(0,PEX_MAX_PEERS),_isIPv4=(peers,addr)=>4===peers[addr].ip,_isIPv6=(peers,addr)=>6===peers[addr].ip,_flags=(peers,addr)=>peers[addr].flags,added=string2compact(localAdded.filter(k=>_isIPv4(this._localAddedPeers,k))),added6=string2compact(localAdded.filter(k=>_isIPv6(this._localAddedPeers,k))),dropped=string2compact(localDropped.filter(k=>_isIPv4(this._localDroppedPeers,k))),dropped6=string2compact(localDropped.filter(k=>_isIPv6(this._localDroppedPeers,k))),addedFlags=Buffer.from(localAdded.filter(k=>_isIPv4(this._localAddedPeers,k)).map(k=>_flags(this._localAddedPeers,k))),added6Flags=Buffer.from(localAdded.filter(k=>_isIPv6(this._localAddedPeers,k)).map(k=>_flags(this._localAddedPeers,k)));localAdded.forEach(peer=>delete this._localAddedPeers[peer]),localDropped.forEach(peer=>delete this._localDroppedPeers[peer]),this._wire.extended("ut_pex",{added:added,"added.f":addedFlags,dropped:dropped,added6:added6,"added6.f":added6Flags,dropped6:dropped6})}}return utPex.prototype.name="ut_pex",utPex}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:47,buffer:101,compact2string:112,events:156,string2compact:320}],335:[function(require,module,exports){(function(global){(function(){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);else config("traceDeprecation")?console.trace(msg):console.warn(msg);warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===(val+"").toLowerCase()}module.exports=deprecate}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],336:[function(require,module,exports){arguments[4][34][0].apply(exports,arguments)},{dup:34}],337:[function(require,module,exports){"use strict";function uncurryThis(f){return f.call.bind(f)}function checkBoxedPrimitive(value,prototypeValueOf){if("object"!=typeof value)return!1;try{return prototypeValueOf(value),!0}catch(e){return!1}}function isPromise(input){return"undefined"!=typeof Promise&&input instanceof Promise||null!==input&&"object"==typeof input&&"function"==typeof input.then&&"function"==typeof input.catch}function isArrayBufferView(value){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(value):isTypedArray(value)||isDataView(value)}function isUint8Array(value){return"Uint8Array"===whichTypedArray(value)}function isUint8ClampedArray(value){return"Uint8ClampedArray"===whichTypedArray(value)}function isUint16Array(value){return"Uint16Array"===whichTypedArray(value)}function isUint32Array(value){return"Uint32Array"===whichTypedArray(value)}function isInt8Array(value){return"Int8Array"===whichTypedArray(value)}function isInt16Array(value){return"Int16Array"===whichTypedArray(value)}function isInt32Array(value){return"Int32Array"===whichTypedArray(value)}function isFloat32Array(value){return"Float32Array"===whichTypedArray(value)}function isFloat64Array(value){return"Float64Array"===whichTypedArray(value)}function isBigInt64Array(value){return"BigInt64Array"===whichTypedArray(value)}function isBigUint64Array(value){return"BigUint64Array"===whichTypedArray(value)}function isMapToString(value){return"[object Map]"===ObjectToString(value)}function isMap(value){return"undefined"!=typeof Map&&(isMapToString.working?isMapToString(value):value instanceof Map)}function isSetToString(value){return"[object Set]"===ObjectToString(value)}function isSet(value){return"undefined"!=typeof Set&&(isSetToString.working?isSetToString(value):value instanceof Set)}function isWeakMapToString(value){return"[object WeakMap]"===ObjectToString(value)}function isWeakMap(value){return"undefined"!=typeof WeakMap&&(isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap)}function isWeakSetToString(value){return"[object WeakSet]"===ObjectToString(value)}function isWeakSet(value){return isWeakSetToString(value)}function isArrayBufferToString(value){return"[object ArrayBuffer]"===ObjectToString(value)}function isArrayBuffer(value){return"undefined"!=typeof ArrayBuffer&&(isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer)}function isDataViewToString(value){return"[object DataView]"===ObjectToString(value)}function isDataView(value){return"undefined"!=typeof DataView&&(isDataViewToString.working?isDataViewToString(value):value instanceof DataView)}function isSharedArrayBufferToString(value){return"[object SharedArrayBuffer]"===ObjectToString(value)}function isSharedArrayBuffer(value){return"undefined"!=typeof SharedArrayBufferCopy&&("undefined"==typeof isSharedArrayBufferToString.working&&(isSharedArrayBufferToString.working=isSharedArrayBufferToString(new SharedArrayBufferCopy)),isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBufferCopy)}function isAsyncFunction(value){return"[object AsyncFunction]"===ObjectToString(value)}function isMapIterator(value){return"[object Map Iterator]"===ObjectToString(value)}function isSetIterator(value){return"[object Set Iterator]"===ObjectToString(value)}function isGeneratorObject(value){return"[object Generator]"===ObjectToString(value)}function isWebAssemblyCompiledModule(value){return"[object WebAssembly.Module]"===ObjectToString(value)}function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}function isBoxedPrimitive(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)}function isAnyArrayBuffer(value){return"undefined"!=typeof Uint8Array&&(isArrayBuffer(value)||isSharedArrayBuffer(value))}var isArgumentsObject=require("is-arguments"),isGeneratorFunction=require("is-generator-function"),whichTypedArray=require("which-typed-array"),isTypedArray=require("is-typed-array"),BigIntSupported="undefined"!=typeof BigInt,SymbolSupported="undefined"!=typeof Symbol,ObjectToString=uncurryThis(Object.prototype.toString),numberValue=uncurryThis(Number.prototype.valueOf),stringValue=uncurryThis(_Stringprototype.valueOf),booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported)var bigIntValue=uncurryThis(BigInt.prototype.valueOf);if(SymbolSupported)var symbolValue=uncurryThis(Symbol.prototype.valueOf);exports.isArgumentsObject=isArgumentsObject,exports.isGeneratorFunction=isGeneratorFunction,exports.isTypedArray=isTypedArray,exports.isPromise=isPromise,exports.isArrayBufferView=isArrayBufferView,exports.isUint8Array=isUint8Array,exports.isUint8ClampedArray=isUint8ClampedArray,exports.isUint16Array=isUint16Array,exports.isUint32Array=isUint32Array,exports.isInt8Array=isInt8Array,exports.isInt16Array=isInt16Array,exports.isInt32Array=isInt32Array,exports.isFloat32Array=isFloat32Array,exports.isFloat64Array=isFloat64Array,exports.isBigInt64Array=isBigInt64Array,exports.isBigUint64Array=isBigUint64Array,isMapToString.working="undefined"!=typeof Map&&isMapToString(new Map),exports.isMap=isMap,isSetToString.working="undefined"!=typeof Set&&isSetToString(new Set),exports.isSet=isSet,isWeakMapToString.working="undefined"!=typeof WeakMap&&isWeakMapToString(new WeakMap),exports.isWeakMap=isWeakMap,isWeakSetToString.working="undefined"!=typeof WeakSet&&isWeakSetToString(new WeakSet),exports.isWeakSet=isWeakSet,isArrayBufferToString.working="undefined"!=typeof ArrayBuffer&&isArrayBufferToString(new ArrayBuffer),exports.isArrayBuffer=isArrayBuffer,isDataViewToString.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1)),exports.isDataView=isDataView;var SharedArrayBufferCopy="undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer;exports.isSharedArrayBuffer=isSharedArrayBuffer,exports.isAsyncFunction=isAsyncFunction,exports.isMapIterator=isMapIterator,exports.isSetIterator=isSetIterator,exports.isGeneratorObject=isGeneratorObject,exports.isWebAssemblyCompiledModule=isWebAssemblyCompiledModule,exports.isNumberObject=isNumberObject,exports.isStringObject=isStringObject,exports.isBooleanObject=isBooleanObject,exports.isBigIntObject=isBigIntObject,exports.isSymbolObject=isSymbolObject,exports.isBoxedPrimitive=isBoxedPrimitive,exports.isAnyArrayBuffer=isAnyArrayBuffer,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(method){Object.defineProperty(exports,method,{enumerable:!1,value:function(){throw new Error(method+" is not supported in userland")}})})},{"is-arguments":192,"is-generator-function":196,"is-typed-array":197,"which-typed-array":341}],338:[function(require,module,exports){(function(process){(function(){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return 3<=arguments.length&&(ctx.depth=arguments[2]),4<=arguments.length&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"\x1B["+inspect.colors[style][0]+"m"+str+"\x1B["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(0<=keys.indexOf("message")||0<=keys.indexOf("description")))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(0>recurseTimes)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,"\"")+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;ictx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1n?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason,reason=newReason}return cb(reason)}function callbackify(original){function callbackified(){for(var args=[],i=0;i=len)return x;switch(x){case"%s":return args[i++]+"";case"%d":return+args[i++];case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x;}}),x=args[i];i{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*MIN_FRAGMENT_DURATION)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}const MIN_FRAGMENT_DURATION=1;module.exports=MP4Remuxer}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":50,buffer:101,events:156,"mp4-box-encoding":224,"mp4-stream":227,"range-slice-stream":265}],340:[function(require,module,exports){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":339,mediasource:212,pump:254}],341:[function(require,module,exports){(function(global){(function(){"use strict";var forEach=require("for-each"),availableTypedArrays=require("available-typed-arrays"),callBound=require("call-bind/callBound"),$toString=callBound("Object.prototype.toString"),hasToStringTag=require("has-tostringtag/shams")(),g="undefined"==typeof globalThis?global:globalThis,typedArrays=availableTypedArrays(),$slice=callBound("String.prototype.slice"),toStrTags={},gOPD=require("es-abstract/helpers/getOwnPropertyDescriptor"),getPrototypeOf=Object.getPrototypeOf;hasToStringTag&&gOPD&&getPrototypeOf&&forEach(typedArrays,function(typedArray){if("function"==typeof g[typedArray]){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr),descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}}});var tryTypedArrays=function tryAllTypedArrays(value){var foundName=!1;return forEach(toStrTags,function(getter,typedArray){if(!foundName)try{var name=getter.call(value);name===typedArray&&(foundName=name)}catch(e){}}),foundName},isTypedArray=require("is-typed-array");module.exports=function whichTypedArray(value){return!!isTypedArray(value)&&(hasToStringTag&&Symbol.toStringTag in value?tryTypedArrays(value):$slice($toString(value),8,-1))}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"available-typed-arrays":36,"call-bind/callBound":104,"es-abstract/helpers/getOwnPropertyDescriptor":154,"for-each":162,"has-tostringtag/shams":170,"is-typed-array":197}],342:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const EventEmitter=require("events"),path=require("path"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debugFactory=require("debug"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),randombytes=require("randombytes"),sha1=require("simple-sha1"),throughput=require("throughput"),{ThrottleGroup}=require("speed-limiter"),ConnPool=require("./lib/conn-pool.js"),Torrent=require("./lib/torrent.js"),{version:VERSION}=require("./package.json"),debug=debugFactory("webtorrent"),VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4),VERSION_PREFIX=`-WW${VERSION_STR}-`;class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(VERSION_PREFIX+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=WebTorrent.UTP_SUPPORT&&!1!==opts.utp,this._downloadLimit=_Mathmax("number"==typeof opts.downloadLimit?opts.downloadLimit:-1,-1),this._uploadLimit=_Mathmax("number"==typeof opts.uploadLimit?opts.uploadLimit:-1,-1),this.serviceWorker=null,this.workerKeepAliveInterval=null,this.workerPortCount=0,!0===opts.secure&&require("./lib/peer").enableSecure(),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new ThrottleGroup({rate:_Mathmax(this._downloadLimit,0),enabled:0<=this._downloadLimit}),up:new ThrottleGroup({rate:_Mathmax(this._uploadLimit,0),enabled:0<=this._uploadLimit})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):queueMicrotask(()=>{this._onListening()}),this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?console.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):queueMicrotask(ready)}loadWorker(controller,cb=()=>{}){if(!(controller instanceof ServiceWorker))throw new Error("Invalid worker registration");if("activated"!==controller.state)throw new Error("Worker isn't activated");const keepAliveTime=2e4;this.serviceWorker=controller,navigator.serviceWorker.addEventListener("message",event=>{const{data}=event;if(!data.type||"webtorrent"===!data.type||!data.url)return null;let[infoHash,...filePath]=data.url.slice(data.url.indexOf(data.scope+"webtorrent/")+11+data.scope.length).split("/");if(filePath=decodeURI(filePath.join("/")),!infoHash||!filePath)return null;const[port]=event.ports,file=this.get(infoHash)&&this.get(infoHash).files.find(file=>file.path===filePath);if(!file)return null;const[response,stream,raw]=file._serve(data),asyncIterator=stream&&stream[Symbol.asyncIterator](),cleanup=()=>{port.onmessage=null,stream&&stream.destroy(),raw&&raw.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};port.onmessage=async msg=>{if(msg.data){let chunk;try{chunk=(await asyncIterator.next()).value}catch(e){}port.postMessage(chunk),chunk||cleanup(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval(()=>fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/keepalive/`),keepAliveTime))}else cleanup()},this.workerPortCount++,port.postMessage(response)}),fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/cancel/`).then(res=>{res.body.cancel()}),cb(null,this.serviceWorker)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`)),void ontorrent(t)},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const onTorrent=torrent=>{const tasks=[cb=>isFilePath||opts.preloadedStore?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))},_onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,onTorrent);let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{!opts.preloadedStore&&isReadable(item)?concat(item,(err,buf)=>err?cb(err):void(buf.name=item.name,cb(null,buf))):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?(console.warn("A torrent with the same id is already being seeded"),torrent._destroy(),"function"==typeof onseed&&onseed(existingTorrent)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb),this.dht&&this.dht._tables.remove(torrent.infoHash))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._downloadLimit=rate,0>this._downloadLimit?this.throttleGroups.down.setEnabled(!1):void(this.throttleGroups.down.setEnabled(!0),this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._uploadLimit=rate,0>this._uploadLimit?this.throttleGroups.up.setEnabled(!1):void(this.throttleGroups.up.setEnabled(!0),this.throttleGroups.up.setRate(this._uploadLimit)))}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_getByHash(infoHashHash){for(const torrent of this.torrents)if(torrent.infoHashHash||(torrent.infoHashHash=sha1.sync(Buffer.from("72657132"+torrent.infoHash,"hex"))),infoHashHash===torrent.infoHashHash)return torrent;return null}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.UTP_SUPPORT=ConnPool.UTP_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("buffer").Buffer)},{"./lib/conn-pool.js":1,"./lib/peer":4,"./lib/torrent.js":7,"./package.json":344,"bittorrent-dht/client":52,buffer:101,"create-torrent":120,debug:122,events:156,"load-ip-set":66,"parse-torrent":237,path:238,"queue-microtask":259,randombytes:262,"run-parallel":287,"simple-concat":300,"simple-peer":302,"simple-sha1":303,"speed-limiter":306,throughput:324}]},{},[345])(345)}); \ No newline at end of file diff --git a/webtorrent.min.js b/webtorrent.min.js index e398dd5..8575d3f 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -13,4 +13,4 @@ * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015-2016 Douglas Christopher Wilson * MIT Licensed - */"use strict";function rangeParser(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;isize-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;icurrent.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=rangeParser},{}],211:[function(require,module,exports){const{Writable,PassThrough}=require("readable-stream");class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;!0;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}module.exports=RangeSliceStream},{"readable-stream":227}],212:[function(require,module,exports){"use strict";function isInteger(n){return parseInt(n,10)===n}function createRC4(N){function identityPermutation(){for(var s=Array(N),i=0;in?_StringfromCharCode(48+n):_StringfromCharCode(97+n-10)}function fromHex(c){return parseInt(c,16)}var RC4=createRC4(256);RC4.prototype.randomByte=RC4.prototype.randomNative;var RC4small=createRC4(16);RC4small.prototype.randomByte=function(){var a=this.randomNative(),b=this.randomNative();return 16*a+b};var ordA=97,ord0=48;RC4small.prototype.currentStateString=function(){var state=this.currentState(),i=toHex(state.i),j=toHex(state.j),res=i+j+state.s.map(toHex).join("");return res},RC4small.prototype.setStateString=function(stateString){if(!stateString.match(/^[0-9a-f]{18}$/))throw new TypeError("RC4small stateString should be 18 hex character string");var i=fromHex(stateString[0]),j=fromHex(stateString[1]),s=stateString.split("").slice(2).map(fromHex);this.setState({i:i,j:j,s:s})},RC4.RC4small=RC4small,module.exports=RC4},{}],213:[function(require,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],214:[function(require,module,exports){(function(process){(function(){"use strict";function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:75,util:41}],221:[function(require,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)}function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require("_process"))},{_process:192}],222:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function onlegacyfinish(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function onfinish(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function onend(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function onerror(err){callback.call(stream,err)},onclose=function onclose(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function onrequest(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":213}],223:[function(require,module,exports){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],224:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}function pipeline(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":213}],226:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:122}],227:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":214,"./lib/_stream_passthrough.js":215,"./lib/_stream_readable.js":216,"./lib/_stream_transform.js":217,"./lib/_stream_writable.js":218,"./lib/internal/streams/end-of-stream.js":222,"./lib/internal/streams/pipeline.js":224}],228:[function(require,module,exports){function render(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)}function append(file,rootElem,opts,cb){function getElem(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)}function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,getElem,opts,done)}function renderMedia(file,getElem,opts,cb){function renderMediaSource(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),elem.src=url)))}function onLoadStart(){if(elem.removeEventListener("loadstart",onLoadStart),opts.autoplay){const playPromise=elem.play();"undefined"!=typeof playPromise&&playPromise.catch(fatalError)}}function onLoadedMetadata(){elem.removeEventListener("loadedmetadata",onLoadedMetadata),cb(null,elem)}function renderImage(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function tryRenderIframe(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?renderMediaSource():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?renderImage():IFRAME_EXTS.includes(extname)?renderIframe():tryRenderIframe()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=render,exports.append=append,exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_AUDIO_EXTS=[".m4a",".m4b",".m4p",".mp3"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,MEDIASOURCE_AUDIO_EXTS),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":229,debug:90,"is-ascii":147,mediasource:159,path:184,"stream-to-blob-url":260,videostream:278}],229:[function(require,module,exports){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],230:[function(require,module,exports){"use strict";function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^c^d)+m+k,s)+e}function fn2(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&c|~b&d)+m+k,s)+e}function fn3(a,b,c,d,e,m,k,s){return 0|rotl(0|a+((b|~c)^d)+m+k,s)+e}function fn4(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&d|c&~d)+m+k,s)+e}function fn5(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^(c|~d))+m+k,s)+e}var Buffer=require("buffer").Buffer,inherits=require("inherits"),HashBase=require("hash-base"),ARRAY16=Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;16>j;++j)words[j]=this._block.readInt32LE(4*j);for(var al=0|this._a,bl=0|this._b,cl=0|this._c,dl=0|this._d,el=0|this._e,ar=0|this._a,br=0|this._b,cr=0|this._c,dr=0|this._d,er=0|this._e,i=0;80>i;i+=1){var tl,tr;16>i?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):32>i?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):48>i?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):64>i?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=0|this._b+cl+dr;this._b=0|this._c+dl+er,this._c=0|this._d+el+ar,this._d=0|this._e+al+br,this._e=0|this._a+bl+cr,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,56>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function _write(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function _coreCall(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function rawDigest(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function digest(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function digestFromString(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function digestFromBuffer(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function digestFromArrayBuffer(str){return this.digest(str)},Rusha.prototype.resetState=function resetState(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function append(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$851=0|H$843[x$846+324>>2],y2$853=0|H$843[x$846+328>>2],y3$855=0|H$843[x$846+332>>2],y4$857=0|H$843[x$846+336>>2],i$847=0;(0|i$847)<(0|k$845);i$847=0|i$847+64){for(z0$850=y0$849,z1$852=y1$851,z2$854=y2$853,z3$856=y3$855,z4$858=y4$857,j$848=0;64>(0|j$848);j$848=0|j$848+4)t1$860=0|H$843[i$847+j$848>>2],t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[k$845+j$848>>2]=t1$860;for(j$848=0|k$845+64;(0|j$848)<(0|k$845+80);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+80;(0|j$848)<(0|k$845+160);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)+1859775393),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+160;(0|j$848)<(0|k$845+240);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|y1$851&y3$855|y2$853&y3$855))+(0|(0|t1$860+y4$857)-1894007588),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+240;(0|j$848)<(0|k$845+320);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)-899497514),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;y0$849=0|y0$849+z0$850,y1$851=0|y1$851+z1$852,y2$853=0|y2$853+z2$854,y3$855=0|y3$855+z3$856,y4$857=0|y4$857+z4$858}H$843[x$846+320>>2]=y0$849,H$843[x$846+324>>2]=y1$851,H$843[x$846+328>>2]=y2$853,H$843[x$846+332>>2]=y3$855,H$843[x$846+336>>2]=y4$857}var H$843=new stdlib$840.Int32Array(heap$842);return{hash:hash$844}}},function(module,exports){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:75}],235:[function(require,module,exports){(function(process){(function(){"use strict";var buffer=require("buffer"),Buffer=buffer.Buffer,safer={},key;for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw new TypeError("The \"value\" argument must not be of type number. Received type "+typeof value);if(value&&"undefined"==typeof value.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("The \"size\" argument must be of type number. Received type "+typeof size);if(0>size||2147483648<=size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"");var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}).call(this)}).call(this,require("_process"))},{_process:192,buffer:75}],236:[function(require,module,exports){function Hash(blockSize,finalSize){this._block=Buffer.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}var Buffer=require("safe-buffer").Buffer;Hash.prototype.update=function(data,enc){"string"==typeof data&&(enc=enc||"utf8",data=Buffer.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=8*this._len;if(4294967295>=bits)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(4294967295&bits)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")},module.exports=Hash},{"safe-buffer":234}],237:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha"),exports.sha1=require("./sha1"),exports.sha224=require("./sha224"),exports.sha256=require("./sha256"),exports.sha384=require("./sha384"),exports.sha512=require("./sha512")},{"./sha":238,"./sha1":239,"./sha224":240,"./sha256":241,"./sha384":242,"./sha512":243}],238:[function(require,module,exports){function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha},{"./hash":236,inherits:146,"safe-buffer":234}],239:[function(require,module,exports){function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha1.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha1.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha1},{"./hash":236,inherits:146,"safe-buffer":234}],240:[function(require,module,exports){function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}var inherits=require("inherits"),Sha256=require("./sha256"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(64);inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224},{"./hash":236,"./sha256":241,inherits:146,"safe-buffer":234}],241:[function(require,module,exports){function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=Array(64);inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},Sha256.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;64>i;++i)W[i]=0|gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16];for(var j=0;64>j;++j){var T1=0|h+sigma1(e)+ch(e,f,g)+K[j]+W[j],T2=0|sigma0(a)+maj(a,b,c);h=g,g=f,f=e,e=0|d+T1,d=c,c=b,b=a,a=0|T1+T2}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e,this._f=0|f+this._f,this._g=0|g+this._g,this._h=0|h+this._h},Sha256.prototype._hash=function(){var H=Buffer.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256},{"./hash":236,inherits:146,"safe-buffer":234}],242:[function(require,module,exports){function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}var inherits=require("inherits"),SHA512=require("./sha512"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(160);inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(48);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384},{"./hash":236,"./sha512":243,inherits:146,"safe-buffer":234}],243:[function(require,module,exports){function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=Array(160);inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Sha512.prototype._update=function(M){for(var W=this._w,ah=0|this._ah,bh=0|this._bh,ch=0|this._ch,dh=0|this._dh,eh=0|this._eh,fh=0|this._fh,gh=0|this._gh,hh=0|this._hh,al=0|this._al,bl=0|this._bl,cl=0|this._cl,dl=0|this._dl,el=0|this._el,fl=0|this._fl,gl=0|this._gl,hl=0|this._hl,i=0;32>i;i+=2)W[i]=M.readInt32BE(4*i),W[i+1]=M.readInt32BE(4*i+4);for(;160>i;i+=2){var xh=W[i-30],xl=W[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W[i-4],xl=W[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W[i-14],Wi7l=W[i-14+1],Wi16h=W[i-32],Wi16l=W[i-32+1],Wil=0|gamma0l+Wi7l,Wih=0|gamma0+Wi7h+getCarry(Wil,gamma0l);Wil=0|Wil+gamma1l,Wih=0|Wih+gamma1+getCarry(Wil,gamma1l),Wil=0|Wil+Wi16l,Wih=0|Wih+Wi16h+getCarry(Wil,Wi16l),W[i]=Wih,W[i+1]=Wil}for(var j=0;160>j;j+=2){Wih=W[j],Wil=W[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=0|hl+sigma1l,t1h=0|hh+sigma1h+getCarry(t1l,hl);t1l=0|t1l+chl,t1h=0|t1h+chh+getCarry(t1l,chl),t1l=0|t1l+Kil,t1h=0|t1h+Kih+getCarry(t1l,Kil),t1l=0|t1l+Wil,t1h=0|t1h+Wih+getCarry(t1l,Wil);var t2l=0|sigma0l+majl,t2h=0|sigma0h+majh+getCarry(t2l,sigma0l);hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=0|dl+t1l,eh=0|dh+t1h+getCarry(el,dl),dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=0|t1l+t2l,ah=0|t1h+t2h+getCarry(al,t1l)}this._al=0|this._al+al,this._bl=0|this._bl+bl,this._cl=0|this._cl+cl,this._dl=0|this._dl+dl,this._el=0|this._el+el,this._fl=0|this._fl+fl,this._gl=0|this._gl+gl,this._hl=0|this._hl+hl,this._ah=0|this._ah+ah+getCarry(this._al,al),this._bh=0|this._bh+bh+getCarry(this._bl,bl),this._ch=0|this._ch+ch+getCarry(this._cl,cl),this._dh=0|this._dh+dh+getCarry(this._dl,dl),this._eh=0|this._eh+eh+getCarry(this._el,el),this._fh=0|this._fh+fh+getCarry(this._fl,fl),this._gh=0|this._gh+gh+getCarry(this._gl,gl),this._hh=0|this._hh+hh+getCarry(this._hl,hl)},Sha512.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(64);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512},{"./hash":236,inherits:146,"safe-buffer":234}],244:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],245:[function(require,module,exports){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const originalHost=opts.hostname,protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location){opts.url=res.headers.location,delete opts.headers.host,res.resume();const redirectHost=url.parse(opts.url).hostname;return null!==redirectHost&&redirectHost!==originalHost&&(delete opts.headers.cookie,delete opts.headers.authorization),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb)}const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"decompress-response":41,http:256,https:143,once:177,querystring:204,"simple-concat":244,url:273}],246:[function(require,module,exports){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5000,CHANNEL_CLOSING_TIMEOUT=5000;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(err=>{this.destroy(errCode(err,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(chunk)}}addTransceiver(kind,init){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}}addStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}}addTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=event=>{const err=event.error instanceof Error?event.error:new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`);this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}},onSuccess=()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(offer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}},onSuccess=()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(answer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:75,debug:90,"err-code":121,"get-browser-rtc":128,"queue-microtask":205,randombytes:208,"readable-stream":227}],247:[function(require,module,exports){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function succeed(result){cb(hex(new Uint8Array(result)))},function fail(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function onRushaWorkerSha1(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){const l=s.length,array=new Uint8Array(l);for(let i=0;i>>4).toString(16)),chars.push((15&bite).toString(16))}return chars.join("")}const Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{};let subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":248,rusha:233}],248:[function(require,module,exports){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function onRushaMessage(e){const taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}const Rusha=require("rusha");let worker,nextTaskId,cbs;module.exports=sha1},{rusha:233}],249:[function(require,module,exports){(function(Buffer){(function(){/*! simple-websocket. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,null,{...opts,encoding:void 0}):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",opts.socket&&this.connected?queueMicrotask(()=>this._handleOpen()):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=event=>this._handleMessage(event),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=err=>this._handleError(err),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}this._ws=null,err&&this.emit("error",err),this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_handleOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(_){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,debug:90,"queue-microtask":205,randombytes:208,"readable-stream":227,ws:41}],250:[function(require,module,exports){const Throttle=require("./lib/throttle"),ThrottleGroup=require("./lib/throttle-group");module.exports={Throttle,ThrottleGroup}},{"./lib/throttle":252,"./lib/throttle-group":251}],251:[function(require,module,exports){var _NumberisInteger=Number.isInteger;const{TokenBucket}=require("limiter"),Throttle=require("./throttle");class ThrottleGroup{constructor(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");this.throttles=[],this.setEnabled(opts.enabled),this.setRate(opts.rate,opts.chunksize)}getEnabled(){return this._enabled}getRate(){return this.bucket.tokensPerInterval}getChunksize(){return this.chunksize}setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val;for(const throttle of this.throttles)throttle.setEnabled(val)}setRate(rate,chunksize=null){if(!_NumberisInteger(rate)||0>rate)throw new Error("Rate must be an integer bigger than zero");if(rate=parseInt(rate),chunksize&&("number"!=typeof chunksize||0>=chunksize))throw new Error("Chunksize must be bigger than zero");if(chunksize=chunksize||_Mathmax(parseInt(rate/10),1),chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.bucket||(this.bucket=new TokenBucket(rate,rate,"second",null)),this.bucket.bucketSize=rate,this.bucket.tokensPerInterval=rate,this.chunksize=chunksize}setChunksize(chunksize){if(!_NumberisInteger(chunksize)||0>=chunksize)throw new Error("Chunk size must be an integer bigger than zero");const rate=this.getRate();if(chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.chunksize=chunksize}throttle(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");const newThrottle=new Throttle({...opts,group:this});return newThrottle}destroy(){for(const throttle of this.throttles)throttle.destroy();this.throttles=[]}_addThrottle(throttle){if(!(throttle instanceof Throttle))throw new Error("Throttle must be an instance of Throttle");this.throttles.push(throttle)}_removeThrottle(throttle){const index=this.throttles.indexOf(throttle);-1{function isDone(err){if(self._emitter.removeListener("disabled",isDone),self._emitter.removeListener("destroyed",isDone),!done)return done=!0,err?reject(err):void resolve()}let done=!1;const self=this;this._emitter.once("disabled",isDone),this._emitter.once("destroyed",isDone),this._group.bucket.removeTokens(amount,isDone)})}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(chunk,done){if(!this._areBothEnabled())return done(null,chunk);let pos=0,chunksize=this._group.getChunksize(),slice=chunk.slice(pos,pos+chunksize);for(;0setTimeout(resolve,time))}module.exports={wait}},{}],254:[function(require,module,exports){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){resetTimers(!0),self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&(resetTimers(!0),self.push(null))}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":257,_process:192,buffer:75,inherits:146,"readable-stream":227}],260:[function(require,module,exports){async function getBlobURL(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url}module.exports=getBlobURL;const getBlob=require("stream-to-blob")},{"stream-to-blob":261}],261:[function(require,module,exports){function streamToBlob(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=streamToBlob},{}],262:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function getBuffer(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,once:177}],263:[function(require,module,exports){function afterDrain(){this.stream._duplexState|=READ_PIPE_DRAINED,0==(this.stream._duplexState&READ_ACTIVE_AND_SYNC)?this.updateNextTick():this.drain()}function afterFinal(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROY_STATUS)&&(stream._duplexState|=WRITE_DONE,stream.emit("finish")),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),stream._duplexState&=WRITE_NOT_ACTIVE,this.update()}function afterDestroy(err){const stream=this.stream;err||this.error===STREAM_DESTROYED||(err=this.error),err&&stream.emit("error",err),stream._duplexState|=DESTROYED,stream.emit("close");const rs=stream._readableState,ws=stream._writableState;null!==rs&&null!==rs.pipeline&&rs.pipeline.done(stream,err),null!==ws&&null!==ws.pipeline&&ws.pipeline.done(stream,err)}function afterWrite(err){const stream=this.stream;err&&stream.destroy(err),stream._duplexState&=WRITE_NOT_ACTIVE,(stream._duplexState&WRITE_DRAIN_STATUS)===WRITE_UNDRAINED&&(stream._duplexState&=WRITE_DRAINED,(stream._duplexState&WRITE_EMIT_DRAIN)===WRITE_EMIT_DRAIN&&stream.emit("drain")),0==(stream._duplexState&WRITE_SYNC)&&this.update()}function afterRead(err){err&&this.stream.destroy(err),this.stream._duplexState&=READ_NOT_ACTIVE,0==(this.stream._duplexState&READ_SYNC)&&this.update()}function updateReadNT(){this.stream._duplexState&=READ_NOT_NEXT_TICK,this.update()}function updateWriteNT(){this.stream._duplexState&=WRITE_NOT_NEXT_TICK,this.update()}function afterOpen(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROYING)&&(0==(stream._duplexState&READ_PRIMARY_STATUS)&&(stream._duplexState|=READ_PRIMARY),0==(stream._duplexState&WRITE_PRIMARY_STATUS)&&(stream._duplexState|=WRITE_PRIMARY),stream.emit("open")),stream._duplexState&=NOT_ACTIVE,null!==stream._writableState&&stream._writableState.update(),null!==stream._readableState&&stream._readableState.update()}function afterTransform(err,data){data!==void 0&&null!==data&&this.push(data),this._writableState.afterWrite(err)}function transformAfterFlush(err,data){const cb=this._transformState.afterFinal;return err?cb(err):void(null!==data&&data!==void 0&&this.push(data),this.push(null),cb(null))}function pipelinePromise(...streams){return new Promise((resolve,reject)=>pipeline(...streams,err=>err?reject(err):void resolve()))}function pipeline(stream,...streams){function errorHandle(s,rd,wr,onerror){function onclose(){return rd&&s._readableState&&!s._readableState.ended?onerror(PREMATURE_CLOSE):wr&&s._writableState&&!s._writableState.ended?onerror(PREMATURE_CLOSE):void 0}s.on("error",onerror),s.on("close",onclose)}function onerror(err){if(err&&!error){error=err;for(const s of all)s.destroy(err)}}const all=Array.isArray(stream)?[...stream,...streams]:[stream,...streams],done=all.length&&"function"==typeof all[all.length-1]?all.pop():null;if(2>all.length)throw new Error("Pipeline requires at least 2 streams");let src=all[0],dest=null,error=null;for(let i=1;i{fin=!0}),dest.on("error",err=>{error=error||err}),dest.on("close",()=>done(error||(fin?null:PREMATURE_CLOSE)))}return dest}function isStream(stream){return!!stream._readableState||!!stream._writableState}function isStreamx(stream){return"number"==typeof stream._duplexState&&isStream(stream)}function isReadStreamx(stream){return isStreamx(stream)&&stream.readable}function isTypedArray(data){return"object"==typeof data&&null!==data&&"number"==typeof data.byteLength}function defaultByteLength(data){return isTypedArray(data)?data.byteLength:1024}function noop(){}function abort(){this.destroy(new Error("Stream aborted."))}const{EventEmitter}=require("events"),STREAM_DESTROYED=new Error("Stream was destroyed"),PREMATURE_CLOSE=new Error("Premature close"),queueTick=require("queue-tick"),FIFO=require("fast-fifo"),MAX=33554431,OPENING=1,DESTROYING=2,DESTROYED=4,NOT_OPENING=MAX^OPENING,READ_ACTIVE=8,READ_PRIMARY=16,READ_SYNC=32,READ_QUEUED=64,READ_RESUMED=128,READ_PIPE_DRAINED=256,READ_ENDING=512,READ_EMIT_DATA=1024,READ_EMIT_READABLE=2048,READ_EMITTED_READABLE=4096,READ_DONE=8192,READ_NEXT_TICK=16392,READ_NEEDS_PUSH=32768,READ_NOT_ACTIVE=MAX^READ_ACTIVE,READ_NON_PRIMARY=MAX^READ_PRIMARY,READ_NON_PRIMARY_AND_PUSHED=MAX^(READ_PRIMARY|READ_NEEDS_PUSH),READ_NOT_SYNC=MAX^READ_SYNC,READ_PUSHED=MAX^READ_NEEDS_PUSH,READ_PAUSED=MAX^READ_RESUMED,READ_NOT_QUEUED=MAX^(READ_QUEUED|READ_EMITTED_READABLE),READ_NOT_ENDING=MAX^READ_ENDING,READ_PIPE_NOT_DRAINED=MAX^(READ_RESUMED|READ_PIPE_DRAINED),READ_NOT_NEXT_TICK=MAX^READ_NEXT_TICK,WRITE_ACTIVE=65536,WRITE_PRIMARY=131072,WRITE_SYNC=262144,WRITE_QUEUED=524288,WRITE_UNDRAINED=1048576,WRITE_DONE=2097152,WRITE_EMIT_DRAIN=4194304,WRITE_NEXT_TICK=8454144,WRITE_FINISHING=16777216,WRITE_NOT_ACTIVE=MAX^WRITE_ACTIVE,WRITE_NOT_SYNC=MAX^WRITE_SYNC,WRITE_NON_PRIMARY=MAX^WRITE_PRIMARY,WRITE_NOT_FINISHING=MAX^WRITE_FINISHING,WRITE_DRAINED=MAX^WRITE_UNDRAINED,WRITE_NOT_QUEUED=MAX^WRITE_QUEUED,WRITE_NOT_NEXT_TICK=MAX^WRITE_NEXT_TICK,ACTIVE=READ_ACTIVE|WRITE_ACTIVE,NOT_ACTIVE=MAX^ACTIVE,DONE=READ_DONE|WRITE_DONE,DESTROY_STATUS=DESTROYING|DESTROYED,OPEN_STATUS=DESTROY_STATUS|OPENING,AUTO_DESTROY=DESTROY_STATUS|DONE,NON_PRIMARY=WRITE_NON_PRIMARY&READ_NON_PRIMARY,TICKING=(WRITE_NEXT_TICK|READ_NEXT_TICK)&NOT_ACTIVE,ACTIVE_OR_TICKING=ACTIVE|TICKING,IS_OPENING=OPEN_STATUS|TICKING,READ_PRIMARY_STATUS=OPEN_STATUS|READ_ENDING|READ_DONE,READ_STATUS=OPEN_STATUS|READ_DONE|READ_QUEUED,READ_FLOWING=READ_RESUMED|READ_PIPE_DRAINED,READ_ACTIVE_AND_SYNC=READ_ACTIVE|READ_SYNC,READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH=READ_ACTIVE|READ_SYNC|READ_NEEDS_PUSH,READ_PRIMARY_AND_ACTIVE=READ_PRIMARY|READ_ACTIVE,READ_ENDING_STATUS=OPEN_STATUS|READ_ENDING|READ_QUEUED,READ_EMIT_READABLE_AND_QUEUED=READ_EMIT_READABLE|READ_QUEUED,READ_READABLE_STATUS=OPEN_STATUS|READ_EMIT_READABLE|READ_QUEUED|READ_EMITTED_READABLE,SHOULD_NOT_READ=OPEN_STATUS|READ_ACTIVE|READ_ENDING|READ_DONE|READ_NEEDS_PUSH,READ_BACKPRESSURE_STATUS=DESTROY_STATUS|READ_ENDING|READ_DONE,WRITE_PRIMARY_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_DONE,WRITE_QUEUED_AND_UNDRAINED=WRITE_QUEUED|WRITE_UNDRAINED,WRITE_QUEUED_AND_ACTIVE=WRITE_QUEUED|WRITE_ACTIVE,WRITE_DRAIN_STATUS=WRITE_QUEUED|WRITE_UNDRAINED|OPEN_STATUS|WRITE_ACTIVE,WRITE_STATUS=OPEN_STATUS|WRITE_ACTIVE|WRITE_QUEUED,WRITE_PRIMARY_AND_ACTIVE=WRITE_PRIMARY|WRITE_ACTIVE,WRITE_ACTIVE_AND_SYNC=WRITE_ACTIVE|WRITE_SYNC,WRITE_FINISHING_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_QUEUED_AND_ACTIVE|WRITE_DONE,WRITE_BACKPRESSURE_STATUS=WRITE_UNDRAINED|DESTROY_STATUS|WRITE_FINISHING|WRITE_DONE,asyncIterator=Symbol.asyncIterator||Symbol("asyncIterator");class WritableState{constructor(stream,{highWaterMark=16384,map=null,mapWritable,byteLength,byteLengthWritable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthWritable||byteLength||defaultByteLength,this.map=mapWritable||map,this.afterWrite=afterWrite.bind(this),this.afterUpdateNextTick=updateWriteNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&WRITE_DONE)}push(data){return(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),this.buffered=rs._readableState.highWaterMark}static isPaused(rs){return 0==(rs._duplexState&READ_RESUMED)}[asyncIterator](){function onreadable(){null!==promiseResolve&&ondata(stream.read())}function onclose(){null!==promiseResolve&&ondata(null)}function ondata(data){null===promiseReject||(error?promiseReject(error):null===data&&0==(stream._duplexState&READ_DONE)?promiseReject(STREAM_DESTROYED):promiseResolve({value:data,done:null==data}),promiseReject=promiseResolve=null)}function destroy(err){return stream.destroy(err),new Promise((resolve,reject)=>stream._duplexState&DESTROYED?resolve({value:void 0,done:!0}):void stream.once("close",function(){err?reject(err):resolve({value:void 0,done:!0})}))}const stream=this;let error=null,promiseResolve=null,promiseReject=null;return this.on("error",err=>{error=err}),this.on("readable",onreadable),this.on("close",onclose),{[asyncIterator](){return this},next(){return new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject;const data=stream.read();null===data?0!=(stream._duplexState&DESTROYED)&&ondata(null):ondata(data)})},return(){return destroy(null)},throw(err){return destroy(err)}}}}class Writable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|READ_DONE,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}static isBackpressured(ws){return 0!=(ws._duplexState&WRITE_BACKPRESSURE_STATUS)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Duplex extends Readable{constructor(opts){super(opts),this._duplexState=OPENING,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Transform extends Duplex{constructor(opts){super(opts),this._transformState=new TransformState(this),opts&&(opts.transform&&(this._transform=opts.transform),opts.flush&&(this._flush=opts.flush))}_write(data,cb){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=data:this._transform(data,this._transformState.afterTransform)}_read(cb){if(null!==this._transformState.data){const data=this._transformState.data;this._transformState.data=null,cb(null),this._transform(data,this._transformState.afterTransform)}else cb(null)}_transform(data,cb){cb(null,data)}_flush(cb){cb(null)}_final(cb){this._transformState.afterFinal=cb,this._flush(transformAfterFlush.bind(this))}}class PassThrough extends Transform{}module.exports={pipeline,pipelinePromise,isStream,isStreamx,Stream,Writable,Readable,Duplex,Transform,PassThrough}},{events:122,"fast-fifo":126,"queue-tick":206}],264:[function(require,module,exports){arguments[4][70][0].apply(exports,arguments)},{dup:70,"safe-buffer":234}],265:[function(require,module,exports){var base32=require("./thirty-two");exports.encode=base32.encode,exports.decode=base32.decode},{"./thirty-two":266}],266:[function(require,module,exports){(function(Buffer){(function(){"use strict";function quintetCount(buff){var quintets=_Mathfloor(buff.length/5);return 0==buff.length%5?quintets:quintets+1}var charTable="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",byteTable=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];exports.encode=function(plain){Buffer.isBuffer(plain)||(plain=new Buffer(plain));for(var i=0,j=0,shiftIndex=0,digit=0,encoded=new Buffer(8*quintetCount(plain));i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],267:[function(require,module,exports){function getTick(start){return 65535&(+Date.now()-start)/timeDiff}const maxTick=65535,resolution=10,timeDiff=1e3/resolution;module.exports=function(seconds){const start=+Date.now(),size=resolution*(seconds||5),buffer=[0];let pointer=1,last=getTick(start)-1&maxTick;return function(delta){const tick=getTick(start);let dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);const top=buffer[pointer-1],btm=buffer.length */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=(peer,infoHash)=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}module.exports=Discovery}).call(this)}).call(this,require("_process"))},{_process:192,"bittorrent-dht/client":41,"bittorrent-lsd":41,"bittorrent-tracker/client":33,debug:90,events:122,"run-parallel":232}],270:[function(require,module,exports){(function(Buffer){(function(){/*! torrent-piece. MIT License. WebTorrent LLC */const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),MAX_METADATA_SIZE=1E7,BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash,peerId,extensions){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||MAX_METADATA_SIZE=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf,totalSize){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*MIN_FRAGMENT_DURATION)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}const MIN_FRAGMENT_DURATION=1;module.exports=MP4Remuxer}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":30,buffer:75,events:122,"mp4-box-encoding":171,"mp4-stream":174,"range-slice-stream":211}],278:[function(require,module,exports){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":277,mediasource:159,pump:200}],279:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const EventEmitter=require("events"),path=require("path"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debugFactory=require("debug"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),randombytes=require("randombytes"),sha1=require("simple-sha1"),throughput=require("throughput"),{ThrottleGroup}=require("speed-limiter"),ConnPool=require("./lib/conn-pool.js"),Torrent=require("./lib/torrent.js"),{version:VERSION}=require("./package.json"),debug=debugFactory("webtorrent"),VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4),VERSION_PREFIX=`-WW${VERSION_STR}-`;class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(VERSION_PREFIX+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=WebTorrent.UTP_SUPPORT&&!1!==opts.utp,this._downloadLimit=_Mathmax("number"==typeof opts.downloadLimit?opts.downloadLimit:-1,-1),this._uploadLimit=_Mathmax("number"==typeof opts.uploadLimit?opts.uploadLimit:-1,-1),this.serviceWorker=null,this.workerKeepAliveInterval=null,this.workerPortCount=0,!0===opts.secure&&require("./lib/peer").enableSecure(),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new ThrottleGroup({rate:_Mathmax(this._downloadLimit,0),enabled:0<=this._downloadLimit}),up:new ThrottleGroup({rate:_Mathmax(this._uploadLimit,0),enabled:0<=this._uploadLimit})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):queueMicrotask(()=>{this._onListening()}),this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?console.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):queueMicrotask(ready)}loadWorker(controller,cb=()=>{}){if(!(controller instanceof ServiceWorker))throw new Error("Invalid worker registration");if("activated"!==controller.state)throw new Error("Worker isn't activated");const keepAliveTime=2e4;this.serviceWorker=controller,navigator.serviceWorker.addEventListener("message",event=>{const{data}=event;if(!data.type||"webtorrent"===!data.type||!data.url)return null;let[infoHash,...filePath]=data.url.slice(data.url.indexOf(data.scope+"webtorrent/")+11+data.scope.length).split("/");if(filePath=decodeURI(filePath.join("/")),!infoHash||!filePath)return null;const[port]=event.ports,file=this.get(infoHash)&&this.get(infoHash).files.find(file=>file.path===filePath);if(!file)return null;const[response,stream,raw]=file._serve(data),asyncIterator=stream&&stream[Symbol.asyncIterator](),cleanup=()=>{port.onmessage=null,stream&&stream.destroy(),raw&&raw.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};port.onmessage=async msg=>{if(msg.data){let chunk;try{chunk=(await asyncIterator.next()).value}catch(e){}port.postMessage(chunk),chunk||cleanup(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval(()=>fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/keepalive/`),keepAliveTime))}else cleanup()},this.workerPortCount++,port.postMessage(response)}),fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/cancel/`).then(res=>{res.body.cancel()}),cb(null,this.serviceWorker)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`)),void ontorrent(t)},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const onTorrent=torrent=>{const tasks=[cb=>isFilePath||opts.preloadedStore?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))},_onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,onTorrent);let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{!opts.preloadedStore&&isReadable(item)?concat(item,(err,buf)=>err?cb(err):void(buf.name=item.name,cb(null,buf))):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?(console.warn("A torrent with the same id is already being seeded"),torrent._destroy(),"function"==typeof onseed&&onseed(existingTorrent)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb),this.dht&&this.dht._tables.remove(torrent.infoHash))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._downloadLimit=rate,0>this._downloadLimit?this.throttleGroups.down.setEnabled(!1):void(this.throttleGroups.down.setEnabled(!0),this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._uploadLimit=rate,0>this._uploadLimit?this.throttleGroups.up.setEnabled(!1):void(this.throttleGroups.up.setEnabled(!0),this.throttleGroups.up.setRate(this._uploadLimit)))}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_getByHash(infoHashHash){for(const torrent of this.torrents)if(torrent.infoHashHash||(torrent.infoHashHash=sha1.sync(Buffer.from("72657132"+torrent.infoHash,"hex"))),infoHashHash===torrent.infoHashHash)return torrent;return null}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.UTP_SUPPORT=ConnPool.UTP_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("buffer").Buffer)},{"./lib/conn-pool.js":41,"./lib/peer":3,"./lib/torrent.js":5,"./package.json":281,"bittorrent-dht/client":41,buffer:75,"create-torrent":88,debug:90,events:122,"load-ip-set":41,"parse-torrent":183,path:184,"queue-microtask":205,randombytes:208,"run-parallel":232,"simple-concat":244,"simple-peer":246,"simple-sha1":247,"speed-limiter":250,throughput:267}]},{},[282])(282)}); \ No newline at end of file + */"use strict";function rangeParser(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;isize-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;icurrent.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=rangeParser},{}],211:[function(require,module,exports){const{Writable,PassThrough}=require("readable-stream");class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;!0;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}module.exports=RangeSliceStream},{"readable-stream":227}],212:[function(require,module,exports){"use strict";function isInteger(n){return parseInt(n,10)===n}function createRC4(N){function identityPermutation(){for(var s=Array(N),i=0;in?_StringfromCharCode(48+n):_StringfromCharCode(97+n-10)}function fromHex(c){return parseInt(c,16)}var RC4=createRC4(256);RC4.prototype.randomByte=RC4.prototype.randomNative;var RC4small=createRC4(16);RC4small.prototype.randomByte=function(){var a=this.randomNative(),b=this.randomNative();return 16*a+b};var ordA=97,ord0=48;RC4small.prototype.currentStateString=function(){var state=this.currentState(),i=toHex(state.i),j=toHex(state.j),res=i+j+state.s.map(toHex).join("");return res},RC4small.prototype.setStateString=function(stateString){if(!stateString.match(/^[0-9a-f]{18}$/))throw new TypeError("RC4small stateString should be 18 hex character string");var i=fromHex(stateString[0]),j=fromHex(stateString[1]),s=stateString.split("").slice(2).map(fromHex);this.setState({i:i,j:j,s:s})},RC4.RC4small=RC4small,module.exports=RC4},{}],213:[function(require,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],214:[function(require,module,exports){(function(process){(function(){"use strict";function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:75,util:41}],221:[function(require,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)}function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require("_process"))},{_process:192}],222:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function onlegacyfinish(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function onfinish(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function onend(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function onerror(err){callback.call(stream,err)},onclose=function onclose(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function onrequest(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":213}],223:[function(require,module,exports){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],224:[function(require,module,exports){"use strict";function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}function pipeline(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=ihwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":213}],226:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:122}],227:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":214,"./lib/_stream_passthrough.js":215,"./lib/_stream_readable.js":216,"./lib/_stream_transform.js":217,"./lib/_stream_writable.js":218,"./lib/internal/streams/end-of-stream.js":222,"./lib/internal/streams/pipeline.js":224}],228:[function(require,module,exports){function render(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,tagName=>{if(elem.nodeName!==tagName.toUpperCase()){const extname=path.extname(file.name).toLowerCase();throw new Error(`Cannot render "${extname}" inside a "${elem.nodeName.toLowerCase()}" element, expected "${tagName}"`)}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)}function append(file,rootElem,opts,cb){function getElem(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)}function createMedia(tagName){const elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){const elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=()=>{}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,getElem,opts,done)}function renderMedia(file,getElem,opts,cb){function renderMediaSource(){function useVideostream(){debug(`Use \`videostream\` package for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),new VideoStream(file,elem)}function useMediaSource(){debug(`Use MediaSource API for ${file.name}`),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata);const wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug(`Use Blob URL for ${file.name}`),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime)))}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("loadedmetadata",onLoadedMetadata),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",()=>{currentTime=elem.currentTime}))}const tagName=MEDIASOURCE_VIDEO_EXTS.includes(extname)?"video":"audio";MediaSource?VIDEOSTREAM_EXTS.includes(extname)?useVideostream():useMediaSource():useBlobURL()}function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error(`File length too large for Blob URL approach: ${file.length} (max: ${opts.maxBlobLength})`)),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("loadedmetadata",onLoadedMetadata),elem.src=url)))}function onLoadStart(){if(elem.removeEventListener("loadstart",onLoadStart),opts.autoplay){const playPromise=elem.play();"undefined"!=typeof playPromise&&playPromise.catch(fatalError)}}function onLoadedMetadata(){elem.removeEventListener("loadedmetadata",onLoadedMetadata),cb(null,elem)}function renderImage(){elem=getElem("img"),getBlobURL(file,(err,url)=>err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem)))}function renderIframe(){getBlobURL(file,(err,url)=>err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem)))}function tryRenderIframe(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error(`Unsupported file type "${extname}": Cannot append to DOM`)))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);let str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",chunk=>{str+=chunk}).on("end",done).on("error",cb)}function fatalError(err){err.message=`Error rendering file "${file.name}": ${err.message}`,debug(err.message),cb(err)}const extname=path.extname(file.name).toLowerCase();let currentTime=0,elem;MEDIASOURCE_EXTS.includes(extname)?renderMediaSource():VIDEO_EXTS.includes(extname)?renderMediaElement("video"):AUDIO_EXTS.includes(extname)?renderMediaElement("audio"):IMAGE_EXTS.includes(extname)?renderImage():IFRAME_EXTS.includes(extname)?renderIframe():tryRenderIframe()}function getBlobURL(file,cb){const extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){const extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=MAX_BLOB_LENGTH)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=render,exports.append=append,exports.mime=require("./lib/mime.json");const debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),VideoStream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_AUDIO_EXTS=[".m4a",".m4b",".m4p",".mp3"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,MEDIASOURCE_AUDIO_EXTS),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".srt",".txt"],MAX_BLOB_LENGTH=200000000,MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":229,debug:90,"is-ascii":147,mediasource:159,path:184,"stream-to-blob-url":260,videostream:278}],229:[function(require,module,exports){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],230:[function(require,module,exports){"use strict";function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^c^d)+m+k,s)+e}function fn2(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&c|~b&d)+m+k,s)+e}function fn3(a,b,c,d,e,m,k,s){return 0|rotl(0|a+((b|~c)^d)+m+k,s)+e}function fn4(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b&d|c&~d)+m+k,s)+e}function fn5(a,b,c,d,e,m,k,s){return 0|rotl(0|a+(b^(c|~d))+m+k,s)+e}var Buffer=require("buffer").Buffer,inherits=require("inherits"),HashBase=require("hash-base"),ARRAY16=Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;16>j;++j)words[j]=this._block.readInt32LE(4*j);for(var al=0|this._a,bl=0|this._b,cl=0|this._c,dl=0|this._d,el=0|this._e,ar=0|this._a,br=0|this._b,cr=0|this._c,dr=0|this._d,er=0|this._e,i=0;80>i;i+=1){var tl,tr;16>i?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):32>i?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):48>i?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):64>i?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=0|this._b+cl+dr;this._b=0|this._c+dl+er,this._c=0|this._d+el+ar,this._d=0|this._e+al+br,this._e=0|this._a+bl+cr,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,56>2)+1;i>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function _write(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function _coreCall(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function rawDigest(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function digest(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function digestFromString(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function digestFromBuffer(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function digestFromArrayBuffer(str){return this.digest(str)},Rusha.prototype.resetState=function resetState(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function append(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffseti;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i=v)return 65536;if(16777216>v)for(p=1;p>2],y1$851=0|H$843[x$846+324>>2],y2$853=0|H$843[x$846+328>>2],y3$855=0|H$843[x$846+332>>2],y4$857=0|H$843[x$846+336>>2],i$847=0;(0|i$847)<(0|k$845);i$847=0|i$847+64){for(z0$850=y0$849,z1$852=y1$851,z2$854=y2$853,z3$856=y3$855,z4$858=y4$857,j$848=0;64>(0|j$848);j$848=0|j$848+4)t1$860=0|H$843[i$847+j$848>>2],t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[k$845+j$848>>2]=t1$860;for(j$848=0|k$845+64;(0|j$848)<(0|k$845+80);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|~y1$851&y3$855))+(0|(0|t1$860+y4$857)+1518500249),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+80;(0|j$848)<(0|k$845+160);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)+1859775393),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+160;(0|j$848)<(0|k$845+240);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851&y2$853|y1$851&y3$855|y2$853&y3$855))+(0|(0|t1$860+y4$857)-1894007588),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;for(j$848=0|k$845+240;(0|j$848)<(0|k$845+320);j$848=0|j$848+4)t1$860=(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])<<1|(H$843[j$848-12>>2]^H$843[j$848-32>>2]^H$843[j$848-56>>2]^H$843[j$848-64>>2])>>>31,t0$859=0|(0|(y0$849<<5|y0$849>>>27)+(y1$851^y2$853^y3$855))+(0|(0|t1$860+y4$857)-899497514),y4$857=y3$855,y3$855=y2$853,y2$853=y1$851<<30|y1$851>>>2,y1$851=y0$849,y0$849=t0$859,H$843[j$848>>2]=t1$860;y0$849=0|y0$849+z0$850,y1$851=0|y1$851+z1$852,y2$853=0|y2$853+z2$854,y3$855=0|y3$855+z3$856,y4$857=0|y4$857+z4$858}H$843[x$846+320>>2]=y0$849,H$843[x$846+324>>2]=y1$851,H$843[x$846+328>>2]=y2$853,H$843[x$846+332>>2]=y3$855,H$843[x$846+336>>2]=y4$857}var H$843=new stdlib$840.Int32Array(heap$842);return{hash:hash$844}}},function(module,exports){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0,descriptor;i */var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:75}],235:[function(require,module,exports){(function(process){(function(){"use strict";var buffer=require("buffer"),Buffer=buffer.Buffer,safer={},key;for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw new TypeError("The \"value\" argument must not be of type number. Received type "+typeof value);if(value&&"undefined"==typeof value.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("The \"size\" argument must be of type number. Received type "+typeof size);if(0>size||2147483648<=size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"");var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}).call(this)}).call(this,require("_process"))},{_process:192,buffer:75}],236:[function(require,module,exports){function Hash(blockSize,finalSize){this._block=Buffer.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}var Buffer=require("safe-buffer").Buffer;Hash.prototype.update=function(data,enc){"string"==typeof data&&(enc=enc||"utf8",data=Buffer.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=8*this._len;if(4294967295>=bits)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(4294967295&bits)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")},module.exports=Hash},{"safe-buffer":234}],237:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha"),exports.sha1=require("./sha1"),exports.sha224=require("./sha224"),exports.sha256=require("./sha256"),exports.sha384=require("./sha384"),exports.sha512=require("./sha512")},{"./sha":238,"./sha1":239,"./sha224":240,"./sha256":241,"./sha384":242,"./sha512":243}],238:[function(require,module,exports){function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha},{"./hash":236,inherits:146,"safe-buffer":234}],239:[function(require,module,exports){function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=Array(80);inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha1.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;80>i;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;80>j;++j){var s=~~(j/20),t=0|rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e},Sha1.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha1},{"./hash":236,inherits:146,"safe-buffer":234}],240:[function(require,module,exports){function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}var inherits=require("inherits"),Sha256=require("./sha256"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(64);inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224},{"./hash":236,"./sha256":241,inherits:146,"safe-buffer":234}],241:[function(require,module,exports){function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=Array(64);inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},Sha256.prototype._update=function(M){for(var W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,i=0;16>i;++i)W[i]=M.readInt32BE(4*i);for(;64>i;++i)W[i]=0|gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16];for(var j=0;64>j;++j){var T1=0|h+sigma1(e)+ch(e,f,g)+K[j]+W[j],T2=0|sigma0(a)+maj(a,b,c);h=g,g=f,f=e,e=0|d+T1,d=c,c=b,b=a,a=0|T1+T2}this._a=0|a+this._a,this._b=0|b+this._b,this._c=0|c+this._c,this._d=0|d+this._d,this._e=0|e+this._e,this._f=0|f+this._f,this._g=0|g+this._g,this._h=0|h+this._h},Sha256.prototype._hash=function(){var H=Buffer.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256},{"./hash":236,inherits:146,"safe-buffer":234}],242:[function(require,module,exports){function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}var inherits=require("inherits"),SHA512=require("./sha512"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,W=Array(160);inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(48);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384},{"./hash":236,"./sha512":243,inherits:146,"safe-buffer":234}],243:[function(require,module,exports){function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}var inherits=require("inherits"),Hash=require("./hash"),Buffer=require("safe-buffer").Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=Array(160);inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Sha512.prototype._update=function(M){for(var W=this._w,ah=0|this._ah,bh=0|this._bh,ch=0|this._ch,dh=0|this._dh,eh=0|this._eh,fh=0|this._fh,gh=0|this._gh,hh=0|this._hh,al=0|this._al,bl=0|this._bl,cl=0|this._cl,dl=0|this._dl,el=0|this._el,fl=0|this._fl,gl=0|this._gl,hl=0|this._hl,i=0;32>i;i+=2)W[i]=M.readInt32BE(4*i),W[i+1]=M.readInt32BE(4*i+4);for(;160>i;i+=2){var xh=W[i-30],xl=W[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W[i-4],xl=W[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W[i-14],Wi7l=W[i-14+1],Wi16h=W[i-32],Wi16l=W[i-32+1],Wil=0|gamma0l+Wi7l,Wih=0|gamma0+Wi7h+getCarry(Wil,gamma0l);Wil=0|Wil+gamma1l,Wih=0|Wih+gamma1+getCarry(Wil,gamma1l),Wil=0|Wil+Wi16l,Wih=0|Wih+Wi16h+getCarry(Wil,Wi16l),W[i]=Wih,W[i+1]=Wil}for(var j=0;160>j;j+=2){Wih=W[j],Wil=W[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=0|hl+sigma1l,t1h=0|hh+sigma1h+getCarry(t1l,hl);t1l=0|t1l+chl,t1h=0|t1h+chh+getCarry(t1l,chl),t1l=0|t1l+Kil,t1h=0|t1h+Kih+getCarry(t1l,Kil),t1l=0|t1l+Wil,t1h=0|t1h+Wih+getCarry(t1l,Wil);var t2l=0|sigma0l+majl,t2h=0|sigma0h+majh+getCarry(t2l,sigma0l);hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=0|dl+t1l,eh=0|dh+t1h+getCarry(el,dl),dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=0|t1l+t2l,ah=0|t1h+t2h+getCarry(al,t1l)}this._al=0|this._al+al,this._bl=0|this._bl+bl,this._cl=0|this._cl+cl,this._dl=0|this._dl+dl,this._el=0|this._el+el,this._fl=0|this._fl+fl,this._gl=0|this._gl+gl,this._hl=0|this._hl+hl,this._ah=0|this._ah+ah+getCarry(this._al,al),this._bh=0|this._bh+bh+getCarry(this._bl,bl),this._ch=0|this._ch+ch+getCarry(this._cl,cl),this._dh=0|this._dh+dh+getCarry(this._dl,dl),this._eh=0|this._eh+eh+getCarry(this._el,el),this._fh=0|this._fh+fh+getCarry(this._fl,fl),this._gh=0|this._gh+gh+getCarry(this._gl,gl),this._hh=0|this._hh+hh+getCarry(this._hl,hl)},Sha512.prototype._hash=function(){function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}var H=Buffer.allocUnsafe(64);return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512},{"./hash":236,inherits:146,"safe-buffer":234}],244:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh */module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],245:[function(require,module,exports){(function(Buffer){(function(){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const originalHost=opts.hostname,protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location){opts.url=res.headers.location,delete opts.headers.host,res.resume();const redirectHost=url.parse(opts.url).hostname;return null!==redirectHost&&redirectHost!==originalHost&&(delete opts.headers.cookie,delete opts.headers.authorization),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb)}const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"decompress-response":41,http:256,https:143,once:177,querystring:204,"simple-concat":244,url:273}],246:[function(require,module,exports){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}/*! simple-peer. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),errCode=require("err-code"),{Buffer}=require("buffer"),MAX_BUFFERED_AMOUNT=65536,ICECOMPLETE_TIMEOUT=5000,CHANNEL_CLOSING_TIMEOUT=5000;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(err=>{this.destroy(errCode(err,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(chunk)}}addTransceiver(kind,init){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind,init}})}}addStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}}addTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",err&&(err.message||err)),queueMicrotask(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}))}_setupData(event){if(!event.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=event=>{const err=event.error instanceof Error?event.error:new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`);this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}},onSuccess=()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(offer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){const signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}},onSuccess=()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))},onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(answer).then(onSuccess).catch(onError)}).catch(err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{const reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0{if(this.destroyed)return;const reports=[];res.result().forEach(result=>{const report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);const remoteCandidates={},localCandidates={},candidatePairs={};let foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;let local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this._debug("on stream"),this.emit("stream",eventStream)}))})}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer},{buffer:75,debug:90,"err-code":121,"get-browser-rtc":128,"queue-microtask":205,randombytes:208,"readable-stream":227}],247:[function(require,module,exports){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function succeed(result){cb(hex(new Uint8Array(result)))},function fail(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function onRushaWorkerSha1(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){const l=s.length,array=new Uint8Array(l);for(let i=0;i>>4).toString(16)),chars.push((15&bite).toString(16))}return chars.join("")}const Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{};let subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":248,rusha:233}],248:[function(require,module,exports){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function onRushaMessage(e){const taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}const Rusha=require("rusha");let worker,nextTaskId,cbs;module.exports=sha1},{rusha:233}],249:[function(require,module,exports){(function(Buffer){(function(){/*! simple-websocket. MIT License. Feross Aboukhadijeh */const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,null,{...opts,encoding:void 0}):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",opts.socket&&this.connected?queueMicrotask(()=>this._handleOpen()):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=event=>this._handleMessage(event),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=err=>this._handleError(err),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}this._ws=null,err&&this.emit("error",err),this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_handleOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(_){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,debug:90,"queue-microtask":205,randombytes:208,"readable-stream":227,ws:41}],250:[function(require,module,exports){const Throttle=require("./lib/throttle"),ThrottleGroup=require("./lib/throttle-group");module.exports={Throttle,ThrottleGroup}},{"./lib/throttle":252,"./lib/throttle-group":251}],251:[function(require,module,exports){var _NumberisInteger=Number.isInteger;const{TokenBucket}=require("limiter"),Throttle=require("./throttle");class ThrottleGroup{constructor(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");this.throttles=[],this.setEnabled(opts.enabled),this.setRate(opts.rate,opts.chunksize)}getEnabled(){return this._enabled}getRate(){return this.bucket.tokensPerInterval}getChunksize(){return this.chunksize}setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val;for(const throttle of this.throttles)throttle.setEnabled(val)}setRate(rate,chunksize=null){if(!_NumberisInteger(rate)||0>rate)throw new Error("Rate must be an integer bigger than zero");if(rate=parseInt(rate),chunksize&&("number"!=typeof chunksize||0>=chunksize))throw new Error("Chunksize must be bigger than zero");if(chunksize=chunksize||_Mathmax(parseInt(rate/10),1),chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.bucket||(this.bucket=new TokenBucket(rate,rate,"second",null)),this.bucket.bucketSize=rate,this.bucket.tokensPerInterval=rate,this.chunksize=chunksize}setChunksize(chunksize){if(!_NumberisInteger(chunksize)||0>=chunksize)throw new Error("Chunk size must be an integer bigger than zero");const rate=this.getRate();if(chunksize=parseInt(chunksize),0rate)throw new Error("Chunk size must be smaller than rate");this.chunksize=chunksize}throttle(opts={}){if("object"!=typeof opts)throw new Error("Options must be an object");const newThrottle=new Throttle({...opts,group:this});return newThrottle}destroy(){for(const throttle of this.throttles)throttle.destroy();this.throttles=[]}_addThrottle(throttle){if(!(throttle instanceof Throttle))throw new Error("Throttle must be an instance of Throttle");this.throttles.push(throttle)}_removeThrottle(throttle){const index=this.throttles.indexOf(throttle);-1{function isDone(err){if(self._emitter.removeListener("disabled",isDone),self._emitter.removeListener("destroyed",isDone),!done)return done=!0,err?reject(err):void resolve()}let done=!1;const self=this;this._emitter.once("disabled",isDone),this._emitter.once("destroyed",isDone),this._group.bucket.removeTokens(amount,isDone)})}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(chunk,done){if(!this._areBothEnabled())return done(null,chunk);let pos=0,chunksize=this._group.getChunksize(),slice=chunk.slice(pos,pos+chunksize);for(;0setTimeout(resolve,time))}module.exports={wait}},{}],254:[function(require,module,exports){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.lengthself._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;iself._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){resetTimers(!0),self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&(resetTimers(!0),self.push(null))}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":257,_process:192,buffer:75,inherits:146,"readable-stream":227}],260:[function(require,module,exports){async function getBlobURL(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url}module.exports=getBlobURL;const getBlob=require("stream-to-blob")},{"stream-to-blob":261}],261:[function(require,module,exports){function streamToBlob(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}/*! stream-to-blob. MIT License. Feross Aboukhadijeh */module.exports=streamToBlob},{}],262:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh */var once=require("once");module.exports=function getBuffer(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,once:177}],263:[function(require,module,exports){function afterDrain(){this.stream._duplexState|=READ_PIPE_DRAINED,0==(this.stream._duplexState&READ_ACTIVE_AND_SYNC)?this.updateNextTick():this.drain()}function afterFinal(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROY_STATUS)&&(stream._duplexState|=WRITE_DONE,stream.emit("finish")),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),stream._duplexState&=WRITE_NOT_ACTIVE,this.update()}function afterDestroy(err){const stream=this.stream;err||this.error===STREAM_DESTROYED||(err=this.error),err&&stream.emit("error",err),stream._duplexState|=DESTROYED,stream.emit("close");const rs=stream._readableState,ws=stream._writableState;null!==rs&&null!==rs.pipeline&&rs.pipeline.done(stream,err),null!==ws&&null!==ws.pipeline&&ws.pipeline.done(stream,err)}function afterWrite(err){const stream=this.stream;err&&stream.destroy(err),stream._duplexState&=WRITE_NOT_ACTIVE,(stream._duplexState&WRITE_DRAIN_STATUS)===WRITE_UNDRAINED&&(stream._duplexState&=WRITE_DRAINED,(stream._duplexState&WRITE_EMIT_DRAIN)===WRITE_EMIT_DRAIN&&stream.emit("drain")),0==(stream._duplexState&WRITE_SYNC)&&this.update()}function afterRead(err){err&&this.stream.destroy(err),this.stream._duplexState&=READ_NOT_ACTIVE,0==(this.stream._duplexState&READ_SYNC)&&this.update()}function updateReadNT(){this.stream._duplexState&=READ_NOT_NEXT_TICK,this.update()}function updateWriteNT(){this.stream._duplexState&=WRITE_NOT_NEXT_TICK,this.update()}function afterOpen(err){const stream=this.stream;err&&stream.destroy(err),0==(stream._duplexState&DESTROYING)&&(0==(stream._duplexState&READ_PRIMARY_STATUS)&&(stream._duplexState|=READ_PRIMARY),0==(stream._duplexState&WRITE_PRIMARY_STATUS)&&(stream._duplexState|=WRITE_PRIMARY),stream.emit("open")),stream._duplexState&=NOT_ACTIVE,null!==stream._writableState&&stream._writableState.update(),null!==stream._readableState&&stream._readableState.update()}function afterTransform(err,data){data!==void 0&&null!==data&&this.push(data),this._writableState.afterWrite(err)}function transformAfterFlush(err,data){const cb=this._transformState.afterFinal;return err?cb(err):void(null!==data&&data!==void 0&&this.push(data),this.push(null),cb(null))}function pipelinePromise(...streams){return new Promise((resolve,reject)=>pipeline(...streams,err=>err?reject(err):void resolve()))}function pipeline(stream,...streams){function errorHandle(s,rd,wr,onerror){function onclose(){return rd&&s._readableState&&!s._readableState.ended?onerror(PREMATURE_CLOSE):wr&&s._writableState&&!s._writableState.ended?onerror(PREMATURE_CLOSE):void 0}s.on("error",onerror),s.on("close",onclose)}function onerror(err){if(err&&!error){error=err;for(const s of all)s.destroy(err)}}const all=Array.isArray(stream)?[...stream,...streams]:[stream,...streams],done=all.length&&"function"==typeof all[all.length-1]?all.pop():null;if(2>all.length)throw new Error("Pipeline requires at least 2 streams");let src=all[0],dest=null,error=null;for(let i=1;i{fin=!0}),dest.on("error",err=>{error=error||err}),dest.on("close",()=>done(error||(fin?null:PREMATURE_CLOSE)))}return dest}function isStream(stream){return!!stream._readableState||!!stream._writableState}function isStreamx(stream){return"number"==typeof stream._duplexState&&isStream(stream)}function isReadStreamx(stream){return isStreamx(stream)&&stream.readable}function isTypedArray(data){return"object"==typeof data&&null!==data&&"number"==typeof data.byteLength}function defaultByteLength(data){return isTypedArray(data)?data.byteLength:1024}function noop(){}function abort(){this.destroy(new Error("Stream aborted."))}const{EventEmitter}=require("events"),STREAM_DESTROYED=new Error("Stream was destroyed"),PREMATURE_CLOSE=new Error("Premature close"),queueTick=require("queue-tick"),FIFO=require("fast-fifo"),MAX=33554431,OPENING=1,DESTROYING=2,DESTROYED=4,NOT_OPENING=MAX^OPENING,READ_ACTIVE=8,READ_PRIMARY=16,READ_SYNC=32,READ_QUEUED=64,READ_RESUMED=128,READ_PIPE_DRAINED=256,READ_ENDING=512,READ_EMIT_DATA=1024,READ_EMIT_READABLE=2048,READ_EMITTED_READABLE=4096,READ_DONE=8192,READ_NEXT_TICK=16392,READ_NEEDS_PUSH=32768,READ_NOT_ACTIVE=MAX^READ_ACTIVE,READ_NON_PRIMARY=MAX^READ_PRIMARY,READ_NON_PRIMARY_AND_PUSHED=MAX^(READ_PRIMARY|READ_NEEDS_PUSH),READ_NOT_SYNC=MAX^READ_SYNC,READ_PUSHED=MAX^READ_NEEDS_PUSH,READ_PAUSED=MAX^READ_RESUMED,READ_NOT_QUEUED=MAX^(READ_QUEUED|READ_EMITTED_READABLE),READ_NOT_ENDING=MAX^READ_ENDING,READ_PIPE_NOT_DRAINED=MAX^(READ_RESUMED|READ_PIPE_DRAINED),READ_NOT_NEXT_TICK=MAX^READ_NEXT_TICK,WRITE_ACTIVE=65536,WRITE_PRIMARY=131072,WRITE_SYNC=262144,WRITE_QUEUED=524288,WRITE_UNDRAINED=1048576,WRITE_DONE=2097152,WRITE_EMIT_DRAIN=4194304,WRITE_NEXT_TICK=8454144,WRITE_FINISHING=16777216,WRITE_NOT_ACTIVE=MAX^WRITE_ACTIVE,WRITE_NOT_SYNC=MAX^WRITE_SYNC,WRITE_NON_PRIMARY=MAX^WRITE_PRIMARY,WRITE_NOT_FINISHING=MAX^WRITE_FINISHING,WRITE_DRAINED=MAX^WRITE_UNDRAINED,WRITE_NOT_QUEUED=MAX^WRITE_QUEUED,WRITE_NOT_NEXT_TICK=MAX^WRITE_NEXT_TICK,ACTIVE=READ_ACTIVE|WRITE_ACTIVE,NOT_ACTIVE=MAX^ACTIVE,DONE=READ_DONE|WRITE_DONE,DESTROY_STATUS=DESTROYING|DESTROYED,OPEN_STATUS=DESTROY_STATUS|OPENING,AUTO_DESTROY=DESTROY_STATUS|DONE,NON_PRIMARY=WRITE_NON_PRIMARY&READ_NON_PRIMARY,TICKING=(WRITE_NEXT_TICK|READ_NEXT_TICK)&NOT_ACTIVE,ACTIVE_OR_TICKING=ACTIVE|TICKING,IS_OPENING=OPEN_STATUS|TICKING,READ_PRIMARY_STATUS=OPEN_STATUS|READ_ENDING|READ_DONE,READ_STATUS=OPEN_STATUS|READ_DONE|READ_QUEUED,READ_FLOWING=READ_RESUMED|READ_PIPE_DRAINED,READ_ACTIVE_AND_SYNC=READ_ACTIVE|READ_SYNC,READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH=READ_ACTIVE|READ_SYNC|READ_NEEDS_PUSH,READ_PRIMARY_AND_ACTIVE=READ_PRIMARY|READ_ACTIVE,READ_ENDING_STATUS=OPEN_STATUS|READ_ENDING|READ_QUEUED,READ_EMIT_READABLE_AND_QUEUED=READ_EMIT_READABLE|READ_QUEUED,READ_READABLE_STATUS=OPEN_STATUS|READ_EMIT_READABLE|READ_QUEUED|READ_EMITTED_READABLE,SHOULD_NOT_READ=OPEN_STATUS|READ_ACTIVE|READ_ENDING|READ_DONE|READ_NEEDS_PUSH,READ_BACKPRESSURE_STATUS=DESTROY_STATUS|READ_ENDING|READ_DONE,WRITE_PRIMARY_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_DONE,WRITE_QUEUED_AND_UNDRAINED=WRITE_QUEUED|WRITE_UNDRAINED,WRITE_QUEUED_AND_ACTIVE=WRITE_QUEUED|WRITE_ACTIVE,WRITE_DRAIN_STATUS=WRITE_QUEUED|WRITE_UNDRAINED|OPEN_STATUS|WRITE_ACTIVE,WRITE_STATUS=OPEN_STATUS|WRITE_ACTIVE|WRITE_QUEUED,WRITE_PRIMARY_AND_ACTIVE=WRITE_PRIMARY|WRITE_ACTIVE,WRITE_ACTIVE_AND_SYNC=WRITE_ACTIVE|WRITE_SYNC,WRITE_FINISHING_STATUS=OPEN_STATUS|WRITE_FINISHING|WRITE_QUEUED_AND_ACTIVE|WRITE_DONE,WRITE_BACKPRESSURE_STATUS=WRITE_UNDRAINED|DESTROY_STATUS|WRITE_FINISHING|WRITE_DONE,asyncIterator=Symbol.asyncIterator||Symbol("asyncIterator");class WritableState{constructor(stream,{highWaterMark=16384,map=null,mapWritable,byteLength,byteLengthWritable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthWritable||byteLength||defaultByteLength,this.map=mapWritable||map,this.afterWrite=afterWrite.bind(this),this.afterUpdateNextTick=updateWriteNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&WRITE_DONE)}push(data){return(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),this.buffered=rs._readableState.highWaterMark}static isPaused(rs){return 0==(rs._duplexState&READ_RESUMED)}[asyncIterator](){function onreadable(){null!==promiseResolve&&ondata(stream.read())}function onclose(){null!==promiseResolve&&ondata(null)}function ondata(data){null===promiseReject||(error?promiseReject(error):null===data&&0==(stream._duplexState&READ_DONE)?promiseReject(STREAM_DESTROYED):promiseResolve({value:data,done:null==data}),promiseReject=promiseResolve=null)}function destroy(err){return stream.destroy(err),new Promise((resolve,reject)=>stream._duplexState&DESTROYED?resolve({value:void 0,done:!0}):void stream.once("close",function(){err?reject(err):resolve({value:void 0,done:!0})}))}const stream=this;let error=null,promiseResolve=null,promiseReject=null;return this.on("error",err=>{error=err}),this.on("readable",onreadable),this.on("close",onclose),{[asyncIterator](){return this},next(){return new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject;const data=stream.read();null===data?0!=(stream._duplexState&DESTROYED)&&ondata(null):ondata(data)})},return(){return destroy(null)},throw(err){return destroy(err)}}}}class Writable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|READ_DONE,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}static isBackpressured(ws){return 0!=(ws._duplexState&WRITE_BACKPRESSURE_STATUS)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Duplex extends Readable{constructor(opts){super(opts),this._duplexState=OPENING,this._writableState=new WritableState(this,opts),opts&&(opts.writev&&(this._writev=opts.writev),opts.write&&(this._write=opts.write),opts.final&&(this._final=opts.final))}_writev(batch,cb){cb(null)}_write(data,cb){this._writableState.autoBatch(data,cb)}_final(cb){cb(null)}write(data){return this._writableState.updateNextTick(),this._writableState.push(data)}end(data){return this._writableState.updateNextTick(),this._writableState.end(data),this}}class Transform extends Duplex{constructor(opts){super(opts),this._transformState=new TransformState(this),opts&&(opts.transform&&(this._transform=opts.transform),opts.flush&&(this._flush=opts.flush))}_write(data,cb){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=data:this._transform(data,this._transformState.afterTransform)}_read(cb){if(null!==this._transformState.data){const data=this._transformState.data;this._transformState.data=null,cb(null),this._transform(data,this._transformState.afterTransform)}else cb(null)}_transform(data,cb){cb(null,data)}_flush(cb){cb(null)}_final(cb){this._transformState.afterFinal=cb,this._flush(transformAfterFlush.bind(this))}}class PassThrough extends Transform{}module.exports={pipeline,pipelinePromise,isStream,isStreamx,Stream,Writable,Readable,Duplex,Transform,PassThrough}},{events:122,"fast-fifo":126,"queue-tick":206}],264:[function(require,module,exports){arguments[4][70][0].apply(exports,arguments)},{dup:70,"safe-buffer":234}],265:[function(require,module,exports){var base32=require("./thirty-two");exports.encode=base32.encode,exports.decode=base32.decode},{"./thirty-two":266}],266:[function(require,module,exports){(function(Buffer){(function(){"use strict";function quintetCount(buff){var quintets=_Mathfloor(buff.length/5);return 0==buff.length%5?quintets:quintets+1}var charTable="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",byteTable=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];exports.encode=function(plain){Buffer.isBuffer(plain)||(plain=new Buffer(plain));for(var i=0,j=0,shiftIndex=0,digit=0,encoded=new Buffer(8*quintetCount(plain));i>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],267:[function(require,module,exports){function getTick(start){return 65535&(+Date.now()-start)/timeDiff}const maxTick=65535,resolution=10,timeDiff=1e3/resolution;module.exports=function(seconds){const start=+Date.now(),size=resolution*(seconds||5),buffer=[0];let pointer=1,last=getTick(start)-1&maxTick;return function(delta){const tick=getTick(start);let dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);const top=buffer[pointer-1],btm=buffer.length */const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client"),LSD=require("bittorrent-lsd");class Discovery extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")},this._onLSDPeer=(peer,infoHash)=>{this.emit("peer",peer,"lsd")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),this.lsd=!1===opts.lsd||"function"!=typeof LSD?null:this._createLSD()}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),tasks.push(cb=>{this.lsd.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this.lsd=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}_createLSD(){const opts=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),lsd=new LSD(opts);return lsd.on("warning",this._onWarning),lsd.on("error",this._onError),lsd.on("peer",this._onLSDPeer),lsd.start(),lsd}}module.exports=Discovery}).call(this)}).call(this,require("_process"))},{_process:192,"bittorrent-dht/client":41,"bittorrent-lsd":41,"bittorrent-tracker/client":33,debug:90,events:122,"run-parallel":232}],270:[function(require,module,exports){(function(Buffer){(function(){/*! torrent-piece. MIT License. WebTorrent LLC */const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations=arr.length||0>i)){var last=arr.pop();if(i","\"","`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndexrelPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0 */const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield").default,debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),MAX_METADATA_SIZE=1E7,BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash,peerId,extensions){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||MAX_METADATA_SIZE=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf,totalSize){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample=currTrack.timeScale*MIN_FRAGMENT_DURATION)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;jcurrSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}const MIN_FRAGMENT_DURATION=1;module.exports=MP4Remuxer}).call(this)}).call(this,require("buffer").Buffer)},{"binary-search":30,buffer:75,events:122,"mp4-box-encoding":171,"mp4-stream":174,"range-slice-stream":211}],278:[function(require,module,exports){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("Don't invoke VideoStream without the 'new' keyword."),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":277,mediasource:159,pump:200}],279:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i */const EventEmitter=require("events"),path=require("path"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debugFactory=require("debug"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),randombytes=require("randombytes"),sha1=require("simple-sha1"),throughput=require("throughput"),{ThrottleGroup}=require("speed-limiter"),ConnPool=require("./lib/conn-pool.js"),Torrent=require("./lib/torrent.js"),{version:VERSION}=require("./package.json"),debug=debugFactory("webtorrent"),VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4),VERSION_PREFIX=`-WW${VERSION_STR}-`;class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(VERSION_PREFIX+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.lsd=!1!==opts.lsd,this.torrents=[],this.maxConns=+opts.maxConns||55,this.utp=WebTorrent.UTP_SUPPORT&&!1!==opts.utp,this._downloadLimit=_Mathmax("number"==typeof opts.downloadLimit?opts.downloadLimit:-1,-1),this._uploadLimit=_Mathmax("number"==typeof opts.uploadLimit?opts.uploadLimit:-1,-1),this.serviceWorker=null,this.workerKeepAliveInterval=null,this.workerPortCount=0,!0===opts.secure&&require("./lib/peer").enableSecure(),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new ThrottleGroup({rate:_Mathmax(this._downloadLimit,0),enabled:0<=this._downloadLimit}),up:new ThrottleGroup({rate:_Mathmax(this._uploadLimit,0),enabled:0<=this._uploadLimit})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof ConnPool?this._connPool=new ConnPool(this):queueMicrotask(()=>{this._onListening()}),this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?console.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):queueMicrotask(ready)}loadWorker(controller,cb=()=>{}){if(!(controller instanceof ServiceWorker))throw new Error("Invalid worker registration");if("activated"!==controller.state)throw new Error("Worker isn't activated");const keepAliveTime=2e4;this.serviceWorker=controller,navigator.serviceWorker.addEventListener("message",event=>{const{data}=event;if(!data.type||"webtorrent"===!data.type||!data.url)return null;let[infoHash,...filePath]=data.url.slice(data.url.indexOf(data.scope+"webtorrent/")+11+data.scope.length).split("/");if(filePath=decodeURI(filePath.join("/")),!infoHash||!filePath)return null;const[port]=event.ports,file=this.get(infoHash)&&this.get(infoHash).files.find(file=>file.path===filePath);if(!file)return null;const[response,stream,raw]=file._serve(data),asyncIterator=stream&&stream[Symbol.asyncIterator](),cleanup=()=>{port.onmessage=null,stream&&stream.destroy(),raw&&raw.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};port.onmessage=async msg=>{if(msg.data){let chunk;try{chunk=(await asyncIterator.next()).value}catch(e){}port.postMessage(chunk),chunk||cleanup(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval(()=>fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/keepalive/`),keepAliveTime))}else cleanup()},this.workerPortCount++,port.postMessage(response)}),fetch(`${this.serviceWorker.scriptURL.slice(0,this.serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length)}webtorrent/cancel/`).then(res=>{res.body.cancel()}),cb(null,this.serviceWorker)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}add(torrentId,opts={},ontorrent=()=>{}){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`)),void ontorrent(t)},onReady=()=>{this.destroyed||(ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const onTorrent=torrent=>{const tasks=[cb=>isFilePath||opts.preloadedStore?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))},_onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,onTorrent);let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{!opts.preloadedStore&&isReadable(item)?concat(item,(err,buf)=>err?cb(err):void(buf.name=item.name,cb(null,buf))):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?(console.warn("A torrent with the same id is already being seeded"),torrent._destroy(),"function"==typeof onseed&&onseed(existingTorrent)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,opts,cb){if("function"==typeof opts)return this.remove(torrentId,null,opts);this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,opts,cb)}_remove(torrentId,opts,cb){if("function"==typeof opts)return this._remove(torrentId,null,opts);const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(opts,cb),this.dht&&this.dht._tables.remove(torrent.infoHash))}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._downloadLimit=rate,0>this._downloadLimit?this.throttleGroups.down.setEnabled(!1):void(this.throttleGroups.down.setEnabled(!0),this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(rate){return(rate=+rate,!(isNaN(rate)||!isFinite(rate)||-1>rate))&&(this._uploadLimit=rate,0>this._uploadLimit?this.throttleGroups.up.setEnabled(!1):void(this.throttleGroups.up.setEnabled(!0),this.throttleGroups.up.setRate(this._uploadLimit)))}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._connPool&&tasks.push(cb=>{this._connPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const address=this._connPool.tcpServer.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_getByHash(infoHashHash){for(const torrent of this.torrents)if(torrent.infoHashHash||(torrent.infoHashHash=sha1.sync(Buffer.from("72657132"+torrent.infoHash,"hex"))),infoHashHash===torrent.infoHashHash)return torrent;return null}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.UTP_SUPPORT=ConnPool.UTP_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this)}).call(this,require("buffer").Buffer)},{"./lib/conn-pool.js":41,"./lib/peer":3,"./lib/torrent.js":5,"./package.json":281,"bittorrent-dht/client":41,buffer:75,"create-torrent":88,debug:90,events:122,"load-ip-set":41,"parse-torrent":183,path:184,"queue-microtask":205,randombytes:208,"run-parallel":232,"simple-concat":244,"simple-peer":246,"simple-sha1":247,"speed-limiter":250,throughput:267}]},{},[282])(282)}); \ No newline at end of file -- cgit v1.2.3