Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/webtorrent/webtorrent.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsemantic-release-bot <semantic-release-bot@martynus.net>2022-06-23 04:15:06 +0300
committersemantic-release-bot <semantic-release-bot@martynus.net>2022-06-23 04:15:06 +0300
commite74a6219e7b11a870760adffed5377840e0f01cd (patch)
treeba0ab5556cc26e8a770c8ffe45bfae9ba3f485c1
parent1e3373ab9e6dd16e5b10a2e32988386615f6cf28 (diff)
chore(release): 1.8.23v1.8.23
## [1.8.23](https://github.com/webtorrent/webtorrent/compare/v1.8.22...v1.8.23) (2022-06-23) ### Bug Fixes * **deps:** update dependency torrent-discovery to ^9.4.13 ([1e3373a](https://github.com/webtorrent/webtorrent/commit/1e3373ab9e6dd16e5b10a2e32988386615f6cf28))
-rw-r--r--CHANGELOG.md7
-rw-r--r--package.json2
-rw-r--r--webtorrent.chromeapp.js6
-rw-r--r--webtorrent.min.js4
4 files changed, 13 insertions, 6 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6702217..d9633b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,10 @@
+## [1.8.23](https://github.com/webtorrent/webtorrent/compare/v1.8.22...v1.8.23) (2022-06-23)
+
+
+### Bug Fixes
+
+* **deps:** update dependency torrent-discovery to ^9.4.13 ([1e3373a](https://github.com/webtorrent/webtorrent/commit/1e3373ab9e6dd16e5b10a2e32988386615f6cf28))
+
## [1.8.22](https://github.com/webtorrent/webtorrent/compare/v1.8.21...v1.8.22) (2022-05-24)
diff --git a/package.json b/package.json
index 6b8c0fc..9e8b6ba 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "webtorrent",
"description": "Streaming torrent client",
- "version": "1.8.22",
+ "version": "1.8.23",
"author": {
"name": "WebTorrent LLC",
"email": "feross@webtorrent.io",
diff --git a/webtorrent.chromeapp.js b/webtorrent.chromeapp.js
index 30fc6a5..aad093a 100644
--- a/webtorrent.chromeapp.js
+++ b/webtorrent.chromeapp.js
@@ -25,7 +25,7 @@
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
- */function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return x<y?-1:y<x?1:0}function isBuffer(b){return global.Buffer&&"function"==typeof global.Buffer.isBuffer?global.Buffer.isBuffer(b):!!(null!=b&&b._isBuffer)}function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){return!isBuffer(arrbuf)&&!("function"!=typeof global.ArrayBuffer)&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(arrbuf):!!arrbuf&&(!!(arrbuf instanceof DataView)||!!(arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer)))}function getName(func){if(util.isFunction(func)){if(functionsHaveNames)return func.name;var str=func.toString(),match=str.match(regex);return match&&match[1]}}function truncate(s,n){return"string"==typeof s?s.length<n?s:s.slice(0,n):s}function inspect(something){if(functionsHaveNames||!util.isFunction(something))return util.inspect(something);var rawname=getName(something),name=rawname?": "+rawname:"";return"[Function"+name+"]"}function getMessage(self){return truncate(inspect(self.actual),128)+" "+self.operator+" "+truncate(inspect(self.expected),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}function ok(value,message){value||fail(value,!0,message,"==",assert.ok)}function _deepEqual(actual,expected,strict,memos){if(actual===expected)return!0;if(isBuffer(actual)&&isBuffer(expected))return 0===compare(actual,expected);if(util.isDate(actual)&&util.isDate(expected))return actual.getTime()===expected.getTime();if(util.isRegExp(actual)&&util.isRegExp(expected))return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase;if((null===actual||"object"!=typeof actual)&&(null===expected||"object"!=typeof expected))return strict?actual===expected:actual==expected;if(isView(actual)&&isView(expected)&&pToString(actual)===pToString(expected)&&!(actual instanceof Float32Array||actual instanceof Float64Array))return 0===compare(new Uint8Array(actual.buffer),new Uint8Array(expected.buffer));if(isBuffer(actual)!==isBuffer(expected))return!1;memos=memos||{actual:[],expected:[]};var actualIndex=memos.actual.indexOf(actual);return-1!==actualIndex&&actualIndex===memos.expected.indexOf(expected)||(memos.actual.push(actual),memos.expected.push(expected),objEquiv(actual,expected,strict,memos))}function isArguments(object){return"[object Arguments]"==Object.prototype.toString.call(object)}function objEquiv(a,b,strict,actualVisitedObjects){if(null===a||a===void 0||null===b||b===void 0)return!1;if(util.isPrimitive(a)||util.isPrimitive(b))return a===b;if(strict&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return!1;var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return!1;if(aIsArgs)return a=pSlice.call(a),b=pSlice.call(b),_deepEqual(a,b,strict);var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!==kb.length)return!1;for(ka.sort(),kb.sort(),i=ka.length-1;0<=i;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;0<=i;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError("\"block\" argument must be a function");"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}function strict(value,message){value||fail(value,!0,message,"==",strict)}var objectAssign=require("object-assign"),util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function foo(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function AssertionError(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(0<=idx){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function equal(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function notEqual(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function deepEqual(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function notDeepEqual(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function strictEqual(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function notStrictEqual(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err},assert.strict=objectAssign(strict,assert,{equal:assert.strictEqual,deepEqual:assert.deepStrictEqual,notEqual:assert.notStrictEqual,notDeepEqual:assert.notDeepStrictEqual}),assert.strict.strict=assert.strict;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"object-assign":230,"util/":35}],33:[function(require,module,exports){module.exports="function"==typeof Object.create?function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],34:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],35:[function(require,module,exports){(function(process,global){(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;i<l;++i)hasOwnProperty(value,i+"")?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,i+"",!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?desc.set?str=ctx.stylize("[Getter/Setter]","special"):str=ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(0>ctx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1<str.indexOf("\n")&&(array?str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,"\"").replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,0<=cur.indexOf("\n")&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return 60<length?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"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)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i<arguments.length;i++)objects.push(inspect(arguments[i]));return objects.join(" ")}for(var i=1,args=arguments,len=args.length,str=(f+"").replace(formatRegExp,function(x){if("%%"===x)return"%";if(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<len;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);else process.traceDeprecation?console.trace(msg):console.error(msg);warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(!0===process.noDeprecation)return fn;var warned=!1;return deprecated};var debugs={},debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./support/isBuffer":34,_process:246,inherits:33}],36:[function(require,module,exports){(function(global){(function(){"use strict";var possibleNames=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],g="undefined"==typeof globalThis?global:globalThis;module.exports=function availableTypedArrays(){for(var out=[],i=0;i<possibleNames.length;i++)"function"==typeof g[possibleNames[i]]&&(out[out.length]=possibleNames[i]);return out}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],37:[function(require,module,exports){function codecFor(encoding){switch(encoding){case"ascii":return ascii;case"base64":return base64;case"hex":return hex;case"utf8":case"utf-8":case void 0:return utf8;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16le;default:throw new Error(`Unknown encoding: ${encoding}`);}}function isBuffer(value){return value instanceof Uint8Array}function isEncoding(encoding){try{return codecFor(encoding),!0}catch{return!1}}function alloc(size,fill,encoding){const buffer=new Uint8Array(size);return void 0!==fill&&fill(buffer,fill,0,buffer.byteLength,encoding),buffer}function allocUnsafe(size){return new Uint8Array(size)}function allocUnsafeSlow(size){return new Uint8Array(size)}function byteLength(string,encoding){return codecFor(encoding).byteLength(string)}function compare(a,b){if(a===b)return 0;const len=_Mathmin(a.byteLength,b.byteLength);a=new DataView(a.buffer,a.byteOffset,a.byteLength),b=new DataView(b.buffer,b.byteOffset,b.byteLength);let i=0;for(let n=len-len%4;i<n;i+=4){const x=a.getUint32(i,LE),y=b.getUint32(i,LE);if(x!==y)break}for(;i<len;i++){const x=a.getUint8(i),y=b.getUint8(i);if(x<y)return-1;if(x>y)return 1}return a.byteLength>b.byteLength?1:a.byteLength<b.byteLength?-1:0}function concat(buffers,totalLength){void 0===totalLength&&(totalLength=buffers.reduce((len,buffer)=>len+buffer.byteLength,0));const result=new Uint8Array(totalLength);return buffers.reduce((offset,buffer)=>(result.set(buffer,offset),offset+buffer.byteLength),0),result}function copy(source,target,targetStart=0,start=0,end=source.byteLength){if(0<end&&end<start)return 0;if(end===start)return 0;if(0===source.byteLength||0===target.byteLength)return 0;if(0>targetStart)throw new RangeError("targetStart is out of range");if(0>start||start>=source.byteLength)throw new RangeError("sourceStart is out of range");if(0>end)throw new RangeError("sourceEnd is out of range");targetStart>=target.byteLength&&(targetStart=target.byteLength),end>source.byteLength&&(end=source.byteLength),target.byteLength-targetStart<end-start&&(end=target.length-targetStart+start);const len=end-start;return source===target?target.copyWithin(targetStart,start,end):target.set(source.subarray(start,end),targetStart),len}function equals(a,b){if(a===b)return!0;if(a.byteLength!==b.byteLength)return!1;const len=a.byteLength;a=new DataView(a.buffer,a.byteOffset,a.byteLength),b=new DataView(b.buffer,b.byteOffset,b.byteLength);let i=0;for(let n=len-len%4;i<n;i+=4)if(a.getUint32(i,LE)!==b.getUint32(i,LE))return!1;for(;i<len;i++)if(a.getUint8(i)!==b.getUint8(i))return!1;return!0}function fill(buffer,value,offset,end,encoding){if("string"==typeof value?"string"==typeof offset?(encoding=offset,offset=0,end=buffer.byteLength):"string"==typeof end&&(encoding=end,end=buffer.byteLength):"number"==typeof val?value&=255:"boolean"==typeof val&&(value=+value),0>offset||buffer.byteLength<offset||buffer.byteLength<end)throw new RangeError("Out of range index");if(void 0===offset&&(offset=0),void 0===end&&(end=buffer.byteLength),end<=offset)return buffer;if(value||(value=0),"number"==typeof value)for(let i=offset;i<end;++i)buffer[i]=value;else{value=isBuffer(value)?value:from(value,encoding);const len=value.byteLength;for(let i=0;i<end-offset;++i)buffer[i+offset]=value[i%len]}return buffer}function from(value,encodingOrOffset,length){return"string"==typeof value?fromString(value,encodingOrOffset):Array.isArray(value)?fromArray(value):ArrayBuffer.isView(value)?fromBuffer(value):fromArrayBuffer(value,encodingOrOffset,length)}function fromString(string,encoding){const codec=codecFor(encoding),buffer=new Uint8Array(codec.byteLength(string));return codec.write(buffer,string,0,buffer.byteLength),buffer}function fromArray(array){const buffer=new Uint8Array(array.length);return buffer.set(array),buffer}function fromBuffer(buffer){const copy=new Uint8Array(buffer.byteLength);return copy.set(buffer),copy}function fromArrayBuffer(arrayBuffer,byteOffset,length){return new Uint8Array(arrayBuffer,byteOffset,length)}function includes(buffer,value,byteOffset,encoding){return-1!==indexOf(buffer,value,byteOffset,encoding)}function bidirectionalIndexOf(buffer,value,byteOffset,encoding,first){if(0===buffer.byteLength)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):void 0===byteOffset?byteOffset=first?0:buffer.length-1:0>byteOffset&&(byteOffset+=buffer.byteLength),byteOffset>=buffer.byteLength){if(first)return-1;byteOffset=buffer.byteLength-1}else if(0>byteOffset)if(first)byteOffset=0;else return-1;if("string"==typeof value)value=from(value,encoding);else if("number"==typeof value)return value&=255,first?buffer.indexOf(value,byteOffset):buffer.lastIndexOf(value,byteOffset);if(0===value.byteLength)return-1;if(first){let foundIndex=-1;for(let i=byteOffset;i<buffer.byteLength;i++)if(buffer[i]!==value[-1===foundIndex?0:i-foundIndex])-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1;else if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===value.byteLength)return foundIndex}else{byteOffset+value.byteLength>buffer.byteLength&&(byteOffset=buffer.byteLength-value.byteLength);for(let i=byteOffset,found;0<=i;i--){found=!0;for(let j=0;j<value.byteLength;j++)if(buffer[i+j]!==value[j]){found=!1;break}if(found)return i}}return-1}function indexOf(buffer,value,byteOffset,encoding){return bidirectionalIndexOf(buffer,value,byteOffset,encoding,!0)}function lastIndexOf(buffer,value,byteOffset,encoding){return bidirectionalIndexOf(buffer,value,byteOffset,encoding,!1)}function swap(buffer,n,m){const i=buffer[n];buffer[n]=buffer[m],buffer[m]=i}function swap16(buffer){const len=buffer.byteLength;if(0!=len%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let i=0;i<len;i+=2)swap(buffer,i,i+1);return buffer}function swap32(buffer){const len=buffer.byteLength;if(0!=len%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let i=0;i<len;i+=4)swap(buffer,i,i+3),swap(buffer,i+1,i+2);return buffer}function swap64(buffer){const len=buffer.byteLength;if(0!=len%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let i=0;i<len;i+=8)swap(buffer,i,i+7),swap(buffer,i+1,i+6),swap(buffer,i+2,i+5),swap(buffer,i+3,i+4);return buffer}function toBuffer(buffer){return buffer}function toString(buffer,encoding,start=0,end=buffer.byteLength){const len=buffer.byteLength;return start>=len?"":end<=start?"":(0>start&&(start=0),end>len&&(end=len),(0!==start||end<len)&&(buffer=buffer.subarray(start,end)),codecFor(encoding).toString(buffer))}function write(buffer,string,offset,length,encoding){return void 0===offset?encoding="utf8":void 0===length&&"string"==typeof offset?(encoding=offset,offset=void 0):void 0===encoding&&"string"==typeof length&&(encoding=length,length=void 0),codecFor(encoding).write(buffer,string,offset,length)}const ascii=require("./lib/ascii"),base64=require("./lib/base64"),hex=require("./lib/hex"),utf8=require("./lib/utf8"),utf16le=require("./lib/utf16le"),LE=255===new Uint8Array(Uint16Array.of(255).buffer)[0];module.exports={isBuffer,isEncoding,alloc,allocUnsafe,allocUnsafeSlow,byteLength,compare,concat,copy,equals,fill,from,includes,indexOf,lastIndexOf,swap16,swap32,swap64,toBuffer,toString,write}},{"./lib/ascii":38,"./lib/base64":39,"./lib/hex":40,"./lib/utf16le":41,"./lib/utf8":42}],38:[function(require,module,exports){function byteLength(string){return string.length}function toString(buffer){const len=buffer.byteLength;let result="";for(let i=0;i<len;i++)result+=_StringfromCharCode(buffer[i]);return result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);for(let i=0;i<len;i++)buffer[offset+i]=string.charCodeAt(i);return len}module.exports={byteLength,toString,write}},{}],39:[function(require,module,exports){function byteLength(string){let len=string.length;return 61===string.charCodeAt(len-1)&&len--,1<len&&61===string.charCodeAt(len-1)&&len--,3*len>>>2}function toString(buffer){const len=buffer.byteLength;let result="";for(let i=0;i<len;i+=3)result+=alphabet[buffer[i]>>2]+alphabet[(3&buffer[i])<<4|buffer[i+1]>>4]+alphabet[(15&buffer[i+1])<<2|buffer[i+2]>>6]+alphabet[63&buffer[i+2]];return 2==len%3?result=result.substring(0,result.length-1)+"=":1==len%3&&(result=result.substring(0,result.length-2)+"=="),result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);for(let i=0,j=0;i<len;i+=4){const a=codes[string.charCodeAt(i)],b=codes[string.charCodeAt(i+1)],c=codes[string.charCodeAt(i+2)],d=codes[string.charCodeAt(i+3)];buffer[j++]=a<<2|b>>4,buffer[j++]=(15&b)<<4|c>>2,buffer[j++]=(3&c)<<6|63&d}return len}const alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",codes=new Uint8Array(256);for(let i=0;i<alphabet.length;i++)codes[alphabet.charCodeAt(i)]=i;codes[45]=62,codes[95]=63;module.exports={byteLength,toString,write}},{}],40:[function(require,module,exports){function byteLength(string){return string.length>>>1}function toString(buffer){const len=buffer.byteLength;buffer=new DataView(buffer.buffer,buffer.byteOffset,len);let result="",i=0;for(let n=len-len%4;i<n;i+=4)result+=buffer.getUint32(i).toString(16).padStart(8,"0");for(;i<len;i++)result+=buffer.getUint8(i).toString(16).padStart(2,"0");return result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);for(let i=0;i<len;i++){const a=hexValue(string.charCodeAt(2*i)),b=hexValue(string.charCodeAt(2*i+1));if(a===void 0||b===void 0)return buffer.subarray(0,i);buffer[offset+i]=a<<4|b}return len}function hexValue(char){return 48<=char&&57>=char?char-48:65<=char&&70>=char?char-65+10:97<=char&&102>=char?char-97+10:void 0}module.exports={byteLength,toString,write}},{}],41:[function(require,module,exports){function byteLength(string){return 2*string.length}function toString(buffer){const len=buffer.byteLength;let result="";for(let i=0;i<len-1;i+=2)result+=_StringfromCharCode(buffer[i]+256*buffer[i+1]);return result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);let units=len;for(let i=0;i<string.length&&!(0>(units-=2));++i){const c=string.charCodeAt(i),hi=c>>8,lo=c%256;buffer[offset+2*i]=lo,buffer[offset+2*i+1]=hi}return len}module.exports={byteLength,toString,write}},{}],42:[function(require,module,exports){function byteLength(string){let length=0;for(let i=0,n=string.length;i<n;i++){const code=string.charCodeAt(i);if(55296<=code&&56319>=code&&i+1<n){const code=string.charCodeAt(i+1);if(56320<=code&&57343>=code){length+=4,i++;continue}}length+=127>=code?1:2047>=code?2:3}return length}let toString;if("undefined"!=typeof TextDecoder){const decoder=new TextDecoder;toString=function toString(buffer){return decoder.decode(buffer)}}else toString=function toString(buffer){var _StringfromCodePoint=String.fromCodePoint;const len=buffer.byteLength;let output="",i=0;for(;i<len;){let byte=buffer[i];if(127>=byte){output+=_StringfromCharCode(byte),i++;continue}let bytesNeeded=0,codePoint=0;if(223>=byte?(bytesNeeded=1,codePoint=31&byte):239>=byte?(bytesNeeded=2,codePoint=15&byte):244>=byte&&(bytesNeeded=3,codePoint=7&byte),0<len-i-bytesNeeded)for(let k=0;k<bytesNeeded;)byte=buffer[i+k+1],codePoint=codePoint<<6|63&byte,k+=1;else codePoint=65533,bytesNeeded=len-i;output+=_StringfromCodePoint(codePoint),i+=bytesNeeded+1}return output};let write;if("undefined"!=typeof TextEncoder){const encoder=new TextEncoder;write=function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);return encoder.encodeInto(string,buffer.subarray(offset,offset+len)),len}}else write=function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);buffer=buffer.subarray(offset,offset+len);let i=0,j=0;for(;i<string.length;){const code=string.codePointAt(i);if(127>=code){buffer[j++]=code,i++;continue}let count=0,bits=0;for(2047>=code?(count=6,bits=192):65535>=code?(count=12,bits=224):2097151>=code&&(count=18,bits=240),buffer[j++]=bits|code>>count,count-=6;0<=count;)buffer[j++]=128|63&code>>count,count-=6;i+=65536<=code?2:1}return len};module.exports={byteLength,toString,write}},{}],43:[function(require,module,exports){"use strict";function getLens(b64){var len=b64.length;if(0<len%4)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");-1===validLen&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=0<placeHoldersLen?validLen-4:validLen,tmp,i;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=255&tmp>>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;i<end;i+=3)tmp=(16711680&uint8[i]<<16)+(65280&uint8[i+1]<<8)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes,tmp;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62,revLookup[95]=63},{}],44:[function(require,module,exports){(function(Buffer){(function(){function getIntFromBuffer(buffer,start,end){let sum=0,sign=1;for(let i=start;i<end;i++){const num=buffer[i];if(58>num&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}const INTEGER_START=105,STRING_DELIM=58,DICTIONARY_START=100,LIST_START=108,END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case DICTIONARY_START:return decode.dictionary();case LIST_START:return decode.list();case INTEGER_START:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){let i=decode.position;const c=decode.data.length,d=decode.data;for(;i<c;){if(d[i]===chr)return i;i++}throw new Error("Invalid data: Missing delimiter \""+_StringfromCharCode(chr)+"\" [0x"+chr.toString(16)+"]")},decode.dictionary=function(){decode.position++;const dict={};for(;decode.data[decode.position]!==END_OF_TYPE;)dict[decode.buffer()]=decode.next();return decode.position++,dict},decode.list=function(){decode.position++;const lst=[];for(;decode.data[decode.position]!==END_OF_TYPE;)lst.push(decode.next());return decode.position++,lst},decode.integer=function(){const end=decode.find(END_OF_TYPE),number=getIntFromBuffer(decode.data,decode.position+1,end);return decode.position+=end+1-decode.position,number},decode.buffer=function(){let sep=decode.find(STRING_DELIM);const length=getIntFromBuffer(decode.data,decode.position,sep),end=++sep+length;return decode.position=end,decode.encoding?decode.data.toString(decode.encoding,sep,end):decode.data.slice(sep,end)},module.exports=decode}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],45:[function(require,module,exports){(function(Buffer){(function(){function encode(data,buffer,offset){const buffers=[];let result=null;return encode._encode(buffers,data),result=Buffer.concat(buffers),encode.bytes=result.length,Buffer.isBuffer(buffer)?(result.copy(buffer,offset),buffer):result}const{getType}=require("./util.js");encode.bytes=-1,encode._floatConversionDetected=!1,encode._encode=function(buffers,data){if(null!=data)switch(getType(data)){case"buffer":encode.buffer(buffers,data);break;case"object":encode.dict(buffers,data);break;case"map":encode.dictMap(buffers,data);break;case"array":encode.list(buffers,data);break;case"set":encode.listSet(buffers,data);break;case"string":encode.string(buffers,data);break;case"number":encode.number(buffers,data);break;case"boolean":encode.number(buffers,data);break;case"arraybufferview":encode.buffer(buffers,Buffer.from(data.buffer,data.byteOffset,data.byteLength));break;case"arraybuffer":encode.buffer(buffers,Buffer.from(data));}};const buffE=Buffer.from("e"),buffD=Buffer.from("d"),buffL=Buffer.from("l");encode.buffer=function(buffers,data){buffers.push(Buffer.from(data.length+":"),data)},encode.string=function(buffers,data){buffers.push(Buffer.from(Buffer.byteLength(data)+":"+data))},encode.number=function(buffers,data){const maxLo=2147483648,hi=data/2147483648<<0,lo=data%2147483648<<0,val=hi*2147483648+lo;buffers.push(Buffer.from("i"+val+"e")),val===data||encode._floatConversionDetected||(encode._floatConversionDetected=!0,console.warn("WARNING: Possible data corruption detected with value \""+data+"\":","Bencoding only defines support for integers, value was converted to \""+val+"\""),console.trace())},encode.dict=function(buffers,data){buffers.push(buffD);let j=0,k;const keys=Object.keys(data).sort(),kl=keys.length;for(;j<kl;j++)k=keys[j],null!=data[k]&&(encode.string(buffers,k),encode._encode(buffers,data[k]));buffers.push(buffE)},encode.dictMap=function(buffers,data){buffers.push(buffD);const keys=Array.from(data.keys()).sort();for(const key of keys)null!=data.get(key)&&(Buffer.isBuffer(key)?encode._encode(buffers,key):encode.string(buffers,key+""),encode._encode(buffers,data.get(key)));buffers.push(buffE)},encode.list=function(buffers,data){let i=0;const c=data.length;for(buffers.push(buffL);i<c;i++)null!=data[i]&&encode._encode(buffers,data[i]);buffers.push(buffE)},encode.listSet=function(buffers,data){buffers.push(buffL);for(const item of data)null!=item&&encode._encode(buffers,item);buffers.push(buffE)},module.exports=encode}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":48,buffer:101}],46:[function(require,module,exports){(function(Buffer){(function(){function listLength(list){let length=2;for(const value of list)length+=encodingLength(value);return length}function mapLength(map){let length=2;for(const[key,value]of map){const keyLength=Buffer.byteLength(key);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value)}return length}function objectLength(value){let length=2;const keys=Object.keys(value);for(let i=0;i<keys.length;i++){const keyLength=Buffer.byteLength(keys[i]);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value[keys[i]])}return length}function stringLength(value){const length=Buffer.byteLength(value);return digitCount(length)+1+length}function arrayBufferLength(value){const length=value.byteLength-value.byteOffset;return digitCount(length)+1+length}function encodingLength(value){const length=0;if(null==value)return 0;const type=getType(value);switch(type){case"buffer":return digitCount(value.length)+1+value.length;case"arraybufferview":return arrayBufferLength(value);case"string":return stringLength(value);case"array":case"set":return listLength(value);case"number":return 1+digitCount(_Mathfloor(value))+1;case"bigint":return 1+value.toString().length+1;case"object":return objectLength(value);case"map":return mapLength(value);default:throw new TypeError(`Unsupported value of type "${type}"`);}}const{digitCount,getType}=require("./util.js");module.exports=encodingLength}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":48,buffer:101}],47:[function(require,module,exports){const bencode=module.exports;bencode.encode=require("./encode.js"),bencode.decode=require("./decode.js"),bencode.byteLength=bencode.encodingLength=require("./encoding-length.js")},{"./decode.js":44,"./encode.js":45,"./encoding-length.js":46}],48:[function(require,module,exports){(function(Buffer){(function(){const util=module.exports;util.digitCount=function digitCount(value){var _Mathlog=Math.log10;const sign=0>value?1:0;return value=_Mathabs(+(value||1)),_Mathfloor(_Mathlog(value))+1+sign},util.getType=function getType(value){return Buffer.isBuffer(value)?"buffer":ArrayBuffer.isView(value)?"arraybufferview":Array.isArray(value)?"array":value instanceof Number?"number":value instanceof Boolean?"boolean":value instanceof Set?"set":value instanceof Map?"map":value instanceof String?"string":value instanceof ArrayBuffer?"arraybuffer":typeof value}}).call(this)}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":193}],49:[function(require,module,exports){function composeRange(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1<cur.length?`${cur[0]}-${cur[cur.length-1]}`:`${cur[0]}`)}function parseRange(range){const generateRange=(start,end=start)=>Array.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur,idx,arr)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=composeRange},{}],50:[function(require,module,exports){module.exports=function(haystack,needle,comparator,low,high){var mid,cmp;if(void 0===low)low=0;else if(low|=0,0>low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high<low||high>=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0<cmp)high=mid-1;else return mid;return~low}},{}],51:[function(require,module,exports){"use strict";function getByteSize(num){var out=num>>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j<this.buffer.length&&!!(this.buffer[j]&128>>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length<j+1){var length=_Mathmax(j+1,_Mathmin(2*this.buffer.length,this.grow));if(length<=this.grow){var newBuffer=new Uint8Array(length);newBuffer.set(this.buffer),this.buffer=newBuffer}}this.buffer[j]|=128>>i%8}else j<this.buffer.length&&(this.buffer[j]&=~(128>>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i<end;i++)fn(!!(byte&y),i),y=1==y?(byte=this.buffer[++j],128):y>>1},BitField}();exports.default=BitField},{}],52:[function(require,module,exports){(function(process,Buffer){(function(){function noop(){}function sha1(buf){return Buffer.from(simpleSha1.sync(buf),"hex")}function createGetResponse(id,token,value){const r={id,token,v:value.v};return value.sig&&(r.sig=value.sig,r.k=value.k,"number"==typeof value.seq&&(r.seq=value.seq)),r}function encodePeer(host,port){const buf=Buffer.allocUnsafe(6),ip=host.split(".");for(let i=0;4>i;i++)buf[i]=parseInt(ip[i]||0,10);return buf.writeUInt16BE(port,4),buf}function decodePeers(buf){const peers=[];try{for(let i=0;i<buf.length;i++){const port=buf[i].readUInt16BE(4);port&&peers.push({host:parseIp(buf[i],0),port})}}catch(err){}return peers}function parseIp(buf,offset){return`${buf[offset++]}.${buf[offset++]}.${buf[offset++]}.${buf[offset++]}`}function encodeSigData(msg){const ref={seq:msg.seq||0,v:msg.v};return msg.salt&&(ref.salt=msg.salt),bencode.encode(ref).slice(1,-1)}function toNode(node){return{host:node.host,port:node.port}}function toBuffer(str){if(Buffer.isBuffer(str))return str;if(ArrayBuffer.isView(str))return Buffer.from(str.buffer,str.byteOffset,str.byteLength);if("string"==typeof str)return Buffer.from(str,"hex");throw new Error("Pass a buffer or a string")}const bencode=require("bencode"),debug=require("debug")("bittorrent-dht"),KBucket=require("k-bucket"),krpc=require("k-rpc"),low=require("last-one-wins"),LRU=require("lru"),randombytes=require("randombytes"),records=require("record-cache"),simpleSha1=require("simple-sha1"),{EventEmitter}=require("events"),ROTATE_INTERVAL=300000,BUCKET_OUTDATED_TIMESPAN=900000;class DHT extends EventEmitter{constructor(opts={}){function ping(opts,cb){const older=opts.older,swap=opts.swap;self._debug("received ping",older),self._checkNodes(older,!1,(_,deadNode)=>deadNode?(self._debug("swaping dead node with newer",deadNode),swap(deadNode),cb()):void(self._debug("no node added, all other nodes ok"),cb()))}function onlistening(){self.listening=!0,self._debug("listening %d",self.address().port),self.updateBucketTimestamp(),self._setBucketCheckInterval(),self.emit("listening")}function onquery(query,peer){self._onquery(query,peer)}function rotateSecrets(){self._rotateSecrets()}function bootstrap(){self.destroyed||self._bootstrap(!1!==opts.bootstrap)}function onwarning(err){self.emit("warning",err)}function onerror(err){self.emit("error",err)}function onnode(node){self.emit("node",node)}super(),this._tables=new LRU({maxAge:ROTATE_INTERVAL,max:opts.maxTables||1e3}),this._values=new LRU(opts.maxValues||1e3),this._peers=records({maxAge:opts.maxAge||0,maxSize:opts.maxPeers||1e4}),this._secrets=null,this._hash=opts.hash||sha1,this._hashLength=this._hash(Buffer.from("")).length,this._rpc=opts.krpc||krpc(Object.assign({idLength:this._hashLength},opts)),this._rpc.on("query",onquery),this._rpc.on("node",onnode),this._rpc.on("warning",onwarning),this._rpc.on("error",onerror),this._rpc.on("listening",onlistening),this._rotateSecrets(),this._verify=opts.verify||null,this._host=opts.host||null,this._interval=setInterval(rotateSecrets,ROTATE_INTERVAL),this._runningBucketCheck=!1,this._bucketCheckTimeout=null,this._bucketOutdatedTimeSpan=opts.timeBucketOutdated||BUCKET_OUTDATED_TIMESPAN,this.listening=!1,this.destroyed=!1,this.nodeId=this._rpc.id,this.nodes=this._rpc.nodes;const onping=low(ping);this._rpc.on("ping",(older,swap)=>{onping({older,swap})}),process.nextTick(bootstrap),this._debug("new DHT %s",this.nodeId);const self=this}_setBucketCheckInterval(){function checkBucket(){const diff=Date.now()-self._rpc.nodes.metadata.lastChange;return diff<self._bucketOutdatedTimeSpan?queueNext():void self._pingAll(()=>{self.destroyed||(1>self.nodes.toArray().length&&self._bootstrap(!0),queueNext())})}function queueNext(){if(self._runningBucketCheck&&!self.destroyed){const nextTimeout=_Mathfloor(Math.random()*interval+30000);self._bucketCheckTimeout=setTimeout(checkBucket,nextTimeout)}}const self=this,interval=60000;this._runningBucketCheck=!0,queueNext()}_pingAll(cb){this._checkAndRemoveNodes(this.nodes.toArray(),cb)}removeBucketCheckInterval(){this._runningBucketCheck=!1,clearTimeout(this._bucketCheckTimeout)}updateBucketTimestamp(){this._rpc.nodes.metadata.lastChange=Date.now()}_checkAndRemoveNodes(nodes,cb){const self=this;this._checkNodes(nodes,!0,(_,node)=>{node&&self.removeNode(node.id),cb(null,node)})}_checkNodes(nodes,force,cb){function test(acc){let current=null;for(;acc.length&&(current=acc.pop(),current.id&&!force)&&!(1e4<Date.now()-(current.seen||0));)current=null;return current?void self._sendPing(current,err=>err?void cb(null,current):(self.updateBucketTimestamp(),test(acc))):cb(null)}const self=this;test(nodes)}addNode(node){const self=this;if(node.id){node.id=toBuffer(node.id);const old=!!this._rpc.nodes.get(node.id);return this._rpc.nodes.add(node),void(old||(this.emit("node",node),this.updateBucketTimestamp()))}this._sendPing(node,(_,node)=>{node&&self.addNode(node)})}removeNode(id){this._rpc.nodes.remove(toBuffer(id))}_sendPing(node,cb){const self=this,expectedId=node.id;this._rpc.query(node,{q:"ping"},(err,pong,node)=>err?cb(err):pong.r&&pong.r.id&&Buffer.isBuffer(pong.r.id)&&pong.r.id.length===self._hashLength?Buffer.isBuffer(expectedId)&&!expectedId.equals(pong.r.id)?cb(new Error("Unexpected node id")):void(self.updateBucketTimestamp(),cb(null,{id:pong.r.id,host:node.host||node.address,port:node.port})):cb(new Error("Bad reply")))}toJSON(){const self=this,values={};return Object.keys(this._values.cache).forEach(key=>{const value=self._values.cache[key].value;values[key]={v:value.v.toString("hex"),id:value.id.toString("hex")},null!=value.seq&&(values[key].seq=value.seq),null!=value.sig&&(values[key].sig=value.sig.toString("hex")),null!=value.k&&(values[key].k=value.k.toString("hex"))}),{nodes:this._rpc.nodes.toArray().map(toNode),values}}put(opts,cb){(Buffer.isBuffer(opts)||"string"==typeof opts)&&(opts={v:opts});const isMutable=!!opts.k;if(opts.v===void 0)throw new Error("opts.v not given");if(1e3<=opts.v.length)throw new Error("v must be less than 1000 bytes in put()");if(isMutable&&void 0!==opts.cas&&"number"!=typeof opts.cas)throw new Error("opts.cas must be an integer if provided");if(isMutable&&32!==opts.k.length)throw new Error("opts.k ed25519 public key must be 32 bytes");if(isMutable&&"function"!=typeof opts.sign&&!Buffer.isBuffer(opts.sig))throw new Error("opts.sign function or options.sig signature is required for mutable put");if(isMutable&&opts.salt&&64<opts.salt.length)throw new Error("opts.salt is > 64 bytes long");if(isMutable&&void 0===opts.seq)throw new Error("opts.seq not provided for a mutable update");if(isMutable&&"number"!=typeof opts.seq)throw new Error("opts.seq not an integer");return this._put(opts,cb)}_put(opts,cb){cb||(cb=noop);const isMutable=!!opts.k,v="string"==typeof opts.v?Buffer.from(opts.v):opts.v,key=isMutable?this._hash(opts.salt?Buffer.concat([opts.k,opts.salt]):opts.k):this._hash(bencode.encode(v)),table=this._tables.get(key.toString("hex"));if(!table)return this._preput(key,opts,cb);const message={q:"put",a:{id:this._rpc.id,token:null,v}};return isMutable?("number"==typeof opts.cas&&(message.a.cas=opts.cas),opts.salt&&(message.a.salt=opts.salt),message.a.k=opts.k,message.a.seq=opts.seq,"function"==typeof opts.sign?message.a.sig=opts.sign(encodeSigData(message.a)):Buffer.isBuffer(opts.sig)&&(message.a.sig=opts.sig)):this._values.set(key.toString("hex"),message.a),this._rpc.queryAll(table.closest(key),message,null,(err,n)=>err?cb(err,key,n):void cb(null,key,n)),key}_preput(key,opts,cb){const self=this;return this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},null,(err,n)=>err?cb(err):void self.put(opts,cb)),key}get(key,opts,cb){function done(err){return err?cb(err):void cb(null,value)}function onreply(message){const r=message.r;if(!r||!r.v)return!0;const isMutable=r.k||r.sig;if(opts.salt&&(r.salt=Buffer.from(opts.salt)),isMutable){if(!verify||!r.sig||!r.k)return!0;if(!verify(r.sig,encodeSigData(r),r.k))return!0;hash(r.salt?Buffer.concat([r.k,r.salt]):r.k).equals(key)&&(!value||r.seq>value.seq)&&(value=r)}else if(hash(bencode.encode(r.v)).equals(key))return value=r,!1;return!0}key=toBuffer(key),"function"==typeof opts&&(cb=opts,opts=null),opts||(opts={});const verify=opts.verify||this._verify,hash=this._hash;let value=this._values.get(key.toString("hex"))||null;return value&&!1!==opts.cache?(value=createGetResponse(this._rpc.id,null,value),process.nextTick(done)):void this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},onreply,done)}announce(infoHash,port,cb){if("function"==typeof port)return this.announce(infoHash,0,port);infoHash=toBuffer(infoHash),cb||(cb=noop);const table=this._tables.get(infoHash.toString("hex"));if(!table)return this._preannounce(infoHash,port,cb);if(this._host){const dhtPort=this.listening?this.address().port:0;this._addPeer({host:this._host,port:port||dhtPort},infoHash,{host:this._host,port:dhtPort})}const message={q:"announce_peer",a:{id:this._rpc.id,token:null,info_hash:infoHash,port,implied_port:port?0:1}};this._debug("announce %s %d",infoHash,port),this._rpc.queryAll(table.closest(infoHash),message,null,cb)}_preannounce(infoHash,port,cb){const self=this;this.lookup(infoHash,err=>self.destroyed?cb(new Error("dht is destroyed")):err?cb(err):void self.announce(infoHash,port,cb))}lookup(infoHash,cb){function emit(values,from){values||(values=self._peers.get(infoHash.toString("hex"),100));const peers=decodePeers(values);for(let i=0;i<peers.length;i++)self.emit("peer",peers[i],infoHash,from||null)}function onreply(message,node){return!aborted&&void(message.r.values&&emit(message.r.values,node))}infoHash=toBuffer(infoHash),cb||(cb=noop);const self=this;let aborted=!1;return this._debug("lookup %s",infoHash),process.nextTick(emit),this._closest(infoHash,{q:"get_peers",a:{id:this._rpc.id,info_hash:infoHash}},onreply,cb),function abort(){aborted=!0}}address(){return this._rpc.address()}listen(...args){this._rpc.bind(...args)}destroy(cb){if(this.destroyed)return void(cb&&process.nextTick(cb));this.destroyed=!0;const self=this;clearInterval(this._interval),this.removeBucketCheckInterval(),this._peers.destroy(),this._debug("destroying"),this._rpc.destroy(()=>{self.emit("close"),cb&&cb()})}_onquery(query,peer){if(void 0!==query.q&&null!==query.q){const q=query.q.toString();if(this._debug("received %s query from %s:%d",q,peer.address,peer.port),!!query.a)return"ping"===q?this._rpc.response(peer,query,{id:this._rpc.id}):"find_node"===q?this._onfindnode(query,peer):"get_peers"===q?this._ongetpeers(query,peer):"announce_peer"===q?this._onannouncepeer(query,peer):"get"===q?this._onget(query,peer):"put"===q?this._onput(query,peer):void 0}}_onfindnode(query,peer){const target=query.a.target;if(!target)return this._rpc.error(peer,query,[203,"`find_node` missing required `a.target` field"]);this.emit("find_node",target);const nodes=this._rpc.nodes.closest(target);this._rpc.response(peer,query,{id:this._rpc.id},nodes)}_ongetpeers(query,peer){const host=peer.address||peer.host,infoHash=query.a.info_hash;if(!infoHash)return this._rpc.error(peer,query,[203,"`get_peers` missing required `a.info_hash` field"]);this.emit("get_peers",infoHash);const r={id:this._rpc.id,token:this._generateToken(host)},peers=this._peers.get(infoHash.toString("hex"));peers.length?(r.values=peers,this._rpc.response(peer,query,r)):this._rpc.response(peer,query,r,this._rpc.nodes.closest(infoHash))}_onannouncepeer(query,peer){const host=peer.address||peer.host,port=query.a.implied_port?peer.port:query.a.port;if(!port||"number"!=typeof port||0>=port||65535<port)return;const infoHash=query.a.info_hash,token=query.a.token;return infoHash&&token?this._validateToken(host,token)?void(this.emit("announce_peer",infoHash,{host,port:peer.port}),this._addPeer({host,port},infoHash,{host,port:peer.port}),this._rpc.response(peer,query,{id:this._rpc.id})):this._rpc.error(peer,query,[203,"cannot `announce_peer` with bad token"]):void 0}_addPeer(peer,infoHash,from){this._peers.add(infoHash.toString("hex"),encodePeer(peer.host,peer.port)),this.emit("announce",peer,infoHash,from)}_onget(query,peer){const host=peer.address||peer.host,target=query.a.target;if(!target)return;const token=this._generateToken(host),value=this._values.get(target.toString("hex"));if(this.emit("get",target,value),!value){const nodes=this._rpc.nodes.closest(target);this._rpc.response(peer,query,{id:this._rpc.id,token},nodes)}else this._rpc.response(peer,query,createGetResponse(this._rpc.id,token,value))}_onput(query,peer){const host=peer.address||peer.host,a=query.a;if(!a)return;const v=query.a.v;if(!v)return;const id=query.a.id;if(!id)return;const token=a.token;if(!token)return;if(!this._validateToken(host,token))return this._rpc.error(peer,query,[203,"cannot `put` with bad token"]);if(1e3<v.length)return this._rpc.error(peer,query,[205,"data payload too large"]);const isMutable=!!(a.k||a.sig);if(isMutable&&!a.k&&!a.sig)return;const key=isMutable?this._hash(a.salt?Buffer.concat([a.k,a.salt]):a.k):this._hash(bencode.encode(v)),keyHex=key.toString("hex");if(this.emit("put",key,v),isMutable){if(!this._verify)return this._rpc.error(peer,query,[400,"verification not supported"]);if(!this._verify(a.sig,encodeSigData(a),a.k))return;const prev=this._values.get(keyHex);if(prev&&"number"==typeof a.cas&&prev.seq!==a.cas)return this._rpc.error(peer,query,[301,"CAS mismatch, re-read and try again"]);if(prev&&"number"==typeof prev.seq&&!(a.seq>prev.seq))return this._rpc.error(peer,query,[302,"sequence number less than current"]);this._values.set(keyHex,{v,k:a.k,salt:a.salt,sig:a.sig,seq:a.seq,id})}else this._values.set(keyHex,{v,id});this._rpc.response(peer,query,{id:this._rpc.id})}_bootstrap(populate){function ready(){self.ready||(self._debug("emit ready"),self.ready=!0,self.emit("ready"))}const self=this;return populate?void this._rpc.populate(self._rpc.id,{q:"find_node",a:{id:self._rpc.id,target:self._rpc.id}},ready):process.nextTick(ready)}_closest(target,message,onmessage,cb){function done(err,n){return err?cb(err):void(self._tables.set(target.toString("hex"),table),self._debug("visited %d nodes",n),cb(null,n))}function onreply(message,node){return!message.r||(message.r.token&&message.r.id&&Buffer.isBuffer(message.r.id)&&message.r.id.length===self._hashLength&&(self._debug("found node %s (target: %s)",message.r.id,target),table.add({id:message.r.id,host:node.host||node.address,port:node.port,token:message.r.token})),!onmessage||onmessage(message,node))}const self=this,table=new KBucket({localNodeId:target,numberOfNodesPerKBucket:this._rpc.k});this._rpc.closest(target,message,onreply,done)}_debug(){if(debug.enabled){const args=[].slice.call(arguments);args[0]=`[${this.nodeId.toString("hex").substring(0,7)}] ${args[0]}`;for(let i=1;i<args.length;i++)Buffer.isBuffer(args[i])&&(args[i]=args[i].toString("hex"));debug(...args)}}_validateToken(host,token){const tokenA=this._generateToken(host,this._secrets[0]),tokenB=this._generateToken(host,this._secrets[1]);return token.equals(tokenA)||token.equals(tokenB)}_generateToken(host,secret){return secret||(secret=this._secrets[0]),this._hash(Buffer.concat([Buffer.from(host),secret]))}_rotateSecrets(){this._secrets?(this._secrets[1]=this._secrets[0],this._secrets[0]=randombytes(this._hashLength)):this._secrets=[randombytes(this._hashLength),randombytes(this._hashLength)]}}module.exports=DHT}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{_process:246,bencode:47,buffer:101,debug:122,events:156,"k-bucket":199,"k-rpc":201,"last-one-wins":202,lru:207,randombytes:262,"record-cache":282,"simple-sha1":303}],53:[function(require,module,exports){/*! bittorrent-lsd. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */const dgram=require("dgram"),EventEmitter=require("events").EventEmitter,debug=require("debug")("bittorrent-lsd"),ANNOUNCE_INTERVAL=3e5,LSD_HOST="239.192.152.143",LSD_PORT=6771;class LSD 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(!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="string"==typeof opts.port?opts.port:opts.port.toString(),this.cookie=`bittorrent-lsd-${this.peerId}`,this.destroyed=!1,this.annouceIntervalId=null,this.server=dgram.createSocket({type:"udp4",reuseAddr:!0});const onListening=()=>{debug("listening");try{this.server.addMembership(LSD_HOST)}catch(err){this.emit("warning",err)}},onMessage=(msg,rinfo)=>{debug("message",msg.toString(),`${rinfo.address}:${rinfo.port}`);const parsedAnnounce=this._parseAnnounce(msg.toString());null===parsedAnnounce||parsedAnnounce.cookie===this.cookie||parsedAnnounce.infoHash.forEach(infoHash=>{this.emit("peer",`${rinfo.address}:${parsedAnnounce.port}`,infoHash)})},onError=err=>{this.emit("error",err)};this.server.on("listening",onListening),this.server.on("message",onMessage),this.server.on("error",onError)}_parseAnnounce(announce){const checkHost=host=>/^(239.192.152.143|\[ff15::efc0:988f]):6771$/.test(host),checkPort=port=>/^\d+$/.test(port),checkInfoHash=infoHash=>/^[0-9a-fA-F]{40}$/.test(infoHash);debug("parse announce",announce);const sections=announce.split("\r\n");if("BT-SEARCH * HTTP/1.1"!==sections[0])return this.emit("warning","Invalid LSD announce (header)"),null;const host=sections[1].split("Host: ")[1];if(!checkHost(host))return this.emit("warning","Invalid LSD announce (host)"),null;const port=sections[2].split("Port: ")[1];if(!checkPort(port))return this.emit("warning","Invalid LSD announce (port)"),null;const infoHash=sections.filter(section=>section.includes("Infohash: ")).map(section=>section.split("Infohash: ")[1]).filter(infoHash=>checkInfoHash(infoHash));if(0===infoHash.length)return this.emit("warning","Invalid LSD announce (infoHash)"),null;const cookie=sections.filter(section=>section.includes("cookie: ")).map(section=>section.split("cookie: ")[1]).reduce((acc,cur)=>cur,null);return{host:host,port:port,infoHash:infoHash,cookie:cookie}}destroy(cb){this.destroyed||(this.destroyed=!0,debug("destroy"),clearInterval(this.annouceIntervalId),this.server.close(cb))}start(){debug("start"),this.server.bind(LSD_PORT),this._announce(),this.annouceIntervalId=setInterval(()=>{this._announce()},ANNOUNCE_INTERVAL)}_announce(){debug("send announce");const host=`${LSD_HOST}:${LSD_PORT}`,announce=`BT-SEARCH * HTTP/1.1\r\nHost: ${host}\r\nPort: ${this.port}\r\nInfohash: ${this.infoHash}\r\ncookie: ${this.cookie}\r\n\r\n\r\n`;this.server.send(announce,LSD_PORT,LSD_HOST)}}module.exports=LSD},{debug:122,dgram:106,events:156}],54:[function(require,module,exports){(function(Buffer){(function(){function xor(a,b){for(let len=a.length;len--;)a[len]^=b[len];return a}/*! bittorrent-protocol. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,crypto=require("crypto"),debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),sha1=require("simple-sha1"),speedometer=require("speedometer"),stream=require("readable-stream"),RC4=require("rc4"),BITFIELD_GROW=4e5,KEEP_ALIVE_TIMEOUT=55e3,ALLOWED_FAST_SET_MAX_LENGTH=100,MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0],MESSAGE_HAVE_ALL=Buffer.from([0,0,0,1,14]),MESSAGE_HAVE_NONE=Buffer.from([0,0,0,1,15]),DH_PRIME="ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563",DH_GENERATOR=2,VC=Buffer.from([0,0,0,0,0,0,0,0]),CRYPTO_PROVIDE=Buffer.from([0,0,1,2]),CRYPTO_SELECT=Buffer.from([0,0,0,2]);class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class HaveAllBitField{constructor(){this.buffer=new Uint8Array}get(index){return!0}set(index){}}class Wire extends stream.Duplex{constructor(type=null,retries=0,peEnabled=!1){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=type,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:BITFIELD_GROW}),this.extensions={},this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this.hasFast=!1,this.allowedFastSet=[],this.peerAllowedFastSet=[],this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=peEnabled,peEnabled?(this._dh=crypto.createDiffieHellman(DH_PRIME,"hex",DH_GENERATOR),this._myPubKey=this._dh.generateKeys("hex")):this._myPubKey=null,this._peerPubKey=null,this._sharedSecret=null,this._peerCryptoProvide=[],this._cryptoHandshakeDone=!1,this._cryptoSyncPattern=null,this._waitMaxBytes=null,this._encryptionMethod=null,this._encryptGenerator=null,this._decryptGenerator=null,this._setGenerators=!1,this.once("finish",()=>this._onFinish()),this.on("finish",this._onFinish),this._debug("type:",this.type),"tcpIncoming"===this.type&&this._peEnabled?this._determineHandshakeType():"tcpOutgoing"===this.type&&this._peEnabled&&0===retries?this._parsePe2():this._parseHandshake(null)}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},KEEP_ALIVE_TIMEOUT))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._resetTimeout(!0)}destroy(){if(!this.destroyed)return this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end(),this}end(...args){return this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}sendPe1(){if(this._peEnabled){const padALen=_Mathfloor(513*Math.random()),padA=randombytes(padALen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padA]))}}sendPe2(){const padBLen=_Mathfloor(513*Math.random()),padB=randombytes(padBLen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padB]))}sendPe3(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex"),hash2Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req2")+infoHash,"hex")),"hex"),hash3Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),"hex"),hashesXorBuffer=xor(hash2Buffer,hash3Buffer),padCLen=randombytes(2).readUInt16BE(0)%512,padCBuffer=randombytes(padCLen);let vcAndProvideBuffer=Buffer.alloc(14+padCLen+2);VC.copy(vcAndProvideBuffer),CRYPTO_PROVIDE.copy(vcAndProvideBuffer,8),vcAndProvideBuffer.writeInt16BE(padCLen,12),padCBuffer.copy(vcAndProvideBuffer,14),vcAndProvideBuffer.writeInt16BE(0,14+padCLen),vcAndProvideBuffer=this._encryptHandshake(vcAndProvideBuffer),this._push(Buffer.concat([hash1Buffer,hashesXorBuffer,vcAndProvideBuffer]))}sendPe4(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const padDLen=randombytes(2).readUInt16BE(0)%512,padDBuffer=randombytes(padDLen);let vcAndSelectBuffer=Buffer.alloc(14+padDLen);VC.copy(vcAndSelectBuffer),CRYPTO_SELECT.copy(vcAndSelectBuffer,8),vcAndSelectBuffer.writeInt16BE(padDLen,12),padDBuffer.copy(vcAndSelectBuffer,14),vcAndSelectBuffer=this._encryptHandshake(vcAndSelectBuffer),this._push(vcAndSelectBuffer),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),this._infoHash=infoHashBuffer,20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);this.extensions={extended:!0,dht:!!(extensions&&extensions.dht),fast:!!(extensions&&extensions.fast)},reserved[5]|=16,this.extensions.dht&&(reserved[7]|=1),this.extensions.fast&&(reserved[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(MESSAGE_CHOKE),this.hasFast)for(let allowedCount=0;this.peerRequests.length>allowedCount;){const request=this.peerRequests[allowedCount];this.allowedFastSet.includes(request.piece)?++allowedCount:this.reject(request.piece,request.offset,request.length)}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking&&!(this.hasFast&&this.peerAllowedFastSet.includes(index))?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),!this._timeout&&this._resetTimeout(!0),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this._message(7,[index,offset],buffer),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}suggest(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("suggest %d",index),this._message(13,[index],null)}haveAll(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-all"),this._push(MESSAGE_HAVE_ALL)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(MESSAGE_HAVE_NONE)}reject(index,offset,length){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this._message(16,[index,offset,length],null)}allowedFast(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("allowed-fast %d",index),this.allowedFastSet.includes(index)||this.allowedFastSet.push(index),this._message(17,[index],null)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}setEncrypt(sharedSecret,infoHash){let encryptKey,decryptKey,encryptKeyBuf,encryptKeyIntArray,decryptKeyBuf,decryptKeyIntArray;switch(this.type){case"tcpIncoming":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;case"tcpOutgoing":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;default:return!1;}for(let i=0;1024>i;i++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;i<numbers.length;i++)buffer.writeUInt32BE(numbers[i],5+4*i);this._push(buffer),data&&this._push(data)}_push(data){if(!this._finished)return 2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._encrypt(data)),this.push(data)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onPe1(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}_onPe3(hashesXorBuffer){const hash3=sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),sKeyHash=xor(Buffer.from(hash3,"hex"),hashesXorBuffer).toString("hex");this.emit("pe3",sKeyHash)}_onPe3Encrypted(vcBuffer,peerProvideBuffer){if(!vcBuffer.equals(VC))return this._debug("Error: verification constant did not match"),void this.destroy();for(const provideByte of peerProvideBuffer.values())0!==provideByte&&this._peerCryptoProvide.push(provideByte);this._peerCryptoProvide.includes(2)?this._encryptionMethod=2:(this._debug("Error: RC4 encryption method not provided by peer"),this.destroy())}_onPe4(peerSelectBuffer){this._encryptionMethod=peerSelectBuffer.readUInt8(3),CRYPTO_PROVIDE.includes(this._encryptionMethod)||(this._debug("Error: peer selected invalid crypto method"),this.destroy()),this._cryptoHandshakeDone=!0,this._debug("crypto handshake done"),this.emit("pe4")}_onHandshake(infoHashBuffer,peerIdBuffer,extensions){const infoHash=infoHashBuffer.toString("hex"),peerId=peerIdBuffer.toString("hex");for(const name in this._debug("got handshake i=%s p=%s exts=%o",infoHash,peerId,extensions),this.peerId=peerId,this.peerIdBuffer=peerIdBuffer,this.peerExtensions=extensions,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",infoHash,peerId,extensions),this._ext)this._ext[name].onHandshake(infoHash,peerId,extensions);extensions.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){if(this.peerChoking=!0,this._debug("got choke"),this.emit("choke"),!this.hasFast)for(;this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(index){this.peerPieces.get(index)||(this._debug("got have %d",index),this.peerPieces.set(index,!0),this.emit("have",index))}_onBitField(buffer){this.peerPieces=new BitField(buffer),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(index,offset,length){if(this.amChoking&&!(this.hasFast&&this.allowedFastSet.includes(index)))return void(this.hasFast&&this.reject(index,offset,length));this._debug("got request index=%d offset=%d length=%d",index,offset,length);const respond=(err,buffer)=>request===this._pull(this.peerRequests,index,offset,length)?err?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message),void(this.hasFast&&this.reject(index,offset,length))):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onSuggest(index){return this.hasFast?void(this._debug("got suggest %d",index),this.emit("suggest",index)):(this._debug("Error: got suggest whereas fast extension is disabled"),void this.destroy())}_onHaveAll(){return this.hasFast?void(this._debug("got have-all"),this.peerPieces=new HaveAllBitField,this.emit("have-all")):(this._debug("Error: got have-all whereas fast extension is disabled"),void this.destroy())}_onHaveNone(){return this.hasFast?void(this._debug("got have-none"),this.emit("have-none")):(this._debug("Error: got have-none whereas fast extension is disabled"),void this.destroy())}_onReject(index,offset,length){return this.hasFast?void(this._debug("got reject index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was rejected"),null),this.emit("reject",index,offset,length)):(this._debug("Error: got reject whereas fast extension is disabled"),void this.destroy())}_onAllowedFast(index){return this.hasFast?void(this._debug("got allowed-fast %d",index),!this.peerAllowedFastSet.includes(index)&&this.peerAllowedFastSet.push(index),this.peerAllowedFastSet.length>ALLOWED_FAST_SET_MAX_LENGTH&&this.peerAllowedFastSet.shift(),this.emit("allowed-fast",index)):(this._debug("Error: got allowed-fast whereas fast extension is disabled"),void this.destroy())}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;if(this.peerExtendedHandshake=info,"object"==typeof info.m)for(const name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(const name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._decrypt(data)),this._bufferSize+=data.length,this._buffer.push(data),1<this._buffer.length&&(this._buffer=[Buffer.concat(this._buffer,this._bufferSize)]),this._cryptoSyncPattern){const index=this._buffer[0].indexOf(this._cryptoSyncPattern);if(-1!==index)this._buffer[0]=this._buffer[0].slice(index+this._cryptoSyncPattern.length),this._bufferSize-=index+this._cryptoSyncPattern.length,this._cryptoSyncPattern=null;else if(this._bufferSize+data.length>this._waitMaxBytes+this._cryptoSyncPattern.length)return this._debug("Error: could not resynchronize"),void this.destroy()}for(;this._bufferSize>=this._parserSize&&!this._cryptoSyncPattern;)if(0===this._parserSize)this._parser(Buffer.from([]));else{const buffer=this._buffer[0];this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._resetTimeout(!this.peerChoking&&!this._finished),request.callback(err,buffer))}_resetTimeout(setAgain){if(!setAgain||!this._timeoutMs||!this.requests.length)return clearTimeout(this._timeout),this._timeout=null,void(this._timeoutExpiresAt=null);const timeoutExpiresAt=Date.now()+this._timeoutMs;if(this._timeout){if(timeoutExpiresAt-this._timeoutExpiresAt<.05*this._timeoutMs)return;clearTimeout(this._timeout)}this._timeoutExpiresAt=timeoutExpiresAt,this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref()}_parse(size,parser){this._parserSize=size,this._parser=parser}_parseUntil(pattern,maxBytes){this._cryptoSyncPattern=pattern,this._waitMaxBytes=maxBytes}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0<length?this._parse(length,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(buffer){switch(this._parse(4,this._onMessageLength),buffer[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(buffer.readUInt32BE(1));case 5:return this._onBitField(buffer.slice(1));case 6:return this._onRequest(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 7:return this._onPiece(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.slice(9));case 8:return this._onCancel(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 9:return this._onPort(buffer.readUInt16BE(1));case 13:return this._onSuggest(buffer.readUInt32BE(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 17:return this._onAllowedFast(buffer.readUInt32BE(1));case 20:return this._onExtended(buffer.readUInt8(1),buffer.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",buffer);}}_determineHandshakeType(){this._parse(1,pstrLenBuffer=>{const pstrlen=pstrLenBuffer.readUInt8(0);19===pstrlen?this._parse(pstrlen+48,this._onHandshakeBuffer):this._parsePe1(pstrLenBuffer)})}_parsePe1(pubKeyPrefix){this._parse(95,pubKeySuffix=>{this._onPe1(Buffer.concat([pubKeyPrefix,pubKeySuffix])),this._parsePe3()})}_parsePe2(){this._parse(96,pubKey=>{for(this._onPe2(pubKey);!this._setGenerators;);this._parsePe4()})}_parsePe3(){const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex");this._parseUntil(hash1Buffer,512),this._parse(20,buffer=>{for(this._onPe3(buffer);!this._setGenerators;);this._parsePe3Encrypted()})}_parsePe3Encrypted(){this._parse(14,buffer=>{const vcBuffer=this._decryptHandshake(buffer.slice(0,8)),peerProvideBuffer=this._decryptHandshake(buffer.slice(8,12)),padCLen=this._decryptHandshake(buffer.slice(12,14)).readUInt16BE(0);this._parse(padCLen,padCBuffer=>{padCBuffer=this._decryptHandshake(padCBuffer),this._parse(2,iaLenBuf=>{const iaLen=this._decryptHandshake(iaLenBuf).readUInt16BE(0);this._parse(iaLen,iaBuffer=>{iaBuffer=this._decryptHandshake(iaBuffer),this._onPe3Encrypted(vcBuffer,peerProvideBuffer,padCBuffer,iaBuffer);const pstrlen=iaLen?iaBuffer.readUInt8(0):null,protocol=iaLen?iaBuffer.slice(1,20):null;19===pstrlen&&"BitTorrent protocol"===protocol.toString()?this._onHandshakeBuffer(iaBuffer.slice(1)):this._parseHandshake()})})})})}_parsePe4(){const vcBufferEncrypted=this._decryptHandshake(VC);this._parseUntil(vcBufferEncrypted,512),this._parse(6,buffer=>{const peerSelectBuffer=this._decryptHandshake(buffer.slice(0,4)),padDLen=this._decryptHandshake(buffer.slice(4,6)).readUInt16BE(0);this._parse(padDLen,padDBuf=>{this._decryptHandshake(padDBuf),this._onPe4(peerSelectBuffer),this._parseHandshake(null)})})}_parseHandshake(){this._parse(1,buffer=>{const pstrlen=buffer.readUInt8(0);return 19===pstrlen?void this._parse(pstrlen+48,this._onHandshakeBuffer):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",pstrlen.toString()),void this.end())})}_onHandshakeBuffer(handshake){const protocol=handshake.slice(0,19);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(19),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),fast:!!(4&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i<requests.length;i++){const req=requests[i];if(req.piece===piece&&req.offset===offset&&req.length===length)return arrayRemove(requests,i),req}return null}_encryptHandshake(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_encrypt(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator||2!==this._encryptionMethod)return crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_decryptHandshake(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_decrypt(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator||2!==this._encryptionMethod)return decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_utfToHex(str){return Buffer.from(str,"utf8").toString("hex")}}module.exports=Wire}).call(this)}).call(this,require("buffer").Buffer)},{bencode:47,bitfield:51,buffer:101,crypto:121,debug:122,randombytes:262,rc4:266,"readable-stream":281,"simple-sha1":303,speedometer:310,"unordered-array-remove":331}],55:[function(require,module,exports){(function(process,Buffer){(function(){const debug=require("debug")("bittorrent-tracker:client"),EventEmitter=require("events"),once=require("once"),parallel=require("run-parallel"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),common=require("./lib/common"),HTTPTracker=require("./lib/client/http-tracker"),UDPTracker=require("./lib/client/udp-tracker"),WebSocketTracker=require("./lib/client/websocket-tracker");class Client 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(!opts.announce)throw new Error("Option `announce` 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._peerIdBuffer=Buffer.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._infoHashBuffer=Buffer.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),debug("new client %s",this.infoHash),this.destroyed=!1,this._port=opts.port,this._getAnnounceOpts=opts.getAnnounceOpts,this._rtcConfig=opts.rtcConfig,this._userAgent=opts.userAgent,this._proxyOpts=opts.proxyOpts,this._wrtc="function"==typeof opts.wrtc?opts.wrtc():opts.wrtc;let announce="string"==typeof opts.announce?[opts.announce]:null==opts.announce?[]:opts.announce;announce=announce.map(announceUrl=>(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{queueMicrotask(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=common.parseUrl(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535<port)return nextTickWarn(new Error(`Invalid tracker port: ${announceUrl}`)),null;const protocol=parsedUrl.protocol;return("http:"===protocol||"https:"===protocol)&&"function"==typeof HTTPTracker?new HTTPTracker(this,announceUrl):"udp:"===protocol&&"function"==typeof UDPTracker?new UDPTracker(this,announceUrl):("ws:"===protocol||"wss:"===protocol)&&webrtcSupport?"ws:"===protocol&&"undefined"!=typeof window&&"https:"===window.location.protocol?(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null):new WebSocketTracker(this,announceUrl):(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null)}).filter(Boolean)}start(opts){opts=this._defaultAnnounceOpts(opts),opts.event="started",debug("send `start` %o",opts),this._announce(opts),this._trackers.forEach(tracker=>{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":56,"./lib/client/udp-tracker":58,"./lib/client/websocket-tracker":59,"./lib/common":61,_process:246,buffer:101,debug:122,events:156,once:231,"queue-microtask":259,"run-parallel":287,"simple-peer":302}],56:[function(require,module,exports){(function(Buffer){(function(){const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),clone=require("clone"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:http-tracker"),get=require("simple-get"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker"),HTTP_SCRAPE_SUPPORT=/\/(announce)[^/]*$/;class HTTPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new http tracker %s",announceUrl),this.scrapeUrl=null;const match=this.announceUrl.match(HTTP_SCRAPE_SUPPORT);if(match){const pre=this.announceUrl.slice(0,match.index),post=this.announceUrl.slice(match.index+9);this.scrapeUrl=`${pre}/scrape${post}`}this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){if(!this.destroyed){const params=Object.assign({},opts,{compact:null==opts.compact?1:opts.compact,info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,port:this.client._port});this._trackerId&&(params.trackerid=this._trackerId),this._request(this.announceUrl,params,(err,data)=>err?this.client.emit("warning",err):void this._onAnnounceResponse(data))}}scrape(opts){if(this.destroyed)return;if(!this.scrapeUrl)return void this.client.emit("error",new Error(`scrape not supported ${this.announceUrl}`));const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary,params={info_hash:infoHashes};this._request(this.scrapeUrl,params,(err,data)=>err?this.client.emit("warning",err):void this._onScrapeResponse(data))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);this.destroyed=!0,clearInterval(this.interval);let timeout;return 0===this.cleanupFns.length?destroyCleanup():void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()})}_request(requestUrl,params,cb){function cleanup(){request&&(arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),request.abort(),request=null),self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}function onResponse(err,res,data){if(cleanup(),!self.destroyed){if(err)return cb(err);if(200!==res.statusCode)return cb(new Error(`Non-200 response code ${res.statusCode} from ${self.announceUrl}`));if(!data||0===data.length)return cb(new Error(`Invalid tracker response from${self.announceUrl}`));try{data=bencode.decode(data)}catch(err){return cb(new Error(`Error decoding tracker response: ${err.message}`))}const failure=data["failure reason"];if(failure)return debug(`failure from ${requestUrl} (${failure})`),cb(new Error(failure));const warning=data["warning message"];warning&&(debug(`warning from ${requestUrl} (${warning})`),self.client.emit("warning",new Error(warning))),debug(`response from ${requestUrl}`),cb(null,data)}}const self=this,parsedUrl=new URL(requestUrl+(-1===requestUrl.indexOf("?")?"?":"&")+common.querystringStringify(params));let agent;this.client._proxyOpts&&(agent="https:"===parsedUrl.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!agent&&this.client._proxyOpts.socksProxy&&(agent=new Socks.Agent(clone(this.client._proxyOpts.socksProxy),"https:"===parsedUrl.protocol))),this.cleanupFns.push(cleanup);let request=get.concat({url:parsedUrl.toString(),agent,timeout:common.REQUEST_TIMEOUT,headers:{"user-agent":this.client._userAgent||""}},onResponse)}_onAnnounceResponse(data){const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];trackerId&&(this._trackerId=trackerId);const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response);let addrs;if(Buffer.isBuffer(data.peers)){try{addrs=compact2string.multi(data.peers)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers)&&data.peers.forEach(peer=>{this.client.emit("peer",`${peer.ip}:${peer.port}`)});if(Buffer.isBuffer(data.peers6)){try{addrs=compact2string.multi6(data.peers6)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers6)&&data.peers6.forEach(peer=>{const ip=/^\[/.test(peer.ip)||!/:/.test(peer.ip)?peer.ip:`[${peer.ip}]`;this.client.emit("peer",`${ip}:${peer.port}`)})}_onScrapeResponse(data){data=data.files||data.host||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}}HTTPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000,module.exports=HTTPTracker}).call(this)}).call(this,{isBuffer:require("../../../is-buffer/index.js")})},{"../../../is-buffer/index.js":193,"../common":61,"./tracker":57,bencode:47,clone:111,compact2string:112,debug:122,"simple-get":301,socks:66,"unordered-array-remove":331}],57:[function(require,module,exports){const EventEmitter=require("events");class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}module.exports=Tracker},{events:156}],58:[function(require,module,exports){(function(Buffer){(function(){function genTransactionId(){return randombytes(4)}function toUInt16(n){const buf=Buffer.allocUnsafe(2);return buf.writeUInt16BE(n,0),buf}function toUInt64(n){if(n>MAX_UINT||"string"==typeof n){const bytes=new BN(n).toArray();for(;8>bytes.length;)bytes.unshift(0);return Buffer.from(bytes)}return Buffer.concat([common.toUInt32(0),common.toUInt32(n)])}function noop(){}const arrayRemove=require("unordered-array-remove"),BN=require("bn.js"),clone=require("clone"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:udp-tracker"),dgram=require("dgram"),randombytes=require("randombytes"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker");class UDPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new udp tracker %s",announceUrl),this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){this.destroyed||this._request(opts)}scrape(opts){this.destroyed||(opts._scrape=!0,this._request(opts))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);this.destroyed=!0,clearInterval(this.interval);let timeout;return 0===this.cleanupFns.length?destroyCleanup():void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()})}_request(opts){function onGotConnection(err,s,info){return err?onError(err):void(proxySocket=s,socket=dgram.createSocket("udp4"),relay=info,timeout=setTimeout(()=>{"stopped"===opts.event?cleanup():onError(new Error(`tracker request timed out (${opts.event})`)),timeout=null},common.REQUEST_TIMEOUT),timeout.unref&&timeout.unref(),send(Buffer.concat([common.CONNECTION_ID,common.toUInt32(common.ACTIONS.CONNECT),transactionId]),relay),socket.once("error",onError),socket.on("message",onSocketMessage))}function cleanup(){if(timeout&&(clearTimeout(timeout),timeout=null),socket){arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),socket.removeListener("error",onError),socket.removeListener("message",onSocketMessage),socket.on("error",noop);try{socket.close()}catch(err){}if(socket=null,proxySocket){try{proxySocket.close()}catch(err){}proxySocket=null}}self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}function onError(err){if(cleanup(),!self.destroyed){try{err.message&&(err.message+=` (${self.announceUrl})`)}catch(ignoredErr){}self.client.emit("warning",err)}}function onSocketMessage(msg){if(proxySocket&&(msg=msg.slice(10)),8>msg.length||msg.readUInt32BE(4)!==transactionId.readUInt32BE(0))return onError(new Error("tracker sent invalid transaction id"));const action=msg.readUInt32BE(0);switch(debug("UDP response %s, action %s",self.announceUrl,action),action){case 0:{if(16>msg.length)return onError(new Error("invalid udp handshake"));opts._scrape?scrape(msg.slice(8,16)):announce(msg.slice(8,16),opts);break}case 1:{if(cleanup(),self.destroyed)return;if(20>msg.length)return onError(new Error("invalid announce message"));const interval=msg.readUInt32BE(8);interval&&self.setInterval(1e3*interval),self.client.emit("update",{announce:self.announceUrl,complete:msg.readUInt32BE(16),incomplete:msg.readUInt32BE(12)});let addrs;try{addrs=compact2string.multi(msg.slice(20))}catch(err){return self.client.emit("warning",err)}addrs.forEach(addr=>{self.client.emit("peer",addr)});break}case 2:{if(cleanup(),self.destroyed)return;if(20>msg.length||0!=(msg.length-8)%12)return onError(new Error("invalid scrape message"));const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("hex")):[opts.infoHash&&opts.infoHash.toString("hex")||self.client.infoHash];for(let i=0,len=(msg.length-8)/12;i<len;i+=1)self.client.emit("scrape",{announce:self.announceUrl,infoHash:infoHashes[i],complete:msg.readUInt32BE(8+12*i),downloaded:msg.readUInt32BE(12+12*i),incomplete:msg.readUInt32BE(16+12*i)});break}case 3:{if(cleanup(),self.destroyed)return;if(8>msg.length)return onError(new Error("invalid error message"));self.client.emit("warning",new Error(msg.slice(8).toString()));break}default:onError(new Error("tracker sent invalid action"));}}function send(message,proxyInfo){if(proxyInfo){const pack=Socks.createUDPFrame({host:hostname,port},message);socket.send(pack,0,pack.length,proxyInfo.port,proxyInfo.host)}else socket.send(message,0,message.length,port,hostname)}function announce(connectionId,opts){transactionId=genTransactionId(),send(Buffer.concat([connectionId,common.toUInt32(common.ACTIONS.ANNOUNCE),transactionId,self.client._infoHashBuffer,self.client._peerIdBuffer,toUInt64(opts.downloaded),null==opts.left?Buffer.from("FFFFFFFFFFFFFFFF","hex"):toUInt64(opts.left),toUInt64(opts.uploaded),common.toUInt32(common.EVENTS[opts.event]||0),common.toUInt32(0),common.toUInt32(0),common.toUInt32(opts.numwant),toUInt16(self.client._port)]),relay)}function scrape(connectionId){transactionId=genTransactionId();const infoHash=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?Buffer.concat(opts.infoHash):opts.infoHash||self.client._infoHashBuffer;send(Buffer.concat([connectionId,common.toUInt32(common.ACTIONS.SCRAPE),transactionId,infoHash]),relay)}const self=this;opts||(opts={});let{hostname,port}=common.parseUrl(this.announceUrl);""===port&&(port=80);let transactionId=genTransactionId(),timeout,proxySocket,socket,relay;const proxyOpts=this.client._proxyOpts&&clone(this.client._proxyOpts.socksProxy);proxyOpts?(!proxyOpts.proxy&&(proxyOpts.proxy={}),proxyOpts.proxy.command="associate",!proxyOpts.target&&(proxyOpts.target={host:"0.0.0.0",port:0}),5===proxyOpts.proxy.type?Socks.createConnection(proxyOpts,onGotConnection):(debug("Ignoring Socks proxy for UDP request because type 5 is required"),onGotConnection(null))):onGotConnection(null),this.cleanupFns.push(cleanup)}}UDPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000;const MAX_UINT=4294967295;module.exports=UDPTracker}).call(this)}).call(this,require("buffer").Buffer)},{"../common":61,"./tracker":57,"bn.js":64,buffer:101,clone:111,compact2string:112,debug:122,dgram:106,randombytes:262,socks:66,"unordered-array-remove":331}],59:[function(require,module,exports){function noop(){}const clone=require("clone"),debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker"),socketPool={},RECONNECT_MINIMUM=10000,RECONNECT_MAXIMUM=3600000,RECONNECT_VARIANCE=300000,OFFER_TIMEOUT=50000;class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,5);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary,params={action:"scrape",info_hash:infoHashes};this._send(params)}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0<socketPool[this.announceUrl].consumers)return cb();let socket=socketPool[this.announceUrl];delete socketPool[this.announceUrl],socket.on("error",noop),socket.once("close",cb);let timeout;return this.expectingResponse?void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),socket.once("data",destroyCleanup)):destroyCleanup()}_openSocket(){if(this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket)socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound();else{const parsedUrl=new URL(this.announceUrl);let agent;this.client._proxyOpts&&(agent="wss:"===parsedUrl.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!agent&&this.client._proxyOpts.socksProxy&&(agent=new Socks.Agent(clone(this.client._proxyOpts.socksProxy),"wss:"===parsedUrl.protocol))),this.socket=socketPool[this.announceUrl]=new Socket({url:this.announceUrl,agent}),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)}this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),this.client.emit("peer",peer),peer.signal(data.offer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),this.client.emit("peer",peer),peer.signal(data.answer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*RECONNECT_VARIANCE)+_Mathmin(_Mathpow(2,this.retries)*RECONNECT_MINIMUM,RECONNECT_MAXIMUM);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},OFFER_TIMEOUT),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i<numwant;++i)generateOffer();checkDone()}_createPeer(opts){function onError(err){self.client.emit("warning",new Error(`Connection error: ${err.message}`)),peer.destroy()}function onConnect(){peer.removeListener("error",onError),peer.removeListener("connect",onConnect)}const self=this;opts=Object.assign({trickle:!1,config:self.client._rtcConfig,wrtc:self.client._wrtc},opts);const peer=new Peer(opts);return peer.once("error",onError),peer.once("connect",onConnect),peer}}WebSocketTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=30000,WebSocketTracker._socketPool=socketPool,module.exports=WebSocketTracker},{"../common":61,"./tracker":57,clone:111,debug:122,randombytes:262,"simple-peer":302,"simple-websocket":305,socks:66}],60:[function(require,module,exports){(function(Buffer){(function(){function toUInt32(n){const buf=Buffer.allocUnsafe(4);return buf.writeUInt32BE(n,0),buf}const querystring=require("querystring");exports.IPV4_RE=/^[\d.]+$/,exports.IPV6_RE=/^[\da-fA-F:]+$/,exports.REMOVE_IPV4_MAPPED_IPV6_RE=/^::ffff:/,exports.CONNECTION_ID=Buffer.concat([toUInt32(1047),toUInt32(655366528)]),exports.ACTIONS={CONNECT:0,ANNOUNCE:1,SCRAPE:2,ERROR:3},exports.EVENTS={update:0,completed:1,started:2,stopped:3},exports.EVENT_IDS={0:"update",1:"completed",2:"started",3:"stopped"},exports.EVENT_NAMES={update:"update",completed:"complete",started:"start",stopped:"stop"},exports.REQUEST_TIMEOUT=15e3,exports.DESTROY_TIMEOUT=1e3,exports.toUInt32=toUInt32,exports.querystringParse=q=>querystring.parse(q,null,null,{decodeURIComponent:unescape}),exports.querystringStringify=obj=>{let ret=querystring.stringify(obj,null,null,{encodeURIComponent:escape});return ret=ret.replace(/[@*/+]/g,char=>`%${char.charCodeAt(0).toString(16).toUpperCase()}`),ret}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,querystring:258}],61:[function(require,module,exports){(function(Buffer){(function(){exports.DEFAULT_ANNOUNCE_PEERS=50,exports.MAX_ANNOUNCE_PEERS=82,exports.binaryToHex=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"binary").toString("hex")),exports.hexToBinary=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"hex").toString("binary")),exports.parseUrl=str=>{const url=new URL(str.replace(/^udp:/,"http:"));return str.match(/^udp:/)&&Object.defineProperties(url,{href:{value:url.href.replace(/^http/,"udp")},protocol:{value:url.protocol.replace(/^http/,"udp")},origin:{value:url.origin.replace(/^http/,"udp")}}),url};const config=require("./common-node");Object.assign(exports,config)}).call(this)}).call(this,require("buffer").Buffer)},{"./common-node":60,buffer:101}],62:[function(require,module,exports){(function(Buffer){(function(){/*! blob-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */module.exports=function blobToBuffer(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],63:[function(require,module,exports){(function(Buffer){(function(){const{Transform}=require("readable-stream");class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){this._bufferedBytes-=this.size;const blockBufs=[];for(let blockBufsBytes=0;blockBufsBytes<this.size;){const b=this._buffered.shift();if(blockBufsBytes+b.length<=this.size)blockBufs.push(b),blockBufsBytes+=b.length;else{const neededSize=this.size-blockBufsBytes;blockBufs.push(b.slice(0,neededSize)),blockBufsBytes+=neededSize,this._buffered.unshift(b.slice(neededSize))}}this.push(Buffer.concat(blockBufs,this.size))}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}module.exports=Block}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"readable-stream":281}],64:[function(require,module,exports){(function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return 48<=c&&57>=c?c-48:65<=c&&70>=c?c-55:97<=c&&102>=c?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=_Mathmin(str.length,end),i=start,c;i<len;i++)c=str.charCodeAt(i)-48,r*=mul,b=49<=c?c-49+10:17<=c?c-17+10:c,assert(0<=c&&b<mul,"Invalid character"),r+=b;return r}function move(dest,src){dest.words=src.words,dest.length=src.length,dest.negative=src.negative,dest.red=src.red}function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit<w.length;bit++){var off=0|bit/26,wbit=bit%26;w[bit]=1&num.words[off]>>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k<len;k++){for(var ncarry=carry>>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out._strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k<out.length-1;k++){ncarry=hncarry,hncarry=0;for(var rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1);j<=maxJ;j++){var i=k-j,a=0|self.words[i],b=0|num.words[j],r=a*b,lo=67108863&r;ncarry=0|ncarry+(0|r/67108864),lo=0|lo+rword,rword=67108863&lo,ncarry=0|ncarry+(lo>>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer="undefined"!=typeof window&&"undefined"!=typeof window.Buffer?window.Buffer:require("buffer").Buffer}catch(e){}if(BN.isBN=function isBN(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return 0<left.cmp(right)?left:right},BN.min=function min(left,right){return 0>left.cmp(right)?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function _initNumber(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function _initArray(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j,w;if("be"===endian)for(i=number.length-1,j=0;0<=i;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i<number.length;i+=3)w=number[i]|number[i+1]<<8|number[i+2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j=0,w;if("be"===endian)for(i=number.length-1;i>=start;i-=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=0==parseLength%2?start+1:start;i<number.length;i+=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;i<end;i+=limbLen)word=parseBase(number,i,i+limbLen,base),this.imuln(limbPow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;i<mod;i++)pow*=base;this.imuln(pow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word)}this._strip()},BN.prototype.copy=function copy(dest){dest.words=Array(this.length);for(var i=0;i<this.length;i++)dest.words[i]=this.words[i];dest.length=this.length,dest.negative=this.negative,dest.red=this.red},BN.prototype._move=function _move(dest){move(dest,this)},BN.prototype.clone=function clone(){var r=new BN(null);return this.copy(r),r},BN.prototype._expand=function _expand(size){for(;this.length<size;)this.words[this.length++]=0;return this},BN.prototype._strip=function strip(){for(;1<this.length&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i<this.length;i++){var w=this.words[i],word=(16777215&(w<<off|carry)).toString(16);carry=16777215&w>>>24-off,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,26<=off&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2<this.length&&assert(!1,"Number can only safely store up to 53 bits"),0===this.negative?ret:-ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};var allocate=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||_Mathmax(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(0<reqLength,"Requested array length <= 0");var res=allocate(ArrayType,reqLength),postfix="le"===endian?"LE":"BE";return this["_toArrayLike"+postfix](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position++]=255&word,position<res.length&&(res[position++]=255&word>>8),position<res.length&&(res[position++]=255&word>>16),6==shift?(position<res.length&&(res[position++]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(position<res.length)for(res[position++]=carry;position<res.length;)res[position++]=0},BN.prototype._toArrayLikeBE=function _toArrayLikeBE(res,byteLength){for(var position=res.length-1,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position--]=255&word,0<=position&&(res[position--]=255&word>>8),0<=position&&(res[position--]=255&word>>16),6==shift?(0<=position&&(res[position--]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(0<=position)for(res[position--]=carry;0<=position;)res[position--]=0},BN.prototype._countBits=_Mathclz?function _countBits(w){return 32-_Mathclz(w)}:function _countBits(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0,b;i<this.length&&(b=this._zeroBits(this.words[i]),r+=b,26===b);i++);return r},BN.prototype.byteLength=function byteLength(){return _Mathceil(this.bitLength()/8)},BN.prototype.toTwos=function toTwos(width){return 0===this.negative?this.clone():this.abs().inotn(width).iaddn(1)},BN.prototype.fromTwos=function fromTwos(width){return this.testn(width-1)?this.notn(width).iaddn(1).ineg():this.clone()},BN.prototype.isNeg=function isNeg(){return 0!==this.negative},BN.prototype.neg=function neg(){return this.clone().ineg()},BN.prototype.ineg=function ineg(){return this.isZero()||(this.negative^=1),this},BN.prototype.iuor=function iuor(num){for(;this.length<num.length;)this.words[this.length++]=0;for(var i=0;i<num.length;i++)this.words[i]|=num.words[i];return this._strip()},BN.prototype.ior=function ior(num){return assert(0==(this.negative|num.negative)),this.iuor(num)},BN.prototype.or=function or(num){return this.length>num.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;i<b.length;i++)this.words[i]&=num.words[i];return this.length=b.length,this._strip()},BN.prototype.iand=function iand(num){return assert(0==(this.negative|num.negative)),this.iuand(num)},BN.prototype.and=function and(num){return this.length>num.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;i<b.length;i++)this.words[i]=a.words[i]^b.words[i];if(this!==a)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=a.length,this._strip()},BN.prototype.ixor=function ixor(num){return assert(0==(this.negative|num.negative)),this.iuxor(num)},BN.prototype.xor=function xor(num){return this.length>num.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0<bitsLeft&&bytesNeeded--;for(var i=0;i<bytesNeeded;i++)this.words[i]=67108863&~this.words[i];return 0<bitsLeft&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<<wbit:this.words[off]&=~(1<<wbit),this._strip()},BN.prototype.iadd=function iadd(num){var r;if(0!==this.negative&&0===num.negative)return this.negative=0,r=this.isub(num),this.negative^=1,this._normSign();if(0===this.negative&&0!==num.negative)return num.negative=0,r=this.isub(num),num.negative=1,r._normSign();var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])+(0|b.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this},BN.prototype.add=function add(num){var res;return 0!==num.negative&&0===this.negative?(num.negative=0,res=this.sub(num),num.negative^=1,res):0===num.negative&&0!==this.negative?(this.negative=0,res=num.sub(this),this.negative=1,res):this.length>num.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0<cmp?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])-(0|b.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;if(0===carry&&i<a.length&&a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=_Mathmax(this.length,i),a!==this&&(this.negative=1),this._strip()},BN.prototype.sub=function sub(num){return this.clone().isub(num)};var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words,b=num.words,o=out.words,c=0,a0=0|a[0],al0=8191&a0,ah0=a0>>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i<N;i++)t[i]=this.revBin(i,l,N);return t},FFTM.prototype.revBin=function revBin(x,l,N){if(0===x||x===N-1)return x;for(var rb=0,i=0;i<l;i++)rb|=(1&x)<<l-i-1,x>>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i<N;i++)rtws[i]=rws[rbt[i]],itws[i]=iws[rbt[i]]},FFTM.prototype.transform=function transform(rws,iws,rtws,itws,N,rbt){this.permute(rbt,rws,iws,rtws,itws,N);for(var s=1;s<N;s<<=1)for(var l=s<<1,rtwdf=_Mathcos(2*_MathPI/l),itwdf=_Mathsin(2*_MathPI/l),p=0;p<N;p+=l)for(var rtwdf_=rtwdf,itwdf_=itwdf,j=0;j<s;j++){var re=rtws[p+j],ie=itws[p+j],ro=rtws[p+j+s],io=itws[p+j+s],rx=rtwdf_*ro-itwdf_*io;io=rtwdf_*io+itwdf_*ro,ro=rx,rtws[p+j]=re+ro,itws[p+j]=ie+io,rtws[p+j+s]=re-ro,itws[p+j+s]=ie-io,j!==l&&(rx=rtwdf*rtwdf_-itwdf*itwdf_,itwdf_=rtwdf*itwdf_+itwdf*rtwdf_,rtwdf_=rx)}},FFTM.prototype.guessLen13b=function guessLen13b(n,m){var N=1|_Mathmax(m,n),odd=1&N,i=0;for(N=0|N/2;N;N>>>=1)i++;return 1<<i+1+odd},FFTM.prototype.conjugate=function conjugate(rws,iws,N){if(!(1>=N))for(var i=0,t;i<N/2;i++)t=rws[i],rws[i]=rws[N-i-1],rws[N-i-1]=t,t=iws[i],iws[i]=-iws[N-i-1],iws[N-i-1]=-t},FFTM.prototype.normalize13b=function normalize13b(ws,N){for(var carry=0,i=0,w;i<N/2;i++)w=8192*_Mathround(ws[2*i+1]/N)+_Mathround(ws[2*i]/N)+carry,ws[i]=67108863&w,carry=67108864>w?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function convert13b(ws,len,rws,N){for(var carry=0,i=0;i<len;i++)carry+=0|ws[i],rws[2*i]=8191&carry,carry>>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i<N;++i)rws[i]=0;assert(0===carry),assert(0==(-8192&carry))},FFTM.prototype.stub=function stub(N){for(var ph=Array(N),i=0;i<N;i++)ph[i]=0;return ph},FFTM.prototype.mulp=function mulp(x,y,out){var N=2*this.guessLen13b(x.length,y.length),rbt=this.makeRBT(N),_=this.stub(N),rws=Array(N),rwst=Array(N),iwst=Array(N),nrws=Array(N),nrwst=Array(N),niwst=Array(N),rmws=out.words;rmws.length=N,this.convert13b(x.words,x.length,rws,N),this.convert13b(y.words,y.length,nrws,N),this.transform(rws,_,rwst,iwst,N,rbt),this.transform(nrws,_,nrwst,niwst,N,rbt);for(var i=0,rx;i<N;i++)rx=rwst[i]*nrwst[i]-iwst[i]*niwst[i],iwst[i]=rwst[i]*niwst[i]+iwst[i]*nrwst[i],rwst[i]=rx;return this.conjugate(rwst,iwst,N),this.transform(rwst,iwst,rmws,_,N,rbt),this.conjugate(rmws,_,N),this.normalize13b(rmws,N),out.negative=x.negative^y.negative,out.length=x.length+y.length,out._strip()},BN.prototype.mul=function mul(num){var out=new BN(null);return out.words=Array(this.length+num.length),this.mulTo(num,out)},BN.prototype.mulf=function mulf(num){var out=new BN(null);return out.words=Array(this.length+num.length),jumboMulTo(this,num,out)},BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)},BN.prototype.imuln=function imuln(num){var isNegNum=0>num;isNegNum&&(num=-num),assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i<this.length;i++){var w=(0|this.words[i])*num,lo=(67108863&w)+(67108863&carry);carry>>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i<w.length&&0===w[i];i++,res=res.sqr());if(++i<w.length)for(var q=res.sqr();i<w.length;i++,q=q.sqr())0!==w[i]&&(res=res.mul(q));return res},BN.prototype.iushln=function iushln(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(0!=r){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask,c=(0|this.words[i])-newCarry<<r;this.words[i]=c|carry,carry=newCarry>>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;i<s;i++)this.words[i]=0;this.length+=s}return this._strip()},BN.prototype.ishln=function ishln(bits){return assert(0===this.negative),this.iushln(bits)},BN.prototype.iushrn=function iushrn(bits,hint,extended){assert("number"==typeof bits&&0<=bits);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=_Mathmin((bits-r)/26,this.length),mask=67108863^67108863>>>r<<r,maskedWords=extended;if(h-=s,h=_Mathmax(0,h),maskedWords){for(var i=0;i<s;i++)maskedWords.words[i]=this.words[i];maskedWords.length=s}if(0===s);else if(this.length>s)for(this.length-=s,i=0;i<this.length;i++)this.words[i]=this.words[i+s];else this.words[0]=0,this.length=1;var carry=0;for(i=this.length-1;0<=i&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&0<=bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return!1;var w=this.words[s];return!!(w&q)},BN.prototype.imaskn=function imaskn(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!=r&&s++,this.length=_Mathmin(s,this.length),0!=r){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this._strip()},BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)},BN.prototype.iaddn=function iaddn(num){return assert("number"==typeof num),assert(67108864>num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<=num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&67108864<=this.words[i];i++)this.words[i]-=67108864,i==this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=_Mathmax(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(67108864>num),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i<this.length&&0>this.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this._strip()},BN.prototype.addn=function addn(num){return this.clone().iaddn(num)},BN.prototype.subn=function subn(num){return this.clone().isubn(num)},BN.prototype.iabs=function iabs(){return this.negative=0,this},BN.prototype.abs=function abs(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i<num.length;i++){w=(0|this.words[i+shift])+carry;var right=(0|num.words[i])*mul;w-=67108863&right,carry=(w>>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i<this.length-shift;i++)w=(0|this.words[i+shift])+carry,carry=w>>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i<this.length;i++)w=-(0|this.words[i])+carry,carry=w>>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;i<q.length;i++)q.words[i]=0}var diff=a.clone()._ishlnsubmul(b,1,m);0===diff.negative&&(a=diff,q&&(q.words[m]=1));for(var j=m-1,qj;0<=j;j--){for(qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]),qj=_Mathmin(0|qj/bhi,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0==(this.negative&num.negative)?num.length>this.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(x.iushrn(i);0<i--;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(y.iushrn(j);0<j--;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);0<=x.cmp(y)?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0===a.negative?a.clone():a.umod(p);for(var x1=new BN(1),x2=new BN(0),delta=b.clone();0<a.cmpn(1)&&0<b.cmpn(1);){for(var i=0,im=1;0==(a.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(a.iushrn(i);0<i--;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(b.iushrn(j);0<j--;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);0<=a.cmp(b)?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,0>res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return this._expand(s+1),this.words[s]|=q,this;for(var carry=q,i=s,w;0!==carry&&i<this.length;i++)w=0|this.words[i],w+=carry,carry=w>>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this._strip();var res;if(1<this.length)res=1;else{negative&&(num=-num),assert(67108863>=num,"Number is too big");var w=0|this.words[0];res=w===num?0:w<num?-1:1}return 0===this.negative?res:0|-res},BN.prototype.cmp=function cmp(num){if(0!==this.negative&&0===num.negative)return-1;if(0===this.negative&&0!==num.negative)return 1;var res=this.ucmp(num);return 0===this.negative?res:0|-res},BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;for(var res=0,i=this.length-1;0<=i;i--){var a=0|this.words[i],b=0|num.words[i];if(a!=b){a<b?res=-1:a>b&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return 0<=this.cmpn(num)},BN.prototype.gte=function gte(num){return 0<=this.cmp(num)},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return 0>=this.cmpn(num)},BN.prototype.lte=function lte(num){return 0>=this.cmp(num)},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);return 0===cmp?(r.words[0]=0,r.length=1):0<cmp?r.isub(this.p):void 0===r.strip?r._strip():r.strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var mask=4194303,outLen=_Mathmin(input.length,9),i=0;i<outLen;i++)output.words[i]=input.words[i];if(output.length=outLen,9>=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i<input.length;i++){var next=0|input.words[i];input.words[i-10]=(next&mask)<<4|prev>>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10<input.length?10:9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0,w;i<num.length;i++)w=0|num.words[i],lo+=977*w,num.words[i]=67108863&lo,lo=64*w+(0|lo/67108864);return 0===num.words[num.length-1]&&(num.length--,0===num.words[num.length-1]&&num.length--),num},inherits(P224,MPrime),inherits(P192,MPrime),inherits(P25519,MPrime),P25519.prototype.imulK=function imulK(num){for(var carry=0,i=0;i<num.length;i++){var hi=19*(0|num.words[i])+carry,lo=67108863&hi;hi>>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b),c=b.redSqr(),t=t.redMul(c),m=i}return r},Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);return 0===inv.negative?this.imod(inv):(inv.negative=0,this.imod(inv).redNeg())},Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(0===num.cmpn(1))return a.clone();var windowSize=4,wnd=Array(16);wnd[0]=new BN(1).toRed(this),wnd[1]=a;for(var i=2;i<wnd.length;i++)wnd[i]=this.mul(wnd[i-1],a);var res=wnd[0],current=0,currentLen=0,start=num.bitLength()%26;for(0===start&&(start=26),i=num.length-1;0<=i;i--){for(var word=num.words[i],j=start-1,bit;0<=j;j--){if(bit=1&word>>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:66}],65:[function(require,module,exports){function Rand(rand){this.rand=rand}var r;if(module.exports=function rand(len){return r||(r=new Rand(null)),r.generate(len)},module.exports.Rand=Rand,Rand.prototype.generate=function generate(len){return this._rand(len)},Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);for(var res=new Uint8Array(n),i=0;i<res.length;i++)res[i]=this.rand.getByte();return res},"object"==typeof self)self.crypto&&self.crypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.crypto.getRandomValues(arr),arr}:self.msCrypto&&self.msCrypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.msCrypto.getRandomValues(arr),arr}:"object"==typeof window&&(Rand.prototype._rand=function(){throw new Error("Not implemented yet")});else try{var crypto=require("crypto");if("function"!=typeof crypto.randomBytes)throw new Error("Not supported");Rand.prototype._rand=function _rand(n){return crypto.randomBytes(n)}}catch(e){}},{crypto:66}],66:[function(require,module,exports){},{}],67:[function(require,module,exports){function asUInt32Array(buf){Buffer.isBuffer(buf)||(buf=Buffer.from(buf));for(var len=0|buf.length/4,out=Array(len),i=0;i<len;i++)out[i]=buf.readUInt32BE(4*i);return out}function scrubVec(v){for(var i=0;i<v.length;v++)v[i]=0}function cryptBlock(M,keySchedule,SUB_MIX,SBOX,nRounds){for(var SUB_MIX0=SUB_MIX[0],SUB_MIX1=SUB_MIX[1],SUB_MIX2=SUB_MIX[2],SUB_MIX3=SUB_MIX[3],s0=M[0]^keySchedule[0],s1=M[1]^keySchedule[1],s2=M[2]^keySchedule[2],s3=M[3]^keySchedule[3],ksRow=4,round=1,t0,t1,t2,t3;round<nRounds;round++)t0=SUB_MIX0[s0>>>24]^SUB_MIX1[255&s1>>>16]^SUB_MIX2[255&s2>>>8]^SUB_MIX3[255&s3]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[255&s2>>>16]^SUB_MIX2[255&s3>>>8]^SUB_MIX3[255&s0]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[255&s3>>>16]^SUB_MIX2[255&s0>>>8]^SUB_MIX3[255&s1]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[255&s0>>>16]^SUB_MIX2[255&s1>>>8]^SUB_MIX3[255&s2]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[255&s1>>>16]<<16|SBOX[255&s2>>>8]<<8|SBOX[255&s3])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[255&s2>>>16]<<16|SBOX[255&s3>>>8]<<8|SBOX[255&s0])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[255&s3>>>16]<<16|SBOX[255&s0>>>8]<<8|SBOX[255&s1])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[255&s0>>>16]<<16|SBOX[255&s1>>>8]<<8|SBOX[255&s2])^keySchedule[ksRow++],t0>>>=0,t1>>>=0,t2>>>=0,t3>>>=0,[t0,t1,t2,t3]}function AES(key){this._key=asUInt32Array(key),this._reset()}var Buffer=require("safe-buffer").Buffer,RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=Array(256),j=0;256>j;j++)d[j]=128>j?j<<1:283^j<<1;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0,sx;256>i;++i){sx=xi^xi<<1^xi<<2^xi<<3^xi<<4,sx=99^(sx>>>8^255&sx),SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,0===x?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX:SBOX,INV_SBOX:INV_SBOX,SUB_MIX:SUB_MIX,INV_SUB_MIX:INV_SUB_MIX}}();AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=4*(nRounds+1),keySchedule=[],k=0;k<keySize;k++)keySchedule[k]=keyWords[k];for(k=keySize;k<ksRows;k++){var t=keySchedule[k-1];0==k%keySize?(t=t<<8|t>>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t],t^=RCON[0|k/keySize]<<24):6<keySize&&4==k%keySize&&(t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik<ksRows;ik++){var ksR=ksRows-ik,tt=keySchedule[ksR-(ik%4?0:4)];invKeySchedule[ik]=4>ik||4>=ksR?tt:G.INV_SUB_MIX[0][G.SBOX[tt>>>24]]^G.INV_SUB_MIX[1][G.SBOX[255&tt>>>16]]^G.INV_SUB_MIX[2][G.SBOX[255&tt>>>8]]^G.INV_SUB_MIX[3][G.SBOX[255&tt]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES},{"safe-buffer":290}],68:[function(require,module,exports){function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=_Mathmin(a.length,b.length),i=0;i<len;++i)out+=a[i]^b[i];return out}function calcIv(self,iv,ck){if(12===iv.length)return self._finID=Buffer.concat([iv,Buffer.from([0,0,0,1])]),Buffer.concat([iv,Buffer.from([0,0,0,2])]);var ghash=new GHASH(ck),len=iv.length,toPad=len%16;ghash.update(iv),toPad&&(toPad=16-toPad,ghash.update(Buffer.alloc(toPad,0))),ghash.update(Buffer.alloc(8,0));var ivBits=8*len,tail=Buffer.alloc(8);tail.writeUIntBE(ivBits,0,8),ghash.update(tail),self._finID=ghash.state;var out=Buffer.from(self._finID);return incr32(out),out}function StreamCipher(mode,key,iv,decrypt){Transform.call(this);var h=Buffer.alloc(4,0);this._cipher=new aes.AES(key);var ck=this._cipher.encryptBlock(h);this._ghash=new GHASH(ck),iv=calcIv(this,iv,ck),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._alen=0,this._len=0,this._mode=mode,this._authTag=null,this._called=!1}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits"),GHASH=require("./ghash"),xor=require("buffer-xor"),incr32=require("./incr32");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;16>rump&&(rump=Buffer.alloc(rump,0),this._ghash.update(rump))}this._called=!0;var out=this._mode.encrypt(this,chunk);return this._decrypt?this._ghash.update(chunk):this._ghash.update(out),this._len+=chunk.length,out},StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var tag=xor(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&xorTest(tag,this._authTag))throw new Error("Unsupported state or unable to authenticate data");this._authTag=tag,this._cipher.scrub()},StreamCipher.prototype.getAuthTag=function getAuthTag(){if(this._decrypt||!Buffer.isBuffer(this._authTag))throw new Error("Attempting to get auth tag in unsupported state");return this._authTag},StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(!this._decrypt)throw new Error("Attempting to set auth tag in unsupported state");this._authTag=tag},StreamCipher.prototype.setAAD=function setAAD(buf){if(this._called)throw new Error("Attempting to set AAD in unsupported state");this._ghash.update(buf),this._alen+=buf.length},module.exports=StreamCipher},{"./aes":67,"./ghash":72,"./incr32":73,"buffer-xor":100,"cipher-base":110,inherits:189,"safe-buffer":290}],69:[function(require,module,exports){function getCiphers(){return Object.keys(modes)}var ciphers=require("./encrypter"),deciphers=require("./decrypter"),modes=require("./modes/list.json");exports.createCipher=exports.Cipher=ciphers.createCipher,exports.createCipheriv=exports.Cipheriv=ciphers.createCipheriv,exports.createDecipher=exports.Decipher=deciphers.createDecipher,exports.createDecipheriv=exports.Decipheriv=deciphers.createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"./decrypter":70,"./encrypter":71,"./modes/list.json":81}],70:[function(require,module,exports){function Decipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function unpad(last){var padded=last[15];if(1>padded||16<padded)throw new Error("unable to decrypt data");for(var i=-1;++i<padded;)if(last[i+(16-padded)]!==padded)throw new Error("unable to decrypt data");return 16===padded?void 0:last.slice(0,16-padded)}function createDecipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);return"stream"===config.type?new StreamCipher(config.module,password,iv,!0):"auth"===config.type?new AuthCipher(config.module,password,iv,!0):new Decipher(config.module,password,iv)}function createDecipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createDecipheriv(suite,keys.key,keys.iv)}var AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,MODES=require("./modes"),StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Decipher,Transform),Decipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get(this._autopadding);)thing=this._mode.decrypt(this,chunk),out.push(thing);return Buffer.concat(out)},Decipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return unpad(this._mode.decrypt(this,chunk));if(chunk)throw new Error("data not multiple of block length")},Decipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(autoPadding){var out;if(autoPadding){if(16<this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;}else if(16<=this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache},exports.createDecipher=createDecipher,exports.createDecipheriv=createDecipheriv},{"./aes":67,"./authCipher":68,"./modes":80,"./streamCipher":83,"cipher-base":110,evp_bytestokey:157,inherits:189,"safe-buffer":290}],71:[function(require,module,exports){function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function createCipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);return"stream"===config.type?new StreamCipher(config.module,password,iv):"auth"===config.type?new AuthCipher(config.module,password,iv):new Cipher(config.module,password,iv)}function createCipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createCipheriv(suite,keys.key,keys.iv)}var MODES=require("./modes"),AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer.concat(out)};var PADDING=Buffer.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error("data not multiple of block length")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(){if(15<this.cache.length){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer.allocUnsafe(len),i=-1;++i<len;)padBuff.writeUInt8(len,i);return Buffer.concat([this.cache,padBuff])},exports.createCipheriv=createCipheriv,exports.createCipher=createCipher},{"./aes":67,"./authCipher":68,"./modes":80,"./streamCipher":83,"cipher-base":110,evp_bytestokey:157,inherits:189,"safe-buffer":290}],72:[function(require,module,exports){function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer.alloc(16,0),this.cache=Buffer.allocUnsafe(0)}var Buffer=require("safe-buffer").Buffer,ZEROES=Buffer.alloc(16,0);GHASH.prototype.ghash=function(block){for(var i=-1;++i<block.length;)this.state[i]^=block[i];this._multiply()},GHASH.prototype._multiply=function(){for(var Vi=toArray(this.h),Zi=[0,0,0,0],i=-1,j,xi,lsbVi;128>++i;){for(xi=0!=(this.state[~~(i/8)]&1<<7-i%8),xi&&(Zi[0]^=Vi[0],Zi[1]^=Vi[1],Zi[2]^=Vi[2],Zi[3]^=Vi[3]),lsbVi=0!=(1&Vi[3]),j=3;0<j;j--)Vi[j]=Vi[j]>>>1|(1&Vi[j-1])<<31;Vi[0]>>>=1,lsbVi&&(Vi[0]^=-520093696)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);for(var chunk;16<=this.cache.length;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH},{"safe-buffer":290}],73:[function(require,module,exports){function incr32(iv){for(var len=iv.length,item;len--;)if(item=iv.readUInt8(len),255===item)iv.writeUInt8(0,len);else{item++,iv.writeUInt8(item,len);break}}module.exports=incr32},{}],74:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);return self._prev=self._cipher.encryptBlock(data),self._prev},exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":100}],75:[function(require,module,exports){function encryptStart(self,data,decrypt){var len=data.length,out=xor(data,self._cache);return self._cache=self._cache.slice(len),self._prev=Buffer.concat([self._prev,decrypt?data:out]),out}var Buffer=require("safe-buffer").Buffer,xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){for(var out=Buffer.allocUnsafe(0),len;data.length;)if(0===self._cache.length&&(self._cache=self._cipher.encryptBlock(self._prev),self._prev=Buffer.allocUnsafe(0)),self._cache.length<=data.length)len=self._cache.length,out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]),data=data.slice(len);else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}return out}},{"buffer-xor":100,"safe-buffer":290}],76:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){for(var i=-1,len=8,out=0,pad,bit,value;++i<len;)pad=self._cipher.encryptBlock(self._prev),bit=byteParam&1<<7-i?128:0,value=pad[0]^bit,out+=(128&value)>>i%8,self._prev=shiftIn(self._prev,decrypt?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer.allocUnsafe(buffer.length);for(buffer=Buffer.concat([buffer,Buffer.from([value])]);++i<len;)out[i]=buffer[i]<<1|buffer[i+1]>>7;return out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":290}],77:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev),out=pad[0]^byteParam;return self._prev=Buffer.concat([self._prev.slice(1),Buffer.from([decrypt?byteParam:out])]),out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":290}],78:[function(require,module,exports){function getBlock(self){var out=self._cipher.encryptBlockRaw(self._prev);return incr32(self._prev),out}var xor=require("buffer-xor"),Buffer=require("safe-buffer").Buffer,incr32=require("../incr32"),blockSize=16;exports.encrypt=function(self,chunk){var chunkNum=_Mathceil(chunk.length/blockSize),start=self._cache.length;self._cache=Buffer.concat([self._cache,Buffer.allocUnsafe(chunkNum*blockSize)]);for(var i=0;i<chunkNum;i++){var out=getBlock(self),offset=start+i*blockSize;self._cache.writeUInt32BE(out[0],offset+0),self._cache.writeUInt32BE(out[1],offset+4),self._cache.writeUInt32BE(out[2],offset+8),self._cache.writeUInt32BE(out[3],offset+12)}var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}},{"../incr32":73,"buffer-xor":100,"safe-buffer":290}],79:[function(require,module,exports){exports.encrypt=function(self,block){return self._cipher.encryptBlock(block)},exports.decrypt=function(self,block){return self._cipher.decryptBlock(block)}},{}],80:[function(require,module,exports){var modeModules={ECB:require("./ecb"),CBC:require("./cbc"),CFB:require("./cfb"),CFB8:require("./cfb8"),CFB1:require("./cfb1"),OFB:require("./ofb"),CTR:require("./ctr"),GCM:require("./ctr")},modes=require("./list.json");for(var key in modes)modes[key].module=modeModules[modes[key].mode];module.exports=modes},{"./cbc":74,"./cfb":75,"./cfb1":76,"./cfb8":77,"./ctr":78,"./ecb":79,"./list.json":81,"./ofb":82}],81:[function(require,module,exports){module.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}},{}],82:[function(require,module,exports){(function(Buffer){(function(){function getBlock(self){return self._prev=self._cipher.encryptBlock(self._prev),self._prev}var xor=require("buffer-xor");exports.encrypt=function(self,chunk){for(;self._cache.length<chunk.length;)self._cache=Buffer.concat([self._cache,getBlock(self)]);var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"buffer-xor":100}],83:[function(require,module,exports){function StreamCipher(mode,key,iv,decrypt){Transform.call(this),this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._mode=mode}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){return this._mode.encrypt(this,chunk,this._decrypt)},StreamCipher.prototype._final=function(){this._cipher.scrub()},module.exports=StreamCipher},{"./aes":67,"cipher-base":110,inherits:189,"safe-buffer":290}],84:[function(require,module,exports){function createCipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createCipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite});throw new TypeError("invalid suite type")}function createDecipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createDecipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite,decrypt:!0});throw new TypeError("invalid suite type")}function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}var DES=require("browserify-des"),aes=require("browserify-aes/browser"),aesModes=require("browserify-aes/modes"),desModes=require("browserify-des/modes"),ebtk=require("evp_bytestokey");exports.createCipher=exports.Cipher=createCipher,exports.createCipheriv=exports.Cipheriv=createCipheriv,exports.createDecipher=exports.Decipher=createDecipher,exports.createDecipheriv=exports.Decipheriv=createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":69,"browserify-aes/modes":80,"browserify-des":85,"browserify-des/modes":86,evp_bytestokey:157}],85:[function(require,module,exports){function DES(opts){CipherBase.call(this);var modeName=opts.mode.toLowerCase(),mode=modes[modeName],type;type=opts.decrypt?"decrypt":"encrypt";var key=opts.key;Buffer.isBuffer(key)||(key=Buffer.from(key)),("des-ede"===modeName||"des-ede-cbc"===modeName)&&(key=Buffer.concat([key,key.slice(0,8)]));var iv=opts.iv;Buffer.isBuffer(iv)||(iv=Buffer.from(iv)),this._des=mode.create({key:key,iv:iv,type:type})}var CipherBase=require("cipher-base"),des=require("des.js"),inherits=require("inherits"),Buffer=require("safe-buffer").Buffer,modes={"des-ede3-cbc":des.CBC.instantiate(des.EDE),"des-ede3":des.EDE,"des-ede-cbc":des.CBC.instantiate(des.EDE),"des-ede":des.EDE,"des-cbc":des.CBC.instantiate(des.DES),"des-ecb":des.DES};modes.des=modes["des-cbc"],modes.des3=modes["des-ede3-cbc"],module.exports=DES,inherits(DES,CipherBase),DES.prototype._update=function(data){return Buffer.from(this._des.update(data))},DES.prototype._final=function(){return Buffer.from(this._des.final())}},{"cipher-base":110,"des.js":124,inherits:189,"safe-buffer":290}],86:[function(require,module,exports){exports["des-ecb"]={key:8,iv:0},exports["des-cbc"]=exports.des={key:8,iv:8},exports["des-ede3-cbc"]=exports.des3={key:24,iv:8},exports["des-ede3"]={key:24,iv:0},exports["des-ede-cbc"]={key:16,iv:8},exports["des-ede"]={key:16,iv:0}},{}],87:[function(require,module,exports){(function(Buffer){(function(){function blind(priv){var r=getr(priv),blinder=r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function getr(priv){var len=priv.modulus.byteLength(),r;do r=new BN(randomBytes(len));while(0<=r.cmp(priv.modulus)||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,"be",len)}var BN=require("bn.js"),randomBytes=require("randombytes");crt.getr=getr,module.exports=crt}).call(this)}).call(this,require("buffer").Buffer)},{"bn.js":64,buffer:101,randombytes:262}],88:[function(require,module,exports){module.exports=require("./browser/algorithms.json")},{"./browser/algorithms.json":89}],89:[function(require,module,exports){module.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],90:[function(require,module,exports){module.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],91:[function(require,module,exports){function Sign(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function Verify(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}var Buffer=require("safe-buffer").Buffer,createHash=require("create-hash"),stream=require("readable-stream"),inherits=require("inherits"),sign=require("./sign"),verify=require("./verify"),algorithms=require("./algorithms.json");Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer.from(algorithms[key].id,"hex"),algorithms[key.toLowerCase()]=algorithms[key]}),inherits(Sign,stream.Writable),Sign.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function signMethod(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc?sig.toString(enc):sig},inherits(Verify,stream.Writable),Verify.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function verifyMethod(key,sig,enc){"string"==typeof sig&&(sig=Buffer.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)},module.exports={Sign:createSign,Verify:createVerify,createSign:createSign,createVerify:createVerify}},{"./algorithms.json":89,"./sign":92,"./verify":93,"create-hash":116,inherits:189,"readable-stream":281,"safe-buffer":290}],92:[function(require,module,exports){function sign(hash,key,hashType,signType,tag){var priv=parseKeys(key);if(priv.curve){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");return ecSign(hash,priv)}if("dsa"===priv.type){if("dsa"!==signType)throw new Error("wrong private key type");return dsaSign(hash,priv,hashType)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");hash=Buffer.concat([tag,hash]);for(var len=priv.modulus.byteLength(),pad=[0,1];hash.length+pad.length+1<len;)pad.push(255);pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);var out=crt(pad,priv);return out}function ecSign(hash,priv){var curveId=curves[priv.curve.join(".")];if(!curveId)throw new Error("unknown curve "+priv.curve.join("."));var curve=new EC(curveId),key=curve.keyFromPrivate(priv.privateKey),out=key.sign(hash);return Buffer.from(out.toDER())}function dsaSign(hash,priv,algo){for(var x=priv.params.priv_key,p=priv.params.p,q=priv.params.q,g=priv.params.g,r=new BN(0),H=bits2int(hash,q).mod(q),s=!1,kv=getKey(x,q,hash,algo),k;!1===s;)k=makeKey(q,kv,algo),r=makeR(g,k,p,q),s=k.invm(q).imul(H.add(x.mul(r))).mod(q),0===s.cmpn(0)&&(s=!1,r=new BN(0));return toDER(r,s)}function toDER(r,s){r=r.toArray(),s=s.toArray(),128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s));var total=r.length+s.length+4,res=[48,total,2,r.length];return res=res.concat(r,[2,s.length],s),Buffer.from(res)}function getKey(x,q,hash,algo){if(x=Buffer.from(x.toArray()),x.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-x.length);x=Buffer.concat([zeros,x])}var hlen=hash.length,hbits=bits2octets(hash,q),v=Buffer.alloc(hlen);v.fill(1);var k=Buffer.alloc(hlen);return k=createHmac(algo,k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),k=createHmac(algo,k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),{k:k,v:v}}function bits2int(obits,q){var bits=new BN(obits),shift=(obits.length<<3)-q.bitLength();return 0<shift&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer.from(bits.toArray());if(out.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-out.length);out=Buffer.concat([zeros,out])}return out}function makeKey(q,kv,algo){var t,k;do{for(t=Buffer.alloc(0);8*t.length<q.bitLength();)kv.v=createHmac(algo,kv.k).update(kv.v).digest(),t=Buffer.concat([t,kv.v]);k=bits2int(t,q),kv.k=createHmac(algo,kv.k).update(kv.v).update(Buffer.from([0])).digest(),kv.v=createHmac(algo,kv.k).update(kv.v).digest()}while(-1!==k.cmp(q));return k}function makeR(g,k,p,q){return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)}var Buffer=require("safe-buffer").Buffer,createHmac=require("create-hmac"),crt=require("browserify-rsa"),EC=require("elliptic").ec,BN=require("bn.js"),parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=sign,module.exports.getKey=getKey,module.exports.makeKey=makeKey},{"./curves.json":90,"bn.js":64,"browserify-rsa":87,"create-hmac":118,elliptic:135,"parse-asn1":236,"safe-buffer":290}],93:[function(require,module,exports){function verify(sig,hash,key,signType,tag){var pub=parseKeys(key);if("ec"===pub.type){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");return ecVerify(sig,hash,pub)}if("dsa"===pub.type){if("dsa"!==signType)throw new Error("wrong public key type");return dsaVerify(sig,hash,pub)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");hash=Buffer.concat([tag,hash]);for(var len=pub.modulus.byteLength(),pad=[1],padNum=0;hash.length+pad.length+2<len;)pad.push(255),padNum++;pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);pad=Buffer.from(pad);var red=BN.mont(pub.modulus);sig=new BN(sig).toRed(red),sig=sig.redPow(new BN(pub.publicExponent)),sig=Buffer.from(sig.fromRed().toArray());var out=8>padNum?1:0;for(len=_Mathmin(sig.length,pad.length),sig.length!==pad.length&&(out=1),i=-1;++i<len;)out|=sig[i]^pad[i];return 0==out}function ecVerify(sig,hash,pub){var curveId=curves[pub.data.algorithm.curve.join(".")];if(!curveId)throw new Error("unknown curve "+pub.data.algorithm.curve.join("."));var curve=new EC(curveId),pubkey=pub.data.subjectPrivateKey.data;return curve.verify(hash,sig,pubkey)}function dsaVerify(sig,hash,pub){var p=pub.data.p,q=pub.data.q,g=pub.data.g,y=pub.data.pub_key,unpacked=parseKeys.signature.decode(sig,"der"),s=unpacked.s,r=unpacked.r;checkValue(s,q),checkValue(r,q);var montp=BN.mont(p),w=s.invm(q),v=g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q);return 0===v.cmp(r)}function checkValue(b,q){if(0>=b.cmpn(0))throw new Error("invalid sig");if(b.cmp(q)>=q)throw new Error("invalid sig")}var Buffer=require("safe-buffer").Buffer,BN=require("bn.js"),EC=require("elliptic").ec,parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=verify},{"./curves.json":90,"bn.js":64,elliptic:135,"parse-asn1":236,"safe-buffer":290}],94:[function(require,module,exports){arguments[4][66][0].apply(exports,arguments)},{dup:66}],95:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),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}],96:[function(require,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;!0;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);return 0<=nb?(0<nb&&(self.lastNeed=nb-1),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb)?(0<nb&&(self.lastNeed=nb-2),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb?(0<nb&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"\uFFFD";if(1<self.lastNeed&&1<buf.length){if(128!=(192&buf[1]))return self.lastNeed=1,"\uFFFD";if(2<self.lastNeed&&2<buf.length&&128!=(192&buf[2]))return self.lastNeed=2,"\uFFFD"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0===r?this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,p,0,buf.length),this.lastNeed-=buf.length):r}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"\uFFFD":r}function utf16Text(buf,i){if(0==(buf.length-i)%2){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(55296<=c&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<buf.length?r?r+this.text(buf,i):this.text(buf,i):r||""},StringDecoder.prototype.end=utf8End,StringDecoder.prototype.text=utf8Text,StringDecoder.prototype.fillLast=function(buf){return this.lastNeed<=buf.length?(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length)}},{"safe-buffer":95}],97:[function(require,module,exports){(function(Buffer){(function(){function allocUnsafe(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}module.exports=allocUnsafe}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],98:[function(require,module,exports){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function alloc(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"buffer-alloc-unsafe":97,"buffer-fill":99}],99:[function(require,module,exports){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}function fill(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=fill}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],100:[function(require,module,exports){(function(Buffer){(function(){module.exports=function xor(a,b){for(var length=_Mathmin(a.length,b.length),buffer=new Buffer(length),i=0;i<length;++i)buffer[i]=a[i]^b[i];return buffer}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],101:[function(require,module,exports){(function(Buffer){(function(){/*!
+ */function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return x<y?-1:y<x?1:0}function isBuffer(b){return global.Buffer&&"function"==typeof global.Buffer.isBuffer?global.Buffer.isBuffer(b):!!(null!=b&&b._isBuffer)}function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){return!isBuffer(arrbuf)&&!("function"!=typeof global.ArrayBuffer)&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(arrbuf):!!arrbuf&&(!!(arrbuf instanceof DataView)||!!(arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer)))}function getName(func){if(util.isFunction(func)){if(functionsHaveNames)return func.name;var str=func.toString(),match=str.match(regex);return match&&match[1]}}function truncate(s,n){return"string"==typeof s?s.length<n?s:s.slice(0,n):s}function inspect(something){if(functionsHaveNames||!util.isFunction(something))return util.inspect(something);var rawname=getName(something),name=rawname?": "+rawname:"";return"[Function"+name+"]"}function getMessage(self){return truncate(inspect(self.actual),128)+" "+self.operator+" "+truncate(inspect(self.expected),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}function ok(value,message){value||fail(value,!0,message,"==",assert.ok)}function _deepEqual(actual,expected,strict,memos){if(actual===expected)return!0;if(isBuffer(actual)&&isBuffer(expected))return 0===compare(actual,expected);if(util.isDate(actual)&&util.isDate(expected))return actual.getTime()===expected.getTime();if(util.isRegExp(actual)&&util.isRegExp(expected))return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase;if((null===actual||"object"!=typeof actual)&&(null===expected||"object"!=typeof expected))return strict?actual===expected:actual==expected;if(isView(actual)&&isView(expected)&&pToString(actual)===pToString(expected)&&!(actual instanceof Float32Array||actual instanceof Float64Array))return 0===compare(new Uint8Array(actual.buffer),new Uint8Array(expected.buffer));if(isBuffer(actual)!==isBuffer(expected))return!1;memos=memos||{actual:[],expected:[]};var actualIndex=memos.actual.indexOf(actual);return-1!==actualIndex&&actualIndex===memos.expected.indexOf(expected)||(memos.actual.push(actual),memos.expected.push(expected),objEquiv(actual,expected,strict,memos))}function isArguments(object){return"[object Arguments]"==Object.prototype.toString.call(object)}function objEquiv(a,b,strict,actualVisitedObjects){if(null===a||a===void 0||null===b||b===void 0)return!1;if(util.isPrimitive(a)||util.isPrimitive(b))return a===b;if(strict&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return!1;var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return!1;if(aIsArgs)return a=pSlice.call(a),b=pSlice.call(b),_deepEqual(a,b,strict);var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!==kb.length)return!1;for(ka.sort(),kb.sort(),i=ka.length-1;0<=i;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;0<=i;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError("\"block\" argument must be a function");"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}function strict(value,message){value||fail(value,!0,message,"==",strict)}var objectAssign=require("object-assign"),util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function foo(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function AssertionError(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(0<=idx){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function equal(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function notEqual(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function deepEqual(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function notDeepEqual(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function strictEqual(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function notStrictEqual(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err},assert.strict=objectAssign(strict,assert,{equal:assert.strictEqual,deepEqual:assert.deepStrictEqual,notEqual:assert.notStrictEqual,notDeepEqual:assert.notDeepStrictEqual}),assert.strict.strict=assert.strict;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"object-assign":230,"util/":35}],33:[function(require,module,exports){module.exports="function"==typeof Object.create?function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],34:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],35:[function(require,module,exports){(function(process,global){(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;i<l;++i)hasOwnProperty(value,i+"")?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,i+"",!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?desc.set?str=ctx.stylize("[Getter/Setter]","special"):str=ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(0>ctx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1<str.indexOf("\n")&&(array?str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,"\"").replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,0<=cur.indexOf("\n")&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return 60<length?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"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)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i<arguments.length;i++)objects.push(inspect(arguments[i]));return objects.join(" ")}for(var i=1,args=arguments,len=args.length,str=(f+"").replace(formatRegExp,function(x){if("%%"===x)return"%";if(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<len;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);else process.traceDeprecation?console.trace(msg):console.error(msg);warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(!0===process.noDeprecation)return fn;var warned=!1;return deprecated};var debugs={},debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./support/isBuffer":34,_process:246,inherits:33}],36:[function(require,module,exports){(function(global){(function(){"use strict";var possibleNames=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],g="undefined"==typeof globalThis?global:globalThis;module.exports=function availableTypedArrays(){for(var out=[],i=0;i<possibleNames.length;i++)"function"==typeof g[possibleNames[i]]&&(out[out.length]=possibleNames[i]);return out}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],37:[function(require,module,exports){function codecFor(encoding){switch(encoding){case"ascii":return ascii;case"base64":return base64;case"hex":return hex;case"utf8":case"utf-8":case void 0:return utf8;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16le;default:throw new Error(`Unknown encoding: ${encoding}`);}}function isBuffer(value){return value instanceof Uint8Array}function isEncoding(encoding){try{return codecFor(encoding),!0}catch{return!1}}function alloc(size,fill,encoding){const buffer=new Uint8Array(size);return void 0!==fill&&fill(buffer,fill,0,buffer.byteLength,encoding),buffer}function allocUnsafe(size){return new Uint8Array(size)}function allocUnsafeSlow(size){return new Uint8Array(size)}function byteLength(string,encoding){return codecFor(encoding).byteLength(string)}function compare(a,b){if(a===b)return 0;const len=_Mathmin(a.byteLength,b.byteLength);a=new DataView(a.buffer,a.byteOffset,a.byteLength),b=new DataView(b.buffer,b.byteOffset,b.byteLength);let i=0;for(let n=len-len%4;i<n;i+=4){const x=a.getUint32(i,LE),y=b.getUint32(i,LE);if(x!==y)break}for(;i<len;i++){const x=a.getUint8(i),y=b.getUint8(i);if(x<y)return-1;if(x>y)return 1}return a.byteLength>b.byteLength?1:a.byteLength<b.byteLength?-1:0}function concat(buffers,totalLength){void 0===totalLength&&(totalLength=buffers.reduce((len,buffer)=>len+buffer.byteLength,0));const result=new Uint8Array(totalLength);return buffers.reduce((offset,buffer)=>(result.set(buffer,offset),offset+buffer.byteLength),0),result}function copy(source,target,targetStart=0,start=0,end=source.byteLength){if(0<end&&end<start)return 0;if(end===start)return 0;if(0===source.byteLength||0===target.byteLength)return 0;if(0>targetStart)throw new RangeError("targetStart is out of range");if(0>start||start>=source.byteLength)throw new RangeError("sourceStart is out of range");if(0>end)throw new RangeError("sourceEnd is out of range");targetStart>=target.byteLength&&(targetStart=target.byteLength),end>source.byteLength&&(end=source.byteLength),target.byteLength-targetStart<end-start&&(end=target.length-targetStart+start);const len=end-start;return source===target?target.copyWithin(targetStart,start,end):target.set(source.subarray(start,end),targetStart),len}function equals(a,b){if(a===b)return!0;if(a.byteLength!==b.byteLength)return!1;const len=a.byteLength;a=new DataView(a.buffer,a.byteOffset,a.byteLength),b=new DataView(b.buffer,b.byteOffset,b.byteLength);let i=0;for(let n=len-len%4;i<n;i+=4)if(a.getUint32(i,LE)!==b.getUint32(i,LE))return!1;for(;i<len;i++)if(a.getUint8(i)!==b.getUint8(i))return!1;return!0}function fill(buffer,value,offset,end,encoding){if("string"==typeof value?"string"==typeof offset?(encoding=offset,offset=0,end=buffer.byteLength):"string"==typeof end&&(encoding=end,end=buffer.byteLength):"number"==typeof val?value&=255:"boolean"==typeof val&&(value=+value),0>offset||buffer.byteLength<offset||buffer.byteLength<end)throw new RangeError("Out of range index");if(void 0===offset&&(offset=0),void 0===end&&(end=buffer.byteLength),end<=offset)return buffer;if(value||(value=0),"number"==typeof value)for(let i=offset;i<end;++i)buffer[i]=value;else{value=isBuffer(value)?value:from(value,encoding);const len=value.byteLength;for(let i=0;i<end-offset;++i)buffer[i+offset]=value[i%len]}return buffer}function from(value,encodingOrOffset,length){return"string"==typeof value?fromString(value,encodingOrOffset):Array.isArray(value)?fromArray(value):ArrayBuffer.isView(value)?fromBuffer(value):fromArrayBuffer(value,encodingOrOffset,length)}function fromString(string,encoding){const codec=codecFor(encoding),buffer=new Uint8Array(codec.byteLength(string));return codec.write(buffer,string,0,buffer.byteLength),buffer}function fromArray(array){const buffer=new Uint8Array(array.length);return buffer.set(array),buffer}function fromBuffer(buffer){const copy=new Uint8Array(buffer.byteLength);return copy.set(buffer),copy}function fromArrayBuffer(arrayBuffer,byteOffset,length){return new Uint8Array(arrayBuffer,byteOffset,length)}function includes(buffer,value,byteOffset,encoding){return-1!==indexOf(buffer,value,byteOffset,encoding)}function bidirectionalIndexOf(buffer,value,byteOffset,encoding,first){if(0===buffer.byteLength)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):void 0===byteOffset?byteOffset=first?0:buffer.length-1:0>byteOffset&&(byteOffset+=buffer.byteLength),byteOffset>=buffer.byteLength){if(first)return-1;byteOffset=buffer.byteLength-1}else if(0>byteOffset)if(first)byteOffset=0;else return-1;if("string"==typeof value)value=from(value,encoding);else if("number"==typeof value)return value&=255,first?buffer.indexOf(value,byteOffset):buffer.lastIndexOf(value,byteOffset);if(0===value.byteLength)return-1;if(first){let foundIndex=-1;for(let i=byteOffset;i<buffer.byteLength;i++)if(buffer[i]!==value[-1===foundIndex?0:i-foundIndex])-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1;else if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===value.byteLength)return foundIndex}else{byteOffset+value.byteLength>buffer.byteLength&&(byteOffset=buffer.byteLength-value.byteLength);for(let i=byteOffset,found;0<=i;i--){found=!0;for(let j=0;j<value.byteLength;j++)if(buffer[i+j]!==value[j]){found=!1;break}if(found)return i}}return-1}function indexOf(buffer,value,byteOffset,encoding){return bidirectionalIndexOf(buffer,value,byteOffset,encoding,!0)}function lastIndexOf(buffer,value,byteOffset,encoding){return bidirectionalIndexOf(buffer,value,byteOffset,encoding,!1)}function swap(buffer,n,m){const i=buffer[n];buffer[n]=buffer[m],buffer[m]=i}function swap16(buffer){const len=buffer.byteLength;if(0!=len%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let i=0;i<len;i+=2)swap(buffer,i,i+1);return buffer}function swap32(buffer){const len=buffer.byteLength;if(0!=len%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let i=0;i<len;i+=4)swap(buffer,i,i+3),swap(buffer,i+1,i+2);return buffer}function swap64(buffer){const len=buffer.byteLength;if(0!=len%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let i=0;i<len;i+=8)swap(buffer,i,i+7),swap(buffer,i+1,i+6),swap(buffer,i+2,i+5),swap(buffer,i+3,i+4);return buffer}function toBuffer(buffer){return buffer}function toString(buffer,encoding,start=0,end=buffer.byteLength){const len=buffer.byteLength;return start>=len?"":end<=start?"":(0>start&&(start=0),end>len&&(end=len),(0!==start||end<len)&&(buffer=buffer.subarray(start,end)),codecFor(encoding).toString(buffer))}function write(buffer,string,offset,length,encoding){return void 0===offset?encoding="utf8":void 0===length&&"string"==typeof offset?(encoding=offset,offset=void 0):void 0===encoding&&"string"==typeof length&&(encoding=length,length=void 0),codecFor(encoding).write(buffer,string,offset,length)}const ascii=require("./lib/ascii"),base64=require("./lib/base64"),hex=require("./lib/hex"),utf8=require("./lib/utf8"),utf16le=require("./lib/utf16le"),LE=255===new Uint8Array(Uint16Array.of(255).buffer)[0];module.exports={isBuffer,isEncoding,alloc,allocUnsafe,allocUnsafeSlow,byteLength,compare,concat,copy,equals,fill,from,includes,indexOf,lastIndexOf,swap16,swap32,swap64,toBuffer,toString,write}},{"./lib/ascii":38,"./lib/base64":39,"./lib/hex":40,"./lib/utf16le":41,"./lib/utf8":42}],38:[function(require,module,exports){function byteLength(string){return string.length}function toString(buffer){const len=buffer.byteLength;let result="";for(let i=0;i<len;i++)result+=_StringfromCharCode(buffer[i]);return result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);for(let i=0;i<len;i++)buffer[offset+i]=string.charCodeAt(i);return len}module.exports={byteLength,toString,write}},{}],39:[function(require,module,exports){function byteLength(string){let len=string.length;return 61===string.charCodeAt(len-1)&&len--,1<len&&61===string.charCodeAt(len-1)&&len--,3*len>>>2}function toString(buffer){const len=buffer.byteLength;let result="";for(let i=0;i<len;i+=3)result+=alphabet[buffer[i]>>2]+alphabet[(3&buffer[i])<<4|buffer[i+1]>>4]+alphabet[(15&buffer[i+1])<<2|buffer[i+2]>>6]+alphabet[63&buffer[i+2]];return 2==len%3?result=result.substring(0,result.length-1)+"=":1==len%3&&(result=result.substring(0,result.length-2)+"=="),result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);for(let i=0,j=0;i<len;i+=4){const a=codes[string.charCodeAt(i)],b=codes[string.charCodeAt(i+1)],c=codes[string.charCodeAt(i+2)],d=codes[string.charCodeAt(i+3)];buffer[j++]=a<<2|b>>4,buffer[j++]=(15&b)<<4|c>>2,buffer[j++]=(3&c)<<6|63&d}return len}const alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",codes=new Uint8Array(256);for(let i=0;i<alphabet.length;i++)codes[alphabet.charCodeAt(i)]=i;codes[45]=62,codes[95]=63;module.exports={byteLength,toString,write}},{}],40:[function(require,module,exports){function byteLength(string){return string.length>>>1}function toString(buffer){const len=buffer.byteLength;buffer=new DataView(buffer.buffer,buffer.byteOffset,len);let result="",i=0;for(let n=len-len%4;i<n;i+=4)result+=buffer.getUint32(i).toString(16).padStart(8,"0");for(;i<len;i++)result+=buffer.getUint8(i).toString(16).padStart(2,"0");return result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);for(let i=0;i<len;i++){const a=hexValue(string.charCodeAt(2*i)),b=hexValue(string.charCodeAt(2*i+1));if(a===void 0||b===void 0)return buffer.subarray(0,i);buffer[offset+i]=a<<4|b}return len}function hexValue(char){return 48<=char&&57>=char?char-48:65<=char&&70>=char?char-65+10:97<=char&&102>=char?char-97+10:void 0}module.exports={byteLength,toString,write}},{}],41:[function(require,module,exports){function byteLength(string){return 2*string.length}function toString(buffer){const len=buffer.byteLength;let result="";for(let i=0;i<len-1;i+=2)result+=_StringfromCharCode(buffer[i]+256*buffer[i+1]);return result}function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);let units=len;for(let i=0;i<string.length&&!(0>(units-=2));++i){const c=string.charCodeAt(i),hi=c>>8,lo=c%256;buffer[offset+2*i]=lo,buffer[offset+2*i+1]=hi}return len}module.exports={byteLength,toString,write}},{}],42:[function(require,module,exports){function byteLength(string){let length=0;for(let i=0,n=string.length;i<n;i++){const code=string.charCodeAt(i);if(55296<=code&&56319>=code&&i+1<n){const code=string.charCodeAt(i+1);if(56320<=code&&57343>=code){length+=4,i++;continue}}length+=127>=code?1:2047>=code?2:3}return length}let toString;if("undefined"!=typeof TextDecoder){const decoder=new TextDecoder;toString=function toString(buffer){return decoder.decode(buffer)}}else toString=function toString(buffer){var _StringfromCodePoint=String.fromCodePoint;const len=buffer.byteLength;let output="",i=0;for(;i<len;){let byte=buffer[i];if(127>=byte){output+=_StringfromCharCode(byte),i++;continue}let bytesNeeded=0,codePoint=0;if(223>=byte?(bytesNeeded=1,codePoint=31&byte):239>=byte?(bytesNeeded=2,codePoint=15&byte):244>=byte&&(bytesNeeded=3,codePoint=7&byte),0<len-i-bytesNeeded)for(let k=0;k<bytesNeeded;)byte=buffer[i+k+1],codePoint=codePoint<<6|63&byte,k+=1;else codePoint=65533,bytesNeeded=len-i;output+=_StringfromCodePoint(codePoint),i+=bytesNeeded+1}return output};let write;if("undefined"!=typeof TextEncoder){const encoder=new TextEncoder;write=function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);return encoder.encodeInto(string,buffer.subarray(offset,offset+len)),len}}else write=function write(buffer,string,offset=0,length=byteLength(string)){const len=_Mathmin(length,buffer.byteLength-offset);buffer=buffer.subarray(offset,offset+len);let i=0,j=0;for(;i<string.length;){const code=string.codePointAt(i);if(127>=code){buffer[j++]=code,i++;continue}let count=0,bits=0;for(2047>=code?(count=6,bits=192):65535>=code?(count=12,bits=224):2097151>=code&&(count=18,bits=240),buffer[j++]=bits|code>>count,count-=6;0<=count;)buffer[j++]=128|63&code>>count,count-=6;i+=65536<=code?2:1}return len};module.exports={byteLength,toString,write}},{}],43:[function(require,module,exports){"use strict";function getLens(b64){var len=b64.length;if(0<len%4)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");-1===validLen&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=0<placeHoldersLen?validLen-4:validLen,tmp,i;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=255&tmp>>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;i<end;i+=3)tmp=(16711680&uint8[i]<<16)+(65280&uint8[i+1]<<8)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes,tmp;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62,revLookup[95]=63},{}],44:[function(require,module,exports){(function(Buffer){(function(){function getIntFromBuffer(buffer,start,end){let sum=0,sign=1;for(let i=start;i<end;i++){const num=buffer[i];if(58>num&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}const INTEGER_START=105,STRING_DELIM=58,DICTIONARY_START=100,LIST_START=108,END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case DICTIONARY_START:return decode.dictionary();case LIST_START:return decode.list();case INTEGER_START:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){let i=decode.position;const c=decode.data.length,d=decode.data;for(;i<c;){if(d[i]===chr)return i;i++}throw new Error("Invalid data: Missing delimiter \""+_StringfromCharCode(chr)+"\" [0x"+chr.toString(16)+"]")},decode.dictionary=function(){decode.position++;const dict={};for(;decode.data[decode.position]!==END_OF_TYPE;)dict[decode.buffer()]=decode.next();return decode.position++,dict},decode.list=function(){decode.position++;const lst=[];for(;decode.data[decode.position]!==END_OF_TYPE;)lst.push(decode.next());return decode.position++,lst},decode.integer=function(){const end=decode.find(END_OF_TYPE),number=getIntFromBuffer(decode.data,decode.position+1,end);return decode.position+=end+1-decode.position,number},decode.buffer=function(){let sep=decode.find(STRING_DELIM);const length=getIntFromBuffer(decode.data,decode.position,sep),end=++sep+length;return decode.position=end,decode.encoding?decode.data.toString(decode.encoding,sep,end):decode.data.slice(sep,end)},module.exports=decode}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],45:[function(require,module,exports){(function(Buffer){(function(){function encode(data,buffer,offset){const buffers=[];let result=null;return encode._encode(buffers,data),result=Buffer.concat(buffers),encode.bytes=result.length,Buffer.isBuffer(buffer)?(result.copy(buffer,offset),buffer):result}const{getType}=require("./util.js");encode.bytes=-1,encode._floatConversionDetected=!1,encode._encode=function(buffers,data){if(null!=data)switch(getType(data)){case"buffer":encode.buffer(buffers,data);break;case"object":encode.dict(buffers,data);break;case"map":encode.dictMap(buffers,data);break;case"array":encode.list(buffers,data);break;case"set":encode.listSet(buffers,data);break;case"string":encode.string(buffers,data);break;case"number":encode.number(buffers,data);break;case"boolean":encode.number(buffers,data);break;case"arraybufferview":encode.buffer(buffers,Buffer.from(data.buffer,data.byteOffset,data.byteLength));break;case"arraybuffer":encode.buffer(buffers,Buffer.from(data));}};const buffE=Buffer.from("e"),buffD=Buffer.from("d"),buffL=Buffer.from("l");encode.buffer=function(buffers,data){buffers.push(Buffer.from(data.length+":"),data)},encode.string=function(buffers,data){buffers.push(Buffer.from(Buffer.byteLength(data)+":"+data))},encode.number=function(buffers,data){const maxLo=2147483648,hi=data/2147483648<<0,lo=data%2147483648<<0,val=hi*2147483648+lo;buffers.push(Buffer.from("i"+val+"e")),val===data||encode._floatConversionDetected||(encode._floatConversionDetected=!0,console.warn("WARNING: Possible data corruption detected with value \""+data+"\":","Bencoding only defines support for integers, value was converted to \""+val+"\""),console.trace())},encode.dict=function(buffers,data){buffers.push(buffD);let j=0,k;const keys=Object.keys(data).sort(),kl=keys.length;for(;j<kl;j++)k=keys[j],null!=data[k]&&(encode.string(buffers,k),encode._encode(buffers,data[k]));buffers.push(buffE)},encode.dictMap=function(buffers,data){buffers.push(buffD);const keys=Array.from(data.keys()).sort();for(const key of keys)null!=data.get(key)&&(Buffer.isBuffer(key)?encode._encode(buffers,key):encode.string(buffers,key+""),encode._encode(buffers,data.get(key)));buffers.push(buffE)},encode.list=function(buffers,data){let i=0;const c=data.length;for(buffers.push(buffL);i<c;i++)null!=data[i]&&encode._encode(buffers,data[i]);buffers.push(buffE)},encode.listSet=function(buffers,data){buffers.push(buffL);for(const item of data)null!=item&&encode._encode(buffers,item);buffers.push(buffE)},module.exports=encode}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":48,buffer:101}],46:[function(require,module,exports){(function(Buffer){(function(){function listLength(list){let length=2;for(const value of list)length+=encodingLength(value);return length}function mapLength(map){let length=2;for(const[key,value]of map){const keyLength=Buffer.byteLength(key);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value)}return length}function objectLength(value){let length=2;const keys=Object.keys(value);for(let i=0;i<keys.length;i++){const keyLength=Buffer.byteLength(keys[i]);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value[keys[i]])}return length}function stringLength(value){const length=Buffer.byteLength(value);return digitCount(length)+1+length}function arrayBufferLength(value){const length=value.byteLength-value.byteOffset;return digitCount(length)+1+length}function encodingLength(value){const length=0;if(null==value)return 0;const type=getType(value);switch(type){case"buffer":return digitCount(value.length)+1+value.length;case"arraybufferview":return arrayBufferLength(value);case"string":return stringLength(value);case"array":case"set":return listLength(value);case"number":return 1+digitCount(_Mathfloor(value))+1;case"bigint":return 1+value.toString().length+1;case"object":return objectLength(value);case"map":return mapLength(value);default:throw new TypeError(`Unsupported value of type "${type}"`);}}const{digitCount,getType}=require("./util.js");module.exports=encodingLength}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":48,buffer:101}],47:[function(require,module,exports){const bencode=module.exports;bencode.encode=require("./encode.js"),bencode.decode=require("./decode.js"),bencode.byteLength=bencode.encodingLength=require("./encoding-length.js")},{"./decode.js":44,"./encode.js":45,"./encoding-length.js":46}],48:[function(require,module,exports){(function(Buffer){(function(){const util=module.exports;util.digitCount=function digitCount(value){var _Mathlog=Math.log10;const sign=0>value?1:0;return value=_Mathabs(+(value||1)),_Mathfloor(_Mathlog(value))+1+sign},util.getType=function getType(value){return Buffer.isBuffer(value)?"buffer":ArrayBuffer.isView(value)?"arraybufferview":Array.isArray(value)?"array":value instanceof Number?"number":value instanceof Boolean?"boolean":value instanceof Set?"set":value instanceof Map?"map":value instanceof String?"string":value instanceof ArrayBuffer?"arraybuffer":typeof value}}).call(this)}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":193}],49:[function(require,module,exports){function composeRange(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1<cur.length?`${cur[0]}-${cur[cur.length-1]}`:`${cur[0]}`)}function parseRange(range){const generateRange=(start,end=start)=>Array.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur,idx,arr)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=composeRange},{}],50:[function(require,module,exports){module.exports=function(haystack,needle,comparator,low,high){var mid,cmp;if(void 0===low)low=0;else if(low|=0,0>low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high<low||high>=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0<cmp)high=mid-1;else return mid;return~low}},{}],51:[function(require,module,exports){"use strict";function getByteSize(num){var out=num>>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j<this.buffer.length&&!!(this.buffer[j]&128>>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length<j+1){var length=_Mathmax(j+1,_Mathmin(2*this.buffer.length,this.grow));if(length<=this.grow){var newBuffer=new Uint8Array(length);newBuffer.set(this.buffer),this.buffer=newBuffer}}this.buffer[j]|=128>>i%8}else j<this.buffer.length&&(this.buffer[j]&=~(128>>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i<end;i++)fn(!!(byte&y),i),y=1==y?(byte=this.buffer[++j],128):y>>1},BitField}();exports.default=BitField},{}],52:[function(require,module,exports){(function(process,Buffer){(function(){function noop(){}function sha1(buf){return Buffer.from(simpleSha1.sync(buf),"hex")}function createGetResponse(id,token,value){const r={id,token,v:value.v};return value.sig&&(r.sig=value.sig,r.k=value.k,"number"==typeof value.seq&&(r.seq=value.seq)),r}function encodePeer(host,port){const buf=Buffer.allocUnsafe(6),ip=host.split(".");for(let i=0;4>i;i++)buf[i]=parseInt(ip[i]||0,10);return buf.writeUInt16BE(port,4),buf}function decodePeers(buf){const peers=[];try{for(let i=0;i<buf.length;i++){const port=buf[i].readUInt16BE(4);port&&peers.push({host:parseIp(buf[i],0),port})}}catch(err){}return peers}function parseIp(buf,offset){return`${buf[offset++]}.${buf[offset++]}.${buf[offset++]}.${buf[offset++]}`}function encodeSigData(msg){const ref={seq:msg.seq||0,v:msg.v};return msg.salt&&(ref.salt=msg.salt),bencode.encode(ref).slice(1,-1)}function toNode(node){return{host:node.host,port:node.port}}function toBuffer(str){if(Buffer.isBuffer(str))return str;if(ArrayBuffer.isView(str))return Buffer.from(str.buffer,str.byteOffset,str.byteLength);if("string"==typeof str)return Buffer.from(str,"hex");throw new Error("Pass a buffer or a string")}const bencode=require("bencode"),debug=require("debug")("bittorrent-dht"),KBucket=require("k-bucket"),krpc=require("k-rpc"),low=require("last-one-wins"),LRU=require("lru"),randombytes=require("randombytes"),records=require("record-cache"),simpleSha1=require("simple-sha1"),{EventEmitter}=require("events"),ROTATE_INTERVAL=300000,BUCKET_OUTDATED_TIMESPAN=900000;class DHT extends EventEmitter{constructor(opts={}){function ping(opts,cb){const older=opts.older,swap=opts.swap;self._debug("received ping",older),self._checkNodes(older,!1,(_,deadNode)=>deadNode?(self._debug("swaping dead node with newer",deadNode),swap(deadNode),cb()):void(self._debug("no node added, all other nodes ok"),cb()))}function onlistening(){self.listening=!0,self._debug("listening %d",self.address().port),self.updateBucketTimestamp(),self._setBucketCheckInterval(),self.emit("listening")}function onquery(query,peer){self._onquery(query,peer)}function rotateSecrets(){self._rotateSecrets()}function bootstrap(){self.destroyed||self._bootstrap(!1!==opts.bootstrap)}function onwarning(err){self.emit("warning",err)}function onerror(err){self.emit("error",err)}function onnode(node){self.emit("node",node)}super(),this._tables=new LRU({maxAge:ROTATE_INTERVAL,max:opts.maxTables||1e3}),this._values=new LRU(opts.maxValues||1e3),this._peers=records({maxAge:opts.maxAge||0,maxSize:opts.maxPeers||1e4}),this._secrets=null,this._hash=opts.hash||sha1,this._hashLength=this._hash(Buffer.from("")).length,this._rpc=opts.krpc||krpc(Object.assign({idLength:this._hashLength},opts)),this._rpc.on("query",onquery),this._rpc.on("node",onnode),this._rpc.on("warning",onwarning),this._rpc.on("error",onerror),this._rpc.on("listening",onlistening),this._rotateSecrets(),this._verify=opts.verify||null,this._host=opts.host||null,this._interval=setInterval(rotateSecrets,ROTATE_INTERVAL),this._runningBucketCheck=!1,this._bucketCheckTimeout=null,this._bucketOutdatedTimeSpan=opts.timeBucketOutdated||BUCKET_OUTDATED_TIMESPAN,this.listening=!1,this.destroyed=!1,this.nodeId=this._rpc.id,this.nodes=this._rpc.nodes;const onping=low(ping);this._rpc.on("ping",(older,swap)=>{onping({older,swap})}),process.nextTick(bootstrap),this._debug("new DHT %s",this.nodeId);const self=this}_setBucketCheckInterval(){function checkBucket(){const diff=Date.now()-self._rpc.nodes.metadata.lastChange;return diff<self._bucketOutdatedTimeSpan?queueNext():void self._pingAll(()=>{self.destroyed||(1>self.nodes.toArray().length&&self._bootstrap(!0),queueNext())})}function queueNext(){if(self._runningBucketCheck&&!self.destroyed){const nextTimeout=_Mathfloor(Math.random()*interval+30000);self._bucketCheckTimeout=setTimeout(checkBucket,nextTimeout)}}const self=this,interval=60000;this._runningBucketCheck=!0,queueNext()}_pingAll(cb){this._checkAndRemoveNodes(this.nodes.toArray(),cb)}removeBucketCheckInterval(){this._runningBucketCheck=!1,clearTimeout(this._bucketCheckTimeout)}updateBucketTimestamp(){this._rpc.nodes.metadata.lastChange=Date.now()}_checkAndRemoveNodes(nodes,cb){const self=this;this._checkNodes(nodes,!0,(_,node)=>{node&&self.removeNode(node.id),cb(null,node)})}_checkNodes(nodes,force,cb){function test(acc){let current=null;for(;acc.length&&(current=acc.pop(),current.id&&!force)&&!(1e4<Date.now()-(current.seen||0));)current=null;return current?void self._sendPing(current,err=>err?void cb(null,current):(self.updateBucketTimestamp(),test(acc))):cb(null)}const self=this;test(nodes)}addNode(node){const self=this;if(node.id){node.id=toBuffer(node.id);const old=!!this._rpc.nodes.get(node.id);return this._rpc.nodes.add(node),void(old||(this.emit("node",node),this.updateBucketTimestamp()))}this._sendPing(node,(_,node)=>{node&&self.addNode(node)})}removeNode(id){this._rpc.nodes.remove(toBuffer(id))}_sendPing(node,cb){const self=this,expectedId=node.id;this._rpc.query(node,{q:"ping"},(err,pong,node)=>err?cb(err):pong.r&&pong.r.id&&Buffer.isBuffer(pong.r.id)&&pong.r.id.length===self._hashLength?Buffer.isBuffer(expectedId)&&!expectedId.equals(pong.r.id)?cb(new Error("Unexpected node id")):void(self.updateBucketTimestamp(),cb(null,{id:pong.r.id,host:node.host||node.address,port:node.port})):cb(new Error("Bad reply")))}toJSON(){const self=this,values={};return Object.keys(this._values.cache).forEach(key=>{const value=self._values.cache[key].value;values[key]={v:value.v.toString("hex"),id:value.id.toString("hex")},null!=value.seq&&(values[key].seq=value.seq),null!=value.sig&&(values[key].sig=value.sig.toString("hex")),null!=value.k&&(values[key].k=value.k.toString("hex"))}),{nodes:this._rpc.nodes.toArray().map(toNode),values}}put(opts,cb){(Buffer.isBuffer(opts)||"string"==typeof opts)&&(opts={v:opts});const isMutable=!!opts.k;if(opts.v===void 0)throw new Error("opts.v not given");if(1e3<=opts.v.length)throw new Error("v must be less than 1000 bytes in put()");if(isMutable&&void 0!==opts.cas&&"number"!=typeof opts.cas)throw new Error("opts.cas must be an integer if provided");if(isMutable&&32!==opts.k.length)throw new Error("opts.k ed25519 public key must be 32 bytes");if(isMutable&&"function"!=typeof opts.sign&&!Buffer.isBuffer(opts.sig))throw new Error("opts.sign function or options.sig signature is required for mutable put");if(isMutable&&opts.salt&&64<opts.salt.length)throw new Error("opts.salt is > 64 bytes long");if(isMutable&&void 0===opts.seq)throw new Error("opts.seq not provided for a mutable update");if(isMutable&&"number"!=typeof opts.seq)throw new Error("opts.seq not an integer");return this._put(opts,cb)}_put(opts,cb){cb||(cb=noop);const isMutable=!!opts.k,v="string"==typeof opts.v?Buffer.from(opts.v):opts.v,key=isMutable?this._hash(opts.salt?Buffer.concat([opts.k,opts.salt]):opts.k):this._hash(bencode.encode(v)),table=this._tables.get(key.toString("hex"));if(!table)return this._preput(key,opts,cb);const message={q:"put",a:{id:this._rpc.id,token:null,v}};return isMutable?("number"==typeof opts.cas&&(message.a.cas=opts.cas),opts.salt&&(message.a.salt=opts.salt),message.a.k=opts.k,message.a.seq=opts.seq,"function"==typeof opts.sign?message.a.sig=opts.sign(encodeSigData(message.a)):Buffer.isBuffer(opts.sig)&&(message.a.sig=opts.sig)):this._values.set(key.toString("hex"),message.a),this._rpc.queryAll(table.closest(key),message,null,(err,n)=>err?cb(err,key,n):void cb(null,key,n)),key}_preput(key,opts,cb){const self=this;return this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},null,(err,n)=>err?cb(err):void self.put(opts,cb)),key}get(key,opts,cb){function done(err){return err?cb(err):void cb(null,value)}function onreply(message){const r=message.r;if(!r||!r.v)return!0;const isMutable=r.k||r.sig;if(opts.salt&&(r.salt=Buffer.from(opts.salt)),isMutable){if(!verify||!r.sig||!r.k)return!0;if(!verify(r.sig,encodeSigData(r),r.k))return!0;hash(r.salt?Buffer.concat([r.k,r.salt]):r.k).equals(key)&&(!value||r.seq>value.seq)&&(value=r)}else if(hash(bencode.encode(r.v)).equals(key))return value=r,!1;return!0}key=toBuffer(key),"function"==typeof opts&&(cb=opts,opts=null),opts||(opts={});const verify=opts.verify||this._verify,hash=this._hash;let value=this._values.get(key.toString("hex"))||null;return value&&!1!==opts.cache?(value=createGetResponse(this._rpc.id,null,value),process.nextTick(done)):void this._closest(key,{q:"get",a:{id:this._rpc.id,target:key}},onreply,done)}announce(infoHash,port,cb){if("function"==typeof port)return this.announce(infoHash,0,port);infoHash=toBuffer(infoHash),cb||(cb=noop);const table=this._tables.get(infoHash.toString("hex"));if(!table)return this._preannounce(infoHash,port,cb);if(this._host){const dhtPort=this.listening?this.address().port:0;this._addPeer({host:this._host,port:port||dhtPort},infoHash,{host:this._host,port:dhtPort})}const message={q:"announce_peer",a:{id:this._rpc.id,token:null,info_hash:infoHash,port,implied_port:port?0:1}};this._debug("announce %s %d",infoHash,port),this._rpc.queryAll(table.closest(infoHash),message,null,cb)}_preannounce(infoHash,port,cb){const self=this;this.lookup(infoHash,err=>self.destroyed?cb(new Error("dht is destroyed")):err?cb(err):void self.announce(infoHash,port,cb))}lookup(infoHash,cb){function emit(values,from){values||(values=self._peers.get(infoHash.toString("hex"),100));const peers=decodePeers(values);for(let i=0;i<peers.length;i++)self.emit("peer",peers[i],infoHash,from||null)}function onreply(message,node){return!aborted&&void(message.r.values&&emit(message.r.values,node))}infoHash=toBuffer(infoHash),cb||(cb=noop);const self=this;let aborted=!1;return this._debug("lookup %s",infoHash),process.nextTick(emit),this._closest(infoHash,{q:"get_peers",a:{id:this._rpc.id,info_hash:infoHash}},onreply,cb),function abort(){aborted=!0}}address(){return this._rpc.address()}listen(...args){this._rpc.bind(...args)}destroy(cb){if(this.destroyed)return void(cb&&process.nextTick(cb));this.destroyed=!0;const self=this;clearInterval(this._interval),this.removeBucketCheckInterval(),this._peers.destroy(),this._debug("destroying"),this._rpc.destroy(()=>{self.emit("close"),cb&&cb()})}_onquery(query,peer){if(void 0!==query.q&&null!==query.q){const q=query.q.toString();if(this._debug("received %s query from %s:%d",q,peer.address,peer.port),!!query.a)return"ping"===q?this._rpc.response(peer,query,{id:this._rpc.id}):"find_node"===q?this._onfindnode(query,peer):"get_peers"===q?this._ongetpeers(query,peer):"announce_peer"===q?this._onannouncepeer(query,peer):"get"===q?this._onget(query,peer):"put"===q?this._onput(query,peer):void 0}}_onfindnode(query,peer){const target=query.a.target;if(!target)return this._rpc.error(peer,query,[203,"`find_node` missing required `a.target` field"]);this.emit("find_node",target);const nodes=this._rpc.nodes.closest(target);this._rpc.response(peer,query,{id:this._rpc.id},nodes)}_ongetpeers(query,peer){const host=peer.address||peer.host,infoHash=query.a.info_hash;if(!infoHash)return this._rpc.error(peer,query,[203,"`get_peers` missing required `a.info_hash` field"]);this.emit("get_peers",infoHash);const r={id:this._rpc.id,token:this._generateToken(host)},peers=this._peers.get(infoHash.toString("hex"));peers.length?(r.values=peers,this._rpc.response(peer,query,r)):this._rpc.response(peer,query,r,this._rpc.nodes.closest(infoHash))}_onannouncepeer(query,peer){const host=peer.address||peer.host,port=query.a.implied_port?peer.port:query.a.port;if(!port||"number"!=typeof port||0>=port||65535<port)return;const infoHash=query.a.info_hash,token=query.a.token;return infoHash&&token?this._validateToken(host,token)?void(this.emit("announce_peer",infoHash,{host,port:peer.port}),this._addPeer({host,port},infoHash,{host,port:peer.port}),this._rpc.response(peer,query,{id:this._rpc.id})):this._rpc.error(peer,query,[203,"cannot `announce_peer` with bad token"]):void 0}_addPeer(peer,infoHash,from){this._peers.add(infoHash.toString("hex"),encodePeer(peer.host,peer.port)),this.emit("announce",peer,infoHash,from)}_onget(query,peer){const host=peer.address||peer.host,target=query.a.target;if(!target)return;const token=this._generateToken(host),value=this._values.get(target.toString("hex"));if(this.emit("get",target,value),!value){const nodes=this._rpc.nodes.closest(target);this._rpc.response(peer,query,{id:this._rpc.id,token},nodes)}else this._rpc.response(peer,query,createGetResponse(this._rpc.id,token,value))}_onput(query,peer){const host=peer.address||peer.host,a=query.a;if(!a)return;const v=query.a.v;if(!v)return;const id=query.a.id;if(!id)return;const token=a.token;if(!token)return;if(!this._validateToken(host,token))return this._rpc.error(peer,query,[203,"cannot `put` with bad token"]);if(1e3<v.length)return this._rpc.error(peer,query,[205,"data payload too large"]);const isMutable=!!(a.k||a.sig);if(isMutable&&!a.k&&!a.sig)return;const key=isMutable?this._hash(a.salt?Buffer.concat([a.k,a.salt]):a.k):this._hash(bencode.encode(v)),keyHex=key.toString("hex");if(this.emit("put",key,v),isMutable){if(!this._verify)return this._rpc.error(peer,query,[400,"verification not supported"]);if(!this._verify(a.sig,encodeSigData(a),a.k))return;const prev=this._values.get(keyHex);if(prev&&"number"==typeof a.cas&&prev.seq!==a.cas)return this._rpc.error(peer,query,[301,"CAS mismatch, re-read and try again"]);if(prev&&"number"==typeof prev.seq&&!(a.seq>prev.seq))return this._rpc.error(peer,query,[302,"sequence number less than current"]);this._values.set(keyHex,{v,k:a.k,salt:a.salt,sig:a.sig,seq:a.seq,id})}else this._values.set(keyHex,{v,id});this._rpc.response(peer,query,{id:this._rpc.id})}_bootstrap(populate){function ready(){self.ready||(self._debug("emit ready"),self.ready=!0,self.emit("ready"))}const self=this;return populate?void this._rpc.populate(self._rpc.id,{q:"find_node",a:{id:self._rpc.id,target:self._rpc.id}},ready):process.nextTick(ready)}_closest(target,message,onmessage,cb){function done(err,n){return err?cb(err):void(self._tables.set(target.toString("hex"),table),self._debug("visited %d nodes",n),cb(null,n))}function onreply(message,node){return!message.r||(message.r.token&&message.r.id&&Buffer.isBuffer(message.r.id)&&message.r.id.length===self._hashLength&&(self._debug("found node %s (target: %s)",message.r.id,target),table.add({id:message.r.id,host:node.host||node.address,port:node.port,token:message.r.token})),!onmessage||onmessage(message,node))}const self=this,table=new KBucket({localNodeId:target,numberOfNodesPerKBucket:this._rpc.k});this._rpc.closest(target,message,onreply,done)}_debug(){if(debug.enabled){const args=[].slice.call(arguments);args[0]=`[${this.nodeId.toString("hex").substring(0,7)}] ${args[0]}`;for(let i=1;i<args.length;i++)Buffer.isBuffer(args[i])&&(args[i]=args[i].toString("hex"));debug(...args)}}_validateToken(host,token){const tokenA=this._generateToken(host,this._secrets[0]),tokenB=this._generateToken(host,this._secrets[1]);return token.equals(tokenA)||token.equals(tokenB)}_generateToken(host,secret){return secret||(secret=this._secrets[0]),this._hash(Buffer.concat([Buffer.from(host),secret]))}_rotateSecrets(){this._secrets?(this._secrets[1]=this._secrets[0],this._secrets[0]=randombytes(this._hashLength)):this._secrets=[randombytes(this._hashLength),randombytes(this._hashLength)]}}module.exports=DHT}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{_process:246,bencode:47,buffer:101,debug:122,events:156,"k-bucket":199,"k-rpc":201,"last-one-wins":202,lru:207,randombytes:262,"record-cache":282,"simple-sha1":303}],53:[function(require,module,exports){/*! bittorrent-lsd. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */const dgram=require("dgram"),EventEmitter=require("events").EventEmitter,debug=require("debug")("bittorrent-lsd"),ANNOUNCE_INTERVAL=3e5,LSD_HOST="239.192.152.143",LSD_PORT=6771;class LSD 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(!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="string"==typeof opts.port?opts.port:opts.port.toString(),this.cookie=`bittorrent-lsd-${this.peerId}`,this.destroyed=!1,this.annouceIntervalId=null,this.server=dgram.createSocket({type:"udp4",reuseAddr:!0});const onListening=()=>{debug("listening");try{this.server.addMembership(LSD_HOST)}catch(err){this.emit("warning",err)}},onMessage=(msg,rinfo)=>{debug("message",msg.toString(),`${rinfo.address}:${rinfo.port}`);const parsedAnnounce=this._parseAnnounce(msg.toString());null===parsedAnnounce||parsedAnnounce.cookie===this.cookie||parsedAnnounce.infoHash.forEach(infoHash=>{this.emit("peer",`${rinfo.address}:${parsedAnnounce.port}`,infoHash)})},onError=err=>{this.emit("error",err)};this.server.on("listening",onListening),this.server.on("message",onMessage),this.server.on("error",onError)}_parseAnnounce(announce){const checkHost=host=>/^(239.192.152.143|\[ff15::efc0:988f]):6771$/.test(host),checkPort=port=>/^\d+$/.test(port),checkInfoHash=infoHash=>/^[0-9a-fA-F]{40}$/.test(infoHash);debug("parse announce",announce);const sections=announce.split("\r\n");if("BT-SEARCH * HTTP/1.1"!==sections[0])return this.emit("warning","Invalid LSD announce (header)"),null;const host=sections[1].split("Host: ")[1];if(!checkHost(host))return this.emit("warning","Invalid LSD announce (host)"),null;const port=sections[2].split("Port: ")[1];if(!checkPort(port))return this.emit("warning","Invalid LSD announce (port)"),null;const infoHash=sections.filter(section=>section.includes("Infohash: ")).map(section=>section.split("Infohash: ")[1]).filter(infoHash=>checkInfoHash(infoHash));if(0===infoHash.length)return this.emit("warning","Invalid LSD announce (infoHash)"),null;const cookie=sections.filter(section=>section.includes("cookie: ")).map(section=>section.split("cookie: ")[1]).reduce((acc,cur)=>cur,null);return{host:host,port:port,infoHash:infoHash,cookie:cookie}}destroy(cb){this.destroyed||(this.destroyed=!0,debug("destroy"),clearInterval(this.annouceIntervalId),this.server.close(cb))}start(){debug("start"),this.server.bind(LSD_PORT),this._announce(),this.annouceIntervalId=setInterval(()=>{this._announce()},ANNOUNCE_INTERVAL)}_announce(){debug("send announce");const host=`${LSD_HOST}:${LSD_PORT}`,announce=`BT-SEARCH * HTTP/1.1\r\nHost: ${host}\r\nPort: ${this.port}\r\nInfohash: ${this.infoHash}\r\ncookie: ${this.cookie}\r\n\r\n\r\n`;this.server.send(announce,LSD_PORT,LSD_HOST)}}module.exports=LSD},{debug:122,dgram:106,events:156}],54:[function(require,module,exports){(function(Buffer){(function(){function xor(a,b){for(let len=a.length;len--;)a[len]^=b[len];return a}/*! bittorrent-protocol. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,crypto=require("crypto"),debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),sha1=require("simple-sha1"),speedometer=require("speedometer"),stream=require("readable-stream"),RC4=require("rc4"),BITFIELD_GROW=4e5,KEEP_ALIVE_TIMEOUT=55e3,ALLOWED_FAST_SET_MAX_LENGTH=100,MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0],MESSAGE_HAVE_ALL=Buffer.from([0,0,0,1,14]),MESSAGE_HAVE_NONE=Buffer.from([0,0,0,1,15]),DH_PRIME="ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563",DH_GENERATOR=2,VC=Buffer.from([0,0,0,0,0,0,0,0]),CRYPTO_PROVIDE=Buffer.from([0,0,1,2]),CRYPTO_SELECT=Buffer.from([0,0,0,2]);class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class HaveAllBitField{constructor(){this.buffer=new Uint8Array}get(index){return!0}set(index){}}class Wire extends stream.Duplex{constructor(type=null,retries=0,peEnabled=!1){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=type,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:BITFIELD_GROW}),this.extensions={},this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this.hasFast=!1,this.allowedFastSet=[],this.peerAllowedFastSet=[],this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=peEnabled,peEnabled?(this._dh=crypto.createDiffieHellman(DH_PRIME,"hex",DH_GENERATOR),this._myPubKey=this._dh.generateKeys("hex")):this._myPubKey=null,this._peerPubKey=null,this._sharedSecret=null,this._peerCryptoProvide=[],this._cryptoHandshakeDone=!1,this._cryptoSyncPattern=null,this._waitMaxBytes=null,this._encryptionMethod=null,this._encryptGenerator=null,this._decryptGenerator=null,this._setGenerators=!1,this.once("finish",()=>this._onFinish()),this.on("finish",this._onFinish),this._debug("type:",this.type),"tcpIncoming"===this.type&&this._peEnabled?this._determineHandshakeType():"tcpOutgoing"===this.type&&this._peEnabled&&0===retries?this._parsePe2():this._parseHandshake(null)}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},KEEP_ALIVE_TIMEOUT))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._resetTimeout(!0)}destroy(){if(!this.destroyed)return this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end(),this}end(...args){return this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}sendPe1(){if(this._peEnabled){const padALen=_Mathfloor(513*Math.random()),padA=randombytes(padALen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padA]))}}sendPe2(){const padBLen=_Mathfloor(513*Math.random()),padB=randombytes(padBLen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padB]))}sendPe3(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex"),hash2Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req2")+infoHash,"hex")),"hex"),hash3Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),"hex"),hashesXorBuffer=xor(hash2Buffer,hash3Buffer),padCLen=randombytes(2).readUInt16BE(0)%512,padCBuffer=randombytes(padCLen);let vcAndProvideBuffer=Buffer.alloc(14+padCLen+2);VC.copy(vcAndProvideBuffer),CRYPTO_PROVIDE.copy(vcAndProvideBuffer,8),vcAndProvideBuffer.writeInt16BE(padCLen,12),padCBuffer.copy(vcAndProvideBuffer,14),vcAndProvideBuffer.writeInt16BE(0,14+padCLen),vcAndProvideBuffer=this._encryptHandshake(vcAndProvideBuffer),this._push(Buffer.concat([hash1Buffer,hashesXorBuffer,vcAndProvideBuffer]))}sendPe4(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const padDLen=randombytes(2).readUInt16BE(0)%512,padDBuffer=randombytes(padDLen);let vcAndSelectBuffer=Buffer.alloc(14+padDLen);VC.copy(vcAndSelectBuffer),CRYPTO_SELECT.copy(vcAndSelectBuffer,8),vcAndSelectBuffer.writeInt16BE(padDLen,12),padDBuffer.copy(vcAndSelectBuffer,14),vcAndSelectBuffer=this._encryptHandshake(vcAndSelectBuffer),this._push(vcAndSelectBuffer),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),this._infoHash=infoHashBuffer,20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);this.extensions={extended:!0,dht:!!(extensions&&extensions.dht),fast:!!(extensions&&extensions.fast)},reserved[5]|=16,this.extensions.dht&&(reserved[7]|=1),this.extensions.fast&&(reserved[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(MESSAGE_CHOKE),this.hasFast)for(let allowedCount=0;this.peerRequests.length>allowedCount;){const request=this.peerRequests[allowedCount];this.allowedFastSet.includes(request.piece)?++allowedCount:this.reject(request.piece,request.offset,request.length)}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking&&!(this.hasFast&&this.peerAllowedFastSet.includes(index))?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),!this._timeout&&this._resetTimeout(!0),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this._message(7,[index,offset],buffer),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}suggest(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("suggest %d",index),this._message(13,[index],null)}haveAll(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-all"),this._push(MESSAGE_HAVE_ALL)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(MESSAGE_HAVE_NONE)}reject(index,offset,length){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this._message(16,[index,offset,length],null)}allowedFast(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("allowed-fast %d",index),this.allowedFastSet.includes(index)||this.allowedFastSet.push(index),this._message(17,[index],null)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}setEncrypt(sharedSecret,infoHash){let encryptKey,decryptKey,encryptKeyBuf,encryptKeyIntArray,decryptKeyBuf,decryptKeyIntArray;switch(this.type){case"tcpIncoming":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;case"tcpOutgoing":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;default:return!1;}for(let i=0;1024>i;i++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;i<numbers.length;i++)buffer.writeUInt32BE(numbers[i],5+4*i);this._push(buffer),data&&this._push(data)}_push(data){if(!this._finished)return 2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._encrypt(data)),this.push(data)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onPe1(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}_onPe3(hashesXorBuffer){const hash3=sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),sKeyHash=xor(Buffer.from(hash3,"hex"),hashesXorBuffer).toString("hex");this.emit("pe3",sKeyHash)}_onPe3Encrypted(vcBuffer,peerProvideBuffer){if(!vcBuffer.equals(VC))return this._debug("Error: verification constant did not match"),void this.destroy();for(const provideByte of peerProvideBuffer.values())0!==provideByte&&this._peerCryptoProvide.push(provideByte);this._peerCryptoProvide.includes(2)?this._encryptionMethod=2:(this._debug("Error: RC4 encryption method not provided by peer"),this.destroy())}_onPe4(peerSelectBuffer){this._encryptionMethod=peerSelectBuffer.readUInt8(3),CRYPTO_PROVIDE.includes(this._encryptionMethod)||(this._debug("Error: peer selected invalid crypto method"),this.destroy()),this._cryptoHandshakeDone=!0,this._debug("crypto handshake done"),this.emit("pe4")}_onHandshake(infoHashBuffer,peerIdBuffer,extensions){const infoHash=infoHashBuffer.toString("hex"),peerId=peerIdBuffer.toString("hex");for(const name in this._debug("got handshake i=%s p=%s exts=%o",infoHash,peerId,extensions),this.peerId=peerId,this.peerIdBuffer=peerIdBuffer,this.peerExtensions=extensions,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",infoHash,peerId,extensions),this._ext)this._ext[name].onHandshake(infoHash,peerId,extensions);extensions.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){if(this.peerChoking=!0,this._debug("got choke"),this.emit("choke"),!this.hasFast)for(;this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(index){this.peerPieces.get(index)||(this._debug("got have %d",index),this.peerPieces.set(index,!0),this.emit("have",index))}_onBitField(buffer){this.peerPieces=new BitField(buffer),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(index,offset,length){if(this.amChoking&&!(this.hasFast&&this.allowedFastSet.includes(index)))return void(this.hasFast&&this.reject(index,offset,length));this._debug("got request index=%d offset=%d length=%d",index,offset,length);const respond=(err,buffer)=>request===this._pull(this.peerRequests,index,offset,length)?err?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message),void(this.hasFast&&this.reject(index,offset,length))):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onSuggest(index){return this.hasFast?void(this._debug("got suggest %d",index),this.emit("suggest",index)):(this._debug("Error: got suggest whereas fast extension is disabled"),void this.destroy())}_onHaveAll(){return this.hasFast?void(this._debug("got have-all"),this.peerPieces=new HaveAllBitField,this.emit("have-all")):(this._debug("Error: got have-all whereas fast extension is disabled"),void this.destroy())}_onHaveNone(){return this.hasFast?void(this._debug("got have-none"),this.emit("have-none")):(this._debug("Error: got have-none whereas fast extension is disabled"),void this.destroy())}_onReject(index,offset,length){return this.hasFast?void(this._debug("got reject index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was rejected"),null),this.emit("reject",index,offset,length)):(this._debug("Error: got reject whereas fast extension is disabled"),void this.destroy())}_onAllowedFast(index){return this.hasFast?void(this._debug("got allowed-fast %d",index),!this.peerAllowedFastSet.includes(index)&&this.peerAllowedFastSet.push(index),this.peerAllowedFastSet.length>ALLOWED_FAST_SET_MAX_LENGTH&&this.peerAllowedFastSet.shift(),this.emit("allowed-fast",index)):(this._debug("Error: got allowed-fast whereas fast extension is disabled"),void this.destroy())}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;if(this.peerExtendedHandshake=info,"object"==typeof info.m)for(const name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(const name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._decrypt(data)),this._bufferSize+=data.length,this._buffer.push(data),1<this._buffer.length&&(this._buffer=[Buffer.concat(this._buffer,this._bufferSize)]),this._cryptoSyncPattern){const index=this._buffer[0].indexOf(this._cryptoSyncPattern);if(-1!==index)this._buffer[0]=this._buffer[0].slice(index+this._cryptoSyncPattern.length),this._bufferSize-=index+this._cryptoSyncPattern.length,this._cryptoSyncPattern=null;else if(this._bufferSize+data.length>this._waitMaxBytes+this._cryptoSyncPattern.length)return this._debug("Error: could not resynchronize"),void this.destroy()}for(;this._bufferSize>=this._parserSize&&!this._cryptoSyncPattern;)if(0===this._parserSize)this._parser(Buffer.from([]));else{const buffer=this._buffer[0];this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._resetTimeout(!this.peerChoking&&!this._finished),request.callback(err,buffer))}_resetTimeout(setAgain){if(!setAgain||!this._timeoutMs||!this.requests.length)return clearTimeout(this._timeout),this._timeout=null,void(this._timeoutExpiresAt=null);const timeoutExpiresAt=Date.now()+this._timeoutMs;if(this._timeout){if(timeoutExpiresAt-this._timeoutExpiresAt<.05*this._timeoutMs)return;clearTimeout(this._timeout)}this._timeoutExpiresAt=timeoutExpiresAt,this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref()}_parse(size,parser){this._parserSize=size,this._parser=parser}_parseUntil(pattern,maxBytes){this._cryptoSyncPattern=pattern,this._waitMaxBytes=maxBytes}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0<length?this._parse(length,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(buffer){switch(this._parse(4,this._onMessageLength),buffer[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(buffer.readUInt32BE(1));case 5:return this._onBitField(buffer.slice(1));case 6:return this._onRequest(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 7:return this._onPiece(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.slice(9));case 8:return this._onCancel(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 9:return this._onPort(buffer.readUInt16BE(1));case 13:return this._onSuggest(buffer.readUInt32BE(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 17:return this._onAllowedFast(buffer.readUInt32BE(1));case 20:return this._onExtended(buffer.readUInt8(1),buffer.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",buffer);}}_determineHandshakeType(){this._parse(1,pstrLenBuffer=>{const pstrlen=pstrLenBuffer.readUInt8(0);19===pstrlen?this._parse(pstrlen+48,this._onHandshakeBuffer):this._parsePe1(pstrLenBuffer)})}_parsePe1(pubKeyPrefix){this._parse(95,pubKeySuffix=>{this._onPe1(Buffer.concat([pubKeyPrefix,pubKeySuffix])),this._parsePe3()})}_parsePe2(){this._parse(96,pubKey=>{for(this._onPe2(pubKey);!this._setGenerators;);this._parsePe4()})}_parsePe3(){const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex");this._parseUntil(hash1Buffer,512),this._parse(20,buffer=>{for(this._onPe3(buffer);!this._setGenerators;);this._parsePe3Encrypted()})}_parsePe3Encrypted(){this._parse(14,buffer=>{const vcBuffer=this._decryptHandshake(buffer.slice(0,8)),peerProvideBuffer=this._decryptHandshake(buffer.slice(8,12)),padCLen=this._decryptHandshake(buffer.slice(12,14)).readUInt16BE(0);this._parse(padCLen,padCBuffer=>{padCBuffer=this._decryptHandshake(padCBuffer),this._parse(2,iaLenBuf=>{const iaLen=this._decryptHandshake(iaLenBuf).readUInt16BE(0);this._parse(iaLen,iaBuffer=>{iaBuffer=this._decryptHandshake(iaBuffer),this._onPe3Encrypted(vcBuffer,peerProvideBuffer,padCBuffer,iaBuffer);const pstrlen=iaLen?iaBuffer.readUInt8(0):null,protocol=iaLen?iaBuffer.slice(1,20):null;19===pstrlen&&"BitTorrent protocol"===protocol.toString()?this._onHandshakeBuffer(iaBuffer.slice(1)):this._parseHandshake()})})})})}_parsePe4(){const vcBufferEncrypted=this._decryptHandshake(VC);this._parseUntil(vcBufferEncrypted,512),this._parse(6,buffer=>{const peerSelectBuffer=this._decryptHandshake(buffer.slice(0,4)),padDLen=this._decryptHandshake(buffer.slice(4,6)).readUInt16BE(0);this._parse(padDLen,padDBuf=>{this._decryptHandshake(padDBuf),this._onPe4(peerSelectBuffer),this._parseHandshake(null)})})}_parseHandshake(){this._parse(1,buffer=>{const pstrlen=buffer.readUInt8(0);return 19===pstrlen?void this._parse(pstrlen+48,this._onHandshakeBuffer):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",pstrlen.toString()),void this.end())})}_onHandshakeBuffer(handshake){const protocol=handshake.slice(0,19);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(19),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),fast:!!(4&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i<requests.length;i++){const req=requests[i];if(req.piece===piece&&req.offset===offset&&req.length===length)return arrayRemove(requests,i),req}return null}_encryptHandshake(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_encrypt(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator||2!==this._encryptionMethod)return crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_decryptHandshake(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_decrypt(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator||2!==this._encryptionMethod)return decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_utfToHex(str){return Buffer.from(str,"utf8").toString("hex")}}module.exports=Wire}).call(this)}).call(this,require("buffer").Buffer)},{bencode:47,bitfield:51,buffer:101,crypto:121,debug:122,randombytes:262,rc4:266,"readable-stream":281,"simple-sha1":303,speedometer:310,"unordered-array-remove":331}],55:[function(require,module,exports){(function(process,Buffer){(function(){const debug=require("debug")("bittorrent-tracker:client"),EventEmitter=require("events"),once=require("once"),parallel=require("run-parallel"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),common=require("./lib/common"),HTTPTracker=require("./lib/client/http-tracker"),UDPTracker=require("./lib/client/udp-tracker"),WebSocketTracker=require("./lib/client/websocket-tracker");class Client 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(!opts.announce)throw new Error("Option `announce` 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._peerIdBuffer=Buffer.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._infoHashBuffer=Buffer.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),debug("new client %s",this.infoHash),this.destroyed=!1,this._port=opts.port,this._getAnnounceOpts=opts.getAnnounceOpts,this._rtcConfig=opts.rtcConfig,this._userAgent=opts.userAgent,this._proxyOpts=opts.proxyOpts,this._wrtc="function"==typeof opts.wrtc?opts.wrtc():opts.wrtc;let announce="string"==typeof opts.announce?[opts.announce]:null==opts.announce?[]:opts.announce;announce=announce.map(announceUrl=>(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{queueMicrotask(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=common.parseUrl(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535<port)return nextTickWarn(new Error(`Invalid tracker port: ${announceUrl}`)),null;const protocol=parsedUrl.protocol;return("http:"===protocol||"https:"===protocol)&&"function"==typeof HTTPTracker?new HTTPTracker(this,announceUrl):"udp:"===protocol&&"function"==typeof UDPTracker?new UDPTracker(this,announceUrl):("ws:"===protocol||"wss:"===protocol)&&webrtcSupport?"ws:"===protocol&&"undefined"!=typeof window&&"https:"===window.location.protocol?(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null):new WebSocketTracker(this,announceUrl):(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null)}).filter(Boolean)}start(opts){opts=this._defaultAnnounceOpts(opts),opts.event="started",debug("send `start` %o",opts),this._announce(opts),this._trackers.forEach(tracker=>{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":56,"./lib/client/udp-tracker":58,"./lib/client/websocket-tracker":59,"./lib/common":61,_process:246,buffer:101,debug:122,events:156,once:231,"queue-microtask":259,"run-parallel":287,"simple-peer":302}],56:[function(require,module,exports){(function(Buffer){(function(){const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),clone=require("clone"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:http-tracker"),get=require("simple-get"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker"),HTTP_SCRAPE_SUPPORT=/\/(announce)[^/]*$/;class HTTPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new http tracker %s",announceUrl),this.scrapeUrl=null;const match=this.announceUrl.match(HTTP_SCRAPE_SUPPORT);if(match){const pre=this.announceUrl.slice(0,match.index),post=this.announceUrl.slice(match.index+9);this.scrapeUrl=`${pre}/scrape${post}`}this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){if(!this.destroyed){const params=Object.assign({},opts,{compact:null==opts.compact?1:opts.compact,info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,port:this.client._port});this._trackerId&&(params.trackerid=this._trackerId),this._request(this.announceUrl,params,(err,data)=>err?this.client.emit("warning",err):void this._onAnnounceResponse(data))}}scrape(opts){if(this.destroyed)return;if(!this.scrapeUrl)return void this.client.emit("error",new Error(`scrape not supported ${this.announceUrl}`));const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary,params={info_hash:infoHashes};this._request(this.scrapeUrl,params,(err,data)=>err?this.client.emit("warning",err):void this._onScrapeResponse(data))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);this.destroyed=!0,clearInterval(this.interval);let timeout;return 0===this.cleanupFns.length?destroyCleanup():void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()})}_request(requestUrl,params,cb){function cleanup(){request&&(arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),request.abort(),request=null),self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}function onResponse(err,res,data){if(cleanup(),!self.destroyed){if(err)return cb(err);if(200!==res.statusCode)return cb(new Error(`Non-200 response code ${res.statusCode} from ${self.announceUrl}`));if(!data||0===data.length)return cb(new Error(`Invalid tracker response from${self.announceUrl}`));try{data=bencode.decode(data)}catch(err){return cb(new Error(`Error decoding tracker response: ${err.message}`))}const failure=data["failure reason"];if(failure)return debug(`failure from ${requestUrl} (${failure})`),cb(new Error(failure));const warning=data["warning message"];warning&&(debug(`warning from ${requestUrl} (${warning})`),self.client.emit("warning",new Error(warning))),debug(`response from ${requestUrl}`),cb(null,data)}}const self=this,parsedUrl=new URL(requestUrl+(-1===requestUrl.indexOf("?")?"?":"&")+common.querystringStringify(params));let agent;this.client._proxyOpts&&(agent="https:"===parsedUrl.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!agent&&this.client._proxyOpts.socksProxy&&(agent=new Socks.Agent(clone(this.client._proxyOpts.socksProxy),"https:"===parsedUrl.protocol))),this.cleanupFns.push(cleanup);let request=get.concat({url:parsedUrl.toString(),agent,timeout:common.REQUEST_TIMEOUT,headers:{"user-agent":this.client._userAgent||""}},onResponse)}_onAnnounceResponse(data){const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];trackerId&&(this._trackerId=trackerId);const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response);let addrs;if(Buffer.isBuffer(data.peers)){try{addrs=compact2string.multi(data.peers)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers)&&data.peers.forEach(peer=>{this.client.emit("peer",`${peer.ip}:${peer.port}`)});if(Buffer.isBuffer(data.peers6)){try{addrs=compact2string.multi6(data.peers6)}catch(err){return this.client.emit("warning",err)}addrs.forEach(addr=>{this.client.emit("peer",addr)})}else Array.isArray(data.peers6)&&data.peers6.forEach(peer=>{const ip=/^\[/.test(peer.ip)||!/:/.test(peer.ip)?peer.ip:`[${peer.ip}]`;this.client.emit("peer",`${ip}:${peer.port}`)})}_onScrapeResponse(data){data=data.files||data.host||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}}HTTPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000,module.exports=HTTPTracker}).call(this)}).call(this,{isBuffer:require("../../../is-buffer/index.js")})},{"../../../is-buffer/index.js":193,"../common":61,"./tracker":57,bencode:47,clone:111,compact2string:112,debug:122,"simple-get":301,socks:66,"unordered-array-remove":331}],57:[function(require,module,exports){const EventEmitter=require("events");class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}module.exports=Tracker},{events:156}],58:[function(require,module,exports){(function(Buffer){(function(){function genTransactionId(){return randombytes(4)}function toUInt16(n){const buf=Buffer.allocUnsafe(2);return buf.writeUInt16BE(n,0),buf}function toUInt64(n){if(n>MAX_UINT||"string"==typeof n){const bytes=new BN(n).toArray();for(;8>bytes.length;)bytes.unshift(0);return Buffer.from(bytes)}return Buffer.concat([common.toUInt32(0),common.toUInt32(n)])}function noop(){}const arrayRemove=require("unordered-array-remove"),BN=require("bn.js"),clone=require("clone"),compact2string=require("compact2string"),debug=require("debug")("bittorrent-tracker:udp-tracker"),dgram=require("dgram"),randombytes=require("randombytes"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker");class UDPTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new udp tracker %s",announceUrl),this.cleanupFns=[],this.maybeDestroyCleanup=null}announce(opts){this.destroyed||this._request(opts)}scrape(opts){this.destroyed||(opts._scrape=!0,this._request(opts))}destroy(cb){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),self.maybeDestroyCleanup=null,self.cleanupFns.slice(0).forEach(cleanup=>{cleanup()}),self.cleanupFns=[],cb(null)}const self=this;if(this.destroyed)return cb(null);this.destroyed=!0,clearInterval(this.interval);let timeout;return 0===this.cleanupFns.length?destroyCleanup():void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),this.maybeDestroyCleanup=()=>{0===this.cleanupFns.length&&destroyCleanup()})}_request(opts){function onGotConnection(err,s,info){return err?onError(err):void(proxySocket=s,socket=dgram.createSocket("udp4"),relay=info,timeout=setTimeout(()=>{"stopped"===opts.event?cleanup():onError(new Error(`tracker request timed out (${opts.event})`)),timeout=null},common.REQUEST_TIMEOUT),timeout.unref&&timeout.unref(),send(Buffer.concat([common.CONNECTION_ID,common.toUInt32(common.ACTIONS.CONNECT),transactionId]),relay),socket.once("error",onError),socket.on("message",onSocketMessage))}function cleanup(){if(timeout&&(clearTimeout(timeout),timeout=null),socket){arrayRemove(self.cleanupFns,self.cleanupFns.indexOf(cleanup)),socket.removeListener("error",onError),socket.removeListener("message",onSocketMessage),socket.on("error",noop);try{socket.close()}catch(err){}if(socket=null,proxySocket){try{proxySocket.close()}catch(err){}proxySocket=null}}self.maybeDestroyCleanup&&self.maybeDestroyCleanup()}function onError(err){if(cleanup(),!self.destroyed){try{err.message&&(err.message+=` (${self.announceUrl})`)}catch(ignoredErr){}self.client.emit("warning",err)}}function onSocketMessage(msg){if(proxySocket&&(msg=msg.slice(10)),8>msg.length||msg.readUInt32BE(4)!==transactionId.readUInt32BE(0))return onError(new Error("tracker sent invalid transaction id"));const action=msg.readUInt32BE(0);switch(debug("UDP response %s, action %s",self.announceUrl,action),action){case 0:{if(16>msg.length)return onError(new Error("invalid udp handshake"));opts._scrape?scrape(msg.slice(8,16)):announce(msg.slice(8,16),opts);break}case 1:{if(cleanup(),self.destroyed)return;if(20>msg.length)return onError(new Error("invalid announce message"));const interval=msg.readUInt32BE(8);interval&&self.setInterval(1e3*interval),self.client.emit("update",{announce:self.announceUrl,complete:msg.readUInt32BE(16),incomplete:msg.readUInt32BE(12)});let addrs;try{addrs=compact2string.multi(msg.slice(20))}catch(err){return self.client.emit("warning",err)}addrs.forEach(addr=>{self.client.emit("peer",addr)});break}case 2:{if(cleanup(),self.destroyed)return;if(20>msg.length||0!=(msg.length-8)%12)return onError(new Error("invalid scrape message"));const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("hex")):[opts.infoHash&&opts.infoHash.toString("hex")||self.client.infoHash];for(let i=0,len=(msg.length-8)/12;i<len;i+=1)self.client.emit("scrape",{announce:self.announceUrl,infoHash:infoHashes[i],complete:msg.readUInt32BE(8+12*i),downloaded:msg.readUInt32BE(12+12*i),incomplete:msg.readUInt32BE(16+12*i)});break}case 3:{if(cleanup(),self.destroyed)return;if(8>msg.length)return onError(new Error("invalid error message"));self.client.emit("warning",new Error(msg.slice(8).toString()));break}default:onError(new Error("tracker sent invalid action"));}}function send(message,proxyInfo){if(proxyInfo){const pack=Socks.createUDPFrame({host:hostname,port},message);socket.send(pack,0,pack.length,proxyInfo.port,proxyInfo.host)}else socket.send(message,0,message.length,port,hostname)}function announce(connectionId,opts){transactionId=genTransactionId(),send(Buffer.concat([connectionId,common.toUInt32(common.ACTIONS.ANNOUNCE),transactionId,self.client._infoHashBuffer,self.client._peerIdBuffer,toUInt64(opts.downloaded),null==opts.left?Buffer.from("FFFFFFFFFFFFFFFF","hex"):toUInt64(opts.left),toUInt64(opts.uploaded),common.toUInt32(common.EVENTS[opts.event]||0),common.toUInt32(0),common.toUInt32(0),common.toUInt32(opts.numwant),toUInt16(self.client._port)]),relay)}function scrape(connectionId){transactionId=genTransactionId();const infoHash=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?Buffer.concat(opts.infoHash):opts.infoHash||self.client._infoHashBuffer;send(Buffer.concat([connectionId,common.toUInt32(common.ACTIONS.SCRAPE),transactionId,infoHash]),relay)}const self=this;opts||(opts={});let{hostname,port}=common.parseUrl(this.announceUrl);""===port&&(port=80);let transactionId=genTransactionId(),timeout,proxySocket,socket,relay;const proxyOpts=this.client._proxyOpts&&clone(this.client._proxyOpts.socksProxy);proxyOpts?(!proxyOpts.proxy&&(proxyOpts.proxy={}),proxyOpts.proxy.command="associate",!proxyOpts.target&&(proxyOpts.target={host:"0.0.0.0",port:0}),5===proxyOpts.proxy.type?Socks.createConnection(proxyOpts,onGotConnection):(debug("Ignoring Socks proxy for UDP request because type 5 is required"),onGotConnection(null))):onGotConnection(null),this.cleanupFns.push(cleanup)}}UDPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=1800000;const MAX_UINT=4294967295;module.exports=UDPTracker}).call(this)}).call(this,require("buffer").Buffer)},{"../common":61,"./tracker":57,"bn.js":64,buffer:101,clone:111,compact2string:112,debug:122,dgram:106,randombytes:262,socks:66,"unordered-array-remove":331}],59:[function(require,module,exports){function noop(){}const clone=require("clone"),debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker"),socketPool={},RECONNECT_MINIMUM=10000,RECONNECT_MAXIMUM=3600000,RECONNECT_VARIANCE=300000,OFFER_TIMEOUT=50000;class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,5);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary,params={action:"scrape",info_hash:infoHashes};this._send(params)}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0<socketPool[this.announceUrl].consumers)return cb();let socket=socketPool[this.announceUrl];delete socketPool[this.announceUrl],socket.on("error",noop),socket.once("close",cb);let timeout;return this.expectingResponse?void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),socket.once("data",destroyCleanup)):destroyCleanup()}_openSocket(){if(this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket)socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound();else{const parsedUrl=new URL(this.announceUrl);let agent;this.client._proxyOpts&&(agent="wss:"===parsedUrl.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!agent&&this.client._proxyOpts.socksProxy&&(agent=new Socks.Agent(clone(this.client._proxyOpts.socksProxy),"wss:"===parsedUrl.protocol))),this.socket=socketPool[this.announceUrl]=new Socket({url:this.announceUrl,agent}),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)}this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),this.client.emit("peer",peer),peer.signal(data.offer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),this.client.emit("peer",peer),peer.signal(data.answer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*RECONNECT_VARIANCE)+_Mathmin(_Mathpow(2,this.retries)*RECONNECT_MINIMUM,RECONNECT_MAXIMUM);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},OFFER_TIMEOUT),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i<numwant;++i)generateOffer();checkDone()}_createPeer(opts){function onError(err){self.client.emit("warning",new Error(`Connection error: ${err.message}`)),peer.destroy()}function onConnect(){peer.removeListener("error",onError),peer.removeListener("connect",onConnect)}const self=this;opts=Object.assign({trickle:!1,config:self.client._rtcConfig,wrtc:self.client._wrtc},opts);const peer=new Peer(opts);return peer.once("error",onError),peer.once("connect",onConnect),peer}}WebSocketTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=30000,WebSocketTracker._socketPool=socketPool,module.exports=WebSocketTracker},{"../common":61,"./tracker":57,clone:111,debug:122,randombytes:262,"simple-peer":302,"simple-websocket":305,socks:66}],60:[function(require,module,exports){(function(Buffer){(function(){function toUInt32(n){const buf=Buffer.allocUnsafe(4);return buf.writeUInt32BE(n,0),buf}const querystring=require("querystring");exports.IPV4_RE=/^[\d.]+$/,exports.IPV6_RE=/^[\da-fA-F:]+$/,exports.REMOVE_IPV4_MAPPED_IPV6_RE=/^::ffff:/,exports.CONNECTION_ID=Buffer.concat([toUInt32(1047),toUInt32(655366528)]),exports.ACTIONS={CONNECT:0,ANNOUNCE:1,SCRAPE:2,ERROR:3},exports.EVENTS={update:0,completed:1,started:2,stopped:3,paused:4},exports.EVENT_IDS={0:"update",1:"completed",2:"started",3:"stopped",4:"paused"},exports.EVENT_NAMES={update:"update",completed:"complete",started:"start",stopped:"stop",paused:"pause"},exports.REQUEST_TIMEOUT=15e3,exports.DESTROY_TIMEOUT=1e3,exports.toUInt32=toUInt32,exports.querystringParse=q=>querystring.parse(q,null,null,{decodeURIComponent:unescape}),exports.querystringStringify=obj=>{let ret=querystring.stringify(obj,null,null,{encodeURIComponent:escape});return ret=ret.replace(/[@*/+]/g,char=>`%${char.charCodeAt(0).toString(16).toUpperCase()}`),ret}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,querystring:258}],61:[function(require,module,exports){(function(Buffer){(function(){exports.DEFAULT_ANNOUNCE_PEERS=50,exports.MAX_ANNOUNCE_PEERS=82,exports.binaryToHex=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"binary").toString("hex")),exports.hexToBinary=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"hex").toString("binary")),exports.parseUrl=str=>{const url=new URL(str.replace(/^udp:/,"http:"));return str.match(/^udp:/)&&Object.defineProperties(url,{href:{value:url.href.replace(/^http/,"udp")},protocol:{value:url.protocol.replace(/^http/,"udp")},origin:{value:url.origin.replace(/^http/,"udp")}}),url};const config=require("./common-node");Object.assign(exports,config)}).call(this)}).call(this,require("buffer").Buffer)},{"./common-node":60,buffer:101}],62:[function(require,module,exports){(function(Buffer){(function(){/*! blob-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */module.exports=function blobToBuffer(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],63:[function(require,module,exports){(function(Buffer){(function(){const{Transform}=require("readable-stream");class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){this._bufferedBytes-=this.size;const blockBufs=[];for(let blockBufsBytes=0;blockBufsBytes<this.size;){const b=this._buffered.shift();if(blockBufsBytes+b.length<=this.size)blockBufs.push(b),blockBufsBytes+=b.length;else{const neededSize=this.size-blockBufsBytes;blockBufs.push(b.slice(0,neededSize)),blockBufsBytes+=neededSize,this._buffered.unshift(b.slice(neededSize))}}this.push(Buffer.concat(blockBufs,this.size))}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}module.exports=Block}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"readable-stream":281}],64:[function(require,module,exports){(function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return 48<=c&&57>=c?c-48:65<=c&&70>=c?c-55:97<=c&&102>=c?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=_Mathmin(str.length,end),i=start,c;i<len;i++)c=str.charCodeAt(i)-48,r*=mul,b=49<=c?c-49+10:17<=c?c-17+10:c,assert(0<=c&&b<mul,"Invalid character"),r+=b;return r}function move(dest,src){dest.words=src.words,dest.length=src.length,dest.negative=src.negative,dest.red=src.red}function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit<w.length;bit++){var off=0|bit/26,wbit=bit%26;w[bit]=1&num.words[off]>>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k<len;k++){for(var ncarry=carry>>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out._strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k<out.length-1;k++){ncarry=hncarry,hncarry=0;for(var rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1);j<=maxJ;j++){var i=k-j,a=0|self.words[i],b=0|num.words[j],r=a*b,lo=67108863&r;ncarry=0|ncarry+(0|r/67108864),lo=0|lo+rword,rword=67108863&lo,ncarry=0|ncarry+(lo>>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer="undefined"!=typeof window&&"undefined"!=typeof window.Buffer?window.Buffer:require("buffer").Buffer}catch(e){}if(BN.isBN=function isBN(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return 0<left.cmp(right)?left:right},BN.min=function min(left,right){return 0>left.cmp(right)?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function _initNumber(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function _initArray(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j,w;if("be"===endian)for(i=number.length-1,j=0;0<=i;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i<number.length;i+=3)w=number[i]|number[i+1]<<8|number[i+2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j=0,w;if("be"===endian)for(i=number.length-1;i>=start;i-=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=0==parseLength%2?start+1:start;i<number.length;i+=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;i<end;i+=limbLen)word=parseBase(number,i,i+limbLen,base),this.imuln(limbPow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;i<mod;i++)pow*=base;this.imuln(pow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word)}this._strip()},BN.prototype.copy=function copy(dest){dest.words=Array(this.length);for(var i=0;i<this.length;i++)dest.words[i]=this.words[i];dest.length=this.length,dest.negative=this.negative,dest.red=this.red},BN.prototype._move=function _move(dest){move(dest,this)},BN.prototype.clone=function clone(){var r=new BN(null);return this.copy(r),r},BN.prototype._expand=function _expand(size){for(;this.length<size;)this.words[this.length++]=0;return this},BN.prototype._strip=function strip(){for(;1<this.length&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i<this.length;i++){var w=this.words[i],word=(16777215&(w<<off|carry)).toString(16);carry=16777215&w>>>24-off,off+=2,26<=off&&(off-=26,i--),out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2<this.length&&assert(!1,"Number can only safely store up to 53 bits"),0===this.negative?ret:-ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};var allocate=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||_Mathmax(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(0<reqLength,"Requested array length <= 0");var res=allocate(ArrayType,reqLength),postfix="le"===endian?"LE":"BE";return this["_toArrayLike"+postfix](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position++]=255&word,position<res.length&&(res[position++]=255&word>>8),position<res.length&&(res[position++]=255&word>>16),6==shift?(position<res.length&&(res[position++]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(position<res.length)for(res[position++]=carry;position<res.length;)res[position++]=0},BN.prototype._toArrayLikeBE=function _toArrayLikeBE(res,byteLength){for(var position=res.length-1,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position--]=255&word,0<=position&&(res[position--]=255&word>>8),0<=position&&(res[position--]=255&word>>16),6==shift?(0<=position&&(res[position--]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(0<=position)for(res[position--]=carry;0<=position;)res[position--]=0},BN.prototype._countBits=_Mathclz?function _countBits(w){return 32-_Mathclz(w)}:function _countBits(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0,b;i<this.length&&(b=this._zeroBits(this.words[i]),r+=b,26===b);i++);return r},BN.prototype.byteLength=function byteLength(){return _Mathceil(this.bitLength()/8)},BN.prototype.toTwos=function toTwos(width){return 0===this.negative?this.clone():this.abs().inotn(width).iaddn(1)},BN.prototype.fromTwos=function fromTwos(width){return this.testn(width-1)?this.notn(width).iaddn(1).ineg():this.clone()},BN.prototype.isNeg=function isNeg(){return 0!==this.negative},BN.prototype.neg=function neg(){return this.clone().ineg()},BN.prototype.ineg=function ineg(){return this.isZero()||(this.negative^=1),this},BN.prototype.iuor=function iuor(num){for(;this.length<num.length;)this.words[this.length++]=0;for(var i=0;i<num.length;i++)this.words[i]|=num.words[i];return this._strip()},BN.prototype.ior=function ior(num){return assert(0==(this.negative|num.negative)),this.iuor(num)},BN.prototype.or=function or(num){return this.length>num.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;i<b.length;i++)this.words[i]&=num.words[i];return this.length=b.length,this._strip()},BN.prototype.iand=function iand(num){return assert(0==(this.negative|num.negative)),this.iuand(num)},BN.prototype.and=function and(num){return this.length>num.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;i<b.length;i++)this.words[i]=a.words[i]^b.words[i];if(this!==a)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=a.length,this._strip()},BN.prototype.ixor=function ixor(num){return assert(0==(this.negative|num.negative)),this.iuxor(num)},BN.prototype.xor=function xor(num){return this.length>num.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0<bitsLeft&&bytesNeeded--;for(var i=0;i<bytesNeeded;i++)this.words[i]=67108863&~this.words[i];return 0<bitsLeft&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<<wbit:this.words[off]&=~(1<<wbit),this._strip()},BN.prototype.iadd=function iadd(num){var r;if(0!==this.negative&&0===num.negative)return this.negative=0,r=this.isub(num),this.negative^=1,this._normSign();if(0===this.negative&&0!==num.negative)return num.negative=0,r=this.isub(num),num.negative=1,r._normSign();var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])+(0|b.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this},BN.prototype.add=function add(num){var res;return 0!==num.negative&&0===this.negative?(num.negative=0,res=this.sub(num),num.negative^=1,res):0===num.negative&&0!==this.negative?(this.negative=0,res=num.sub(this),this.negative=1,res):this.length>num.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0<cmp?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])-(0|b.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;if(0===carry&&i<a.length&&a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=_Mathmax(this.length,i),a!==this&&(this.negative=1),this._strip()},BN.prototype.sub=function sub(num){return this.clone().isub(num)};var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words,b=num.words,o=out.words,c=0,a0=0|a[0],al0=8191&a0,ah0=a0>>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i<N;i++)t[i]=this.revBin(i,l,N);return t},FFTM.prototype.revBin=function revBin(x,l,N){if(0===x||x===N-1)return x;for(var rb=0,i=0;i<l;i++)rb|=(1&x)<<l-i-1,x>>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i<N;i++)rtws[i]=rws[rbt[i]],itws[i]=iws[rbt[i]]},FFTM.prototype.transform=function transform(rws,iws,rtws,itws,N,rbt){this.permute(rbt,rws,iws,rtws,itws,N);for(var s=1;s<N;s<<=1)for(var l=s<<1,rtwdf=_Mathcos(2*_MathPI/l),itwdf=_Mathsin(2*_MathPI/l),p=0;p<N;p+=l)for(var rtwdf_=rtwdf,itwdf_=itwdf,j=0;j<s;j++){var re=rtws[p+j],ie=itws[p+j],ro=rtws[p+j+s],io=itws[p+j+s],rx=rtwdf_*ro-itwdf_*io;io=rtwdf_*io+itwdf_*ro,ro=rx,rtws[p+j]=re+ro,itws[p+j]=ie+io,rtws[p+j+s]=re-ro,itws[p+j+s]=ie-io,j!==l&&(rx=rtwdf*rtwdf_-itwdf*itwdf_,itwdf_=rtwdf*itwdf_+itwdf*rtwdf_,rtwdf_=rx)}},FFTM.prototype.guessLen13b=function guessLen13b(n,m){var N=1|_Mathmax(m,n),odd=1&N,i=0;for(N=0|N/2;N;N>>>=1)i++;return 1<<i+1+odd},FFTM.prototype.conjugate=function conjugate(rws,iws,N){if(!(1>=N))for(var i=0,t;i<N/2;i++)t=rws[i],rws[i]=rws[N-i-1],rws[N-i-1]=t,t=iws[i],iws[i]=-iws[N-i-1],iws[N-i-1]=-t},FFTM.prototype.normalize13b=function normalize13b(ws,N){for(var carry=0,i=0,w;i<N/2;i++)w=8192*_Mathround(ws[2*i+1]/N)+_Mathround(ws[2*i]/N)+carry,ws[i]=67108863&w,carry=67108864>w?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function convert13b(ws,len,rws,N){for(var carry=0,i=0;i<len;i++)carry+=0|ws[i],rws[2*i]=8191&carry,carry>>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i<N;++i)rws[i]=0;assert(0===carry),assert(0==(-8192&carry))},FFTM.prototype.stub=function stub(N){for(var ph=Array(N),i=0;i<N;i++)ph[i]=0;return ph},FFTM.prototype.mulp=function mulp(x,y,out){var N=2*this.guessLen13b(x.length,y.length),rbt=this.makeRBT(N),_=this.stub(N),rws=Array(N),rwst=Array(N),iwst=Array(N),nrws=Array(N),nrwst=Array(N),niwst=Array(N),rmws=out.words;rmws.length=N,this.convert13b(x.words,x.length,rws,N),this.convert13b(y.words,y.length,nrws,N),this.transform(rws,_,rwst,iwst,N,rbt),this.transform(nrws,_,nrwst,niwst,N,rbt);for(var i=0,rx;i<N;i++)rx=rwst[i]*nrwst[i]-iwst[i]*niwst[i],iwst[i]=rwst[i]*niwst[i]+iwst[i]*nrwst[i],rwst[i]=rx;return this.conjugate(rwst,iwst,N),this.transform(rwst,iwst,rmws,_,N,rbt),this.conjugate(rmws,_,N),this.normalize13b(rmws,N),out.negative=x.negative^y.negative,out.length=x.length+y.length,out._strip()},BN.prototype.mul=function mul(num){var out=new BN(null);return out.words=Array(this.length+num.length),this.mulTo(num,out)},BN.prototype.mulf=function mulf(num){var out=new BN(null);return out.words=Array(this.length+num.length),jumboMulTo(this,num,out)},BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)},BN.prototype.imuln=function imuln(num){var isNegNum=0>num;isNegNum&&(num=-num),assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i<this.length;i++){var w=(0|this.words[i])*num,lo=(67108863&w)+(67108863&carry);carry>>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i<w.length&&0===w[i];i++,res=res.sqr());if(++i<w.length)for(var q=res.sqr();i<w.length;i++,q=q.sqr())0!==w[i]&&(res=res.mul(q));return res},BN.prototype.iushln=function iushln(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(0!=r){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask,c=(0|this.words[i])-newCarry<<r;this.words[i]=c|carry,carry=newCarry>>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;i<s;i++)this.words[i]=0;this.length+=s}return this._strip()},BN.prototype.ishln=function ishln(bits){return assert(0===this.negative),this.iushln(bits)},BN.prototype.iushrn=function iushrn(bits,hint,extended){assert("number"==typeof bits&&0<=bits);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=_Mathmin((bits-r)/26,this.length),mask=67108863^67108863>>>r<<r,maskedWords=extended;if(h-=s,h=_Mathmax(0,h),maskedWords){for(var i=0;i<s;i++)maskedWords.words[i]=this.words[i];maskedWords.length=s}if(0===s);else if(this.length>s)for(this.length-=s,i=0;i<this.length;i++)this.words[i]=this.words[i+s];else this.words[0]=0,this.length=1;var carry=0;for(i=this.length-1;0<=i&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&0<=bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return!1;var w=this.words[s];return!!(w&q)},BN.prototype.imaskn=function imaskn(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!=r&&s++,this.length=_Mathmin(s,this.length),0!=r){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this._strip()},BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)},BN.prototype.iaddn=function iaddn(num){return assert("number"==typeof num),assert(67108864>num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<=num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&67108864<=this.words[i];i++)this.words[i]-=67108864,i==this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=_Mathmax(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(67108864>num),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i<this.length&&0>this.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this._strip()},BN.prototype.addn=function addn(num){return this.clone().iaddn(num)},BN.prototype.subn=function subn(num){return this.clone().isubn(num)},BN.prototype.iabs=function iabs(){return this.negative=0,this},BN.prototype.abs=function abs(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i<num.length;i++){w=(0|this.words[i+shift])+carry;var right=(0|num.words[i])*mul;w-=67108863&right,carry=(w>>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i<this.length-shift;i++)w=(0|this.words[i+shift])+carry,carry=w>>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i<this.length;i++)w=-(0|this.words[i])+carry,carry=w>>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;i<q.length;i++)q.words[i]=0}var diff=a.clone()._ishlnsubmul(b,1,m);0===diff.negative&&(a=diff,q&&(q.words[m]=1));for(var j=m-1,qj;0<=j;j--){for(qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]),qj=_Mathmin(0|qj/bhi,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0==(this.negative&num.negative)?num.length>this.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(x.iushrn(i);0<i--;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(y.iushrn(j);0<j--;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);0<=x.cmp(y)?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0===a.negative?a.clone():a.umod(p);for(var x1=new BN(1),x2=new BN(0),delta=b.clone();0<a.cmpn(1)&&0<b.cmpn(1);){for(var i=0,im=1;0==(a.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(a.iushrn(i);0<i--;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(b.iushrn(j);0<j--;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);0<=a.cmp(b)?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,0>res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return this._expand(s+1),this.words[s]|=q,this;for(var carry=q,i=s,w;0!==carry&&i<this.length;i++)w=0|this.words[i],w+=carry,carry=w>>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this._strip();var res;if(1<this.length)res=1;else{negative&&(num=-num),assert(67108863>=num,"Number is too big");var w=0|this.words[0];res=w===num?0:w<num?-1:1}return 0===this.negative?res:0|-res},BN.prototype.cmp=function cmp(num){if(0!==this.negative&&0===num.negative)return-1;if(0===this.negative&&0!==num.negative)return 1;var res=this.ucmp(num);return 0===this.negative?res:0|-res},BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;for(var res=0,i=this.length-1;0<=i;i--){var a=0|this.words[i],b=0|num.words[i];if(a!=b){a<b?res=-1:a>b&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return 0<=this.cmpn(num)},BN.prototype.gte=function gte(num){return 0<=this.cmp(num)},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return 0>=this.cmpn(num)},BN.prototype.lte=function lte(num){return 0>=this.cmp(num)},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);return 0===cmp?(r.words[0]=0,r.length=1):0<cmp?r.isub(this.p):void 0===r.strip?r._strip():r.strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var mask=4194303,outLen=_Mathmin(input.length,9),i=0;i<outLen;i++)output.words[i]=input.words[i];if(output.length=outLen,9>=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i<input.length;i++){var next=0|input.words[i];input.words[i-10]=(next&mask)<<4|prev>>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10<input.length?10:9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0,w;i<num.length;i++)w=0|num.words[i],lo+=977*w,num.words[i]=67108863&lo,lo=64*w+(0|lo/67108864);return 0===num.words[num.length-1]&&(num.length--,0===num.words[num.length-1]&&num.length--),num},inherits(P224,MPrime),inherits(P192,MPrime),inherits(P25519,MPrime),P25519.prototype.imulK=function imulK(num){for(var carry=0,i=0;i<num.length;i++){var hi=19*(0|num.words[i])+carry,lo=67108863&hi;hi>>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b),c=b.redSqr(),t=t.redMul(c),m=i}return r},Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);return 0===inv.negative?this.imod(inv):(inv.negative=0,this.imod(inv).redNeg())},Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(0===num.cmpn(1))return a.clone();var windowSize=4,wnd=Array(16);wnd[0]=new BN(1).toRed(this),wnd[1]=a;for(var i=2;i<wnd.length;i++)wnd[i]=this.mul(wnd[i-1],a);var res=wnd[0],current=0,currentLen=0,start=num.bitLength()%26;for(0===start&&(start=26),i=num.length-1;0<=i;i--){for(var word=num.words[i],j=start-1,bit;0<=j;j--){if(bit=1&word>>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:66}],65:[function(require,module,exports){function Rand(rand){this.rand=rand}var r;if(module.exports=function rand(len){return r||(r=new Rand(null)),r.generate(len)},module.exports.Rand=Rand,Rand.prototype.generate=function generate(len){return this._rand(len)},Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);for(var res=new Uint8Array(n),i=0;i<res.length;i++)res[i]=this.rand.getByte();return res},"object"==typeof self)self.crypto&&self.crypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.crypto.getRandomValues(arr),arr}:self.msCrypto&&self.msCrypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.msCrypto.getRandomValues(arr),arr}:"object"==typeof window&&(Rand.prototype._rand=function(){throw new Error("Not implemented yet")});else try{var crypto=require("crypto");if("function"!=typeof crypto.randomBytes)throw new Error("Not supported");Rand.prototype._rand=function _rand(n){return crypto.randomBytes(n)}}catch(e){}},{crypto:66}],66:[function(require,module,exports){},{}],67:[function(require,module,exports){function asUInt32Array(buf){Buffer.isBuffer(buf)||(buf=Buffer.from(buf));for(var len=0|buf.length/4,out=Array(len),i=0;i<len;i++)out[i]=buf.readUInt32BE(4*i);return out}function scrubVec(v){for(var i=0;i<v.length;v++)v[i]=0}function cryptBlock(M,keySchedule,SUB_MIX,SBOX,nRounds){for(var SUB_MIX0=SUB_MIX[0],SUB_MIX1=SUB_MIX[1],SUB_MIX2=SUB_MIX[2],SUB_MIX3=SUB_MIX[3],s0=M[0]^keySchedule[0],s1=M[1]^keySchedule[1],s2=M[2]^keySchedule[2],s3=M[3]^keySchedule[3],ksRow=4,round=1,t0,t1,t2,t3;round<nRounds;round++)t0=SUB_MIX0[s0>>>24]^SUB_MIX1[255&s1>>>16]^SUB_MIX2[255&s2>>>8]^SUB_MIX3[255&s3]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[255&s2>>>16]^SUB_MIX2[255&s3>>>8]^SUB_MIX3[255&s0]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[255&s3>>>16]^SUB_MIX2[255&s0>>>8]^SUB_MIX3[255&s1]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[255&s0>>>16]^SUB_MIX2[255&s1>>>8]^SUB_MIX3[255&s2]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[255&s1>>>16]<<16|SBOX[255&s2>>>8]<<8|SBOX[255&s3])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[255&s2>>>16]<<16|SBOX[255&s3>>>8]<<8|SBOX[255&s0])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[255&s3>>>16]<<16|SBOX[255&s0>>>8]<<8|SBOX[255&s1])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[255&s0>>>16]<<16|SBOX[255&s1>>>8]<<8|SBOX[255&s2])^keySchedule[ksRow++],t0>>>=0,t1>>>=0,t2>>>=0,t3>>>=0,[t0,t1,t2,t3]}function AES(key){this._key=asUInt32Array(key),this._reset()}var Buffer=require("safe-buffer").Buffer,RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=Array(256),j=0;256>j;j++)d[j]=128>j?j<<1:283^j<<1;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0,sx;256>i;++i){sx=xi^xi<<1^xi<<2^xi<<3^xi<<4,sx=99^(sx>>>8^255&sx),SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,0===x?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX:SBOX,INV_SBOX:INV_SBOX,SUB_MIX:SUB_MIX,INV_SUB_MIX:INV_SUB_MIX}}();AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=4*(nRounds+1),keySchedule=[],k=0;k<keySize;k++)keySchedule[k]=keyWords[k];for(k=keySize;k<ksRows;k++){var t=keySchedule[k-1];0==k%keySize?(t=t<<8|t>>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t],t^=RCON[0|k/keySize]<<24):6<keySize&&4==k%keySize&&(t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik<ksRows;ik++){var ksR=ksRows-ik,tt=keySchedule[ksR-(ik%4?0:4)];invKeySchedule[ik]=4>ik||4>=ksR?tt:G.INV_SUB_MIX[0][G.SBOX[tt>>>24]]^G.INV_SUB_MIX[1][G.SBOX[255&tt>>>16]]^G.INV_SUB_MIX[2][G.SBOX[255&tt>>>8]]^G.INV_SUB_MIX[3][G.SBOX[255&tt]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES},{"safe-buffer":290}],68:[function(require,module,exports){function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=_Mathmin(a.length,b.length),i=0;i<len;++i)out+=a[i]^b[i];return out}function calcIv(self,iv,ck){if(12===iv.length)return self._finID=Buffer.concat([iv,Buffer.from([0,0,0,1])]),Buffer.concat([iv,Buffer.from([0,0,0,2])]);var ghash=new GHASH(ck),len=iv.length,toPad=len%16;ghash.update(iv),toPad&&(toPad=16-toPad,ghash.update(Buffer.alloc(toPad,0))),ghash.update(Buffer.alloc(8,0));var ivBits=8*len,tail=Buffer.alloc(8);tail.writeUIntBE(ivBits,0,8),ghash.update(tail),self._finID=ghash.state;var out=Buffer.from(self._finID);return incr32(out),out}function StreamCipher(mode,key,iv,decrypt){Transform.call(this);var h=Buffer.alloc(4,0);this._cipher=new aes.AES(key);var ck=this._cipher.encryptBlock(h);this._ghash=new GHASH(ck),iv=calcIv(this,iv,ck),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._alen=0,this._len=0,this._mode=mode,this._authTag=null,this._called=!1}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits"),GHASH=require("./ghash"),xor=require("buffer-xor"),incr32=require("./incr32");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;16>rump&&(rump=Buffer.alloc(rump,0),this._ghash.update(rump))}this._called=!0;var out=this._mode.encrypt(this,chunk);return this._decrypt?this._ghash.update(chunk):this._ghash.update(out),this._len+=chunk.length,out},StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var tag=xor(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&xorTest(tag,this._authTag))throw new Error("Unsupported state or unable to authenticate data");this._authTag=tag,this._cipher.scrub()},StreamCipher.prototype.getAuthTag=function getAuthTag(){if(this._decrypt||!Buffer.isBuffer(this._authTag))throw new Error("Attempting to get auth tag in unsupported state");return this._authTag},StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(!this._decrypt)throw new Error("Attempting to set auth tag in unsupported state");this._authTag=tag},StreamCipher.prototype.setAAD=function setAAD(buf){if(this._called)throw new Error("Attempting to set AAD in unsupported state");this._ghash.update(buf),this._alen+=buf.length},module.exports=StreamCipher},{"./aes":67,"./ghash":72,"./incr32":73,"buffer-xor":100,"cipher-base":110,inherits:189,"safe-buffer":290}],69:[function(require,module,exports){function getCiphers(){return Object.keys(modes)}var ciphers=require("./encrypter"),deciphers=require("./decrypter"),modes=require("./modes/list.json");exports.createCipher=exports.Cipher=ciphers.createCipher,exports.createCipheriv=exports.Cipheriv=ciphers.createCipheriv,exports.createDecipher=exports.Decipher=deciphers.createDecipher,exports.createDecipheriv=exports.Decipheriv=deciphers.createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"./decrypter":70,"./encrypter":71,"./modes/list.json":81}],70:[function(require,module,exports){function Decipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function unpad(last){var padded=last[15];if(1>padded||16<padded)throw new Error("unable to decrypt data");for(var i=-1;++i<padded;)if(last[i+(16-padded)]!==padded)throw new Error("unable to decrypt data");return 16===padded?void 0:last.slice(0,16-padded)}function createDecipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);return"stream"===config.type?new StreamCipher(config.module,password,iv,!0):"auth"===config.type?new AuthCipher(config.module,password,iv,!0):new Decipher(config.module,password,iv)}function createDecipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createDecipheriv(suite,keys.key,keys.iv)}var AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,MODES=require("./modes"),StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Decipher,Transform),Decipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get(this._autopadding);)thing=this._mode.decrypt(this,chunk),out.push(thing);return Buffer.concat(out)},Decipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return unpad(this._mode.decrypt(this,chunk));if(chunk)throw new Error("data not multiple of block length")},Decipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(autoPadding){var out;if(autoPadding){if(16<this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;}else if(16<=this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache},exports.createDecipher=createDecipher,exports.createDecipheriv=createDecipheriv},{"./aes":67,"./authCipher":68,"./modes":80,"./streamCipher":83,"cipher-base":110,evp_bytestokey:157,inherits:189,"safe-buffer":290}],71:[function(require,module,exports){function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function createCipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);return"stream"===config.type?new StreamCipher(config.module,password,iv):"auth"===config.type?new AuthCipher(config.module,password,iv):new Cipher(config.module,password,iv)}function createCipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createCipheriv(suite,keys.key,keys.iv)}var MODES=require("./modes"),AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer.concat(out)};var PADDING=Buffer.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error("data not multiple of block length")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(){if(15<this.cache.length){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer.allocUnsafe(len),i=-1;++i<len;)padBuff.writeUInt8(len,i);return Buffer.concat([this.cache,padBuff])},exports.createCipheriv=createCipheriv,exports.createCipher=createCipher},{"./aes":67,"./authCipher":68,"./modes":80,"./streamCipher":83,"cipher-base":110,evp_bytestokey:157,inherits:189,"safe-buffer":290}],72:[function(require,module,exports){function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer.alloc(16,0),this.cache=Buffer.allocUnsafe(0)}var Buffer=require("safe-buffer").Buffer,ZEROES=Buffer.alloc(16,0);GHASH.prototype.ghash=function(block){for(var i=-1;++i<block.length;)this.state[i]^=block[i];this._multiply()},GHASH.prototype._multiply=function(){for(var Vi=toArray(this.h),Zi=[0,0,0,0],i=-1,j,xi,lsbVi;128>++i;){for(xi=0!=(this.state[~~(i/8)]&1<<7-i%8),xi&&(Zi[0]^=Vi[0],Zi[1]^=Vi[1],Zi[2]^=Vi[2],Zi[3]^=Vi[3]),lsbVi=0!=(1&Vi[3]),j=3;0<j;j--)Vi[j]=Vi[j]>>>1|(1&Vi[j-1])<<31;Vi[0]>>>=1,lsbVi&&(Vi[0]^=-520093696)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);for(var chunk;16<=this.cache.length;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH},{"safe-buffer":290}],73:[function(require,module,exports){function incr32(iv){for(var len=iv.length,item;len--;)if(item=iv.readUInt8(len),255===item)iv.writeUInt8(0,len);else{item++,iv.writeUInt8(item,len);break}}module.exports=incr32},{}],74:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);return self._prev=self._cipher.encryptBlock(data),self._prev},exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":100}],75:[function(require,module,exports){function encryptStart(self,data,decrypt){var len=data.length,out=xor(data,self._cache);return self._cache=self._cache.slice(len),self._prev=Buffer.concat([self._prev,decrypt?data:out]),out}var Buffer=require("safe-buffer").Buffer,xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){for(var out=Buffer.allocUnsafe(0),len;data.length;)if(0===self._cache.length&&(self._cache=self._cipher.encryptBlock(self._prev),self._prev=Buffer.allocUnsafe(0)),self._cache.length<=data.length)len=self._cache.length,out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]),data=data.slice(len);else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}return out}},{"buffer-xor":100,"safe-buffer":290}],76:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){for(var i=-1,len=8,out=0,pad,bit,value;++i<len;)pad=self._cipher.encryptBlock(self._prev),bit=byteParam&1<<7-i?128:0,value=pad[0]^bit,out+=(128&value)>>i%8,self._prev=shiftIn(self._prev,decrypt?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer.allocUnsafe(buffer.length);for(buffer=Buffer.concat([buffer,Buffer.from([value])]);++i<len;)out[i]=buffer[i]<<1|buffer[i+1]>>7;return out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":290}],77:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev),out=pad[0]^byteParam;return self._prev=Buffer.concat([self._prev.slice(1),Buffer.from([decrypt?byteParam:out])]),out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":290}],78:[function(require,module,exports){function getBlock(self){var out=self._cipher.encryptBlockRaw(self._prev);return incr32(self._prev),out}var xor=require("buffer-xor"),Buffer=require("safe-buffer").Buffer,incr32=require("../incr32"),blockSize=16;exports.encrypt=function(self,chunk){var chunkNum=_Mathceil(chunk.length/blockSize),start=self._cache.length;self._cache=Buffer.concat([self._cache,Buffer.allocUnsafe(chunkNum*blockSize)]);for(var i=0;i<chunkNum;i++){var out=getBlock(self),offset=start+i*blockSize;self._cache.writeUInt32BE(out[0],offset+0),self._cache.writeUInt32BE(out[1],offset+4),self._cache.writeUInt32BE(out[2],offset+8),self._cache.writeUInt32BE(out[3],offset+12)}var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}},{"../incr32":73,"buffer-xor":100,"safe-buffer":290}],79:[function(require,module,exports){exports.encrypt=function(self,block){return self._cipher.encryptBlock(block)},exports.decrypt=function(self,block){return self._cipher.decryptBlock(block)}},{}],80:[function(require,module,exports){var modeModules={ECB:require("./ecb"),CBC:require("./cbc"),CFB:require("./cfb"),CFB8:require("./cfb8"),CFB1:require("./cfb1"),OFB:require("./ofb"),CTR:require("./ctr"),GCM:require("./ctr")},modes=require("./list.json");for(var key in modes)modes[key].module=modeModules[modes[key].mode];module.exports=modes},{"./cbc":74,"./cfb":75,"./cfb1":76,"./cfb8":77,"./ctr":78,"./ecb":79,"./list.json":81,"./ofb":82}],81:[function(require,module,exports){module.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}},{}],82:[function(require,module,exports){(function(Buffer){(function(){function getBlock(self){return self._prev=self._cipher.encryptBlock(self._prev),self._prev}var xor=require("buffer-xor");exports.encrypt=function(self,chunk){for(;self._cache.length<chunk.length;)self._cache=Buffer.concat([self._cache,getBlock(self)]);var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"buffer-xor":100}],83:[function(require,module,exports){function StreamCipher(mode,key,iv,decrypt){Transform.call(this),this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._mode=mode}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){return this._mode.encrypt(this,chunk,this._decrypt)},StreamCipher.prototype._final=function(){this._cipher.scrub()},module.exports=StreamCipher},{"./aes":67,"cipher-base":110,inherits:189,"safe-buffer":290}],84:[function(require,module,exports){function createCipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createCipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite});throw new TypeError("invalid suite type")}function createDecipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createDecipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite,decrypt:!0});throw new TypeError("invalid suite type")}function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}var DES=require("browserify-des"),aes=require("browserify-aes/browser"),aesModes=require("browserify-aes/modes"),desModes=require("browserify-des/modes"),ebtk=require("evp_bytestokey");exports.createCipher=exports.Cipher=createCipher,exports.createCipheriv=exports.Cipheriv=createCipheriv,exports.createDecipher=exports.Decipher=createDecipher,exports.createDecipheriv=exports.Decipheriv=createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":69,"browserify-aes/modes":80,"browserify-des":85,"browserify-des/modes":86,evp_bytestokey:157}],85:[function(require,module,exports){function DES(opts){CipherBase.call(this);var modeName=opts.mode.toLowerCase(),mode=modes[modeName],type;type=opts.decrypt?"decrypt":"encrypt";var key=opts.key;Buffer.isBuffer(key)||(key=Buffer.from(key)),("des-ede"===modeName||"des-ede-cbc"===modeName)&&(key=Buffer.concat([key,key.slice(0,8)]));var iv=opts.iv;Buffer.isBuffer(iv)||(iv=Buffer.from(iv)),this._des=mode.create({key:key,iv:iv,type:type})}var CipherBase=require("cipher-base"),des=require("des.js"),inherits=require("inherits"),Buffer=require("safe-buffer").Buffer,modes={"des-ede3-cbc":des.CBC.instantiate(des.EDE),"des-ede3":des.EDE,"des-ede-cbc":des.CBC.instantiate(des.EDE),"des-ede":des.EDE,"des-cbc":des.CBC.instantiate(des.DES),"des-ecb":des.DES};modes.des=modes["des-cbc"],modes.des3=modes["des-ede3-cbc"],module.exports=DES,inherits(DES,CipherBase),DES.prototype._update=function(data){return Buffer.from(this._des.update(data))},DES.prototype._final=function(){return Buffer.from(this._des.final())}},{"cipher-base":110,"des.js":124,inherits:189,"safe-buffer":290}],86:[function(require,module,exports){exports["des-ecb"]={key:8,iv:0},exports["des-cbc"]=exports.des={key:8,iv:8},exports["des-ede3-cbc"]=exports.des3={key:24,iv:8},exports["des-ede3"]={key:24,iv:0},exports["des-ede-cbc"]={key:16,iv:8},exports["des-ede"]={key:16,iv:0}},{}],87:[function(require,module,exports){(function(Buffer){(function(){function blind(priv){var r=getr(priv),blinder=r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function getr(priv){var len=priv.modulus.byteLength(),r;do r=new BN(randomBytes(len));while(0<=r.cmp(priv.modulus)||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,"be",len)}var BN=require("bn.js"),randomBytes=require("randombytes");crt.getr=getr,module.exports=crt}).call(this)}).call(this,require("buffer").Buffer)},{"bn.js":64,buffer:101,randombytes:262}],88:[function(require,module,exports){module.exports=require("./browser/algorithms.json")},{"./browser/algorithms.json":89}],89:[function(require,module,exports){module.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],90:[function(require,module,exports){module.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],91:[function(require,module,exports){function Sign(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function Verify(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}var Buffer=require("safe-buffer").Buffer,createHash=require("create-hash"),stream=require("readable-stream"),inherits=require("inherits"),sign=require("./sign"),verify=require("./verify"),algorithms=require("./algorithms.json");Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer.from(algorithms[key].id,"hex"),algorithms[key.toLowerCase()]=algorithms[key]}),inherits(Sign,stream.Writable),Sign.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function signMethod(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc?sig.toString(enc):sig},inherits(Verify,stream.Writable),Verify.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function verifyMethod(key,sig,enc){"string"==typeof sig&&(sig=Buffer.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)},module.exports={Sign:createSign,Verify:createVerify,createSign:createSign,createVerify:createVerify}},{"./algorithms.json":89,"./sign":92,"./verify":93,"create-hash":116,inherits:189,"readable-stream":281,"safe-buffer":290}],92:[function(require,module,exports){function sign(hash,key,hashType,signType,tag){var priv=parseKeys(key);if(priv.curve){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");return ecSign(hash,priv)}if("dsa"===priv.type){if("dsa"!==signType)throw new Error("wrong private key type");return dsaSign(hash,priv,hashType)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");hash=Buffer.concat([tag,hash]);for(var len=priv.modulus.byteLength(),pad=[0,1];hash.length+pad.length+1<len;)pad.push(255);pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);var out=crt(pad,priv);return out}function ecSign(hash,priv){var curveId=curves[priv.curve.join(".")];if(!curveId)throw new Error("unknown curve "+priv.curve.join("."));var curve=new EC(curveId),key=curve.keyFromPrivate(priv.privateKey),out=key.sign(hash);return Buffer.from(out.toDER())}function dsaSign(hash,priv,algo){for(var x=priv.params.priv_key,p=priv.params.p,q=priv.params.q,g=priv.params.g,r=new BN(0),H=bits2int(hash,q).mod(q),s=!1,kv=getKey(x,q,hash,algo),k;!1===s;)k=makeKey(q,kv,algo),r=makeR(g,k,p,q),s=k.invm(q).imul(H.add(x.mul(r))).mod(q),0===s.cmpn(0)&&(s=!1,r=new BN(0));return toDER(r,s)}function toDER(r,s){r=r.toArray(),s=s.toArray(),128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s));var total=r.length+s.length+4,res=[48,total,2,r.length];return res=res.concat(r,[2,s.length],s),Buffer.from(res)}function getKey(x,q,hash,algo){if(x=Buffer.from(x.toArray()),x.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-x.length);x=Buffer.concat([zeros,x])}var hlen=hash.length,hbits=bits2octets(hash,q),v=Buffer.alloc(hlen);v.fill(1);var k=Buffer.alloc(hlen);return k=createHmac(algo,k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),k=createHmac(algo,k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),{k:k,v:v}}function bits2int(obits,q){var bits=new BN(obits),shift=(obits.length<<3)-q.bitLength();return 0<shift&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer.from(bits.toArray());if(out.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-out.length);out=Buffer.concat([zeros,out])}return out}function makeKey(q,kv,algo){var t,k;do{for(t=Buffer.alloc(0);8*t.length<q.bitLength();)kv.v=createHmac(algo,kv.k).update(kv.v).digest(),t=Buffer.concat([t,kv.v]);k=bits2int(t,q),kv.k=createHmac(algo,kv.k).update(kv.v).update(Buffer.from([0])).digest(),kv.v=createHmac(algo,kv.k).update(kv.v).digest()}while(-1!==k.cmp(q));return k}function makeR(g,k,p,q){return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)}var Buffer=require("safe-buffer").Buffer,createHmac=require("create-hmac"),crt=require("browserify-rsa"),EC=require("elliptic").ec,BN=require("bn.js"),parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=sign,module.exports.getKey=getKey,module.exports.makeKey=makeKey},{"./curves.json":90,"bn.js":64,"browserify-rsa":87,"create-hmac":118,elliptic:135,"parse-asn1":236,"safe-buffer":290}],93:[function(require,module,exports){function verify(sig,hash,key,signType,tag){var pub=parseKeys(key);if("ec"===pub.type){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");return ecVerify(sig,hash,pub)}if("dsa"===pub.type){if("dsa"!==signType)throw new Error("wrong public key type");return dsaVerify(sig,hash,pub)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");hash=Buffer.concat([tag,hash]);for(var len=pub.modulus.byteLength(),pad=[1],padNum=0;hash.length+pad.length+2<len;)pad.push(255),padNum++;pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);pad=Buffer.from(pad);var red=BN.mont(pub.modulus);sig=new BN(sig).toRed(red),sig=sig.redPow(new BN(pub.publicExponent)),sig=Buffer.from(sig.fromRed().toArray());var out=8>padNum?1:0;for(len=_Mathmin(sig.length,pad.length),sig.length!==pad.length&&(out=1),i=-1;++i<len;)out|=sig[i]^pad[i];return 0==out}function ecVerify(sig,hash,pub){var curveId=curves[pub.data.algorithm.curve.join(".")];if(!curveId)throw new Error("unknown curve "+pub.data.algorithm.curve.join("."));var curve=new EC(curveId),pubkey=pub.data.subjectPrivateKey.data;return curve.verify(hash,sig,pubkey)}function dsaVerify(sig,hash,pub){var p=pub.data.p,q=pub.data.q,g=pub.data.g,y=pub.data.pub_key,unpacked=parseKeys.signature.decode(sig,"der"),s=unpacked.s,r=unpacked.r;checkValue(s,q),checkValue(r,q);var montp=BN.mont(p),w=s.invm(q),v=g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q);return 0===v.cmp(r)}function checkValue(b,q){if(0>=b.cmpn(0))throw new Error("invalid sig");if(b.cmp(q)>=q)throw new Error("invalid sig")}var Buffer=require("safe-buffer").Buffer,BN=require("bn.js"),EC=require("elliptic").ec,parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=verify},{"./curves.json":90,"bn.js":64,elliptic:135,"parse-asn1":236,"safe-buffer":290}],94:[function(require,module,exports){arguments[4][66][0].apply(exports,arguments)},{dup:66}],95:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),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}],96:[function(require,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;!0;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);return 0<=nb?(0<nb&&(self.lastNeed=nb-1),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb)?(0<nb&&(self.lastNeed=nb-2),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb?(0<nb&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"\uFFFD";if(1<self.lastNeed&&1<buf.length){if(128!=(192&buf[1]))return self.lastNeed=1,"\uFFFD";if(2<self.lastNeed&&2<buf.length&&128!=(192&buf[2]))return self.lastNeed=2,"\uFFFD"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0===r?this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,p,0,buf.length),this.lastNeed-=buf.length):r}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"\uFFFD":r}function utf16Text(buf,i){if(0==(buf.length-i)%2){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(55296<=c&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<buf.length?r?r+this.text(buf,i):this.text(buf,i):r||""},StringDecoder.prototype.end=utf8End,StringDecoder.prototype.text=utf8Text,StringDecoder.prototype.fillLast=function(buf){return this.lastNeed<=buf.length?(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length)}},{"safe-buffer":95}],97:[function(require,module,exports){(function(Buffer){(function(){function allocUnsafe(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}module.exports=allocUnsafe}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],98:[function(require,module,exports){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function alloc(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"buffer-alloc-unsafe":97,"buffer-fill":99}],99:[function(require,module,exports){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}function fill(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=fill}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],100:[function(require,module,exports){(function(Buffer){(function(){module.exports=function xor(a,b){for(var length=_Mathmin(a.length,b.length),buffer=new Buffer(length),i=0;i<length;++i)buffer[i]=a[i]^b[i];return buffer}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],101:[function(require,module,exports){(function(Buffer){(function(){/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
@@ -36,7 +36,7 @@
* Copyright(c) 2015 Andreas Lubbe
* Copyright(c) 2015 Tiancheng "Timothy" Gu
* MIT Licensed
- */"use strict";function escapeHtml(string){var str=""+string,match=matchHtmlRegExp.exec(str);if(!match)return str;var html="",index=0,lastIndex=0,escape;for(index=match.index;index<str.length;index++){switch(str.charCodeAt(index)){case 34:escape="&quot;";break;case 38:escape="&amp;";break;case 39:escape="&#39;";break;case 60:escape="&lt;";break;case 62:escape="&gt;";break;default:continue;}lastIndex!==index&&(html+=str.substring(lastIndex,index)),lastIndex=index+1,html+=escape}return lastIndex===index?html:html+str.substring(lastIndex,index)}var matchHtmlRegExp=/["'&<>]/;module.exports=escapeHtml},{}],156:[function(require,module,exports){"use strict";function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)}function EventEmitter(){EventEmitter.init.call(this)}function checkListener(listener){if("function"!=typeof listener)throw new TypeError("The \"listener\" argument must be of type Function. Received type "+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m,events,existing;if(checkListener(listener),events=target._events,void 0===events?(events=target._events=Object.create(null),target._eventsCount=0):(void 0!==events.newListener&&(target.emit("newListener",type,listener.listener?listener.listener:listener),events=target._events),existing=events[type]),void 0===existing)existing=events[type]=listener,++target._eventsCount;else if("function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener),m=_getMaxListeners(target),0<m&&existing.length>m&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+(type+" listeners added. Use emitter.setMaxListeners() to increase limit"));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,ProcessEmitWarning(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(events===void 0)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount(type){var events=this._events;if(events!==void 0){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n){for(var copy=Array(n),i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){for(var ret=Array(arr.length),i=0;i<ret.length;++i)ret[i]=arr[i].listener||arr[i];return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver),reject(err)}function resolver(){"function"==typeof emitter.removeListener&&emitter.removeListener("error",errorListener),resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:!0}),"error"!==name&&addErrorHandlerIfEventEmitter(emitter,errorListener,{once:!0})})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){"function"==typeof emitter.on&&eventTargetAgnosticAddListener(emitter,"error",handler,flags)}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if("function"==typeof emitter.on)flags.once?emitter.once(name,listener):emitter.on(name,listener);else if("function"==typeof emitter.addEventListener)emitter.addEventListener(name,function wrapListener(arg){flags.once&&emitter.removeEventListener(name,wrapListener),listener(arg)});else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type "+typeof emitter)}var R="object"==typeof Reflect?Reflect:null,ReflectApply=R&&"function"==typeof R.apply?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)},ReflectOwnKeys;ReflectOwnKeys=R&&"function"==typeof R.ownKeys?R.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}:function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)};var NumberIsNaN=_NumberisNaN||function NumberIsNaN(value){return value!==value};module.exports=EventEmitter,module.exports.once=once,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(arg){if("number"!=typeof arg||0>arg||NumberIsNaN(arg))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+arg+".");defaultMaxListeners=arg}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if("number"!=typeof n||0>n||NumberIsNaN(n))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+n+".");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function emit(type){for(var args=[],i=1;i<arguments.length;i++)args.push(arguments[i]);var doError="error"===type,events=this._events;if(events!==void 0)doError=doError&&events.error===void 0;else if(!doError)return!1;if(doError){var er;if(0<args.length&&(er=args[0]),er instanceof Error)throw er;var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));throw err.context=er,err}var handler=events[type];if(handler===void 0)return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)ReflectApply(listeners[i],this,args);return!0},EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,!0)},EventEmitter.prototype.once=function once(type,listener){return checkListener(listener),this.on(type,_onceWrap(this,type,listener)),this},EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){return checkListener(listener),this.prependListener(type,_onceWrap(this,type,listener)),this},EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;if(checkListener(listener),events=this._events,void 0===events)return this;if(list=events[type],void 0===list)return this;if(list===listener||list.listener===listener)0==--this._eventsCount?this._events=Object.create(null):(delete events[type],events.removeListener&&this.emit("removeListener",type,list.listener||listener));else if("function"!=typeof list){for(position=-1,i=list.length-1;0<=i;i--)if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener,position=i;break}if(0>position)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;if(events=this._events,void 0===events)return this;if(void 0===events.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]),this;if(0===arguments.length){var keys=Object.keys(events),key;for(i=0;i<keys.length;++i)key=keys[i],"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(listeners=events[type],"function"==typeof listeners)this.removeListener(type,listeners);else if(void 0!==listeners)for(i=listeners.length-1;0<=i;i--)this.removeListener(type,listeners[i]);return this},EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,!0)},EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,!1)},EventEmitter.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount.call(emitter,type)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return 0<this._eventsCount?ReflectOwnKeys(this._events):[]}},{}],157:[function(require,module,exports){function EVP_BytesToKey(password,salt,keyBits,ivLen){if(Buffer.isBuffer(password)||(password=Buffer.from(password,"binary")),salt&&(Buffer.isBuffer(salt)||(salt=Buffer.from(salt,"binary")),8!==salt.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var keyLen=keyBits/8,key=Buffer.alloc(keyLen),iv=Buffer.alloc(ivLen||0),tmp=Buffer.alloc(0),hash;0<keyLen||0<ivLen;){hash=new MD5,hash.update(tmp),hash.update(password),salt&&hash.update(salt),tmp=hash.digest();var used=0;if(0<keyLen){var keyStart=key.length-keyLen;used=_Mathmin(keyLen,tmp.length),tmp.copy(key,keyStart,0,used),keyLen-=used}if(used<tmp.length&&0<ivLen){var ivStart=iv.length-ivLen,length=_Mathmin(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length),ivLen-=length}}return tmp.fill(0),{key:key,iv:iv}}var Buffer=require("safe-buffer").Buffer,MD5=require("md5.js");module.exports=EVP_BytesToKey},{"md5.js":210,"safe-buffer":290}],158:[function(require,module,exports){module.exports=class FixedFIFO{constructor(hwm){if(!(0<hwm)||0!=(hwm-1&hwm))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(hwm),this.mask=hwm-1,this.top=0,this.btm=0,this.next=null}push(data){return!(void 0!==this.buffer[this.top])&&(this.buffer[this.top]=data,this.top=this.top+1&this.mask,!0)}shift(){const last=this.buffer[this.btm];if(void 0!==last)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,last}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}},{}],159:[function(require,module,exports){const FixedFIFO=require("./fixed-size");module.exports=class FastFIFO{constructor(hwm){this.hwm=hwm||16,this.head=new FixedFIFO(this.hwm),this.tail=this.head}push(val){if(!this.head.push(val)){const prev=this.head;this.head=prev.next=new FixedFIFO(2*this.head.buffer.length),this.head.push(val)}}shift(){const val=this.tail.shift();if(void 0===val&&this.tail.next){const next=this.tail.next;return this.tail.next=null,this.tail=next,this.tail.shift()}return val}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},{"./fixed-size":158}],160:[function(require,module,exports){const{Readable}=require("readable-stream"),toBuffer=require("typedarray-to-buffer");class FileReadStream extends Readable{constructor(file,opts={}){super(opts),this._offset=0,this._ready=!1,this._file=file,this._size=file.size,this._chunkSize=opts.chunkSize||_Mathmax(this._size/1e3,204800);const reader=new FileReader;reader.onload=()=>{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}module.exports=FileReadStream},{"readable-stream":281,"typedarray-to-buffer":329}],161:[function(require,module,exports){"use strict";var isCallable=require("is-callable"),toStr=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,forEachArray=function forEachArray(array,iterator,receiver){for(var i=0,len=array.length;i<len;i++)hasOwnProperty.call(array,i)&&(null==receiver?iterator(array[i],i,array):iterator.call(receiver,array[i],i,array))},forEachString=function forEachString(string,iterator,receiver){for(var i=0,len=string.length;i<len;i++)null==receiver?iterator(string.charAt(i),i,string):iterator.call(receiver,string.charAt(i),i,string)},forEachObject=function forEachObject(object,iterator,receiver){for(var k in object)hasOwnProperty.call(object,k)&&(null==receiver?iterator(object[k],k,object):iterator.call(receiver,object[k],k,object))},forEach=function forEach(list,iterator,thisArg){if(!isCallable(iterator))throw new TypeError("iterator must be a function");var receiver;3<=arguments.length&&(receiver=thisArg),"[object Array]"===toStr.call(list)?forEachArray(list,iterator,receiver):"string"==typeof list?forEachString(list,iterator,receiver):forEachObject(list,iterator,receiver)};module.exports=forEach},{"is-callable":194}],162:[function(require,module,exports){var FreeList=function(){function FreeList(name,max,constructor){this.name=name,this.max=max,this.constructor=null==constructor?function(){}:constructor,this.list=[]}return FreeList.prototype.alloc=function(){return this.list.length?this.list.shift():this.constructor.apply(this,arguments)},FreeList.prototype.free=function(obj){return!!(this.list.length<this.max)&&(this.list.push(obj),!0)},FreeList}();FreeList.FreeList=FreeList,module.exports=FreeList},{}],163:[function(require,module,exports){"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",slice=Array.prototype.slice,toStr=Object.prototype.toString,funcType="[object Function]";module.exports=function bind(that){var target=this;if("function"!=typeof target||toStr.call(target)!==funcType)throw new TypeError("Function.prototype.bind called on incompatible "+target);for(var args=slice.call(arguments,1),binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))},boundLength=_Mathmax(0,target.length-args.length),boundArgs=[],i=0,bound;i<boundLength;i++)boundArgs.push("$"+i);if(bound=Function("binder","return function ("+boundArgs.join(",")+"){ return binder.apply(this,arguments); }")(binder),target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null}return bound}},{}],164:[function(require,module,exports){"use strict";var implementation=require("./implementation");module.exports=Function.prototype.bind||implementation},{"./implementation":163}],165:[function(require,module,exports){module.exports=function getBrowserRTC(){if("undefined"==typeof globalThis)return null;var wrtc={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return wrtc.RTCPeerConnection?wrtc:null}},{}],166:[function(require,module,exports){"use strict";var $SyntaxError=SyntaxError,$Function=Function,$TypeError=TypeError,getEvalledConstructor=function(expressionSyntax){try{return $Function("\"use strict\"; return ("+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=Object.getOwnPropertyDescriptor,undefined;if($gOPD)try{$gOPD({},"")}catch(e){$gOPD=null}var throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return arguments.callee,throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=require("has-symbols")(),getProto=Object.getPrototypeOf||function(x){return x.__proto__},needsEval={},TypedArray="undefined"==typeof Uint8Array?void 0:getProto(Uint8Array),INTRINSICS={"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols?getProto(new Map()[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols?getProto(new Set()[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):void 0,"%Symbol%":hasSymbols?Symbol:void 0,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet},doEval=function doEval(name){var value;if("%AsyncFunction%"===name)value=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===name)value=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===name)value=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===name){var fn=doEval("%AsyncGeneratorFunction%");fn&&(value=fn.prototype)}else if("%AsyncIteratorPrototype%"===name){var gen=doEval("%AsyncGenerator%");gen&&(value=getProto(gen.prototype))}return INTRINSICS[name]=value,value},LEGACY_ALIASES={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=require("function-bind"),hasOwn=require("has"),$concat=bind.call(Function.call,Array.prototype.concat),$spliceApply=bind.call(Function.apply,Array.prototype.splice),$replace=bind.call(Function.call,_Stringprototype.replace),$strSlice=bind.call(Function.call,_Stringprototype.slice),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function stringToPath(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");else if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match}),result},getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var intrinsicName=name,alias;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(alias=LEGACY_ALIASES[intrinsicName],intrinsicName="%"+alias[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval&&(value=doEval(intrinsicName)),"undefined"==typeof value&&!allowMissing)throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!");return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};module.exports=function GetIntrinsic(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(1<arguments.length&&"boolean"!=typeof allowMissing)throw new $TypeError("\"allowMissing\" argument must be a boolean");var parts=stringToPath(name),intrinsicBaseName=0<parts.length?parts[0]:"",intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing),intrinsicRealName=intrinsic.name,value=intrinsic.value,skipFurtherCaching=!1,alias=intrinsic.alias;alias&&(intrinsicBaseName=alias[0],$spliceApply(parts,$concat([0,1],alias)));for(var i=1,isOwn=!0;i<parts.length;i+=1){var part=parts[i],first=$strSlice(part,0,1),last=$strSlice(part,-1);if(("\""===first||"'"===first||"`"===first||"\""===last||"'"===last||"`"===last)&&first!==last)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==part&&isOwn||(skipFurtherCaching=!0),intrinsicBaseName+="."+part,intrinsicRealName="%"+intrinsicBaseName+"%",hasOwn(INTRINSICS,intrinsicRealName))value=INTRINSICS[intrinsicRealName];else if(null!=value){if(!(part in value)){if(!allowMissing)throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");return}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);isOwn=!!desc,value=isOwn&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[part]}else isOwn=hasOwn(value,part),value=value[part];isOwn&&!skipFurtherCaching&&(INTRINSICS[intrinsicRealName]=value)}}return value}},{"function-bind":164,has:170,"has-symbols":167}],167:[function(require,module,exports){"use strict";var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=require("./shams");module.exports=function hasNativeSymbols(){return!("function"!=typeof origSymbol)&&!("function"!=typeof Symbol)&&!("symbol"!=typeof origSymbol("foo"))&&!("symbol"!=typeof Symbol("bar"))&&hasSymbolSham()}},{"./shams":168}],168:[function(require,module,exports){"use strict";module.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;var symVal=42;for(sym in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;var syms=Object.getOwnPropertySymbols(obj);if(1!==syms.length||syms[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(42!==descriptor.value||!0!==descriptor.enumerable)return!1}return!0}},{}],169:[function(require,module,exports){"use strict";var hasSymbols=require("has-symbols/shams");module.exports=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}},{"has-symbols/shams":168}],170:[function(require,module,exports){"use strict";var bind=require("function-bind");module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":164}],171:[function(require,module,exports){"use strict";function throwIfNotStringOrBuffer(val,prefix){if(!Buffer.isBuffer(val)&&"string"!=typeof val)throw new TypeError(prefix+" must be a string or a buffer")}function HashBase(blockSize){Transform.call(this),this._block=Buffer.allocUnsafe(blockSize),this._blockSize=blockSize,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}var Buffer=require("safe-buffer").Buffer,Transform=require("readable-stream").Transform,inherits=require("inherits");inherits(HashBase,Transform),HashBase.prototype._transform=function(chunk,encoding,callback){var error=null;try{this.update(chunk,encoding)}catch(err){error=err}callback(error)},HashBase.prototype._flush=function(callback){var error=null;try{this.push(this.digest())}catch(err){error=err}callback(error)},HashBase.prototype.update=function(data,encoding){if(throwIfNotStringOrBuffer(data,"Data"),this._finalized)throw new Error("Digest already called");Buffer.isBuffer(data)||(data=Buffer.from(data,encoding));for(var block=this._block,offset=0;this._blockOffset+data.length-offset>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)block[i++]=data[offset++];this._update(),this._blockOffset=0}for(;offset<data.length;)block[this._blockOffset++]=data[offset++];for(var j=0,carry=8*data.length;0<carry;++j)this._length[j]+=carry,carry=0|this._length[j]/4294967296,0<carry&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error("_update is not implemented")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var digest=this._digest();encoding!==void 0&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;4>i;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error("_digest is not implemented")},module.exports=HashBase},{inherits:189,"readable-stream":281,"safe-buffer":290}],172:[function(require,module,exports){var hash=exports;hash.utils=require("./hash/utils"),hash.common=require("./hash/common"),hash.sha=require("./hash/sha"),hash.ripemd=require("./hash/ripemd"),hash.hmac=require("./hash/hmac"),hash.sha1=hash.sha.sha1,hash.sha256=hash.sha.sha256,hash.sha224=hash.sha.sha224,hash.sha384=hash.sha.sha384,hash.sha512=hash.sha.sha512,hash.ripemd160=hash.ripemd.ripemd160},{"./hash/common":173,"./hash/hmac":174,"./hash/ripemd":175,"./hash/sha":176,"./hash/utils":183}],173:[function(require,module,exports){"use strict";function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var utils=require("./utils"),assert=require("minimalistic-assert");exports.BlockHash=BlockHash,BlockHash.prototype.update=function update(msg,enc){if(msg=utils.toArray(msg,enc),this.pending=this.pending?this.pending.concat(msg):msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),0===this.pending.length&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i<msg.length;i+=this._delta32)this._update(msg,i,i+this._delta32)}return this},BlockHash.prototype.digest=function digest(enc){return this.update(this._pad()),assert(null===this.pending),this._digest(enc)},BlockHash.prototype._pad=function pad(){var len=this.pendingTotal,bytes=this._delta8,k=bytes-(len+this.padLength)%bytes,res=Array(k+this.padLength);res[0]=128;for(var i=1;i<k;i++)res[i]=0;if(len<<=3,"big"===this.endian){for(var t=8;t<this.padLength;t++)res[i++]=0;res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=255&len>>>24,res[i++]=255&len>>>16,res[i++]=255&len>>>8,res[i++]=255&len}else for(res[i++]=255&len,res[i++]=255&len>>>8,res[i++]=255&len>>>16,res[i++]=255&len>>>24,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,t=8;t<this.padLength;t++)res[i++]=0;return res}},{"./utils":183,"minimalistic-assert":219}],174:[function(require,module,exports){"use strict";function Hmac(hash,key,enc){return this instanceof Hmac?void(this.Hash=hash,this.blockSize=hash.blockSize/8,this.outSize=hash.outSize/8,this.inner=null,this.outer=null,this._init(utils.toArray(key,enc))):new Hmac(hash,key,enc)}var utils=require("./utils"),assert=require("minimalistic-assert");module.exports=Hmac,Hmac.prototype._init=function init(key){key.length>this.blockSize&&(key=new this.Hash().update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i<this.blockSize;i++)key.push(0);for(i=0;i<key.length;i++)key[i]^=54;for(this.inner=new this.Hash().update(key),i=0;i<key.length;i++)key[i]^=106;this.outer=new this.Hash().update(key)},Hmac.prototype.update=function update(msg,enc){return this.inner.update(msg,enc),this},Hmac.prototype.digest=function digest(enc){return this.outer.update(this.inner.digest()),this.outer.digest(enc)}},{"./utils":183,"minimalistic-assert":219}],175:[function(require,module,exports){"use strict";function RIPEMD160(){return this instanceof RIPEMD160?void(BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"):new RIPEMD160}function f(j,x,y,z){return 15>=j?x^y^z:31>=j?x&y|~x&z:47>=j?(x|~y)^z:63>=j?x&z|y&~z:x^(y|~z)}function K(j){return 15>=j?0:31>=j?1518500249:47>=j?1859775393:63>=j?2400959708:2840853838}function Kh(j){return 15>=j?1352829926:31>=j?1548603684:47>=j?1836072691:63>=j?2053994217:0}var utils=require("./utils"),common=require("./common"),rotl32=utils.rotl32,sum32=utils.sum32,sum32_3=utils.sum32_3,sum32_4=utils.sum32_4,BlockHash=common.BlockHash;utils.inherits(RIPEMD160,BlockHash),exports.ripemd160=RIPEMD160,RIPEMD160.blockSize=512,RIPEMD160.outSize=160,RIPEMD160.hmacStrength=192,RIPEMD160.padLength=64,RIPEMD160.prototype._update=function update(msg,start){for(var A=this.h[0],B=this.h[1],C=this.h[2],D=this.h[3],E=this.h[4],Ah=A,Bh=B,Ch=C,Dh=D,Eh=E,j=0,T;80>j;j++)T=sum32(rotl32(sum32_4(A,f(j,B,C,D),msg[r[j]+start],K(j)),s[j]),E),A=E,E=D,D=rotl32(C,10),C=B,B=T,T=sum32(rotl32(sum32_4(Ah,f(79-j,Bh,Ch,Dh),msg[rh[j]+start],Kh(j)),sh[j]),Eh),Ah=Eh,Eh=Dh,Dh=rotl32(Ch,10),Ch=Bh,Bh=T;T=sum32_3(this.h[1],C,Dh),this.h[1]=sum32_3(this.h[2],D,Eh),this.h[2]=sum32_3(this.h[3],E,Ah),this.h[3]=sum32_3(this.h[4],A,Bh),this.h[4]=sum32_3(this.h[0],B,Ch),this.h[0]=T},RIPEMD160.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"little"):utils.split32(this.h,"little")};var r=[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],rh=[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],s=[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],sh=[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]},{"./common":173,"./utils":183}],176:[function(require,module,exports){"use strict";exports.sha1=require("./sha/1"),exports.sha224=require("./sha/224"),exports.sha256=require("./sha/256"),exports.sha384=require("./sha/384"),exports.sha512=require("./sha/512")},{"./sha/1":177,"./sha/224":178,"./sha/256":179,"./sha/384":180,"./sha/512":181}],177:[function(require,module,exports){"use strict";function SHA1(){return this instanceof SHA1?void(BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)):new SHA1}var utils=require("../utils"),common=require("../common"),shaCommon=require("./common"),rotl32=utils.rotl32,sum32=utils.sum32,sum32_5=utils.sum32_5,ft_1=shaCommon.ft_1,BlockHash=common.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];utils.inherits(SHA1,BlockHash),module.exports=SHA1,SHA1.blockSize=512,SHA1.outSize=160,SHA1.hmacStrength=80,SHA1.padLength=64,SHA1.prototype._update=function _update(msg,start){for(var W=this.W,i=0;16>i;i++)W[i]=msg[start+i];for(;i<W.length;i++)W[i]=rotl32(W[i-3]^W[i-8]^W[i-14]^W[i-16],1);var a=this.h[0],b=this.h[1],c=this.h[2],d=this.h[3],e=this.h[4];for(i=0;i<W.length;i++){var s=~~(i/20),t=sum32_5(rotl32(a,5),ft_1(s,b,c,d),e,W[i],sha1_K[s]);e=d,d=c,c=rotl32(b,30),b=a,a=t}this.h[0]=sum32(this.h[0],a),this.h[1]=sum32(this.h[1],b),this.h[2]=sum32(this.h[2],c),this.h[3]=sum32(this.h[3],d),this.h[4]=sum32(this.h[4],e)},SHA1.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"big"):utils.split32(this.h,"big")}},{"../common":173,"../utils":183,"./common":182}],178:[function(require,module,exports){"use strict";function SHA224(){return this instanceof SHA224?void(SHA256.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]):new SHA224}var utils=require("../utils"),SHA256=require("./256");utils.inherits(SHA224,SHA256),module.exports=SHA224,SHA224.blockSize=512,SHA224.outSize=224,SHA224.hmacStrength=192,SHA224.padLength=64,SHA224.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h.slice(0,7),"big"):utils.split32(this.h.slice(0,7),"big")}},{"../utils":183,"./256":179}],179:[function(require,module,exports){"use strict";function SHA256(){return this instanceof SHA256?void(BlockHash.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=sha256_K,this.W=Array(64)):new SHA256}var utils=require("../utils"),common=require("../common"),shaCommon=require("./common"),assert=require("minimalistic-assert"),sum32=utils.sum32,sum32_4=utils.sum32_4,sum32_5=utils.sum32_5,ch32=shaCommon.ch32,maj32=shaCommon.maj32,s0_256=shaCommon.s0_256,s1_256=shaCommon.s1_256,g0_256=shaCommon.g0_256,g1_256=shaCommon.g1_256,BlockHash=common.BlockHash,sha256_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];utils.inherits(SHA256,BlockHash),module.exports=SHA256,SHA256.blockSize=512,SHA256.outSize=256,SHA256.hmacStrength=192,SHA256.padLength=64,SHA256.prototype._update=function _update(msg,start){for(var W=this.W,i=0;16>i;i++)W[i]=msg[start+i];for(;i<W.length;i++)W[i]=sum32_4(g1_256(W[i-2]),W[i-7],g0_256(W[i-15]),W[i-16]);var a=this.h[0],b=this.h[1],c=this.h[2],d=this.h[3],e=this.h[4],f=this.h[5],g=this.h[6],h=this.h[7];for(assert(this.k.length===W.length),i=0;i<W.length;i++){var T1=sum32_5(h,s1_256(e),ch32(e,f,g),this.k[i],W[i]),T2=sum32(s0_256(a),maj32(a,b,c));h=g,g=f,f=e,e=sum32(d,T1),d=c,c=b,b=a,a=sum32(T1,T2)}this.h[0]=sum32(this.h[0],a),this.h[1]=sum32(this.h[1],b),this.h[2]=sum32(this.h[2],c),this.h[3]=sum32(this.h[3],d),this.h[4]=sum32(this.h[4],e),this.h[5]=sum32(this.h[5],f),this.h[6]=sum32(this.h[6],g),this.h[7]=sum32(this.h[7],h)},SHA256.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"big"):utils.split32(this.h,"big")}},{"../common":173,"../utils":183,"./common":182,"minimalistic-assert":219}],180:[function(require,module,exports){"use strict";function SHA384(){return this instanceof SHA384?void(SHA512.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]):new SHA384}var utils=require("../utils"),SHA512=require("./512");utils.inherits(SHA384,SHA512),module.exports=SHA384,SHA384.blockSize=1024,SHA384.outSize=384,SHA384.hmacStrength=192,SHA384.padLength=128,SHA384.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h.slice(0,12),"big"):utils.split32(this.h.slice(0,12),"big")}},{"../utils":183,"./512":181}],181:[function(require,module,exports){"use strict";function SHA512(){return this instanceof SHA512?void(BlockHash.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=sha512_K,this.W=Array(160)):new SHA512}function ch64_hi(xh,xl,yh,yl,zh){var r=xh&yh^~xh&zh;return 0>r&&(r+=4294967296),r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;return 0>r&&(r+=4294967296),r}function maj64_hi(xh,xl,yh,yl,zh){var r=xh&yh^xh&zh^yh&zh;return 0>r&&(r+=4294967296),r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;return 0>r&&(r+=4294967296),r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28),c1_hi=rotr64_hi(xl,xh,2),c2_hi=rotr64_hi(xl,xh,7),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28),c1_lo=rotr64_lo(xl,xh,2),c2_lo=rotr64_lo(xl,xh,7),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14),c1_hi=rotr64_hi(xh,xl,18),c2_hi=rotr64_hi(xl,xh,9),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14),c1_lo=rotr64_lo(xh,xl,18),c2_lo=rotr64_lo(xl,xh,9),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1),c1_hi=rotr64_hi(xh,xl,8),c2_hi=shr64_hi(xh,xl,7),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1),c1_lo=rotr64_lo(xh,xl,8),c2_lo=shr64_lo(xh,xl,7),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19),c1_hi=rotr64_hi(xl,xh,29),c2_hi=shr64_hi(xh,xl,6),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19),c1_lo=rotr64_lo(xl,xh,29),c2_lo=shr64_lo(xh,xl,6),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}var utils=require("../utils"),common=require("../common"),assert=require("minimalistic-assert"),rotr64_hi=utils.rotr64_hi,rotr64_lo=utils.rotr64_lo,shr64_hi=utils.shr64_hi,shr64_lo=utils.shr64_lo,sum64=utils.sum64,sum64_hi=utils.sum64_hi,sum64_lo=utils.sum64_lo,sum64_4_hi=utils.sum64_4_hi,sum64_4_lo=utils.sum64_4_lo,sum64_5_hi=utils.sum64_5_hi,sum64_5_lo=utils.sum64_5_lo,BlockHash=common.BlockHash,sha512_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];utils.inherits(SHA512,BlockHash),module.exports=SHA512,SHA512.blockSize=1024,SHA512.outSize=512,SHA512.hmacStrength=192,SHA512.padLength=128,SHA512.prototype._prepareBlock=function _prepareBlock(msg,start){for(var W=this.W,i=0;32>i;i++)W[i]=msg[start+i];for(;i<W.length;i+=2){var c0_hi=g1_512_hi(W[i-4],W[i-3]),c0_lo=g1_512_lo(W[i-4],W[i-3]),c1_hi=W[i-14],c1_lo=W[i-13],c2_hi=g0_512_hi(W[i-30],W[i-29]),c2_lo=g0_512_lo(W[i-30],W[i-29]),c3_hi=W[i-32],c3_lo=W[i-31];W[i]=sum64_4_hi(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo),W[i+1]=sum64_4_lo(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo)}},SHA512.prototype._update=function _update(msg,start){this._prepareBlock(msg,start);var W=this.W,ah=this.h[0],al=this.h[1],bh=this.h[2],bl=this.h[3],ch=this.h[4],cl=this.h[5],dh=this.h[6],dl=this.h[7],eh=this.h[8],el=this.h[9],fh=this.h[10],fl=this.h[11],gh=this.h[12],gl=this.h[13],hh=this.h[14],hl=this.h[15];assert(this.k.length===W.length);for(var i=0;i<W.length;i+=2){var c0_hi=hh,c0_lo=hl,c1_hi=s1_512_hi(eh,el),c1_lo=s1_512_lo(eh,el),c2_hi=ch64_hi(eh,el,fh,fl,gh,gl),c2_lo=ch64_lo(eh,el,fh,fl,gh,gl),c3_hi=this.k[i],c3_lo=this.k[i+1],c4_hi=W[i],c4_lo=W[i+1],T1_hi=sum64_5_hi(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo,c4_hi,c4_lo),T1_lo=sum64_5_lo(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo,c4_hi,c4_lo);c0_hi=s0_512_hi(ah,al),c0_lo=s0_512_lo(ah,al),c1_hi=maj64_hi(ah,al,bh,bl,ch,cl),c1_lo=maj64_lo(ah,al,bh,bl,ch,cl);var T2_hi=sum64_hi(c0_hi,c0_lo,c1_hi,c1_lo),T2_lo=sum64_lo(c0_hi,c0_lo,c1_hi,c1_lo);hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,eh=sum64_hi(dh,dl,T1_hi,T1_lo),el=sum64_lo(dl,dl,T1_hi,T1_lo),dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,ah=sum64_hi(T1_hi,T1_lo,T2_hi,T2_lo),al=sum64_lo(T1_hi,T1_lo,T2_hi,T2_lo)}sum64(this.h,0,ah,al),sum64(this.h,2,bh,bl),sum64(this.h,4,ch,cl),sum64(this.h,6,dh,dl),sum64(this.h,8,eh,el),sum64(this.h,10,fh,fl),sum64(this.h,12,gh,gl),sum64(this.h,14,hh,hl)},SHA512.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"big"):utils.split32(this.h,"big")}},{"../common":173,"../utils":183,"minimalistic-assert":219}],182:[function(require,module,exports){"use strict";function ft_1(s,x,y,z){return 0===s?ch32(x,y,z):1===s||3===s?p32(x,y,z):2===s?maj32(x,y,z):void 0}function ch32(x,y,z){return x&y^~x&z}function maj32(x,y,z){return x&y^x&z^y&z}function p32(x,y,z){return x^y^z}function s0_256(x){return rotr32(x,2)^rotr32(x,13)^rotr32(x,22)}function s1_256(x){return rotr32(x,6)^rotr32(x,11)^rotr32(x,25)}function g0_256(x){return rotr32(x,7)^rotr32(x,18)^x>>>3}function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}var utils=require("../utils"),rotr32=utils.rotr32;exports.ft_1=ft_1,exports.ch32=ch32,exports.maj32=maj32,exports.p32=p32,exports.s0_256=s0_256,exports.s1_256=s1_256,exports.g0_256=g0_256,exports.g1_256=g1_256},{"../utils":183}],183:[function(require,module,exports){"use strict";function isSurrogatePair(msg,i){return!(55296!=(64512&msg.charCodeAt(i)))&&!(0>i||i+1>=msg.length)&&56320==(64512&msg.charCodeAt(i+1))}function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(!("string"==typeof msg))for(i=0;i<msg.length;i++)res[i]=0|msg[i];else if(!enc)for(var p=0,i=0,c;i<msg.length;i++)c=msg.charCodeAt(i),128>c?res[p++]=c:2048>c?(res[p++]=192|c>>6,res[p++]=128|63&c):isSurrogatePair(msg,i)?(c=65536+((1023&c)<<10)+(1023&msg.charCodeAt(++i)),res[p++]=240|c>>18,res[p++]=128|63&c>>12,res[p++]=128|63&c>>6,res[p++]=128|63&c):(res[p++]=224|c>>12,res[p++]=128|63&c>>6,res[p++]=128|63&c);else if("hex"===enc)for(msg=msg.replace(/[^a-z0-9]+/ig,""),0!=msg.length%2&&(msg="0"+msg),i=0;i<msg.length;i+=2)res.push(parseInt(msg[i]+msg[i+1],16));return res}function toHex(msg){for(var res="",i=0;i<msg.length;i++)res+=zero2(msg[i].toString(16));return res}function htonl(w){var res=w>>>24|65280&w>>>8|16711680&w<<8|(255&w)<<24;return res>>>0}function toHex32(msg,endian){for(var res="",i=0,w;i<msg.length;i++)w=msg[i],"little"===endian&&(w=htonl(w)),res+=zero8(w.toString(16));return res}function zero2(word){return 1===word.length?"0"+word:word}function zero8(word){return 7===word.length?"0"+word:6===word.length?"00"+word:5===word.length?"000"+word:4===word.length?"0000"+word:3===word.length?"00000"+word:2===word.length?"000000"+word:1===word.length?"0000000"+word:word}function join32(msg,start,end,endian){var len=end-start;assert(0==len%4);for(var res=Array(len/4),i=0,k=start;i<res.length;i++,k+=4){var w;w="big"===endian?msg[k]<<24|msg[k+1]<<16|msg[k+2]<<8|msg[k+3]:msg[k+3]<<24|msg[k+2]<<16|msg[k+1]<<8|msg[k],res[i]=w>>>0}return res}function split32(msg,endian){for(var res=Array(4*msg.length),i=0,k=0,m;i<msg.length;i++,k+=4)m=msg[i],"big"===endian?(res[k]=m>>>24,res[k+1]=255&m>>>16,res[k+2]=255&m>>>8,res[k+3]=255&m):(res[k+3]=m>>>24,res[k+2]=255&m>>>16,res[k+1]=255&m>>>8,res[k]=255&m);return res}function rotr32(w,b){return w>>>b|w<<32-b}function rotl32(w,b){return w<<b|w>>>32-b}function sum32(a,b){return a+b>>>0}function sum32_3(a,b,c){return a+b+c>>>0}function sum32_4(a,b,c,d){return a+b+c+d>>>0}function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo<al?1:0)+ah+bh;buf[pos]=hi>>>0,buf[pos+1]=lo}function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo<al?1:0)+ah+bh;return hi>>>0}function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo<al?1:0,lo=lo+cl>>>0,carry+=lo<cl?1:0,lo=lo+dl>>>0,carry+=lo<dl?1:0;var hi=ah+bh+ch+dh+carry;return hi>>>0}function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo<al?1:0,lo=lo+cl>>>0,carry+=lo<cl?1:0,lo=lo+dl>>>0,carry+=lo<dl?1:0,lo=lo+el>>>0,carry+=lo<el?1:0;var hi=ah+bh+ch+dh+eh+carry;return hi>>>0}function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}function shr64_hi(ah,al,num){return ah>>>num}function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}var assert=require("minimalistic-assert"),inherits=require("inherits");exports.inherits=inherits,exports.toArray=toArray,exports.toHex=toHex,exports.htonl=htonl,exports.toHex32=toHex32,exports.zero2=zero2,exports.zero8=zero8,exports.join32=join32,exports.split32=split32,exports.rotr32=rotr32,exports.rotl32=rotl32,exports.sum32=sum32,exports.sum32_3=sum32_3,exports.sum32_4=sum32_4,exports.sum32_5=sum32_5,exports.sum64=sum64,exports.sum64_hi=sum64_hi,exports.sum64_lo=sum64_lo,exports.sum64_4_hi=sum64_4_hi,exports.sum64_4_lo=sum64_4_lo,exports.sum64_5_hi=sum64_5_hi,exports.sum64_5_lo=sum64_5_lo,exports.rotr64_hi=rotr64_hi,exports.rotr64_lo=rotr64_lo,exports.shr64_hi=shr64_hi,exports.shr64_lo=shr64_lo},{inherits:189,"minimalistic-assert":219}],184:[function(require,module,exports){"use strict";function HmacDRBG(options){if(!(this instanceof HmacDRBG))return new HmacDRBG(options);this.hash=options.hash,this.predResist=!!options.predResist,this.outLen=this.hash.outSize,this.minEntropy=options.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var entropy=utils.toArray(options.entropy,options.entropyEnc||"hex"),nonce=utils.toArray(options.nonce,options.nonceEnc||"hex"),pers=utils.toArray(options.pers,options.persEnc||"hex");assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(entropy,nonce,pers)}var hash=require("hash.js"),utils=require("minimalistic-crypto-utils"),assert=require("minimalistic-assert");module.exports=HmacDRBG,HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var i=0;i<this.V.length;i++)this.K[i]=0,this.V[i]=1;this._update(seed),this._reseed=1,this.reseedInterval=281474976710656},HmacDRBG.prototype._hmac=function hmac(){return new hash.hmac(this.hash,this.K)},HmacDRBG.prototype._update=function update(seed){var kmac=this._hmac().update(this.V).update([0]);seed&&(kmac=kmac.update(seed)),this.K=kmac.digest(),this.V=this._hmac().update(this.V).digest();seed&&(this.K=this._hmac().update(this.V).update([1]).update(seed).digest(),this.V=this._hmac().update(this.V).digest())},HmacDRBG.prototype.reseed=function reseed(entropy,entropyEnc,add,addEnc){"string"!=typeof entropyEnc&&(addEnc=add,add=entropyEnc,entropyEnc=null),entropy=utils.toArray(entropy,entropyEnc),add=utils.toArray(add,addEnc),assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof enc&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc||"hex"),this._update(add));for(var temp=[];temp.length<len;)this.V=this._hmac().update(this.V).digest(),temp=temp.concat(this.V);var res=temp.slice(0,len);return this._update(add),this._reseed++,utils.encode(res,enc)}},{"hash.js":172,"minimalistic-assert":219,"minimalistic-crypto-utils":220}],185:[function(require,module,exports){function HTTPParser(type){assert.ok(type===HTTPParser.REQUEST||type===HTTPParser.RESPONSE),this.type=type,this.state=type+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1}function parseErrorCode(code){var err=new Error("Parse Error");return err.code=code,err}var assert=require("assert");exports.HTTPParser=HTTPParser,HTTPParser.encoding="ascii",HTTPParser.maxHeaderSize=81920,HTTPParser.REQUEST="REQUEST",HTTPParser.RESPONSE="RESPONSE";var kOnHeaders=HTTPParser.kOnHeaders=0,kOnHeadersComplete=HTTPParser.kOnHeadersComplete=1,kOnBody=HTTPParser.kOnBody=2,kOnMessageComplete=HTTPParser.kOnMessageComplete=3;HTTPParser.prototype[kOnHeaders]=HTTPParser.prototype[kOnHeadersComplete]=HTTPParser.prototype[kOnBody]=HTTPParser.prototype[kOnMessageComplete]=function(){};var compatMode0_12=!0;Object.defineProperty(HTTPParser,"kOnExecute",{get:function(){return compatMode0_12=!1,4}});var methods=exports.methods=HTTPParser.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK"],method_connect=methods.indexOf("CONNECT");HTTPParser.prototype.reinitialize=HTTPParser,HTTPParser.prototype.close=HTTPParser.prototype.pause=HTTPParser.prototype.resume=HTTPParser.prototype.free=function(){},HTTPParser.prototype._compatMode0_11=!1,HTTPParser.prototype.getAsyncId=function(){return 0};var headerState={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};HTTPParser.prototype.execute=function(chunk,start,length){if(!(this instanceof HTTPParser))throw new TypeError("not a HTTPParser");start=start||0,length="number"==typeof length?length:chunk.length,this.chunk=chunk,this.offset=start;var end=this.end=start+length;try{for(;this.offset<end&&!this[this.state](););}catch(err){if(this.isUserCall)throw err;return this.hadError=!0,err}return this.chunk=null,length=this.offset-start,headerState[this.state]&&(this.headerSize+=length,this.headerSize>HTTPParser.maxHeaderSize)?new Error("max header size exceeded"):length};var stateFinishAllowed={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};HTTPParser.prototype.finish=function(){return this.hadError?void 0:stateFinishAllowed[this.state]?void("BODY_RAW"===this.state&&this.userCall()(this[kOnMessageComplete]())):new Error("invalid state for EOF")},HTTPParser.prototype.consume=HTTPParser.prototype.unconsume=HTTPParser.prototype.getCurrentBuffer=function(){},HTTPParser.prototype.userCall=function(){this.isUserCall=!0;var self=this;return function(ret){return self.isUserCall=!1,ret}},HTTPParser.prototype.nextRequest=function(){this.userCall()(this[kOnMessageComplete]()),this.reinitialize(this.type)},HTTPParser.prototype.consumeLine=function(){for(var end=this.end,chunk=this.chunk,i=this.offset;i<end;i++)if(10===chunk[i]){var line=this.line+chunk.toString(HTTPParser.encoding,this.offset,i);return"\r"===line.charAt(line.length-1)&&(line=line.substr(0,line.length-1)),this.line="",this.offset=i+1,line}this.line+=chunk.toString(HTTPParser.encoding,this.offset,this.end),this.offset=this.end};var headerExp=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,headerContinueExp=/^[ \t]+(.*[^ \t])/;HTTPParser.prototype.parseHeader=function(line,headers){if(-1!==line.indexOf("\r"))throw parseErrorCode("HPE_LF_EXPECTED");var match=headerExp.exec(line),k=match&&match[1];if(k)headers.push(k),headers.push(match[2]);else{var matchContinue=headerContinueExp.exec(line);matchContinue&&headers.length&&(headers[headers.length-1]&&(headers[headers.length-1]+=" "),headers[headers.length-1]+=matchContinue[1])}};var requestExp=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;HTTPParser.prototype.REQUEST_LINE=function(){var line=this.consumeLine();if(line){var match=requestExp.exec(line);if(null===match)throw parseErrorCode("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?match[1]:methods.indexOf(match[1]),-1===this.info.method)throw new Error("invalid request method");this.info.url=match[2],this.info.versionMajor=+match[3],this.info.versionMinor=+match[4],this.body_bytes=0,this.state="HEADER"}};var responseExp=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;HTTPParser.prototype.RESPONSE_LINE=function(){var line=this.consumeLine();if(line){var match=responseExp.exec(line);if(null===match)throw parseErrorCode("HPE_INVALID_CONSTANT");this.info.versionMajor=+match[1],this.info.versionMinor=+match[2];var statusCode=this.info.statusCode=+match[3];this.info.statusMessage=match[4],(1==(0|statusCode/100)||204===statusCode||304===statusCode)&&(this.body_bytes=0),this.state="HEADER"}},HTTPParser.prototype.shouldKeepAlive=function(){if(0<this.info.versionMajor&&0<this.info.versionMinor){if(-1!==this.connection.indexOf("close"))return!1;}else if(-1===this.connection.indexOf("keep-alive"))return!1;return!!(null!==this.body_bytes||this.isChunked)},HTTPParser.prototype.HEADER=function(){var line=this.consumeLine();if(void 0!==line){var info=this.info;if(line)this.parseHeader(line,info.headers);else{for(var headers=info.headers,hasContentLength=!1,hasUpgradeHeader=!1,i=0,currentContentLengthValue;i<headers.length;i+=2)switch(headers[i].toLowerCase()){case"transfer-encoding":this.isChunked="chunked"===headers[i+1].toLowerCase();break;case"content-length":if(currentContentLengthValue=+headers[i+1],!hasContentLength)hasContentLength=!0,this.body_bytes=currentContentLengthValue;else if(currentContentLengthValue!==this.body_bytes)throw parseErrorCode("HPE_UNEXPECTED_CONTENT_LENGTH");break;case"connection":this.connection+=headers[i+1].toLowerCase();break;case"upgrade":hasUpgradeHeader=!0;}this.isChunked&&hasContentLength&&(this.isChunked=!1),info.upgrade=hasUpgradeHeader&&-1!=this.connection.indexOf("upgrade")?this.type===HTTPParser.REQUEST||101===info.statusCode:info.method===method_connect,info.shouldKeepAlive=this.shouldKeepAlive();var skipBody;if(skipBody=compatMode0_12?this.userCall()(this[kOnHeadersComplete](info)):this.userCall()(this[kOnHeadersComplete](info.versionMajor,info.versionMinor,info.headers,info.method,info.url,info.statusCode,info.statusMessage,info.upgrade,info.shouldKeepAlive)),2===skipBody)return this.nextRequest(),!0;if(this.isChunked&&!skipBody)this.state="BODY_CHUNKHEAD";else{if(skipBody||0===this.body_bytes)return this.nextRequest(),info.upgrade;this.state=null===this.body_bytes?"BODY_RAW":"BODY_SIZED"}}}},HTTPParser.prototype.BODY_CHUNKHEAD=function(){var line=this.consumeLine();void 0===line||(this.body_bytes=parseInt(line,16),this.state=this.body_bytes?"BODY_CHUNK":"BODY_CHUNKTRAILERS")},HTTPParser.prototype.BODY_CHUNK=function(){var length=_Mathmin(this.end-this.offset,this.body_bytes);this.userCall()(this[kOnBody](this.chunk,this.offset,length)),this.offset+=length,this.body_bytes-=length,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")},HTTPParser.prototype.BODY_CHUNKEMPTYLINE=function(){var line=this.consumeLine();void 0===line||(assert.equal(line,""),this.state="BODY_CHUNKHEAD")},HTTPParser.prototype.BODY_CHUNKTRAILERS=function(){var line=this.consumeLine();void 0===line||(line?this.parseHeader(line,this.trailers):(this.trailers.length&&this.userCall()(this[kOnHeaders](this.trailers,"")),this.nextRequest()))},HTTPParser.prototype.BODY_RAW=function(){var length=this.end-this.offset;this.userCall()(this[kOnBody](this.chunk,this.offset,length)),this.offset=this.end},HTTPParser.prototype.BODY_SIZED=function(){var length=_Mathmin(this.end-this.offset,this.body_bytes);this.userCall()(this[kOnBody](this.chunk,this.offset,length)),this.offset+=length,this.body_bytes-=length,this.body_bytes||this.nextRequest()},["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(name){var k=HTTPParser["kOn"+name];Object.defineProperty(HTTPParser.prototype,"on"+name,{get:function(){return this[k]},set:function(to){return this._compatMode0_11=!0,method_connect="CONNECT",this[k]=to}})})},{assert:32}],186:[function(require,module,exports){function validateParams(params){if("string"==typeof params&&(params=url.parse(params)),params.protocol||(params.protocol="https:"),"https:"!==params.protocol)throw new Error("Protocol \""+params.protocol+"\" not supported. Expected \"https:\"");return params}var http=require("http"),url=require("url"),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);https.request=function(params,cb){return params=validateParams(params),http.request.call(this,params,cb)},https.get=function(params,cb){return params=validateParams(params),http.get.call(this,params,cb)}},{http:312,url:332}],187:[function(require,module,exports){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0<nBits;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;0<nBits;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=_Mathpow(2,mLen),e-=eBias}return(s?-1:1)*m*_Mathpow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog2(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<<mLen|m,eLen+=mLen;0<eLen;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],188:[function(require,module,exports){/*! immediate-chunk-store. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const queueMicrotask=require("queue-microtask");class ImmediateStore{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb=()=>{}){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb(err)})}get(index,opts,cb=()=>{}){if("function"==typeof opts)return this.get(index,null,opts);let buf=this.mem[index];if(!buf)return this.store.get(index,opts,cb);opts||(opts={});const offset=opts.offset||0,len=opts.length||buf.length-offset;(0!==offset||len!==buf.length)&&(buf=buf.slice(offset,len+offset)),queueMicrotask(()=>cb(null,buf))}close(cb=()=>{}){this.store.close(cb)}destroy(cb=()=>{}){this.store.destroy(cb)}}module.exports=ImmediateStore},{"queue-microtask":259}],189:[function(require,module,exports){module.exports="function"==typeof Object.create?function inherits(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],190:[function(require,module,exports){(function(root){"use strict";function expandIPv6(string,parts){if(string.indexOf("::")!==string.lastIndexOf("::"))return null;let colonCount=0,lastColon=-1,zoneId=(string.match(ipv6Regexes.zoneIndex)||[])[0],replacement,replacementCount;for(zoneId&&(zoneId=zoneId.substring(1),string=string.replace(/%.+$/,""));0<=(lastColon=string.indexOf(":",lastColon+1));)colonCount++;if("::"===string.substr(0,2)&&colonCount--,"::"===string.substr(-2,2)&&colonCount--,colonCount>parts)return null;for(replacementCount=parts-colonCount,replacement=":";replacementCount--;)replacement+="0:";return string=string.replace("::",replacement),":"===string[0]&&(string=string.slice(1)),":"===string[string.length-1]&&(string=string.slice(0,-1)),parts=function(){const ref=string.split(":"),results=[];for(let i=0;i<ref.length;i++)results.push(parseInt(ref[i],16));return results}(),{parts:parts,zoneId:zoneId}}function matchCIDR(first,second,partSize,cidrBits){if(first.length!==second.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let part=0,shift;for(;0<cidrBits;){if(shift=partSize-cidrBits,0>shift&&(shift=0),first[part]>>shift!=second[part]>>shift)return!1;cidrBits-=partSize,part+=1}return!0}function parseIntAuto(string){if(hexRegex.test(string))return parseInt(string,16);if("0"===string[0]&&!isNaN(parseInt(string[1],10))){if(octalRegex.test(string))return parseInt(string,8);throw new Error(`ipaddr: cannot parse ${string} as octal`)}return parseInt(string,10)}function padPart(part,length){for(;part.length<length;)part=`0${part}`;return part}const ipv4Part="(0?\\d+|0x[a-f0-9]+)",ipv4Regexes={fourOctet:/^(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)$/i,threeOctet:/^(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)$/i,twoOctet:/^(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)$/i,longValue:/^(0?\d+|0x[a-f0-9]+)$/i},octalRegex=/^0[0-7]+$/i,hexRegex=/^0x[a-f0-9]+$/i,zoneIndex="%[0-9a-z]{1,}",ipv6Part="(?:[0-9a-f]+::?)+",ipv6Regexes={zoneIndex:new RegExp(zoneIndex,"i"),native:new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}(${zoneIndex})?)$`,"i"),transitional:new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}(${zoneIndex})?$`,"i")},ipaddr={};ipaddr.IPv4=function(){function IPv4(octets){if(4!==octets.length)throw new Error("ipaddr: ipv4 octet count should be 4");let i,octet;for(i=0;i<octets.length;i++)if(octet=octets[i],!(0<=octet&&255>=octet))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=octets}return IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]]},IPv4.prototype.kind=function(){return"ipv4"},IPv4.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv4"!==other.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return matchCIDR(this.octets,other.octets,8,cidrRange)},IPv4.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0};let i,octet,zeros;for(i=3;0<=i;i-=1)if(octet=this.octets[i],octet in zerotable){if(zeros=zerotable[octet],stop&&0!==zeros)return null;8!==zeros&&(stop=!0),cidr+=zeros}else return null;return 32-cidr},IPv4.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.toIPv4MappedAddress=function(){return ipaddr.IPv6.parse(`::ffff:${this.toString()}`)},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toString=function(){return this.octets.join(".")},IPv4}(),ipaddr.IPv4.broadcastAddressFromCIDR=function(string){try{const cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[];for(let i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.isIPv4=function(string){return null!==this.parser(string)},ipaddr.IPv4.isValid=function(string){try{return new this(this.parser(string)),!0}catch(e){return!1}},ipaddr.IPv4.isValidFourPartDecimal=function(string){return!!(ipaddr.IPv4.isValid(string)&&string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},ipaddr.IPv4.networkAddressFromCIDR=function(string){let cidr,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.parse=function(string){const parts=this.parser(string);if(null===parts)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(parts)},ipaddr.IPv4.parseCIDR=function(string){let match;if(match=string.match(/^(.+)\/(\d+)$/)){const maskLength=parseInt(match[2]);if(0<=maskLength&&32>=maskLength){const parsed=[this.parse(match[1]),maskLength];return Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},ipaddr.IPv4.parser=function(string){let match,part,value;if(match=string.match(ipv4Regexes.fourOctet))return function(){const ref=match.slice(1,6),results=[];for(let i=0;i<ref.length;i++)part=ref[i],results.push(parseIntAuto(part));return results}();if(match=string.match(ipv4Regexes.longValue)){if(value=parseIntAuto(match[1]),4294967295<value||0>value)throw new Error("ipaddr: address outside defined range");return function(){const results=[];let shift;for(shift=0;24>=shift;shift+=8)results.push(255&value>>shift);return results}().reverse()}return(match=string.match(ipv4Regexes.twoOctet))?function(){const ref=match.slice(1,4),results=[];if(value=parseIntAuto(ref[1]),16777215<value||0>value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(255&value>>16),results.push(255&value>>8),results.push(255&value),results}():(match=string.match(ipv4Regexes.threeOctet))?function(){const ref=match.slice(1,5),results=[];if(value=parseIntAuto(ref[2]),65535<value||0>value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(parseIntAuto(ref[1])),results.push(255&value>>8),results.push(255&value),results}():null},ipaddr.IPv4.subnetMaskFromPrefixLength=function(prefix){if(prefix=parseInt(prefix),0>prefix||32<prefix)throw new Error("ipaddr: invalid IPv4 prefix length");const octets=[0,0,0,0];let j=0;const filledOctetCount=_Mathfloor(prefix/8);for(;j<filledOctetCount;)octets[j]=255,j++;return 4>filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.IPv6=function(){function IPv6(parts,zoneId){let i,part;if(16===parts.length)for(this.parts=[],i=0;14>=i;i+=2)this.parts.push(parts[i]<<8|parts[i+1]);else if(8===parts.length)this.parts=parts;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(i=0;i<this.parts.length;i++)if(part=this.parts[i],!(0<=part&&65535>=part))throw new Error("ipaddr: ipv6 part should fit in 16 bits");zoneId&&(this.zoneId=zoneId)}return IPv6.prototype.SpecialRanges={unspecified:[new IPv6([0,0,0,0,0,0,0,0]),128],linkLocal:[new IPv6([65152,0,0,0,0,0,0,0]),10],multicast:[new IPv6([65280,0,0,0,0,0,0,0]),8],loopback:[new IPv6([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new IPv6([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new IPv6([0,0,0,0,0,65535,0,0]),96],rfc6145:[new IPv6([0,0,0,0,65535,0,0,0]),96],rfc6052:[new IPv6([100,65435,0,0,0,0,0,0]),96],"6to4":[new IPv6([8194,0,0,0,0,0,0,0]),16],teredo:[new IPv6([8193,0,0,0,0,0,0,0]),32],reserved:[[new IPv6([8193,3512,0,0,0,0,0,0]),32]]},IPv6.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},IPv6.prototype.kind=function(){return"ipv6"},IPv6.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv6"!==other.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return matchCIDR(this.parts,other.parts,16,cidrRange)},IPv6.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0};let part,zeros;for(let i=7;0<=i;i-=1)if(part=this.parts[i],part in zerotable){if(zeros=zerotable[part],stop&&0!==zeros)return null;16!==zeros&&(stop=!0),cidr+=zeros}else return null;return 128-cidr},IPv6.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv6.prototype.toByteArray=function(){let part;const bytes=[],ref=this.parts;for(let i=0;i<ref.length;i++)part=ref[i],bytes.push(part>>8),bytes.push(255&part);return bytes},IPv6.prototype.toFixedLengthString=function(){const addr=function(){const results=[];for(let i=0;i<this.parts.length;i++)results.push(padPart(this.parts[i].toString(16),4));return results}.call(this).join(":");let suffix="";return this.zoneId&&(suffix=`%${this.zoneId}`),addr+suffix},IPv6.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");const ref=this.parts.slice(-2),high=ref[0],low=ref[1];return new ipaddr.IPv4([high>>8,255&high,low>>8,255&low])},IPv6.prototype.toNormalizedString=function(){const addr=function(){const results=[];for(let i=0;i<this.parts.length;i++)results.push(this.parts[i].toString(16));return results}.call(this).join(":");let suffix="";return this.zoneId&&(suffix=`%${this.zoneId}`),addr+suffix},IPv6.prototype.toRFC5952String=function(){const regex=/((^|:)(0(:|$)){2,})/g,string=this.toNormalizedString();let bestMatchIndex=0,bestMatchLength=-1,match;for(;match=regex.exec(string);)match[0].length>bestMatchLength&&(bestMatchIndex=match.index,bestMatchLength=match[0].length);return 0>bestMatchLength?string:`${string.substring(0,bestMatchIndex)}::${string.substring(bestMatchIndex+bestMatchLength)}`},IPv6.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},IPv6}(),ipaddr.IPv6.broadcastAddressFromCIDR=function(string){try{const cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[];for(let i=0;16>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},ipaddr.IPv6.isIPv6=function(string){return null!==this.parser(string)},ipaddr.IPv6.isValid=function(string){if("string"==typeof string&&-1===string.indexOf(":"))return!1;try{const addr=this.parser(string);return new this(addr.parts,addr.zoneId),!0}catch(e){return!1}},ipaddr.IPv6.networkAddressFromCIDR=function(string){let cidr,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;16>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},ipaddr.IPv6.parse=function(string){const addr=this.parser(string);if(null===addr.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(addr.parts,addr.zoneId)},ipaddr.IPv6.parseCIDR=function(string){let maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&128>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},ipaddr.IPv6.parser=function(string){let addr,i,match,octet,octets,zoneId;if(match=string.match(ipv6Regexes.deprecatedTransitional))return this.parser(`::ffff:${match[1]}`);if(ipv6Regexes.native.test(string))return expandIPv6(string,8);if((match=string.match(ipv6Regexes.transitional))&&(zoneId=match[6]||"",addr=expandIPv6(match[1].slice(0,-1)+zoneId,6),addr.parts)){for(octets=[parseInt(match[2]),parseInt(match[3]),parseInt(match[4]),parseInt(match[5])],i=0;i<octets.length;i++)if(octet=octets[i],!(0<=octet&&255>=octet))return null;return addr.parts.push(octets[0]<<8|octets[1]),addr.parts.push(octets[2]<<8|octets[3]),{parts:addr.parts,zoneId:addr.zoneId}}return null},ipaddr.IPv6.subnetMaskFromPrefixLength=function(prefix){if(prefix=parseInt(prefix),0>prefix||128<prefix)throw new Error("ipaddr: invalid IPv6 prefix length");const octets=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let j=0;const filledOctetCount=_Mathfloor(prefix/8);for(;j<filledOctetCount;)octets[j]=255,j++;return 16>filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.fromByteArray=function(bytes){const length=bytes.length;if(4===length)return new ipaddr.IPv4(bytes);if(16===length)return new ipaddr.IPv6(bytes);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},ipaddr.isValid=function(string){return ipaddr.IPv6.isValid(string)||ipaddr.IPv4.isValid(string)},ipaddr.parse=function(string){if(ipaddr.IPv6.isValid(string))return ipaddr.IPv6.parse(string);if(ipaddr.IPv4.isValid(string))return ipaddr.IPv4.parse(string);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},ipaddr.parseCIDR=function(string){try{return ipaddr.IPv6.parseCIDR(string)}catch(e){try{return ipaddr.IPv4.parseCIDR(string)}catch(e2){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},ipaddr.process=function(string){const addr=this.parse(string);return"ipv6"===addr.kind()&&addr.isIPv4MappedAddress()?addr.toIPv4Address():addr},ipaddr.subnetMatch=function(address,rangeList,defaultName){let i,rangeName,rangeSubnets,subnet;for(rangeName in(void 0===defaultName||null===defaultName)&&(defaultName="unicast"),rangeList)if(Object.prototype.hasOwnProperty.call(rangeList,rangeName))for(rangeSubnets=rangeList[rangeName],rangeSubnets[0]&&!(rangeSubnets[0]instanceof Array)&&(rangeSubnets=[rangeSubnets]),i=0;i<rangeSubnets.length;i++)if(subnet=rangeSubnets[i],address.kind()===subnet[0].kind()&&address.match.apply(address,subnet))return rangeName;return defaultName},"undefined"!=typeof module&&module.exports?module.exports=ipaddr:root.ipaddr=ipaddr})(this)},{}],191:[function(require,module,exports){"use strict";var hasToStringTag=require("has-tostringtag/shams")(),callBound=require("call-bind/callBound"),$toString=callBound("Object.prototype.toString"),isStandardArguments=function isArguments(value){return!(hasToStringTag&&value&&"object"==typeof value&&Symbol.toStringTag in value)&&"[object Arguments]"===$toString(value)},isLegacyArguments=function isArguments(value){return!!isStandardArguments(value)||null!==value&&"object"==typeof value&&"number"==typeof value.length&&0<=value.length&&"[object Array]"!==$toString(value)&&"[object Function]"===$toString(value.callee)},supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments,module.exports=supportsStandardArguments?isStandardArguments:isLegacyArguments},{"call-bind/callBound":104,"has-tostringtag/shams":169}],192:[function(require,module,exports){var MAX_ASCII_CHAR_CODE=127;module.exports=function isAscii(str){for(var i=0,strLen=str.length;i<strLen;++i)if(str.charCodeAt(i)>127)return!1;return!0}},{}],193:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}/*!
+ */"use strict";function escapeHtml(string){var str=""+string,match=matchHtmlRegExp.exec(str);if(!match)return str;var html="",index=0,lastIndex=0,escape;for(index=match.index;index<str.length;index++){switch(str.charCodeAt(index)){case 34:escape="&quot;";break;case 38:escape="&amp;";break;case 39:escape="&#39;";break;case 60:escape="&lt;";break;case 62:escape="&gt;";break;default:continue;}lastIndex!==index&&(html+=str.substring(lastIndex,index)),lastIndex=index+1,html+=escape}return lastIndex===index?html:html+str.substring(lastIndex,index)}var matchHtmlRegExp=/["'&<>]/;module.exports=escapeHtml},{}],156:[function(require,module,exports){"use strict";function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)}function EventEmitter(){EventEmitter.init.call(this)}function checkListener(listener){if("function"!=typeof listener)throw new TypeError("The \"listener\" argument must be of type Function. Received type "+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m,events,existing;if(checkListener(listener),events=target._events,void 0===events?(events=target._events=Object.create(null),target._eventsCount=0):(void 0!==events.newListener&&(target.emit("newListener",type,listener.listener?listener.listener:listener),events=target._events),existing=events[type]),void 0===existing)existing=events[type]=listener,++target._eventsCount;else if("function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener),m=_getMaxListeners(target),0<m&&existing.length>m&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+(type+" listeners added. Use emitter.setMaxListeners() to increase limit"));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,ProcessEmitWarning(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(events===void 0)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount(type){var events=this._events;if(events!==void 0){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n){for(var copy=Array(n),i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){for(var ret=Array(arr.length),i=0;i<ret.length;++i)ret[i]=arr[i].listener||arr[i];return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver),reject(err)}function resolver(){"function"==typeof emitter.removeListener&&emitter.removeListener("error",errorListener),resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:!0}),"error"!==name&&addErrorHandlerIfEventEmitter(emitter,errorListener,{once:!0})})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){"function"==typeof emitter.on&&eventTargetAgnosticAddListener(emitter,"error",handler,flags)}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if("function"==typeof emitter.on)flags.once?emitter.once(name,listener):emitter.on(name,listener);else if("function"==typeof emitter.addEventListener)emitter.addEventListener(name,function wrapListener(arg){flags.once&&emitter.removeEventListener(name,wrapListener),listener(arg)});else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type "+typeof emitter)}var R="object"==typeof Reflect?Reflect:null,ReflectApply=R&&"function"==typeof R.apply?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)},ReflectOwnKeys;ReflectOwnKeys=R&&"function"==typeof R.ownKeys?R.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}:function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)};var NumberIsNaN=_NumberisNaN||function NumberIsNaN(value){return value!==value};module.exports=EventEmitter,module.exports.once=once,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(arg){if("number"!=typeof arg||0>arg||NumberIsNaN(arg))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+arg+".");defaultMaxListeners=arg}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if("number"!=typeof n||0>n||NumberIsNaN(n))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+n+".");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function emit(type){for(var args=[],i=1;i<arguments.length;i++)args.push(arguments[i]);var doError="error"===type,events=this._events;if(events!==void 0)doError=doError&&events.error===void 0;else if(!doError)return!1;if(doError){var er;if(0<args.length&&(er=args[0]),er instanceof Error)throw er;var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));throw err.context=er,err}var handler=events[type];if(handler===void 0)return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)ReflectApply(listeners[i],this,args);return!0},EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,!0)},EventEmitter.prototype.once=function once(type,listener){return checkListener(listener),this.on(type,_onceWrap(this,type,listener)),this},EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){return checkListener(listener),this.prependListener(type,_onceWrap(this,type,listener)),this},EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;if(checkListener(listener),events=this._events,void 0===events)return this;if(list=events[type],void 0===list)return this;if(list===listener||list.listener===listener)0==--this._eventsCount?this._events=Object.create(null):(delete events[type],events.removeListener&&this.emit("removeListener",type,list.listener||listener));else if("function"!=typeof list){for(position=-1,i=list.length-1;0<=i;i--)if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener,position=i;break}if(0>position)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;if(events=this._events,void 0===events)return this;if(void 0===events.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]),this;if(0===arguments.length){var keys=Object.keys(events),key;for(i=0;i<keys.length;++i)key=keys[i],"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(listeners=events[type],"function"==typeof listeners)this.removeListener(type,listeners);else if(void 0!==listeners)for(i=listeners.length-1;0<=i;i--)this.removeListener(type,listeners[i]);return this},EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,!0)},EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,!1)},EventEmitter.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount.call(emitter,type)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return 0<this._eventsCount?ReflectOwnKeys(this._events):[]}},{}],157:[function(require,module,exports){function EVP_BytesToKey(password,salt,keyBits,ivLen){if(Buffer.isBuffer(password)||(password=Buffer.from(password,"binary")),salt&&(Buffer.isBuffer(salt)||(salt=Buffer.from(salt,"binary")),8!==salt.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var keyLen=keyBits/8,key=Buffer.alloc(keyLen),iv=Buffer.alloc(ivLen||0),tmp=Buffer.alloc(0),hash;0<keyLen||0<ivLen;){hash=new MD5,hash.update(tmp),hash.update(password),salt&&hash.update(salt),tmp=hash.digest();var used=0;if(0<keyLen){var keyStart=key.length-keyLen;used=_Mathmin(keyLen,tmp.length),tmp.copy(key,keyStart,0,used),keyLen-=used}if(used<tmp.length&&0<ivLen){var ivStart=iv.length-ivLen,length=_Mathmin(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length),ivLen-=length}}return tmp.fill(0),{key:key,iv:iv}}var Buffer=require("safe-buffer").Buffer,MD5=require("md5.js");module.exports=EVP_BytesToKey},{"md5.js":210,"safe-buffer":290}],158:[function(require,module,exports){module.exports=class FixedFIFO{constructor(hwm){if(!(0<hwm)||0!=(hwm-1&hwm))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(hwm),this.mask=hwm-1,this.top=0,this.btm=0,this.next=null}push(data){return!(void 0!==this.buffer[this.top])&&(this.buffer[this.top]=data,this.top=this.top+1&this.mask,!0)}shift(){const last=this.buffer[this.btm];if(void 0!==last)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,last}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}},{}],159:[function(require,module,exports){const FixedFIFO=require("./fixed-size");module.exports=class FastFIFO{constructor(hwm){this.hwm=hwm||16,this.head=new FixedFIFO(this.hwm),this.tail=this.head}push(val){if(!this.head.push(val)){const prev=this.head;this.head=prev.next=new FixedFIFO(2*this.head.buffer.length),this.head.push(val)}}shift(){const val=this.tail.shift();if(void 0===val&&this.tail.next){const next=this.tail.next;return this.tail.next=null,this.tail=next,this.tail.shift()}return val}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},{"./fixed-size":158}],160:[function(require,module,exports){const{Readable}=require("readable-stream"),toBuffer=require("typedarray-to-buffer");class FileReadStream extends Readable{constructor(file,opts={}){super(opts),this._offset=0,this._ready=!1,this._file=file,this._size=file.size,this._chunkSize=opts.chunkSize||_Mathmax(this._size/1e3,204800);const reader=new FileReader;reader.onload=()=>{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}module.exports=FileReadStream},{"readable-stream":281,"typedarray-to-buffer":329}],161:[function(require,module,exports){"use strict";var isCallable=require("is-callable"),toStr=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,forEachArray=function forEachArray(array,iterator,receiver){for(var i=0,len=array.length;i<len;i++)hasOwnProperty.call(array,i)&&(null==receiver?iterator(array[i],i,array):iterator.call(receiver,array[i],i,array))},forEachString=function forEachString(string,iterator,receiver){for(var i=0,len=string.length;i<len;i++)null==receiver?iterator(string.charAt(i),i,string):iterator.call(receiver,string.charAt(i),i,string)},forEachObject=function forEachObject(object,iterator,receiver){for(var k in object)hasOwnProperty.call(object,k)&&(null==receiver?iterator(object[k],k,object):iterator.call(receiver,object[k],k,object))},forEach=function forEach(list,iterator,thisArg){if(!isCallable(iterator))throw new TypeError("iterator must be a function");var receiver;3<=arguments.length&&(receiver=thisArg),"[object Array]"===toStr.call(list)?forEachArray(list,iterator,receiver):"string"==typeof list?forEachString(list,iterator,receiver):forEachObject(list,iterator,receiver)};module.exports=forEach},{"is-callable":194}],162:[function(require,module,exports){var FreeList=function(){function FreeList(name,max,constructor){this.name=name,this.max=max,this.constructor=null==constructor?function(){}:constructor,this.list=[]}return FreeList.prototype.alloc=function(){return this.list.length?this.list.shift():this.constructor.apply(this,arguments)},FreeList.prototype.free=function(obj){return!!(this.list.length<this.max)&&(this.list.push(obj),!0)},FreeList}();FreeList.FreeList=FreeList,module.exports=FreeList},{}],163:[function(require,module,exports){"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",slice=Array.prototype.slice,toStr=Object.prototype.toString,funcType="[object Function]";module.exports=function bind(that){var target=this;if("function"!=typeof target||toStr.call(target)!==funcType)throw new TypeError("Function.prototype.bind called on incompatible "+target);for(var args=slice.call(arguments,1),binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))},boundLength=_Mathmax(0,target.length-args.length),boundArgs=[],i=0,bound;i<boundLength;i++)boundArgs.push("$"+i);if(bound=Function("binder","return function ("+boundArgs.join(",")+"){ return binder.apply(this,arguments); }")(binder),target.prototype){var Empty=function Empty(){};Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null}return bound}},{}],164:[function(require,module,exports){"use strict";var implementation=require("./implementation");module.exports=Function.prototype.bind||implementation},{"./implementation":163}],165:[function(require,module,exports){module.exports=function getBrowserRTC(){if("undefined"==typeof globalThis)return null;var wrtc={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return wrtc.RTCPeerConnection?wrtc:null}},{}],166:[function(require,module,exports){"use strict";var $SyntaxError=SyntaxError,$Function=Function,$TypeError=TypeError,getEvalledConstructor=function(expressionSyntax){try{return $Function("\"use strict\"; return ("+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=Object.getOwnPropertyDescriptor,undefined;if($gOPD)try{$gOPD({},"")}catch(e){$gOPD=null}var throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return arguments.callee,throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=require("has-symbols")(),getProto=Object.getPrototypeOf||function(x){return x.__proto__},needsEval={},TypedArray="undefined"==typeof Uint8Array?void 0:getProto(Uint8Array),INTRINSICS={"%AggregateError%":"undefined"==typeof AggregateError?void 0:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?void 0:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):void 0,"%AsyncFromSyncIteratorPrototype%":void 0,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?void 0:Atomics,"%BigInt%":"undefined"==typeof BigInt?void 0:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?void 0:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?void 0:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?void 0:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?void 0:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?void 0:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?void 0:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?void 0:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):void 0,"%JSON%":"object"==typeof JSON?JSON:void 0,"%Map%":"undefined"==typeof Map?void 0:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols?getProto(new Map()[Symbol.iterator]()):void 0,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?void 0:Promise,"%Proxy%":"undefined"==typeof Proxy?void 0:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?void 0:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?void 0:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols?getProto(new Set()[Symbol.iterator]()):void 0,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?void 0:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):void 0,"%Symbol%":hasSymbols?Symbol:void 0,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?void 0:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?void 0:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?void 0:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?void 0:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?void 0:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?void 0:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?void 0:WeakSet},doEval=function doEval(name){var value;if("%AsyncFunction%"===name)value=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===name)value=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===name)value=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===name){var fn=doEval("%AsyncGeneratorFunction%");fn&&(value=fn.prototype)}else if("%AsyncIteratorPrototype%"===name){var gen=doEval("%AsyncGenerator%");gen&&(value=getProto(gen.prototype))}return INTRINSICS[name]=value,value},LEGACY_ALIASES={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=require("function-bind"),hasOwn=require("has"),$concat=bind.call(Function.call,Array.prototype.concat),$spliceApply=bind.call(Function.apply,Array.prototype.splice),$replace=bind.call(Function.call,_Stringprototype.replace),$strSlice=bind.call(Function.call,_Stringprototype.slice),$exec=bind.call(Function.call,RegExp.prototype.exec),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function stringToPath(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");else if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match}),result},getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var intrinsicName=name,alias;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(alias=LEGACY_ALIASES[intrinsicName],intrinsicName="%"+alias[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval&&(value=doEval(intrinsicName)),"undefined"==typeof value&&!allowMissing)throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!");return{alias:alias,name:intrinsicName,value:value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};module.exports=function GetIntrinsic(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(1<arguments.length&&"boolean"!=typeof allowMissing)throw new $TypeError("\"allowMissing\" argument must be a boolean");if(null===$exec(/^%?[^%]*%?$/g,name))throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var parts=stringToPath(name),intrinsicBaseName=0<parts.length?parts[0]:"",intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing),intrinsicRealName=intrinsic.name,value=intrinsic.value,skipFurtherCaching=!1,alias=intrinsic.alias;alias&&(intrinsicBaseName=alias[0],$spliceApply(parts,$concat([0,1],alias)));for(var i=1,isOwn=!0;i<parts.length;i+=1){var part=parts[i],first=$strSlice(part,0,1),last=$strSlice(part,-1);if(("\""===first||"'"===first||"`"===first||"\""===last||"'"===last||"`"===last)&&first!==last)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==part&&isOwn||(skipFurtherCaching=!0),intrinsicBaseName+="."+part,intrinsicRealName="%"+intrinsicBaseName+"%",hasOwn(INTRINSICS,intrinsicRealName))value=INTRINSICS[intrinsicRealName];else if(null!=value){if(!(part in value)){if(!allowMissing)throw new $TypeError("base intrinsic for "+name+" exists, but the property is not available.");return}if($gOPD&&i+1>=parts.length){var desc=$gOPD(value,part);isOwn=!!desc,value=isOwn&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[part]}else isOwn=hasOwn(value,part),value=value[part];isOwn&&!skipFurtherCaching&&(INTRINSICS[intrinsicRealName]=value)}}return value}},{"function-bind":164,has:170,"has-symbols":167}],167:[function(require,module,exports){"use strict";var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=require("./shams");module.exports=function hasNativeSymbols(){return!("function"!=typeof origSymbol)&&!("function"!=typeof Symbol)&&!("symbol"!=typeof origSymbol("foo"))&&!("symbol"!=typeof Symbol("bar"))&&hasSymbolSham()}},{"./shams":168}],168:[function(require,module,exports){"use strict";module.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;var symVal=42;for(sym in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;var syms=Object.getOwnPropertySymbols(obj);if(1!==syms.length||syms[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(42!==descriptor.value||!0!==descriptor.enumerable)return!1}return!0}},{}],169:[function(require,module,exports){"use strict";var hasSymbols=require("has-symbols/shams");module.exports=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}},{"has-symbols/shams":168}],170:[function(require,module,exports){"use strict";var bind=require("function-bind");module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":164}],171:[function(require,module,exports){"use strict";function throwIfNotStringOrBuffer(val,prefix){if(!Buffer.isBuffer(val)&&"string"!=typeof val)throw new TypeError(prefix+" must be a string or a buffer")}function HashBase(blockSize){Transform.call(this),this._block=Buffer.allocUnsafe(blockSize),this._blockSize=blockSize,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}var Buffer=require("safe-buffer").Buffer,Transform=require("readable-stream").Transform,inherits=require("inherits");inherits(HashBase,Transform),HashBase.prototype._transform=function(chunk,encoding,callback){var error=null;try{this.update(chunk,encoding)}catch(err){error=err}callback(error)},HashBase.prototype._flush=function(callback){var error=null;try{this.push(this.digest())}catch(err){error=err}callback(error)},HashBase.prototype.update=function(data,encoding){if(throwIfNotStringOrBuffer(data,"Data"),this._finalized)throw new Error("Digest already called");Buffer.isBuffer(data)||(data=Buffer.from(data,encoding));for(var block=this._block,offset=0;this._blockOffset+data.length-offset>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)block[i++]=data[offset++];this._update(),this._blockOffset=0}for(;offset<data.length;)block[this._blockOffset++]=data[offset++];for(var j=0,carry=8*data.length;0<carry;++j)this._length[j]+=carry,carry=0|this._length[j]/4294967296,0<carry&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error("_update is not implemented")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var digest=this._digest();encoding!==void 0&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;4>i;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error("_digest is not implemented")},module.exports=HashBase},{inherits:189,"readable-stream":281,"safe-buffer":290}],172:[function(require,module,exports){var hash=exports;hash.utils=require("./hash/utils"),hash.common=require("./hash/common"),hash.sha=require("./hash/sha"),hash.ripemd=require("./hash/ripemd"),hash.hmac=require("./hash/hmac"),hash.sha1=hash.sha.sha1,hash.sha256=hash.sha.sha256,hash.sha224=hash.sha.sha224,hash.sha384=hash.sha.sha384,hash.sha512=hash.sha.sha512,hash.ripemd160=hash.ripemd.ripemd160},{"./hash/common":173,"./hash/hmac":174,"./hash/ripemd":175,"./hash/sha":176,"./hash/utils":183}],173:[function(require,module,exports){"use strict";function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}var utils=require("./utils"),assert=require("minimalistic-assert");exports.BlockHash=BlockHash,BlockHash.prototype.update=function update(msg,enc){if(msg=utils.toArray(msg,enc),this.pending=this.pending?this.pending.concat(msg):msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),0===this.pending.length&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i<msg.length;i+=this._delta32)this._update(msg,i,i+this._delta32)}return this},BlockHash.prototype.digest=function digest(enc){return this.update(this._pad()),assert(null===this.pending),this._digest(enc)},BlockHash.prototype._pad=function pad(){var len=this.pendingTotal,bytes=this._delta8,k=bytes-(len+this.padLength)%bytes,res=Array(k+this.padLength);res[0]=128;for(var i=1;i<k;i++)res[i]=0;if(len<<=3,"big"===this.endian){for(var t=8;t<this.padLength;t++)res[i++]=0;res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=255&len>>>24,res[i++]=255&len>>>16,res[i++]=255&len>>>8,res[i++]=255&len}else for(res[i++]=255&len,res[i++]=255&len>>>8,res[i++]=255&len>>>16,res[i++]=255&len>>>24,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,t=8;t<this.padLength;t++)res[i++]=0;return res}},{"./utils":183,"minimalistic-assert":219}],174:[function(require,module,exports){"use strict";function Hmac(hash,key,enc){return this instanceof Hmac?void(this.Hash=hash,this.blockSize=hash.blockSize/8,this.outSize=hash.outSize/8,this.inner=null,this.outer=null,this._init(utils.toArray(key,enc))):new Hmac(hash,key,enc)}var utils=require("./utils"),assert=require("minimalistic-assert");module.exports=Hmac,Hmac.prototype._init=function init(key){key.length>this.blockSize&&(key=new this.Hash().update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i<this.blockSize;i++)key.push(0);for(i=0;i<key.length;i++)key[i]^=54;for(this.inner=new this.Hash().update(key),i=0;i<key.length;i++)key[i]^=106;this.outer=new this.Hash().update(key)},Hmac.prototype.update=function update(msg,enc){return this.inner.update(msg,enc),this},Hmac.prototype.digest=function digest(enc){return this.outer.update(this.inner.digest()),this.outer.digest(enc)}},{"./utils":183,"minimalistic-assert":219}],175:[function(require,module,exports){"use strict";function RIPEMD160(){return this instanceof RIPEMD160?void(BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"):new RIPEMD160}function f(j,x,y,z){return 15>=j?x^y^z:31>=j?x&y|~x&z:47>=j?(x|~y)^z:63>=j?x&z|y&~z:x^(y|~z)}function K(j){return 15>=j?0:31>=j?1518500249:47>=j?1859775393:63>=j?2400959708:2840853838}function Kh(j){return 15>=j?1352829926:31>=j?1548603684:47>=j?1836072691:63>=j?2053994217:0}var utils=require("./utils"),common=require("./common"),rotl32=utils.rotl32,sum32=utils.sum32,sum32_3=utils.sum32_3,sum32_4=utils.sum32_4,BlockHash=common.BlockHash;utils.inherits(RIPEMD160,BlockHash),exports.ripemd160=RIPEMD160,RIPEMD160.blockSize=512,RIPEMD160.outSize=160,RIPEMD160.hmacStrength=192,RIPEMD160.padLength=64,RIPEMD160.prototype._update=function update(msg,start){for(var A=this.h[0],B=this.h[1],C=this.h[2],D=this.h[3],E=this.h[4],Ah=A,Bh=B,Ch=C,Dh=D,Eh=E,j=0,T;80>j;j++)T=sum32(rotl32(sum32_4(A,f(j,B,C,D),msg[r[j]+start],K(j)),s[j]),E),A=E,E=D,D=rotl32(C,10),C=B,B=T,T=sum32(rotl32(sum32_4(Ah,f(79-j,Bh,Ch,Dh),msg[rh[j]+start],Kh(j)),sh[j]),Eh),Ah=Eh,Eh=Dh,Dh=rotl32(Ch,10),Ch=Bh,Bh=T;T=sum32_3(this.h[1],C,Dh),this.h[1]=sum32_3(this.h[2],D,Eh),this.h[2]=sum32_3(this.h[3],E,Ah),this.h[3]=sum32_3(this.h[4],A,Bh),this.h[4]=sum32_3(this.h[0],B,Ch),this.h[0]=T},RIPEMD160.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"little"):utils.split32(this.h,"little")};var r=[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],rh=[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],s=[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],sh=[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]},{"./common":173,"./utils":183}],176:[function(require,module,exports){"use strict";exports.sha1=require("./sha/1"),exports.sha224=require("./sha/224"),exports.sha256=require("./sha/256"),exports.sha384=require("./sha/384"),exports.sha512=require("./sha/512")},{"./sha/1":177,"./sha/224":178,"./sha/256":179,"./sha/384":180,"./sha/512":181}],177:[function(require,module,exports){"use strict";function SHA1(){return this instanceof SHA1?void(BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)):new SHA1}var utils=require("../utils"),common=require("../common"),shaCommon=require("./common"),rotl32=utils.rotl32,sum32=utils.sum32,sum32_5=utils.sum32_5,ft_1=shaCommon.ft_1,BlockHash=common.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];utils.inherits(SHA1,BlockHash),module.exports=SHA1,SHA1.blockSize=512,SHA1.outSize=160,SHA1.hmacStrength=80,SHA1.padLength=64,SHA1.prototype._update=function _update(msg,start){for(var W=this.W,i=0;16>i;i++)W[i]=msg[start+i];for(;i<W.length;i++)W[i]=rotl32(W[i-3]^W[i-8]^W[i-14]^W[i-16],1);var a=this.h[0],b=this.h[1],c=this.h[2],d=this.h[3],e=this.h[4];for(i=0;i<W.length;i++){var s=~~(i/20),t=sum32_5(rotl32(a,5),ft_1(s,b,c,d),e,W[i],sha1_K[s]);e=d,d=c,c=rotl32(b,30),b=a,a=t}this.h[0]=sum32(this.h[0],a),this.h[1]=sum32(this.h[1],b),this.h[2]=sum32(this.h[2],c),this.h[3]=sum32(this.h[3],d),this.h[4]=sum32(this.h[4],e)},SHA1.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"big"):utils.split32(this.h,"big")}},{"../common":173,"../utils":183,"./common":182}],178:[function(require,module,exports){"use strict";function SHA224(){return this instanceof SHA224?void(SHA256.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]):new SHA224}var utils=require("../utils"),SHA256=require("./256");utils.inherits(SHA224,SHA256),module.exports=SHA224,SHA224.blockSize=512,SHA224.outSize=224,SHA224.hmacStrength=192,SHA224.padLength=64,SHA224.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h.slice(0,7),"big"):utils.split32(this.h.slice(0,7),"big")}},{"../utils":183,"./256":179}],179:[function(require,module,exports){"use strict";function SHA256(){return this instanceof SHA256?void(BlockHash.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=sha256_K,this.W=Array(64)):new SHA256}var utils=require("../utils"),common=require("../common"),shaCommon=require("./common"),assert=require("minimalistic-assert"),sum32=utils.sum32,sum32_4=utils.sum32_4,sum32_5=utils.sum32_5,ch32=shaCommon.ch32,maj32=shaCommon.maj32,s0_256=shaCommon.s0_256,s1_256=shaCommon.s1_256,g0_256=shaCommon.g0_256,g1_256=shaCommon.g1_256,BlockHash=common.BlockHash,sha256_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];utils.inherits(SHA256,BlockHash),module.exports=SHA256,SHA256.blockSize=512,SHA256.outSize=256,SHA256.hmacStrength=192,SHA256.padLength=64,SHA256.prototype._update=function _update(msg,start){for(var W=this.W,i=0;16>i;i++)W[i]=msg[start+i];for(;i<W.length;i++)W[i]=sum32_4(g1_256(W[i-2]),W[i-7],g0_256(W[i-15]),W[i-16]);var a=this.h[0],b=this.h[1],c=this.h[2],d=this.h[3],e=this.h[4],f=this.h[5],g=this.h[6],h=this.h[7];for(assert(this.k.length===W.length),i=0;i<W.length;i++){var T1=sum32_5(h,s1_256(e),ch32(e,f,g),this.k[i],W[i]),T2=sum32(s0_256(a),maj32(a,b,c));h=g,g=f,f=e,e=sum32(d,T1),d=c,c=b,b=a,a=sum32(T1,T2)}this.h[0]=sum32(this.h[0],a),this.h[1]=sum32(this.h[1],b),this.h[2]=sum32(this.h[2],c),this.h[3]=sum32(this.h[3],d),this.h[4]=sum32(this.h[4],e),this.h[5]=sum32(this.h[5],f),this.h[6]=sum32(this.h[6],g),this.h[7]=sum32(this.h[7],h)},SHA256.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"big"):utils.split32(this.h,"big")}},{"../common":173,"../utils":183,"./common":182,"minimalistic-assert":219}],180:[function(require,module,exports){"use strict";function SHA384(){return this instanceof SHA384?void(SHA512.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]):new SHA384}var utils=require("../utils"),SHA512=require("./512");utils.inherits(SHA384,SHA512),module.exports=SHA384,SHA384.blockSize=1024,SHA384.outSize=384,SHA384.hmacStrength=192,SHA384.padLength=128,SHA384.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h.slice(0,12),"big"):utils.split32(this.h.slice(0,12),"big")}},{"../utils":183,"./512":181}],181:[function(require,module,exports){"use strict";function SHA512(){return this instanceof SHA512?void(BlockHash.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=sha512_K,this.W=Array(160)):new SHA512}function ch64_hi(xh,xl,yh,yl,zh){var r=xh&yh^~xh&zh;return 0>r&&(r+=4294967296),r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;return 0>r&&(r+=4294967296),r}function maj64_hi(xh,xl,yh,yl,zh){var r=xh&yh^xh&zh^yh&zh;return 0>r&&(r+=4294967296),r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;return 0>r&&(r+=4294967296),r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28),c1_hi=rotr64_hi(xl,xh,2),c2_hi=rotr64_hi(xl,xh,7),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28),c1_lo=rotr64_lo(xl,xh,2),c2_lo=rotr64_lo(xl,xh,7),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14),c1_hi=rotr64_hi(xh,xl,18),c2_hi=rotr64_hi(xl,xh,9),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14),c1_lo=rotr64_lo(xh,xl,18),c2_lo=rotr64_lo(xl,xh,9),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1),c1_hi=rotr64_hi(xh,xl,8),c2_hi=shr64_hi(xh,xl,7),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1),c1_lo=rotr64_lo(xh,xl,8),c2_lo=shr64_lo(xh,xl,7),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19),c1_hi=rotr64_hi(xl,xh,29),c2_hi=shr64_hi(xh,xl,6),r=c0_hi^c1_hi^c2_hi;return 0>r&&(r+=4294967296),r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19),c1_lo=rotr64_lo(xl,xh,29),c2_lo=shr64_lo(xh,xl,6),r=c0_lo^c1_lo^c2_lo;return 0>r&&(r+=4294967296),r}var utils=require("../utils"),common=require("../common"),assert=require("minimalistic-assert"),rotr64_hi=utils.rotr64_hi,rotr64_lo=utils.rotr64_lo,shr64_hi=utils.shr64_hi,shr64_lo=utils.shr64_lo,sum64=utils.sum64,sum64_hi=utils.sum64_hi,sum64_lo=utils.sum64_lo,sum64_4_hi=utils.sum64_4_hi,sum64_4_lo=utils.sum64_4_lo,sum64_5_hi=utils.sum64_5_hi,sum64_5_lo=utils.sum64_5_lo,BlockHash=common.BlockHash,sha512_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];utils.inherits(SHA512,BlockHash),module.exports=SHA512,SHA512.blockSize=1024,SHA512.outSize=512,SHA512.hmacStrength=192,SHA512.padLength=128,SHA512.prototype._prepareBlock=function _prepareBlock(msg,start){for(var W=this.W,i=0;32>i;i++)W[i]=msg[start+i];for(;i<W.length;i+=2){var c0_hi=g1_512_hi(W[i-4],W[i-3]),c0_lo=g1_512_lo(W[i-4],W[i-3]),c1_hi=W[i-14],c1_lo=W[i-13],c2_hi=g0_512_hi(W[i-30],W[i-29]),c2_lo=g0_512_lo(W[i-30],W[i-29]),c3_hi=W[i-32],c3_lo=W[i-31];W[i]=sum64_4_hi(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo),W[i+1]=sum64_4_lo(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo)}},SHA512.prototype._update=function _update(msg,start){this._prepareBlock(msg,start);var W=this.W,ah=this.h[0],al=this.h[1],bh=this.h[2],bl=this.h[3],ch=this.h[4],cl=this.h[5],dh=this.h[6],dl=this.h[7],eh=this.h[8],el=this.h[9],fh=this.h[10],fl=this.h[11],gh=this.h[12],gl=this.h[13],hh=this.h[14],hl=this.h[15];assert(this.k.length===W.length);for(var i=0;i<W.length;i+=2){var c0_hi=hh,c0_lo=hl,c1_hi=s1_512_hi(eh,el),c1_lo=s1_512_lo(eh,el),c2_hi=ch64_hi(eh,el,fh,fl,gh,gl),c2_lo=ch64_lo(eh,el,fh,fl,gh,gl),c3_hi=this.k[i],c3_lo=this.k[i+1],c4_hi=W[i],c4_lo=W[i+1],T1_hi=sum64_5_hi(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo,c4_hi,c4_lo),T1_lo=sum64_5_lo(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo,c4_hi,c4_lo);c0_hi=s0_512_hi(ah,al),c0_lo=s0_512_lo(ah,al),c1_hi=maj64_hi(ah,al,bh,bl,ch,cl),c1_lo=maj64_lo(ah,al,bh,bl,ch,cl);var T2_hi=sum64_hi(c0_hi,c0_lo,c1_hi,c1_lo),T2_lo=sum64_lo(c0_hi,c0_lo,c1_hi,c1_lo);hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,eh=sum64_hi(dh,dl,T1_hi,T1_lo),el=sum64_lo(dl,dl,T1_hi,T1_lo),dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,ah=sum64_hi(T1_hi,T1_lo,T2_hi,T2_lo),al=sum64_lo(T1_hi,T1_lo,T2_hi,T2_lo)}sum64(this.h,0,ah,al),sum64(this.h,2,bh,bl),sum64(this.h,4,ch,cl),sum64(this.h,6,dh,dl),sum64(this.h,8,eh,el),sum64(this.h,10,fh,fl),sum64(this.h,12,gh,gl),sum64(this.h,14,hh,hl)},SHA512.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"big"):utils.split32(this.h,"big")}},{"../common":173,"../utils":183,"minimalistic-assert":219}],182:[function(require,module,exports){"use strict";function ft_1(s,x,y,z){return 0===s?ch32(x,y,z):1===s||3===s?p32(x,y,z):2===s?maj32(x,y,z):void 0}function ch32(x,y,z){return x&y^~x&z}function maj32(x,y,z){return x&y^x&z^y&z}function p32(x,y,z){return x^y^z}function s0_256(x){return rotr32(x,2)^rotr32(x,13)^rotr32(x,22)}function s1_256(x){return rotr32(x,6)^rotr32(x,11)^rotr32(x,25)}function g0_256(x){return rotr32(x,7)^rotr32(x,18)^x>>>3}function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}var utils=require("../utils"),rotr32=utils.rotr32;exports.ft_1=ft_1,exports.ch32=ch32,exports.maj32=maj32,exports.p32=p32,exports.s0_256=s0_256,exports.s1_256=s1_256,exports.g0_256=g0_256,exports.g1_256=g1_256},{"../utils":183}],183:[function(require,module,exports){"use strict";function isSurrogatePair(msg,i){return!(55296!=(64512&msg.charCodeAt(i)))&&!(0>i||i+1>=msg.length)&&56320==(64512&msg.charCodeAt(i+1))}function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(!("string"==typeof msg))for(i=0;i<msg.length;i++)res[i]=0|msg[i];else if(!enc)for(var p=0,i=0,c;i<msg.length;i++)c=msg.charCodeAt(i),128>c?res[p++]=c:2048>c?(res[p++]=192|c>>6,res[p++]=128|63&c):isSurrogatePair(msg,i)?(c=65536+((1023&c)<<10)+(1023&msg.charCodeAt(++i)),res[p++]=240|c>>18,res[p++]=128|63&c>>12,res[p++]=128|63&c>>6,res[p++]=128|63&c):(res[p++]=224|c>>12,res[p++]=128|63&c>>6,res[p++]=128|63&c);else if("hex"===enc)for(msg=msg.replace(/[^a-z0-9]+/ig,""),0!=msg.length%2&&(msg="0"+msg),i=0;i<msg.length;i+=2)res.push(parseInt(msg[i]+msg[i+1],16));return res}function toHex(msg){for(var res="",i=0;i<msg.length;i++)res+=zero2(msg[i].toString(16));return res}function htonl(w){var res=w>>>24|65280&w>>>8|16711680&w<<8|(255&w)<<24;return res>>>0}function toHex32(msg,endian){for(var res="",i=0,w;i<msg.length;i++)w=msg[i],"little"===endian&&(w=htonl(w)),res+=zero8(w.toString(16));return res}function zero2(word){return 1===word.length?"0"+word:word}function zero8(word){return 7===word.length?"0"+word:6===word.length?"00"+word:5===word.length?"000"+word:4===word.length?"0000"+word:3===word.length?"00000"+word:2===word.length?"000000"+word:1===word.length?"0000000"+word:word}function join32(msg,start,end,endian){var len=end-start;assert(0==len%4);for(var res=Array(len/4),i=0,k=start;i<res.length;i++,k+=4){var w;w="big"===endian?msg[k]<<24|msg[k+1]<<16|msg[k+2]<<8|msg[k+3]:msg[k+3]<<24|msg[k+2]<<16|msg[k+1]<<8|msg[k],res[i]=w>>>0}return res}function split32(msg,endian){for(var res=Array(4*msg.length),i=0,k=0,m;i<msg.length;i++,k+=4)m=msg[i],"big"===endian?(res[k]=m>>>24,res[k+1]=255&m>>>16,res[k+2]=255&m>>>8,res[k+3]=255&m):(res[k+3]=m>>>24,res[k+2]=255&m>>>16,res[k+1]=255&m>>>8,res[k]=255&m);return res}function rotr32(w,b){return w>>>b|w<<32-b}function rotl32(w,b){return w<<b|w>>>32-b}function sum32(a,b){return a+b>>>0}function sum32_3(a,b,c){return a+b+c>>>0}function sum32_4(a,b,c,d){return a+b+c+d>>>0}function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo<al?1:0)+ah+bh;buf[pos]=hi>>>0,buf[pos+1]=lo}function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo<al?1:0)+ah+bh;return hi>>>0}function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo<al?1:0,lo=lo+cl>>>0,carry+=lo<cl?1:0,lo=lo+dl>>>0,carry+=lo<dl?1:0;var hi=ah+bh+ch+dh+carry;return hi>>>0}function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo<al?1:0,lo=lo+cl>>>0,carry+=lo<cl?1:0,lo=lo+dl>>>0,carry+=lo<dl?1:0,lo=lo+el>>>0,carry+=lo<el?1:0;var hi=ah+bh+ch+dh+eh+carry;return hi>>>0}function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}function shr64_hi(ah,al,num){return ah>>>num}function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}var assert=require("minimalistic-assert"),inherits=require("inherits");exports.inherits=inherits,exports.toArray=toArray,exports.toHex=toHex,exports.htonl=htonl,exports.toHex32=toHex32,exports.zero2=zero2,exports.zero8=zero8,exports.join32=join32,exports.split32=split32,exports.rotr32=rotr32,exports.rotl32=rotl32,exports.sum32=sum32,exports.sum32_3=sum32_3,exports.sum32_4=sum32_4,exports.sum32_5=sum32_5,exports.sum64=sum64,exports.sum64_hi=sum64_hi,exports.sum64_lo=sum64_lo,exports.sum64_4_hi=sum64_4_hi,exports.sum64_4_lo=sum64_4_lo,exports.sum64_5_hi=sum64_5_hi,exports.sum64_5_lo=sum64_5_lo,exports.rotr64_hi=rotr64_hi,exports.rotr64_lo=rotr64_lo,exports.shr64_hi=shr64_hi,exports.shr64_lo=shr64_lo},{inherits:189,"minimalistic-assert":219}],184:[function(require,module,exports){"use strict";function HmacDRBG(options){if(!(this instanceof HmacDRBG))return new HmacDRBG(options);this.hash=options.hash,this.predResist=!!options.predResist,this.outLen=this.hash.outSize,this.minEntropy=options.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var entropy=utils.toArray(options.entropy,options.entropyEnc||"hex"),nonce=utils.toArray(options.nonce,options.nonceEnc||"hex"),pers=utils.toArray(options.pers,options.persEnc||"hex");assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(entropy,nonce,pers)}var hash=require("hash.js"),utils=require("minimalistic-crypto-utils"),assert=require("minimalistic-assert");module.exports=HmacDRBG,HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var i=0;i<this.V.length;i++)this.K[i]=0,this.V[i]=1;this._update(seed),this._reseed=1,this.reseedInterval=281474976710656},HmacDRBG.prototype._hmac=function hmac(){return new hash.hmac(this.hash,this.K)},HmacDRBG.prototype._update=function update(seed){var kmac=this._hmac().update(this.V).update([0]);seed&&(kmac=kmac.update(seed)),this.K=kmac.digest(),this.V=this._hmac().update(this.V).digest();seed&&(this.K=this._hmac().update(this.V).update([1]).update(seed).digest(),this.V=this._hmac().update(this.V).digest())},HmacDRBG.prototype.reseed=function reseed(entropy,entropyEnc,add,addEnc){"string"!=typeof entropyEnc&&(addEnc=add,add=entropyEnc,entropyEnc=null),entropy=utils.toArray(entropy,entropyEnc),add=utils.toArray(add,addEnc),assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof enc&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc||"hex"),this._update(add));for(var temp=[];temp.length<len;)this.V=this._hmac().update(this.V).digest(),temp=temp.concat(this.V);var res=temp.slice(0,len);return this._update(add),this._reseed++,utils.encode(res,enc)}},{"hash.js":172,"minimalistic-assert":219,"minimalistic-crypto-utils":220}],185:[function(require,module,exports){function HTTPParser(type){assert.ok(type===HTTPParser.REQUEST||type===HTTPParser.RESPONSE),this.type=type,this.state=type+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1}function parseErrorCode(code){var err=new Error("Parse Error");return err.code=code,err}var assert=require("assert");exports.HTTPParser=HTTPParser,HTTPParser.encoding="ascii",HTTPParser.maxHeaderSize=81920,HTTPParser.REQUEST="REQUEST",HTTPParser.RESPONSE="RESPONSE";var kOnHeaders=HTTPParser.kOnHeaders=0,kOnHeadersComplete=HTTPParser.kOnHeadersComplete=1,kOnBody=HTTPParser.kOnBody=2,kOnMessageComplete=HTTPParser.kOnMessageComplete=3;HTTPParser.prototype[kOnHeaders]=HTTPParser.prototype[kOnHeadersComplete]=HTTPParser.prototype[kOnBody]=HTTPParser.prototype[kOnMessageComplete]=function(){};var compatMode0_12=!0;Object.defineProperty(HTTPParser,"kOnExecute",{get:function(){return compatMode0_12=!1,4}});var methods=exports.methods=HTTPParser.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK"],method_connect=methods.indexOf("CONNECT");HTTPParser.prototype.reinitialize=HTTPParser,HTTPParser.prototype.close=HTTPParser.prototype.pause=HTTPParser.prototype.resume=HTTPParser.prototype.free=function(){},HTTPParser.prototype._compatMode0_11=!1,HTTPParser.prototype.getAsyncId=function(){return 0};var headerState={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};HTTPParser.prototype.execute=function(chunk,start,length){if(!(this instanceof HTTPParser))throw new TypeError("not a HTTPParser");start=start||0,length="number"==typeof length?length:chunk.length,this.chunk=chunk,this.offset=start;var end=this.end=start+length;try{for(;this.offset<end&&!this[this.state](););}catch(err){if(this.isUserCall)throw err;return this.hadError=!0,err}return this.chunk=null,length=this.offset-start,headerState[this.state]&&(this.headerSize+=length,this.headerSize>HTTPParser.maxHeaderSize)?new Error("max header size exceeded"):length};var stateFinishAllowed={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};HTTPParser.prototype.finish=function(){return this.hadError?void 0:stateFinishAllowed[this.state]?void("BODY_RAW"===this.state&&this.userCall()(this[kOnMessageComplete]())):new Error("invalid state for EOF")},HTTPParser.prototype.consume=HTTPParser.prototype.unconsume=HTTPParser.prototype.getCurrentBuffer=function(){},HTTPParser.prototype.userCall=function(){this.isUserCall=!0;var self=this;return function(ret){return self.isUserCall=!1,ret}},HTTPParser.prototype.nextRequest=function(){this.userCall()(this[kOnMessageComplete]()),this.reinitialize(this.type)},HTTPParser.prototype.consumeLine=function(){for(var end=this.end,chunk=this.chunk,i=this.offset;i<end;i++)if(10===chunk[i]){var line=this.line+chunk.toString(HTTPParser.encoding,this.offset,i);return"\r"===line.charAt(line.length-1)&&(line=line.substr(0,line.length-1)),this.line="",this.offset=i+1,line}this.line+=chunk.toString(HTTPParser.encoding,this.offset,this.end),this.offset=this.end};var headerExp=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,headerContinueExp=/^[ \t]+(.*[^ \t])/;HTTPParser.prototype.parseHeader=function(line,headers){if(-1!==line.indexOf("\r"))throw parseErrorCode("HPE_LF_EXPECTED");var match=headerExp.exec(line),k=match&&match[1];if(k)headers.push(k),headers.push(match[2]);else{var matchContinue=headerContinueExp.exec(line);matchContinue&&headers.length&&(headers[headers.length-1]&&(headers[headers.length-1]+=" "),headers[headers.length-1]+=matchContinue[1])}};var requestExp=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;HTTPParser.prototype.REQUEST_LINE=function(){var line=this.consumeLine();if(line){var match=requestExp.exec(line);if(null===match)throw parseErrorCode("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?match[1]:methods.indexOf(match[1]),-1===this.info.method)throw new Error("invalid request method");this.info.url=match[2],this.info.versionMajor=+match[3],this.info.versionMinor=+match[4],this.body_bytes=0,this.state="HEADER"}};var responseExp=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;HTTPParser.prototype.RESPONSE_LINE=function(){var line=this.consumeLine();if(line){var match=responseExp.exec(line);if(null===match)throw parseErrorCode("HPE_INVALID_CONSTANT");this.info.versionMajor=+match[1],this.info.versionMinor=+match[2];var statusCode=this.info.statusCode=+match[3];this.info.statusMessage=match[4],(1==(0|statusCode/100)||204===statusCode||304===statusCode)&&(this.body_bytes=0),this.state="HEADER"}},HTTPParser.prototype.shouldKeepAlive=function(){if(0<this.info.versionMajor&&0<this.info.versionMinor){if(-1!==this.connection.indexOf("close"))return!1;}else if(-1===this.connection.indexOf("keep-alive"))return!1;return!!(null!==this.body_bytes||this.isChunked)},HTTPParser.prototype.HEADER=function(){var line=this.consumeLine();if(void 0!==line){var info=this.info;if(line)this.parseHeader(line,info.headers);else{for(var headers=info.headers,hasContentLength=!1,hasUpgradeHeader=!1,i=0,currentContentLengthValue;i<headers.length;i+=2)switch(headers[i].toLowerCase()){case"transfer-encoding":this.isChunked="chunked"===headers[i+1].toLowerCase();break;case"content-length":if(currentContentLengthValue=+headers[i+1],!hasContentLength)hasContentLength=!0,this.body_bytes=currentContentLengthValue;else if(currentContentLengthValue!==this.body_bytes)throw parseErrorCode("HPE_UNEXPECTED_CONTENT_LENGTH");break;case"connection":this.connection+=headers[i+1].toLowerCase();break;case"upgrade":hasUpgradeHeader=!0;}this.isChunked&&hasContentLength&&(this.isChunked=!1),info.upgrade=hasUpgradeHeader&&-1!=this.connection.indexOf("upgrade")?this.type===HTTPParser.REQUEST||101===info.statusCode:info.method===method_connect,info.shouldKeepAlive=this.shouldKeepAlive();var skipBody;if(skipBody=compatMode0_12?this.userCall()(this[kOnHeadersComplete](info)):this.userCall()(this[kOnHeadersComplete](info.versionMajor,info.versionMinor,info.headers,info.method,info.url,info.statusCode,info.statusMessage,info.upgrade,info.shouldKeepAlive)),2===skipBody)return this.nextRequest(),!0;if(this.isChunked&&!skipBody)this.state="BODY_CHUNKHEAD";else{if(skipBody||0===this.body_bytes)return this.nextRequest(),info.upgrade;this.state=null===this.body_bytes?"BODY_RAW":"BODY_SIZED"}}}},HTTPParser.prototype.BODY_CHUNKHEAD=function(){var line=this.consumeLine();void 0===line||(this.body_bytes=parseInt(line,16),this.state=this.body_bytes?"BODY_CHUNK":"BODY_CHUNKTRAILERS")},HTTPParser.prototype.BODY_CHUNK=function(){var length=_Mathmin(this.end-this.offset,this.body_bytes);this.userCall()(this[kOnBody](this.chunk,this.offset,length)),this.offset+=length,this.body_bytes-=length,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")},HTTPParser.prototype.BODY_CHUNKEMPTYLINE=function(){var line=this.consumeLine();void 0===line||(assert.equal(line,""),this.state="BODY_CHUNKHEAD")},HTTPParser.prototype.BODY_CHUNKTRAILERS=function(){var line=this.consumeLine();void 0===line||(line?this.parseHeader(line,this.trailers):(this.trailers.length&&this.userCall()(this[kOnHeaders](this.trailers,"")),this.nextRequest()))},HTTPParser.prototype.BODY_RAW=function(){var length=this.end-this.offset;this.userCall()(this[kOnBody](this.chunk,this.offset,length)),this.offset=this.end},HTTPParser.prototype.BODY_SIZED=function(){var length=_Mathmin(this.end-this.offset,this.body_bytes);this.userCall()(this[kOnBody](this.chunk,this.offset,length)),this.offset+=length,this.body_bytes-=length,this.body_bytes||this.nextRequest()},["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(name){var k=HTTPParser["kOn"+name];Object.defineProperty(HTTPParser.prototype,"on"+name,{get:function(){return this[k]},set:function(to){return this._compatMode0_11=!0,method_connect="CONNECT",this[k]=to}})})},{assert:32}],186:[function(require,module,exports){function validateParams(params){if("string"==typeof params&&(params=url.parse(params)),params.protocol||(params.protocol="https:"),"https:"!==params.protocol)throw new Error("Protocol \""+params.protocol+"\" not supported. Expected \"https:\"");return params}var http=require("http"),url=require("url"),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);https.request=function(params,cb){return params=validateParams(params),http.request.call(this,params,cb)},https.get=function(params,cb){return params=validateParams(params),http.get.call(this,params,cb)}},{http:312,url:332}],187:[function(require,module,exports){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0<nBits;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;0<nBits;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=_Mathpow(2,mLen),e-=eBias}return(s?-1:1)*m*_Mathpow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog2(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<<mLen|m,eLen+=mLen;0<eLen;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],188:[function(require,module,exports){/*! immediate-chunk-store. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const queueMicrotask=require("queue-microtask");class ImmediateStore{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb=()=>{}){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb(err)})}get(index,opts,cb=()=>{}){if("function"==typeof opts)return this.get(index,null,opts);let buf=this.mem[index];if(!buf)return this.store.get(index,opts,cb);opts||(opts={});const offset=opts.offset||0,len=opts.length||buf.length-offset;(0!==offset||len!==buf.length)&&(buf=buf.slice(offset,len+offset)),queueMicrotask(()=>cb(null,buf))}close(cb=()=>{}){this.store.close(cb)}destroy(cb=()=>{}){this.store.destroy(cb)}}module.exports=ImmediateStore},{"queue-microtask":259}],189:[function(require,module,exports){module.exports="function"==typeof Object.create?function inherits(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],190:[function(require,module,exports){(function(root){"use strict";function expandIPv6(string,parts){if(string.indexOf("::")!==string.lastIndexOf("::"))return null;let colonCount=0,lastColon=-1,zoneId=(string.match(ipv6Regexes.zoneIndex)||[])[0],replacement,replacementCount;for(zoneId&&(zoneId=zoneId.substring(1),string=string.replace(/%.+$/,""));0<=(lastColon=string.indexOf(":",lastColon+1));)colonCount++;if("::"===string.substr(0,2)&&colonCount--,"::"===string.substr(-2,2)&&colonCount--,colonCount>parts)return null;for(replacementCount=parts-colonCount,replacement=":";replacementCount--;)replacement+="0:";return string=string.replace("::",replacement),":"===string[0]&&(string=string.slice(1)),":"===string[string.length-1]&&(string=string.slice(0,-1)),parts=function(){const ref=string.split(":"),results=[];for(let i=0;i<ref.length;i++)results.push(parseInt(ref[i],16));return results}(),{parts:parts,zoneId:zoneId}}function matchCIDR(first,second,partSize,cidrBits){if(first.length!==second.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let part=0,shift;for(;0<cidrBits;){if(shift=partSize-cidrBits,0>shift&&(shift=0),first[part]>>shift!=second[part]>>shift)return!1;cidrBits-=partSize,part+=1}return!0}function parseIntAuto(string){if(hexRegex.test(string))return parseInt(string,16);if("0"===string[0]&&!isNaN(parseInt(string[1],10))){if(octalRegex.test(string))return parseInt(string,8);throw new Error(`ipaddr: cannot parse ${string} as octal`)}return parseInt(string,10)}function padPart(part,length){for(;part.length<length;)part=`0${part}`;return part}const ipv4Part="(0?\\d+|0x[a-f0-9]+)",ipv4Regexes={fourOctet:/^(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)$/i,threeOctet:/^(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)$/i,twoOctet:/^(0?\d+|0x[a-f0-9]+)\.(0?\d+|0x[a-f0-9]+)$/i,longValue:/^(0?\d+|0x[a-f0-9]+)$/i},octalRegex=/^0[0-7]+$/i,hexRegex=/^0x[a-f0-9]+$/i,zoneIndex="%[0-9a-z]{1,}",ipv6Part="(?:[0-9a-f]+::?)+",ipv6Regexes={zoneIndex:new RegExp(zoneIndex,"i"),native:new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}(${zoneIndex})?)$`,"i"),transitional:new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}\\.${"(0?\\d+|0x[a-f0-9]+)"}(${zoneIndex})?$`,"i")},ipaddr={};ipaddr.IPv4=function(){function IPv4(octets){if(4!==octets.length)throw new Error("ipaddr: ipv4 octet count should be 4");let i,octet;for(i=0;i<octets.length;i++)if(octet=octets[i],!(0<=octet&&255>=octet))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=octets}return IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]]},IPv4.prototype.kind=function(){return"ipv4"},IPv4.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv4"!==other.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return matchCIDR(this.octets,other.octets,8,cidrRange)},IPv4.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0};let i,octet,zeros;for(i=3;0<=i;i-=1)if(octet=this.octets[i],octet in zerotable){if(zeros=zerotable[octet],stop&&0!==zeros)return null;8!==zeros&&(stop=!0),cidr+=zeros}else return null;return 32-cidr},IPv4.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.toIPv4MappedAddress=function(){return ipaddr.IPv6.parse(`::ffff:${this.toString()}`)},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toString=function(){return this.octets.join(".")},IPv4}(),ipaddr.IPv4.broadcastAddressFromCIDR=function(string){try{const cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[];for(let i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.isIPv4=function(string){return null!==this.parser(string)},ipaddr.IPv4.isValid=function(string){try{return new this(this.parser(string)),!0}catch(e){return!1}},ipaddr.IPv4.isValidFourPartDecimal=function(string){return!!(ipaddr.IPv4.isValid(string)&&string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},ipaddr.IPv4.networkAddressFromCIDR=function(string){let cidr,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;4>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},ipaddr.IPv4.parse=function(string){const parts=this.parser(string);if(null===parts)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(parts)},ipaddr.IPv4.parseCIDR=function(string){let match;if(match=string.match(/^(.+)\/(\d+)$/)){const maskLength=parseInt(match[2]);if(0<=maskLength&&32>=maskLength){const parsed=[this.parse(match[1]),maskLength];return Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},ipaddr.IPv4.parser=function(string){let match,part,value;if(match=string.match(ipv4Regexes.fourOctet))return function(){const ref=match.slice(1,6),results=[];for(let i=0;i<ref.length;i++)part=ref[i],results.push(parseIntAuto(part));return results}();if(match=string.match(ipv4Regexes.longValue)){if(value=parseIntAuto(match[1]),4294967295<value||0>value)throw new Error("ipaddr: address outside defined range");return function(){const results=[];let shift;for(shift=0;24>=shift;shift+=8)results.push(255&value>>shift);return results}().reverse()}return(match=string.match(ipv4Regexes.twoOctet))?function(){const ref=match.slice(1,4),results=[];if(value=parseIntAuto(ref[1]),16777215<value||0>value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(255&value>>16),results.push(255&value>>8),results.push(255&value),results}():(match=string.match(ipv4Regexes.threeOctet))?function(){const ref=match.slice(1,5),results=[];if(value=parseIntAuto(ref[2]),65535<value||0>value)throw new Error("ipaddr: address outside defined range");return results.push(parseIntAuto(ref[0])),results.push(parseIntAuto(ref[1])),results.push(255&value>>8),results.push(255&value),results}():null},ipaddr.IPv4.subnetMaskFromPrefixLength=function(prefix){if(prefix=parseInt(prefix),0>prefix||32<prefix)throw new Error("ipaddr: invalid IPv4 prefix length");const octets=[0,0,0,0];let j=0;const filledOctetCount=_Mathfloor(prefix/8);for(;j<filledOctetCount;)octets[j]=255,j++;return 4>filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.IPv6=function(){function IPv6(parts,zoneId){let i,part;if(16===parts.length)for(this.parts=[],i=0;14>=i;i+=2)this.parts.push(parts[i]<<8|parts[i+1]);else if(8===parts.length)this.parts=parts;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(i=0;i<this.parts.length;i++)if(part=this.parts[i],!(0<=part&&65535>=part))throw new Error("ipaddr: ipv6 part should fit in 16 bits");zoneId&&(this.zoneId=zoneId)}return IPv6.prototype.SpecialRanges={unspecified:[new IPv6([0,0,0,0,0,0,0,0]),128],linkLocal:[new IPv6([65152,0,0,0,0,0,0,0]),10],multicast:[new IPv6([65280,0,0,0,0,0,0,0]),8],loopback:[new IPv6([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new IPv6([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new IPv6([0,0,0,0,0,65535,0,0]),96],rfc6145:[new IPv6([0,0,0,0,65535,0,0,0]),96],rfc6052:[new IPv6([100,65435,0,0,0,0,0,0]),96],"6to4":[new IPv6([8194,0,0,0,0,0,0,0]),16],teredo:[new IPv6([8193,0,0,0,0,0,0,0]),32],reserved:[[new IPv6([8193,3512,0,0,0,0,0,0]),32]]},IPv6.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},IPv6.prototype.kind=function(){return"ipv6"},IPv6.prototype.match=function(other,cidrRange){let ref;if(void 0===cidrRange&&(ref=other,other=ref[0],cidrRange=ref[1]),"ipv6"!==other.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return matchCIDR(this.parts,other.parts,16,cidrRange)},IPv6.prototype.prefixLengthFromSubnetMask=function(){let cidr=0,stop=!1;const zerotable={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0};let part,zeros;for(let i=7;0<=i;i-=1)if(part=this.parts[i],part in zerotable){if(zeros=zerotable[part],stop&&0!==zeros)return null;16!==zeros&&(stop=!0),cidr+=zeros}else return null;return 128-cidr},IPv6.prototype.range=function(){return ipaddr.subnetMatch(this,this.SpecialRanges)},IPv6.prototype.toByteArray=function(){let part;const bytes=[],ref=this.parts;for(let i=0;i<ref.length;i++)part=ref[i],bytes.push(part>>8),bytes.push(255&part);return bytes},IPv6.prototype.toFixedLengthString=function(){const addr=function(){const results=[];for(let i=0;i<this.parts.length;i++)results.push(padPart(this.parts[i].toString(16),4));return results}.call(this).join(":");let suffix="";return this.zoneId&&(suffix=`%${this.zoneId}`),addr+suffix},IPv6.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");const ref=this.parts.slice(-2),high=ref[0],low=ref[1];return new ipaddr.IPv4([high>>8,255&high,low>>8,255&low])},IPv6.prototype.toNormalizedString=function(){const addr=function(){const results=[];for(let i=0;i<this.parts.length;i++)results.push(this.parts[i].toString(16));return results}.call(this).join(":");let suffix="";return this.zoneId&&(suffix=`%${this.zoneId}`),addr+suffix},IPv6.prototype.toRFC5952String=function(){const regex=/((^|:)(0(:|$)){2,})/g,string=this.toNormalizedString();let bestMatchIndex=0,bestMatchLength=-1,match;for(;match=regex.exec(string);)match[0].length>bestMatchLength&&(bestMatchIndex=match.index,bestMatchLength=match[0].length);return 0>bestMatchLength?string:`${string.substring(0,bestMatchIndex)}::${string.substring(bestMatchIndex+bestMatchLength)}`},IPv6.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},IPv6}(),ipaddr.IPv6.broadcastAddressFromCIDR=function(string){try{const cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[];for(let i=0;16>i;)octets.push(parseInt(ipInterfaceOctets[i],10)|255^parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},ipaddr.IPv6.isIPv6=function(string){return null!==this.parser(string)},ipaddr.IPv6.isValid=function(string){if("string"==typeof string&&-1===string.indexOf(":"))return!1;try{const addr=this.parser(string);return new this(addr.parts,addr.zoneId),!0}catch(e){return!1}},ipaddr.IPv6.networkAddressFromCIDR=function(string){let cidr,i,ipInterfaceOctets,octets,subnetMaskOctets;try{for(cidr=this.parseCIDR(string),ipInterfaceOctets=cidr[0].toByteArray(),subnetMaskOctets=this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(),octets=[],i=0;16>i;)octets.push(parseInt(ipInterfaceOctets[i],10)&parseInt(subnetMaskOctets[i],10)),i++;return new this(octets)}catch(e){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},ipaddr.IPv6.parse=function(string){const addr=this.parser(string);if(null===addr.parts)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(addr.parts,addr.zoneId)},ipaddr.IPv6.parseCIDR=function(string){let maskLength,match,parsed;if((match=string.match(/^(.+)\/(\d+)$/))&&(maskLength=parseInt(match[2]),0<=maskLength&&128>=maskLength))return parsed=[this.parse(match[1]),maskLength],Object.defineProperty(parsed,"toString",{value:function(){return this.join("/")}}),parsed;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},ipaddr.IPv6.parser=function(string){let addr,i,match,octet,octets,zoneId;if(match=string.match(ipv6Regexes.deprecatedTransitional))return this.parser(`::ffff:${match[1]}`);if(ipv6Regexes.native.test(string))return expandIPv6(string,8);if((match=string.match(ipv6Regexes.transitional))&&(zoneId=match[6]||"",addr=expandIPv6(match[1].slice(0,-1)+zoneId,6),addr.parts)){for(octets=[parseInt(match[2]),parseInt(match[3]),parseInt(match[4]),parseInt(match[5])],i=0;i<octets.length;i++)if(octet=octets[i],!(0<=octet&&255>=octet))return null;return addr.parts.push(octets[0]<<8|octets[1]),addr.parts.push(octets[2]<<8|octets[3]),{parts:addr.parts,zoneId:addr.zoneId}}return null},ipaddr.IPv6.subnetMaskFromPrefixLength=function(prefix){if(prefix=parseInt(prefix),0>prefix||128<prefix)throw new Error("ipaddr: invalid IPv6 prefix length");const octets=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let j=0;const filledOctetCount=_Mathfloor(prefix/8);for(;j<filledOctetCount;)octets[j]=255,j++;return 16>filledOctetCount&&(octets[filledOctetCount]=_Mathpow(2,prefix%8)-1<<8-prefix%8),new this(octets)},ipaddr.fromByteArray=function(bytes){const length=bytes.length;if(4===length)return new ipaddr.IPv4(bytes);if(16===length)return new ipaddr.IPv6(bytes);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},ipaddr.isValid=function(string){return ipaddr.IPv6.isValid(string)||ipaddr.IPv4.isValid(string)},ipaddr.parse=function(string){if(ipaddr.IPv6.isValid(string))return ipaddr.IPv6.parse(string);if(ipaddr.IPv4.isValid(string))return ipaddr.IPv4.parse(string);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},ipaddr.parseCIDR=function(string){try{return ipaddr.IPv6.parseCIDR(string)}catch(e){try{return ipaddr.IPv4.parseCIDR(string)}catch(e2){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},ipaddr.process=function(string){const addr=this.parse(string);return"ipv6"===addr.kind()&&addr.isIPv4MappedAddress()?addr.toIPv4Address():addr},ipaddr.subnetMatch=function(address,rangeList,defaultName){let i,rangeName,rangeSubnets,subnet;for(rangeName in(void 0===defaultName||null===defaultName)&&(defaultName="unicast"),rangeList)if(Object.prototype.hasOwnProperty.call(rangeList,rangeName))for(rangeSubnets=rangeList[rangeName],rangeSubnets[0]&&!(rangeSubnets[0]instanceof Array)&&(rangeSubnets=[rangeSubnets]),i=0;i<rangeSubnets.length;i++)if(subnet=rangeSubnets[i],address.kind()===subnet[0].kind()&&address.match.apply(address,subnet))return rangeName;return defaultName},"undefined"!=typeof module&&module.exports?module.exports=ipaddr:root.ipaddr=ipaddr})(this)},{}],191:[function(require,module,exports){"use strict";var hasToStringTag=require("has-tostringtag/shams")(),callBound=require("call-bind/callBound"),$toString=callBound("Object.prototype.toString"),isStandardArguments=function isArguments(value){return!(hasToStringTag&&value&&"object"==typeof value&&Symbol.toStringTag in value)&&"[object Arguments]"===$toString(value)},isLegacyArguments=function isArguments(value){return!!isStandardArguments(value)||null!==value&&"object"==typeof value&&"number"==typeof value.length&&0<=value.length&&"[object Array]"!==$toString(value)&&"[object Function]"===$toString(value.callee)},supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments,module.exports=supportsStandardArguments?isStandardArguments:isLegacyArguments},{"call-bind/callBound":104,"has-tostringtag/shams":169}],192:[function(require,module,exports){var MAX_ASCII_CHAR_CODE=127;module.exports=function isAscii(str){for(var i=0,strLen=str.length;i<strLen;++i)if(str.charCodeAt(i)>127)return!1;return!0}},{}],193:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
@@ -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;i<arr.length;i++){var range=arr[i].split("-"),start=parseInt(range[0],10),end=parseInt(range[1],10);(isNaN(start)?(start=size-end,end=size-1):isNaN(end)&&(end=size-1),end>size-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;i<ordered.length;i++){var range=ordered[i],current=ordered[j];range.start>current.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;i<N;i++)s[i]=i;return s}function seed(key){if(void 0===key){key=Array(N);for(var k=0;k<N;k++)key[k]=_Mathfloor(Math.random()*N)}else if("string"==typeof key)key=""+key,key=key.split("").map(function(c){return c.charCodeAt(0)%N});else if(!Array.isArray(key))throw new TypeError("invalid seed key specified");else if(!key.every(function(v){return"number"==typeof v&&v===(0|v)}))throw new TypeError("invalid seed key specified: not array of integers");for(var keylen=key.length,s=identityPermutation(),j=0,i=0;i<N;i++){j=(j+s[i]+key[i%keylen])%N;var tmp=s[i];s[i]=s[j],s[j]=tmp}return s}function RC4(key){this.s=seed(key),this.i=0,this.j=0}return RC4.prototype.randomNative=function(){this.i=(this.i+1)%N,this.j=(this.j+this.s[this.i])%N;var tmp=this.s[this.i];this.s[this.i]=this.s[this.j],this.s[this.j]=tmp;var k=this.s[(this.s[this.i]+this.s[this.j])%N];return k},RC4.prototype.randomUInt32=function(){var a=this.randomByte(),b=this.randomByte(),c=this.randomByte(),d=this.randomByte();return 256*(256*(256*a+b)+c)+d},RC4.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},RC4.prototype.random=function(){var a,b;if(1===arguments.length)a=0,b=arguments[0];else if(2===arguments.length)a=arguments[0],b=arguments[1];else throw new TypeError("random takes one or two integer arguments");if(!isInteger(a)||!isInteger(b))throw new TypeError("random takes one or two integer arguments");return a+this.randomUInt32()%(b-a+1)},RC4.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},RC4.prototype.setState=function(state){var s=state.s,i=state.i,j=state.j;if(!(i===(0|i)&&0<=i&&i<N))throw new Error("state.i should be integer [0, "+(N-1)+"]");if(!(j===(0|j)&&0<=j&&j<N))throw new Error("state.j should be integer [0, "+(N-1)+"]");if(!Array.isArray(s)||s.length!==N)throw new Error("state should be array of length "+N);for(var k=0;k<N;k++)if(-1===s.indexOf(k))throw new Error("state should be permutation of 0.."+(N-1)+": "+k+" is missing");this.i=i,this.j=j,this.s=s.slice()},RC4}function toHex(n){return 10>n?_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+""}),2<len?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(expected+"")}function startsWith(str,search,pos){return str.substr(!pos||0>pos?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<keys.length;v++)method=keys[v],Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method]);Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this)}).call(this,require("_process"))},{"./_stream_readable":270,"./_stream_writable":272,_process:246,inherits:189}],269:[function(require,module,exports){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform");require("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":271,inherits:189}],270:[function(require,module,exports){(function(process,global){(function(){"use strict";function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(!StringDecoder&&(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else{var er;if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(!(state.objectMode||chunk&&0<chunk.length))addToFront||(state.reading=!1,maybeReadMore(stream,state));else if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return 1073741824<=n?n=1073741824:(n--,n|=n>>>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.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self){var state=self._readableState;state.readableListening=0<self.listenerCount("readable"),state.resumeScheduled&&!state.paused?state.flowing=!0:0<self.listenerCount("data")&&self.resume()}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){if(0===state.length)return null;var ret;return state.objectMode?ret=state.buffer.shift():!n||n>=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<l;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter,EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},debugUtil=require("util"),debug;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var BufferList=require("./internal/streams/buffer_list"),destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,StringDecoder,createReadableStreamAsyncIterator,from;require("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&this._readableState.destroyed},set:function set(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var state=this._readableState,skipChunkCheck;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this};var MAX_HWM=1073741824;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0===state.highWaterMark?0<state.length:state.length>=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<state.highWaterMark)&&(doRead=!0,debug("length less than watermark",doRead)),state.ended||state.reading?(doRead=!1,debug("reading or ended",doRead)):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,!state.reading&&(n=howMuchToRead(nOrig,state)));var ret;return ret=0<n?fromList(n,state):null,null===ret?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(!state.ended&&(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||1<state.pipesCount&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=0<this.listenerCount("readable"),!1!==state.flowing&&this.resume()):"readable"==ev&&!state.endEmitted&&!state.readableListening&&(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):!state.reading&&process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){if((debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),!(state.objectMode&&(null===chunk||void 0===chunk)))&&(state.objectMode||chunk&&chunk.length)){var ret=_this.push(chunk);ret||(paused=!0,stream.pause())}}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function get(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function get(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function get(){return this._readableState.flowing},set:function set(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function get(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":267,"./_stream_duplex":268,"./internal/streams/async_iterator":273,"./internal/streams/buffer_list":274,"./internal/streams/destroy":275,"./internal/streams/from":277,"./internal/streams/state":279,"./internal/streams/stream":280,_process:246,buffer:101,events:156,inherits:189,"string_decoder/":321,util:66}],271:[function(require,module,exports){"use strict";function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){return this instanceof Transform?void(Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)):new Transform(options)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}module.exports=Transform;var _require$codes=require("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require("./_stream_duplex");require("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":267,"./_stream_duplex":268,inherits:189}],272:[function(require,module,exports){(function(process,global){(function(){"use strict";function WriteReq(chunk,encoding,cb){this.chunk=chunk,this.encoding=encoding,this.callback=cb,this.next=null}function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){Duplex=Duplex||require("./_stream_duplex");var isDuplex=this instanceof Duplex;return isDuplex||realHasInstance.call(Writable,this)?void(this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)):new Writable(options)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"!=typeof chunk&&!state.objectMode&&(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}module.exports=Writable;var Duplex;Writable.WritableState=WritableState;var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;require("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function writableStateBufferGetter(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||!(this!==Writable)&&object&&object._writableState instanceof WritableState}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":!encoding&&(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,!state.writing&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest&&clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":267,"./_stream_duplex":268,"./internal/streams/destroy":275,"./internal/streams/state":279,"./internal/streams/stream":280,_process:246,buffer:101,inherits:189,"util-deprecate":336}],273:[function(require,module,exports){(function(process){(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){return iter[kEnded]?void resolve(createIterResult(void 0,!0)):void iter[kHandlePromise](resolve,reject)},reject)}}var finished=require("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream"),AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var _this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise],promise;if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},_defineProperty(_Object$setPrototypeO,Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function _return(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){return err?void reject(err):void resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype),createReadableStreamAsyncIterator=function createReadableStreamAsyncIterator(stream){var iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_Object$create={},_defineProperty(_Object$create,kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create)),_Object$create;return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];return null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),void(iterator[kError]=err)}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator},_Object$setPrototypeO;module.exports=createReadableStreamAsyncIterator}).call(this)}).call(this,require("_process"))},{"./end-of-stream":276,_process:246}],274:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1,source;i<arguments.length;i++)source=null==arguments[i]?{}:arguments[i],i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))});return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}var _require=require("buffer"),Buffer=_require.Buffer,_require2=require("util"),inspect=_require2.inspect,custom=inspect&&inspect.custom||"inspect";module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};0<this.length?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(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 n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):n===this.head.data.length?ret=this.shift():ret=hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.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=i<streams.length-1,writing=0<i;return destroyer(stream,reading,writing,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})}),error;return streams.reduce(pipe)}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=pipeline},{"../../../errors":267,"./end-of-stream":276}],279:[function(require,module,exports){"use strict";function highWaterMarkFrom(options,isDuplex,duplexKey){return null==options.highWaterMark?isDuplex?options[duplexKey]:null:options.highWaterMark}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&_Mathfloor(hwm)===hwm)||0>hwm){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<n;i++)j=_Mathfloor(Math.random()*(aLen+bLen)),j<aLen?(result[i]=a[j].record,swap(a,j,--aLen)):(j-=aLen,result[i]=b[j].record,swap(b,j,--bLen));return result},RecordCache.prototype._gcAuto=function(){this._gced||this._gc(),this._gced=!1},RecordCache.prototype._gc=function(){this._onstale&&0<this._stale.size&&this._onstale(this._stale),this._stale=this._fresh,this._fresh=new RecordStore,this._gced=!0},RecordCache.prototype.clear=function(){this._gc(),this._gc()},RecordCache.prototype.destroy=function(){this.clear(),clearInterval(this._interval),this._interval=null}},{b4a:37}],283:[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":284,debug:122,"is-ascii":192,mediasource:211,path:238,"stream-to-blob-url":316,videostream:341}],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<<n|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<this._blockOffset&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.alloc?Buffer.alloc(20):new Buffer(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer},module.exports=RIPEMD160},{buffer:101,"hash-base":171,inherits:189}],286:[function(require,module,exports){function runParallelLimit(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next<len){let key;keys?(key=keys[next],next+=1,tasks[key](function(err,result){each(key,err,result)})):(key=next,next+=1,tasks[key](function(err,result){each(key,err,result)}))}}if("number"!=typeof limit)throw new Error("second argument must be a Number");let isSync=!0,results,len,pending,keys,isErrored,next;Array.isArray(tasks)?(results=[],pending=len=tasks.length):(keys=Object.keys(tasks),results={},pending=len=keys.length),next=limit,pending?keys?keys.some(function(key,i){return tasks[key](function(err,result){each(key,err,result)}),i===limit-1}):tasks.some(function(task,i){return task(function(err,result){each(i,err,result)}),i===limit-1}):done(null),isSync=!1}module.exports=runParallelLimit;const queueMicrotask=require("queue-microtask")},{"queue-microtask":259}],287:[function(require,module,exports){function runParallel(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}let isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}module.exports=runParallel;const queueMicrotask=require("queue-microtask")},{"queue-microtask":259}],288:[function(require,module,exports){(function(process){(function(){function runSeries(tasks,cb){function done(err){function end(){cb&&cb(err,results)}isSync?process.nextTick(end):end()}function each(err,result){results.push(result),++current>=tasks.length||err?done(err):tasks[current](each)}var current=0,results=[],isSync=!0;0<tasks.length?tasks[0](each):done(null),isSync=!1}/*! run-series. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<len%64;len+=1);return len},padZeroes=function(bin,len){var h8=new Uint8Array(bin.buffer),om=len%4,align=len-om;switch(om){case 0:h8[align+3]=0;case 1:h8[align+2]=0;case 2:h8[align+1]=0;case 3:h8[align+0]=0;}for(var i=(len>>2)+1;i<bin.length;i++)bin[i]=0},padData=function(bin,chunkLen,msgLen){bin[chunkLen>>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<chunkSize%64)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=chunkSize,this._padMaxChunkLen=padlen(chunkSize),this._heap=new ArrayBuffer(ceilHeapSize(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new RushaCore({Int32Array:Int32Array},{},this._heap)}return Rusha.prototype._initState=function _initState(heap,padMsgLen){this._offset=0;var io=new Int32Array(heap,padMsgLen+320,5);io[0]=1732584193,io[1]=-271733879,io[2]=-1732584194,io[3]=271733878,io[4]=-1009589776},Rusha.prototype._padChunk=function _padChunk(chunkLen,msgLen){var padChunkLen=padlen(chunkLen),view=new Int32Array(this._heap,0,padChunkLen>>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;chunkOffset<chunkLen;)inputLen=_Mathmin(chunkLen-chunkOffset,this._maxChunkLen-turnOffset),this._write(chunk,chunkOffset,inputLen,turnOffset),turnOffset+=inputLen,chunkOffset+=inputLen,turnOffset===this._maxChunkLen&&(this._core.hash(this._maxChunkLen,this._padMaxChunkLen),turnOffset=0);return this},Rusha.prototype.getState=function getState(){var turnOffset=this._offset%this._maxChunkLen,heap=void 0;if(!turnOffset){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);heap=io.buffer.slice(io.byteOffset,io.byteOffset+io.byteLength)}else heap=this._heap.slice(0);return{offset:this._offset,heap:heap}},Rusha.prototype.setState=function setState(state){if(this._offset=state.offset,20===state.heap.byteLength){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);io.set(new Int32Array(state.heap))}else this._h32.set(new Int32Array(state.heap));return this},Rusha.prototype.rawEnd=function rawEnd(){var msgLen=this._offset,chunkLen=msgLen%this._maxChunkLen,padChunkLen=this._padChunk(chunkLen,msgLen);this._core.hash(padChunkLen,this._padMaxChunkLen);var result=getRawDigest(this._heap,this._padMaxChunkLen);return this._initState(this._heap,this._padMaxChunkLen),result},Rusha.prototype.end=function end(){return toHex(this.rawEnd().buffer)},Rusha}();module.exports=Rusha,module.exports._core=RushaCore},function(module,exports){for(var precomputedHex=Array(256),i=0;256>i;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<res.length;_i++)res[_i]=precomputedHex[binarray[_i]];return res.join("")},module.exports.ceilHeapSize=function(v){var p=0;if(65536>=v)return 65536;if(16777216>v)for(p=1;p<v;p<<=1);else for(p=16777216;p<v;p+=16777216);return p},module.exports.isDedicatedWorkerScope=function(self){var isRunningInWorker="WorkerGlobalScope"in self&&self instanceof self.WorkerGlobalScope,isRunningInSharedWorker="SharedWorkerGlobalScope"in self&&self instanceof self.SharedWorkerGlobalScope,isRunningInServiceWorker="ServiceWorkerGlobalScope"in self&&self instanceof self.ServiceWorkerGlobalScope;return isRunningInWorker&&!isRunningInSharedWorker&&!isRunningInServiceWorker}},function(module,exports,__webpack_require__){module.exports=function(){var Rusha=__webpack_require__(0),hashData=function(hasher,data,cb){try{return cb(null,hasher.digest(data))}catch(e){return cb(e)}},hashFile=function(hasher,readTotal,blockSize,file,cb){var reader=new self.FileReader;reader.onloadend=function onloadend(){if(reader.error)return cb(reader.error);var buffer=reader.result;readTotal+=reader.result.byteLength;try{hasher.append(buffer)}catch(e){return void cb(e)}readTotal<file.size?hashFile(hasher,readTotal,blockSize,file,cb):cb(null,hasher.end())},reader.readAsArrayBuffer(file.slice(readTotal,readTotal+blockSize))},workerBehaviourEnabled=!0;return self.onmessage=function(event){if(workerBehaviourEnabled){var data=event.data.data,file=event.data.file,id=event.data.id;if("undefined"!=typeof id&&(file||data)){var blockSize=event.data.blockSize||4194304,hasher=new Rusha(blockSize);hasher.resetState();var done=function(err,hash){err?self.postMessage({id:id,error:err.name}):self.postMessage({id:id,hash:hash})};data&&hashData(hasher,data,done),file&&hashFile(hasher,0,blockSize,file,done)}}},function(){workerBehaviourEnabled=!1}}},function(module,exports,__webpack_require__){var work=__webpack_require__(4),Rusha=__webpack_require__(0),createHash=__webpack_require__(7),runWorker=__webpack_require__(2),_require=__webpack_require__(1),isDedicatedWorkerScope=_require.isDedicatedWorkerScope,isRunningInDedicatedWorker="undefined"!=typeof self&&isDedicatedWorkerScope(self);Rusha.disableWorkerBehaviour=isRunningInDedicatedWorker?runWorker():function(){},Rusha.createWorker=function(){var worker=work(2),terminate=worker.terminate;return worker.terminate=function(){URL.revokeObjectURL(worker.objectURL),terminate.call(worker)},worker},Rusha.createHash=createHash,module.exports=Rusha},function(module,exports,__webpack_require__){function webpackBootstrapFunc(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={};__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.r=function(exports){Object.defineProperty(exports,"__esModule",{value:!0})},__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__.oe=function(err){throw console.error(err),err};var f=__webpack_require__(__webpack_require__.s=ENTRY_MODULE);return f.default||f}function quoteRegExp(str){return(str+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function getModuleDependencies(sources,module,queueName){var retval={};retval[queueName]=[];var fnString=module.toString(),wrapperSignature=fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!wrapperSignature)return retval;for(var webpackRequireName=wrapperSignature[1],re=new RegExp("(\\\\n|\\W)"+quoteRegExp(webpackRequireName)+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g"),match;match=re.exec(fnString);)"dll-reference"!==match[3]&&retval[queueName].push(match[3]);for(re=new RegExp("\\("+quoteRegExp(webpackRequireName)+"\\(\"(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))\"\\)\\)\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");match=re.exec(fnString);)sources[match[2]]||(retval[queueName].push(match[1]),sources[match[2]]=__webpack_require__(match[1]).m),retval[match[2]]=retval[match[2]]||[],retval[match[2]].push(match[4]);return retval}function hasValuesInQueues(queues){var keys=Object.keys(queues);return keys.reduce(function(hasValues,key){return hasValues||0<queues[key].length},!1)}function getRequiredModules(sources,moduleId){for(var modulesQueue={main:[moduleId]},requiredModules={main:[]},seenModules={main:{}};hasValuesInQueues(modulesQueue);)for(var queues=Object.keys(modulesQueue),i=0;i<queues.length;i++){var queueName=queues[i],queue=modulesQueue[queueName],moduleToCheck=queue.pop();if(seenModules[queueName]=seenModules[queueName]||{},!seenModules[queueName][moduleToCheck]&&sources[queueName][moduleToCheck]){seenModules[queueName][moduleToCheck]=!0,requiredModules[queueName]=requiredModules[queueName]||[],requiredModules[queueName].push(moduleToCheck);for(var newModules=getModuleDependencies(sources,sources[queueName][moduleToCheck],queueName),newModulesKeys=Object.keys(newModules),j=0;j<newModulesKeys.length;j++)modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]]||[],modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])}}return requiredModules}var moduleNameReqExp="[\\.|\\-|\\+|\\w|/|@]+",dependencyRegExp="\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";module.exports=function(moduleId,options){options=options||{};var sources={main:__webpack_require__.m},requiredModules=options.all?{main:Object.keys(sources)}:getRequiredModules(sources,moduleId),src="";Object.keys(requiredModules).filter(function(m){return"main"!==m}).forEach(function(module){for(var entryModule=0;requiredModules[module][entryModule];)entryModule++;requiredModules[module].push(entryModule),sources[module][entryModule]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",src=src+"var "+module+" = ("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(entryModule))+")({"+requiredModules[module].map(function(id){return""+JSON.stringify(id)+": "+sources[module][id].toString()}).join(",")+"});\n"}),src=src+"("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(moduleId))+")({"+requiredModules.main.map(function(id){return""+JSON.stringify(id)+": "+sources.main[id].toString()}).join(",")+"})(self);";var blob=new window.Blob([src],{type:"text/javascript"});if(options.bare)return blob;var URL=window.URL||window.webkitURL||window.mozURL||window.msURL,workerUrl=URL.createObjectURL(blob),worker=new window.Worker(workerUrl);return worker.objectURL=workerUrl,worker}},function(module,exports){module.exports=function RushaCore(stdlib$840,foreign$841,heap$842){"use asm";function hash$844(k$845,x$846){k$845|=0,x$846|=0;var i$847=0,j$848=0,y0$849=0,z0$850=0,y1$851=0,z1$852=0,y2$853=0,z2$854=0,y3$855=0,z3$856=0,y4$857=0,z4$858=0,t0$859=0,t1$860=0;for(y0$849=0|H$843[x$846+320>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function update(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},_createClass(Hash,[{key:"state",get:function(){return this._rusha.getState()},set:function(state){this._rusha.setState(state)}}]),Hash}();module.exports=function(){return new Hash}}])})},{}],290:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<length;){for(var assigned=accum%blockSize,remainder=_Mathmin(length-offset,blockSize-assigned),i=0;i<remainder;i++)block[assigned+i]=data[offset+i];accum+=remainder,offset+=remainder,0==accum%blockSize&&this._update(block)}return this._len+=length,this},Hash.prototype.digest=function(enc){var rem=this._len%this._blockSize;this._block[rem]=128,this._block.fill(0,rem+1),rem>=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:189,"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:189,"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:189,"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:189,"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:189,"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<b>>>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:189,"safe-buffer":290}],300:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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:186,once:231,querystring:258,"simple-concat":300,url:332}],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 <https://feross.org/opensource> */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<this._pc.getStats.length?this._pc.getStats(res=>{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":165,"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<l;i++)array[i]=s.charCodeAt(i);return array}function hex(buf){const l=buf.length,chars=[];for(let i=0;i<l;i++){const bite=buf[i];chars.push((bite>>>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 <https://feross.org/opensource> */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),0<rate&&chunksize>rate)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),0<rate&&chunksize>rate)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<index&&this.throttles.splice(index,1)}}module.exports=ThrottleGroup},{"./throttle":308,limiter:203}],308:[function(require,module,exports){const{EventEmitter}=require("events"),{Transform}=require("streamx"),{wait}=require("./utils");class Throttle extends Transform{constructor(opts={}){if(super(),"object"!=typeof opts)throw new Error("Options must be an object");const params=Object.assign({},opts);if(params.group&&!(params.group instanceof ThrottleGroup))throw new Error("Group must be an instanece of ThrottleGroup");else params.group||(params.group=new ThrottleGroup(params));this._setEnabled(params.enabled||params.group.enabled),this._group=params.group,this._emitter=new EventEmitter,this._destroyed=!1,this._group._addThrottle(this)}getEnabled(){return this._enabled}getGroup(){return this._group}_setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val}setEnabled(val){this._setEnabled(val),this._enabled?this._emitter.emit("enabled"):this._emitter.emit("disabled")}_transform(chunk,done){this._processChunk(chunk,done)}async _waitForTokens(amount){return new Promise((resolve,reject)=>{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(;0<slice.length;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await wait(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(slice.length)&&(await this._waitForTokens(slice.length),this._destroyed))return}catch(err){return done(err)}this.push(slice),pos+=chunksize,chunksize=this._areBothEnabled()?this._group.getChunksize():chunk.length-pos,slice=chunk.slice(pos,pos+chunksize)}return done()}destroy(...args){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...args)}}module.exports=Throttle;const ThrottleGroup=require("./throttle-group")},{"./throttle-group":307,"./utils":309,events:156,streamx:319}],309:[function(require,module,exports){function wait(time){return new Promise(resolve=>setTimeout(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.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],311:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter,inherits=require("inherits");inherits(Stream,EE),Stream.Readable=require("readable-stream/lib/_stream_readable.js"),Stream.Writable=require("readable-stream/lib/_stream_writable.js"),Stream.Duplex=require("readable-stream/lib/_stream_duplex.js"),Stream.Transform=require("readable-stream/lib/_stream_transform.js"),Stream.PassThrough=require("readable-stream/lib/_stream_passthrough.js"),Stream.finished=require("readable-stream/lib/internal/streams/end-of-stream.js"),Stream.pipeline=require("readable-stream/lib/internal/streams/pipeline.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:156,inherits:189,"readable-stream/lib/_stream_duplex.js":268,"readable-stream/lib/_stream_passthrough.js":269,"readable-stream/lib/_stream_readable.js":270,"readable-stream/lib/_stream_transform.js":271,"readable-stream/lib/_stream_writable.js":272,"readable-stream/lib/internal/streams/end-of-stream.js":276,"readable-stream/lib/internal/streams/pipeline.js":278}],312:[function(require,module,exports){(function(global){(function(){var ClientRequest=require("./lib/request"),response=require("./lib/response"),extend=require("xtend"),statusCodes=require("builtin-status-codes"),url=require("url"),http=exports;http.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},http.get=function get(opts,cb){var req=http.request(opts,cb);return req.end(),req},http.ClientRequest=ClientRequest,http.IncomingMessage=response.IncomingMessage,http.Agent=function(){},http.Agent.defaultMaxSockets=4,http.globalAgent=new http.Agent,http.STATUS_CODES=statusCodes,http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./lib/request":314,"./lib/response":315,"builtin-status-codes":102,url:332,xtend:344}],313:[function(require,module,exports){(function(global){(function(){function getXHR(){if(xhr!==void 0)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}function isFunction(value){return"function"==typeof value}exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController);var xhr;exports.arraybuffer=exports.fetch||checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),xhr=null}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],314:[function(require,module,exports){(function(process,global,Buffer){(function(){function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":"text"}function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}var capability=require("./capability"),inherits=require("inherits"),response=require("./response"),stream=require("readable-stream"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates,ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self),self._opts=opts,self._body=[],self._headers={},opts.auth&&self.setHeader("Authorization","Basic "+Buffer.from(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var useFetch=!0,preferBinary;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(!opts.mode||"default"===opts.mode||"prefer-fast"===opts.mode)preferBinary=!0;else throw new Error("Invalid value for opts.mode");self._mode=decideMode(preferBinary,useFetch),self._fetchTimer=null,self._socketTimeout=null,self._socketTimer=null,self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var self=this,lowerName=name.toLowerCase();-1!==unsafeHeaders.indexOf(lowerName)||(self._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self=this;if(!self._destroyed){var opts=self._opts;"timeout"in opts&&0!==opts.timeout&&self.setTimeout(opts.timeout);var headersObj=self._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=new Blob(self._body,{type:(headersObj["content-type"]||{}).value||""}));var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout"),self._fetchAbortController&&self._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response,self._resetTimers(!1),self._connect()},function(reason){self._resetTimers(!0),self._destroyed||self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,!0)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}"responseType"in xhr&&(xhr.responseType=self._mode),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();}},"moz-chunked-arraybuffer"===self._mode&&(xhr.onprogress=function(){self._onXHRProgress()}),xhr.onerror=function(){self._destroyed||(self._resetTimers(!0),self.emit("error",new Error("XHR error")))};try{xhr.send(body)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}}}},ClientRequest.prototype._onXHRProgress=function(){var self=this;self._resetTimers(!1);!statusValid(self._xhr)||self._destroyed||(!self._response&&self._connect(),self._response._onXHRProgress(self._resetTimers.bind(self)))},ClientRequest.prototype._connect=function(){var self=this;self._destroyed||(self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._resetTimers.bind(self)),self._response.on("error",function(err){self.emit("error",err)}),self.emit("response",self._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk),cb()},ClientRequest.prototype._resetTimers=function(done){var self=this;global.clearTimeout(self._socketTimer),self._socketTimer=null,done?(global.clearTimeout(self._fetchTimer),self._fetchTimer=null):self._socketTimeout&&(self._socketTimer=global.setTimeout(function(){self.emit("timeout")},self._socketTimeout))},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(err){var self=this;self._destroyed=!0,self._resetTimers(!0),self._response&&(self._response._destroyed=!0),self._xhr?self._xhr.abort():self._fetchAbortController&&self._fetchAbortController.abort(),err&&self.emit("error",err)},ClientRequest.prototype.end=function(data,encoding,cb){var self=this;"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(self,data,encoding,cb)},ClientRequest.prototype.setTimeout=function(timeout,cb){var self=this;cb&&self.once("timeout",cb),self._socketTimeout=timeout,self._resetTimers(!1)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":313,"./response":315,_process:246,buffer:101,inherits:189,"readable-stream":281}],315:[function(require,module,exports){(function(process,global,Buffer){(function(){var capability=require("./capability"),inherits=require("inherits"),stream=require("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,resetTimers){var self=this;if(stream.Readable.call(self),self._mode=mode,self.headers={},self.rawHeaders=[],self.trailers={},self.rawTrailers=[],self.on("end",function(){process.nextTick(function(){self.emit("close")})}),"fetch"===mode){function read(){reader.read().then(function(result){if(!self._destroyed)return resetTimers(result.done),result.done?void self.push(null):void(self.push(Buffer.from(result.value)),read())}).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}if(self._fetchResponse=response,self.url=response.url,self.statusCode=response.status,self.statusMessage=response.statusText,response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header,self.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return resetTimers(!1),new Promise(function(resolve,reject){self._destroyed?reject():self.push(Buffer.from(chunk))?resolve():self._resumeFetch=resolve})},close:function(){resetTimers(!0),self._destroyed||self.push(null)},abort:function(err){resetTimers(!0),self._destroyed||self.emit("error",err)}});try{return void response.body.pipeTo(writable).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}catch(e){}}var reader=response.body.getReader();read()}else{self._xhr=xhr,self._pos=0,self.url=xhr.responseURL,self.statusCode=xhr.status,self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);if(headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self.headers[key]&&(self.headers[key]=[]),self.headers[key].push(matches[2])):void 0===self.headers[key]?self.headers[key]=matches[2]:self.headers[key]+=", "+matches[2],self.rawHeaders.push(matches[1],matches[2])}}),self._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self._charset=charsetMatch[1].toLowerCase())}self._charset||(self._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var self=this,resolve=self._resumeFetch;resolve&&(self._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(resetTimers){var self=this,xhr=self._xhr,response=null;switch(self._mode){case"text":if(response=xhr.responseText,response.length>self._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self.push(buffer)}else self.push(newData,self._charset);self._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self.push(Buffer.from(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self.push(Buffer.from(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self._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:189,"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 <https://feross.org/opensource> */module.exports=streamToBlob},{}],318:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<all.length;i++)dest=all[i],isStreamx(src)?src.pipe(dest,onerror):(errorHandle(src,!0,1<i,onerror),src.pipe(dest)),src=dest;if(done){let fin=!1;dest.on("finish",()=>{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<this.highWaterMark)?(this.stream._duplexState|=WRITE_QUEUED,!0):(this.stream._duplexState|=WRITE_QUEUED_AND_UNDRAINED,!1)}shift(){const data=this.queue.shift(),stream=this.stream;return this.buffered-=this.byteLength(data),0===this.buffered&&(stream._duplexState&=WRITE_NOT_QUEUED),data}end(data){"function"==typeof data?this.stream.once("finish",data):data!==void 0&&null!==data&&this.push(data),this.stream._duplexState=(this.stream._duplexState|WRITE_FINISHING)&WRITE_NON_PRIMARY}autoBatch(data,cb){const buffer=[],stream=this.stream;for(buffer.push(data);(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED_AND_ACTIVE;)buffer.push(stream._writableState.shift());return 0==(stream._duplexState&OPEN_STATUS)?void stream._writev(buffer,cb):cb(null)}update(){const stream=this.stream;for(;(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED;){const data=this.shift();stream._duplexState|=WRITE_ACTIVE_AND_SYNC,stream._write(data,this.afterWrite),stream._duplexState&=WRITE_NOT_SYNC}0==(stream._duplexState&WRITE_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&WRITE_FINISHING_STATUS)===WRITE_FINISHING?(stream._duplexState=(stream._duplexState|WRITE_ACTIVE)&WRITE_NOT_FINISHING,void stream._final(afterFinal.bind(this))):(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&WRITE_NEXT_TICK)||(this.stream._duplexState|=WRITE_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class ReadableState{constructor(stream,{highWaterMark=16384,map=null,mapReadable,byteLength,byteLengthReadable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthReadable||byteLength||defaultByteLength,this.map=mapReadable||map,this.pipeTo=null,this.afterRead=afterRead.bind(this),this.afterUpdateNextTick=updateReadNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&READ_DONE)}pipe(pipeTo,cb){if(null!==this.pipeTo)throw new Error("Can only pipe to one destination");if("function"!=typeof cb&&(cb=null),this.stream._duplexState|=READ_PIPE_DRAINED,this.pipeTo=pipeTo,this.pipeline=new Pipeline(this.stream,pipeTo,cb),cb&&this.stream.on("error",noop),isStreamx(pipeTo))pipeTo._writableState.pipeline=this.pipeline,cb&&pipeTo.on("error",noop),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline));else{const onerror=this.pipeline.done.bind(this.pipeline,pipeTo),onclose=this.pipeline.done.bind(this.pipeline,pipeTo,null);pipeTo.on("error",onerror),pipeTo.on("close",onclose),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline))}pipeTo.on("drain",afterDrain.bind(this)),this.stream.emit("piping",pipeTo),pipeTo.emit("pipe",this.stream)}push(data){const stream=this.stream;return null===data?(this.highWaterMark=0,stream._duplexState=(stream._duplexState|READ_ENDING)&READ_NON_PRIMARY_AND_PUSHED,!1):(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),stream._duplexState=(stream._duplexState|READ_QUEUED)&READ_PUSHED,this.buffered<this.highWaterMark)}shift(){const data=this.queue.shift();return this.buffered-=this.byteLength(data),0===this.buffered&&(this.stream._duplexState&=READ_NOT_QUEUED),data}unshift(data){let tail;const pending=[];for(;(tail=this.queue.shift())!==void 0;)pending.push(tail);this.push(data);for(let i=0;i<pending.length;i++)this.queue.push(pending[i])}read(){const stream=this.stream;if((stream._duplexState&READ_STATUS)===READ_QUEUED){const data=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data),data}return null}drain(){for(const stream=this.stream;(stream._duplexState&READ_STATUS)===READ_QUEUED&&0!=(stream._duplexState&READ_FLOWING);){const data=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data)}}update(){const stream=this.stream;for(this.drain();this.buffered<this.highWaterMark&&0==(stream._duplexState&SHOULD_NOT_READ);)stream._duplexState|=READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH,stream._read(this.afterRead),stream._duplexState&=READ_NOT_SYNC,0==(stream._duplexState&READ_ACTIVE)&&this.drain();(stream._duplexState&READ_READABLE_STATUS)===READ_EMIT_READABLE_AND_QUEUED&&(stream._duplexState|=READ_EMITTED_READABLE,stream.emit("readable")),0==(stream._duplexState&READ_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&READ_ENDING_STATUS)===READ_ENDING&&(stream._duplexState=(stream._duplexState|READ_DONE)&READ_NOT_ENDING,stream.emit("end"),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),null!==this.pipeTo&&this.pipeTo.end()),(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&READ_NEXT_TICK)||(this.stream._duplexState|=READ_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class TransformState{constructor(stream){this.data=null,this.afterTransform=afterTransform.bind(stream),this.afterFinal=null}}class Pipeline{constructor(src,dst,cb){this.from=src,this.to=dst,this.afterPipe=cb,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(stream,err){return err&&(this.error=err),stream===this.to&&(this.to=null,null!==this.from)?void(0!=(this.from._duplexState&READ_DONE)&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))):stream===this.from&&(this.from=null,null!==this.to)?void(0==(stream._duplexState&READ_DONE)&&this.to.destroy(this.error||new Error("Readable stream closed before ending"))):void(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null)}}class Stream extends EventEmitter{constructor(opts){super(),this._duplexState=0,this._readableState=null,this._writableState=null,opts&&(opts.open&&(this._open=opts.open),opts.destroy&&(this._destroy=opts.destroy),opts.predestroy&&(this._predestroy=opts.predestroy),opts.signal&&opts.signal.addEventListener("abort",abort.bind(this)))}_open(cb){cb(null)}_destroy(cb){cb(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return 0!=(this._duplexState&DESTROYED)}get destroying(){return 0!=(this._duplexState&DESTROY_STATUS)}destroy(err){0==(this._duplexState&DESTROY_STATUS)&&(!err&&(err=STREAM_DESTROYED),this._duplexState=(this._duplexState|DESTROYING)&NON_PRIMARY,null!==this._readableState&&(this._readableState.error=err,this._readableState.updateNextTick()),null!==this._writableState&&(this._writableState.error=err,this._writableState.updateNextTick()),this._predestroy())}on(name,fn){return null!==this._readableState&&("data"===name&&(this._duplexState|=READ_EMIT_DATA|READ_RESUMED,this._readableState.updateNextTick()),"readable"===name&&(this._duplexState|=READ_EMIT_READABLE,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===name&&(this._duplexState|=WRITE_EMIT_DRAIN,this._writableState.updateNextTick()),super.on(name,fn)}}class Readable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|WRITE_DONE,this._readableState=new ReadableState(this,opts),opts&&(opts.read&&(this._read=opts.read),opts.eagerOpen&&this.resume().pause())}_read(cb){cb(null)}pipe(dest,cb){return this._readableState.pipe(dest,cb),this._readableState.updateNextTick(),dest}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(data){return this._readableState.updateNextTick(),this._readableState.push(data)}unshift(data){return this._readableState.updateNextTick(),this._readableState.unshift(data)}resume(){return this._duplexState|=READ_RESUMED,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=READ_PAUSED,this}static _fromAsyncIterator(ite,opts){function push(data){data.done?rs.push(null):rs.push(data.value)}let destroy;const rs=new Readable({...opts,read(cb){ite.next().then(push).then(cb.bind(null,null)).catch(cb)},predestroy(){destroy=ite.return()},destroy(cb){return destroy?void destroy.then(cb.bind(null,null)).catch(cb):cb(null)}});return rs}static from(data,opts){if(isReadStreamx(data))return data;if(data[asyncIterator])return this._fromAsyncIterator(data[asyncIterator](),opts);Array.isArray(data)||(data=data===void 0?[]:[data]);let i=0;return new Readable({...opts,read(cb){this.push(i===data.length?null:data[i++]),cb(null)}})}static isBackpressured(rs){return 0!=(rs._duplexState&READ_BACKPRESSURE_STATUS)||rs._readableState.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":159,"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":190}],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<plain.length;){var current=plain[i];3<shiftIndex?(digit=current&255>>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<<shiftIndex|(i+1<plain.length?plain[i+1]:0)>>8-shiftIndex,i++):(digit=31&current>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i<encoded.length;i++)encoded[i]=61;return encoded},exports.decode=function(encoded){var shiftIndex=0,plainDigit=0,plainPos=0,plainChar;Buffer.isBuffer(encoded)||(encoded=new Buffer(encoded));for(var decoded=new Buffer(_Mathceil(5*encoded.length/8)),i=0;i<encoded.length&&!(61===encoded[i]);i++){var encodedByte=encoded[i]-48;if(encodedByte<byteTable.length)plainDigit=byteTable[encodedByte],3>=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.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],325:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;0<=msecs&&(item._idleTimeoutId=setTimeout(function onTimeout(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(2>arguments.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<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw new Error("Argument must be a Buffer")}},{buffer:101}],327:[function(require,module,exports){(function(process){(function(){/*! torrent-discovery. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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 <https://webtorrent.io/opensource> */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<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._cancellations.length||this._reservations<this._chunks){let min=this._reservations;for(;this._cancellations.length;)min=_Mathmin(min,this._cancellations.pop());return this._reservations=this._chunks,min}return-1}cancel(i){this.init()&&this._cancellations.push(i)}cancelRemaining(i){this.init()&&(this._reservations=i)}get(i){return this.init()?this._buffer[i]:null}set(i,data,source){if(!this.init())return!1;const len=data.length,blocks=_Mathceil(len/BLOCK_LENGTH);for(let j=0;j<blocks;j++)if(!this._buffer[i+j]){const offset=j*BLOCK_LENGTH,splitData=data.slice(offset,offset+BLOCK_LENGTH);this._buffered++,this._buffer[i+j]=splitData,this.missing-=splitData.length,this.sources.includes(source)||this.sources.push(source)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const buffer=Buffer.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,buffer}init(){return!this._flushed&&(!!this._buffer||(this._buffer=Array(this._chunks),this._cancellations=[],this.sources=[],!0))}}Object.defineProperty(Piece,"BLOCK_LENGTH",{value:16384}),module.exports=Piece}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],329:[function(require,module,exports){(function(Buffer){(function(){var isTypedArray=require("is-typedarray").strict;module.exports=function typedarrayToBuffer(arr){if(isTypedArray(arr)){var buf=Buffer.from(arr.buffer);return arr.byteLength!==arr.buffer.byteLength&&(buf=buf.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)),buf}return Buffer.from(arr)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"is-typedarray":197}],330:[function(require,module,exports){var bufferAlloc=require("buffer-alloc"),UINT_32_MAX=_Mathpow(2,32);exports.encodingLength=function(){return 8},exports.encode=function(num,buf,offset){buf||(buf=bufferAlloc(8)),offset||(offset=0);var top=_Mathfloor(num/UINT_32_MAX),rem=num-top*UINT_32_MAX;return buf.writeUInt32BE(top,offset),buf.writeUInt32BE(rem,offset+4),buf},exports.decode=function(buf,offset){offset||(offset=0);var top=buf.readUInt32BE(offset),rem=buf.readUInt32BE(offset+4);return top*UINT_32_MAX+rem},exports.encode.bytes=8,exports.decode.bytes=8},{"buffer-alloc":98}],331:[function(require,module,exports){function remove(arr,i){if(!(i>=arr.length||0>i)){var last=arr.pop();if(i<arr.length){var tmp=arr[i];return arr[i]=last,tmp}return last}}module.exports=remove},{}],332:[function(require,module,exports){"use strict";function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}var punycode=require("punycode"),util=require("./util");exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">","\"","`"," ","\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&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/"),url=uSplit.join(splitter);var rest=url;if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=simplePathPattern.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],this.query=parseQueryString?querystring.parse(this.search.substr(1)):this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0,hec;i<hostEndingChars.length;i++)hec=rest.indexOf(hostEndingChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0,hec;i<nonHostChars.length;i++)hec=rest.indexOf(nonHostChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length,part;i<l;i++)if(part=hostparts[i],part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)newpart+=127<part.charCodeAt(j)?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}this.hostname=255<this.hostname.length?"":this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length,ae;i<l;i++)if(ae=autoEscape[i],-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1===qm?parseQueryString&&(this.search="",this.query={}):(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):!host&&(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0,tkey;tk<tkeys.length;tk++)tkey=tkeys[tk],result[tkey]=this[tkey];if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0,rkey;rk<rkeys.length;rk++)rkey=rkeys[rk],"protocol"!==rkey&&(result[rkey]=relative[rkey]);return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0,k;v<keys.length;v++)k=keys[v],result[k]=relative[k];return result.href=result.format(),result}if(result.protocol=relative.protocol,!relative.host&&!hostlessProtocol[relative.protocol]){for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),2>relPath.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<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.path=result.search?"/"+result.search:null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||1<srcPath.length)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;0<=i;i--)last=srcPath[i],"."===last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&0<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":333,punycode:255,querystring:258}],333:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],334:[function(require,module,exports){(function(Buffer){(function(){/*! ut_metadata. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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||0>=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<this._remainingRejects&&this._fetching?(this._request(piece),this._remainingRejects-=1):this.emit("warning",new Error("Peer sent \"reject\" too much"))}_requestPieces(){if(this._fetching){this.metadata=Buffer.alloc(this._metadataSize);for(let piece=0;piece<this._numPieces;piece++)this._request(piece)}}_checkDone(){let done=!0;for(let piece=0;piece<this._numPieces;piece++)if(!this._bitfield.get(piece)){done=!1;break}if(done){const success=this.setMetadata(this.metadata);success||this._failedMetadata()}}_failedMetadata(){this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),this._remainingRejects-=this._numPieces,0<this._remainingRejects?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return utMetadata.prototype.name="ut_metadata",utMetadata}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:47,bitfield:51,buffer:101,debug:122,events:156,"simple-sha1":303}],335:[function(require,module,exports){(function(Buffer){(function(){/*! ut_pex. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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<PEX_MIN_ALLOWED_INTERVAL)return this.reset(),this._wire.destroy(),this.emit("warning",new Error("Peer disconnected for sending PEX messages too frequently"));this._lastMessageTimestamp=currentMessageTimestamp;let message;try{message=bencode.decode(buf),message.added&&compact2string.multi(message.added).forEach((peer,idx)=>{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}],336:[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)},{}],337:[function(require,module,exports){arguments[4][34][0].apply(exports,arguments)},{dup:34}],338:[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":191,"is-generator-function":195,"is-typed-array":196,"which-typed-array":342}],339:[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;i<l;++i)hasOwnProperty(value,i+"")?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,i+"",!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?desc.set?str=ctx.stylize("[Getter/Setter]","special"):str=ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(0>ctx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1<str.indexOf("\n")&&(array?str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,"\"").replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,0<=cur.indexOf("\n")&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return 60<length?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"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<arguments.length;i++)args.push(arguments[i]);var maybeCb=args.pop();if("function"!=typeof maybeCb)throw new TypeError("The last argument must be of type Function");var self=this,cb=function(){return maybeCb.apply(self,arguments)};original.apply(this,args).then(function(ret){process.nextTick(cb.bind(null,null,ret))},function(rej){process.nextTick(callbackifyOnRejected.bind(null,rej,cb))})}if("function"!=typeof original)throw new TypeError("The \"original\" argument must be of type Function");return Object.setPrototypeOf(callbackified,Object.getPrototypeOf(original)),Object.defineProperties(callbackified,getOwnPropertyDescriptors(original)),callbackified}var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function getOwnPropertyDescriptors(obj){for(var keys=Object.keys(obj),descriptors={},i=0;i<keys.length;i++)descriptors[keys[i]]=Object.getOwnPropertyDescriptor(obj,keys[i]);return descriptors},formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i<arguments.length;i++)objects.push(inspect(arguments[i]));return objects.join(" ")}for(var i=1,args=arguments,len=args.length,str=(f+"").replace(formatRegExp,function(x){if("%%"===x)return"%";if(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<len;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);else process.traceDeprecation?console.trace(msg):console.error(msg);warned=!0}return fn.apply(this,arguments)}if("undefined"!=typeof process&&!0===process.noDeprecation)return fn;if("undefined"==typeof process)return function(){return exports.deprecate(fn,msg).apply(this,arguments)};var warned=!1;return deprecated};var debugs={},debugEnvRegex=/^$/;if(process.env.NODE_DEBUG){var debugEnv=process.env.NODE_DEBUG;debugEnv=debugEnv.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),debugEnvRegex=new RegExp("^"+debugEnv+"$","i")}exports.debuglog=function(set){if(set=set.toUpperCase(),!debugs[set])if(debugEnvRegex.test(set)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.types=require("./support/types"),exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.types.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.types.isDate=isDate,exports.isError=isError,exports.types.isNativeError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin};var kCustomPromisifiedSymbol="undefined"==typeof Symbol?void 0:Symbol("util.promisify.custom");exports.promisify=function promisify(original){function fn(){for(var promise=new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject}),args=[],i=0,promiseResolve,promiseReject;i<arguments.length;i++)args.push(arguments[i]);args.push(function(err,value){err?promiseReject(err):promiseResolve(value)});try{original.apply(this,args)}catch(err){promiseReject(err)}return promise}if("function"!=typeof original)throw new TypeError("The \"original\" argument must be of type Function");if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if("function"!=typeof fn)throw new TypeError("The \"util.promisify.custom\" argument must be of type Function");return Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),fn}return Object.setPrototypeOf(fn,Object.getPrototypeOf(original)),kCustomPromisifiedSymbol&&Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(fn,getOwnPropertyDescriptors(original))},exports.promisify.custom=kCustomPromisifiedSymbol,exports.callbackify=callbackify}).call(this)}).call(this,require("_process"))},{"./support/isBuffer":337,"./support/types":338,_process:246,inherits:189}],340:[function(require,module,exports){(function(Buffer){(function(){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream"),FIND_MOOV_SEEK_SIZE=4096;class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"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<FIND_MOOV_SEEK_SIZE?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i<traks.length;i++){const trak=traks[i],stbl=trak.mdia.minf.stbl,stsdEntry=stbl.stsd.entries[0],handlerType=trak.mdia.hdlr.handlerType;let codec,mime;if("vide"===handlerType&&"avc1"===stsdEntry.type){if(this._hasVideo)continue;this._hasVideo=!0,codec="avc1",stsdEntry.avcC&&(codec+=`.${stsdEntry.avcC.mimeCodec}`),mime=`video/mp4; codecs="${codec}"`}else if("soun"===handlerType&&"mp4a"===stsdEntry.type){if(this._hasAudio)continue;this._hasAudio=!0,codec="mp4a",stsdEntry.esds&&stsdEntry.esds.mimeCodec&&(codec+=`.${stsdEntry.esds.mimeCodec}`),mime=`audio/mp4; codecs="${codec}"`}else continue;const samples=[];let sample=0,sampleInChunk=0,chunk=0,offsetInChunk=0,sampleToChunkIndex=0,dts=0;const decodingTimeEntry=new RunLengthIndex(stbl.stts.entries);let presentationOffsetEntry=null;stbl.ctts&&(presentationOffsetEntry=new RunLengthIndex(stbl.ctts.entries));for(let syncSampleIndex=0;!0;){var currChunkEntry=stbl.stsc.entries[sampleToChunkIndex];const size=stbl.stsz.entries[sample],duration=decodingTimeEntry.value.duration,presentationOffset=presentationOffsetEntry?presentationOffsetEntry.value.compositionOffset:0;let sync=!0;stbl.stss&&(sync=stbl.stss.entries[syncSampleIndex]===sample+1);const chunkOffsetTable=stbl.stco||stbl.co64;if(samples.push({size,duration,dts,presentationOffset,sync,offset:offsetInChunk+chunkOffsetTable.entries[chunk]}),sample++,sample>=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<startOffset)&&(startOffset=fragment.ranges[0].start);const writeFragment=frag=>{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.samples.length;currSample++){const sample=currTrack.samples[currSample];if(sample.sync&&sample.dts-startDts>=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;j<lastSample;j++){const currSample=currTrack.samples[j];0>currSample.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":223,"mp4-stream":226,"range-slice-stream":265}],341:[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":340,mediasource:211,pump:254}],342:[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":161,"has-tostringtag/shams":169,"is-typed-array":196}],343:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];var ret=fn.apply(this,args),cb=args[args.length-1];return"function"==typeof ret&&ret!==cb&&Object.keys(cb).forEach(function(k){ret[k]=cb[k]}),ret}if(fn&&cb)return wrappy(fn)(cb);if("function"!=typeof fn)throw new TypeError("need wrapper function");return Object.keys(fn).forEach(function(k){wrapper[k]=fn[k]}),wrapper}module.exports=wrappy},{}],344:[function(require,module,exports){function extend(){for(var target={},i=0,source;i<arguments.length;i++)for(var key in source=arguments[i],source)hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target}module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty},{}],345:[function(require,module,exports){module.exports={version:"1.8.21"}},{}],346:[function(require,module,exports){(function(Buffer){(function(){function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}/*! webtorrent. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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)}),cb(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 void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},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":345,"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}]},{},[346])(346)}); \ 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;i<arr.length;i++){var range=arr[i].split("-"),start=parseInt(range[0],10),end=parseInt(range[1],10);(isNaN(start)?(start=size-end,end=size-1):isNaN(end)&&(end=size-1),end>size-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;i<ordered.length;i++){var range=ordered[i],current=ordered[j];range.start>current.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;i<N;i++)s[i]=i;return s}function seed(key){if(void 0===key){key=Array(N);for(var k=0;k<N;k++)key[k]=_Mathfloor(Math.random()*N)}else if("string"==typeof key)key=""+key,key=key.split("").map(function(c){return c.charCodeAt(0)%N});else if(!Array.isArray(key))throw new TypeError("invalid seed key specified");else if(!key.every(function(v){return"number"==typeof v&&v===(0|v)}))throw new TypeError("invalid seed key specified: not array of integers");for(var keylen=key.length,s=identityPermutation(),j=0,i=0;i<N;i++){j=(j+s[i]+key[i%keylen])%N;var tmp=s[i];s[i]=s[j],s[j]=tmp}return s}function RC4(key){this.s=seed(key),this.i=0,this.j=0}return RC4.prototype.randomNative=function(){this.i=(this.i+1)%N,this.j=(this.j+this.s[this.i])%N;var tmp=this.s[this.i];this.s[this.i]=this.s[this.j],this.s[this.j]=tmp;var k=this.s[(this.s[this.i]+this.s[this.j])%N];return k},RC4.prototype.randomUInt32=function(){var a=this.randomByte(),b=this.randomByte(),c=this.randomByte(),d=this.randomByte();return 256*(256*(256*a+b)+c)+d},RC4.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},RC4.prototype.random=function(){var a,b;if(1===arguments.length)a=0,b=arguments[0];else if(2===arguments.length)a=arguments[0],b=arguments[1];else throw new TypeError("random takes one or two integer arguments");if(!isInteger(a)||!isInteger(b))throw new TypeError("random takes one or two integer arguments");return a+this.randomUInt32()%(b-a+1)},RC4.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},RC4.prototype.setState=function(state){var s=state.s,i=state.i,j=state.j;if(!(i===(0|i)&&0<=i&&i<N))throw new Error("state.i should be integer [0, "+(N-1)+"]");if(!(j===(0|j)&&0<=j&&j<N))throw new Error("state.j should be integer [0, "+(N-1)+"]");if(!Array.isArray(s)||s.length!==N)throw new Error("state should be array of length "+N);for(var k=0;k<N;k++)if(-1===s.indexOf(k))throw new Error("state should be permutation of 0.."+(N-1)+": "+k+" is missing");this.i=i,this.j=j,this.s=s.slice()},RC4}function toHex(n){return 10>n?_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+""}),2<len?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(expected+"")}function startsWith(str,search,pos){return str.substr(!pos||0>pos?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<keys.length;v++)method=keys[v],Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method]);Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this)}).call(this,require("_process"))},{"./_stream_readable":270,"./_stream_writable":272,_process:246,inherits:189}],269:[function(require,module,exports){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform");require("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":271,inherits:189}],270:[function(require,module,exports){(function(process,global){(function(){"use strict";function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(!StringDecoder&&(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else{var er;if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(!(state.objectMode||chunk&&0<chunk.length))addToFront||(state.reading=!1,maybeReadMore(stream,state));else if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return 1073741824<=n?n=1073741824:(n--,n|=n>>>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.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self){var state=self._readableState;state.readableListening=0<self.listenerCount("readable"),state.resumeScheduled&&!state.paused?state.flowing=!0:0<self.listenerCount("data")&&self.resume()}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){if(0===state.length)return null;var ret;return state.objectMode?ret=state.buffer.shift():!n||n>=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<l;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter,EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},debugUtil=require("util"),debug;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var BufferList=require("./internal/streams/buffer_list"),destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,StringDecoder,createReadableStreamAsyncIterator,from;require("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&this._readableState.destroyed},set:function set(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var state=this._readableState,skipChunkCheck;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this};var MAX_HWM=1073741824;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0===state.highWaterMark?0<state.length:state.length>=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<state.highWaterMark)&&(doRead=!0,debug("length less than watermark",doRead)),state.ended||state.reading?(doRead=!1,debug("reading or ended",doRead)):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,!state.reading&&(n=howMuchToRead(nOrig,state)));var ret;return ret=0<n?fromList(n,state):null,null===ret?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(!state.ended&&(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||1<state.pipesCount&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=0<this.listenerCount("readable"),!1!==state.flowing&&this.resume()):"readable"==ev&&!state.endEmitted&&!state.readableListening&&(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):!state.reading&&process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){if((debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),!(state.objectMode&&(null===chunk||void 0===chunk)))&&(state.objectMode||chunk&&chunk.length)){var ret=_this.push(chunk);ret||(paused=!0,stream.pause())}}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function get(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function get(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function get(){return this._readableState.flowing},set:function set(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function get(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":267,"./_stream_duplex":268,"./internal/streams/async_iterator":273,"./internal/streams/buffer_list":274,"./internal/streams/destroy":275,"./internal/streams/from":277,"./internal/streams/state":279,"./internal/streams/stream":280,_process:246,buffer:101,events:156,inherits:189,"string_decoder/":321,util:66}],271:[function(require,module,exports){"use strict";function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){return this instanceof Transform?void(Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)):new Transform(options)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}module.exports=Transform;var _require$codes=require("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require("./_stream_duplex");require("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":267,"./_stream_duplex":268,inherits:189}],272:[function(require,module,exports){(function(process,global){(function(){"use strict";function WriteReq(chunk,encoding,cb){this.chunk=chunk,this.encoding=encoding,this.callback=cb,this.next=null}function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){Duplex=Duplex||require("./_stream_duplex");var isDuplex=this instanceof Duplex;return isDuplex||realHasInstance.call(Writable,this)?void(this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)):new Writable(options)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"!=typeof chunk&&!state.objectMode&&(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}module.exports=Writable;var Duplex;Writable.WritableState=WritableState;var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;require("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function writableStateBufferGetter(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||!(this!==Writable)&&object&&object._writableState instanceof WritableState}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":!encoding&&(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,!state.writing&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest&&clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":267,"./_stream_duplex":268,"./internal/streams/destroy":275,"./internal/streams/state":279,"./internal/streams/stream":280,_process:246,buffer:101,inherits:189,"util-deprecate":336}],273:[function(require,module,exports){(function(process){(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){return iter[kEnded]?void resolve(createIterResult(void 0,!0)):void iter[kHandlePromise](resolve,reject)},reject)}}var finished=require("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream"),AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var _this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise],promise;if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},_defineProperty(_Object$setPrototypeO,Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function _return(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){return err?void reject(err):void resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype),createReadableStreamAsyncIterator=function createReadableStreamAsyncIterator(stream){var iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_Object$create={},_defineProperty(_Object$create,kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create)),_Object$create;return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];return null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),void(iterator[kError]=err)}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator},_Object$setPrototypeO;module.exports=createReadableStreamAsyncIterator}).call(this)}).call(this,require("_process"))},{"./end-of-stream":276,_process:246}],274:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1,source;i<arguments.length;i++)source=null==arguments[i]?{}:arguments[i],i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))});return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}var _require=require("buffer"),Buffer=_require.Buffer,_require2=require("util"),inspect=_require2.inspect,custom=inspect&&inspect.custom||"inspect";module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};0<this.length?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(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 n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):n===this.head.data.length?ret=this.shift():ret=hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.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=i<streams.length-1,writing=0<i;return destroyer(stream,reading,writing,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})}),error;return streams.reduce(pipe)}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=pipeline},{"../../../errors":267,"./end-of-stream":276}],279:[function(require,module,exports){"use strict";function highWaterMarkFrom(options,isDuplex,duplexKey){return null==options.highWaterMark?isDuplex?options[duplexKey]:null:options.highWaterMark}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&_Mathfloor(hwm)===hwm)||0>hwm){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<n;i++)j=_Mathfloor(Math.random()*(aLen+bLen)),j<aLen?(result[i]=a[j].record,swap(a,j,--aLen)):(j-=aLen,result[i]=b[j].record,swap(b,j,--bLen));return result},RecordCache.prototype._gcAuto=function(){this._gced||this._gc(),this._gced=!1},RecordCache.prototype._gc=function(){this._onstale&&0<this._stale.size&&this._onstale(this._stale),this._stale=this._fresh,this._fresh=new RecordStore,this._gced=!0},RecordCache.prototype.clear=function(){this._gc(),this._gc()},RecordCache.prototype.destroy=function(){this.clear(),clearInterval(this._interval),this._interval=null}},{b4a:37}],283:[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":284,debug:122,"is-ascii":192,mediasource:211,path:238,"stream-to-blob-url":316,videostream:341}],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<<n|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<this._blockOffset&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.alloc?Buffer.alloc(20):new Buffer(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer},module.exports=RIPEMD160},{buffer:101,"hash-base":171,inherits:189}],286:[function(require,module,exports){function runParallelLimit(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next<len){let key;keys?(key=keys[next],next+=1,tasks[key](function(err,result){each(key,err,result)})):(key=next,next+=1,tasks[key](function(err,result){each(key,err,result)}))}}if("number"!=typeof limit)throw new Error("second argument must be a Number");let isSync=!0,results,len,pending,keys,isErrored,next;Array.isArray(tasks)?(results=[],pending=len=tasks.length):(keys=Object.keys(tasks),results={},pending=len=keys.length),next=limit,pending?keys?keys.some(function(key,i){return tasks[key](function(err,result){each(key,err,result)}),i===limit-1}):tasks.some(function(task,i){return task(function(err,result){each(i,err,result)}),i===limit-1}):done(null),isSync=!1}module.exports=runParallelLimit;const queueMicrotask=require("queue-microtask")},{"queue-microtask":259}],287:[function(require,module,exports){function runParallel(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}let isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}module.exports=runParallel;const queueMicrotask=require("queue-microtask")},{"queue-microtask":259}],288:[function(require,module,exports){(function(process){(function(){function runSeries(tasks,cb){function done(err){function end(){cb&&cb(err,results)}isSync?process.nextTick(end):end()}function each(err,result){results.push(result),++current>=tasks.length||err?done(err):tasks[current](each)}var current=0,results=[],isSync=!0;0<tasks.length?tasks[0](each):done(null),isSync=!1}/*! run-series. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<len%64;len+=1);return len},padZeroes=function(bin,len){var h8=new Uint8Array(bin.buffer),om=len%4,align=len-om;switch(om){case 0:h8[align+3]=0;case 1:h8[align+2]=0;case 2:h8[align+1]=0;case 3:h8[align+0]=0;}for(var i=(len>>2)+1;i<bin.length;i++)bin[i]=0},padData=function(bin,chunkLen,msgLen){bin[chunkLen>>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<chunkSize%64)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=chunkSize,this._padMaxChunkLen=padlen(chunkSize),this._heap=new ArrayBuffer(ceilHeapSize(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new RushaCore({Int32Array:Int32Array},{},this._heap)}return Rusha.prototype._initState=function _initState(heap,padMsgLen){this._offset=0;var io=new Int32Array(heap,padMsgLen+320,5);io[0]=1732584193,io[1]=-271733879,io[2]=-1732584194,io[3]=271733878,io[4]=-1009589776},Rusha.prototype._padChunk=function _padChunk(chunkLen,msgLen){var padChunkLen=padlen(chunkLen),view=new Int32Array(this._heap,0,padChunkLen>>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;chunkOffset<chunkLen;)inputLen=_Mathmin(chunkLen-chunkOffset,this._maxChunkLen-turnOffset),this._write(chunk,chunkOffset,inputLen,turnOffset),turnOffset+=inputLen,chunkOffset+=inputLen,turnOffset===this._maxChunkLen&&(this._core.hash(this._maxChunkLen,this._padMaxChunkLen),turnOffset=0);return this},Rusha.prototype.getState=function getState(){var turnOffset=this._offset%this._maxChunkLen,heap=void 0;if(!turnOffset){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);heap=io.buffer.slice(io.byteOffset,io.byteOffset+io.byteLength)}else heap=this._heap.slice(0);return{offset:this._offset,heap:heap}},Rusha.prototype.setState=function setState(state){if(this._offset=state.offset,20===state.heap.byteLength){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);io.set(new Int32Array(state.heap))}else this._h32.set(new Int32Array(state.heap));return this},Rusha.prototype.rawEnd=function rawEnd(){var msgLen=this._offset,chunkLen=msgLen%this._maxChunkLen,padChunkLen=this._padChunk(chunkLen,msgLen);this._core.hash(padChunkLen,this._padMaxChunkLen);var result=getRawDigest(this._heap,this._padMaxChunkLen);return this._initState(this._heap,this._padMaxChunkLen),result},Rusha.prototype.end=function end(){return toHex(this.rawEnd().buffer)},Rusha}();module.exports=Rusha,module.exports._core=RushaCore},function(module,exports){for(var precomputedHex=Array(256),i=0;256>i;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<res.length;_i++)res[_i]=precomputedHex[binarray[_i]];return res.join("")},module.exports.ceilHeapSize=function(v){var p=0;if(65536>=v)return 65536;if(16777216>v)for(p=1;p<v;p<<=1);else for(p=16777216;p<v;p+=16777216);return p},module.exports.isDedicatedWorkerScope=function(self){var isRunningInWorker="WorkerGlobalScope"in self&&self instanceof self.WorkerGlobalScope,isRunningInSharedWorker="SharedWorkerGlobalScope"in self&&self instanceof self.SharedWorkerGlobalScope,isRunningInServiceWorker="ServiceWorkerGlobalScope"in self&&self instanceof self.ServiceWorkerGlobalScope;return isRunningInWorker&&!isRunningInSharedWorker&&!isRunningInServiceWorker}},function(module,exports,__webpack_require__){module.exports=function(){var Rusha=__webpack_require__(0),hashData=function(hasher,data,cb){try{return cb(null,hasher.digest(data))}catch(e){return cb(e)}},hashFile=function(hasher,readTotal,blockSize,file,cb){var reader=new self.FileReader;reader.onloadend=function onloadend(){if(reader.error)return cb(reader.error);var buffer=reader.result;readTotal+=reader.result.byteLength;try{hasher.append(buffer)}catch(e){return void cb(e)}readTotal<file.size?hashFile(hasher,readTotal,blockSize,file,cb):cb(null,hasher.end())},reader.readAsArrayBuffer(file.slice(readTotal,readTotal+blockSize))},workerBehaviourEnabled=!0;return self.onmessage=function(event){if(workerBehaviourEnabled){var data=event.data.data,file=event.data.file,id=event.data.id;if("undefined"!=typeof id&&(file||data)){var blockSize=event.data.blockSize||4194304,hasher=new Rusha(blockSize);hasher.resetState();var done=function(err,hash){err?self.postMessage({id:id,error:err.name}):self.postMessage({id:id,hash:hash})};data&&hashData(hasher,data,done),file&&hashFile(hasher,0,blockSize,file,done)}}},function(){workerBehaviourEnabled=!1}}},function(module,exports,__webpack_require__){var work=__webpack_require__(4),Rusha=__webpack_require__(0),createHash=__webpack_require__(7),runWorker=__webpack_require__(2),_require=__webpack_require__(1),isDedicatedWorkerScope=_require.isDedicatedWorkerScope,isRunningInDedicatedWorker="undefined"!=typeof self&&isDedicatedWorkerScope(self);Rusha.disableWorkerBehaviour=isRunningInDedicatedWorker?runWorker():function(){},Rusha.createWorker=function(){var worker=work(2),terminate=worker.terminate;return worker.terminate=function(){URL.revokeObjectURL(worker.objectURL),terminate.call(worker)},worker},Rusha.createHash=createHash,module.exports=Rusha},function(module,exports,__webpack_require__){function webpackBootstrapFunc(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={};__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.r=function(exports){Object.defineProperty(exports,"__esModule",{value:!0})},__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__.oe=function(err){throw console.error(err),err};var f=__webpack_require__(__webpack_require__.s=ENTRY_MODULE);return f.default||f}function quoteRegExp(str){return(str+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function getModuleDependencies(sources,module,queueName){var retval={};retval[queueName]=[];var fnString=module.toString(),wrapperSignature=fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!wrapperSignature)return retval;for(var webpackRequireName=wrapperSignature[1],re=new RegExp("(\\\\n|\\W)"+quoteRegExp(webpackRequireName)+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g"),match;match=re.exec(fnString);)"dll-reference"!==match[3]&&retval[queueName].push(match[3]);for(re=new RegExp("\\("+quoteRegExp(webpackRequireName)+"\\(\"(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))\"\\)\\)\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");match=re.exec(fnString);)sources[match[2]]||(retval[queueName].push(match[1]),sources[match[2]]=__webpack_require__(match[1]).m),retval[match[2]]=retval[match[2]]||[],retval[match[2]].push(match[4]);return retval}function hasValuesInQueues(queues){var keys=Object.keys(queues);return keys.reduce(function(hasValues,key){return hasValues||0<queues[key].length},!1)}function getRequiredModules(sources,moduleId){for(var modulesQueue={main:[moduleId]},requiredModules={main:[]},seenModules={main:{}};hasValuesInQueues(modulesQueue);)for(var queues=Object.keys(modulesQueue),i=0;i<queues.length;i++){var queueName=queues[i],queue=modulesQueue[queueName],moduleToCheck=queue.pop();if(seenModules[queueName]=seenModules[queueName]||{},!seenModules[queueName][moduleToCheck]&&sources[queueName][moduleToCheck]){seenModules[queueName][moduleToCheck]=!0,requiredModules[queueName]=requiredModules[queueName]||[],requiredModules[queueName].push(moduleToCheck);for(var newModules=getModuleDependencies(sources,sources[queueName][moduleToCheck],queueName),newModulesKeys=Object.keys(newModules),j=0;j<newModulesKeys.length;j++)modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]]||[],modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])}}return requiredModules}var moduleNameReqExp="[\\.|\\-|\\+|\\w|/|@]+",dependencyRegExp="\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";module.exports=function(moduleId,options){options=options||{};var sources={main:__webpack_require__.m},requiredModules=options.all?{main:Object.keys(sources)}:getRequiredModules(sources,moduleId),src="";Object.keys(requiredModules).filter(function(m){return"main"!==m}).forEach(function(module){for(var entryModule=0;requiredModules[module][entryModule];)entryModule++;requiredModules[module].push(entryModule),sources[module][entryModule]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",src=src+"var "+module+" = ("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(entryModule))+")({"+requiredModules[module].map(function(id){return""+JSON.stringify(id)+": "+sources[module][id].toString()}).join(",")+"});\n"}),src=src+"("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(moduleId))+")({"+requiredModules.main.map(function(id){return""+JSON.stringify(id)+": "+sources.main[id].toString()}).join(",")+"})(self);";var blob=new window.Blob([src],{type:"text/javascript"});if(options.bare)return blob;var URL=window.URL||window.webkitURL||window.mozURL||window.msURL,workerUrl=URL.createObjectURL(blob),worker=new window.Worker(workerUrl);return worker.objectURL=workerUrl,worker}},function(module,exports){module.exports=function RushaCore(stdlib$840,foreign$841,heap$842){"use asm";function hash$844(k$845,x$846){k$845|=0,x$846|=0;var i$847=0,j$848=0,y0$849=0,z0$850=0,y1$851=0,z1$852=0,y2$853=0,z2$854=0,y3$855=0,z3$856=0,y4$857=0,z4$858=0,t0$859=0,t1$860=0;for(y0$849=0|H$843[x$846+320>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function update(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},_createClass(Hash,[{key:"state",get:function(){return this._rusha.getState()},set:function(state){this._rusha.setState(state)}}]),Hash}();module.exports=function(){return new Hash}}])})},{}],290:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<length;){for(var assigned=accum%blockSize,remainder=_Mathmin(length-offset,blockSize-assigned),i=0;i<remainder;i++)block[assigned+i]=data[offset+i];accum+=remainder,offset+=remainder,0==accum%blockSize&&this._update(block)}return this._len+=length,this},Hash.prototype.digest=function(enc){var rem=this._len%this._blockSize;this._block[rem]=128,this._block.fill(0,rem+1),rem>=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:189,"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:189,"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:189,"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:189,"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:189,"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<b>>>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:189,"safe-buffer":290}],300:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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:186,once:231,querystring:258,"simple-concat":300,url:332}],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 <https://feross.org/opensource> */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<this._pc.getStats.length?this._pc.getStats(res=>{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":165,"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<l;i++)array[i]=s.charCodeAt(i);return array}function hex(buf){const l=buf.length,chars=[];for(let i=0;i<l;i++){const bite=buf[i];chars.push((bite>>>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 <https://feross.org/opensource> */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),0<rate&&chunksize>rate)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),0<rate&&chunksize>rate)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<index&&this.throttles.splice(index,1)}}module.exports=ThrottleGroup},{"./throttle":308,limiter:203}],308:[function(require,module,exports){const{EventEmitter}=require("events"),{Transform}=require("streamx"),{wait}=require("./utils");class Throttle extends Transform{constructor(opts={}){if(super(),"object"!=typeof opts)throw new Error("Options must be an object");const params=Object.assign({},opts);if(params.group&&!(params.group instanceof ThrottleGroup))throw new Error("Group must be an instanece of ThrottleGroup");else params.group||(params.group=new ThrottleGroup(params));this._setEnabled(params.enabled||params.group.enabled),this._group=params.group,this._emitter=new EventEmitter,this._destroyed=!1,this._group._addThrottle(this)}getEnabled(){return this._enabled}getGroup(){return this._group}_setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val}setEnabled(val){this._setEnabled(val),this._enabled?this._emitter.emit("enabled"):this._emitter.emit("disabled")}_transform(chunk,done){this._processChunk(chunk,done)}async _waitForTokens(amount){return new Promise((resolve,reject)=>{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(;0<slice.length;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await wait(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(slice.length)&&(await this._waitForTokens(slice.length),this._destroyed))return}catch(err){return done(err)}this.push(slice),pos+=chunksize,chunksize=this._areBothEnabled()?this._group.getChunksize():chunk.length-pos,slice=chunk.slice(pos,pos+chunksize)}return done()}destroy(...args){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...args)}}module.exports=Throttle;const ThrottleGroup=require("./throttle-group")},{"./throttle-group":307,"./utils":309,events:156,streamx:319}],309:[function(require,module,exports){function wait(time){return new Promise(resolve=>setTimeout(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.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],311:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter,inherits=require("inherits");inherits(Stream,EE),Stream.Readable=require("readable-stream/lib/_stream_readable.js"),Stream.Writable=require("readable-stream/lib/_stream_writable.js"),Stream.Duplex=require("readable-stream/lib/_stream_duplex.js"),Stream.Transform=require("readable-stream/lib/_stream_transform.js"),Stream.PassThrough=require("readable-stream/lib/_stream_passthrough.js"),Stream.finished=require("readable-stream/lib/internal/streams/end-of-stream.js"),Stream.pipeline=require("readable-stream/lib/internal/streams/pipeline.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:156,inherits:189,"readable-stream/lib/_stream_duplex.js":268,"readable-stream/lib/_stream_passthrough.js":269,"readable-stream/lib/_stream_readable.js":270,"readable-stream/lib/_stream_transform.js":271,"readable-stream/lib/_stream_writable.js":272,"readable-stream/lib/internal/streams/end-of-stream.js":276,"readable-stream/lib/internal/streams/pipeline.js":278}],312:[function(require,module,exports){(function(global){(function(){var ClientRequest=require("./lib/request"),response=require("./lib/response"),extend=require("xtend"),statusCodes=require("builtin-status-codes"),url=require("url"),http=exports;http.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},http.get=function get(opts,cb){var req=http.request(opts,cb);return req.end(),req},http.ClientRequest=ClientRequest,http.IncomingMessage=response.IncomingMessage,http.Agent=function(){},http.Agent.defaultMaxSockets=4,http.globalAgent=new http.Agent,http.STATUS_CODES=statusCodes,http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./lib/request":314,"./lib/response":315,"builtin-status-codes":102,url:332,xtend:344}],313:[function(require,module,exports){(function(global){(function(){function getXHR(){if(xhr!==void 0)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}function isFunction(value){return"function"==typeof value}exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController);var xhr;exports.arraybuffer=exports.fetch||checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),xhr=null}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],314:[function(require,module,exports){(function(process,global,Buffer){(function(){function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":"text"}function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}var capability=require("./capability"),inherits=require("inherits"),response=require("./response"),stream=require("readable-stream"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates,ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self),self._opts=opts,self._body=[],self._headers={},opts.auth&&self.setHeader("Authorization","Basic "+Buffer.from(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var useFetch=!0,preferBinary;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(!opts.mode||"default"===opts.mode||"prefer-fast"===opts.mode)preferBinary=!0;else throw new Error("Invalid value for opts.mode");self._mode=decideMode(preferBinary,useFetch),self._fetchTimer=null,self._socketTimeout=null,self._socketTimer=null,self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var self=this,lowerName=name.toLowerCase();-1!==unsafeHeaders.indexOf(lowerName)||(self._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self=this;if(!self._destroyed){var opts=self._opts;"timeout"in opts&&0!==opts.timeout&&self.setTimeout(opts.timeout);var headersObj=self._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=new Blob(self._body,{type:(headersObj["content-type"]||{}).value||""}));var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout"),self._fetchAbortController&&self._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response,self._resetTimers(!1),self._connect()},function(reason){self._resetTimers(!0),self._destroyed||self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,!0)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}"responseType"in xhr&&(xhr.responseType=self._mode),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();}},"moz-chunked-arraybuffer"===self._mode&&(xhr.onprogress=function(){self._onXHRProgress()}),xhr.onerror=function(){self._destroyed||(self._resetTimers(!0),self.emit("error",new Error("XHR error")))};try{xhr.send(body)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}}}},ClientRequest.prototype._onXHRProgress=function(){var self=this;self._resetTimers(!1);!statusValid(self._xhr)||self._destroyed||(!self._response&&self._connect(),self._response._onXHRProgress(self._resetTimers.bind(self)))},ClientRequest.prototype._connect=function(){var self=this;self._destroyed||(self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._resetTimers.bind(self)),self._response.on("error",function(err){self.emit("error",err)}),self.emit("response",self._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk),cb()},ClientRequest.prototype._resetTimers=function(done){var self=this;global.clearTimeout(self._socketTimer),self._socketTimer=null,done?(global.clearTimeout(self._fetchTimer),self._fetchTimer=null):self._socketTimeout&&(self._socketTimer=global.setTimeout(function(){self.emit("timeout")},self._socketTimeout))},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(err){var self=this;self._destroyed=!0,self._resetTimers(!0),self._response&&(self._response._destroyed=!0),self._xhr?self._xhr.abort():self._fetchAbortController&&self._fetchAbortController.abort(),err&&self.emit("error",err)},ClientRequest.prototype.end=function(data,encoding,cb){var self=this;"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(self,data,encoding,cb)},ClientRequest.prototype.setTimeout=function(timeout,cb){var self=this;cb&&self.once("timeout",cb),self._socketTimeout=timeout,self._resetTimers(!1)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":313,"./response":315,_process:246,buffer:101,inherits:189,"readable-stream":281}],315:[function(require,module,exports){(function(process,global,Buffer){(function(){var capability=require("./capability"),inherits=require("inherits"),stream=require("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,resetTimers){var self=this;if(stream.Readable.call(self),self._mode=mode,self.headers={},self.rawHeaders=[],self.trailers={},self.rawTrailers=[],self.on("end",function(){process.nextTick(function(){self.emit("close")})}),"fetch"===mode){function read(){reader.read().then(function(result){if(!self._destroyed)return resetTimers(result.done),result.done?void self.push(null):void(self.push(Buffer.from(result.value)),read())}).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}if(self._fetchResponse=response,self.url=response.url,self.statusCode=response.status,self.statusMessage=response.statusText,response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header,self.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return resetTimers(!1),new Promise(function(resolve,reject){self._destroyed?reject():self.push(Buffer.from(chunk))?resolve():self._resumeFetch=resolve})},close:function(){resetTimers(!0),self._destroyed||self.push(null)},abort:function(err){resetTimers(!0),self._destroyed||self.emit("error",err)}});try{return void response.body.pipeTo(writable).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}catch(e){}}var reader=response.body.getReader();read()}else{self._xhr=xhr,self._pos=0,self.url=xhr.responseURL,self.statusCode=xhr.status,self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);if(headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self.headers[key]&&(self.headers[key]=[]),self.headers[key].push(matches[2])):void 0===self.headers[key]?self.headers[key]=matches[2]:self.headers[key]+=", "+matches[2],self.rawHeaders.push(matches[1],matches[2])}}),self._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self._charset=charsetMatch[1].toLowerCase())}self._charset||(self._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var self=this,resolve=self._resumeFetch;resolve&&(self._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(resetTimers){var self=this,xhr=self._xhr,response=null;switch(self._mode){case"text":if(response=xhr.responseText,response.length>self._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self.push(buffer)}else self.push(newData,self._charset);self._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self.push(Buffer.from(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self.push(Buffer.from(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self._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:189,"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 <https://feross.org/opensource> */module.exports=streamToBlob},{}],318:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<all.length;i++)dest=all[i],isStreamx(src)?src.pipe(dest,onerror):(errorHandle(src,!0,1<i,onerror),src.pipe(dest)),src=dest;if(done){let fin=!1;dest.on("finish",()=>{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<this.highWaterMark)?(this.stream._duplexState|=WRITE_QUEUED,!0):(this.stream._duplexState|=WRITE_QUEUED_AND_UNDRAINED,!1)}shift(){const data=this.queue.shift(),stream=this.stream;return this.buffered-=this.byteLength(data),0===this.buffered&&(stream._duplexState&=WRITE_NOT_QUEUED),data}end(data){"function"==typeof data?this.stream.once("finish",data):data!==void 0&&null!==data&&this.push(data),this.stream._duplexState=(this.stream._duplexState|WRITE_FINISHING)&WRITE_NON_PRIMARY}autoBatch(data,cb){const buffer=[],stream=this.stream;for(buffer.push(data);(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED_AND_ACTIVE;)buffer.push(stream._writableState.shift());return 0==(stream._duplexState&OPEN_STATUS)?void stream._writev(buffer,cb):cb(null)}update(){const stream=this.stream;for(;(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED;){const data=this.shift();stream._duplexState|=WRITE_ACTIVE_AND_SYNC,stream._write(data,this.afterWrite),stream._duplexState&=WRITE_NOT_SYNC}0==(stream._duplexState&WRITE_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&WRITE_FINISHING_STATUS)===WRITE_FINISHING?(stream._duplexState=(stream._duplexState|WRITE_ACTIVE)&WRITE_NOT_FINISHING,void stream._final(afterFinal.bind(this))):(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&WRITE_NEXT_TICK)||(this.stream._duplexState|=WRITE_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class ReadableState{constructor(stream,{highWaterMark=16384,map=null,mapReadable,byteLength,byteLengthReadable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthReadable||byteLength||defaultByteLength,this.map=mapReadable||map,this.pipeTo=null,this.afterRead=afterRead.bind(this),this.afterUpdateNextTick=updateReadNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&READ_DONE)}pipe(pipeTo,cb){if(null!==this.pipeTo)throw new Error("Can only pipe to one destination");if("function"!=typeof cb&&(cb=null),this.stream._duplexState|=READ_PIPE_DRAINED,this.pipeTo=pipeTo,this.pipeline=new Pipeline(this.stream,pipeTo,cb),cb&&this.stream.on("error",noop),isStreamx(pipeTo))pipeTo._writableState.pipeline=this.pipeline,cb&&pipeTo.on("error",noop),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline));else{const onerror=this.pipeline.done.bind(this.pipeline,pipeTo),onclose=this.pipeline.done.bind(this.pipeline,pipeTo,null);pipeTo.on("error",onerror),pipeTo.on("close",onclose),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline))}pipeTo.on("drain",afterDrain.bind(this)),this.stream.emit("piping",pipeTo),pipeTo.emit("pipe",this.stream)}push(data){const stream=this.stream;return null===data?(this.highWaterMark=0,stream._duplexState=(stream._duplexState|READ_ENDING)&READ_NON_PRIMARY_AND_PUSHED,!1):(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),stream._duplexState=(stream._duplexState|READ_QUEUED)&READ_PUSHED,this.buffered<this.highWaterMark)}shift(){const data=this.queue.shift();return this.buffered-=this.byteLength(data),0===this.buffered&&(this.stream._duplexState&=READ_NOT_QUEUED),data}unshift(data){let tail;const pending=[];for(;(tail=this.queue.shift())!==void 0;)pending.push(tail);this.push(data);for(let i=0;i<pending.length;i++)this.queue.push(pending[i])}read(){const stream=this.stream;if((stream._duplexState&READ_STATUS)===READ_QUEUED){const data=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data),data}return null}drain(){for(const stream=this.stream;(stream._duplexState&READ_STATUS)===READ_QUEUED&&0!=(stream._duplexState&READ_FLOWING);){const data=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data)}}update(){const stream=this.stream;for(this.drain();this.buffered<this.highWaterMark&&0==(stream._duplexState&SHOULD_NOT_READ);)stream._duplexState|=READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH,stream._read(this.afterRead),stream._duplexState&=READ_NOT_SYNC,0==(stream._duplexState&READ_ACTIVE)&&this.drain();(stream._duplexState&READ_READABLE_STATUS)===READ_EMIT_READABLE_AND_QUEUED&&(stream._duplexState|=READ_EMITTED_READABLE,stream.emit("readable")),0==(stream._duplexState&READ_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&READ_ENDING_STATUS)===READ_ENDING&&(stream._duplexState=(stream._duplexState|READ_DONE)&READ_NOT_ENDING,stream.emit("end"),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),null!==this.pipeTo&&this.pipeTo.end()),(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&READ_NEXT_TICK)||(this.stream._duplexState|=READ_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class TransformState{constructor(stream){this.data=null,this.afterTransform=afterTransform.bind(stream),this.afterFinal=null}}class Pipeline{constructor(src,dst,cb){this.from=src,this.to=dst,this.afterPipe=cb,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(stream,err){return err&&(this.error=err),stream===this.to&&(this.to=null,null!==this.from)?void(0!=(this.from._duplexState&READ_DONE)&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))):stream===this.from&&(this.from=null,null!==this.to)?void(0==(stream._duplexState&READ_DONE)&&this.to.destroy(this.error||new Error("Readable stream closed before ending"))):void(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null)}}class Stream extends EventEmitter{constructor(opts){super(),this._duplexState=0,this._readableState=null,this._writableState=null,opts&&(opts.open&&(this._open=opts.open),opts.destroy&&(this._destroy=opts.destroy),opts.predestroy&&(this._predestroy=opts.predestroy),opts.signal&&opts.signal.addEventListener("abort",abort.bind(this)))}_open(cb){cb(null)}_destroy(cb){cb(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return 0!=(this._duplexState&DESTROYED)}get destroying(){return 0!=(this._duplexState&DESTROY_STATUS)}destroy(err){0==(this._duplexState&DESTROY_STATUS)&&(!err&&(err=STREAM_DESTROYED),this._duplexState=(this._duplexState|DESTROYING)&NON_PRIMARY,null!==this._readableState&&(this._readableState.error=err,this._readableState.updateNextTick()),null!==this._writableState&&(this._writableState.error=err,this._writableState.updateNextTick()),this._predestroy())}on(name,fn){return null!==this._readableState&&("data"===name&&(this._duplexState|=READ_EMIT_DATA|READ_RESUMED,this._readableState.updateNextTick()),"readable"===name&&(this._duplexState|=READ_EMIT_READABLE,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===name&&(this._duplexState|=WRITE_EMIT_DRAIN,this._writableState.updateNextTick()),super.on(name,fn)}}class Readable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|WRITE_DONE,this._readableState=new ReadableState(this,opts),opts&&(opts.read&&(this._read=opts.read),opts.eagerOpen&&this.resume().pause())}_read(cb){cb(null)}pipe(dest,cb){return this._readableState.pipe(dest,cb),this._readableState.updateNextTick(),dest}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(data){return this._readableState.updateNextTick(),this._readableState.push(data)}unshift(data){return this._readableState.updateNextTick(),this._readableState.unshift(data)}resume(){return this._duplexState|=READ_RESUMED,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=READ_PAUSED,this}static _fromAsyncIterator(ite,opts){function push(data){data.done?rs.push(null):rs.push(data.value)}let destroy;const rs=new Readable({...opts,read(cb){ite.next().then(push).then(cb.bind(null,null)).catch(cb)},predestroy(){destroy=ite.return()},destroy(cb){return destroy?void destroy.then(cb.bind(null,null)).catch(cb):cb(null)}});return rs}static from(data,opts){if(isReadStreamx(data))return data;if(data[asyncIterator])return this._fromAsyncIterator(data[asyncIterator](),opts);Array.isArray(data)||(data=data===void 0?[]:[data]);let i=0;return new Readable({...opts,read(cb){this.push(i===data.length?null:data[i++]),cb(null)}})}static isBackpressured(rs){return 0!=(rs._duplexState&READ_BACKPRESSURE_STATUS)||rs._readableState.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":159,"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":190}],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<plain.length;){var current=plain[i];3<shiftIndex?(digit=current&255>>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<<shiftIndex|(i+1<plain.length?plain[i+1]:0)>>8-shiftIndex,i++):(digit=31&current>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i<encoded.length;i++)encoded[i]=61;return encoded},exports.decode=function(encoded){var shiftIndex=0,plainDigit=0,plainPos=0,plainChar;Buffer.isBuffer(encoded)||(encoded=new Buffer(encoded));for(var decoded=new Buffer(_Mathceil(5*encoded.length/8)),i=0;i<encoded.length&&!(61===encoded[i]);i++){var encodedByte=encoded[i]-48;if(encodedByte<byteTable.length)plainDigit=byteTable[encodedByte],3>=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.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],325:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;0<=msecs&&(item._idleTimeoutId=setTimeout(function onTimeout(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(2>arguments.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<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw new Error("Argument must be a Buffer")}},{buffer:101}],327:[function(require,module,exports){(function(process){(function(){/*! torrent-discovery. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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 <https://webtorrent.io/opensource> */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<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._cancellations.length||this._reservations<this._chunks){let min=this._reservations;for(;this._cancellations.length;)min=_Mathmin(min,this._cancellations.pop());return this._reservations=this._chunks,min}return-1}cancel(i){this.init()&&this._cancellations.push(i)}cancelRemaining(i){this.init()&&(this._reservations=i)}get(i){return this.init()?this._buffer[i]:null}set(i,data,source){if(!this.init())return!1;const len=data.length,blocks=_Mathceil(len/BLOCK_LENGTH);for(let j=0;j<blocks;j++)if(!this._buffer[i+j]){const offset=j*BLOCK_LENGTH,splitData=data.slice(offset,offset+BLOCK_LENGTH);this._buffered++,this._buffer[i+j]=splitData,this.missing-=splitData.length,this.sources.includes(source)||this.sources.push(source)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const buffer=Buffer.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,buffer}init(){return!this._flushed&&(!!this._buffer||(this._buffer=Array(this._chunks),this._cancellations=[],this.sources=[],!0))}}Object.defineProperty(Piece,"BLOCK_LENGTH",{value:16384}),module.exports=Piece}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101}],329:[function(require,module,exports){(function(Buffer){(function(){var isTypedArray=require("is-typedarray").strict;module.exports=function typedarrayToBuffer(arr){if(isTypedArray(arr)){var buf=Buffer.from(arr.buffer);return arr.byteLength!==arr.buffer.byteLength&&(buf=buf.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)),buf}return Buffer.from(arr)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:101,"is-typedarray":197}],330:[function(require,module,exports){var bufferAlloc=require("buffer-alloc"),UINT_32_MAX=_Mathpow(2,32);exports.encodingLength=function(){return 8},exports.encode=function(num,buf,offset){buf||(buf=bufferAlloc(8)),offset||(offset=0);var top=_Mathfloor(num/UINT_32_MAX),rem=num-top*UINT_32_MAX;return buf.writeUInt32BE(top,offset),buf.writeUInt32BE(rem,offset+4),buf},exports.decode=function(buf,offset){offset||(offset=0);var top=buf.readUInt32BE(offset),rem=buf.readUInt32BE(offset+4);return top*UINT_32_MAX+rem},exports.encode.bytes=8,exports.decode.bytes=8},{"buffer-alloc":98}],331:[function(require,module,exports){function remove(arr,i){if(!(i>=arr.length||0>i)){var last=arr.pop();if(i<arr.length){var tmp=arr[i];return arr[i]=last,tmp}return last}}module.exports=remove},{}],332:[function(require,module,exports){"use strict";function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}var punycode=require("punycode"),util=require("./util");exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">","\"","`"," ","\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&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/"),url=uSplit.join(splitter);var rest=url;if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=simplePathPattern.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],this.query=parseQueryString?querystring.parse(this.search.substr(1)):this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0,hec;i<hostEndingChars.length;i++)hec=rest.indexOf(hostEndingChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0,hec;i<nonHostChars.length;i++)hec=rest.indexOf(nonHostChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length,part;i<l;i++)if(part=hostparts[i],part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)newpart+=127<part.charCodeAt(j)?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}this.hostname=255<this.hostname.length?"":this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length,ae;i<l;i++)if(ae=autoEscape[i],-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1===qm?parseQueryString&&(this.search="",this.query={}):(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):!host&&(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0,tkey;tk<tkeys.length;tk++)tkey=tkeys[tk],result[tkey]=this[tkey];if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0,rkey;rk<rkeys.length;rk++)rkey=rkeys[rk],"protocol"!==rkey&&(result[rkey]=relative[rkey]);return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0,k;v<keys.length;v++)k=keys[v],result[k]=relative[k];return result.href=result.format(),result}if(result.protocol=relative.protocol,!relative.host&&!hostlessProtocol[relative.protocol]){for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),2>relPath.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<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.path=result.search?"/"+result.search:null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||1<srcPath.length)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;0<=i;i--)last=srcPath[i],"."===last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&0<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":333,punycode:255,querystring:258}],333:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],334:[function(require,module,exports){(function(Buffer){(function(){/*! ut_metadata. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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||0>=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<this._remainingRejects&&this._fetching?(this._request(piece),this._remainingRejects-=1):this.emit("warning",new Error("Peer sent \"reject\" too much"))}_requestPieces(){if(this._fetching){this.metadata=Buffer.alloc(this._metadataSize);for(let piece=0;piece<this._numPieces;piece++)this._request(piece)}}_checkDone(){let done=!0;for(let piece=0;piece<this._numPieces;piece++)if(!this._bitfield.get(piece)){done=!1;break}if(done){const success=this.setMetadata(this.metadata);success||this._failedMetadata()}}_failedMetadata(){this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),this._remainingRejects-=this._numPieces,0<this._remainingRejects?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return utMetadata.prototype.name="ut_metadata",utMetadata}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:47,bitfield:51,buffer:101,debug:122,events:156,"simple-sha1":303}],335:[function(require,module,exports){(function(Buffer){(function(){/*! ut_pex. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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<PEX_MIN_ALLOWED_INTERVAL)return this.reset(),this._wire.destroy(),this.emit("warning",new Error("Peer disconnected for sending PEX messages too frequently"));this._lastMessageTimestamp=currentMessageTimestamp;let message;try{message=bencode.decode(buf),message.added&&compact2string.multi(message.added).forEach((peer,idx)=>{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}],336:[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)},{}],337:[function(require,module,exports){arguments[4][34][0].apply(exports,arguments)},{dup:34}],338:[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":191,"is-generator-function":195,"is-typed-array":196,"which-typed-array":342}],339:[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;i<l;++i)hasOwnProperty(value,i+"")?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,i+"",!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?desc.set?str=ctx.stylize("[Getter/Setter]","special"):str=ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(0>ctx.seen.indexOf(desc.value)?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),-1<str.indexOf("\n")&&(array?str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,"\"").replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,0<=cur.indexOf("\n")&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return 60<length?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"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<arguments.length;i++)args.push(arguments[i]);var maybeCb=args.pop();if("function"!=typeof maybeCb)throw new TypeError("The last argument must be of type Function");var self=this,cb=function(){return maybeCb.apply(self,arguments)};original.apply(this,args).then(function(ret){process.nextTick(cb.bind(null,null,ret))},function(rej){process.nextTick(callbackifyOnRejected.bind(null,rej,cb))})}if("function"!=typeof original)throw new TypeError("The \"original\" argument must be of type Function");return Object.setPrototypeOf(callbackified,Object.getPrototypeOf(original)),Object.defineProperties(callbackified,getOwnPropertyDescriptors(original)),callbackified}var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function getOwnPropertyDescriptors(obj){for(var keys=Object.keys(obj),descriptors={},i=0;i<keys.length;i++)descriptors[keys[i]]=Object.getOwnPropertyDescriptor(obj,keys[i]);return descriptors},formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i<arguments.length;i++)objects.push(inspect(arguments[i]));return objects.join(" ")}for(var i=1,args=arguments,len=args.length,str=(f+"").replace(formatRegExp,function(x){if("%%"===x)return"%";if(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<len;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);else process.traceDeprecation?console.trace(msg):console.error(msg);warned=!0}return fn.apply(this,arguments)}if("undefined"!=typeof process&&!0===process.noDeprecation)return fn;if("undefined"==typeof process)return function(){return exports.deprecate(fn,msg).apply(this,arguments)};var warned=!1;return deprecated};var debugs={},debugEnvRegex=/^$/;if(process.env.NODE_DEBUG){var debugEnv=process.env.NODE_DEBUG;debugEnv=debugEnv.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),debugEnvRegex=new RegExp("^"+debugEnv+"$","i")}exports.debuglog=function(set){if(set=set.toUpperCase(),!debugs[set])if(debugEnvRegex.test(set)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.types=require("./support/types"),exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.types.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.types.isDate=isDate,exports.isError=isError,exports.types.isNativeError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin};var kCustomPromisifiedSymbol="undefined"==typeof Symbol?void 0:Symbol("util.promisify.custom");exports.promisify=function promisify(original){function fn(){for(var promise=new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject}),args=[],i=0,promiseResolve,promiseReject;i<arguments.length;i++)args.push(arguments[i]);args.push(function(err,value){err?promiseReject(err):promiseResolve(value)});try{original.apply(this,args)}catch(err){promiseReject(err)}return promise}if("function"!=typeof original)throw new TypeError("The \"original\" argument must be of type Function");if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if("function"!=typeof fn)throw new TypeError("The \"util.promisify.custom\" argument must be of type Function");return Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),fn}return Object.setPrototypeOf(fn,Object.getPrototypeOf(original)),kCustomPromisifiedSymbol&&Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(fn,getOwnPropertyDescriptors(original))},exports.promisify.custom=kCustomPromisifiedSymbol,exports.callbackify=callbackify}).call(this)}).call(this,require("_process"))},{"./support/isBuffer":337,"./support/types":338,_process:246,inherits:189}],340:[function(require,module,exports){(function(Buffer){(function(){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream"),FIND_MOOV_SEEK_SIZE=4096;class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"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<FIND_MOOV_SEEK_SIZE?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i<traks.length;i++){const trak=traks[i],stbl=trak.mdia.minf.stbl,stsdEntry=stbl.stsd.entries[0],handlerType=trak.mdia.hdlr.handlerType;let codec,mime;if("vide"===handlerType&&"avc1"===stsdEntry.type){if(this._hasVideo)continue;this._hasVideo=!0,codec="avc1",stsdEntry.avcC&&(codec+=`.${stsdEntry.avcC.mimeCodec}`),mime=`video/mp4; codecs="${codec}"`}else if("soun"===handlerType&&"mp4a"===stsdEntry.type){if(this._hasAudio)continue;this._hasAudio=!0,codec="mp4a",stsdEntry.esds&&stsdEntry.esds.mimeCodec&&(codec+=`.${stsdEntry.esds.mimeCodec}`),mime=`audio/mp4; codecs="${codec}"`}else continue;const samples=[];let sample=0,sampleInChunk=0,chunk=0,offsetInChunk=0,sampleToChunkIndex=0,dts=0;const decodingTimeEntry=new RunLengthIndex(stbl.stts.entries);let presentationOffsetEntry=null;stbl.ctts&&(presentationOffsetEntry=new RunLengthIndex(stbl.ctts.entries));for(let syncSampleIndex=0;!0;){var currChunkEntry=stbl.stsc.entries[sampleToChunkIndex];const size=stbl.stsz.entries[sample],duration=decodingTimeEntry.value.duration,presentationOffset=presentationOffsetEntry?presentationOffsetEntry.value.compositionOffset:0;let sync=!0;stbl.stss&&(sync=stbl.stss.entries[syncSampleIndex]===sample+1);const chunkOffsetTable=stbl.stco||stbl.co64;if(samples.push({size,duration,dts,presentationOffset,sync,offset:offsetInChunk+chunkOffsetTable.entries[chunk]}),sample++,sample>=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<startOffset)&&(startOffset=fragment.ranges[0].start);const writeFragment=frag=>{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.samples.length;currSample++){const sample=currTrack.samples[currSample];if(sample.sync&&sample.dts-startDts>=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;j<lastSample;j++){const currSample=currTrack.samples[j];0>currSample.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":223,"mp4-stream":226,"range-slice-stream":265}],341:[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":340,mediasource:211,pump:254}],342:[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":161,"has-tostringtag/shams":169,"is-typed-array":196}],343:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];var ret=fn.apply(this,args),cb=args[args.length-1];return"function"==typeof ret&&ret!==cb&&Object.keys(cb).forEach(function(k){ret[k]=cb[k]}),ret}if(fn&&cb)return wrappy(fn)(cb);if("function"!=typeof fn)throw new TypeError("need wrapper function");return Object.keys(fn).forEach(function(k){wrapper[k]=fn[k]}),wrapper}module.exports=wrappy},{}],344:[function(require,module,exports){function extend(){for(var target={},i=0,source;i<arguments.length;i++)for(var key in source=arguments[i],source)hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target}module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty},{}],345:[function(require,module,exports){module.exports={version:"1.8.22"}},{}],346:[function(require,module,exports){(function(Buffer){(function(){function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}/*! webtorrent. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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)}),cb(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 void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},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":345,"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}]},{},[346])(346)}); \ No newline at end of file
diff --git a/webtorrent.min.js b/webtorrent.min.js
index d1a0d8f..ddad365 100644
--- a/webtorrent.min.js
+++ b/webtorrent.min.js
@@ -1,4 +1,4 @@
-(function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,g.WebTorrent=f()}})(function(){var _MathLN=Math.LN2,_Mathlog2=Math.log,_Mathpow=Math.pow,_Mathabs=Math.abs,_Mathfloor=Math.floor,_Mathround=Math.round,_Mathsin=Math.sin,_Mathcos=Math.cos,_MathPI=Math.PI,_Mathimul=Math.imul,_Mathclz=Math.clz32,_StringfromCharCode=String.fromCharCode,_Mathmax=Math.max,_Mathceil=Math.ceil,_Mathmin=Math.min,define;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module){const stream=require("stream"),debugFactory=require("debug"),eos=require("end-of-stream"),debug=debugFactory("webtorrent:file-stream");class FileStream extends stream.Readable{constructor(file,opts){super(opts),this._torrent=file._torrent;const start=opts&&opts.start||0,end=opts&&opts.end&&opts.end<file.length?opts.end:file.length-1,pieceLength=file._torrent.pieceLength;this._startPiece=0|(start+file.offset)/pieceLength,this._endPiece=0|(end+file.offset)/pieceLength,this._piece=this._startPiece,this._offset=start+file.offset-this._startPiece*pieceLength,this._missing=end-start+1,this._reading=!1,this._notifying=!1,this._criticalLength=_Mathmin(0|1048576/pieceLength,2),this._torrent.select(this._startPiece,this._endPiece,!0,()=>{this._notify()}),eos(this,err=>{this.destroy(err)})}_read(){this._reading||(this._reading=!0,this._notify())}_notify(){if(!this._reading||0===this._missing)return;if(!this._torrent.bitfield.get(this._piece))return this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return;if(this._notifying=!0,this._torrent.destroyed)return this.destroy(new Error("Torrent removed"));const p=this._piece,getOpts={};p===this._torrent.pieces.length-1&&(getOpts.length=this._torrent.lastPieceLength),this._torrent.store.get(p,getOpts,(err,buffer)=>{if(this._notifying=!1,!this.destroyed)return debug("read %s (length %s) (err %s)",p,buffer&&buffer.length,err&&err.message),err?this.destroy(err):void(this._offset&&(buffer=buffer.slice(this._offset),this._offset=0),this._missing<buffer.length&&(buffer=buffer.slice(0,this._missing)),this._missing-=buffer.length,debug("pushing buffer of length %s",buffer.length),this._reading=!1,this.push(buffer),0===this._missing&&this.push(null))}),this._piece+=1}_destroy(err,cb){this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),cb(err)}}module.exports=FileStream},{debug:90,"end-of-stream":120,stream:255}],2:[function(require,module){const EventEmitter=require("events"),{PassThrough}=require("stream"),path=require("path"),render=require("render-media"),streamToBlob=require("stream-to-blob"),streamToBlobURL=require("stream-to-blob-url"),streamToBuffer=require("stream-with-known-length-to-buffer"),queueMicrotask=require("queue-microtask"),rangeParser=require("range-parser"),mime=require("mime"),eos=require("end-of-stream"),FileStream=require("./file-stream.js");module.exports=class extends EventEmitter{constructor(torrent,file){super(),this._torrent=torrent,this._destroyed=!1,this._fileStreams=new Set,this.name=file.name,this.path=file.path,this.length=file.length,this.offset=file.offset,this.done=!1;const start=file.offset,end=start+file.length-1;this._startPiece=0|start/this._torrent.pieceLength,this._endPiece=0|end/this._torrent.pieceLength,0===this.length&&(this.done=!0,this.emit("done")),this._serviceWorker=torrent.client.serviceWorker}get downloaded(){if(this._destroyed||!this._torrent.bitfield)return 0;const{pieces,bitfield,pieceLength,lastPieceLength}=this._torrent,{_startPiece:start,_endPiece:end}=this,getPieceLength=pieceIndex=>pieceIndex===pieces.length-1?lastPieceLength:pieceLength,getPieceDownloaded=pieceIndex=>{const len=pieceIndex===pieces.length-1?lastPieceLength:pieceLength;return bitfield.get(pieceIndex)?len:len-pieces[pieceIndex].missing};let downloaded=0;for(let index=start;index<=end;index+=1){const pieceDownloaded=getPieceDownloaded(index);if(downloaded+=pieceDownloaded,index===start){const irrelevantFirstPieceBytes=this.offset%pieceLength;downloaded-=_Mathmin(irrelevantFirstPieceBytes,pieceDownloaded)}if(index===end){const irrelevantLastPieceBytes=getPieceLength(end)-(this.offset+this.length)%pieceLength;downloaded-=_Mathmin(irrelevantLastPieceBytes,pieceDownloaded)}}return downloaded}get progress(){return this.length?this.downloaded/this.length:0}select(priority){0===this.length||this._torrent.select(this._startPiece,this._endPiece,priority)}deselect(){0===this.length||this._torrent.deselect(this._startPiece,this._endPiece,!1)}createReadStream(opts){if(0===this.length){const empty=new PassThrough;return queueMicrotask(()=>{empty.end()}),empty}const fileStream=new FileStream(this,opts);return this._fileStreams.add(fileStream),fileStream.once("close",()=>{this._fileStreams.delete(fileStream)}),fileStream}getBuffer(cb){streamToBuffer(this.createReadStream(),this.length,cb)}getBlob(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlob(this.createReadStream(),this._getMimeType()).then(blob=>cb(null,blob),err=>cb(err))}getBlobURL(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlobURL(this.createReadStream(),this._getMimeType()).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}appendTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.append(this,elem,opts,cb)}renderTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.render(this,elem,opts,cb)}_serve(req){const res={status:200,headers:{"Accept-Ranges":"bytes","Content-Type":mime.getType(this.name),"Cache-Control":"no-cache, no-store, must-revalidate, max-age=0",Expires:"0"},body:"HEAD"===req.method?"":"STREAM"};"document"===req.destination&&(res.headers["Content-Type"]="application/octet-stream",res.headers["Content-Disposition"]="attachment",res.body="DOWNLOAD");let range=rangeParser(this.length,req.headers.range||"");range.constructor===Array?(res.status=206,range=range[0],res.headers["Content-Range"]=`bytes ${range.start}-${range.end}/${this.length}`,res.headers["Content-Length"]=`${range.end-range.start+1}`):res.headers["Content-Length"]=this.length;const stream="GET"===req.method&&this.createReadStream(range);let pipe=null;return stream&&this.emit("stream",{stream,req,file:this},piped=>{pipe=piped,eos(piped,()=>{piped&&piped.destroy(),stream.destroy()})}),[res,pipe||stream,pipe&&stream]}getStreamURL(cb=()=>{}){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");const workerPath=this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length),url=`${workerPath}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`;cb(null,url)}streamTo(elem,cb=()=>{}){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");const workerPath=this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length);elem.src=`${workerPath}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`,cb(null,elem)}_getMimeType(){return render.mime[path.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null;for(const fileStream of this._fileStreams)fileStream.destroy();this._fileStreams.clear()}}},{"./file-stream.js":1,"end-of-stream":120,events:122,mime:163,path:184,"queue-microtask":205,"range-parser":210,"render-media":228,stream:255,"stream-to-blob":261,"stream-to-blob-url":260,"stream-with-known-length-to-buffer":262}],3:[function(require,module,exports){const EventEmitter=require("events"),{Transform}=require("stream"),arrayRemove=require("unordered-array-remove"),debugFactory=require("debug"),Wire=require("bittorrent-protocol"),debug=debugFactory("webtorrent:peer");let secure=!1;exports.enableSecure=()=>{secure=!0},exports.createWebRTCPeer=(conn,swarm,throttleGroups)=>{const peer=new Peer(conn.id,"webrtc");if(peer.conn=conn,peer.swarm=swarm,peer.throttleGroups=throttleGroups,peer.conn.connected)peer.onConnect();else{const cleanup=()=>{peer.conn.removeListener("connect",onConnect),peer.conn.removeListener("error",onError)},onConnect=()=>{cleanup(),peer.onConnect()},onError=err=>{cleanup(),peer.destroy(err)};peer.conn.once("connect",onConnect),peer.conn.once("error",onError),peer.startConnectTimeout()}return peer},exports.createTCPIncomingPeer=(conn,throttleGroups)=>_createIncomingPeer(conn,"tcpIncoming",throttleGroups),exports.createUTPIncomingPeer=(conn,throttleGroups)=>_createIncomingPeer(conn,"utpIncoming",throttleGroups),exports.createTCPOutgoingPeer=(addr,swarm,throttleGroups)=>_createOutgoingPeer(addr,swarm,"tcpOutgoing",throttleGroups),exports.createUTPOutgoingPeer=(addr,swarm,throttleGroups)=>_createOutgoingPeer(addr,swarm,"utpOutgoing",throttleGroups);const _createIncomingPeer=(conn,type,throttleGroups)=>{const addr=`${conn.remoteAddress}:${conn.remotePort}`,peer=new Peer(addr,type);return peer.conn=conn,peer.addr=addr,peer.throttleGroups=throttleGroups,peer.onConnect(),peer},_createOutgoingPeer=(addr,swarm,type,throttleGroups)=>{const peer=new Peer(addr,type);return peer.addr=addr,peer.swarm=swarm,peer.throttleGroups=throttleGroups,peer};exports.createWebSeedPeer=(conn,id,swarm,throttleGroups)=>{const peer=new Peer(id,"webSeed");return peer.swarm=swarm,peer.conn=conn,peer.throttleGroups=throttleGroups,peer.onConnect(),peer};class Peer extends EventEmitter{constructor(id,type){super(),this.id=id,this.type=type,debug("new %s Peer %s",type,id),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentPe1=!1,this.sentPe2=!1,this.sentPe3=!1,this.sentPe4=!1,this.sentHandshake=!1}onConnect(){if(!this.destroyed){this.connected=!0,debug("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const conn=this.conn;conn.once("end",()=>{this.destroy()}),conn.once("close",()=>{this.destroy()}),conn.once("finish",()=>{this.destroy()}),conn.once("error",err=>{this.destroy(err)});const wire=this.wire=new Wire(this.type,this.retries,secure);wire.once("end",()=>{this.destroy()}),wire.once("close",()=>{this.destroy()}),wire.once("finish",()=>{this.destroy()}),wire.once("error",err=>{this.destroy(err)}),wire.once("pe1",()=>{this.onPe1()}),wire.once("pe2",()=>{this.onPe2()}),wire.once("pe3",()=>{this.onPe3()}),wire.once("pe4",()=>{this.onPe4()}),wire.once("handshake",(infoHash,peerId)=>{this.onHandshake(infoHash,peerId)}),this.startHandshakeTimeout(),this.setThrottlePipes(),this.swarm&&("tcpOutgoing"===this.type?secure&&0===this.retries&&!this.sentPe1?this.sendPe1():!this.sentHandshake&&this.handshake():"tcpIncoming"!==this.type&&!this.sentHandshake&&this.handshake())}}sendPe1(){this.wire.sendPe1(),this.sentPe1=!0}onPe1(){this.sendPe2()}sendPe2(){this.wire.sendPe2(),this.sentPe2=!0}onPe2(){this.sendPe3()}sendPe3(){this.wire.sendPe3(this.swarm.infoHash),this.sentPe3=!0}onPe3(infoHashHash){this.swarm&&(this.swarm.infoHashHash!==infoHashHash&&this.destroy(new Error("unexpected crypto handshake info hash for this swarm")),this.sendPe4())}sendPe4(){this.wire.sendPe4(this.swarm.infoHash),this.sentPe4=!0}onPe4(){this.sentHandshake||this.handshake()}clearPipes(){this.conn.unpipe(),this.wire.unpipe()}setThrottlePipes(){const self=this;this.conn.pipe(this.throttleGroups.down.throttle()).pipe(new Transform({transform(chunk,_,callback){self.emit("download",chunk.length);self.destroyed||callback(null,chunk)}})).pipe(this.wire).pipe(this.throttleGroups.up.throttle()).pipe(new Transform({transform(chunk,_,callback){self.emit("upload",chunk.length);self.destroyed||callback(null,chunk)}})).pipe(this.conn)}onHandshake(infoHash,peerId){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(infoHash!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(peerId===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));debug("Peer %s got handshake %s",this.id,infoHash),clearTimeout(this.handshakeTimeout),this.retries=0;let addr=this.addr;!addr&&this.conn.remoteAddress&&this.conn.remotePort&&(addr=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,addr);this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const opts={dht:!this.swarm.private&&!!this.swarm.client.dht,fast:!0};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,opts),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},{webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3}[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(err){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,debug("destroy %s %s (error: %s)",this.type,this.id,err&&(err.message||err)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const swarm=this.swarm,conn=this.conn,wire=this.wire;this.swarm=null,this.conn=null,this.wire=null,swarm&&wire&&arrayRemove(swarm.wires,swarm.wires.indexOf(wire)),conn&&(conn.on("error",()=>{}),conn.destroy()),wire&&wire.destroy(),swarm&&swarm.removePeer(this.id)}}},{"bittorrent-protocol":32,debug:90,events:122,stream:255,"unordered-array-remove":273}],4:[function(require,module){module.exports=class{constructor(torrent){this._torrent=torrent,this._numPieces=torrent.pieces.length,this._pieces=Array(this._numPieces),this._onWire=wire=>{this.recalculate(),this._initWire(wire)},this._onWireHave=index=>{this._pieces[index]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach(wire=>{this._initWire(wire)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(pieceFilterFunc){let candidates=[],min=1/0;for(let i=0;i<this._numPieces;++i){if(pieceFilterFunc&&!pieceFilterFunc(i))continue;const availability=this._pieces[i];availability===min?candidates.push(i):availability<min&&(candidates=[i],min=availability)}return candidates.length?candidates[0|Math.random()*candidates.length]:-1}destroy(){this._torrent.removeListener("wire",this._onWire),this._torrent.wires.forEach(wire=>{this._cleanupWireEvents(wire)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(wire){wire._onClose=()=>{this._cleanupWireEvents(wire);for(let i=0;i<this._numPieces;++i)this._pieces[i]-=wire.peerPieces.get(i)},wire.on("have",this._onWireHave),wire.on("bitfield",this._onWireBitfield),wire.once("close",wire._onClose)}recalculate(){this._pieces.fill(0);for(const wire of this._torrent.wires)for(let i=0;i<this._numPieces;++i)this._pieces[i]+=wire.peerPieces.get(i)}_cleanupWireEvents(wire){wire.removeListener("have",this._onWireHave),wire.removeListener("bitfield",this._onWireBitfield),wire._onClose&&wire.removeListener("close",wire._onClose),wire._onClose=null}}},{}],5:[function(require,module){(function(process,global){(function(){function getBlockPipelineLength(wire,duration){let length=2+_Mathceil(duration*wire.downloadSpeed()/Piece.BLOCK_LENGTH);if(wire.peerExtendedHandshake){const reqq=wire.peerExtendedHandshake.reqq;"number"==typeof reqq&&0<reqq&&(length=_Mathmin(length,reqq))}return length}function getPiecePipelineLength(wire,duration,pieceLength){return 1+_Mathceil(duration*wire.downloadSpeed()/pieceLength)}function randomInt(high){return 0|Math.random()*high}function noop(){}const EventEmitter=require("events"),fs=require("fs"),net=require("net"),os=require("os"),path=require("path"),addrToIPPort=require("addr-to-ip-port"),{default:BitField}=require("bitfield"),CacheChunkStore=require("cache-chunk-store"),ChunkStoreWriteStream=require("chunk-store-stream/write"),cpus=require("cpus"),debugFactory=require("debug"),Discovery=require("torrent-discovery"),FSChunkStore=require("fs-chunk-store"),get=require("simple-get"),ImmediateChunkStore=require("immediate-chunk-store"),ltDontHave=require("lt_donthave"),MemoryChunkStore=require("memory-chunk-store"),MultiStream=require("multistream"),parallel=require("run-parallel"),parallelLimit=require("run-parallel-limit"),parseTorrent=require("parse-torrent"),Piece=require("torrent-piece"),pump=require("pump"),queueMicrotask=require("queue-microtask"),randomIterate=require("random-iterate"),sha1=require("simple-sha1"),throughput=require("throughput"),utMetadata=require("ut_metadata"),utPex=require("ut_pex"),File=require("./file.js"),Peer=require("./peer.js"),RarityMap=require("./rarity-map.js"),Server=require("./server.js"),utp=require("./utp.js"),WebConn=require("./webconn.js"),debug=debugFactory("webtorrent:torrent"),CHOKE_TIMEOUT=5e3,SPEED_THRESHOLD=3*Piece.BLOCK_LENGTH,PIPELINE_MAX_DURATION=1,FILESYSTEM_CONCURRENCY=process.browser?cpus().length:2,RECONNECT_WAIT=[1e3,5e3,15e3],VERSION=require("../package.json").version,USER_AGENT=`WebTorrent/${VERSION} (https://webtorrent.io)`;let TMP;try{TMP=path.join(fs.statSync("/tmp")&&"/tmp","webtorrent")}catch(err){TMP=path.join("function"==typeof os.tmpdir?os.tmpdir():"/","webtorrent")}module.exports=class extends EventEmitter{constructor(torrentId,client,opts){super(),this._debugId="unknown infohash",this.client=client,this.announce=opts.announce,this.urlList=opts.urlList,this.path=opts.path||TMP,this.addUID=opts.addUID||!1,this.skipVerify=!!opts.skipVerify,this._store=opts.store||FSChunkStore,this._preloadedStore=opts.preloadedStore||null,this._storeCacheSlots=opts.storeCacheSlots===void 0?20:opts.storeCacheSlots,this._destroyStoreOnDestroy=opts.destroyStoreOnDestroy||!1,this._getAnnounceOpts=opts.getAnnounceOpts,"boolean"==typeof opts.private&&(this.private=opts.private),this.strategy=opts.strategy||"sequential",this.maxWebConns=opts.maxWebConns||4,this._rechokeNumSlots=!1===opts.uploads||0===opts.uploads?0:+opts.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=opts.paused||!1,this.done=!1,this.metadata=null,this.store=null,this.storeOpts=opts.storeOpts,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),this._servers=[],this._xsRequests=[],this._fileModtimes=opts.fileModtimes,null!==torrentId&&this._onTorrentId(torrentId),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:1e3*((this.length-this.downloaded)/this.downloadSpeed)}get downloaded(){if(!this.bitfield)return 0;let downloaded=0;for(let index=0,len=this.pieces.length;index<len;++index)if(this.bitfield.get(index))downloaded+=index===len-1?this.lastPieceLength:this.pieceLength;else{const piece=this.pieces[index];downloaded+=piece.length-piece.missing}return downloaded}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){return this.length?this.downloaded/this.length:0}get ratio(){return this.uploaded/(this.received||this.length)}get numPeers(){return this.wires.length}get torrentFileBlobURL(){if("undefined"==typeof window)throw new Error("browser-only property");return this.torrentFile?URL.createObjectURL(new Blob([this.torrentFile],{type:"application/x-bittorrent"})):null}get _numQueued(){return this._queue.length+(this._peersLength-this._numConns)}get _numConns(){let numConns=0;for(const id in this._peers)this._peers[id].connected&&(numConns+=1);return numConns}_onTorrentId(torrentId){if(this.destroyed)return;let parsedTorrent;try{parsedTorrent=parseTorrent(torrentId)}catch(err){}parsedTorrent?(this.infoHash=parsedTorrent.infoHash,this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),queueMicrotask(()=>{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{if(!this.destroyed){const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}}})),this.peerAddresses&&this.peerAddresses.forEach(peer=>this.addPeer(peer)),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT,lsd:this.client.lsd}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",(peer,source)=>{this._debug("peer %s discovered via %s",peer,source);"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.files=this.files.map(file=>new File(this,file));let rawStore=this._preloadedStore;if(rawStore||(rawStore=new this._store(this.pieceLength,{...this.storeOpts,torrent:this,path:this.path,files:this.files,length:this.length,name:this.name+" - "+this.infoHash.slice(0,8),addUID:this.addUID})),0<this._storeCacheSlots&&!(rawStore instanceof MemoryChunkStore)&&(rawStore=new CacheChunkStore(rawStore,{max:this._storeCacheSlots})),this.store=new ImmediateChunkStore(rawStore),this.so?this.files.forEach((v,i)=>{this.so.includes(i)?this.files[i].select():this.files[i].deselect()}):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{const filePath=this.addUID?path.join(this.name+" - "+this.infoHash.slice(0,8)):path.join(this.path,file.path);fs.stat(filePath,(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));const getOpts={};index===this.pieces.length-1&&(getOpts.length=this.lastPieceLength),this.store.get(index,getOpts,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?queueMicrotask(()=>cb(null)):void sha1(buf,hash=>this.destroyed?cb(new Error("torrent is destroyed")):void(hash===this._hashes[index]?(this._debug("piece verified %s",index),this._markVerified(index)):this._debug("piece invalid %s",index),cb(null))))}),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index<this.pieces.length;index++)this._markVerified(index)}_markVerified(index){this.pieces[index]=null,this._reservations[index]=null,this.bitfield.set(index,!0)}_hasAllPieces(){for(let index=0;index<this.pieces.length;index++)if(!this.bitfield.get(index))return!1;return!0}_hasNoPieces(){return!this._hasMorePieces(0)}_hasMorePieces(threshold){let count=0;for(let index=0;index<this.pieces.length;index++)if(this.bitfield.get(index)&&(count+=1,count>threshold))return!0;return!1}_onStore(){this.destroyed||(this._debug("on store"),this._startDiscovery(),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections(),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}))}destroy(opts,cb){return"function"==typeof opts?this.destroy(null,opts):void this._destroy(null,opts,cb)}_destroy(err,opts,cb){if("function"==typeof opts)return this._destroy(err,null,opts);if(!this.destroyed){for(const id in this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),this._xsRequests.forEach(req=>{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});if(this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store){let destroyStore=this._destroyStoreOnDestroy;opts&&void 0!==opts.destroyStore&&(destroyStore=opts.destroyStore),tasks.push(cb=>{destroyStore?this.store.destroy(cb):this.store.close(cb)})}parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");let host;if(this.client.blocked){if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const type=this.client.utp&&this._isIPv4(host)?"utp":"tcp",wasAdded=!!this._addPeer(peer,type);return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer,type){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?"utp"===type?Peer.createUTPOutgoingPeer(peer,this,this.client.throttleGroups):Peer.createTCPOutgoingPeer(peer,this,this.client.throttleGroups):Peer.createWebRTCPeer(peer,this,this.client.throttleGroups),this._registerPeer(newPeer),"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(urlOrConn){if(this.destroyed)throw new Error("torrent is destroyed");let id,conn;if("string"==typeof urlOrConn){if(id=urlOrConn,!/^https?:\/\/.+/.test(id))return this.emit("warning",new Error(`ignoring invalid web seed: ${id}`)),void this.emit("invalidPeer",id);if(this._peers[id])return this.emit("warning",new Error(`ignoring duplicate web seed: ${id}`)),void this.emit("invalidPeer",id);conn=new WebConn(id,this)}else{if(!(urlOrConn&&"string"==typeof urlOrConn.connId))return void this.emit("warning",new Error("addWebSeed must be passed a string or connection object with id property"));if(conn=urlOrConn,id=conn.connId,this._peers[id])return this.emit("warning",new Error(`ignoring duplicate web seed: ${id}`)),void this.emit("invalidPeer",id)}this._debug("add web seed %s",id);const newPeer=Peer.createWebSeedPeer(conn,id,this,this.client.throttleGroups);this._registerPeer(newPeer),this.emit("peer",id)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._registerPeer(peer))}_registerPeer(newPeer){newPeer.on("download",downloaded=>{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.destroyed||this.client.emit("download",downloaded))}),newPeer.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.destroyed||this.client.emit("upload",uploaded))}),this._peers[newPeer.id]=newPeer,this._peersLength+=1}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||end<start||this.pieces.length<=end)throw new Error(`invalid selection ${start} : ${end}`);priority=+priority||0,this._debug("select %s-%s (priority %s)",start,end,priority),this._selections.push({from:start,to:end,offset:0,priority,notify:notify||noop}),this._selections.sort((a,b)=>b.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i<this._selections.length;++i){const s=this._selections[i];if(s.from===start&&s.to===end&&s.priority===priority){this._selections.splice(i,1);break}}this._updateSelections()}critical(start,end){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",start,end);for(let i=start;i<=end;++i)this._critical[i]=!0;this._updateSelections()}_onWire(wire,addr){if(this._debug("got wire %s (%s)",wire._debugId,addr||"Unknown"),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536<port?this._debug("ignoring invalid PORT from peer"):void(this._debug("port: %s (from %s)",port,addr),this.client.dht.addNode({host:wire.remoteAddress,port})):this._debug("ignoring PORT from peer with no address")),wire.on("timeout",()=>{this._debug("wire timeout (%s)",addr),wire.destroy()}),"webSeed"!==wire.type&&wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),wire.use(ltDontHave()),this.emit("wire",wire,addr),this.ready&&queueMicrotask(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i<this.pieces.length;++i)if(!wire.peerPieces.get(i))return;wire.isSeeder=!0,wire.choke()}};wire.on("bitfield",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.lt_donthave.on("donthave",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have-all",()=>{wire.isSeeder=!0,wire.choke(),this._update(),this._updateWireInterest(wire)}),wire.on("have-none",()=>{wire.isSeeder=!1,this._update(),this._updateWireInterest(wire)}),wire.on("allowed-fast",()=>{this._update()}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.hasFast&&this._hasAllPieces()?wire.haveAll():wire.hasFast&&this._hasNoPieces()?wire.haveNone():wire.bitfield(this.bitfield),this._updateWireInterest(wire),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(queueMicrotask(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;i<this._selections.length;++i){const s=this._selections[i],oldOffset=s.offset;for(;this.bitfield.get(s.from+s.offset)&&s.from+s.offset<s.to;)s.offset+=1;oldOffset!==s.offset&&s.notify(),s.to===s.from+s.offset&&this.bitfield.get(s.from+s.offset)&&(this._selections.splice(i,1),i-=1,s.notify(),this._updateInterest())}this._selections.length||this.emit("idle")}_updateInterest(){const prev=this._amInterested;this._amInterested=!!this._selections.length,this.wires.forEach(wire=>this._updateWireInterest(wire));prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(wire){let interested=!1;for(let index=0;index<this.pieces.length;++index)if(this.pieces[index]&&wire.peerPieces.get(index)){interested=!0;break}interested?wire.interested():wire.uninterested()}_update(){if(!this.destroyed){const ite=randomIterate(this.wires);for(let wire;wire=ite();)this._updateWireWrapper(wire)}}_updateWireWrapper(wire){const self=this;"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?window.requestIdleCallback(()=>{self._updateWire(wire)},{timeout:250}):self._updateWire(wire)}_updateWire(wire){function genPieceFilterFunc(start,end,tried,rank){return i=>i>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr<self.wires.length;ptr++){const otherWire=self.wires[ptr],otherSpeed=otherWire.downloadSpeed();if(!(otherSpeed<SPEED_THRESHOLD)&&!(otherSpeed<=speed)&&otherWire.peerPieces.get(index)&&!(0<(missing-=otherSpeed*secs)))return tries--,!1}return!0}}function shufflePriority(i){let last=i;for(let j=i;j<self._selections.length&&self._selections[j].priority;j++)last=j;const tmp=self._selections[i];self._selections[i]=self._selections[last],self._selections[last]=tmp}function trySelectWire(hotswap){if(wire.requests.length>=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;i<self._selections.length;i++){const next=self._selections[i];let piece;if("rarest"===self.strategy){const start=next.from+next.offset,end=next.to,tried={};let tries=0;for(const filter=genPieceFilterFunc(start,end,tried,rank);tries<end-start+1&&(piece=self._rarityMap.getRarestPiece(filter),!(0>piece));){for(;self._request(wire,piece,self._critical[piece]||hotswap)&&wire.requests.length<maxOutstandingRequests;);if(wire.requests.length<maxOutstandingRequests){tried[piece]=!0,tries++;continue}return next.priority&&shufflePriority(i),!0}}else for(piece=next.from+next.offset;piece<=next.to;piece++)if(wire.peerPieces.get(piece)&&rank(piece)){for(;self._request(wire,piece,self._critical[piece]||hotswap)&&wire.requests.length<maxOutstandingRequests;);if(!(wire.requests.length<maxOutstandingRequests))return next.priority&&shufflePriority(i),!0}}return!1}const self=this,minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);return wire.peerChoking?void(wire.hasFast&&0<wire.peerAllowedFastSet.length&&!this._hasMorePieces(wire.peerAllowedFastSet.length-1)&&function(){if(wire.requests.length>=maxOutstandingRequests)return!1;for(const piece of wire.peerAllowedFastSet){if(wire.peerPieces.get(piece)&&!self.bitfield.get(piece))for(;self._request(wire,piece,!1)&&wire.requests.length<maxOutstandingRequests;);if(!(wire.requests.length<maxOutstandingRequests))return!0}return!1}()):wire.downloaded?void(trySelectWire(!1)||trySelectWire(!0)):function(){if(!wire.requests.length)for(let i=self._selections.length;i--;){const next=self._selections[i];let piece;if("rarest"===self.strategy){const start=next.from+next.offset,end=next.to,tried={};let tries=0;for(const filter=genPieceFilterFunc(start,end,tried);tries<end-start+1&&(piece=self._rarityMap.getRarestPiece(filter),!(0>piece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}()}_rechoke(){if(this.ready){const wireStack=this.wires.map(wire=>({wire,random:Math.random()})).sort((objA,objB)=>{const wireA=objA.wire,wireB=objB.wire;return wireA.downloadSpeed()===wireB.downloadSpeed()?wireA.uploadSpeed()===wireB.uploadSpeed()?wireA.amChoking===wireB.amChoking?objA.random-objB.random:wireA.amChoking?-1:1:wireA.uploadSpeed()-wireB.uploadSpeed():wireA.downloadSpeed()-wireB.downloadSpeed()}).map(obj=>obj.wire);0>=this._rechokeOptimisticTime?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;for(let numInterestedUnchoked=0;0<wireStack.length&&numInterestedUnchoked<this._rechokeNumSlots-1;){const wire=wireStack.pop();wire.isSeeder||wire===this._rechokeOptimisticWire||(wire.unchoke(),wire.peerInterested&&numInterestedUnchoked++)}if(null===this._rechokeOptimisticWire&&0<this._rechokeNumSlots){const remaining=wireStack.filter(wire=>wire.peerInterested);if(0<remaining.length){const newOptimisticPeer=remaining[randomInt(remaining.length)];newOptimisticPeer.unchoke(),this._rechokeOptimisticWire=newOptimisticPeer,this._rechokeOptimisticTime=2}}wireStack.filter(wire=>wire!==this._rechokeOptimisticWire).forEach(wire=>wire.choke())}}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed<Piece.BLOCK_LENGTH)return!1;if(!this._reservations[index])return!1;const r=this._reservations[index];if(!r)return!1;let minSpeed=1/0,minWire,i;for(i=0;i<r.length;i++){const otherWire=r[i];if(!otherWire||otherWire===wire)continue;const otherSpeed=otherWire.downloadSpeed();otherSpeed>=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i<r.length;i++)r[i]===minWire&&(r[i]=null);for(i=0;i<minWire.requests.length;i++){const req=minWire.requests[i];req.piece===index&&this.pieces[index].cancel(0|req.offset/Piece.BLOCK_LENGTH)}return this.emit("hotswap",minWire,wire,index),!0}_request(wire,index,hotswap){function onUpdateTick(){queueMicrotask(()=>{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{self.destroyed||(hash===self._hashes[index]?(self._debug("piece verified %s",index),self.store.put(index,buf,err=>err?void self._destroy(err):void(self.pieces[index]=null,self._markVerified(index),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete(),onUpdateTick()))):(self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`)),onUpdateTick()))})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(const selection of this._selections){for(let piece=selection.from;piece<=selection.to;piece++)if(!this.bitfield.get(piece)){done=!1;break}if(!done)break}return!this.done&&done?(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")):this.done=!1,this._gcSelections(),done}load(streams,cb){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",()=>{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("%s connect attempt to %s",peer.type,peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]};peer.conn=this.client.utp&&"utpOutgoing"===peer.type?utp.connect(opts.port,opts.host):net.connect(opts);const conn=peer.conn;conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length){if(this.client.utp){const newPeer=this._addPeer(peer.addr,"tcp");newPeer&&(newPeer.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);return}const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{if(!this.destroyed){const host=addrToIPPort(peer.addr)[0],type=this.client.utp&&this._isIPv4(host)?"utp":"tcp",newPeer=this._addPeer(peer.addr,type);newPeer&&(newPeer.retries=peer.retries+1)}},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0<port&&65535>port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}_isIPv4(addr){const IPv4Pattern=/^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/;return IPv4Pattern.test(addr)}}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":282,"./file.js":2,"./peer.js":3,"./rarity-map.js":4,"./server.js":41,"./utp.js":41,"./webconn.js":6,_process:192,"addr-to-ip-port":7,bitfield:31,"cache-chunk-store":77,"chunk-store-stream/write":78,cpus:81,debug:90,events:122,fs:41,"fs-chunk-store":159,"immediate-chunk-store":144,lt_donthave:155,"memory-chunk-store":159,multistream:175,net:41,os:41,"parse-torrent":183,path:184,pump:200,"queue-microtask":205,"random-iterate":207,"run-parallel":232,"run-parallel-limit":231,"simple-get":245,"simple-sha1":247,throughput:267,"torrent-discovery":269,"torrent-piece":270,ut_metadata:276,ut_pex:41}],6:[function(require,module,exports){(function(Buffer){(function(){const{default:BitField}=require("bitfield"),debugFactory=require("debug"),get=require("simple-get"),ltDontHave=require("lt_donthave"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),debug=debugFactory("webtorrent:webconn"),VERSION=require("../package.json").version,SOCKET_TIMEOUT=6e4,RETRY_DELAY=1e4;class WebConn extends Wire{constructor(url,torrent){super(),this.url=url,this.connId=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.use(ltDontHave()),this.once("handshake",(infoHash,peerId)=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.lt_donthave.on("donthave",()=>{debug("donthave")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,(err,data)=>{if(err){this.lt_donthave.donthave(pieceIndex);const retryTimeout=setTimeout(()=>{this.destroyed||this.have(pieceIndex)},RETRY_DELAY);retryTimeout.unref&&retryTimeout.unref()}callback(err,data)})})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path.replace(this._torrent.path,"");return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1<requests.length&&(ret=Buffer.alloc(length)),requests.forEach(request=>{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?hasError?void 0:(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`},timeout:SOCKET_TIMEOUT};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}module.exports=WebConn}).call(this)}).call(this,require("buffer").Buffer)},{"../package.json":282,bitfield:31,"bittorrent-protocol":32,buffer:75,debug:90,lt_donthave:155,"simple-get":245,"simple-sha1":247}],7:[function(require,module,exports){const ADDR_RE=/^\[?([^\]]+)]?:(\d+)$/;let cache=new Map;module.exports=function addrToIPPort(addr){if(1e5===cache.size&&cache.clear(),!cache.has(addr)){const m=ADDR_RE.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache.set(addr,[m[1],+m[2]])}return cache.get(addr)}},{}],8:[function(require,module,exports){"use strict";const asn1=exports;asn1.bignum=require("bn.js"),asn1.define=require("./asn1/api").define,asn1.base=require("./asn1/base"),asn1.constants=require("./asn1/constants"),asn1.decoders=require("./asn1/decoders"),asn1.encoders=require("./asn1/encoders")},{"./asn1/api":9,"./asn1/base":11,"./asn1/constants":15,"./asn1/decoders":17,"./asn1/encoders":20,"bn.js":22}],9:[function(require,module,exports){"use strict";function Entity(name,body){this.name=name,this.body=body,this.decoders={},this.encoders={}}const encoders=require("./encoders"),decoders=require("./decoders"),inherits=require("inherits"),api=exports;api.define=function define(name,body){return new Entity(name,body)},Entity.prototype._createNamed=function createNamed(Base){function Generated(entity){this._initNamed(entity,name)}const name=this.name;return inherits(Generated,Base),Generated.prototype._initNamed=function _initNamed(entity,name){Base.call(this,entity,name)},new Generated(this)},Entity.prototype._getDecoder=function _getDecoder(enc){return enc=enc||"der",this.decoders.hasOwnProperty(enc)||(this.decoders[enc]=this._createNamed(decoders[enc])),this.decoders[enc]},Entity.prototype.decode=function decode(data,enc,options){return this._getDecoder(enc).decode(data,options)},Entity.prototype._getEncoder=function _getEncoder(enc){return enc=enc||"der",this.encoders.hasOwnProperty(enc)||(this.encoders[enc]=this._createNamed(encoders[enc])),this.encoders[enc]},Entity.prototype.encode=function encode(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},{"./decoders":17,"./encoders":20,inherits:145}],10:[function(require,module,exports){"use strict";function DecoderBuffer(base,options){return Reporter.call(this,options),Buffer.isBuffer(base)?void(this.base=base,this.offset=0,this.length=base.length):void this.error("Input not Buffer")}function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if("number"==typeof value){if(!(0<=value&&255>=value))return reporter.error("non-byte EncoderBuffer value");this.value=value,this.length=1}else if("string"==typeof value)this.value=value,this.length=Buffer.byteLength(value);else if(Buffer.isBuffer(value))this.value=value,this.length=value.length;else return reporter.error("Unsupported type: "+typeof value)}const inherits=require("inherits"),Reporter=require("../base/reporter").Reporter,Buffer=require("safer-buffer").Buffer;inherits(DecoderBuffer,Reporter),exports.DecoderBuffer=DecoderBuffer,DecoderBuffer.isDecoderBuffer=function isDecoderBuffer(data){if(data instanceof DecoderBuffer)return!0;const isCompatible="object"==typeof data&&Buffer.isBuffer(data.base)&&"DecoderBuffer"===data.constructor.name&&"number"==typeof data.offset&&"number"==typeof data.length&&"function"==typeof data.save&&"function"==typeof data.restore&&"function"==typeof data.isEmpty&&"function"==typeof data.readUInt8&&"function"==typeof data.skip&&"function"==typeof data.raw;return isCompatible},DecoderBuffer.prototype.save=function save(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function restore(save){const res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function isEmpty(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function readUInt8(fail){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.skip=function skip(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");const res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function raw(save){return this.base.slice(save?save.offset:this.offset,this.length)},exports.EncoderBuffer=EncoderBuffer,EncoderBuffer.isEncoderBuffer=function isEncoderBuffer(data){if(data instanceof EncoderBuffer)return!0;const isCompatible="object"==typeof data&&"EncoderBuffer"===data.constructor.name&&"number"==typeof data.length&&"function"==typeof data.join;return isCompatible},EncoderBuffer.prototype.join=function join(out,offset){return(out||(out=Buffer.alloc(this.length)),offset||(offset=0),0===this.length)?out:(Array.isArray(this.value)?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):("number"==typeof this.value?out[offset]=this.value:"string"==typeof this.value?out.write(this.value,offset):Buffer.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length),out)}},{"../base/reporter":13,inherits:145,"safer-buffer":235}],11:[function(require,module,exports){"use strict";const base=exports;base.Reporter=require("./reporter").Reporter,base.DecoderBuffer=require("./buffer").DecoderBuffer,base.EncoderBuffer=require("./buffer").EncoderBuffer,base.Node=require("./node")},{"./buffer":10,"./node":12,"./reporter":13}],12:[function(require,module,exports){"use strict";function Node(enc,parent,name){const state={};this._baseState=state,state.name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state["default"]=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}const Reporter=require("../base/reporter").Reporter,EncoderBuffer=require("../base/buffer").EncoderBuffer,DecoderBuffer=require("../base/buffer").DecoderBuffer,assert=require("minimalistic-assert"),tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags),overrided=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];module.exports=Node;const stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function clone(){const state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});const res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function wrap(){const state=this._baseState;methods.forEach(function(method){this[method]=function _wrappedMethod(){const clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function init(body){const state=this._baseState;assert(null===state.parent),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,"Root node can have only one child")},Node.prototype._useArgs=function useArgs(args){const state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),0!==children.length&&(assert(null===state.children),state.children=children,children.forEach(function(child){child._baseState.parent=this},this)),0!==args.length&&(assert(null===state.args),state.args=args,state.reverseArgs=args.map(function(arg){if("object"!=typeof arg||arg.constructor!==Object)return arg;const res={};return Object.keys(arg).forEach(function(key){key==(0|key)&&(key|=0);const value=arg[key];res[value]=key}),res}))},overrided.forEach(function(method){Node.prototype[method]=function _overrided(){const state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function _tagMethod(){const state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(null===state.tag),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function use(item){assert(item);const state=this._baseState;return assert(null===state.use),state.use=item,this},Node.prototype.optional=function optional(){const state=this._baseState;return state.optional=!0,this},Node.prototype.def=function def(val){const state=this._baseState;return assert(null===state["default"]),state["default"]=val,state.optional=!0,this},Node.prototype.explicit=function explicit(num){const state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.explicit=num,this},Node.prototype.implicit=function implicit(num){const state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.implicit=num,this},Node.prototype.obj=function obj(){const state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,0!==args.length&&this._useArgs(args),this},Node.prototype.key=function key(newKey){const state=this._baseState;return assert(null===state.key),state.key=newKey,this},Node.prototype.any=function any(){const state=this._baseState;return state.any=!0,this},Node.prototype.choice=function choice(obj){const state=this._baseState;return assert(null===state.choice),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function contains(item){const state=this._baseState;return assert(null===state.use),state.contains=item,this},Node.prototype._decode=function decode(input,options){const state=this._baseState;if(null===state.parent)return input.wrapResult(state.children[0]._decode(input,options));let result=state["default"],present=!0,prevKey=null;if(null!==state.key&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(null===state.explicit?null===state.implicit?null!==state.tag&&(tag=state.tag):tag=state.implicit:tag=state.explicit,null===tag&&!state.any){const save=input.save();try{null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch(e){present=!1}input.restore(save)}else if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}let prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(null!==state.explicit){const explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}const start=input.offset;if(null===state.use&&null===state.choice){let save;state.any&&(save=input.save());const body=this._decodeTag(input,null===state.implicit?state.tag:state.implicit,state.any);if(input.isError(body))return body;state.any?result=input.raw(save):input=body}if(options&&options.track&&null!==state.tag&&options.track(input.path(),start,input.length,"tagged"),options&&options.track&&null!==state.tag&&options.track(input.path(),input.offset,input.length,"content"),state.any||(null===state.choice?result=this._decodeGeneric(state.tag,input,options):result=this._decodeChoice(input,options)),input.isError(result))return result;if(state.any||null!==state.choice||null===state.children||state.children.forEach(function decodeChildren(child){child._decode(input,options)}),state.contains&&("octstr"===state.tag||"bitstr"===state.tag)){const data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),null!==state.key&&(null!==result||!0===present)?input.leaveKey(prevKey,state.key,result):null!==prevKey&&input.exitKey(prevKey),result},Node.prototype._decodeGeneric=function decodeGeneric(tag,input,options){const state=this._baseState;if("seq"===tag||"set"===tag)return null;return"seqof"===tag||"setof"===tag?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)?this._decodeStr(input,tag,options):"objid"===tag&&state.args?this._decodeObjid(input,state.args[0],state.args[1],options):"objid"===tag?this._decodeObjid(input,null,null,options):"gentime"===tag||"utctime"===tag?this._decodeTime(input,tag,options):"null_"===tag?this._decodeNull(input,options):"bool"===tag?this._decodeBool(input,options):"objDesc"===tag?this._decodeStr(input,tag,options):"int"===tag||"enum"===tag?this._decodeInt(input,state.args&&state.args[0],options):null===state.use?input.error("unknown tag: "+tag):this._getUse(state.use,input._reporterState.obj)._decode(input,options)},Node.prototype._getUse=function _getUse(entity,obj){const state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(null===state.useDecoder._baseState.parent),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function decodeChoice(input,options){const state=this._baseState;let result=null,match=!1;return Object.keys(state.choice).some(function(key){const save=input.save(),node=state.choice[key];try{const value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value:value},match=!0}catch(e){return input.restore(save),!1}return!0},this),match?result:input.error("Choice not matched")},Node.prototype._createEncoderBuffer=function createEncoderBuffer(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function encode(data,reporter,parent){const state=this._baseState;if(null===state["default"]||state["default"]!==data){const result=this._encodeValue(data,reporter,parent);return void 0===result||this._skipDefault(result,reporter,parent)?void 0:result}},Node.prototype._encodeValue=function encode(data,reporter,parent){const state=this._baseState;if(null===state.parent)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&void 0===data)if(null!==state["default"])data=state["default"];else return;let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if("null_"===child._baseState.tag)return child._encode(null,reporter,data);if(null===child._baseState.key)return reporter.error("Child should have a key");const prevKey=reporter.enterKey(child._baseState.key);if("object"!=typeof data)return reporter.error("Child expected, but input is not object");const res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if("seqof"===state.tag||"setof"===state.tag){if(!(state.args&&1===state.args.length))return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");const child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){const state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else null===state.use?(content=this._encodePrimitive(state.tag,data),primitive=!0):result=this._getUse(state.use,parent)._encode(data,reporter);if(!state.any&&null===state.choice){const tag=null===state.implicit?state.tag:state.implicit,cls=null===state.implicit?"universal":"context";null===tag?null===state.use&&reporter.error("Tag could be omitted only for .use()"):null===state.use&&(result=this._encodeComposite(tag,primitive,cls,content))}return null!==state.explicit&&(result=this._encodeComposite(state.explicit,!1,"context",result)),result},Node.prototype._encodeChoice=function encodeChoice(data,reporter){const state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+" not found in "+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function encodePrimitive(tag,data){const state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if("objid"===tag&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if("objid"===tag)return this._encodeObjid(data,null,null);if("gentime"===tag||"utctime"===tag)return this._encodeTime(data,tag);if("null_"===tag)return this._encodeNull();if("int"===tag||"enum"===tag)return this._encodeInt(data,state.args&&state.reverseArgs[0]);if("bool"===tag)return this._encodeBool(data);if("objDesc"===tag)return this._encodeStr(data,tag);throw new Error("Unsupported tag: "+tag)},Node.prototype._isNumstr=function isNumstr(str){return /^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function isPrintstr(str){return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str)}},{"../base/buffer":10,"../base/reporter":13,"minimalistic-assert":166}],13:[function(require,module,exports){"use strict";function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}function ReporterError(path,msg){this.path=path,this.rethrow(msg)}const inherits=require("inherits");exports.Reporter=Reporter,Reporter.prototype.isError=function isError(obj){return obj instanceof ReporterError},Reporter.prototype.save=function save(){const state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function restore(data){const state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function enterKey(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function exitKey(index){const state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function leaveKey(index,key,value){const state=this._reporterState;this.exitKey(index),null!==state.obj&&(state.obj[key]=value)},Reporter.prototype.path=function path(){return this._reporterState.path.join("/")},Reporter.prototype.enterObject=function enterObject(){const state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function leaveObject(prev){const state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function error(msg){let err;const state=this._reporterState,inherited=msg instanceof ReporterError;if(err=inherited?msg:new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function wrapResult(result){const state=this._reporterState;return state.options.partial?{result:this.isError(result)?null:result,errors:state.errors}:result},inherits(ReporterError,Error),ReporterError.prototype.rethrow=function rethrow(msg){if(this.message=msg+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:145}],14:[function(require,module,exports){"use strict";function reverse(map){const res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);const value=map[key];res[value]=key}),res}exports.tagClass={0:"universal",1:"application",2:"context",3:"private"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},exports.tagByName=reverse(exports.tag)},{}],15:[function(require,module,exports){"use strict";const constants=exports;constants._reverse=function reverse(map){const res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);const value=map[key];res[value]=key}),res},constants.der=require("./der")},{"./der":14}],16:[function(require,module,exports){"use strict";function DERDecoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function derDecodeTag(buf,fail){let tag=buf.readUInt8(fail);if(buf.isError(tag))return tag;const cls=der.tagClass[tag>>6],primitive=0==(32&tag);if(31==(31&tag)){let oct=tag;for(tag=0;128==(128&oct);){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=127&oct}}else tag&=31;const tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&128===len)return null;if(0==(128&len))return len;const num=127&len;if(4<num)return buf.error("length octect is too long");len=0;for(let i=0;i<num;i++){len<<=8;const j=buf.readUInt8(fail);if(buf.isError(j))return j;len|=j}return len}const inherits=require("inherits"),bignum=require("bn.js"),DecoderBuffer=require("../base/buffer").DecoderBuffer,Node=require("../base/node"),der=require("../constants/der");module.exports=DERDecoder,DERDecoder.prototype.decode=function decode(data,options){return DecoderBuffer.isDecoderBuffer(data)||(data=new DecoderBuffer(data,options)),this.tree._decode(data,options)},inherits(DERNode,Node),DERNode.prototype._peekTag=function peekTag(buffer,tag,any){if(buffer.isEmpty())return!1;const state=buffer.save(),decodedTag=derDecodeTag(buffer,"Failed to peek tag: \""+tag+"\"");return buffer.isError(decodedTag)?decodedTag:(buffer.restore(state),decodedTag.tag===tag||decodedTag.tagStr===tag||decodedTag.tagStr+"of"===tag||any)},DERNode.prototype._decodeTag=function decodeTag(buffer,tag,any){const decodedTag=derDecodeTag(buffer,"Failed to decode tag of \""+tag+"\"");if(buffer.isError(decodedTag))return decodedTag;let len=derDecodeLen(buffer,decodedTag.primitive,"Failed to get length of \""+tag+"\"");if(buffer.isError(len))return len;if(!any&&decodedTag.tag!==tag&&decodedTag.tagStr!==tag&&decodedTag.tagStr+"of"!==tag)return buffer.error("Failed to match tag: \""+tag+"\"");if(decodedTag.primitive||null!==len)return buffer.skip(len,"Failed to match body of: \""+tag+"\"");const state=buffer.save(),res=this._skipUntilEnd(buffer,"Failed to skip indefinite length body: \""+this.tag+"\"");return buffer.isError(res)?res:(len=buffer.offset-state.offset,buffer.restore(state),buffer.skip(len,"Failed to match body of: \""+tag+"\""))},DERNode.prototype._skipUntilEnd=function skipUntilEnd(buffer,fail){for(;;){const tag=derDecodeTag(buffer,fail);if(buffer.isError(tag))return tag;const len=derDecodeLen(buffer,tag.primitive,fail);if(buffer.isError(len))return len;let res;if(res=tag.primitive||null!==len?buffer.skip(len):this._skipUntilEnd(buffer,fail),buffer.isError(res))return res;if("end"===tag.tagStr)break}},DERNode.prototype._decodeList=function decodeList(buffer,tag,decoder,options){const result=[];for(;!buffer.isEmpty();){const possibleEnd=this._peekTag(buffer,"end");if(buffer.isError(possibleEnd))return possibleEnd;const res=decoder.decode(buffer,"der",options);if(buffer.isError(res)&&possibleEnd)break;result.push(res)}return result},DERNode.prototype._decodeStr=function decodeStr(buffer,tag){if("bitstr"===tag){const unused=buffer.readUInt8();return buffer.isError(unused)?unused:{unused:unused,data:buffer.raw()}}if("bmpstr"===tag){const raw=buffer.raw();if(1==raw.length%2)return buffer.error("Decoding of string type: bmpstr length mismatch");let str="";for(let i=0;i<raw.length/2;i++)str+=_StringfromCharCode(raw.readUInt16BE(2*i));return str}if("numstr"===tag){const numstr=buffer.raw().toString("ascii");return this._isNumstr(numstr)?numstr:buffer.error("Decoding of string type: numstr unsupported characters")}if("octstr"===tag)return buffer.raw();if("objDesc"===tag)return buffer.raw();if("printstr"===tag){const printstr=buffer.raw().toString("ascii");return this._isPrintstr(printstr)?printstr:buffer.error("Decoding of string type: printstr unsupported characters")}return /str$/.test(tag)?buffer.raw().toString():buffer.error("Decoding of string type: "+tag+" unsupported")},DERNode.prototype._decodeObjid=function decodeObjid(buffer,values,relative){let result;const identifiers=[];let ident=0,subident=0;for(;!buffer.isEmpty();)subident=buffer.readUInt8(),ident<<=7,ident|=127&subident,0==(128&subident)&&(identifiers.push(ident),ident=0);128&subident&&identifiers.push(ident);const first=0|identifiers[0]/40,second=identifiers[0]%40;if(result=relative?identifiers:[first,second].concat(identifiers.slice(1)),values){let tmp=values[result.join(" ")];void 0===tmp&&(tmp=values[result.join(".")]),void 0!==tmp&&(result=tmp)}return result},DERNode.prototype._decodeTime=function decodeTime(buffer,tag){const str=buffer.raw().toString();let year,mon,day,hour,min,sec;if("gentime"===tag)year=0|str.slice(0,4),mon=0|str.slice(4,6),day=0|str.slice(6,8),hour=0|str.slice(8,10),min=0|str.slice(10,12),sec=0|str.slice(12,14);else if("utctime"===tag)year=0|str.slice(0,2),mon=0|str.slice(2,4),day=0|str.slice(4,6),hour=0|str.slice(6,8),min=0|str.slice(8,10),sec=0|str.slice(10,12),year=70>year?2e3+year:1900+year;else return buffer.error("Decoding "+tag+" time is not supported yet");return Date.UTC(year,mon-1,day,hour,min,sec,0)},DERNode.prototype._decodeNull=function decodeNull(){return null},DERNode.prototype._decodeBool=function decodeBool(buffer){const res=buffer.readUInt8();return buffer.isError(res)?res:0!==res},DERNode.prototype._decodeInt=function decodeInt(buffer,values){const raw=buffer.raw();let res=new bignum(raw);return values&&(res=values[res.toString(10)]||res),res},DERNode.prototype._use=function use(entity,obj){return"function"==typeof entity&&(entity=entity(obj)),entity._getDecoder("der").tree}},{"../base/buffer":10,"../base/node":12,"../constants/der":14,"bn.js":22,inherits:145}],17:[function(require,module,exports){"use strict";const decoders=exports;decoders.der=require("./der"),decoders.pem=require("./pem")},{"./der":16,"./pem":18}],18:[function(require,module,exports){"use strict";function PEMDecoder(entity){DERDecoder.call(this,entity),this.enc="pem"}const inherits=require("inherits"),Buffer=require("safer-buffer").Buffer,DERDecoder=require("./der");inherits(PEMDecoder,DERDecoder),module.exports=PEMDecoder,PEMDecoder.prototype.decode=function decode(data,options){const lines=data.toString().split(/[\r\n]+/g),label=options.label.toUpperCase(),re=/^-----(BEGIN|END) ([^-]+)-----$/;let start=-1,end=-1;for(let i=0;i<lines.length;i++){const match=lines[i].match(re);if(null!==match&&match[2]===label)if(-1===start){if("BEGIN"!==match[1])break;start=i}else{if("END"!==match[1])break;end=i;break}}if(-1===start||-1===end)throw new Error("PEM section not found for: "+label);const base64=lines.slice(start+1,end).join("");base64.replace(/[^a-z0-9+/=]+/gi,"");const input=Buffer.from(base64,"base64");return DERDecoder.prototype.decode.call(this,input,options)}},{"./der":16,inherits:145,"safer-buffer":235}],19:[function(require,module,exports){"use strict";function DEREncoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function two(num){return 10>num?"0"+num:num}function encodeTag(tag,primitive,cls,reporter){let res;if("seqof"===tag?tag="seq":"setof"==tag&&(tag="set"),der.tagByName.hasOwnProperty(tag))res=der.tagByName[tag];else if("number"==typeof tag&&(0|tag)===tag)res=tag;else return reporter.error("Unknown tag: "+tag);return 31<=res?reporter.error("Multi-octet tag encoding unsupported"):(primitive||(res|=32),res|=der.tagClassByName[cls||"universal"]<<6,res)}const inherits=require("inherits"),Buffer=require("safer-buffer").Buffer,Node=require("../base/node"),der=require("../constants/der");module.exports=DEREncoder,DEREncoder.prototype.encode=function encode(data,reporter){return this.tree._encode(data,reporter).join()},inherits(DERNode,Node),DERNode.prototype._encodeComposite=function encodeComposite(tag,primitive,cls,content){const encodedTag=encodeTag(tag,primitive,cls,this.reporter);if(128>content.length){const header=Buffer.alloc(2);return header[0]=encodedTag,header[1]=content.length,this._createEncoderBuffer([header,content])}let lenOctets=1;for(let i=content.length;256<=i;i>>=8)lenOctets++;const header=Buffer.alloc(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;0<j;i--,j>>=8)header[i]=255&j;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function encodeStr(str,tag){if("bitstr"===tag)return this._createEncoderBuffer([0|str.unused,str.data]);if("bmpstr"===tag){const buf=Buffer.alloc(2*str.length);for(let i=0;i<str.length;i++)buf.writeUInt16BE(str.charCodeAt(i),2*i);return this._createEncoderBuffer(buf)}return"numstr"===tag?this._isNumstr(str)?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: numstr supports only digits and space"):"printstr"===tag?this._isPrintstr(str)?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(tag)?this._createEncoderBuffer(str):"objDesc"===tag?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: "+tag+" unsupported")},DERNode.prototype._encodeObjid=function encodeObjid(id,values,relative){if("string"==typeof id){if(!values)return this.reporter.error("string objid given, but no values map found");if(!values.hasOwnProperty(id))return this.reporter.error("objid not found in values map");id=values[id].split(/[\s.]+/g);for(let i=0;i<id.length;i++)id[i]|=0}else if(Array.isArray(id)){id=id.slice();for(let i=0;i<id.length;i++)id[i]|=0}if(!Array.isArray(id))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(id));if(!relative){if(40<=id[1])return this.reporter.error("Second objid identifier OOB");id.splice(0,2,40*id[0]+id[1])}let size=0;for(let i=0,ident;i<id.length;i++)for(ident=id[i],size++;128<=ident;ident>>=7)size++;const objid=Buffer.alloc(size);let offset=objid.length-1;for(let i=id.length-1,ident;0<=i;i--)for(ident=id[i],objid[offset--]=127&ident;0<(ident>>=7);)objid[offset--]=128|127&ident;return this._createEncoderBuffer(objid)},DERNode.prototype._encodeTime=function encodeTime(time,tag){let str;const date=new Date(time);return"gentime"===tag?str=[two(date.getUTCFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):"utctime"===tag?str=[two(date.getUTCFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+tag+" time is not supported yet"),this._encodeStr(str,"octstr")},DERNode.prototype._encodeNull=function encodeNull(){return this._createEncoderBuffer("")},DERNode.prototype._encodeInt=function encodeInt(num,values){if("string"==typeof num){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num));num=values[num]}if("number"!=typeof num&&!Buffer.isBuffer(num)){const numArray=num.toArray();!num.sign&&128&numArray[0]&&numArray.unshift(0),num=Buffer.from(numArray)}if(Buffer.isBuffer(num)){let size=num.length;0===num.length&&size++;const out=Buffer.alloc(size);return num.copy(out),0===num.length&&(out[0]=0),this._createEncoderBuffer(out)}if(128>num)return this._createEncoderBuffer(num);if(256>num)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;256<=i;i>>=8)size++;const out=Array(size);for(let i=out.length-1;0<=i;i--)out[i]=255&num,num>>=8;return 128&out[0]&&out.unshift(0),this._createEncoderBuffer(Buffer.from(out))},DERNode.prototype._encodeBool=function encodeBool(value){return this._createEncoderBuffer(value?255:0)},DERNode.prototype._use=function use(entity,obj){return"function"==typeof entity&&(entity=entity(obj)),entity._getEncoder("der").tree},DERNode.prototype._skipDefault=function skipDefault(dataBuffer,reporter,parent){const state=this._baseState;let i;if(null===state["default"])return!1;const data=dataBuffer.join();if(void 0===state.defaultBuffer&&(state.defaultBuffer=this._encodeValue(state["default"],reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i<data.length;i++)if(data[i]!==state.defaultBuffer[i])return!1;return!0}},{"../base/node":12,"../constants/der":14,inherits:145,"safer-buffer":235}],20:[function(require,module,exports){"use strict";const encoders=exports;encoders.der=require("./der"),encoders.pem=require("./pem")},{"./der":19,"./pem":21}],21:[function(require,module,exports){"use strict";function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc="pem"}const inherits=require("inherits"),DEREncoder=require("./der");inherits(PEMEncoder,DEREncoder),module.exports=PEMEncoder,PEMEncoder.prototype.encode=function encode(data,options){const buf=DEREncoder.prototype.encode.call(this,data),p=buf.toString("base64"),out=["-----BEGIN "+options.label+"-----"];for(let i=0;i<p.length;i+=64)out.push(p.slice(i,i+64));return out.push("-----END "+options.label+"-----"),out.join("\n")}},{"./der":19,inherits:145}],22:[function(require,module,exports){(function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return 65<=c&&70>=c?c-55:97<=c&&102>=c?c-87:15&c-48}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=_Mathmin(str.length,end),i=start,c;i<len;i++)c=str.charCodeAt(i)-48,r*=mul,r+=49<=c?c-49+10:17<=c?c-17+10:c;return r}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit<w.length;bit++){var off=0|bit/26,wbit=bit%26;w[bit]=(num.words[off]&1<<wbit)>>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k<len;k++){for(var ncarry=carry>>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out.strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k<out.length-1;k++){ncarry=hncarry,hncarry=0;for(var rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1);j<=maxJ;j++){var i=k-j,a=0|self.words[i],b=0|num.words[j],r=a*b,lo=67108863&r;ncarry=0|ncarry+(0|r/67108864),lo=0|lo+rword,rword=67108863&lo,ncarry=0|ncarry+(lo>>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer="undefined"!=typeof window&&"undefined"!=typeof window.Buffer?window.Buffer:require("buffer").Buffer}catch(e){}BN.isBN=function isBN(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return 0<left.cmp(right)?left:right},BN.min=function min(left,right){return 0>left.cmp(right)?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function _initNumber(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3);"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function _initArray(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j,w;if("be"===endian)for(i=number.length-1,j=0;0<=i;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i<number.length;i+=3)w=number[i]|number[i+1]<<8|number[i+2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j=0,w;if("be"===endian)for(i=number.length-1;i>=start;i-=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=0==parseLength%2?start+1:start;i<number.length;i+=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;i<end;i+=limbLen)word=parseBase(number,i,i+limbLen,base),this.imuln(limbPow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;i<mod;i++)pow*=base;this.imuln(pow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word)}this.strip()},BN.prototype.copy=function copy(dest){dest.words=Array(this.length);for(var i=0;i<this.length;i++)dest.words[i]=this.words[i];dest.length=this.length,dest.negative=this.negative,dest.red=this.red},BN.prototype.clone=function clone(){var r=new BN(null);return this.copy(r),r},BN.prototype._expand=function _expand(size){for(;this.length<size;)this.words[this.length++]=0;return this},BN.prototype.strip=function strip(){for(;1<this.length&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i<this.length;i++){var w=this.words[i],word=(16777215&(w<<off|carry)).toString(16);carry=16777215&w>>>24-off,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,26<=off&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2<this.length&&assert(!1,"Number can only safely store up to 53 bits"),0===this.negative?ret:-ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert("undefined"!=typeof Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||_Mathmax(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(0<reqLength,"Requested array length <= 0"),this.strip();var littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone(),b,i;if(!littleEndian){for(i=0;i<reqLength-byteLength;i++)res[i]=0;for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[reqLength-i-1]=b}else{for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i<reqLength;i++)res[i]=0}return res},BN.prototype._countBits=_Mathclz?function _countBits(w){return 32-_Mathclz(w)}:function _countBits(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0,b;i<this.length&&(b=this._zeroBits(this.words[i]),r+=b,26===b);i++);return r},BN.prototype.byteLength=function byteLength(){return _Mathceil(this.bitLength()/8)},BN.prototype.toTwos=function toTwos(width){return 0===this.negative?this.clone():this.abs().inotn(width).iaddn(1)},BN.prototype.fromTwos=function fromTwos(width){return this.testn(width-1)?this.notn(width).iaddn(1).ineg():this.clone()},BN.prototype.isNeg=function isNeg(){return 0!==this.negative},BN.prototype.neg=function neg(){return this.clone().ineg()},BN.prototype.ineg=function ineg(){return this.isZero()||(this.negative^=1),this},BN.prototype.iuor=function iuor(num){for(;this.length<num.length;)this.words[this.length++]=0;for(var i=0;i<num.length;i++)this.words[i]|=num.words[i];return this.strip()},BN.prototype.ior=function ior(num){return assert(0==(this.negative|num.negative)),this.iuor(num)},BN.prototype.or=function or(num){return this.length>num.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;i<b.length;i++)this.words[i]&=num.words[i];return this.length=b.length,this.strip()},BN.prototype.iand=function iand(num){return assert(0==(this.negative|num.negative)),this.iuand(num)},BN.prototype.and=function and(num){return this.length>num.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;i<b.length;i++)this.words[i]=a.words[i]^b.words[i];if(this!==a)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=a.length,this.strip()},BN.prototype.ixor=function ixor(num){return assert(0==(this.negative|num.negative)),this.iuxor(num)},BN.prototype.xor=function xor(num){return this.length>num.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0<bitsLeft&&bytesNeeded--;for(var i=0;i<bytesNeeded;i++)this.words[i]=67108863&~this.words[i];return 0<bitsLeft&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<<wbit:this.words[off]&=~(1<<wbit),this.strip()},BN.prototype.iadd=function iadd(num){var r;if(0!==this.negative&&0===num.negative)return this.negative=0,r=this.isub(num),this.negative^=1,this._normSign();if(0===this.negative&&0!==num.negative)return num.negative=0,r=this.isub(num),num.negative=1,r._normSign();var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])+(0|b.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this},BN.prototype.add=function add(num){var res;return 0!==num.negative&&0===this.negative?(num.negative=0,res=this.sub(num),num.negative^=1,res):0===num.negative&&0!==this.negative?(this.negative=0,res=num.sub(this),this.negative=1,res):this.length>num.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0<cmp?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])-(0|b.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;if(0===carry&&i<a.length&&a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=_Mathmax(this.length,i),a!==this&&(this.negative=1),this.strip()},BN.prototype.sub=function sub(num){return this.clone().isub(num)};var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words,b=num.words,o=out.words,c=0,a0=0|a[0],al0=8191&a0,ah0=a0>>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i<N;i++)t[i]=this.revBin(i,l,N);return t},FFTM.prototype.revBin=function revBin(x,l,N){if(0===x||x===N-1)return x;for(var rb=0,i=0;i<l;i++)rb|=(1&x)<<l-i-1,x>>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i<N;i++)rtws[i]=rws[rbt[i]],itws[i]=iws[rbt[i]]},FFTM.prototype.transform=function transform(rws,iws,rtws,itws,N,rbt){this.permute(rbt,rws,iws,rtws,itws,N);for(var s=1;s<N;s<<=1)for(var l=s<<1,rtwdf=_Mathcos(2*_MathPI/l),itwdf=_Mathsin(2*_MathPI/l),p=0;p<N;p+=l)for(var rtwdf_=rtwdf,itwdf_=itwdf,j=0;j<s;j++){var re=rtws[p+j],ie=itws[p+j],ro=rtws[p+j+s],io=itws[p+j+s],rx=rtwdf_*ro-itwdf_*io;io=rtwdf_*io+itwdf_*ro,ro=rx,rtws[p+j]=re+ro,itws[p+j]=ie+io,rtws[p+j+s]=re-ro,itws[p+j+s]=ie-io,j!==l&&(rx=rtwdf*rtwdf_-itwdf*itwdf_,itwdf_=rtwdf*itwdf_+itwdf*rtwdf_,rtwdf_=rx)}},FFTM.prototype.guessLen13b=function guessLen13b(n,m){var N=1|_Mathmax(m,n),odd=1&N,i=0;for(N=0|N/2;N;N>>>=1)i++;return 1<<i+1+odd},FFTM.prototype.conjugate=function conjugate(rws,iws,N){if(!(1>=N))for(var i=0,t;i<N/2;i++)t=rws[i],rws[i]=rws[N-i-1],rws[N-i-1]=t,t=iws[i],iws[i]=-iws[N-i-1],iws[N-i-1]=-t},FFTM.prototype.normalize13b=function normalize13b(ws,N){for(var carry=0,i=0,w;i<N/2;i++)w=8192*_Mathround(ws[2*i+1]/N)+_Mathround(ws[2*i]/N)+carry,ws[i]=67108863&w,carry=67108864>w?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function convert13b(ws,len,rws,N){for(var carry=0,i=0;i<len;i++)carry+=0|ws[i],rws[2*i]=8191&carry,carry>>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i<N;++i)rws[i]=0;assert(0===carry),assert(0==(-8192&carry))},FFTM.prototype.stub=function stub(N){for(var ph=Array(N),i=0;i<N;i++)ph[i]=0;return ph},FFTM.prototype.mulp=function mulp(x,y,out){var N=2*this.guessLen13b(x.length,y.length),rbt=this.makeRBT(N),_=this.stub(N),rws=Array(N),rwst=Array(N),iwst=Array(N),nrws=Array(N),nrwst=Array(N),niwst=Array(N),rmws=out.words;rmws.length=N,this.convert13b(x.words,x.length,rws,N),this.convert13b(y.words,y.length,nrws,N),this.transform(rws,_,rwst,iwst,N,rbt),this.transform(nrws,_,nrwst,niwst,N,rbt);for(var i=0,rx;i<N;i++)rx=rwst[i]*nrwst[i]-iwst[i]*niwst[i],iwst[i]=rwst[i]*niwst[i]+iwst[i]*nrwst[i],rwst[i]=rx;return this.conjugate(rwst,iwst,N),this.transform(rwst,iwst,rmws,_,N,rbt),this.conjugate(rmws,_,N),this.normalize13b(rmws,N),out.negative=x.negative^y.negative,out.length=x.length+y.length,out.strip()},BN.prototype.mul=function mul(num){var out=new BN(null);return out.words=Array(this.length+num.length),this.mulTo(num,out)},BN.prototype.mulf=function mulf(num){var out=new BN(null);return out.words=Array(this.length+num.length),jumboMulTo(this,num,out)},BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)},BN.prototype.imuln=function imuln(num){assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i<this.length;i++){var w=(0|this.words[i])*num,lo=(67108863&w)+(67108863&carry);carry>>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i<w.length&&!(0!==w[i]);i++,res=res.sqr());if(++i<w.length)for(var q=res.sqr();i<w.length;i++,q=q.sqr())0!==w[i]&&(res=res.mul(q));return res},BN.prototype.iushln=function iushln(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(0!=r){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask,c=(0|this.words[i])-newCarry<<r;this.words[i]=c|carry,carry=newCarry>>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;i<s;i++)this.words[i]=0;this.length+=s}return this.strip()},BN.prototype.ishln=function ishln(bits){return assert(0===this.negative),this.iushln(bits)},BN.prototype.iushrn=function iushrn(bits,hint,extended){assert("number"==typeof bits&&0<=bits);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=_Mathmin((bits-r)/26,this.length),mask=67108863^67108863>>>r<<r,maskedWords=extended;if(h-=s,h=_Mathmax(0,h),maskedWords){for(var i=0;i<s;i++)maskedWords.words[i]=this.words[i];maskedWords.length=s}if(0===s);else if(this.length>s)for(this.length-=s,i=0;i<this.length;i++)this.words[i]=this.words[i+s];else this.words[0]=0,this.length=1;var carry=0;for(i=this.length-1;0<=i&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&0<=bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return!1;var w=this.words[s];return!!(w&q)},BN.prototype.imaskn=function imaskn(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!=r&&s++,this.length=_Mathmin(s,this.length),0!=r){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this.strip()},BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)},BN.prototype.iaddn=function iaddn(num){return assert("number"==typeof num),assert(67108864>num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&67108864<=this.words[i];i++)this.words[i]-=67108864,i==this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=_Mathmax(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(67108864>num),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i<this.length&&0>this.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this.strip()},BN.prototype.addn=function addn(num){return this.clone().iaddn(num)},BN.prototype.subn=function subn(num){return this.clone().isubn(num)},BN.prototype.iabs=function iabs(){return this.negative=0,this},BN.prototype.abs=function abs(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i<num.length;i++){w=(0|this.words[i+shift])+carry;var right=(0|num.words[i])*mul;w-=67108863&right,carry=(w>>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i<this.length-shift;i++)w=(0|this.words[i+shift])+carry,carry=w>>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i<this.length;i++)w=-(0|this.words[i])+carry,carry=w>>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;i<q.length;i++)q.words[i]=0}var diff=a.clone()._ishlnsubmul(b,1,m);0===diff.negative&&(a=diff,q&&(q.words[m]=1));for(var j=m-1,qj;0<=j;j--){for(qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]),qj=_Mathmin(0|qj/bhi,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0==(this.negative&num.negative)?num.length>this.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modn=function modn(num){assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(x.iushrn(i);0<i--;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(y.iushrn(j);0<j--;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);0<=x.cmp(y)?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0===a.negative?a.clone():a.umod(p);for(var x1=new BN(1),x2=new BN(0),delta=b.clone();0<a.cmpn(1)&&0<b.cmpn(1);){for(var i=0,im=1;0==(a.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(a.iushrn(i);0<i--;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(b.iushrn(j);0<j--;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);0<=a.cmp(b)?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,0>res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return this._expand(s+1),this.words[s]|=q,this;for(var carry=q,i=s,w;0!==carry&&i<this.length;i++)w=0|this.words[i],w+=carry,carry=w>>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this.strip();var res;if(1<this.length)res=1;else{negative&&(num=-num),assert(67108863>=num,"Number is too big");var w=0|this.words[0];res=w===num?0:w<num?-1:1}return 0===this.negative?res:0|-res},BN.prototype.cmp=function cmp(num){if(0!==this.negative&&0===num.negative)return-1;if(0===this.negative&&0!==num.negative)return 1;var res=this.ucmp(num);return 0===this.negative?res:0|-res},BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;for(var res=0,i=this.length-1;0<=i;i--){var a=0|this.words[i],b=0|num.words[i];if(a!=b){a<b?res=-1:a>b&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return 0<=this.cmpn(num)},BN.prototype.gte=function gte(num){return 0<=this.cmp(num)},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return 0>=this.cmpn(num)},BN.prototype.lte=function lte(num){return 0>=this.cmp(num)},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);return 0===cmp?(r.words[0]=0,r.length=1):0<cmp?r.isub(this.p):void 0===r.strip?r._strip():r.strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var mask=4194303,outLen=_Mathmin(input.length,9),i=0;i<outLen;i++)output.words[i]=input.words[i];if(output.length=outLen,9>=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i<input.length;i++){var next=0|input.words[i];input.words[i-10]=(next&mask)<<4|prev>>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10<input.length?10:9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0,w;i<num.length;i++)w=0|num.words[i],lo+=977*w,num.words[i]=67108863&lo,lo=64*w+(0|lo/67108864);return 0===num.words[num.length-1]&&(num.length--,0===num.words[num.length-1]&&num.length--),num},inherits(P224,MPrime),inherits(P192,MPrime),inherits(P25519,MPrime),P25519.prototype.imulK=function imulK(num){for(var carry=0,i=0;i<num.length;i++){var hi=19*(0|num.words[i])+carry,lo=67108863&hi;hi>>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b),c=b.redSqr(),t=t.redMul(c),m=i}return r},Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);return 0===inv.negative?this.imod(inv):(inv.negative=0,this.imod(inv).redNeg())},Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(0===num.cmpn(1))return a.clone();var windowSize=4,wnd=Array(16);wnd[0]=new BN(1).toRed(this),wnd[1]=a;for(var i=2;i<wnd.length;i++)wnd[i]=this.mul(wnd[i-1],a);var res=wnd[0],current=0,currentLen=0,start=num.bitLength()%26;for(0===start&&(start=26),i=num.length-1;0<=i;i--){for(var word=num.words[i],j=start-1,bit;0<=j;j--){if(bit=1&word>>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:41}],23:[function(require,module,exports){"use strict";function getLens(b64){var len=b64.length;if(0<len%4)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");-1===validLen&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=0<placeHoldersLen?validLen-4:validLen,tmp,i;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=255&tmp>>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;i<end;i+=3)tmp=(16711680&uint8[i]<<16)+(65280&uint8[i+1]<<8)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes,tmp;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62,revLookup[95]=63},{}],24:[function(require,module,exports){(function(Buffer){(function(){function getIntFromBuffer(buffer,start,end){let sum=0,sign=1;for(let i=start;i<end;i++){const num=buffer[i];if(58>num&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}const INTEGER_START=105,STRING_DELIM=58,DICTIONARY_START=100,LIST_START=108,END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case DICTIONARY_START:return decode.dictionary();case LIST_START:return decode.list();case INTEGER_START:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){let i=decode.position;const c=decode.data.length,d=decode.data;for(;i<c;){if(d[i]===chr)return i;i++}throw new Error("Invalid data: Missing delimiter \""+_StringfromCharCode(chr)+"\" [0x"+chr.toString(16)+"]")},decode.dictionary=function(){decode.position++;const dict={};for(;decode.data[decode.position]!==END_OF_TYPE;)dict[decode.buffer()]=decode.next();return decode.position++,dict},decode.list=function(){decode.position++;const lst=[];for(;decode.data[decode.position]!==END_OF_TYPE;)lst.push(decode.next());return decode.position++,lst},decode.integer=function(){const end=decode.find(END_OF_TYPE),number=getIntFromBuffer(decode.data,decode.position+1,end);return decode.position+=end+1-decode.position,number},decode.buffer=function(){let sep=decode.find(STRING_DELIM);const length=getIntFromBuffer(decode.data,decode.position,sep),end=++sep+length;return decode.position=end,decode.encoding?decode.data.toString(decode.encoding,sep,end):decode.data.slice(sep,end)},module.exports=decode}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],25:[function(require,module,exports){(function(Buffer){(function(){function encode(data,buffer,offset){const buffers=[];let result=null;return encode._encode(buffers,data),result=Buffer.concat(buffers),encode.bytes=result.length,Buffer.isBuffer(buffer)?(result.copy(buffer,offset),buffer):result}const{getType}=require("./util.js");encode.bytes=-1,encode._floatConversionDetected=!1,encode._encode=function(buffers,data){if(null!=data)switch(getType(data)){case"buffer":encode.buffer(buffers,data);break;case"object":encode.dict(buffers,data);break;case"map":encode.dictMap(buffers,data);break;case"array":encode.list(buffers,data);break;case"set":encode.listSet(buffers,data);break;case"string":encode.string(buffers,data);break;case"number":encode.number(buffers,data);break;case"boolean":encode.number(buffers,data);break;case"arraybufferview":encode.buffer(buffers,Buffer.from(data.buffer,data.byteOffset,data.byteLength));break;case"arraybuffer":encode.buffer(buffers,Buffer.from(data));}};const buffE=Buffer.from("e"),buffD=Buffer.from("d"),buffL=Buffer.from("l");encode.buffer=function(buffers,data){buffers.push(Buffer.from(data.length+":"),data)},encode.string=function(buffers,data){buffers.push(Buffer.from(Buffer.byteLength(data)+":"+data))},encode.number=function(buffers,data){const maxLo=2147483648,hi=data/2147483648<<0,lo=data%2147483648<<0,val=hi*2147483648+lo;buffers.push(Buffer.from("i"+val+"e")),val===data||encode._floatConversionDetected||(encode._floatConversionDetected=!0,console.warn("WARNING: Possible data corruption detected with value \""+data+"\":","Bencoding only defines support for integers, value was converted to \""+val+"\""),console.trace())},encode.dict=function(buffers,data){buffers.push(buffD);let j=0,k;const keys=Object.keys(data).sort(),kl=keys.length;for(;j<kl;j++)k=keys[j],null!=data[k]&&(encode.string(buffers,k),encode._encode(buffers,data[k]));buffers.push(buffE)},encode.dictMap=function(buffers,data){buffers.push(buffD);const keys=Array.from(data.keys()).sort();for(const key of keys)null!=data.get(key)&&(Buffer.isBuffer(key)?encode._encode(buffers,key):encode.string(buffers,key+""),encode._encode(buffers,data.get(key)));buffers.push(buffE)},encode.list=function(buffers,data){let i=0;const c=data.length;for(buffers.push(buffL);i<c;i++)null!=data[i]&&encode._encode(buffers,data[i]);buffers.push(buffE)},encode.listSet=function(buffers,data){buffers.push(buffL);for(const item of data)null!=item&&encode._encode(buffers,item);buffers.push(buffE)},module.exports=encode}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":28,buffer:75}],26:[function(require,module,exports){(function(Buffer){(function(){function listLength(list){let length=2;for(const value of list)length+=encodingLength(value);return length}function mapLength(map){let length=2;for(const[key,value]of map){const keyLength=Buffer.byteLength(key);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value)}return length}function objectLength(value){let length=2;const keys=Object.keys(value);for(let i=0;i<keys.length;i++){const keyLength=Buffer.byteLength(keys[i]);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value[keys[i]])}return length}function stringLength(value){const length=Buffer.byteLength(value);return digitCount(length)+1+length}function arrayBufferLength(value){const length=value.byteLength-value.byteOffset;return digitCount(length)+1+length}function encodingLength(value){const length=0;if(null==value)return 0;const type=getType(value);switch(type){case"buffer":return digitCount(value.length)+1+value.length;case"arraybufferview":return arrayBufferLength(value);case"string":return stringLength(value);case"array":case"set":return listLength(value);case"number":return 1+digitCount(_Mathfloor(value))+1;case"bigint":return 1+value.toString().length+1;case"object":return objectLength(value);case"map":return mapLength(value);default:throw new TypeError(`Unsupported value of type "${type}"`);}}const{digitCount,getType}=require("./util.js");module.exports=encodingLength}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":28,buffer:75}],27:[function(require,module,exports){const bencode=module.exports;bencode.encode=require("./encode.js"),bencode.decode=require("./decode.js"),bencode.byteLength=bencode.encodingLength=require("./encoding-length.js")},{"./decode.js":24,"./encode.js":25,"./encoding-length.js":26}],28:[function(require,module,exports){(function(Buffer){(function(){const util=module.exports;util.digitCount=function digitCount(value){var _Mathlog=Math.log10;const sign=0>value?1:0;return value=_Mathabs(+(value||1)),_Mathfloor(_Mathlog(value))+1+sign},util.getType=function getType(value){return Buffer.isBuffer(value)?"buffer":ArrayBuffer.isView(value)?"arraybufferview":Array.isArray(value)?"array":value instanceof Number?"number":value instanceof Boolean?"boolean":value instanceof Set?"set":value instanceof Map?"map":value instanceof String?"string":value instanceof ArrayBuffer?"arraybuffer":typeof value}}).call(this)}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":147}],29:[function(require,module,exports){function composeRange(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1<cur.length?`${cur[0]}-${cur[cur.length-1]}`:`${cur[0]}`)}function parseRange(range){const generateRange=(start,end=start)=>Array.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur,idx,arr)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=composeRange},{}],30:[function(require,module,exports){module.exports=function(haystack,needle,comparator,low,high){var mid,cmp;if(void 0===low)low=0;else if(low|=0,0>low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high<low||high>=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0<cmp)high=mid-1;else return mid;return~low}},{}],31:[function(require,module,exports){"use strict";function getByteSize(num){var out=num>>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j<this.buffer.length&&!!(this.buffer[j]&128>>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length<j+1){var length=_Mathmax(j+1,_Mathmin(2*this.buffer.length,this.grow));if(length<=this.grow){var newBuffer=new Uint8Array(length);newBuffer.set(this.buffer),this.buffer=newBuffer}}this.buffer[j]|=128>>i%8}else j<this.buffer.length&&(this.buffer[j]&=~(128>>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i<end;i++)fn(!!(byte&y),i),y=1==y?(byte=this.buffer[++j],128):y>>1},BitField}();exports.default=BitField},{}],32:[function(require,module,exports){(function(Buffer){(function(){function xor(a,b){for(let len=a.length;len--;)a[len]^=b[len];return a}/*! bittorrent-protocol. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,crypto=require("crypto"),debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),sha1=require("simple-sha1"),speedometer=require("speedometer"),stream=require("readable-stream"),RC4=require("rc4"),BITFIELD_GROW=4e5,KEEP_ALIVE_TIMEOUT=55e3,ALLOWED_FAST_SET_MAX_LENGTH=100,MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0],MESSAGE_HAVE_ALL=Buffer.from([0,0,0,1,14]),MESSAGE_HAVE_NONE=Buffer.from([0,0,0,1,15]),DH_PRIME="ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563",DH_GENERATOR=2,VC=Buffer.from([0,0,0,0,0,0,0,0]),CRYPTO_PROVIDE=Buffer.from([0,0,1,2]),CRYPTO_SELECT=Buffer.from([0,0,0,2]);class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class HaveAllBitField{constructor(){this.buffer=new Uint8Array}get(index){return!0}set(index){}}class Wire extends stream.Duplex{constructor(type=null,retries=0,peEnabled=!1){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=type,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:BITFIELD_GROW}),this.extensions={},this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this.hasFast=!1,this.allowedFastSet=[],this.peerAllowedFastSet=[],this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=peEnabled,peEnabled?(this._dh=crypto.createDiffieHellman(DH_PRIME,"hex",DH_GENERATOR),this._myPubKey=this._dh.generateKeys("hex")):this._myPubKey=null,this._peerPubKey=null,this._sharedSecret=null,this._peerCryptoProvide=[],this._cryptoHandshakeDone=!1,this._cryptoSyncPattern=null,this._waitMaxBytes=null,this._encryptionMethod=null,this._encryptGenerator=null,this._decryptGenerator=null,this._setGenerators=!1,this.once("finish",()=>this._onFinish()),this.on("finish",this._onFinish),this._debug("type:",this.type),"tcpIncoming"===this.type&&this._peEnabled?this._determineHandshakeType():"tcpOutgoing"===this.type&&this._peEnabled&&0===retries?this._parsePe2():this._parseHandshake(null)}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},KEEP_ALIVE_TIMEOUT))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._resetTimeout(!0)}destroy(){if(!this.destroyed)return this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end(),this}end(...args){return this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}sendPe1(){if(this._peEnabled){const padALen=_Mathfloor(513*Math.random()),padA=randombytes(padALen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padA]))}}sendPe2(){const padBLen=_Mathfloor(513*Math.random()),padB=randombytes(padBLen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padB]))}sendPe3(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex"),hash2Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req2")+infoHash,"hex")),"hex"),hash3Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),"hex"),hashesXorBuffer=xor(hash2Buffer,hash3Buffer),padCLen=randombytes(2).readUInt16BE(0)%512,padCBuffer=randombytes(padCLen);let vcAndProvideBuffer=Buffer.alloc(14+padCLen+2);VC.copy(vcAndProvideBuffer),CRYPTO_PROVIDE.copy(vcAndProvideBuffer,8),vcAndProvideBuffer.writeInt16BE(padCLen,12),padCBuffer.copy(vcAndProvideBuffer,14),vcAndProvideBuffer.writeInt16BE(0,14+padCLen),vcAndProvideBuffer=this._encryptHandshake(vcAndProvideBuffer),this._push(Buffer.concat([hash1Buffer,hashesXorBuffer,vcAndProvideBuffer]))}sendPe4(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const padDLen=randombytes(2).readUInt16BE(0)%512,padDBuffer=randombytes(padDLen);let vcAndSelectBuffer=Buffer.alloc(14+padDLen);VC.copy(vcAndSelectBuffer),CRYPTO_SELECT.copy(vcAndSelectBuffer,8),vcAndSelectBuffer.writeInt16BE(padDLen,12),padDBuffer.copy(vcAndSelectBuffer,14),vcAndSelectBuffer=this._encryptHandshake(vcAndSelectBuffer),this._push(vcAndSelectBuffer),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),this._infoHash=infoHashBuffer,20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);this.extensions={extended:!0,dht:!!(extensions&&extensions.dht),fast:!!(extensions&&extensions.fast)},reserved[5]|=16,this.extensions.dht&&(reserved[7]|=1),this.extensions.fast&&(reserved[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(MESSAGE_CHOKE),this.hasFast)for(let allowedCount=0;this.peerRequests.length>allowedCount;){const request=this.peerRequests[allowedCount];this.allowedFastSet.includes(request.piece)?++allowedCount:this.reject(request.piece,request.offset,request.length)}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking&&!(this.hasFast&&this.peerAllowedFastSet.includes(index))?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),!this._timeout&&this._resetTimeout(!0),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this._message(7,[index,offset],buffer),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}suggest(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("suggest %d",index),this._message(13,[index],null)}haveAll(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-all"),this._push(MESSAGE_HAVE_ALL)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(MESSAGE_HAVE_NONE)}reject(index,offset,length){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this._message(16,[index,offset,length],null)}allowedFast(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("allowed-fast %d",index),this.allowedFastSet.includes(index)||this.allowedFastSet.push(index),this._message(17,[index],null)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}setEncrypt(sharedSecret,infoHash){let encryptKey,decryptKey,encryptKeyBuf,encryptKeyIntArray,decryptKeyBuf,decryptKeyIntArray;switch(this.type){case"tcpIncoming":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;case"tcpOutgoing":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;default:return!1;}for(let i=0;1024>i;i++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;i<numbers.length;i++)buffer.writeUInt32BE(numbers[i],5+4*i);this._push(buffer),data&&this._push(data)}_push(data){if(!this._finished)return 2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._encrypt(data)),this.push(data)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onPe1(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}_onPe3(hashesXorBuffer){const hash3=sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),sKeyHash=xor(Buffer.from(hash3,"hex"),hashesXorBuffer).toString("hex");this.emit("pe3",sKeyHash)}_onPe3Encrypted(vcBuffer,peerProvideBuffer){if(!vcBuffer.equals(VC))return this._debug("Error: verification constant did not match"),void this.destroy();for(const provideByte of peerProvideBuffer.values())0!==provideByte&&this._peerCryptoProvide.push(provideByte);this._peerCryptoProvide.includes(2)?this._encryptionMethod=2:(this._debug("Error: RC4 encryption method not provided by peer"),this.destroy())}_onPe4(peerSelectBuffer){this._encryptionMethod=peerSelectBuffer.readUInt8(3),CRYPTO_PROVIDE.includes(this._encryptionMethod)||(this._debug("Error: peer selected invalid crypto method"),this.destroy()),this._cryptoHandshakeDone=!0,this._debug("crypto handshake done"),this.emit("pe4")}_onHandshake(infoHashBuffer,peerIdBuffer,extensions){const infoHash=infoHashBuffer.toString("hex"),peerId=peerIdBuffer.toString("hex");for(const name in this._debug("got handshake i=%s p=%s exts=%o",infoHash,peerId,extensions),this.peerId=peerId,this.peerIdBuffer=peerIdBuffer,this.peerExtensions=extensions,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",infoHash,peerId,extensions),this._ext)this._ext[name].onHandshake(infoHash,peerId,extensions);extensions.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){if(this.peerChoking=!0,this._debug("got choke"),this.emit("choke"),!this.hasFast)for(;this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(index){this.peerPieces.get(index)||(this._debug("got have %d",index),this.peerPieces.set(index,!0),this.emit("have",index))}_onBitField(buffer){this.peerPieces=new BitField(buffer),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(index,offset,length){if(this.amChoking&&!(this.hasFast&&this.allowedFastSet.includes(index)))return void(this.hasFast&&this.reject(index,offset,length));this._debug("got request index=%d offset=%d length=%d",index,offset,length);const respond=(err,buffer)=>request===this._pull(this.peerRequests,index,offset,length)?err?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message),void(this.hasFast&&this.reject(index,offset,length))):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onSuggest(index){return this.hasFast?void(this._debug("got suggest %d",index),this.emit("suggest",index)):(this._debug("Error: got suggest whereas fast extension is disabled"),void this.destroy())}_onHaveAll(){return this.hasFast?void(this._debug("got have-all"),this.peerPieces=new HaveAllBitField,this.emit("have-all")):(this._debug("Error: got have-all whereas fast extension is disabled"),void this.destroy())}_onHaveNone(){return this.hasFast?void(this._debug("got have-none"),this.emit("have-none")):(this._debug("Error: got have-none whereas fast extension is disabled"),void this.destroy())}_onReject(index,offset,length){return this.hasFast?void(this._debug("got reject index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was rejected"),null),this.emit("reject",index,offset,length)):(this._debug("Error: got reject whereas fast extension is disabled"),void this.destroy())}_onAllowedFast(index){return this.hasFast?void(this._debug("got allowed-fast %d",index),!this.peerAllowedFastSet.includes(index)&&this.peerAllowedFastSet.push(index),this.peerAllowedFastSet.length>ALLOWED_FAST_SET_MAX_LENGTH&&this.peerAllowedFastSet.shift(),this.emit("allowed-fast",index)):(this._debug("Error: got allowed-fast whereas fast extension is disabled"),void this.destroy())}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;if(this.peerExtendedHandshake=info,"object"==typeof info.m)for(const name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(const name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._decrypt(data)),this._bufferSize+=data.length,this._buffer.push(data),1<this._buffer.length&&(this._buffer=[Buffer.concat(this._buffer,this._bufferSize)]),this._cryptoSyncPattern){const index=this._buffer[0].indexOf(this._cryptoSyncPattern);if(-1!==index)this._buffer[0]=this._buffer[0].slice(index+this._cryptoSyncPattern.length),this._bufferSize-=index+this._cryptoSyncPattern.length,this._cryptoSyncPattern=null;else if(this._bufferSize+data.length>this._waitMaxBytes+this._cryptoSyncPattern.length)return this._debug("Error: could not resynchronize"),void this.destroy()}for(;this._bufferSize>=this._parserSize&&!this._cryptoSyncPattern;)if(0===this._parserSize)this._parser(Buffer.from([]));else{const buffer=this._buffer[0];this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._resetTimeout(!this.peerChoking&&!this._finished),request.callback(err,buffer))}_resetTimeout(setAgain){if(!setAgain||!this._timeoutMs||!this.requests.length)return clearTimeout(this._timeout),this._timeout=null,void(this._timeoutExpiresAt=null);const timeoutExpiresAt=Date.now()+this._timeoutMs;if(this._timeout){if(timeoutExpiresAt-this._timeoutExpiresAt<.05*this._timeoutMs)return;clearTimeout(this._timeout)}this._timeoutExpiresAt=timeoutExpiresAt,this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref()}_parse(size,parser){this._parserSize=size,this._parser=parser}_parseUntil(pattern,maxBytes){this._cryptoSyncPattern=pattern,this._waitMaxBytes=maxBytes}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0<length?this._parse(length,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(buffer){switch(this._parse(4,this._onMessageLength),buffer[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(buffer.readUInt32BE(1));case 5:return this._onBitField(buffer.slice(1));case 6:return this._onRequest(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 7:return this._onPiece(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.slice(9));case 8:return this._onCancel(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 9:return this._onPort(buffer.readUInt16BE(1));case 13:return this._onSuggest(buffer.readUInt32BE(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 17:return this._onAllowedFast(buffer.readUInt32BE(1));case 20:return this._onExtended(buffer.readUInt8(1),buffer.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",buffer);}}_determineHandshakeType(){this._parse(1,pstrLenBuffer=>{const pstrlen=pstrLenBuffer.readUInt8(0);19===pstrlen?this._parse(pstrlen+48,this._onHandshakeBuffer):this._parsePe1(pstrLenBuffer)})}_parsePe1(pubKeyPrefix){this._parse(95,pubKeySuffix=>{this._onPe1(Buffer.concat([pubKeyPrefix,pubKeySuffix])),this._parsePe3()})}_parsePe2(){this._parse(96,pubKey=>{for(this._onPe2(pubKey);!this._setGenerators;);this._parsePe4()})}_parsePe3(){const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex");this._parseUntil(hash1Buffer,512),this._parse(20,buffer=>{for(this._onPe3(buffer);!this._setGenerators;);this._parsePe3Encrypted()})}_parsePe3Encrypted(){this._parse(14,buffer=>{const vcBuffer=this._decryptHandshake(buffer.slice(0,8)),peerProvideBuffer=this._decryptHandshake(buffer.slice(8,12)),padCLen=this._decryptHandshake(buffer.slice(12,14)).readUInt16BE(0);this._parse(padCLen,padCBuffer=>{padCBuffer=this._decryptHandshake(padCBuffer),this._parse(2,iaLenBuf=>{const iaLen=this._decryptHandshake(iaLenBuf).readUInt16BE(0);this._parse(iaLen,iaBuffer=>{iaBuffer=this._decryptHandshake(iaBuffer),this._onPe3Encrypted(vcBuffer,peerProvideBuffer,padCBuffer,iaBuffer);const pstrlen=iaLen?iaBuffer.readUInt8(0):null,protocol=iaLen?iaBuffer.slice(1,20):null;19===pstrlen&&"BitTorrent protocol"===protocol.toString()?this._onHandshakeBuffer(iaBuffer.slice(1)):this._parseHandshake()})})})})}_parsePe4(){const vcBufferEncrypted=this._decryptHandshake(VC);this._parseUntil(vcBufferEncrypted,512),this._parse(6,buffer=>{const peerSelectBuffer=this._decryptHandshake(buffer.slice(0,4)),padDLen=this._decryptHandshake(buffer.slice(4,6)).readUInt16BE(0);this._parse(padDLen,padDBuf=>{this._decryptHandshake(padDBuf),this._onPe4(peerSelectBuffer),this._parseHandshake(null)})})}_parseHandshake(){this._parse(1,buffer=>{const pstrlen=buffer.readUInt8(0);return 19===pstrlen?void this._parse(pstrlen+48,this._onHandshakeBuffer):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",pstrlen.toString()),void this.end())})}_onHandshakeBuffer(handshake){const protocol=handshake.slice(0,19);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(19),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),fast:!!(4&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i<requests.length;i++){const req=requests[i];if(req.piece===piece&&req.offset===offset&&req.length===length)return arrayRemove(requests,i),req}return null}_encryptHandshake(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_encrypt(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator||2!==this._encryptionMethod)return crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_decryptHandshake(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_decrypt(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator||2!==this._encryptionMethod)return decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_utfToHex(str){return Buffer.from(str,"utf8").toString("hex")}}module.exports=Wire}).call(this)}).call(this,require("buffer").Buffer)},{bencode:27,bitfield:31,buffer:75,crypto:89,debug:90,randombytes:208,rc4:212,"readable-stream":227,"simple-sha1":247,speedometer:254,"unordered-array-remove":273}],33:[function(require,module,exports){(function(process,Buffer){(function(){const debug=require("debug")("bittorrent-tracker:client"),EventEmitter=require("events"),once=require("once"),parallel=require("run-parallel"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),common=require("./lib/common"),HTTPTracker=require("./lib/client/http-tracker"),UDPTracker=require("./lib/client/udp-tracker"),WebSocketTracker=require("./lib/client/websocket-tracker");class Client 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(!opts.announce)throw new Error("Option `announce` 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._peerIdBuffer=Buffer.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._infoHashBuffer=Buffer.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),debug("new client %s",this.infoHash),this.destroyed=!1,this._port=opts.port,this._getAnnounceOpts=opts.getAnnounceOpts,this._rtcConfig=opts.rtcConfig,this._userAgent=opts.userAgent,this._proxyOpts=opts.proxyOpts,this._wrtc="function"==typeof opts.wrtc?opts.wrtc():opts.wrtc;let announce="string"==typeof opts.announce?[opts.announce]:null==opts.announce?[]:opts.announce;announce=announce.map(announceUrl=>(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{queueMicrotask(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=common.parseUrl(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535<port)return nextTickWarn(new Error(`Invalid tracker port: ${announceUrl}`)),null;const protocol=parsedUrl.protocol;return("http:"===protocol||"https:"===protocol)&&"function"==typeof HTTPTracker?new HTTPTracker(this,announceUrl):"udp:"===protocol&&"function"==typeof UDPTracker?new UDPTracker(this,announceUrl):("ws:"===protocol||"wss:"===protocol)&&webrtcSupport?"ws:"===protocol&&"undefined"!=typeof window&&"https:"===window.location.protocol?(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null):new WebSocketTracker(this,announceUrl):(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null)}).filter(Boolean)}start(opts){opts=this._defaultAnnounceOpts(opts),opts.event="started",debug("send `start` %o",opts),this._announce(opts),this._trackers.forEach(tracker=>{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":41,"./lib/client/udp-tracker":41,"./lib/client/websocket-tracker":35,"./lib/common":36,_process:192,buffer:75,debug:90,events:122,once:177,"queue-microtask":205,"run-parallel":232,"simple-peer":246}],34:[function(require,module,exports){const EventEmitter=require("events");class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}module.exports=Tracker},{events:122}],35:[function(require,module,exports){function noop(){}const clone=require("clone"),debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker"),socketPool={},RECONNECT_MINIMUM=10000,RECONNECT_MAXIMUM=3600000,RECONNECT_VARIANCE=300000,OFFER_TIMEOUT=50000;class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,5);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary,params={action:"scrape",info_hash:infoHashes};this._send(params)}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0<socketPool[this.announceUrl].consumers)return cb();let socket=socketPool[this.announceUrl];delete socketPool[this.announceUrl],socket.on("error",noop),socket.once("close",cb);let timeout;return this.expectingResponse?void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),socket.once("data",destroyCleanup)):destroyCleanup()}_openSocket(){if(this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket)socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound();else{const parsedUrl=new URL(this.announceUrl);let agent;this.client._proxyOpts&&(agent="wss:"===parsedUrl.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!agent&&this.client._proxyOpts.socksProxy&&(agent=new Socks.Agent(clone(this.client._proxyOpts.socksProxy),"wss:"===parsedUrl.protocol))),this.socket=socketPool[this.announceUrl]=new Socket({url:this.announceUrl,agent}),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)}this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),this.client.emit("peer",peer),peer.signal(data.offer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),this.client.emit("peer",peer),peer.signal(data.answer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*RECONNECT_VARIANCE)+_Mathmin(_Mathpow(2,this.retries)*RECONNECT_MINIMUM,RECONNECT_MAXIMUM);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},OFFER_TIMEOUT),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i<numwant;++i)generateOffer();checkDone()}_createPeer(opts){function onError(err){self.client.emit("warning",new Error(`Connection error: ${err.message}`)),peer.destroy()}function onConnect(){peer.removeListener("error",onError),peer.removeListener("connect",onConnect)}const self=this;opts=Object.assign({trickle:!1,config:self.client._rtcConfig,wrtc:self.client._wrtc},opts);const peer=new Peer(opts);return peer.once("error",onError),peer.once("connect",onConnect),peer}}WebSocketTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=30000,WebSocketTracker._socketPool=socketPool,module.exports=WebSocketTracker},{"../common":36,"./tracker":34,clone:80,debug:90,randombytes:208,"simple-peer":246,"simple-websocket":249,socks:41}],36:[function(require,module,exports){(function(Buffer){(function(){exports.DEFAULT_ANNOUNCE_PEERS=50,exports.MAX_ANNOUNCE_PEERS=82,exports.binaryToHex=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"binary").toString("hex")),exports.hexToBinary=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"hex").toString("binary")),exports.parseUrl=str=>{const url=new URL(str.replace(/^udp:/,"http:"));return str.match(/^udp:/)&&Object.defineProperties(url,{href:{value:url.href.replace(/^http/,"udp")},protocol:{value:url.protocol.replace(/^http/,"udp")},origin:{value:url.origin.replace(/^http/,"udp")}}),url};const config=require("./common-node");Object.assign(exports,config)}).call(this)}).call(this,require("buffer").Buffer)},{"./common-node":41,buffer:75}],37:[function(require,module,exports){(function(Buffer){(function(){/*! blob-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */module.exports=function blobToBuffer(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],38:[function(require,module,exports){(function(Buffer){(function(){const{Transform}=require("readable-stream");class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){this._bufferedBytes-=this.size;const blockBufs=[];for(let blockBufsBytes=0;blockBufsBytes<this.size;){const b=this._buffered.shift();if(blockBufsBytes+b.length<=this.size)blockBufs.push(b),blockBufsBytes+=b.length;else{const neededSize=this.size-blockBufsBytes;blockBufs.push(b.slice(0,neededSize)),blockBufsBytes+=neededSize,this._buffered.unshift(b.slice(neededSize))}}this.push(Buffer.concat(blockBufs,this.size))}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}module.exports=Block}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"readable-stream":227}],39:[function(require,module,exports){(function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return 48<=c&&57>=c?c-48:65<=c&&70>=c?c-55:97<=c&&102>=c?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=_Mathmin(str.length,end),i=start,c;i<len;i++)c=str.charCodeAt(i)-48,r*=mul,b=49<=c?c-49+10:17<=c?c-17+10:c,assert(0<=c&&b<mul,"Invalid character"),r+=b;return r}function move(dest,src){dest.words=src.words,dest.length=src.length,dest.negative=src.negative,dest.red=src.red}function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit<w.length;bit++){var off=0|bit/26,wbit=bit%26;w[bit]=1&num.words[off]>>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k<len;k++){for(var ncarry=carry>>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out._strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k<out.length-1;k++){ncarry=hncarry,hncarry=0;for(var rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1);j<=maxJ;j++){var i=k-j,a=0|self.words[i],b=0|num.words[j],r=a*b,lo=67108863&r;ncarry=0|ncarry+(0|r/67108864),lo=0|lo+rword,rword=67108863&lo,ncarry=0|ncarry+(lo>>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer="undefined"!=typeof window&&"undefined"!=typeof window.Buffer?window.Buffer:require("buffer").Buffer}catch(e){}if(BN.isBN=function isBN(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return 0<left.cmp(right)?left:right},BN.min=function min(left,right){return 0>left.cmp(right)?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function _initNumber(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function _initArray(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j,w;if("be"===endian)for(i=number.length-1,j=0;0<=i;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i<number.length;i+=3)w=number[i]|number[i+1]<<8|number[i+2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j=0,w;if("be"===endian)for(i=number.length-1;i>=start;i-=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=0==parseLength%2?start+1:start;i<number.length;i+=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;i<end;i+=limbLen)word=parseBase(number,i,i+limbLen,base),this.imuln(limbPow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;i<mod;i++)pow*=base;this.imuln(pow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word)}this._strip()},BN.prototype.copy=function copy(dest){dest.words=Array(this.length);for(var i=0;i<this.length;i++)dest.words[i]=this.words[i];dest.length=this.length,dest.negative=this.negative,dest.red=this.red},BN.prototype._move=function _move(dest){move(dest,this)},BN.prototype.clone=function clone(){var r=new BN(null);return this.copy(r),r},BN.prototype._expand=function _expand(size){for(;this.length<size;)this.words[this.length++]=0;return this},BN.prototype._strip=function strip(){for(;1<this.length&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i<this.length;i++){var w=this.words[i],word=(16777215&(w<<off|carry)).toString(16);carry=16777215&w>>>24-off,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,26<=off&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2<this.length&&assert(!1,"Number can only safely store up to 53 bits"),0===this.negative?ret:-ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};var allocate=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||_Mathmax(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(0<reqLength,"Requested array length <= 0");var res=allocate(ArrayType,reqLength),postfix="le"===endian?"LE":"BE";return this["_toArrayLike"+postfix](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position++]=255&word,position<res.length&&(res[position++]=255&word>>8),position<res.length&&(res[position++]=255&word>>16),6==shift?(position<res.length&&(res[position++]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(position<res.length)for(res[position++]=carry;position<res.length;)res[position++]=0},BN.prototype._toArrayLikeBE=function _toArrayLikeBE(res,byteLength){for(var position=res.length-1,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position--]=255&word,0<=position&&(res[position--]=255&word>>8),0<=position&&(res[position--]=255&word>>16),6==shift?(0<=position&&(res[position--]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(0<=position)for(res[position--]=carry;0<=position;)res[position--]=0},BN.prototype._countBits=_Mathclz?function _countBits(w){return 32-_Mathclz(w)}:function _countBits(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0,b;i<this.length&&(b=this._zeroBits(this.words[i]),r+=b,26===b);i++);return r},BN.prototype.byteLength=function byteLength(){return _Mathceil(this.bitLength()/8)},BN.prototype.toTwos=function toTwos(width){return 0===this.negative?this.clone():this.abs().inotn(width).iaddn(1)},BN.prototype.fromTwos=function fromTwos(width){return this.testn(width-1)?this.notn(width).iaddn(1).ineg():this.clone()},BN.prototype.isNeg=function isNeg(){return 0!==this.negative},BN.prototype.neg=function neg(){return this.clone().ineg()},BN.prototype.ineg=function ineg(){return this.isZero()||(this.negative^=1),this},BN.prototype.iuor=function iuor(num){for(;this.length<num.length;)this.words[this.length++]=0;for(var i=0;i<num.length;i++)this.words[i]|=num.words[i];return this._strip()},BN.prototype.ior=function ior(num){return assert(0==(this.negative|num.negative)),this.iuor(num)},BN.prototype.or=function or(num){return this.length>num.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;i<b.length;i++)this.words[i]&=num.words[i];return this.length=b.length,this._strip()},BN.prototype.iand=function iand(num){return assert(0==(this.negative|num.negative)),this.iuand(num)},BN.prototype.and=function and(num){return this.length>num.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;i<b.length;i++)this.words[i]=a.words[i]^b.words[i];if(this!==a)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=a.length,this._strip()},BN.prototype.ixor=function ixor(num){return assert(0==(this.negative|num.negative)),this.iuxor(num)},BN.prototype.xor=function xor(num){return this.length>num.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0<bitsLeft&&bytesNeeded--;for(var i=0;i<bytesNeeded;i++)this.words[i]=67108863&~this.words[i];return 0<bitsLeft&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<<wbit:this.words[off]&=~(1<<wbit),this._strip()},BN.prototype.iadd=function iadd(num){var r;if(0!==this.negative&&0===num.negative)return this.negative=0,r=this.isub(num),this.negative^=1,this._normSign();if(0===this.negative&&0!==num.negative)return num.negative=0,r=this.isub(num),num.negative=1,r._normSign();var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])+(0|b.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this},BN.prototype.add=function add(num){var res;return 0!==num.negative&&0===this.negative?(num.negative=0,res=this.sub(num),num.negative^=1,res):0===num.negative&&0!==this.negative?(this.negative=0,res=num.sub(this),this.negative=1,res):this.length>num.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0<cmp?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])-(0|b.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;if(0===carry&&i<a.length&&a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=_Mathmax(this.length,i),a!==this&&(this.negative=1),this._strip()},BN.prototype.sub=function sub(num){return this.clone().isub(num)};var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words,b=num.words,o=out.words,c=0,a0=0|a[0],al0=8191&a0,ah0=a0>>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i<N;i++)t[i]=this.revBin(i,l,N);return t},FFTM.prototype.revBin=function revBin(x,l,N){if(0===x||x===N-1)return x;for(var rb=0,i=0;i<l;i++)rb|=(1&x)<<l-i-1,x>>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i<N;i++)rtws[i]=rws[rbt[i]],itws[i]=iws[rbt[i]]},FFTM.prototype.transform=function transform(rws,iws,rtws,itws,N,rbt){this.permute(rbt,rws,iws,rtws,itws,N);for(var s=1;s<N;s<<=1)for(var l=s<<1,rtwdf=_Mathcos(2*_MathPI/l),itwdf=_Mathsin(2*_MathPI/l),p=0;p<N;p+=l)for(var rtwdf_=rtwdf,itwdf_=itwdf,j=0;j<s;j++){var re=rtws[p+j],ie=itws[p+j],ro=rtws[p+j+s],io=itws[p+j+s],rx=rtwdf_*ro-itwdf_*io;io=rtwdf_*io+itwdf_*ro,ro=rx,rtws[p+j]=re+ro,itws[p+j]=ie+io,rtws[p+j+s]=re-ro,itws[p+j+s]=ie-io,j!==l&&(rx=rtwdf*rtwdf_-itwdf*itwdf_,itwdf_=rtwdf*itwdf_+itwdf*rtwdf_,rtwdf_=rx)}},FFTM.prototype.guessLen13b=function guessLen13b(n,m){var N=1|_Mathmax(m,n),odd=1&N,i=0;for(N=0|N/2;N;N>>>=1)i++;return 1<<i+1+odd},FFTM.prototype.conjugate=function conjugate(rws,iws,N){if(!(1>=N))for(var i=0,t;i<N/2;i++)t=rws[i],rws[i]=rws[N-i-1],rws[N-i-1]=t,t=iws[i],iws[i]=-iws[N-i-1],iws[N-i-1]=-t},FFTM.prototype.normalize13b=function normalize13b(ws,N){for(var carry=0,i=0,w;i<N/2;i++)w=8192*_Mathround(ws[2*i+1]/N)+_Mathround(ws[2*i]/N)+carry,ws[i]=67108863&w,carry=67108864>w?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function convert13b(ws,len,rws,N){for(var carry=0,i=0;i<len;i++)carry+=0|ws[i],rws[2*i]=8191&carry,carry>>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i<N;++i)rws[i]=0;assert(0===carry),assert(0==(-8192&carry))},FFTM.prototype.stub=function stub(N){for(var ph=Array(N),i=0;i<N;i++)ph[i]=0;return ph},FFTM.prototype.mulp=function mulp(x,y,out){var N=2*this.guessLen13b(x.length,y.length),rbt=this.makeRBT(N),_=this.stub(N),rws=Array(N),rwst=Array(N),iwst=Array(N),nrws=Array(N),nrwst=Array(N),niwst=Array(N),rmws=out.words;rmws.length=N,this.convert13b(x.words,x.length,rws,N),this.convert13b(y.words,y.length,nrws,N),this.transform(rws,_,rwst,iwst,N,rbt),this.transform(nrws,_,nrwst,niwst,N,rbt);for(var i=0,rx;i<N;i++)rx=rwst[i]*nrwst[i]-iwst[i]*niwst[i],iwst[i]=rwst[i]*niwst[i]+iwst[i]*nrwst[i],rwst[i]=rx;return this.conjugate(rwst,iwst,N),this.transform(rwst,iwst,rmws,_,N,rbt),this.conjugate(rmws,_,N),this.normalize13b(rmws,N),out.negative=x.negative^y.negative,out.length=x.length+y.length,out._strip()},BN.prototype.mul=function mul(num){var out=new BN(null);return out.words=Array(this.length+num.length),this.mulTo(num,out)},BN.prototype.mulf=function mulf(num){var out=new BN(null);return out.words=Array(this.length+num.length),jumboMulTo(this,num,out)},BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)},BN.prototype.imuln=function imuln(num){var isNegNum=0>num;isNegNum&&(num=-num),assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i<this.length;i++){var w=(0|this.words[i])*num,lo=(67108863&w)+(67108863&carry);carry>>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i<w.length&&0===w[i];i++,res=res.sqr());if(++i<w.length)for(var q=res.sqr();i<w.length;i++,q=q.sqr())0!==w[i]&&(res=res.mul(q));return res},BN.prototype.iushln=function iushln(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(0!=r){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask,c=(0|this.words[i])-newCarry<<r;this.words[i]=c|carry,carry=newCarry>>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;i<s;i++)this.words[i]=0;this.length+=s}return this._strip()},BN.prototype.ishln=function ishln(bits){return assert(0===this.negative),this.iushln(bits)},BN.prototype.iushrn=function iushrn(bits,hint,extended){assert("number"==typeof bits&&0<=bits);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=_Mathmin((bits-r)/26,this.length),mask=67108863^67108863>>>r<<r,maskedWords=extended;if(h-=s,h=_Mathmax(0,h),maskedWords){for(var i=0;i<s;i++)maskedWords.words[i]=this.words[i];maskedWords.length=s}if(0===s);else if(this.length>s)for(this.length-=s,i=0;i<this.length;i++)this.words[i]=this.words[i+s];else this.words[0]=0,this.length=1;var carry=0;for(i=this.length-1;0<=i&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&0<=bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return!1;var w=this.words[s];return!!(w&q)},BN.prototype.imaskn=function imaskn(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!=r&&s++,this.length=_Mathmin(s,this.length),0!=r){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this._strip()},BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)},BN.prototype.iaddn=function iaddn(num){return assert("number"==typeof num),assert(67108864>num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<=num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&67108864<=this.words[i];i++)this.words[i]-=67108864,i==this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=_Mathmax(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(67108864>num),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i<this.length&&0>this.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this._strip()},BN.prototype.addn=function addn(num){return this.clone().iaddn(num)},BN.prototype.subn=function subn(num){return this.clone().isubn(num)},BN.prototype.iabs=function iabs(){return this.negative=0,this},BN.prototype.abs=function abs(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i<num.length;i++){w=(0|this.words[i+shift])+carry;var right=(0|num.words[i])*mul;w-=67108863&right,carry=(w>>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i<this.length-shift;i++)w=(0|this.words[i+shift])+carry,carry=w>>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i<this.length;i++)w=-(0|this.words[i])+carry,carry=w>>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;i<q.length;i++)q.words[i]=0}var diff=a.clone()._ishlnsubmul(b,1,m);0===diff.negative&&(a=diff,q&&(q.words[m]=1));for(var j=m-1,qj;0<=j;j--){for(qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]),qj=_Mathmin(0|qj/bhi,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0==(this.negative&num.negative)?num.length>this.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(x.iushrn(i);0<i--;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(y.iushrn(j);0<j--;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);0<=x.cmp(y)?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0===a.negative?a.clone():a.umod(p);for(var x1=new BN(1),x2=new BN(0),delta=b.clone();0<a.cmpn(1)&&0<b.cmpn(1);){for(var i=0,im=1;0==(a.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(a.iushrn(i);0<i--;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(b.iushrn(j);0<j--;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);0<=a.cmp(b)?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,0>res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return this._expand(s+1),this.words[s]|=q,this;for(var carry=q,i=s,w;0!==carry&&i<this.length;i++)w=0|this.words[i],w+=carry,carry=w>>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this._strip();var res;if(1<this.length)res=1;else{negative&&(num=-num),assert(67108863>=num,"Number is too big");var w=0|this.words[0];res=w===num?0:w<num?-1:1}return 0===this.negative?res:0|-res},BN.prototype.cmp=function cmp(num){if(0!==this.negative&&0===num.negative)return-1;if(0===this.negative&&0!==num.negative)return 1;var res=this.ucmp(num);return 0===this.negative?res:0|-res},BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;for(var res=0,i=this.length-1;0<=i;i--){var a=0|this.words[i],b=0|num.words[i];if(a!=b){a<b?res=-1:a>b&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return 0<=this.cmpn(num)},BN.prototype.gte=function gte(num){return 0<=this.cmp(num)},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return 0>=this.cmpn(num)},BN.prototype.lte=function lte(num){return 0>=this.cmp(num)},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);return 0===cmp?(r.words[0]=0,r.length=1):0<cmp?r.isub(this.p):void 0===r.strip?r._strip():r.strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var mask=4194303,outLen=_Mathmin(input.length,9),i=0;i<outLen;i++)output.words[i]=input.words[i];if(output.length=outLen,9>=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i<input.length;i++){var next=0|input.words[i];input.words[i-10]=(next&mask)<<4|prev>>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10<input.length?10:9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0,w;i<num.length;i++)w=0|num.words[i],lo+=977*w,num.words[i]=67108863&lo,lo=64*w+(0|lo/67108864);return 0===num.words[num.length-1]&&(num.length--,0===num.words[num.length-1]&&num.length--),num},inherits(P224,MPrime),inherits(P192,MPrime),inherits(P25519,MPrime),P25519.prototype.imulK=function imulK(num){for(var carry=0,i=0;i<num.length;i++){var hi=19*(0|num.words[i])+carry,lo=67108863&hi;hi>>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b),c=b.redSqr(),t=t.redMul(c),m=i}return r},Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);return 0===inv.negative?this.imod(inv):(inv.negative=0,this.imod(inv).redNeg())},Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(0===num.cmpn(1))return a.clone();var windowSize=4,wnd=Array(16);wnd[0]=new BN(1).toRed(this),wnd[1]=a;for(var i=2;i<wnd.length;i++)wnd[i]=this.mul(wnd[i-1],a);var res=wnd[0],current=0,currentLen=0,start=num.bitLength()%26;for(0===start&&(start=26),i=num.length-1;0<=i;i--){for(var word=num.words[i],j=start-1,bit;0<=j;j--){if(bit=1&word>>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:41}],40:[function(require,module,exports){function Rand(rand){this.rand=rand}var r;if(module.exports=function rand(len){return r||(r=new Rand(null)),r.generate(len)},module.exports.Rand=Rand,Rand.prototype.generate=function generate(len){return this._rand(len)},Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);for(var res=new Uint8Array(n),i=0;i<res.length;i++)res[i]=this.rand.getByte();return res},"object"==typeof self)self.crypto&&self.crypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.crypto.getRandomValues(arr),arr}:self.msCrypto&&self.msCrypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.msCrypto.getRandomValues(arr),arr}:"object"==typeof window&&(Rand.prototype._rand=function(){throw new Error("Not implemented yet")});else try{var crypto=require("crypto");if("function"!=typeof crypto.randomBytes)throw new Error("Not supported");Rand.prototype._rand=function _rand(n){return crypto.randomBytes(n)}}catch(e){}},{crypto:41}],41:[function(require,module,exports){},{}],42:[function(require,module,exports){function asUInt32Array(buf){Buffer.isBuffer(buf)||(buf=Buffer.from(buf));for(var len=0|buf.length/4,out=Array(len),i=0;i<len;i++)out[i]=buf.readUInt32BE(4*i);return out}function scrubVec(v){for(var i=0;i<v.length;v++)v[i]=0}function cryptBlock(M,keySchedule,SUB_MIX,SBOX,nRounds){for(var SUB_MIX0=SUB_MIX[0],SUB_MIX1=SUB_MIX[1],SUB_MIX2=SUB_MIX[2],SUB_MIX3=SUB_MIX[3],s0=M[0]^keySchedule[0],s1=M[1]^keySchedule[1],s2=M[2]^keySchedule[2],s3=M[3]^keySchedule[3],ksRow=4,round=1,t0,t1,t2,t3;round<nRounds;round++)t0=SUB_MIX0[s0>>>24]^SUB_MIX1[255&s1>>>16]^SUB_MIX2[255&s2>>>8]^SUB_MIX3[255&s3]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[255&s2>>>16]^SUB_MIX2[255&s3>>>8]^SUB_MIX3[255&s0]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[255&s3>>>16]^SUB_MIX2[255&s0>>>8]^SUB_MIX3[255&s1]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[255&s0>>>16]^SUB_MIX2[255&s1>>>8]^SUB_MIX3[255&s2]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[255&s1>>>16]<<16|SBOX[255&s2>>>8]<<8|SBOX[255&s3])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[255&s2>>>16]<<16|SBOX[255&s3>>>8]<<8|SBOX[255&s0])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[255&s3>>>16]<<16|SBOX[255&s0>>>8]<<8|SBOX[255&s1])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[255&s0>>>16]<<16|SBOX[255&s1>>>8]<<8|SBOX[255&s2])^keySchedule[ksRow++],t0>>>=0,t1>>>=0,t2>>>=0,t3>>>=0,[t0,t1,t2,t3]}function AES(key){this._key=asUInt32Array(key),this._reset()}var Buffer=require("safe-buffer").Buffer,RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=Array(256),j=0;256>j;j++)d[j]=128>j?j<<1:283^j<<1;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0,sx;256>i;++i){sx=xi^xi<<1^xi<<2^xi<<3^xi<<4,sx=99^(sx>>>8^255&sx),SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,0===x?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX:SBOX,INV_SBOX:INV_SBOX,SUB_MIX:SUB_MIX,INV_SUB_MIX:INV_SUB_MIX}}();AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=4*(nRounds+1),keySchedule=[],k=0;k<keySize;k++)keySchedule[k]=keyWords[k];for(k=keySize;k<ksRows;k++){var t=keySchedule[k-1];0==k%keySize?(t=t<<8|t>>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t],t^=RCON[0|k/keySize]<<24):6<keySize&&4==k%keySize&&(t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik<ksRows;ik++){var ksR=ksRows-ik,tt=keySchedule[ksR-(ik%4?0:4)];invKeySchedule[ik]=4>ik||4>=ksR?tt:G.INV_SUB_MIX[0][G.SBOX[tt>>>24]]^G.INV_SUB_MIX[1][G.SBOX[255&tt>>>16]]^G.INV_SUB_MIX[2][G.SBOX[255&tt>>>8]]^G.INV_SUB_MIX[3][G.SBOX[255&tt]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES},{"safe-buffer":234}],43:[function(require,module,exports){function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=_Mathmin(a.length,b.length),i=0;i<len;++i)out+=a[i]^b[i];return out}function calcIv(self,iv,ck){if(12===iv.length)return self._finID=Buffer.concat([iv,Buffer.from([0,0,0,1])]),Buffer.concat([iv,Buffer.from([0,0,0,2])]);var ghash=new GHASH(ck),len=iv.length,toPad=len%16;ghash.update(iv),toPad&&(toPad=16-toPad,ghash.update(Buffer.alloc(toPad,0))),ghash.update(Buffer.alloc(8,0));var ivBits=8*len,tail=Buffer.alloc(8);tail.writeUIntBE(ivBits,0,8),ghash.update(tail),self._finID=ghash.state;var out=Buffer.from(self._finID);return incr32(out),out}function StreamCipher(mode,key,iv,decrypt){Transform.call(this);var h=Buffer.alloc(4,0);this._cipher=new aes.AES(key);var ck=this._cipher.encryptBlock(h);this._ghash=new GHASH(ck),iv=calcIv(this,iv,ck),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._alen=0,this._len=0,this._mode=mode,this._authTag=null,this._called=!1}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits"),GHASH=require("./ghash"),xor=require("buffer-xor"),incr32=require("./incr32");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;16>rump&&(rump=Buffer.alloc(rump,0),this._ghash.update(rump))}this._called=!0;var out=this._mode.encrypt(this,chunk);return this._decrypt?this._ghash.update(chunk):this._ghash.update(out),this._len+=chunk.length,out},StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var tag=xor(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&xorTest(tag,this._authTag))throw new Error("Unsupported state or unable to authenticate data");this._authTag=tag,this._cipher.scrub()},StreamCipher.prototype.getAuthTag=function getAuthTag(){if(this._decrypt||!Buffer.isBuffer(this._authTag))throw new Error("Attempting to get auth tag in unsupported state");return this._authTag},StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(!this._decrypt)throw new Error("Attempting to set auth tag in unsupported state");this._authTag=tag},StreamCipher.prototype.setAAD=function setAAD(buf){if(this._called)throw new Error("Attempting to set AAD in unsupported state");this._ghash.update(buf),this._alen+=buf.length},module.exports=StreamCipher},{"./aes":42,"./ghash":47,"./incr32":48,"buffer-xor":74,"cipher-base":79,inherits:145,"safe-buffer":234}],44:[function(require,module,exports){function getCiphers(){return Object.keys(modes)}var ciphers=require("./encrypter"),deciphers=require("./decrypter"),modes=require("./modes/list.json");exports.createCipher=exports.Cipher=ciphers.createCipher,exports.createCipheriv=exports.Cipheriv=ciphers.createCipheriv,exports.createDecipher=exports.Decipher=deciphers.createDecipher,exports.createDecipheriv=exports.Decipheriv=deciphers.createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"./decrypter":45,"./encrypter":46,"./modes/list.json":56}],45:[function(require,module,exports){function Decipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function unpad(last){var padded=last[15];if(1>padded||16<padded)throw new Error("unable to decrypt data");for(var i=-1;++i<padded;)if(last[i+(16-padded)]!==padded)throw new Error("unable to decrypt data");return 16===padded?void 0:last.slice(0,16-padded)}function createDecipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);return"stream"===config.type?new StreamCipher(config.module,password,iv,!0):"auth"===config.type?new AuthCipher(config.module,password,iv,!0):new Decipher(config.module,password,iv)}function createDecipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createDecipheriv(suite,keys.key,keys.iv)}var AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,MODES=require("./modes"),StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Decipher,Transform),Decipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get(this._autopadding);)thing=this._mode.decrypt(this,chunk),out.push(thing);return Buffer.concat(out)},Decipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return unpad(this._mode.decrypt(this,chunk));if(chunk)throw new Error("data not multiple of block length")},Decipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(autoPadding){var out;if(autoPadding){if(16<this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;}else if(16<=this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache},exports.createDecipher=createDecipher,exports.createDecipheriv=createDecipheriv},{"./aes":42,"./authCipher":43,"./modes":55,"./streamCipher":58,"cipher-base":79,evp_bytestokey:123,inherits:145,"safe-buffer":234}],46:[function(require,module,exports){function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function createCipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);return"stream"===config.type?new StreamCipher(config.module,password,iv):"auth"===config.type?new AuthCipher(config.module,password,iv):new Cipher(config.module,password,iv)}function createCipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createCipheriv(suite,keys.key,keys.iv)}var MODES=require("./modes"),AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer.concat(out)};var PADDING=Buffer.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error("data not multiple of block length")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(){if(15<this.cache.length){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer.allocUnsafe(len),i=-1;++i<len;)padBuff.writeUInt8(len,i);return Buffer.concat([this.cache,padBuff])},exports.createCipheriv=createCipheriv,exports.createCipher=createCipher},{"./aes":42,"./authCipher":43,"./modes":55,"./streamCipher":58,"cipher-base":79,evp_bytestokey:123,inherits:145,"safe-buffer":234}],47:[function(require,module,exports){function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer.alloc(16,0),this.cache=Buffer.allocUnsafe(0)}var Buffer=require("safe-buffer").Buffer,ZEROES=Buffer.alloc(16,0);GHASH.prototype.ghash=function(block){for(var i=-1;++i<block.length;)this.state[i]^=block[i];this._multiply()},GHASH.prototype._multiply=function(){for(var Vi=toArray(this.h),Zi=[0,0,0,0],i=-1,j,xi,lsbVi;128>++i;){for(xi=0!=(this.state[~~(i/8)]&1<<7-i%8),xi&&(Zi[0]^=Vi[0],Zi[1]^=Vi[1],Zi[2]^=Vi[2],Zi[3]^=Vi[3]),lsbVi=0!=(1&Vi[3]),j=3;0<j;j--)Vi[j]=Vi[j]>>>1|(1&Vi[j-1])<<31;Vi[0]>>>=1,lsbVi&&(Vi[0]^=-520093696)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);for(var chunk;16<=this.cache.length;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH},{"safe-buffer":234}],48:[function(require,module,exports){function incr32(iv){for(var len=iv.length,item;len--;)if(item=iv.readUInt8(len),255===item)iv.writeUInt8(0,len);else{item++,iv.writeUInt8(item,len);break}}module.exports=incr32},{}],49:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);return self._prev=self._cipher.encryptBlock(data),self._prev},exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":74}],50:[function(require,module,exports){function encryptStart(self,data,decrypt){var len=data.length,out=xor(data,self._cache);return self._cache=self._cache.slice(len),self._prev=Buffer.concat([self._prev,decrypt?data:out]),out}var Buffer=require("safe-buffer").Buffer,xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){for(var out=Buffer.allocUnsafe(0),len;data.length;)if(0===self._cache.length&&(self._cache=self._cipher.encryptBlock(self._prev),self._prev=Buffer.allocUnsafe(0)),self._cache.length<=data.length)len=self._cache.length,out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]),data=data.slice(len);else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}return out}},{"buffer-xor":74,"safe-buffer":234}],51:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){for(var i=-1,len=8,out=0,pad,bit,value;++i<len;)pad=self._cipher.encryptBlock(self._prev),bit=byteParam&1<<7-i?128:0,value=pad[0]^bit,out+=(128&value)>>i%8,self._prev=shiftIn(self._prev,decrypt?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer.allocUnsafe(buffer.length);for(buffer=Buffer.concat([buffer,Buffer.from([value])]);++i<len;)out[i]=buffer[i]<<1|buffer[i+1]>>7;return out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":234}],52:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev),out=pad[0]^byteParam;return self._prev=Buffer.concat([self._prev.slice(1),Buffer.from([decrypt?byteParam:out])]),out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":234}],53:[function(require,module,exports){function getBlock(self){var out=self._cipher.encryptBlockRaw(self._prev);return incr32(self._prev),out}var xor=require("buffer-xor"),Buffer=require("safe-buffer").Buffer,incr32=require("../incr32"),blockSize=16;exports.encrypt=function(self,chunk){var chunkNum=_Mathceil(chunk.length/blockSize),start=self._cache.length;self._cache=Buffer.concat([self._cache,Buffer.allocUnsafe(chunkNum*blockSize)]);for(var i=0;i<chunkNum;i++){var out=getBlock(self),offset=start+i*blockSize;self._cache.writeUInt32BE(out[0],offset+0),self._cache.writeUInt32BE(out[1],offset+4),self._cache.writeUInt32BE(out[2],offset+8),self._cache.writeUInt32BE(out[3],offset+12)}var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}},{"../incr32":48,"buffer-xor":74,"safe-buffer":234}],54:[function(require,module,exports){exports.encrypt=function(self,block){return self._cipher.encryptBlock(block)},exports.decrypt=function(self,block){return self._cipher.decryptBlock(block)}},{}],55:[function(require,module,exports){var modeModules={ECB:require("./ecb"),CBC:require("./cbc"),CFB:require("./cfb"),CFB8:require("./cfb8"),CFB1:require("./cfb1"),OFB:require("./ofb"),CTR:require("./ctr"),GCM:require("./ctr")},modes=require("./list.json");for(var key in modes)modes[key].module=modeModules[modes[key].mode];module.exports=modes},{"./cbc":49,"./cfb":50,"./cfb1":51,"./cfb8":52,"./ctr":53,"./ecb":54,"./list.json":56,"./ofb":57}],56:[function(require,module,exports){module.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}},{}],57:[function(require,module,exports){(function(Buffer){(function(){function getBlock(self){return self._prev=self._cipher.encryptBlock(self._prev),self._prev}var xor=require("buffer-xor");exports.encrypt=function(self,chunk){for(;self._cache.length<chunk.length;)self._cache=Buffer.concat([self._cache,getBlock(self)]);var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"buffer-xor":74}],58:[function(require,module,exports){function StreamCipher(mode,key,iv,decrypt){Transform.call(this),this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._mode=mode}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){return this._mode.encrypt(this,chunk,this._decrypt)},StreamCipher.prototype._final=function(){this._cipher.scrub()},module.exports=StreamCipher},{"./aes":42,"cipher-base":79,inherits:145,"safe-buffer":234}],59:[function(require,module,exports){function createCipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createCipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite});throw new TypeError("invalid suite type")}function createDecipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createDecipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite,decrypt:!0});throw new TypeError("invalid suite type")}function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}var DES=require("browserify-des"),aes=require("browserify-aes/browser"),aesModes=require("browserify-aes/modes"),desModes=require("browserify-des/modes"),ebtk=require("evp_bytestokey");exports.createCipher=exports.Cipher=createCipher,exports.createCipheriv=exports.Cipheriv=createCipheriv,exports.createDecipher=exports.Decipher=createDecipher,exports.createDecipheriv=exports.Decipheriv=createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":44,"browserify-aes/modes":55,"browserify-des":60,"browserify-des/modes":61,evp_bytestokey:123}],60:[function(require,module,exports){function DES(opts){CipherBase.call(this);var modeName=opts.mode.toLowerCase(),mode=modes[modeName],type;type=opts.decrypt?"decrypt":"encrypt";var key=opts.key;Buffer.isBuffer(key)||(key=Buffer.from(key)),("des-ede"===modeName||"des-ede-cbc"===modeName)&&(key=Buffer.concat([key,key.slice(0,8)]));var iv=opts.iv;Buffer.isBuffer(iv)||(iv=Buffer.from(iv)),this._des=mode.create({key:key,iv:iv,type:type})}var CipherBase=require("cipher-base"),des=require("des.js"),inherits=require("inherits"),Buffer=require("safe-buffer").Buffer,modes={"des-ede3-cbc":des.CBC.instantiate(des.EDE),"des-ede3":des.EDE,"des-ede-cbc":des.CBC.instantiate(des.EDE),"des-ede":des.EDE,"des-cbc":des.CBC.instantiate(des.DES),"des-ecb":des.DES};modes.des=modes["des-cbc"],modes.des3=modes["des-ede3-cbc"],module.exports=DES,inherits(DES,CipherBase),DES.prototype._update=function(data){return Buffer.from(this._des.update(data))},DES.prototype._final=function(){return Buffer.from(this._des.final())}},{"cipher-base":79,"des.js":92,inherits:145,"safe-buffer":234}],61:[function(require,module,exports){exports["des-ecb"]={key:8,iv:0},exports["des-cbc"]=exports.des={key:8,iv:8},exports["des-ede3-cbc"]=exports.des3={key:24,iv:8},exports["des-ede3"]={key:24,iv:0},exports["des-ede-cbc"]={key:16,iv:8},exports["des-ede"]={key:16,iv:0}},{}],62:[function(require,module,exports){(function(Buffer){(function(){function blind(priv){var r=getr(priv),blinder=r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function getr(priv){var len=priv.modulus.byteLength(),r;do r=new BN(randomBytes(len));while(0<=r.cmp(priv.modulus)||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,"be",len)}var BN=require("bn.js"),randomBytes=require("randombytes");crt.getr=getr,module.exports=crt}).call(this)}).call(this,require("buffer").Buffer)},{"bn.js":39,buffer:75,randombytes:208}],63:[function(require,module,exports){module.exports=require("./browser/algorithms.json")},{"./browser/algorithms.json":64}],64:[function(require,module,exports){module.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],65:[function(require,module,exports){module.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],66:[function(require,module,exports){function Sign(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function Verify(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}var Buffer=require("safe-buffer").Buffer,createHash=require("create-hash"),stream=require("readable-stream"),inherits=require("inherits"),sign=require("./sign"),verify=require("./verify"),algorithms=require("./algorithms.json");Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer.from(algorithms[key].id,"hex"),algorithms[key.toLowerCase()]=algorithms[key]}),inherits(Sign,stream.Writable),Sign.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function signMethod(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc?sig.toString(enc):sig},inherits(Verify,stream.Writable),Verify.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function verifyMethod(key,sig,enc){"string"==typeof sig&&(sig=Buffer.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)},module.exports={Sign:createSign,Verify:createVerify,createSign:createSign,createVerify:createVerify}},{"./algorithms.json":64,"./sign":67,"./verify":68,"create-hash":84,inherits:145,"readable-stream":227,"safe-buffer":234}],67:[function(require,module,exports){function sign(hash,key,hashType,signType,tag){var priv=parseKeys(key);if(priv.curve){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");return ecSign(hash,priv)}if("dsa"===priv.type){if("dsa"!==signType)throw new Error("wrong private key type");return dsaSign(hash,priv,hashType)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");hash=Buffer.concat([tag,hash]);for(var len=priv.modulus.byteLength(),pad=[0,1];hash.length+pad.length+1<len;)pad.push(255);pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);var out=crt(pad,priv);return out}function ecSign(hash,priv){var curveId=curves[priv.curve.join(".")];if(!curveId)throw new Error("unknown curve "+priv.curve.join("."));var curve=new EC(curveId),key=curve.keyFromPrivate(priv.privateKey),out=key.sign(hash);return Buffer.from(out.toDER())}function dsaSign(hash,priv,algo){for(var x=priv.params.priv_key,p=priv.params.p,q=priv.params.q,g=priv.params.g,r=new BN(0),H=bits2int(hash,q).mod(q),s=!1,kv=getKey(x,q,hash,algo),k;!1===s;)k=makeKey(q,kv,algo),r=makeR(g,k,p,q),s=k.invm(q).imul(H.add(x.mul(r))).mod(q),0===s.cmpn(0)&&(s=!1,r=new BN(0));return toDER(r,s)}function toDER(r,s){r=r.toArray(),s=s.toArray(),128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s));var total=r.length+s.length+4,res=[48,total,2,r.length];return res=res.concat(r,[2,s.length],s),Buffer.from(res)}function getKey(x,q,hash,algo){if(x=Buffer.from(x.toArray()),x.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-x.length);x=Buffer.concat([zeros,x])}var hlen=hash.length,hbits=bits2octets(hash,q),v=Buffer.alloc(hlen);v.fill(1);var k=Buffer.alloc(hlen);return k=createHmac(algo,k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),k=createHmac(algo,k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),{k:k,v:v}}function bits2int(obits,q){var bits=new BN(obits),shift=(obits.length<<3)-q.bitLength();return 0<shift&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer.from(bits.toArray());if(out.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-out.length);out=Buffer.concat([zeros,out])}return out}function makeKey(q,kv,algo){var t,k;do{for(t=Buffer.alloc(0);8*t.length<q.bitLength();)kv.v=createHmac(algo,kv.k).update(kv.v).digest(),t=Buffer.concat([t,kv.v]);k=bits2int(t,q),kv.k=createHmac(algo,kv.k).update(kv.v).update(Buffer.from([0])).digest(),kv.v=createHmac(algo,kv.k).update(kv.v).digest()}while(-1!==k.cmp(q));return k}function makeR(g,k,p,q){return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)}var Buffer=require("safe-buffer").Buffer,createHmac=require("create-hmac"),crt=require("browserify-rsa"),EC=require("elliptic").ec,BN=require("bn.js"),parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=sign,module.exports.getKey=getKey,module.exports.makeKey=makeKey},{"./curves.json":65,"bn.js":39,"browserify-rsa":62,"create-hmac":86,elliptic:103,"parse-asn1":182,"safe-buffer":234}],68:[function(require,module,exports){function verify(sig,hash,key,signType,tag){var pub=parseKeys(key);if("ec"===pub.type){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");return ecVerify(sig,hash,pub)}if("dsa"===pub.type){if("dsa"!==signType)throw new Error("wrong public key type");return dsaVerify(sig,hash,pub)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");hash=Buffer.concat([tag,hash]);for(var len=pub.modulus.byteLength(),pad=[1],padNum=0;hash.length+pad.length+2<len;)pad.push(255),padNum++;pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);pad=Buffer.from(pad);var red=BN.mont(pub.modulus);sig=new BN(sig).toRed(red),sig=sig.redPow(new BN(pub.publicExponent)),sig=Buffer.from(sig.fromRed().toArray());var out=8>padNum?1:0;for(len=_Mathmin(sig.length,pad.length),sig.length!==pad.length&&(out=1),i=-1;++i<len;)out|=sig[i]^pad[i];return 0==out}function ecVerify(sig,hash,pub){var curveId=curves[pub.data.algorithm.curve.join(".")];if(!curveId)throw new Error("unknown curve "+pub.data.algorithm.curve.join("."));var curve=new EC(curveId),pubkey=pub.data.subjectPrivateKey.data;return curve.verify(hash,sig,pubkey)}function dsaVerify(sig,hash,pub){var p=pub.data.p,q=pub.data.q,g=pub.data.g,y=pub.data.pub_key,unpacked=parseKeys.signature.decode(sig,"der"),s=unpacked.s,r=unpacked.r;checkValue(s,q),checkValue(r,q);var montp=BN.mont(p),w=s.invm(q),v=g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q);return 0===v.cmp(r)}function checkValue(b,q){if(0>=b.cmpn(0))throw new Error("invalid sig");if(b.cmp(q)>=q)throw new Error("invalid sig")}var Buffer=require("safe-buffer").Buffer,BN=require("bn.js"),EC=require("elliptic").ec,parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=verify},{"./curves.json":65,"bn.js":39,elliptic:103,"parse-asn1":182,"safe-buffer":234}],69:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),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}],70:[function(require,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;!0;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);return 0<=nb?(0<nb&&(self.lastNeed=nb-1),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb)?(0<nb&&(self.lastNeed=nb-2),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb?(0<nb&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"\uFFFD";if(1<self.lastNeed&&1<buf.length){if(128!=(192&buf[1]))return self.lastNeed=1,"\uFFFD";if(2<self.lastNeed&&2<buf.length&&128!=(192&buf[2]))return self.lastNeed=2,"\uFFFD"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0===r?this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,p,0,buf.length),this.lastNeed-=buf.length):r}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"\uFFFD":r}function utf16Text(buf,i){if(0==(buf.length-i)%2){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(55296<=c&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<buf.length?r?r+this.text(buf,i):this.text(buf,i):r||""},StringDecoder.prototype.end=utf8End,StringDecoder.prototype.text=utf8Text,StringDecoder.prototype.fillLast=function(buf){return this.lastNeed<=buf.length?(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length)}},{"safe-buffer":69}],71:[function(require,module,exports){(function(Buffer){(function(){function allocUnsafe(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}module.exports=allocUnsafe}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],72:[function(require,module,exports){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function alloc(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"buffer-alloc-unsafe":71,"buffer-fill":73}],73:[function(require,module,exports){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}function fill(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=fill}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],74:[function(require,module,exports){(function(Buffer){(function(){module.exports=function xor(a,b){for(var length=_Mathmin(a.length,b.length),buffer=new Buffer(length),i=0;i<length;++i)buffer[i]=a[i]^b[i];return buffer}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],75:[function(require,module,exports){(function(Buffer){(function(){/*!
+(function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,g.WebTorrent=f()}})(function(){var _MathLN=Math.LN2,_Mathlog2=Math.log,_Mathpow=Math.pow,_Mathabs=Math.abs,_Mathfloor=Math.floor,_Mathround=Math.round,_Mathsin=Math.sin,_Mathcos=Math.cos,_MathPI=Math.PI,_Mathimul=Math.imul,_Mathclz=Math.clz32,_StringfromCharCode=String.fromCharCode,_Mathmax=Math.max,_Mathceil=Math.ceil,_Mathmin=Math.min,define;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module){const stream=require("stream"),debugFactory=require("debug"),eos=require("end-of-stream"),debug=debugFactory("webtorrent:file-stream");class FileStream extends stream.Readable{constructor(file,opts){super(opts),this._torrent=file._torrent;const start=opts&&opts.start||0,end=opts&&opts.end&&opts.end<file.length?opts.end:file.length-1,pieceLength=file._torrent.pieceLength;this._startPiece=0|(start+file.offset)/pieceLength,this._endPiece=0|(end+file.offset)/pieceLength,this._piece=this._startPiece,this._offset=start+file.offset-this._startPiece*pieceLength,this._missing=end-start+1,this._reading=!1,this._notifying=!1,this._criticalLength=_Mathmin(0|1048576/pieceLength,2),this._torrent.select(this._startPiece,this._endPiece,!0,()=>{this._notify()}),eos(this,err=>{this.destroy(err)})}_read(){this._reading||(this._reading=!0,this._notify())}_notify(){if(!this._reading||0===this._missing)return;if(!this._torrent.bitfield.get(this._piece))return this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return;if(this._notifying=!0,this._torrent.destroyed)return this.destroy(new Error("Torrent removed"));const p=this._piece,getOpts={};p===this._torrent.pieces.length-1&&(getOpts.length=this._torrent.lastPieceLength),this._torrent.store.get(p,getOpts,(err,buffer)=>{if(this._notifying=!1,!this.destroyed)return debug("read %s (length %s) (err %s)",p,buffer&&buffer.length,err&&err.message),err?this.destroy(err):void(this._offset&&(buffer=buffer.slice(this._offset),this._offset=0),this._missing<buffer.length&&(buffer=buffer.slice(0,this._missing)),this._missing-=buffer.length,debug("pushing buffer of length %s",buffer.length),this._reading=!1,this.push(buffer),0===this._missing&&this.push(null))}),this._piece+=1}_destroy(err,cb){this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),cb(err)}}module.exports=FileStream},{debug:90,"end-of-stream":120,stream:255}],2:[function(require,module){const EventEmitter=require("events"),{PassThrough}=require("stream"),path=require("path"),render=require("render-media"),streamToBlob=require("stream-to-blob"),streamToBlobURL=require("stream-to-blob-url"),streamToBuffer=require("stream-with-known-length-to-buffer"),queueMicrotask=require("queue-microtask"),rangeParser=require("range-parser"),mime=require("mime"),eos=require("end-of-stream"),FileStream=require("./file-stream.js");module.exports=class extends EventEmitter{constructor(torrent,file){super(),this._torrent=torrent,this._destroyed=!1,this._fileStreams=new Set,this.name=file.name,this.path=file.path,this.length=file.length,this.offset=file.offset,this.done=!1;const start=file.offset,end=start+file.length-1;this._startPiece=0|start/this._torrent.pieceLength,this._endPiece=0|end/this._torrent.pieceLength,0===this.length&&(this.done=!0,this.emit("done")),this._serviceWorker=torrent.client.serviceWorker}get downloaded(){if(this._destroyed||!this._torrent.bitfield)return 0;const{pieces,bitfield,pieceLength,lastPieceLength}=this._torrent,{_startPiece:start,_endPiece:end}=this,getPieceLength=pieceIndex=>pieceIndex===pieces.length-1?lastPieceLength:pieceLength,getPieceDownloaded=pieceIndex=>{const len=pieceIndex===pieces.length-1?lastPieceLength:pieceLength;return bitfield.get(pieceIndex)?len:len-pieces[pieceIndex].missing};let downloaded=0;for(let index=start;index<=end;index+=1){const pieceDownloaded=getPieceDownloaded(index);if(downloaded+=pieceDownloaded,index===start){const irrelevantFirstPieceBytes=this.offset%pieceLength;downloaded-=_Mathmin(irrelevantFirstPieceBytes,pieceDownloaded)}if(index===end){const irrelevantLastPieceBytes=getPieceLength(end)-(this.offset+this.length)%pieceLength;downloaded-=_Mathmin(irrelevantLastPieceBytes,pieceDownloaded)}}return downloaded}get progress(){return this.length?this.downloaded/this.length:0}select(priority){0===this.length||this._torrent.select(this._startPiece,this._endPiece,priority)}deselect(){0===this.length||this._torrent.deselect(this._startPiece,this._endPiece,!1)}createReadStream(opts){if(0===this.length){const empty=new PassThrough;return queueMicrotask(()=>{empty.end()}),empty}const fileStream=new FileStream(this,opts);return this._fileStreams.add(fileStream),fileStream.once("close",()=>{this._fileStreams.delete(fileStream)}),fileStream}getBuffer(cb){streamToBuffer(this.createReadStream(),this.length,cb)}getBlob(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlob(this.createReadStream(),this._getMimeType()).then(blob=>cb(null,blob),err=>cb(err))}getBlobURL(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlobURL(this.createReadStream(),this._getMimeType()).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}appendTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.append(this,elem,opts,cb)}renderTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.render(this,elem,opts,cb)}_serve(req){const res={status:200,headers:{"Accept-Ranges":"bytes","Content-Type":mime.getType(this.name),"Cache-Control":"no-cache, no-store, must-revalidate, max-age=0",Expires:"0"},body:"HEAD"===req.method?"":"STREAM"};"document"===req.destination&&(res.headers["Content-Type"]="application/octet-stream",res.headers["Content-Disposition"]="attachment",res.body="DOWNLOAD");let range=rangeParser(this.length,req.headers.range||"");range.constructor===Array?(res.status=206,range=range[0],res.headers["Content-Range"]=`bytes ${range.start}-${range.end}/${this.length}`,res.headers["Content-Length"]=`${range.end-range.start+1}`):res.headers["Content-Length"]=this.length;const stream="GET"===req.method&&this.createReadStream(range);let pipe=null;return stream&&this.emit("stream",{stream,req,file:this},piped=>{pipe=piped,eos(piped,()=>{piped&&piped.destroy(),stream.destroy()})}),[res,pipe||stream,pipe&&stream]}getStreamURL(cb=()=>{}){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");const workerPath=this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length),url=`${workerPath}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`;cb(null,url)}streamTo(elem,cb=()=>{}){if("undefined"==typeof window)throw new Error("browser-only method");if(!this._serviceWorker)throw new Error("No worker registered");if("activated"!==this._serviceWorker.state)throw new Error("Worker isn't activated");const workerPath=this._serviceWorker.scriptURL.slice(0,this._serviceWorker.scriptURL.lastIndexOf("/")+1).slice(window.location.origin.length);elem.src=`${workerPath}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`,cb(null,elem)}_getMimeType(){return render.mime[path.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null;for(const fileStream of this._fileStreams)fileStream.destroy();this._fileStreams.clear()}}},{"./file-stream.js":1,"end-of-stream":120,events:122,mime:163,path:184,"queue-microtask":205,"range-parser":210,"render-media":228,stream:255,"stream-to-blob":261,"stream-to-blob-url":260,"stream-with-known-length-to-buffer":262}],3:[function(require,module,exports){const EventEmitter=require("events"),{Transform}=require("stream"),arrayRemove=require("unordered-array-remove"),debugFactory=require("debug"),Wire=require("bittorrent-protocol"),debug=debugFactory("webtorrent:peer");let secure=!1;exports.enableSecure=()=>{secure=!0},exports.createWebRTCPeer=(conn,swarm,throttleGroups)=>{const peer=new Peer(conn.id,"webrtc");if(peer.conn=conn,peer.swarm=swarm,peer.throttleGroups=throttleGroups,peer.conn.connected)peer.onConnect();else{const cleanup=()=>{peer.conn.removeListener("connect",onConnect),peer.conn.removeListener("error",onError)},onConnect=()=>{cleanup(),peer.onConnect()},onError=err=>{cleanup(),peer.destroy(err)};peer.conn.once("connect",onConnect),peer.conn.once("error",onError),peer.startConnectTimeout()}return peer},exports.createTCPIncomingPeer=(conn,throttleGroups)=>_createIncomingPeer(conn,"tcpIncoming",throttleGroups),exports.createUTPIncomingPeer=(conn,throttleGroups)=>_createIncomingPeer(conn,"utpIncoming",throttleGroups),exports.createTCPOutgoingPeer=(addr,swarm,throttleGroups)=>_createOutgoingPeer(addr,swarm,"tcpOutgoing",throttleGroups),exports.createUTPOutgoingPeer=(addr,swarm,throttleGroups)=>_createOutgoingPeer(addr,swarm,"utpOutgoing",throttleGroups);const _createIncomingPeer=(conn,type,throttleGroups)=>{const addr=`${conn.remoteAddress}:${conn.remotePort}`,peer=new Peer(addr,type);return peer.conn=conn,peer.addr=addr,peer.throttleGroups=throttleGroups,peer.onConnect(),peer},_createOutgoingPeer=(addr,swarm,type,throttleGroups)=>{const peer=new Peer(addr,type);return peer.addr=addr,peer.swarm=swarm,peer.throttleGroups=throttleGroups,peer};exports.createWebSeedPeer=(conn,id,swarm,throttleGroups)=>{const peer=new Peer(id,"webSeed");return peer.swarm=swarm,peer.conn=conn,peer.throttleGroups=throttleGroups,peer.onConnect(),peer};class Peer extends EventEmitter{constructor(id,type){super(),this.id=id,this.type=type,debug("new %s Peer %s",type,id),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentPe1=!1,this.sentPe2=!1,this.sentPe3=!1,this.sentPe4=!1,this.sentHandshake=!1}onConnect(){if(!this.destroyed){this.connected=!0,debug("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const conn=this.conn;conn.once("end",()=>{this.destroy()}),conn.once("close",()=>{this.destroy()}),conn.once("finish",()=>{this.destroy()}),conn.once("error",err=>{this.destroy(err)});const wire=this.wire=new Wire(this.type,this.retries,secure);wire.once("end",()=>{this.destroy()}),wire.once("close",()=>{this.destroy()}),wire.once("finish",()=>{this.destroy()}),wire.once("error",err=>{this.destroy(err)}),wire.once("pe1",()=>{this.onPe1()}),wire.once("pe2",()=>{this.onPe2()}),wire.once("pe3",()=>{this.onPe3()}),wire.once("pe4",()=>{this.onPe4()}),wire.once("handshake",(infoHash,peerId)=>{this.onHandshake(infoHash,peerId)}),this.startHandshakeTimeout(),this.setThrottlePipes(),this.swarm&&("tcpOutgoing"===this.type?secure&&0===this.retries&&!this.sentPe1?this.sendPe1():!this.sentHandshake&&this.handshake():"tcpIncoming"!==this.type&&!this.sentHandshake&&this.handshake())}}sendPe1(){this.wire.sendPe1(),this.sentPe1=!0}onPe1(){this.sendPe2()}sendPe2(){this.wire.sendPe2(),this.sentPe2=!0}onPe2(){this.sendPe3()}sendPe3(){this.wire.sendPe3(this.swarm.infoHash),this.sentPe3=!0}onPe3(infoHashHash){this.swarm&&(this.swarm.infoHashHash!==infoHashHash&&this.destroy(new Error("unexpected crypto handshake info hash for this swarm")),this.sendPe4())}sendPe4(){this.wire.sendPe4(this.swarm.infoHash),this.sentPe4=!0}onPe4(){this.sentHandshake||this.handshake()}clearPipes(){this.conn.unpipe(),this.wire.unpipe()}setThrottlePipes(){const self=this;this.conn.pipe(this.throttleGroups.down.throttle()).pipe(new Transform({transform(chunk,_,callback){self.emit("download",chunk.length);self.destroyed||callback(null,chunk)}})).pipe(this.wire).pipe(this.throttleGroups.up.throttle()).pipe(new Transform({transform(chunk,_,callback){self.emit("upload",chunk.length);self.destroyed||callback(null,chunk)}})).pipe(this.conn)}onHandshake(infoHash,peerId){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(infoHash!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(peerId===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));debug("Peer %s got handshake %s",this.id,infoHash),clearTimeout(this.handshakeTimeout),this.retries=0;let addr=this.addr;!addr&&this.conn.remoteAddress&&this.conn.remotePort&&(addr=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,addr);this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const opts={dht:!this.swarm.private&&!!this.swarm.client.dht,fast:!0};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,opts),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},{webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3}[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(err){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,debug("destroy %s %s (error: %s)",this.type,this.id,err&&(err.message||err)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const swarm=this.swarm,conn=this.conn,wire=this.wire;this.swarm=null,this.conn=null,this.wire=null,swarm&&wire&&arrayRemove(swarm.wires,swarm.wires.indexOf(wire)),conn&&(conn.on("error",()=>{}),conn.destroy()),wire&&wire.destroy(),swarm&&swarm.removePeer(this.id)}}},{"bittorrent-protocol":32,debug:90,events:122,stream:255,"unordered-array-remove":273}],4:[function(require,module){module.exports=class{constructor(torrent){this._torrent=torrent,this._numPieces=torrent.pieces.length,this._pieces=Array(this._numPieces),this._onWire=wire=>{this.recalculate(),this._initWire(wire)},this._onWireHave=index=>{this._pieces[index]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach(wire=>{this._initWire(wire)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(pieceFilterFunc){let candidates=[],min=1/0;for(let i=0;i<this._numPieces;++i){if(pieceFilterFunc&&!pieceFilterFunc(i))continue;const availability=this._pieces[i];availability===min?candidates.push(i):availability<min&&(candidates=[i],min=availability)}return candidates.length?candidates[0|Math.random()*candidates.length]:-1}destroy(){this._torrent.removeListener("wire",this._onWire),this._torrent.wires.forEach(wire=>{this._cleanupWireEvents(wire)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(wire){wire._onClose=()=>{this._cleanupWireEvents(wire);for(let i=0;i<this._numPieces;++i)this._pieces[i]-=wire.peerPieces.get(i)},wire.on("have",this._onWireHave),wire.on("bitfield",this._onWireBitfield),wire.once("close",wire._onClose)}recalculate(){this._pieces.fill(0);for(const wire of this._torrent.wires)for(let i=0;i<this._numPieces;++i)this._pieces[i]+=wire.peerPieces.get(i)}_cleanupWireEvents(wire){wire.removeListener("have",this._onWireHave),wire.removeListener("bitfield",this._onWireBitfield),wire._onClose&&wire.removeListener("close",wire._onClose),wire._onClose=null}}},{}],5:[function(require,module){(function(process,global){(function(){function getBlockPipelineLength(wire,duration){let length=2+_Mathceil(duration*wire.downloadSpeed()/Piece.BLOCK_LENGTH);if(wire.peerExtendedHandshake){const reqq=wire.peerExtendedHandshake.reqq;"number"==typeof reqq&&0<reqq&&(length=_Mathmin(length,reqq))}return length}function getPiecePipelineLength(wire,duration,pieceLength){return 1+_Mathceil(duration*wire.downloadSpeed()/pieceLength)}function randomInt(high){return 0|Math.random()*high}function noop(){}const EventEmitter=require("events"),fs=require("fs"),net=require("net"),os=require("os"),path=require("path"),addrToIPPort=require("addr-to-ip-port"),{default:BitField}=require("bitfield"),CacheChunkStore=require("cache-chunk-store"),ChunkStoreWriteStream=require("chunk-store-stream/write"),cpus=require("cpus"),debugFactory=require("debug"),Discovery=require("torrent-discovery"),FSChunkStore=require("fs-chunk-store"),get=require("simple-get"),ImmediateChunkStore=require("immediate-chunk-store"),ltDontHave=require("lt_donthave"),MemoryChunkStore=require("memory-chunk-store"),MultiStream=require("multistream"),parallel=require("run-parallel"),parallelLimit=require("run-parallel-limit"),parseTorrent=require("parse-torrent"),Piece=require("torrent-piece"),pump=require("pump"),queueMicrotask=require("queue-microtask"),randomIterate=require("random-iterate"),sha1=require("simple-sha1"),throughput=require("throughput"),utMetadata=require("ut_metadata"),utPex=require("ut_pex"),File=require("./file.js"),Peer=require("./peer.js"),RarityMap=require("./rarity-map.js"),Server=require("./server.js"),utp=require("./utp.js"),WebConn=require("./webconn.js"),debug=debugFactory("webtorrent:torrent"),CHOKE_TIMEOUT=5e3,SPEED_THRESHOLD=3*Piece.BLOCK_LENGTH,PIPELINE_MAX_DURATION=1,FILESYSTEM_CONCURRENCY=process.browser?cpus().length:2,RECONNECT_WAIT=[1e3,5e3,15e3],VERSION=require("../package.json").version,USER_AGENT=`WebTorrent/${VERSION} (https://webtorrent.io)`;let TMP;try{TMP=path.join(fs.statSync("/tmp")&&"/tmp","webtorrent")}catch(err){TMP=path.join("function"==typeof os.tmpdir?os.tmpdir():"/","webtorrent")}module.exports=class extends EventEmitter{constructor(torrentId,client,opts){super(),this._debugId="unknown infohash",this.client=client,this.announce=opts.announce,this.urlList=opts.urlList,this.path=opts.path||TMP,this.addUID=opts.addUID||!1,this.skipVerify=!!opts.skipVerify,this._store=opts.store||FSChunkStore,this._preloadedStore=opts.preloadedStore||null,this._storeCacheSlots=opts.storeCacheSlots===void 0?20:opts.storeCacheSlots,this._destroyStoreOnDestroy=opts.destroyStoreOnDestroy||!1,this._getAnnounceOpts=opts.getAnnounceOpts,"boolean"==typeof opts.private&&(this.private=opts.private),this.strategy=opts.strategy||"sequential",this.maxWebConns=opts.maxWebConns||4,this._rechokeNumSlots=!1===opts.uploads||0===opts.uploads?0:+opts.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=opts.paused||!1,this.done=!1,this.metadata=null,this.store=null,this.storeOpts=opts.storeOpts,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=throughput(),this._uploadSpeed=throughput(),this._servers=[],this._xsRequests=[],this._fileModtimes=opts.fileModtimes,null!==torrentId&&this._onTorrentId(torrentId),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:1e3*((this.length-this.downloaded)/this.downloadSpeed)}get downloaded(){if(!this.bitfield)return 0;let downloaded=0;for(let index=0,len=this.pieces.length;index<len;++index)if(this.bitfield.get(index))downloaded+=index===len-1?this.lastPieceLength:this.pieceLength;else{const piece=this.pieces[index];downloaded+=piece.length-piece.missing}return downloaded}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){return this.length?this.downloaded/this.length:0}get ratio(){return this.uploaded/(this.received||this.length)}get numPeers(){return this.wires.length}get torrentFileBlobURL(){if("undefined"==typeof window)throw new Error("browser-only property");return this.torrentFile?URL.createObjectURL(new Blob([this.torrentFile],{type:"application/x-bittorrent"})):null}get _numQueued(){return this._queue.length+(this._peersLength-this._numConns)}get _numConns(){let numConns=0;for(const id in this._peers)this._peers[id].connected&&(numConns+=1);return numConns}_onTorrentId(torrentId){if(this.destroyed)return;let parsedTorrent;try{parsedTorrent=parseTorrent(torrentId)}catch(err){}parsedTorrent?(this.infoHash=parsedTorrent.infoHash,this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),queueMicrotask(()=>{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{if(!this.destroyed){const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}}})),this.peerAddresses&&this.peerAddresses.forEach(peer=>this.addPeer(peer)),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT,lsd:this.client.lsd}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",(peer,source)=>{this._debug("peer %s discovered via %s",peer,source);"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.files=this.files.map(file=>new File(this,file));let rawStore=this._preloadedStore;if(rawStore||(rawStore=new this._store(this.pieceLength,{...this.storeOpts,torrent:this,path:this.path,files:this.files,length:this.length,name:this.name+" - "+this.infoHash.slice(0,8),addUID:this.addUID})),0<this._storeCacheSlots&&!(rawStore instanceof MemoryChunkStore)&&(rawStore=new CacheChunkStore(rawStore,{max:this._storeCacheSlots})),this.store=new ImmediateChunkStore(rawStore),this.so?this.files.forEach((v,i)=>{this.so.includes(i)?this.files[i].select():this.files[i].deselect()}):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{const filePath=this.addUID?path.join(this.name+" - "+this.infoHash.slice(0,8)):path.join(this.path,file.path);fs.stat(filePath,(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));const getOpts={};index===this.pieces.length-1&&(getOpts.length=this.lastPieceLength),this.store.get(index,getOpts,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?queueMicrotask(()=>cb(null)):void sha1(buf,hash=>this.destroyed?cb(new Error("torrent is destroyed")):void(hash===this._hashes[index]?(this._debug("piece verified %s",index),this._markVerified(index)):this._debug("piece invalid %s",index),cb(null))))}),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index<this.pieces.length;index++)this._markVerified(index)}_markVerified(index){this.pieces[index]=null,this._reservations[index]=null,this.bitfield.set(index,!0)}_hasAllPieces(){for(let index=0;index<this.pieces.length;index++)if(!this.bitfield.get(index))return!1;return!0}_hasNoPieces(){return!this._hasMorePieces(0)}_hasMorePieces(threshold){let count=0;for(let index=0;index<this.pieces.length;index++)if(this.bitfield.get(index)&&(count+=1,count>threshold))return!0;return!1}_onStore(){this.destroyed||(this._debug("on store"),this._startDiscovery(),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections(),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}))}destroy(opts,cb){return"function"==typeof opts?this.destroy(null,opts):void this._destroy(null,opts,cb)}_destroy(err,opts,cb){if("function"==typeof opts)return this._destroy(err,null,opts);if(!this.destroyed){for(const id in this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),this._xsRequests.forEach(req=>{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});if(this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store){let destroyStore=this._destroyStoreOnDestroy;opts&&void 0!==opts.destroyStore&&(destroyStore=opts.destroyStore),tasks.push(cb=>{destroyStore?this.store.destroy(cb):this.store.close(cb)})}parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");let host;if(this.client.blocked){if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const type=this.client.utp&&this._isIPv4(host)?"utp":"tcp",wasAdded=!!this._addPeer(peer,type);return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer,type){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?"utp"===type?Peer.createUTPOutgoingPeer(peer,this,this.client.throttleGroups):Peer.createTCPOutgoingPeer(peer,this,this.client.throttleGroups):Peer.createWebRTCPeer(peer,this,this.client.throttleGroups),this._registerPeer(newPeer),"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(urlOrConn){if(this.destroyed)throw new Error("torrent is destroyed");let id,conn;if("string"==typeof urlOrConn){if(id=urlOrConn,!/^https?:\/\/.+/.test(id))return this.emit("warning",new Error(`ignoring invalid web seed: ${id}`)),void this.emit("invalidPeer",id);if(this._peers[id])return this.emit("warning",new Error(`ignoring duplicate web seed: ${id}`)),void this.emit("invalidPeer",id);conn=new WebConn(id,this)}else{if(!(urlOrConn&&"string"==typeof urlOrConn.connId))return void this.emit("warning",new Error("addWebSeed must be passed a string or connection object with id property"));if(conn=urlOrConn,id=conn.connId,this._peers[id])return this.emit("warning",new Error(`ignoring duplicate web seed: ${id}`)),void this.emit("invalidPeer",id)}this._debug("add web seed %s",id);const newPeer=Peer.createWebSeedPeer(conn,id,this,this.client.throttleGroups);this._registerPeer(newPeer),this.emit("peer",id)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._registerPeer(peer))}_registerPeer(newPeer){newPeer.on("download",downloaded=>{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.destroyed||this.client.emit("download",downloaded))}),newPeer.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.destroyed||this.client.emit("upload",uploaded))}),this._peers[newPeer.id]=newPeer,this._peersLength+=1}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||end<start||this.pieces.length<=end)throw new Error(`invalid selection ${start} : ${end}`);priority=+priority||0,this._debug("select %s-%s (priority %s)",start,end,priority),this._selections.push({from:start,to:end,offset:0,priority,notify:notify||noop}),this._selections.sort((a,b)=>b.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i<this._selections.length;++i){const s=this._selections[i];if(s.from===start&&s.to===end&&s.priority===priority){this._selections.splice(i,1);break}}this._updateSelections()}critical(start,end){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",start,end);for(let i=start;i<=end;++i)this._critical[i]=!0;this._updateSelections()}_onWire(wire,addr){if(this._debug("got wire %s (%s)",wire._debugId,addr||"Unknown"),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536<port?this._debug("ignoring invalid PORT from peer"):void(this._debug("port: %s (from %s)",port,addr),this.client.dht.addNode({host:wire.remoteAddress,port})):this._debug("ignoring PORT from peer with no address")),wire.on("timeout",()=>{this._debug("wire timeout (%s)",addr),wire.destroy()}),"webSeed"!==wire.type&&wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),wire.use(ltDontHave()),this.emit("wire",wire,addr),this.ready&&queueMicrotask(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i<this.pieces.length;++i)if(!wire.peerPieces.get(i))return;wire.isSeeder=!0,wire.choke()}};wire.on("bitfield",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.lt_donthave.on("donthave",()=>{updateSeedStatus(),this._update(),this._updateWireInterest(wire)}),wire.on("have-all",()=>{wire.isSeeder=!0,wire.choke(),this._update(),this._updateWireInterest(wire)}),wire.on("have-none",()=>{wire.isSeeder=!1,this._update(),this._updateWireInterest(wire)}),wire.on("allowed-fast",()=>{this._update()}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.hasFast&&this._hasAllPieces()?wire.haveAll():wire.hasFast&&this._hasNoPieces()?wire.haveNone():wire.bitfield(this.bitfield),this._updateWireInterest(wire),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(queueMicrotask(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;i<this._selections.length;++i){const s=this._selections[i],oldOffset=s.offset;for(;this.bitfield.get(s.from+s.offset)&&s.from+s.offset<s.to;)s.offset+=1;oldOffset!==s.offset&&s.notify(),s.to===s.from+s.offset&&this.bitfield.get(s.from+s.offset)&&(this._selections.splice(i,1),i-=1,s.notify(),this._updateInterest())}this._selections.length||this.emit("idle")}_updateInterest(){const prev=this._amInterested;this._amInterested=!!this._selections.length,this.wires.forEach(wire=>this._updateWireInterest(wire));prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(wire){let interested=!1;for(let index=0;index<this.pieces.length;++index)if(this.pieces[index]&&wire.peerPieces.get(index)){interested=!0;break}interested?wire.interested():wire.uninterested()}_update(){if(!this.destroyed){const ite=randomIterate(this.wires);for(let wire;wire=ite();)this._updateWireWrapper(wire)}}_updateWireWrapper(wire){const self=this;"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?window.requestIdleCallback(()=>{self._updateWire(wire)},{timeout:250}):self._updateWire(wire)}_updateWire(wire){function genPieceFilterFunc(start,end,tried,rank){return i=>i>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr<self.wires.length;ptr++){const otherWire=self.wires[ptr],otherSpeed=otherWire.downloadSpeed();if(!(otherSpeed<SPEED_THRESHOLD)&&!(otherSpeed<=speed)&&otherWire.peerPieces.get(index)&&!(0<(missing-=otherSpeed*secs)))return tries--,!1}return!0}}function shufflePriority(i){let last=i;for(let j=i;j<self._selections.length&&self._selections[j].priority;j++)last=j;const tmp=self._selections[i];self._selections[i]=self._selections[last],self._selections[last]=tmp}function trySelectWire(hotswap){if(wire.requests.length>=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;i<self._selections.length;i++){const next=self._selections[i];let piece;if("rarest"===self.strategy){const start=next.from+next.offset,end=next.to,tried={};let tries=0;for(const filter=genPieceFilterFunc(start,end,tried,rank);tries<end-start+1&&(piece=self._rarityMap.getRarestPiece(filter),!(0>piece));){for(;self._request(wire,piece,self._critical[piece]||hotswap)&&wire.requests.length<maxOutstandingRequests;);if(wire.requests.length<maxOutstandingRequests){tried[piece]=!0,tries++;continue}return next.priority&&shufflePriority(i),!0}}else for(piece=next.from+next.offset;piece<=next.to;piece++)if(wire.peerPieces.get(piece)&&rank(piece)){for(;self._request(wire,piece,self._critical[piece]||hotswap)&&wire.requests.length<maxOutstandingRequests;);if(!(wire.requests.length<maxOutstandingRequests))return next.priority&&shufflePriority(i),!0}}return!1}const self=this,minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);return wire.peerChoking?void(wire.hasFast&&0<wire.peerAllowedFastSet.length&&!this._hasMorePieces(wire.peerAllowedFastSet.length-1)&&function(){if(wire.requests.length>=maxOutstandingRequests)return!1;for(const piece of wire.peerAllowedFastSet){if(wire.peerPieces.get(piece)&&!self.bitfield.get(piece))for(;self._request(wire,piece,!1)&&wire.requests.length<maxOutstandingRequests;);if(!(wire.requests.length<maxOutstandingRequests))return!0}return!1}()):wire.downloaded?void(trySelectWire(!1)||trySelectWire(!0)):function(){if(!wire.requests.length)for(let i=self._selections.length;i--;){const next=self._selections[i];let piece;if("rarest"===self.strategy){const start=next.from+next.offset,end=next.to,tried={};let tries=0;for(const filter=genPieceFilterFunc(start,end,tried);tries<end-start+1&&(piece=self._rarityMap.getRarestPiece(filter),!(0>piece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}()}_rechoke(){if(this.ready){const wireStack=this.wires.map(wire=>({wire,random:Math.random()})).sort((objA,objB)=>{const wireA=objA.wire,wireB=objB.wire;return wireA.downloadSpeed()===wireB.downloadSpeed()?wireA.uploadSpeed()===wireB.uploadSpeed()?wireA.amChoking===wireB.amChoking?objA.random-objB.random:wireA.amChoking?-1:1:wireA.uploadSpeed()-wireB.uploadSpeed():wireA.downloadSpeed()-wireB.downloadSpeed()}).map(obj=>obj.wire);0>=this._rechokeOptimisticTime?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;for(let numInterestedUnchoked=0;0<wireStack.length&&numInterestedUnchoked<this._rechokeNumSlots-1;){const wire=wireStack.pop();wire.isSeeder||wire===this._rechokeOptimisticWire||(wire.unchoke(),wire.peerInterested&&numInterestedUnchoked++)}if(null===this._rechokeOptimisticWire&&0<this._rechokeNumSlots){const remaining=wireStack.filter(wire=>wire.peerInterested);if(0<remaining.length){const newOptimisticPeer=remaining[randomInt(remaining.length)];newOptimisticPeer.unchoke(),this._rechokeOptimisticWire=newOptimisticPeer,this._rechokeOptimisticTime=2}}wireStack.filter(wire=>wire!==this._rechokeOptimisticWire).forEach(wire=>wire.choke())}}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed<Piece.BLOCK_LENGTH)return!1;if(!this._reservations[index])return!1;const r=this._reservations[index];if(!r)return!1;let minSpeed=1/0,minWire,i;for(i=0;i<r.length;i++){const otherWire=r[i];if(!otherWire||otherWire===wire)continue;const otherSpeed=otherWire.downloadSpeed();otherSpeed>=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i<r.length;i++)r[i]===minWire&&(r[i]=null);for(i=0;i<minWire.requests.length;i++){const req=minWire.requests[i];req.piece===index&&this.pieces[index].cancel(0|req.offset/Piece.BLOCK_LENGTH)}return this.emit("hotswap",minWire,wire,index),!0}_request(wire,index,hotswap){function onUpdateTick(){queueMicrotask(()=>{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{self.destroyed||(hash===self._hashes[index]?(self._debug("piece verified %s",index),self.store.put(index,buf,err=>err?void self._destroy(err):void(self.pieces[index]=null,self._markVerified(index),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete(),onUpdateTick()))):(self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`)),onUpdateTick()))})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(const selection of this._selections){for(let piece=selection.from;piece<=selection.to;piece++)if(!this.bitfield.get(piece)){done=!1;break}if(!done)break}return!this.done&&done?(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")):this.done=!1,this._gcSelections(),done}load(streams,cb){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",()=>{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("%s connect attempt to %s",peer.type,peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]};peer.conn=this.client.utp&&"utpOutgoing"===peer.type?utp.connect(opts.port,opts.host):net.connect(opts);const conn=peer.conn;conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length){if(this.client.utp){const newPeer=this._addPeer(peer.addr,"tcp");newPeer&&(newPeer.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);return}const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{if(!this.destroyed){const host=addrToIPPort(peer.addr)[0],type=this.client.utp&&this._isIPv4(host)?"utp":"tcp",newPeer=this._addPeer(peer.addr,type);newPeer&&(newPeer.retries=peer.retries+1)}},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0<port&&65535>port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}_isIPv4(addr){const IPv4Pattern=/^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/;return IPv4Pattern.test(addr)}}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":282,"./file.js":2,"./peer.js":3,"./rarity-map.js":4,"./server.js":41,"./utp.js":41,"./webconn.js":6,_process:192,"addr-to-ip-port":7,bitfield:31,"cache-chunk-store":77,"chunk-store-stream/write":78,cpus:81,debug:90,events:122,fs:41,"fs-chunk-store":159,"immediate-chunk-store":144,lt_donthave:155,"memory-chunk-store":159,multistream:175,net:41,os:41,"parse-torrent":183,path:184,pump:200,"queue-microtask":205,"random-iterate":207,"run-parallel":232,"run-parallel-limit":231,"simple-get":245,"simple-sha1":247,throughput:267,"torrent-discovery":269,"torrent-piece":270,ut_metadata:276,ut_pex:41}],6:[function(require,module,exports){(function(Buffer){(function(){const{default:BitField}=require("bitfield"),debugFactory=require("debug"),get=require("simple-get"),ltDontHave=require("lt_donthave"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),debug=debugFactory("webtorrent:webconn"),VERSION=require("../package.json").version,SOCKET_TIMEOUT=6e4,RETRY_DELAY=1e4;class WebConn extends Wire{constructor(url,torrent){super(),this.url=url,this.connId=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.use(ltDontHave()),this.once("handshake",(infoHash,peerId)=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.lt_donthave.on("donthave",()=>{debug("donthave")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,(err,data)=>{if(err){this.lt_donthave.donthave(pieceIndex);const retryTimeout=setTimeout(()=>{this.destroyed||this.have(pieceIndex)},RETRY_DELAY);retryTimeout.unref&&retryTimeout.unref()}callback(err,data)})})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path.replace(this._torrent.path,"");return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1<requests.length&&(ret=Buffer.alloc(length)),requests.forEach(request=>{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?hasError?void 0:(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`},timeout:SOCKET_TIMEOUT};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}module.exports=WebConn}).call(this)}).call(this,require("buffer").Buffer)},{"../package.json":282,bitfield:31,"bittorrent-protocol":32,buffer:75,debug:90,lt_donthave:155,"simple-get":245,"simple-sha1":247}],7:[function(require,module,exports){const ADDR_RE=/^\[?([^\]]+)]?:(\d+)$/;let cache=new Map;module.exports=function addrToIPPort(addr){if(1e5===cache.size&&cache.clear(),!cache.has(addr)){const m=ADDR_RE.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache.set(addr,[m[1],+m[2]])}return cache.get(addr)}},{}],8:[function(require,module,exports){"use strict";const asn1=exports;asn1.bignum=require("bn.js"),asn1.define=require("./asn1/api").define,asn1.base=require("./asn1/base"),asn1.constants=require("./asn1/constants"),asn1.decoders=require("./asn1/decoders"),asn1.encoders=require("./asn1/encoders")},{"./asn1/api":9,"./asn1/base":11,"./asn1/constants":15,"./asn1/decoders":17,"./asn1/encoders":20,"bn.js":22}],9:[function(require,module,exports){"use strict";function Entity(name,body){this.name=name,this.body=body,this.decoders={},this.encoders={}}const encoders=require("./encoders"),decoders=require("./decoders"),inherits=require("inherits"),api=exports;api.define=function define(name,body){return new Entity(name,body)},Entity.prototype._createNamed=function createNamed(Base){function Generated(entity){this._initNamed(entity,name)}const name=this.name;return inherits(Generated,Base),Generated.prototype._initNamed=function _initNamed(entity,name){Base.call(this,entity,name)},new Generated(this)},Entity.prototype._getDecoder=function _getDecoder(enc){return enc=enc||"der",this.decoders.hasOwnProperty(enc)||(this.decoders[enc]=this._createNamed(decoders[enc])),this.decoders[enc]},Entity.prototype.decode=function decode(data,enc,options){return this._getDecoder(enc).decode(data,options)},Entity.prototype._getEncoder=function _getEncoder(enc){return enc=enc||"der",this.encoders.hasOwnProperty(enc)||(this.encoders[enc]=this._createNamed(encoders[enc])),this.encoders[enc]},Entity.prototype.encode=function encode(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},{"./decoders":17,"./encoders":20,inherits:145}],10:[function(require,module,exports){"use strict";function DecoderBuffer(base,options){return Reporter.call(this,options),Buffer.isBuffer(base)?void(this.base=base,this.offset=0,this.length=base.length):void this.error("Input not Buffer")}function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if("number"==typeof value){if(!(0<=value&&255>=value))return reporter.error("non-byte EncoderBuffer value");this.value=value,this.length=1}else if("string"==typeof value)this.value=value,this.length=Buffer.byteLength(value);else if(Buffer.isBuffer(value))this.value=value,this.length=value.length;else return reporter.error("Unsupported type: "+typeof value)}const inherits=require("inherits"),Reporter=require("../base/reporter").Reporter,Buffer=require("safer-buffer").Buffer;inherits(DecoderBuffer,Reporter),exports.DecoderBuffer=DecoderBuffer,DecoderBuffer.isDecoderBuffer=function isDecoderBuffer(data){if(data instanceof DecoderBuffer)return!0;const isCompatible="object"==typeof data&&Buffer.isBuffer(data.base)&&"DecoderBuffer"===data.constructor.name&&"number"==typeof data.offset&&"number"==typeof data.length&&"function"==typeof data.save&&"function"==typeof data.restore&&"function"==typeof data.isEmpty&&"function"==typeof data.readUInt8&&"function"==typeof data.skip&&"function"==typeof data.raw;return isCompatible},DecoderBuffer.prototype.save=function save(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function restore(save){const res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function isEmpty(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function readUInt8(fail){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.skip=function skip(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");const res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function raw(save){return this.base.slice(save?save.offset:this.offset,this.length)},exports.EncoderBuffer=EncoderBuffer,EncoderBuffer.isEncoderBuffer=function isEncoderBuffer(data){if(data instanceof EncoderBuffer)return!0;const isCompatible="object"==typeof data&&"EncoderBuffer"===data.constructor.name&&"number"==typeof data.length&&"function"==typeof data.join;return isCompatible},EncoderBuffer.prototype.join=function join(out,offset){return(out||(out=Buffer.alloc(this.length)),offset||(offset=0),0===this.length)?out:(Array.isArray(this.value)?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):("number"==typeof this.value?out[offset]=this.value:"string"==typeof this.value?out.write(this.value,offset):Buffer.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length),out)}},{"../base/reporter":13,inherits:145,"safer-buffer":235}],11:[function(require,module,exports){"use strict";const base=exports;base.Reporter=require("./reporter").Reporter,base.DecoderBuffer=require("./buffer").DecoderBuffer,base.EncoderBuffer=require("./buffer").EncoderBuffer,base.Node=require("./node")},{"./buffer":10,"./node":12,"./reporter":13}],12:[function(require,module,exports){"use strict";function Node(enc,parent,name){const state={};this._baseState=state,state.name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state["default"]=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}const Reporter=require("../base/reporter").Reporter,EncoderBuffer=require("../base/buffer").EncoderBuffer,DecoderBuffer=require("../base/buffer").DecoderBuffer,assert=require("minimalistic-assert"),tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags),overrided=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];module.exports=Node;const stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function clone(){const state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});const res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function wrap(){const state=this._baseState;methods.forEach(function(method){this[method]=function _wrappedMethod(){const clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function init(body){const state=this._baseState;assert(null===state.parent),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,"Root node can have only one child")},Node.prototype._useArgs=function useArgs(args){const state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),0!==children.length&&(assert(null===state.children),state.children=children,children.forEach(function(child){child._baseState.parent=this},this)),0!==args.length&&(assert(null===state.args),state.args=args,state.reverseArgs=args.map(function(arg){if("object"!=typeof arg||arg.constructor!==Object)return arg;const res={};return Object.keys(arg).forEach(function(key){key==(0|key)&&(key|=0);const value=arg[key];res[value]=key}),res}))},overrided.forEach(function(method){Node.prototype[method]=function _overrided(){const state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function _tagMethod(){const state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(null===state.tag),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function use(item){assert(item);const state=this._baseState;return assert(null===state.use),state.use=item,this},Node.prototype.optional=function optional(){const state=this._baseState;return state.optional=!0,this},Node.prototype.def=function def(val){const state=this._baseState;return assert(null===state["default"]),state["default"]=val,state.optional=!0,this},Node.prototype.explicit=function explicit(num){const state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.explicit=num,this},Node.prototype.implicit=function implicit(num){const state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.implicit=num,this},Node.prototype.obj=function obj(){const state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,0!==args.length&&this._useArgs(args),this},Node.prototype.key=function key(newKey){const state=this._baseState;return assert(null===state.key),state.key=newKey,this},Node.prototype.any=function any(){const state=this._baseState;return state.any=!0,this},Node.prototype.choice=function choice(obj){const state=this._baseState;return assert(null===state.choice),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function contains(item){const state=this._baseState;return assert(null===state.use),state.contains=item,this},Node.prototype._decode=function decode(input,options){const state=this._baseState;if(null===state.parent)return input.wrapResult(state.children[0]._decode(input,options));let result=state["default"],present=!0,prevKey=null;if(null!==state.key&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(null===state.explicit?null===state.implicit?null!==state.tag&&(tag=state.tag):tag=state.implicit:tag=state.explicit,null===tag&&!state.any){const save=input.save();try{null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch(e){present=!1}input.restore(save)}else if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}let prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(null!==state.explicit){const explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}const start=input.offset;if(null===state.use&&null===state.choice){let save;state.any&&(save=input.save());const body=this._decodeTag(input,null===state.implicit?state.tag:state.implicit,state.any);if(input.isError(body))return body;state.any?result=input.raw(save):input=body}if(options&&options.track&&null!==state.tag&&options.track(input.path(),start,input.length,"tagged"),options&&options.track&&null!==state.tag&&options.track(input.path(),input.offset,input.length,"content"),state.any||(null===state.choice?result=this._decodeGeneric(state.tag,input,options):result=this._decodeChoice(input,options)),input.isError(result))return result;if(state.any||null!==state.choice||null===state.children||state.children.forEach(function decodeChildren(child){child._decode(input,options)}),state.contains&&("octstr"===state.tag||"bitstr"===state.tag)){const data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),null!==state.key&&(null!==result||!0===present)?input.leaveKey(prevKey,state.key,result):null!==prevKey&&input.exitKey(prevKey),result},Node.prototype._decodeGeneric=function decodeGeneric(tag,input,options){const state=this._baseState;if("seq"===tag||"set"===tag)return null;return"seqof"===tag||"setof"===tag?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)?this._decodeStr(input,tag,options):"objid"===tag&&state.args?this._decodeObjid(input,state.args[0],state.args[1],options):"objid"===tag?this._decodeObjid(input,null,null,options):"gentime"===tag||"utctime"===tag?this._decodeTime(input,tag,options):"null_"===tag?this._decodeNull(input,options):"bool"===tag?this._decodeBool(input,options):"objDesc"===tag?this._decodeStr(input,tag,options):"int"===tag||"enum"===tag?this._decodeInt(input,state.args&&state.args[0],options):null===state.use?input.error("unknown tag: "+tag):this._getUse(state.use,input._reporterState.obj)._decode(input,options)},Node.prototype._getUse=function _getUse(entity,obj){const state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(null===state.useDecoder._baseState.parent),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function decodeChoice(input,options){const state=this._baseState;let result=null,match=!1;return Object.keys(state.choice).some(function(key){const save=input.save(),node=state.choice[key];try{const value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value:value},match=!0}catch(e){return input.restore(save),!1}return!0},this),match?result:input.error("Choice not matched")},Node.prototype._createEncoderBuffer=function createEncoderBuffer(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function encode(data,reporter,parent){const state=this._baseState;if(null===state["default"]||state["default"]!==data){const result=this._encodeValue(data,reporter,parent);return void 0===result||this._skipDefault(result,reporter,parent)?void 0:result}},Node.prototype._encodeValue=function encode(data,reporter,parent){const state=this._baseState;if(null===state.parent)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&void 0===data)if(null!==state["default"])data=state["default"];else return;let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if("null_"===child._baseState.tag)return child._encode(null,reporter,data);if(null===child._baseState.key)return reporter.error("Child should have a key");const prevKey=reporter.enterKey(child._baseState.key);if("object"!=typeof data)return reporter.error("Child expected, but input is not object");const res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if("seqof"===state.tag||"setof"===state.tag){if(!(state.args&&1===state.args.length))return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");const child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){const state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else null===state.use?(content=this._encodePrimitive(state.tag,data),primitive=!0):result=this._getUse(state.use,parent)._encode(data,reporter);if(!state.any&&null===state.choice){const tag=null===state.implicit?state.tag:state.implicit,cls=null===state.implicit?"universal":"context";null===tag?null===state.use&&reporter.error("Tag could be omitted only for .use()"):null===state.use&&(result=this._encodeComposite(tag,primitive,cls,content))}return null!==state.explicit&&(result=this._encodeComposite(state.explicit,!1,"context",result)),result},Node.prototype._encodeChoice=function encodeChoice(data,reporter){const state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+" not found in "+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function encodePrimitive(tag,data){const state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if("objid"===tag&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if("objid"===tag)return this._encodeObjid(data,null,null);if("gentime"===tag||"utctime"===tag)return this._encodeTime(data,tag);if("null_"===tag)return this._encodeNull();if("int"===tag||"enum"===tag)return this._encodeInt(data,state.args&&state.reverseArgs[0]);if("bool"===tag)return this._encodeBool(data);if("objDesc"===tag)return this._encodeStr(data,tag);throw new Error("Unsupported tag: "+tag)},Node.prototype._isNumstr=function isNumstr(str){return /^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function isPrintstr(str){return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str)}},{"../base/buffer":10,"../base/reporter":13,"minimalistic-assert":166}],13:[function(require,module,exports){"use strict";function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}function ReporterError(path,msg){this.path=path,this.rethrow(msg)}const inherits=require("inherits");exports.Reporter=Reporter,Reporter.prototype.isError=function isError(obj){return obj instanceof ReporterError},Reporter.prototype.save=function save(){const state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function restore(data){const state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function enterKey(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function exitKey(index){const state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function leaveKey(index,key,value){const state=this._reporterState;this.exitKey(index),null!==state.obj&&(state.obj[key]=value)},Reporter.prototype.path=function path(){return this._reporterState.path.join("/")},Reporter.prototype.enterObject=function enterObject(){const state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function leaveObject(prev){const state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function error(msg){let err;const state=this._reporterState,inherited=msg instanceof ReporterError;if(err=inherited?msg:new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function wrapResult(result){const state=this._reporterState;return state.options.partial?{result:this.isError(result)?null:result,errors:state.errors}:result},inherits(ReporterError,Error),ReporterError.prototype.rethrow=function rethrow(msg){if(this.message=msg+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:145}],14:[function(require,module,exports){"use strict";function reverse(map){const res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);const value=map[key];res[value]=key}),res}exports.tagClass={0:"universal",1:"application",2:"context",3:"private"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},exports.tagByName=reverse(exports.tag)},{}],15:[function(require,module,exports){"use strict";const constants=exports;constants._reverse=function reverse(map){const res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);const value=map[key];res[value]=key}),res},constants.der=require("./der")},{"./der":14}],16:[function(require,module,exports){"use strict";function DERDecoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function derDecodeTag(buf,fail){let tag=buf.readUInt8(fail);if(buf.isError(tag))return tag;const cls=der.tagClass[tag>>6],primitive=0==(32&tag);if(31==(31&tag)){let oct=tag;for(tag=0;128==(128&oct);){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=127&oct}}else tag&=31;const tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&128===len)return null;if(0==(128&len))return len;const num=127&len;if(4<num)return buf.error("length octect is too long");len=0;for(let i=0;i<num;i++){len<<=8;const j=buf.readUInt8(fail);if(buf.isError(j))return j;len|=j}return len}const inherits=require("inherits"),bignum=require("bn.js"),DecoderBuffer=require("../base/buffer").DecoderBuffer,Node=require("../base/node"),der=require("../constants/der");module.exports=DERDecoder,DERDecoder.prototype.decode=function decode(data,options){return DecoderBuffer.isDecoderBuffer(data)||(data=new DecoderBuffer(data,options)),this.tree._decode(data,options)},inherits(DERNode,Node),DERNode.prototype._peekTag=function peekTag(buffer,tag,any){if(buffer.isEmpty())return!1;const state=buffer.save(),decodedTag=derDecodeTag(buffer,"Failed to peek tag: \""+tag+"\"");return buffer.isError(decodedTag)?decodedTag:(buffer.restore(state),decodedTag.tag===tag||decodedTag.tagStr===tag||decodedTag.tagStr+"of"===tag||any)},DERNode.prototype._decodeTag=function decodeTag(buffer,tag,any){const decodedTag=derDecodeTag(buffer,"Failed to decode tag of \""+tag+"\"");if(buffer.isError(decodedTag))return decodedTag;let len=derDecodeLen(buffer,decodedTag.primitive,"Failed to get length of \""+tag+"\"");if(buffer.isError(len))return len;if(!any&&decodedTag.tag!==tag&&decodedTag.tagStr!==tag&&decodedTag.tagStr+"of"!==tag)return buffer.error("Failed to match tag: \""+tag+"\"");if(decodedTag.primitive||null!==len)return buffer.skip(len,"Failed to match body of: \""+tag+"\"");const state=buffer.save(),res=this._skipUntilEnd(buffer,"Failed to skip indefinite length body: \""+this.tag+"\"");return buffer.isError(res)?res:(len=buffer.offset-state.offset,buffer.restore(state),buffer.skip(len,"Failed to match body of: \""+tag+"\""))},DERNode.prototype._skipUntilEnd=function skipUntilEnd(buffer,fail){for(;;){const tag=derDecodeTag(buffer,fail);if(buffer.isError(tag))return tag;const len=derDecodeLen(buffer,tag.primitive,fail);if(buffer.isError(len))return len;let res;if(res=tag.primitive||null!==len?buffer.skip(len):this._skipUntilEnd(buffer,fail),buffer.isError(res))return res;if("end"===tag.tagStr)break}},DERNode.prototype._decodeList=function decodeList(buffer,tag,decoder,options){const result=[];for(;!buffer.isEmpty();){const possibleEnd=this._peekTag(buffer,"end");if(buffer.isError(possibleEnd))return possibleEnd;const res=decoder.decode(buffer,"der",options);if(buffer.isError(res)&&possibleEnd)break;result.push(res)}return result},DERNode.prototype._decodeStr=function decodeStr(buffer,tag){if("bitstr"===tag){const unused=buffer.readUInt8();return buffer.isError(unused)?unused:{unused:unused,data:buffer.raw()}}if("bmpstr"===tag){const raw=buffer.raw();if(1==raw.length%2)return buffer.error("Decoding of string type: bmpstr length mismatch");let str="";for(let i=0;i<raw.length/2;i++)str+=_StringfromCharCode(raw.readUInt16BE(2*i));return str}if("numstr"===tag){const numstr=buffer.raw().toString("ascii");return this._isNumstr(numstr)?numstr:buffer.error("Decoding of string type: numstr unsupported characters")}if("octstr"===tag)return buffer.raw();if("objDesc"===tag)return buffer.raw();if("printstr"===tag){const printstr=buffer.raw().toString("ascii");return this._isPrintstr(printstr)?printstr:buffer.error("Decoding of string type: printstr unsupported characters")}return /str$/.test(tag)?buffer.raw().toString():buffer.error("Decoding of string type: "+tag+" unsupported")},DERNode.prototype._decodeObjid=function decodeObjid(buffer,values,relative){let result;const identifiers=[];let ident=0,subident=0;for(;!buffer.isEmpty();)subident=buffer.readUInt8(),ident<<=7,ident|=127&subident,0==(128&subident)&&(identifiers.push(ident),ident=0);128&subident&&identifiers.push(ident);const first=0|identifiers[0]/40,second=identifiers[0]%40;if(result=relative?identifiers:[first,second].concat(identifiers.slice(1)),values){let tmp=values[result.join(" ")];void 0===tmp&&(tmp=values[result.join(".")]),void 0!==tmp&&(result=tmp)}return result},DERNode.prototype._decodeTime=function decodeTime(buffer,tag){const str=buffer.raw().toString();let year,mon,day,hour,min,sec;if("gentime"===tag)year=0|str.slice(0,4),mon=0|str.slice(4,6),day=0|str.slice(6,8),hour=0|str.slice(8,10),min=0|str.slice(10,12),sec=0|str.slice(12,14);else if("utctime"===tag)year=0|str.slice(0,2),mon=0|str.slice(2,4),day=0|str.slice(4,6),hour=0|str.slice(6,8),min=0|str.slice(8,10),sec=0|str.slice(10,12),year=70>year?2e3+year:1900+year;else return buffer.error("Decoding "+tag+" time is not supported yet");return Date.UTC(year,mon-1,day,hour,min,sec,0)},DERNode.prototype._decodeNull=function decodeNull(){return null},DERNode.prototype._decodeBool=function decodeBool(buffer){const res=buffer.readUInt8();return buffer.isError(res)?res:0!==res},DERNode.prototype._decodeInt=function decodeInt(buffer,values){const raw=buffer.raw();let res=new bignum(raw);return values&&(res=values[res.toString(10)]||res),res},DERNode.prototype._use=function use(entity,obj){return"function"==typeof entity&&(entity=entity(obj)),entity._getDecoder("der").tree}},{"../base/buffer":10,"../base/node":12,"../constants/der":14,"bn.js":22,inherits:145}],17:[function(require,module,exports){"use strict";const decoders=exports;decoders.der=require("./der"),decoders.pem=require("./pem")},{"./der":16,"./pem":18}],18:[function(require,module,exports){"use strict";function PEMDecoder(entity){DERDecoder.call(this,entity),this.enc="pem"}const inherits=require("inherits"),Buffer=require("safer-buffer").Buffer,DERDecoder=require("./der");inherits(PEMDecoder,DERDecoder),module.exports=PEMDecoder,PEMDecoder.prototype.decode=function decode(data,options){const lines=data.toString().split(/[\r\n]+/g),label=options.label.toUpperCase(),re=/^-----(BEGIN|END) ([^-]+)-----$/;let start=-1,end=-1;for(let i=0;i<lines.length;i++){const match=lines[i].match(re);if(null!==match&&match[2]===label)if(-1===start){if("BEGIN"!==match[1])break;start=i}else{if("END"!==match[1])break;end=i;break}}if(-1===start||-1===end)throw new Error("PEM section not found for: "+label);const base64=lines.slice(start+1,end).join("");base64.replace(/[^a-z0-9+/=]+/gi,"");const input=Buffer.from(base64,"base64");return DERDecoder.prototype.decode.call(this,input,options)}},{"./der":16,inherits:145,"safer-buffer":235}],19:[function(require,module,exports){"use strict";function DEREncoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function two(num){return 10>num?"0"+num:num}function encodeTag(tag,primitive,cls,reporter){let res;if("seqof"===tag?tag="seq":"setof"==tag&&(tag="set"),der.tagByName.hasOwnProperty(tag))res=der.tagByName[tag];else if("number"==typeof tag&&(0|tag)===tag)res=tag;else return reporter.error("Unknown tag: "+tag);return 31<=res?reporter.error("Multi-octet tag encoding unsupported"):(primitive||(res|=32),res|=der.tagClassByName[cls||"universal"]<<6,res)}const inherits=require("inherits"),Buffer=require("safer-buffer").Buffer,Node=require("../base/node"),der=require("../constants/der");module.exports=DEREncoder,DEREncoder.prototype.encode=function encode(data,reporter){return this.tree._encode(data,reporter).join()},inherits(DERNode,Node),DERNode.prototype._encodeComposite=function encodeComposite(tag,primitive,cls,content){const encodedTag=encodeTag(tag,primitive,cls,this.reporter);if(128>content.length){const header=Buffer.alloc(2);return header[0]=encodedTag,header[1]=content.length,this._createEncoderBuffer([header,content])}let lenOctets=1;for(let i=content.length;256<=i;i>>=8)lenOctets++;const header=Buffer.alloc(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;0<j;i--,j>>=8)header[i]=255&j;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function encodeStr(str,tag){if("bitstr"===tag)return this._createEncoderBuffer([0|str.unused,str.data]);if("bmpstr"===tag){const buf=Buffer.alloc(2*str.length);for(let i=0;i<str.length;i++)buf.writeUInt16BE(str.charCodeAt(i),2*i);return this._createEncoderBuffer(buf)}return"numstr"===tag?this._isNumstr(str)?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: numstr supports only digits and space"):"printstr"===tag?this._isPrintstr(str)?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(tag)?this._createEncoderBuffer(str):"objDesc"===tag?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: "+tag+" unsupported")},DERNode.prototype._encodeObjid=function encodeObjid(id,values,relative){if("string"==typeof id){if(!values)return this.reporter.error("string objid given, but no values map found");if(!values.hasOwnProperty(id))return this.reporter.error("objid not found in values map");id=values[id].split(/[\s.]+/g);for(let i=0;i<id.length;i++)id[i]|=0}else if(Array.isArray(id)){id=id.slice();for(let i=0;i<id.length;i++)id[i]|=0}if(!Array.isArray(id))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(id));if(!relative){if(40<=id[1])return this.reporter.error("Second objid identifier OOB");id.splice(0,2,40*id[0]+id[1])}let size=0;for(let i=0,ident;i<id.length;i++)for(ident=id[i],size++;128<=ident;ident>>=7)size++;const objid=Buffer.alloc(size);let offset=objid.length-1;for(let i=id.length-1,ident;0<=i;i--)for(ident=id[i],objid[offset--]=127&ident;0<(ident>>=7);)objid[offset--]=128|127&ident;return this._createEncoderBuffer(objid)},DERNode.prototype._encodeTime=function encodeTime(time,tag){let str;const date=new Date(time);return"gentime"===tag?str=[two(date.getUTCFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):"utctime"===tag?str=[two(date.getUTCFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+tag+" time is not supported yet"),this._encodeStr(str,"octstr")},DERNode.prototype._encodeNull=function encodeNull(){return this._createEncoderBuffer("")},DERNode.prototype._encodeInt=function encodeInt(num,values){if("string"==typeof num){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num));num=values[num]}if("number"!=typeof num&&!Buffer.isBuffer(num)){const numArray=num.toArray();!num.sign&&128&numArray[0]&&numArray.unshift(0),num=Buffer.from(numArray)}if(Buffer.isBuffer(num)){let size=num.length;0===num.length&&size++;const out=Buffer.alloc(size);return num.copy(out),0===num.length&&(out[0]=0),this._createEncoderBuffer(out)}if(128>num)return this._createEncoderBuffer(num);if(256>num)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;256<=i;i>>=8)size++;const out=Array(size);for(let i=out.length-1;0<=i;i--)out[i]=255&num,num>>=8;return 128&out[0]&&out.unshift(0),this._createEncoderBuffer(Buffer.from(out))},DERNode.prototype._encodeBool=function encodeBool(value){return this._createEncoderBuffer(value?255:0)},DERNode.prototype._use=function use(entity,obj){return"function"==typeof entity&&(entity=entity(obj)),entity._getEncoder("der").tree},DERNode.prototype._skipDefault=function skipDefault(dataBuffer,reporter,parent){const state=this._baseState;let i;if(null===state["default"])return!1;const data=dataBuffer.join();if(void 0===state.defaultBuffer&&(state.defaultBuffer=this._encodeValue(state["default"],reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i<data.length;i++)if(data[i]!==state.defaultBuffer[i])return!1;return!0}},{"../base/node":12,"../constants/der":14,inherits:145,"safer-buffer":235}],20:[function(require,module,exports){"use strict";const encoders=exports;encoders.der=require("./der"),encoders.pem=require("./pem")},{"./der":19,"./pem":21}],21:[function(require,module,exports){"use strict";function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc="pem"}const inherits=require("inherits"),DEREncoder=require("./der");inherits(PEMEncoder,DEREncoder),module.exports=PEMEncoder,PEMEncoder.prototype.encode=function encode(data,options){const buf=DEREncoder.prototype.encode.call(this,data),p=buf.toString("base64"),out=["-----BEGIN "+options.label+"-----"];for(let i=0;i<p.length;i+=64)out.push(p.slice(i,i+64));return out.push("-----END "+options.label+"-----"),out.join("\n")}},{"./der":19,inherits:145}],22:[function(require,module,exports){(function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return 65<=c&&70>=c?c-55:97<=c&&102>=c?c-87:15&c-48}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=_Mathmin(str.length,end),i=start,c;i<len;i++)c=str.charCodeAt(i)-48,r*=mul,r+=49<=c?c-49+10:17<=c?c-17+10:c;return r}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit<w.length;bit++){var off=0|bit/26,wbit=bit%26;w[bit]=(num.words[off]&1<<wbit)>>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k<len;k++){for(var ncarry=carry>>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out.strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k<out.length-1;k++){ncarry=hncarry,hncarry=0;for(var rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1);j<=maxJ;j++){var i=k-j,a=0|self.words[i],b=0|num.words[j],r=a*b,lo=67108863&r;ncarry=0|ncarry+(0|r/67108864),lo=0|lo+rword,rword=67108863&lo,ncarry=0|ncarry+(lo>>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer="undefined"!=typeof window&&"undefined"!=typeof window.Buffer?window.Buffer:require("buffer").Buffer}catch(e){}BN.isBN=function isBN(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return 0<left.cmp(right)?left:right},BN.min=function min(left,right){return 0>left.cmp(right)?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function _initNumber(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3);"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function _initArray(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j,w;if("be"===endian)for(i=number.length-1,j=0;0<=i;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i<number.length;i+=3)w=number[i]|number[i+1]<<8|number[i+2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j=0,w;if("be"===endian)for(i=number.length-1;i>=start;i-=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=0==parseLength%2?start+1:start;i<number.length;i+=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;i<end;i+=limbLen)word=parseBase(number,i,i+limbLen,base),this.imuln(limbPow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;i<mod;i++)pow*=base;this.imuln(pow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word)}this.strip()},BN.prototype.copy=function copy(dest){dest.words=Array(this.length);for(var i=0;i<this.length;i++)dest.words[i]=this.words[i];dest.length=this.length,dest.negative=this.negative,dest.red=this.red},BN.prototype.clone=function clone(){var r=new BN(null);return this.copy(r),r},BN.prototype._expand=function _expand(size){for(;this.length<size;)this.words[this.length++]=0;return this},BN.prototype.strip=function strip(){for(;1<this.length&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i<this.length;i++){var w=this.words[i],word=(16777215&(w<<off|carry)).toString(16);carry=16777215&w>>>24-off,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,26<=off&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2<this.length&&assert(!1,"Number can only safely store up to 53 bits"),0===this.negative?ret:-ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert("undefined"!=typeof Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||_Mathmax(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(0<reqLength,"Requested array length <= 0"),this.strip();var littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone(),b,i;if(!littleEndian){for(i=0;i<reqLength-byteLength;i++)res[i]=0;for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[reqLength-i-1]=b}else{for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i<reqLength;i++)res[i]=0}return res},BN.prototype._countBits=_Mathclz?function _countBits(w){return 32-_Mathclz(w)}:function _countBits(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0,b;i<this.length&&(b=this._zeroBits(this.words[i]),r+=b,26===b);i++);return r},BN.prototype.byteLength=function byteLength(){return _Mathceil(this.bitLength()/8)},BN.prototype.toTwos=function toTwos(width){return 0===this.negative?this.clone():this.abs().inotn(width).iaddn(1)},BN.prototype.fromTwos=function fromTwos(width){return this.testn(width-1)?this.notn(width).iaddn(1).ineg():this.clone()},BN.prototype.isNeg=function isNeg(){return 0!==this.negative},BN.prototype.neg=function neg(){return this.clone().ineg()},BN.prototype.ineg=function ineg(){return this.isZero()||(this.negative^=1),this},BN.prototype.iuor=function iuor(num){for(;this.length<num.length;)this.words[this.length++]=0;for(var i=0;i<num.length;i++)this.words[i]|=num.words[i];return this.strip()},BN.prototype.ior=function ior(num){return assert(0==(this.negative|num.negative)),this.iuor(num)},BN.prototype.or=function or(num){return this.length>num.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;i<b.length;i++)this.words[i]&=num.words[i];return this.length=b.length,this.strip()},BN.prototype.iand=function iand(num){return assert(0==(this.negative|num.negative)),this.iuand(num)},BN.prototype.and=function and(num){return this.length>num.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;i<b.length;i++)this.words[i]=a.words[i]^b.words[i];if(this!==a)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=a.length,this.strip()},BN.prototype.ixor=function ixor(num){return assert(0==(this.negative|num.negative)),this.iuxor(num)},BN.prototype.xor=function xor(num){return this.length>num.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0<bitsLeft&&bytesNeeded--;for(var i=0;i<bytesNeeded;i++)this.words[i]=67108863&~this.words[i];return 0<bitsLeft&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<<wbit:this.words[off]&=~(1<<wbit),this.strip()},BN.prototype.iadd=function iadd(num){var r;if(0!==this.negative&&0===num.negative)return this.negative=0,r=this.isub(num),this.negative^=1,this._normSign();if(0===this.negative&&0!==num.negative)return num.negative=0,r=this.isub(num),num.negative=1,r._normSign();var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])+(0|b.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this},BN.prototype.add=function add(num){var res;return 0!==num.negative&&0===this.negative?(num.negative=0,res=this.sub(num),num.negative^=1,res):0===num.negative&&0!==this.negative?(this.negative=0,res=num.sub(this),this.negative=1,res):this.length>num.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0<cmp?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])-(0|b.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;if(0===carry&&i<a.length&&a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=_Mathmax(this.length,i),a!==this&&(this.negative=1),this.strip()},BN.prototype.sub=function sub(num){return this.clone().isub(num)};var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words,b=num.words,o=out.words,c=0,a0=0|a[0],al0=8191&a0,ah0=a0>>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i<N;i++)t[i]=this.revBin(i,l,N);return t},FFTM.prototype.revBin=function revBin(x,l,N){if(0===x||x===N-1)return x;for(var rb=0,i=0;i<l;i++)rb|=(1&x)<<l-i-1,x>>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i<N;i++)rtws[i]=rws[rbt[i]],itws[i]=iws[rbt[i]]},FFTM.prototype.transform=function transform(rws,iws,rtws,itws,N,rbt){this.permute(rbt,rws,iws,rtws,itws,N);for(var s=1;s<N;s<<=1)for(var l=s<<1,rtwdf=_Mathcos(2*_MathPI/l),itwdf=_Mathsin(2*_MathPI/l),p=0;p<N;p+=l)for(var rtwdf_=rtwdf,itwdf_=itwdf,j=0;j<s;j++){var re=rtws[p+j],ie=itws[p+j],ro=rtws[p+j+s],io=itws[p+j+s],rx=rtwdf_*ro-itwdf_*io;io=rtwdf_*io+itwdf_*ro,ro=rx,rtws[p+j]=re+ro,itws[p+j]=ie+io,rtws[p+j+s]=re-ro,itws[p+j+s]=ie-io,j!==l&&(rx=rtwdf*rtwdf_-itwdf*itwdf_,itwdf_=rtwdf*itwdf_+itwdf*rtwdf_,rtwdf_=rx)}},FFTM.prototype.guessLen13b=function guessLen13b(n,m){var N=1|_Mathmax(m,n),odd=1&N,i=0;for(N=0|N/2;N;N>>>=1)i++;return 1<<i+1+odd},FFTM.prototype.conjugate=function conjugate(rws,iws,N){if(!(1>=N))for(var i=0,t;i<N/2;i++)t=rws[i],rws[i]=rws[N-i-1],rws[N-i-1]=t,t=iws[i],iws[i]=-iws[N-i-1],iws[N-i-1]=-t},FFTM.prototype.normalize13b=function normalize13b(ws,N){for(var carry=0,i=0,w;i<N/2;i++)w=8192*_Mathround(ws[2*i+1]/N)+_Mathround(ws[2*i]/N)+carry,ws[i]=67108863&w,carry=67108864>w?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function convert13b(ws,len,rws,N){for(var carry=0,i=0;i<len;i++)carry+=0|ws[i],rws[2*i]=8191&carry,carry>>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i<N;++i)rws[i]=0;assert(0===carry),assert(0==(-8192&carry))},FFTM.prototype.stub=function stub(N){for(var ph=Array(N),i=0;i<N;i++)ph[i]=0;return ph},FFTM.prototype.mulp=function mulp(x,y,out){var N=2*this.guessLen13b(x.length,y.length),rbt=this.makeRBT(N),_=this.stub(N),rws=Array(N),rwst=Array(N),iwst=Array(N),nrws=Array(N),nrwst=Array(N),niwst=Array(N),rmws=out.words;rmws.length=N,this.convert13b(x.words,x.length,rws,N),this.convert13b(y.words,y.length,nrws,N),this.transform(rws,_,rwst,iwst,N,rbt),this.transform(nrws,_,nrwst,niwst,N,rbt);for(var i=0,rx;i<N;i++)rx=rwst[i]*nrwst[i]-iwst[i]*niwst[i],iwst[i]=rwst[i]*niwst[i]+iwst[i]*nrwst[i],rwst[i]=rx;return this.conjugate(rwst,iwst,N),this.transform(rwst,iwst,rmws,_,N,rbt),this.conjugate(rmws,_,N),this.normalize13b(rmws,N),out.negative=x.negative^y.negative,out.length=x.length+y.length,out.strip()},BN.prototype.mul=function mul(num){var out=new BN(null);return out.words=Array(this.length+num.length),this.mulTo(num,out)},BN.prototype.mulf=function mulf(num){var out=new BN(null);return out.words=Array(this.length+num.length),jumboMulTo(this,num,out)},BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)},BN.prototype.imuln=function imuln(num){assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i<this.length;i++){var w=(0|this.words[i])*num,lo=(67108863&w)+(67108863&carry);carry>>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i<w.length&&!(0!==w[i]);i++,res=res.sqr());if(++i<w.length)for(var q=res.sqr();i<w.length;i++,q=q.sqr())0!==w[i]&&(res=res.mul(q));return res},BN.prototype.iushln=function iushln(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(0!=r){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask,c=(0|this.words[i])-newCarry<<r;this.words[i]=c|carry,carry=newCarry>>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;i<s;i++)this.words[i]=0;this.length+=s}return this.strip()},BN.prototype.ishln=function ishln(bits){return assert(0===this.negative),this.iushln(bits)},BN.prototype.iushrn=function iushrn(bits,hint,extended){assert("number"==typeof bits&&0<=bits);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=_Mathmin((bits-r)/26,this.length),mask=67108863^67108863>>>r<<r,maskedWords=extended;if(h-=s,h=_Mathmax(0,h),maskedWords){for(var i=0;i<s;i++)maskedWords.words[i]=this.words[i];maskedWords.length=s}if(0===s);else if(this.length>s)for(this.length-=s,i=0;i<this.length;i++)this.words[i]=this.words[i+s];else this.words[0]=0,this.length=1;var carry=0;for(i=this.length-1;0<=i&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&0<=bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return!1;var w=this.words[s];return!!(w&q)},BN.prototype.imaskn=function imaskn(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!=r&&s++,this.length=_Mathmin(s,this.length),0!=r){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this.strip()},BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)},BN.prototype.iaddn=function iaddn(num){return assert("number"==typeof num),assert(67108864>num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&67108864<=this.words[i];i++)this.words[i]-=67108864,i==this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=_Mathmax(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(67108864>num),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i<this.length&&0>this.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this.strip()},BN.prototype.addn=function addn(num){return this.clone().iaddn(num)},BN.prototype.subn=function subn(num){return this.clone().isubn(num)},BN.prototype.iabs=function iabs(){return this.negative=0,this},BN.prototype.abs=function abs(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i<num.length;i++){w=(0|this.words[i+shift])+carry;var right=(0|num.words[i])*mul;w-=67108863&right,carry=(w>>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i<this.length-shift;i++)w=(0|this.words[i+shift])+carry,carry=w>>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i<this.length;i++)w=-(0|this.words[i])+carry,carry=w>>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;i<q.length;i++)q.words[i]=0}var diff=a.clone()._ishlnsubmul(b,1,m);0===diff.negative&&(a=diff,q&&(q.words[m]=1));for(var j=m-1,qj;0<=j;j--){for(qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]),qj=_Mathmin(0|qj/bhi,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0==(this.negative&num.negative)?num.length>this.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modn=function modn(num){assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(x.iushrn(i);0<i--;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(y.iushrn(j);0<j--;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);0<=x.cmp(y)?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0===a.negative?a.clone():a.umod(p);for(var x1=new BN(1),x2=new BN(0),delta=b.clone();0<a.cmpn(1)&&0<b.cmpn(1);){for(var i=0,im=1;0==(a.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(a.iushrn(i);0<i--;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(b.iushrn(j);0<j--;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);0<=a.cmp(b)?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,0>res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return this._expand(s+1),this.words[s]|=q,this;for(var carry=q,i=s,w;0!==carry&&i<this.length;i++)w=0|this.words[i],w+=carry,carry=w>>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this.strip();var res;if(1<this.length)res=1;else{negative&&(num=-num),assert(67108863>=num,"Number is too big");var w=0|this.words[0];res=w===num?0:w<num?-1:1}return 0===this.negative?res:0|-res},BN.prototype.cmp=function cmp(num){if(0!==this.negative&&0===num.negative)return-1;if(0===this.negative&&0!==num.negative)return 1;var res=this.ucmp(num);return 0===this.negative?res:0|-res},BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;for(var res=0,i=this.length-1;0<=i;i--){var a=0|this.words[i],b=0|num.words[i];if(a!=b){a<b?res=-1:a>b&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return 0<=this.cmpn(num)},BN.prototype.gte=function gte(num){return 0<=this.cmp(num)},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return 0>=this.cmpn(num)},BN.prototype.lte=function lte(num){return 0>=this.cmp(num)},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);return 0===cmp?(r.words[0]=0,r.length=1):0<cmp?r.isub(this.p):void 0===r.strip?r._strip():r.strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var mask=4194303,outLen=_Mathmin(input.length,9),i=0;i<outLen;i++)output.words[i]=input.words[i];if(output.length=outLen,9>=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i<input.length;i++){var next=0|input.words[i];input.words[i-10]=(next&mask)<<4|prev>>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10<input.length?10:9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0,w;i<num.length;i++)w=0|num.words[i],lo+=977*w,num.words[i]=67108863&lo,lo=64*w+(0|lo/67108864);return 0===num.words[num.length-1]&&(num.length--,0===num.words[num.length-1]&&num.length--),num},inherits(P224,MPrime),inherits(P192,MPrime),inherits(P25519,MPrime),P25519.prototype.imulK=function imulK(num){for(var carry=0,i=0;i<num.length;i++){var hi=19*(0|num.words[i])+carry,lo=67108863&hi;hi>>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b),c=b.redSqr(),t=t.redMul(c),m=i}return r},Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);return 0===inv.negative?this.imod(inv):(inv.negative=0,this.imod(inv).redNeg())},Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(0===num.cmpn(1))return a.clone();var windowSize=4,wnd=Array(16);wnd[0]=new BN(1).toRed(this),wnd[1]=a;for(var i=2;i<wnd.length;i++)wnd[i]=this.mul(wnd[i-1],a);var res=wnd[0],current=0,currentLen=0,start=num.bitLength()%26;for(0===start&&(start=26),i=num.length-1;0<=i;i--){for(var word=num.words[i],j=start-1,bit;0<=j;j--){if(bit=1&word>>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:41}],23:[function(require,module,exports){"use strict";function getLens(b64){var len=b64.length;if(0<len%4)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");-1===validLen&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=0<placeHoldersLen?validLen-4:validLen,tmp,i;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=255&tmp>>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;i<end;i+=3)tmp=(16711680&uint8[i]<<16)+(65280&uint8[i+1]<<8)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes,tmp;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62,revLookup[95]=63},{}],24:[function(require,module,exports){(function(Buffer){(function(){function getIntFromBuffer(buffer,start,end){let sum=0,sign=1;for(let i=start;i<end;i++){const num=buffer[i];if(58>num&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}const INTEGER_START=105,STRING_DELIM=58,DICTIONARY_START=100,LIST_START=108,END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case DICTIONARY_START:return decode.dictionary();case LIST_START:return decode.list();case INTEGER_START:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){let i=decode.position;const c=decode.data.length,d=decode.data;for(;i<c;){if(d[i]===chr)return i;i++}throw new Error("Invalid data: Missing delimiter \""+_StringfromCharCode(chr)+"\" [0x"+chr.toString(16)+"]")},decode.dictionary=function(){decode.position++;const dict={};for(;decode.data[decode.position]!==END_OF_TYPE;)dict[decode.buffer()]=decode.next();return decode.position++,dict},decode.list=function(){decode.position++;const lst=[];for(;decode.data[decode.position]!==END_OF_TYPE;)lst.push(decode.next());return decode.position++,lst},decode.integer=function(){const end=decode.find(END_OF_TYPE),number=getIntFromBuffer(decode.data,decode.position+1,end);return decode.position+=end+1-decode.position,number},decode.buffer=function(){let sep=decode.find(STRING_DELIM);const length=getIntFromBuffer(decode.data,decode.position,sep),end=++sep+length;return decode.position=end,decode.encoding?decode.data.toString(decode.encoding,sep,end):decode.data.slice(sep,end)},module.exports=decode}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],25:[function(require,module,exports){(function(Buffer){(function(){function encode(data,buffer,offset){const buffers=[];let result=null;return encode._encode(buffers,data),result=Buffer.concat(buffers),encode.bytes=result.length,Buffer.isBuffer(buffer)?(result.copy(buffer,offset),buffer):result}const{getType}=require("./util.js");encode.bytes=-1,encode._floatConversionDetected=!1,encode._encode=function(buffers,data){if(null!=data)switch(getType(data)){case"buffer":encode.buffer(buffers,data);break;case"object":encode.dict(buffers,data);break;case"map":encode.dictMap(buffers,data);break;case"array":encode.list(buffers,data);break;case"set":encode.listSet(buffers,data);break;case"string":encode.string(buffers,data);break;case"number":encode.number(buffers,data);break;case"boolean":encode.number(buffers,data);break;case"arraybufferview":encode.buffer(buffers,Buffer.from(data.buffer,data.byteOffset,data.byteLength));break;case"arraybuffer":encode.buffer(buffers,Buffer.from(data));}};const buffE=Buffer.from("e"),buffD=Buffer.from("d"),buffL=Buffer.from("l");encode.buffer=function(buffers,data){buffers.push(Buffer.from(data.length+":"),data)},encode.string=function(buffers,data){buffers.push(Buffer.from(Buffer.byteLength(data)+":"+data))},encode.number=function(buffers,data){const maxLo=2147483648,hi=data/2147483648<<0,lo=data%2147483648<<0,val=hi*2147483648+lo;buffers.push(Buffer.from("i"+val+"e")),val===data||encode._floatConversionDetected||(encode._floatConversionDetected=!0,console.warn("WARNING: Possible data corruption detected with value \""+data+"\":","Bencoding only defines support for integers, value was converted to \""+val+"\""),console.trace())},encode.dict=function(buffers,data){buffers.push(buffD);let j=0,k;const keys=Object.keys(data).sort(),kl=keys.length;for(;j<kl;j++)k=keys[j],null!=data[k]&&(encode.string(buffers,k),encode._encode(buffers,data[k]));buffers.push(buffE)},encode.dictMap=function(buffers,data){buffers.push(buffD);const keys=Array.from(data.keys()).sort();for(const key of keys)null!=data.get(key)&&(Buffer.isBuffer(key)?encode._encode(buffers,key):encode.string(buffers,key+""),encode._encode(buffers,data.get(key)));buffers.push(buffE)},encode.list=function(buffers,data){let i=0;const c=data.length;for(buffers.push(buffL);i<c;i++)null!=data[i]&&encode._encode(buffers,data[i]);buffers.push(buffE)},encode.listSet=function(buffers,data){buffers.push(buffL);for(const item of data)null!=item&&encode._encode(buffers,item);buffers.push(buffE)},module.exports=encode}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":28,buffer:75}],26:[function(require,module,exports){(function(Buffer){(function(){function listLength(list){let length=2;for(const value of list)length+=encodingLength(value);return length}function mapLength(map){let length=2;for(const[key,value]of map){const keyLength=Buffer.byteLength(key);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value)}return length}function objectLength(value){let length=2;const keys=Object.keys(value);for(let i=0;i<keys.length;i++){const keyLength=Buffer.byteLength(keys[i]);length+=digitCount(keyLength)+1+keyLength,length+=encodingLength(value[keys[i]])}return length}function stringLength(value){const length=Buffer.byteLength(value);return digitCount(length)+1+length}function arrayBufferLength(value){const length=value.byteLength-value.byteOffset;return digitCount(length)+1+length}function encodingLength(value){const length=0;if(null==value)return 0;const type=getType(value);switch(type){case"buffer":return digitCount(value.length)+1+value.length;case"arraybufferview":return arrayBufferLength(value);case"string":return stringLength(value);case"array":case"set":return listLength(value);case"number":return 1+digitCount(_Mathfloor(value))+1;case"bigint":return 1+value.toString().length+1;case"object":return objectLength(value);case"map":return mapLength(value);default:throw new TypeError(`Unsupported value of type "${type}"`);}}const{digitCount,getType}=require("./util.js");module.exports=encodingLength}).call(this)}).call(this,require("buffer").Buffer)},{"./util.js":28,buffer:75}],27:[function(require,module,exports){const bencode=module.exports;bencode.encode=require("./encode.js"),bencode.decode=require("./decode.js"),bencode.byteLength=bencode.encodingLength=require("./encoding-length.js")},{"./decode.js":24,"./encode.js":25,"./encoding-length.js":26}],28:[function(require,module,exports){(function(Buffer){(function(){const util=module.exports;util.digitCount=function digitCount(value){var _Mathlog=Math.log10;const sign=0>value?1:0;return value=_Mathabs(+(value||1)),_Mathfloor(_Mathlog(value))+1+sign},util.getType=function getType(value){return Buffer.isBuffer(value)?"buffer":ArrayBuffer.isView(value)?"arraybufferview":Array.isArray(value)?"array":value instanceof Number?"number":value instanceof Boolean?"boolean":value instanceof Set?"set":value instanceof Map?"map":value instanceof String?"string":value instanceof ArrayBuffer?"arraybuffer":typeof value}}).call(this)}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":147}],29:[function(require,module,exports){function composeRange(range){return range.reduce((acc,cur,idx,arr)=>((0===idx||cur!==arr[idx-1]+1)&&acc.push([]),acc[acc.length-1].push(cur),acc),[]).map(cur=>1<cur.length?`${cur[0]}-${cur[cur.length-1]}`:`${cur[0]}`)}function parseRange(range){const generateRange=(start,end=start)=>Array.from({length:end-start+1},(cur,idx)=>idx+start);return range.reduce((acc,cur,idx,arr)=>{const r=cur.split("-").map(cur=>parseInt(cur));return acc.concat(generateRange(...r))},[])}module.exports=parseRange,module.exports.parse=parseRange,module.exports.compose=composeRange},{}],30:[function(require,module,exports){module.exports=function(haystack,needle,comparator,low,high){var mid,cmp;if(void 0===low)low=0;else if(low|=0,0>low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high<low||high>=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0<cmp)high=mid-1;else return mid;return~low}},{}],31:[function(require,module,exports){"use strict";function getByteSize(num){var out=num>>3;return 0!=num%8&&out++,out}Object.defineProperty(exports,"__esModule",{value:!0});var BitField=function(){function BitField(data,opts){void 0===data&&(data=0);var grow=null===opts||void 0===opts?void 0:opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}return BitField.prototype.get=function(i){var j=i>>3;return j<this.buffer.length&&!!(this.buffer[j]&128>>i%8)},BitField.prototype.set=function(i,value){void 0===value&&(value=!0);var j=i>>3;if(value){if(this.buffer.length<j+1){var length=_Mathmax(j+1,_Mathmin(2*this.buffer.length,this.grow));if(length<=this.grow){var newBuffer=new Uint8Array(length);newBuffer.set(this.buffer),this.buffer=newBuffer}}this.buffer[j]|=128>>i%8}else j<this.buffer.length&&(this.buffer[j]&=~(128>>i%8))},BitField.prototype.forEach=function(fn,start,end){void 0===start&&(start=0),void 0===end&&(end=8*this.buffer.length);for(var i=start,j=i>>3,y=128>>i%8,byte=this.buffer[j];i<end;i++)fn(!!(byte&y),i),y=1==y?(byte=this.buffer[++j],128):y>>1},BitField}();exports.default=BitField},{}],32:[function(require,module,exports){(function(Buffer){(function(){function xor(a,b){for(let len=a.length;len--;)a[len]^=b[len];return a}/*! bittorrent-protocol. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield").default,crypto=require("crypto"),debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),sha1=require("simple-sha1"),speedometer=require("speedometer"),stream=require("readable-stream"),RC4=require("rc4"),BITFIELD_GROW=4e5,KEEP_ALIVE_TIMEOUT=55e3,ALLOWED_FAST_SET_MAX_LENGTH=100,MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0],MESSAGE_HAVE_ALL=Buffer.from([0,0,0,1,14]),MESSAGE_HAVE_NONE=Buffer.from([0,0,0,1,15]),DH_PRIME="ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563",DH_GENERATOR=2,VC=Buffer.from([0,0,0,0,0,0,0,0]),CRYPTO_PROVIDE=Buffer.from([0,0,1,2]),CRYPTO_SELECT=Buffer.from([0,0,0,2]);class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class HaveAllBitField{constructor(){this.buffer=new Uint8Array}get(index){return!0}set(index){}}class Wire extends stream.Duplex{constructor(type=null,retries=0,peEnabled=!1){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=type,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:BITFIELD_GROW}),this.extensions={},this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this.hasFast=!1,this.allowedFastSet=[],this.peerAllowedFastSet=[],this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=peEnabled,peEnabled?(this._dh=crypto.createDiffieHellman(DH_PRIME,"hex",DH_GENERATOR),this._myPubKey=this._dh.generateKeys("hex")):this._myPubKey=null,this._peerPubKey=null,this._sharedSecret=null,this._peerCryptoProvide=[],this._cryptoHandshakeDone=!1,this._cryptoSyncPattern=null,this._waitMaxBytes=null,this._encryptionMethod=null,this._encryptGenerator=null,this._decryptGenerator=null,this._setGenerators=!1,this.once("finish",()=>this._onFinish()),this.on("finish",this._onFinish),this._debug("type:",this.type),"tcpIncoming"===this.type&&this._peEnabled?this._determineHandshakeType():"tcpOutgoing"===this.type&&this._peEnabled&&0===retries?this._parsePe2():this._parseHandshake(null)}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},KEEP_ALIVE_TIMEOUT))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._resetTimeout(!0)}destroy(){if(!this.destroyed)return this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end(),this}end(...args){return this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}sendPe1(){if(this._peEnabled){const padALen=_Mathfloor(513*Math.random()),padA=randombytes(padALen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padA]))}}sendPe2(){const padBLen=_Mathfloor(513*Math.random()),padB=randombytes(padBLen);this._push(Buffer.concat([Buffer.from(this._myPubKey,"hex"),padB]))}sendPe3(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex"),hash2Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req2")+infoHash,"hex")),"hex"),hash3Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),"hex"),hashesXorBuffer=xor(hash2Buffer,hash3Buffer),padCLen=randombytes(2).readUInt16BE(0)%512,padCBuffer=randombytes(padCLen);let vcAndProvideBuffer=Buffer.alloc(14+padCLen+2);VC.copy(vcAndProvideBuffer),CRYPTO_PROVIDE.copy(vcAndProvideBuffer,8),vcAndProvideBuffer.writeInt16BE(padCLen,12),padCBuffer.copy(vcAndProvideBuffer,14),vcAndProvideBuffer.writeInt16BE(0,14+padCLen),vcAndProvideBuffer=this._encryptHandshake(vcAndProvideBuffer),this._push(Buffer.concat([hash1Buffer,hashesXorBuffer,vcAndProvideBuffer]))}sendPe4(infoHash){this.setEncrypt(this._sharedSecret,infoHash);const padDLen=randombytes(2).readUInt16BE(0)%512,padDBuffer=randombytes(padDLen);let vcAndSelectBuffer=Buffer.alloc(14+padDLen);VC.copy(vcAndSelectBuffer),CRYPTO_SELECT.copy(vcAndSelectBuffer,8),vcAndSelectBuffer.writeInt16BE(padDLen,12),padDBuffer.copy(vcAndSelectBuffer,14),vcAndSelectBuffer=this._encryptHandshake(vcAndSelectBuffer),this._push(vcAndSelectBuffer),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),this._infoHash=infoHashBuffer,20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);this.extensions={extended:!0,dht:!!(extensions&&extensions.dht),fast:!!(extensions&&extensions.fast)},reserved[5]|=16,this.extensions.dht&&(reserved[7]|=1),this.extensions.fast&&(reserved[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(MESSAGE_CHOKE),this.hasFast)for(let allowedCount=0;this.peerRequests.length>allowedCount;){const request=this.peerRequests[allowedCount];this.allowedFastSet.includes(request.piece)?++allowedCount:this.reject(request.piece,request.offset,request.length)}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking&&!(this.hasFast&&this.peerAllowedFastSet.includes(index))?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),!this._timeout&&this._resetTimeout(!0),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this._message(7,[index,offset],buffer),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}suggest(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("suggest %d",index),this._message(13,[index],null)}haveAll(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-all"),this._push(MESSAGE_HAVE_ALL)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(MESSAGE_HAVE_NONE)}reject(index,offset,length){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this._message(16,[index,offset,length],null)}allowedFast(index){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("allowed-fast %d",index),this.allowedFastSet.includes(index)||this.allowedFastSet.push(index),this._message(17,[index],null)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}setEncrypt(sharedSecret,infoHash){let encryptKey,decryptKey,encryptKeyBuf,encryptKeyIntArray,decryptKeyBuf,decryptKeyIntArray;switch(this.type){case"tcpIncoming":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;case"tcpOutgoing":encryptKey=sha1.sync(Buffer.from(this._utfToHex("keyA")+sharedSecret+infoHash,"hex")),decryptKey=sha1.sync(Buffer.from(this._utfToHex("keyB")+sharedSecret+infoHash,"hex")),encryptKeyBuf=Buffer.from(encryptKey,"hex"),encryptKeyIntArray=[];for(const value of encryptKeyBuf.values())encryptKeyIntArray.push(value);decryptKeyBuf=Buffer.from(decryptKey,"hex"),decryptKeyIntArray=[];for(const value of decryptKeyBuf.values())decryptKeyIntArray.push(value);this._encryptGenerator=new RC4(encryptKeyIntArray),this._decryptGenerator=new RC4(decryptKeyIntArray);break;default:return!1;}for(let i=0;1024>i;i++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;i<numbers.length;i++)buffer.writeUInt32BE(numbers[i],5+4*i);this._push(buffer),data&&this._push(data)}_push(data){if(!this._finished)return 2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._encrypt(data)),this.push(data)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onPe1(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(pubKeyBuffer){this._peerPubKey=pubKeyBuffer.toString("hex"),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}_onPe3(hashesXorBuffer){const hash3=sha1.sync(Buffer.from(this._utfToHex("req3")+this._sharedSecret,"hex")),sKeyHash=xor(Buffer.from(hash3,"hex"),hashesXorBuffer).toString("hex");this.emit("pe3",sKeyHash)}_onPe3Encrypted(vcBuffer,peerProvideBuffer){if(!vcBuffer.equals(VC))return this._debug("Error: verification constant did not match"),void this.destroy();for(const provideByte of peerProvideBuffer.values())0!==provideByte&&this._peerCryptoProvide.push(provideByte);this._peerCryptoProvide.includes(2)?this._encryptionMethod=2:(this._debug("Error: RC4 encryption method not provided by peer"),this.destroy())}_onPe4(peerSelectBuffer){this._encryptionMethod=peerSelectBuffer.readUInt8(3),CRYPTO_PROVIDE.includes(this._encryptionMethod)||(this._debug("Error: peer selected invalid crypto method"),this.destroy()),this._cryptoHandshakeDone=!0,this._debug("crypto handshake done"),this.emit("pe4")}_onHandshake(infoHashBuffer,peerIdBuffer,extensions){const infoHash=infoHashBuffer.toString("hex"),peerId=peerIdBuffer.toString("hex");for(const name in this._debug("got handshake i=%s p=%s exts=%o",infoHash,peerId,extensions),this.peerId=peerId,this.peerIdBuffer=peerIdBuffer,this.peerExtensions=extensions,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",infoHash,peerId,extensions),this._ext)this._ext[name].onHandshake(infoHash,peerId,extensions);extensions.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){if(this.peerChoking=!0,this._debug("got choke"),this.emit("choke"),!this.hasFast)for(;this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(index){this.peerPieces.get(index)||(this._debug("got have %d",index),this.peerPieces.set(index,!0),this.emit("have",index))}_onBitField(buffer){this.peerPieces=new BitField(buffer),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(index,offset,length){if(this.amChoking&&!(this.hasFast&&this.allowedFastSet.includes(index)))return void(this.hasFast&&this.reject(index,offset,length));this._debug("got request index=%d offset=%d length=%d",index,offset,length);const respond=(err,buffer)=>request===this._pull(this.peerRequests,index,offset,length)?err?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message),void(this.hasFast&&this.reject(index,offset,length))):void this.piece(index,offset,buffer):void 0,request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onSuggest(index){return this.hasFast?void(this._debug("got suggest %d",index),this.emit("suggest",index)):(this._debug("Error: got suggest whereas fast extension is disabled"),void this.destroy())}_onHaveAll(){return this.hasFast?void(this._debug("got have-all"),this.peerPieces=new HaveAllBitField,this.emit("have-all")):(this._debug("Error: got have-all whereas fast extension is disabled"),void this.destroy())}_onHaveNone(){return this.hasFast?void(this._debug("got have-none"),this.emit("have-none")):(this._debug("Error: got have-none whereas fast extension is disabled"),void this.destroy())}_onReject(index,offset,length){return this.hasFast?void(this._debug("got reject index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was rejected"),null),this.emit("reject",index,offset,length)):(this._debug("Error: got reject whereas fast extension is disabled"),void this.destroy())}_onAllowedFast(index){return this.hasFast?void(this._debug("got allowed-fast %d",index),!this.peerAllowedFastSet.includes(index)&&this.peerAllowedFastSet.push(index),this.peerAllowedFastSet.length>ALLOWED_FAST_SET_MAX_LENGTH&&this.peerAllowedFastSet.shift(),this.emit("allowed-fast",index)):(this._debug("Error: got allowed-fast whereas fast extension is disabled"),void this.destroy())}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;if(this.peerExtendedHandshake=info,"object"==typeof info.m)for(const name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(const name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(data=this._decrypt(data)),this._bufferSize+=data.length,this._buffer.push(data),1<this._buffer.length&&(this._buffer=[Buffer.concat(this._buffer,this._bufferSize)]),this._cryptoSyncPattern){const index=this._buffer[0].indexOf(this._cryptoSyncPattern);if(-1!==index)this._buffer[0]=this._buffer[0].slice(index+this._cryptoSyncPattern.length),this._bufferSize-=index+this._cryptoSyncPattern.length,this._cryptoSyncPattern=null;else if(this._bufferSize+data.length>this._waitMaxBytes+this._cryptoSyncPattern.length)return this._debug("Error: could not resynchronize"),void this.destroy()}for(;this._bufferSize>=this._parserSize&&!this._cryptoSyncPattern;)if(0===this._parserSize)this._parser(Buffer.from([]));else{const buffer=this._buffer[0];this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._resetTimeout(!this.peerChoking&&!this._finished),request.callback(err,buffer))}_resetTimeout(setAgain){if(!setAgain||!this._timeoutMs||!this.requests.length)return clearTimeout(this._timeout),this._timeout=null,void(this._timeoutExpiresAt=null);const timeoutExpiresAt=Date.now()+this._timeoutMs;if(this._timeout){if(timeoutExpiresAt-this._timeoutExpiresAt<.05*this._timeoutMs)return;clearTimeout(this._timeout)}this._timeoutExpiresAt=timeoutExpiresAt,this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref()}_parse(size,parser){this._parserSize=size,this._parser=parser}_parseUntil(pattern,maxBytes){this._cryptoSyncPattern=pattern,this._waitMaxBytes=maxBytes}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0<length?this._parse(length,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(buffer){switch(this._parse(4,this._onMessageLength),buffer[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(buffer.readUInt32BE(1));case 5:return this._onBitField(buffer.slice(1));case 6:return this._onRequest(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 7:return this._onPiece(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.slice(9));case 8:return this._onCancel(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 9:return this._onPort(buffer.readUInt16BE(1));case 13:return this._onSuggest(buffer.readUInt32BE(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 17:return this._onAllowedFast(buffer.readUInt32BE(1));case 20:return this._onExtended(buffer.readUInt8(1),buffer.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",buffer);}}_determineHandshakeType(){this._parse(1,pstrLenBuffer=>{const pstrlen=pstrLenBuffer.readUInt8(0);19===pstrlen?this._parse(pstrlen+48,this._onHandshakeBuffer):this._parsePe1(pstrLenBuffer)})}_parsePe1(pubKeyPrefix){this._parse(95,pubKeySuffix=>{this._onPe1(Buffer.concat([pubKeyPrefix,pubKeySuffix])),this._parsePe3()})}_parsePe2(){this._parse(96,pubKey=>{for(this._onPe2(pubKey);!this._setGenerators;);this._parsePe4()})}_parsePe3(){const hash1Buffer=Buffer.from(sha1.sync(Buffer.from(this._utfToHex("req1")+this._sharedSecret,"hex")),"hex");this._parseUntil(hash1Buffer,512),this._parse(20,buffer=>{for(this._onPe3(buffer);!this._setGenerators;);this._parsePe3Encrypted()})}_parsePe3Encrypted(){this._parse(14,buffer=>{const vcBuffer=this._decryptHandshake(buffer.slice(0,8)),peerProvideBuffer=this._decryptHandshake(buffer.slice(8,12)),padCLen=this._decryptHandshake(buffer.slice(12,14)).readUInt16BE(0);this._parse(padCLen,padCBuffer=>{padCBuffer=this._decryptHandshake(padCBuffer),this._parse(2,iaLenBuf=>{const iaLen=this._decryptHandshake(iaLenBuf).readUInt16BE(0);this._parse(iaLen,iaBuffer=>{iaBuffer=this._decryptHandshake(iaBuffer),this._onPe3Encrypted(vcBuffer,peerProvideBuffer,padCBuffer,iaBuffer);const pstrlen=iaLen?iaBuffer.readUInt8(0):null,protocol=iaLen?iaBuffer.slice(1,20):null;19===pstrlen&&"BitTorrent protocol"===protocol.toString()?this._onHandshakeBuffer(iaBuffer.slice(1)):this._parseHandshake()})})})})}_parsePe4(){const vcBufferEncrypted=this._decryptHandshake(VC);this._parseUntil(vcBufferEncrypted,512),this._parse(6,buffer=>{const peerSelectBuffer=this._decryptHandshake(buffer.slice(0,4)),padDLen=this._decryptHandshake(buffer.slice(4,6)).readUInt16BE(0);this._parse(padDLen,padDBuf=>{this._decryptHandshake(padDBuf),this._onPe4(peerSelectBuffer),this._parseHandshake(null)})})}_parseHandshake(){this._parse(1,buffer=>{const pstrlen=buffer.readUInt8(0);return 19===pstrlen?void this._parse(pstrlen+48,this._onHandshakeBuffer):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",pstrlen.toString()),void this.end())})}_onHandshakeBuffer(handshake){const protocol=handshake.slice(0,19);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(19),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),fast:!!(4&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i<requests.length;i++){const req=requests[i];if(req.piece===piece&&req.offset===offset&&req.length===length)return arrayRemove(requests,i),req}return null}_encryptHandshake(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_encrypt(buf){const crypt=Buffer.from(buf);if(!this._encryptGenerator||2!==this._encryptionMethod)return crypt;for(let i=0;i<buf.length;i++){const keystream=this._encryptGenerator.randomByte();crypt[i]^=keystream}return crypt}_decryptHandshake(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_decrypt(buf){const decrypt=Buffer.from(buf);if(!this._decryptGenerator||2!==this._encryptionMethod)return decrypt;for(let i=0;i<buf.length;i++){const keystream=this._decryptGenerator.randomByte();decrypt[i]^=keystream}return decrypt}_utfToHex(str){return Buffer.from(str,"utf8").toString("hex")}}module.exports=Wire}).call(this)}).call(this,require("buffer").Buffer)},{bencode:27,bitfield:31,buffer:75,crypto:89,debug:90,randombytes:208,rc4:212,"readable-stream":227,"simple-sha1":247,speedometer:254,"unordered-array-remove":273}],33:[function(require,module,exports){(function(process,Buffer){(function(){const debug=require("debug")("bittorrent-tracker:client"),EventEmitter=require("events"),once=require("once"),parallel=require("run-parallel"),Peer=require("simple-peer"),queueMicrotask=require("queue-microtask"),common=require("./lib/common"),HTTPTracker=require("./lib/client/http-tracker"),UDPTracker=require("./lib/client/udp-tracker"),WebSocketTracker=require("./lib/client/websocket-tracker");class Client 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(!opts.announce)throw new Error("Option `announce` 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._peerIdBuffer=Buffer.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._infoHashBuffer=Buffer.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),debug("new client %s",this.infoHash),this.destroyed=!1,this._port=opts.port,this._getAnnounceOpts=opts.getAnnounceOpts,this._rtcConfig=opts.rtcConfig,this._userAgent=opts.userAgent,this._proxyOpts=opts.proxyOpts,this._wrtc="function"==typeof opts.wrtc?opts.wrtc():opts.wrtc;let announce="string"==typeof opts.announce?[opts.announce]:null==opts.announce?[]:opts.announce;announce=announce.map(announceUrl=>(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{queueMicrotask(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=common.parseUrl(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535<port)return nextTickWarn(new Error(`Invalid tracker port: ${announceUrl}`)),null;const protocol=parsedUrl.protocol;return("http:"===protocol||"https:"===protocol)&&"function"==typeof HTTPTracker?new HTTPTracker(this,announceUrl):"udp:"===protocol&&"function"==typeof UDPTracker?new UDPTracker(this,announceUrl):("ws:"===protocol||"wss:"===protocol)&&webrtcSupport?"ws:"===protocol&&"undefined"!=typeof window&&"https:"===window.location.protocol?(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null):new WebSocketTracker(this,announceUrl):(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null)}).filter(Boolean)}start(opts){opts=this._defaultAnnounceOpts(opts),opts.event="started",debug("send `start` %o",opts),this._announce(opts),this._trackers.forEach(tracker=>{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":41,"./lib/client/udp-tracker":41,"./lib/client/websocket-tracker":35,"./lib/common":36,_process:192,buffer:75,debug:90,events:122,once:177,"queue-microtask":205,"run-parallel":232,"simple-peer":246}],34:[function(require,module,exports){const EventEmitter=require("events");class Tracker extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}module.exports=Tracker},{events:122}],35:[function(require,module,exports){function noop(){}const clone=require("clone"),debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),Socks=require("socks"),common=require("../common"),Tracker=require("./tracker"),socketPool={},RECONNECT_MINIMUM=10000,RECONNECT_MAXIMUM=3600000,RECONNECT_VARIANCE=300000,OFFER_TIMEOUT=50000;class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,5);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary,params={action:"scrape",info_hash:infoHashes};this._send(params)}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0<socketPool[this.announceUrl].consumers)return cb();let socket=socketPool[this.announceUrl];delete socketPool[this.announceUrl],socket.on("error",noop),socket.once("close",cb);let timeout;return this.expectingResponse?void(timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT),socket.once("data",destroyCleanup)):destroyCleanup()}_openSocket(){if(this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket)socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound();else{const parsedUrl=new URL(this.announceUrl);let agent;this.client._proxyOpts&&(agent="wss:"===parsedUrl.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!agent&&this.client._proxyOpts.socksProxy&&(agent=new Socks.Agent(clone(this.client._proxyOpts.socksProxy),"wss:"===parsedUrl.protocol))),this.socket=socketPool[this.announceUrl]=new Socket({url:this.announceUrl,agent}),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)}this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),this.client.emit("peer",peer),peer.signal(data.offer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),this.client.emit("peer",peer),peer.signal(data.answer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*RECONNECT_VARIANCE)+_Mathmin(_Mathpow(2,this.retries)*RECONNECT_MINIMUM,RECONNECT_MAXIMUM);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},OFFER_TIMEOUT),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i<numwant;++i)generateOffer();checkDone()}_createPeer(opts){function onError(err){self.client.emit("warning",new Error(`Connection error: ${err.message}`)),peer.destroy()}function onConnect(){peer.removeListener("error",onError),peer.removeListener("connect",onConnect)}const self=this;opts=Object.assign({trickle:!1,config:self.client._rtcConfig,wrtc:self.client._wrtc},opts);const peer=new Peer(opts);return peer.once("error",onError),peer.once("connect",onConnect),peer}}WebSocketTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=30000,WebSocketTracker._socketPool=socketPool,module.exports=WebSocketTracker},{"../common":36,"./tracker":34,clone:80,debug:90,randombytes:208,"simple-peer":246,"simple-websocket":249,socks:41}],36:[function(require,module,exports){(function(Buffer){(function(){exports.DEFAULT_ANNOUNCE_PEERS=50,exports.MAX_ANNOUNCE_PEERS=82,exports.binaryToHex=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"binary").toString("hex")),exports.hexToBinary=str=>("string"!=typeof str&&(str+=""),Buffer.from(str,"hex").toString("binary")),exports.parseUrl=str=>{const url=new URL(str.replace(/^udp:/,"http:"));return str.match(/^udp:/)&&Object.defineProperties(url,{href:{value:url.href.replace(/^http/,"udp")},protocol:{value:url.protocol.replace(/^http/,"udp")},origin:{value:url.origin.replace(/^http/,"udp")}}),url};const config=require("./common-node");Object.assign(exports,config)}).call(this)}).call(this,require("buffer").Buffer)},{"./common-node":41,buffer:75}],37:[function(require,module,exports){(function(Buffer){(function(){/*! blob-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */module.exports=function blobToBuffer(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");const reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],38:[function(require,module,exports){(function(Buffer){(function(){const{Transform}=require("readable-stream");class Block extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){this._bufferedBytes-=this.size;const blockBufs=[];for(let blockBufsBytes=0;blockBufsBytes<this.size;){const b=this._buffered.shift();if(blockBufsBytes+b.length<=this.size)blockBufs.push(b),blockBufsBytes+=b.length;else{const neededSize=this.size-blockBufsBytes;blockBufs.push(b.slice(0,neededSize)),blockBufsBytes+=neededSize,this._buffered.unshift(b.slice(neededSize))}}this.push(Buffer.concat(blockBufs,this.size))}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}module.exports=Block}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"readable-stream":227}],39:[function(require,module,exports){(function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:void(this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&(("le"===base||"be"===base)&&(endian=base,base=10),this._init(number||0,base||10,endian||"be")))}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return 48<=c&&57>=c?c-48:65<=c&&70>=c?c-55:97<=c&&102>=c?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=_Mathmin(str.length,end),i=start,c;i<len;i++)c=str.charCodeAt(i)-48,r*=mul,b=49<=c?c-49+10:17<=c?c-17+10:c,assert(0<=c&&b<mul,"Invalid character"),r+=b;return r}function move(dest,src){dest.words=src.words,dest.length=src.length,dest.negative=src.negative,dest.red=src.red}function inspect(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}function toBitArray(num){for(var w=Array(num.bitLength()),bit=0;bit<w.length;bit++){var off=0|bit/26,wbit=bit%26;w[bit]=1&num.words[off]>>>wbit}return w}function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=0|self.length+num.length;out.length=len,len=0|len-1;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=0|r/67108864;out.words[0]=lo;for(var k=1;k<len;k++){for(var ncarry=carry>>>26,rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1),i;j<=maxJ;j++)i=0|k-j,a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=0|r/67108864,rword=67108863&r;out.words[k]=0|rword,carry=0|ncarry}return 0===carry?out.length--:out.words[k]=0|carry,out._strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0,ncarry;k<out.length-1;k++){ncarry=hncarry,hncarry=0;for(var rword=67108863&carry,maxJ=_Mathmin(k,num.length-1),j=_Mathmax(0,k-self.length+1);j<=maxJ;j++){var i=k-j,a=0|self.words[i],b=0|num.words[j],r=a*b,lo=67108863&r;ncarry=0|ncarry+(0|r/67108864),lo=0|lo+rword,rword=67108863&lo,ncarry=0|ncarry+(lo>>>26),hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0===carry?out.length--:out.words[k]=carry,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),0!=this.shift%26&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer="undefined"!=typeof window&&"undefined"!=typeof window.Buffer?window.Buffer:require("buffer").Buffer}catch(e){}if(BN.isBN=function isBN(num){return!!(num instanceof BN)||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return 0<left.cmp(right)?left:right},BN.min=function min(left,right){return 0>left.cmp(right)?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&2<=base&&36>=base),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function _initNumber(number,base,endian){0>number&&(this.negative=1,number=-number),67108864>number?(this.words=[67108863&number],this.length=1):4503599627370496>number?(this.words=[67108863&number,67108863&number/67108864],this.length=2):(assert(9007199254740992>number),this.words=[67108863&number,67108863&number/67108864,1],this.length=3),"le"!==endian||this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function _initArray(number,base,endian){if(assert("number"==typeof number.length),0>=number.length)return this.words=[0],this.length=1,this;this.length=_Mathceil(number.length/3),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j,w;if("be"===endian)for(i=number.length-1,j=0;0<=i;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i<number.length;i+=3)w=number[i]|number[i+1]<<8|number[i+2]<<16,this.words[j]|=67108863&w<<off,this.words[j+1]=67108863&w>>>26-off,off+=24,26<=off&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=_Mathceil((number.length-start)/6),this.words=Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var off=0,j=0,w;if("be"===endian)for(i=number.length-1;i>=start;i-=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=0==parseLength%2?start+1:start;i<number.length;i+=2)w=parseHexByte(number,start,i)<<off,this.words[j]|=67108863&w,18<=off?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;67108863>=limbPow;limbPow*=base)limbLen++;limbLen--,limbPow=0|limbPow/base;for(var total=number.length-start,mod=total%limbLen,end=_Mathmin(total,total-mod)+start,word=0,i=start;i<end;i+=limbLen)word=parseBase(number,i,i+limbLen,base),this.imuln(limbPow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word);if(0!==mod){var pow=1;for(word=parseBase(number,i,number.length,base),i=0;i<mod;i++)pow*=base;this.imuln(pow),67108864>this.words[0]+word?this.words[0]+=word:this._iaddn(word)}this._strip()},BN.prototype.copy=function copy(dest){dest.words=Array(this.length);for(var i=0;i<this.length;i++)dest.words[i]=this.words[i];dest.length=this.length,dest.negative=this.negative,dest.red=this.red},BN.prototype._move=function _move(dest){move(dest,this)},BN.prototype.clone=function clone(){var r=new BN(null);return this.copy(r),r},BN.prototype._expand=function _expand(size){for(;this.length<size;)this.words[this.length++]=0;return this},BN.prototype._strip=function strip(){for(;1<this.length&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i<this.length;i++){var w=this.words[i],word=(16777215&(w<<off|carry)).toString(16);carry=16777215&w>>>24-off,off+=2,26<=off&&(off-=26,i--),out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out}for(0!==carry&&(out=carry.toString(16)+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&2<=base&&36>=base){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);0!=out.length%padding;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:2<this.length&&assert(!1,"Number can only safely store up to 53 bits"),0===this.negative?ret:-ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};var allocate=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||_Mathmax(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(0<reqLength,"Requested array length <= 0");var res=allocate(ArrayType,reqLength),postfix="le"===endian?"LE":"BE";return this["_toArrayLike"+postfix](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position++]=255&word,position<res.length&&(res[position++]=255&word>>8),position<res.length&&(res[position++]=255&word>>16),6==shift?(position<res.length&&(res[position++]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(position<res.length)for(res[position++]=carry;position<res.length;)res[position++]=0},BN.prototype._toArrayLikeBE=function _toArrayLikeBE(res,byteLength){for(var position=res.length-1,carry=0,i=0,shift=0,word;i<this.length;i++)word=this.words[i]<<shift|carry,res[position--]=255&word,0<=position&&(res[position--]=255&word>>8),0<=position&&(res[position--]=255&word>>16),6==shift?(0<=position&&(res[position--]=255&word>>24),carry=0,shift=0):(carry=word>>>24,shift+=2);if(0<=position)for(res[position--]=carry;0<=position;)res[position--]=0},BN.prototype._countBits=_Mathclz?function _countBits(w){return 32-_Mathclz(w)}:function _countBits(w){var t=w,r=0;return 4096<=t&&(r+=13,t>>>=13),64<=t&&(r+=7,t>>>=7),8<=t&&(r+=4,t>>>=4),2<=t&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0,b;i<this.length&&(b=this._zeroBits(this.words[i]),r+=b,26===b);i++);return r},BN.prototype.byteLength=function byteLength(){return _Mathceil(this.bitLength()/8)},BN.prototype.toTwos=function toTwos(width){return 0===this.negative?this.clone():this.abs().inotn(width).iaddn(1)},BN.prototype.fromTwos=function fromTwos(width){return this.testn(width-1)?this.notn(width).iaddn(1).ineg():this.clone()},BN.prototype.isNeg=function isNeg(){return 0!==this.negative},BN.prototype.neg=function neg(){return this.clone().ineg()},BN.prototype.ineg=function ineg(){return this.isZero()||(this.negative^=1),this},BN.prototype.iuor=function iuor(num){for(;this.length<num.length;)this.words[this.length++]=0;for(var i=0;i<num.length;i++)this.words[i]|=num.words[i];return this._strip()},BN.prototype.ior=function ior(num){return assert(0==(this.negative|num.negative)),this.iuor(num)},BN.prototype.or=function or(num){return this.length>num.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;i<b.length;i++)this.words[i]&=num.words[i];return this.length=b.length,this._strip()},BN.prototype.iand=function iand(num){return assert(0==(this.negative|num.negative)),this.iuand(num)},BN.prototype.and=function and(num){return this.length>num.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;i<b.length;i++)this.words[i]=a.words[i]^b.words[i];if(this!==a)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=a.length,this._strip()},BN.prototype.ixor=function ixor(num){return assert(0==(this.negative|num.negative)),this.iuxor(num)},BN.prototype.xor=function xor(num){return this.length>num.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&0<=width);var bytesNeeded=0|_Mathceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),0<bitsLeft&&bytesNeeded--;for(var i=0;i<bytesNeeded;i++)this.words[i]=67108863&~this.words[i];return 0<bitsLeft&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&0<=bit);var off=0|bit/26,wbit=bit%26;return this._expand(off+1),val?this.words[off]|=1<<wbit:this.words[off]&=~(1<<wbit),this._strip()},BN.prototype.iadd=function iadd(num){var r;if(0!==this.negative&&0===num.negative)return this.negative=0,r=this.isub(num),this.negative^=1,this._normSign();if(0===this.negative&&0!==num.negative)return num.negative=0,r=this.isub(num),num.negative=1,r._normSign();var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])+(0|b.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,this.words[i]=67108863&r,carry=r>>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this},BN.prototype.add=function add(num){var res;return 0!==num.negative&&0===this.negative?(num.negative=0,res=this.sub(num),num.negative^=1,res):0===num.negative&&0!==this.negative?(this.negative=0,res=num.sub(this),this.negative=1,res):this.length>num.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;0<cmp?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i<b.length;i++)r=(0|a.words[i])-(0|b.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;for(;0!==carry&&i<a.length;i++)r=(0|a.words[i])+carry,carry=r>>26,this.words[i]=67108863&r;if(0===carry&&i<a.length&&a!==this)for(;i<a.length;i++)this.words[i]=a.words[i];return this.length=_Mathmax(this.length,i),a!==this&&(this.negative=1),this._strip()},BN.prototype.sub=function sub(num){return this.clone().isub(num)};var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words,b=num.words,o=out.words,c=0,a0=0|a[0],al0=8191&a0,ah0=a0>>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13,lo,mid,hi;out.negative=self.negative^num.negative,out.length=19,lo=_Mathimul(al0,bl0),mid=_Mathimul(al0,bh0),mid=0|mid+_Mathimul(ah0,bl0),hi=_Mathimul(ah0,bh0);var w0=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w0>>>26),w0&=67108863,lo=_Mathimul(al1,bl0),mid=_Mathimul(al1,bh0),mid=0|mid+_Mathimul(ah1,bl0),hi=_Mathimul(ah1,bh0),lo=0|lo+_Mathimul(al0,bl1),mid=0|mid+_Mathimul(al0,bh1),mid=0|mid+_Mathimul(ah0,bl1),hi=0|hi+_Mathimul(ah0,bh1);var w1=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w1>>>26),w1&=67108863,lo=_Mathimul(al2,bl0),mid=_Mathimul(al2,bh0),mid=0|mid+_Mathimul(ah2,bl0),hi=_Mathimul(ah2,bh0),lo=0|lo+_Mathimul(al1,bl1),mid=0|mid+_Mathimul(al1,bh1),mid=0|mid+_Mathimul(ah1,bl1),hi=0|hi+_Mathimul(ah1,bh1),lo=0|lo+_Mathimul(al0,bl2),mid=0|mid+_Mathimul(al0,bh2),mid=0|mid+_Mathimul(ah0,bl2),hi=0|hi+_Mathimul(ah0,bh2);var w2=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w2>>>26),w2&=67108863,lo=_Mathimul(al3,bl0),mid=_Mathimul(al3,bh0),mid=0|mid+_Mathimul(ah3,bl0),hi=_Mathimul(ah3,bh0),lo=0|lo+_Mathimul(al2,bl1),mid=0|mid+_Mathimul(al2,bh1),mid=0|mid+_Mathimul(ah2,bl1),hi=0|hi+_Mathimul(ah2,bh1),lo=0|lo+_Mathimul(al1,bl2),mid=0|mid+_Mathimul(al1,bh2),mid=0|mid+_Mathimul(ah1,bl2),hi=0|hi+_Mathimul(ah1,bh2),lo=0|lo+_Mathimul(al0,bl3),mid=0|mid+_Mathimul(al0,bh3),mid=0|mid+_Mathimul(ah0,bl3),hi=0|hi+_Mathimul(ah0,bh3);var w3=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w3>>>26),w3&=67108863,lo=_Mathimul(al4,bl0),mid=_Mathimul(al4,bh0),mid=0|mid+_Mathimul(ah4,bl0),hi=_Mathimul(ah4,bh0),lo=0|lo+_Mathimul(al3,bl1),mid=0|mid+_Mathimul(al3,bh1),mid=0|mid+_Mathimul(ah3,bl1),hi=0|hi+_Mathimul(ah3,bh1),lo=0|lo+_Mathimul(al2,bl2),mid=0|mid+_Mathimul(al2,bh2),mid=0|mid+_Mathimul(ah2,bl2),hi=0|hi+_Mathimul(ah2,bh2),lo=0|lo+_Mathimul(al1,bl3),mid=0|mid+_Mathimul(al1,bh3),mid=0|mid+_Mathimul(ah1,bl3),hi=0|hi+_Mathimul(ah1,bh3),lo=0|lo+_Mathimul(al0,bl4),mid=0|mid+_Mathimul(al0,bh4),mid=0|mid+_Mathimul(ah0,bl4),hi=0|hi+_Mathimul(ah0,bh4);var w4=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w4>>>26),w4&=67108863,lo=_Mathimul(al5,bl0),mid=_Mathimul(al5,bh0),mid=0|mid+_Mathimul(ah5,bl0),hi=_Mathimul(ah5,bh0),lo=0|lo+_Mathimul(al4,bl1),mid=0|mid+_Mathimul(al4,bh1),mid=0|mid+_Mathimul(ah4,bl1),hi=0|hi+_Mathimul(ah4,bh1),lo=0|lo+_Mathimul(al3,bl2),mid=0|mid+_Mathimul(al3,bh2),mid=0|mid+_Mathimul(ah3,bl2),hi=0|hi+_Mathimul(ah3,bh2),lo=0|lo+_Mathimul(al2,bl3),mid=0|mid+_Mathimul(al2,bh3),mid=0|mid+_Mathimul(ah2,bl3),hi=0|hi+_Mathimul(ah2,bh3),lo=0|lo+_Mathimul(al1,bl4),mid=0|mid+_Mathimul(al1,bh4),mid=0|mid+_Mathimul(ah1,bl4),hi=0|hi+_Mathimul(ah1,bh4),lo=0|lo+_Mathimul(al0,bl5),mid=0|mid+_Mathimul(al0,bh5),mid=0|mid+_Mathimul(ah0,bl5),hi=0|hi+_Mathimul(ah0,bh5);var w5=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w5>>>26),w5&=67108863,lo=_Mathimul(al6,bl0),mid=_Mathimul(al6,bh0),mid=0|mid+_Mathimul(ah6,bl0),hi=_Mathimul(ah6,bh0),lo=0|lo+_Mathimul(al5,bl1),mid=0|mid+_Mathimul(al5,bh1),mid=0|mid+_Mathimul(ah5,bl1),hi=0|hi+_Mathimul(ah5,bh1),lo=0|lo+_Mathimul(al4,bl2),mid=0|mid+_Mathimul(al4,bh2),mid=0|mid+_Mathimul(ah4,bl2),hi=0|hi+_Mathimul(ah4,bh2),lo=0|lo+_Mathimul(al3,bl3),mid=0|mid+_Mathimul(al3,bh3),mid=0|mid+_Mathimul(ah3,bl3),hi=0|hi+_Mathimul(ah3,bh3),lo=0|lo+_Mathimul(al2,bl4),mid=0|mid+_Mathimul(al2,bh4),mid=0|mid+_Mathimul(ah2,bl4),hi=0|hi+_Mathimul(ah2,bh4),lo=0|lo+_Mathimul(al1,bl5),mid=0|mid+_Mathimul(al1,bh5),mid=0|mid+_Mathimul(ah1,bl5),hi=0|hi+_Mathimul(ah1,bh5),lo=0|lo+_Mathimul(al0,bl6),mid=0|mid+_Mathimul(al0,bh6),mid=0|mid+_Mathimul(ah0,bl6),hi=0|hi+_Mathimul(ah0,bh6);var w6=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w6>>>26),w6&=67108863,lo=_Mathimul(al7,bl0),mid=_Mathimul(al7,bh0),mid=0|mid+_Mathimul(ah7,bl0),hi=_Mathimul(ah7,bh0),lo=0|lo+_Mathimul(al6,bl1),mid=0|mid+_Mathimul(al6,bh1),mid=0|mid+_Mathimul(ah6,bl1),hi=0|hi+_Mathimul(ah6,bh1),lo=0|lo+_Mathimul(al5,bl2),mid=0|mid+_Mathimul(al5,bh2),mid=0|mid+_Mathimul(ah5,bl2),hi=0|hi+_Mathimul(ah5,bh2),lo=0|lo+_Mathimul(al4,bl3),mid=0|mid+_Mathimul(al4,bh3),mid=0|mid+_Mathimul(ah4,bl3),hi=0|hi+_Mathimul(ah4,bh3),lo=0|lo+_Mathimul(al3,bl4),mid=0|mid+_Mathimul(al3,bh4),mid=0|mid+_Mathimul(ah3,bl4),hi=0|hi+_Mathimul(ah3,bh4),lo=0|lo+_Mathimul(al2,bl5),mid=0|mid+_Mathimul(al2,bh5),mid=0|mid+_Mathimul(ah2,bl5),hi=0|hi+_Mathimul(ah2,bh5),lo=0|lo+_Mathimul(al1,bl6),mid=0|mid+_Mathimul(al1,bh6),mid=0|mid+_Mathimul(ah1,bl6),hi=0|hi+_Mathimul(ah1,bh6),lo=0|lo+_Mathimul(al0,bl7),mid=0|mid+_Mathimul(al0,bh7),mid=0|mid+_Mathimul(ah0,bl7),hi=0|hi+_Mathimul(ah0,bh7);var w7=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w7>>>26),w7&=67108863,lo=_Mathimul(al8,bl0),mid=_Mathimul(al8,bh0),mid=0|mid+_Mathimul(ah8,bl0),hi=_Mathimul(ah8,bh0),lo=0|lo+_Mathimul(al7,bl1),mid=0|mid+_Mathimul(al7,bh1),mid=0|mid+_Mathimul(ah7,bl1),hi=0|hi+_Mathimul(ah7,bh1),lo=0|lo+_Mathimul(al6,bl2),mid=0|mid+_Mathimul(al6,bh2),mid=0|mid+_Mathimul(ah6,bl2),hi=0|hi+_Mathimul(ah6,bh2),lo=0|lo+_Mathimul(al5,bl3),mid=0|mid+_Mathimul(al5,bh3),mid=0|mid+_Mathimul(ah5,bl3),hi=0|hi+_Mathimul(ah5,bh3),lo=0|lo+_Mathimul(al4,bl4),mid=0|mid+_Mathimul(al4,bh4),mid=0|mid+_Mathimul(ah4,bl4),hi=0|hi+_Mathimul(ah4,bh4),lo=0|lo+_Mathimul(al3,bl5),mid=0|mid+_Mathimul(al3,bh5),mid=0|mid+_Mathimul(ah3,bl5),hi=0|hi+_Mathimul(ah3,bh5),lo=0|lo+_Mathimul(al2,bl6),mid=0|mid+_Mathimul(al2,bh6),mid=0|mid+_Mathimul(ah2,bl6),hi=0|hi+_Mathimul(ah2,bh6),lo=0|lo+_Mathimul(al1,bl7),mid=0|mid+_Mathimul(al1,bh7),mid=0|mid+_Mathimul(ah1,bl7),hi=0|hi+_Mathimul(ah1,bh7),lo=0|lo+_Mathimul(al0,bl8),mid=0|mid+_Mathimul(al0,bh8),mid=0|mid+_Mathimul(ah0,bl8),hi=0|hi+_Mathimul(ah0,bh8);var w8=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w8>>>26),w8&=67108863,lo=_Mathimul(al9,bl0),mid=_Mathimul(al9,bh0),mid=0|mid+_Mathimul(ah9,bl0),hi=_Mathimul(ah9,bh0),lo=0|lo+_Mathimul(al8,bl1),mid=0|mid+_Mathimul(al8,bh1),mid=0|mid+_Mathimul(ah8,bl1),hi=0|hi+_Mathimul(ah8,bh1),lo=0|lo+_Mathimul(al7,bl2),mid=0|mid+_Mathimul(al7,bh2),mid=0|mid+_Mathimul(ah7,bl2),hi=0|hi+_Mathimul(ah7,bh2),lo=0|lo+_Mathimul(al6,bl3),mid=0|mid+_Mathimul(al6,bh3),mid=0|mid+_Mathimul(ah6,bl3),hi=0|hi+_Mathimul(ah6,bh3),lo=0|lo+_Mathimul(al5,bl4),mid=0|mid+_Mathimul(al5,bh4),mid=0|mid+_Mathimul(ah5,bl4),hi=0|hi+_Mathimul(ah5,bh4),lo=0|lo+_Mathimul(al4,bl5),mid=0|mid+_Mathimul(al4,bh5),mid=0|mid+_Mathimul(ah4,bl5),hi=0|hi+_Mathimul(ah4,bh5),lo=0|lo+_Mathimul(al3,bl6),mid=0|mid+_Mathimul(al3,bh6),mid=0|mid+_Mathimul(ah3,bl6),hi=0|hi+_Mathimul(ah3,bh6),lo=0|lo+_Mathimul(al2,bl7),mid=0|mid+_Mathimul(al2,bh7),mid=0|mid+_Mathimul(ah2,bl7),hi=0|hi+_Mathimul(ah2,bh7),lo=0|lo+_Mathimul(al1,bl8),mid=0|mid+_Mathimul(al1,bh8),mid=0|mid+_Mathimul(ah1,bl8),hi=0|hi+_Mathimul(ah1,bh8),lo=0|lo+_Mathimul(al0,bl9),mid=0|mid+_Mathimul(al0,bh9),mid=0|mid+_Mathimul(ah0,bl9),hi=0|hi+_Mathimul(ah0,bh9);var w9=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w9>>>26),w9&=67108863,lo=_Mathimul(al9,bl1),mid=_Mathimul(al9,bh1),mid=0|mid+_Mathimul(ah9,bl1),hi=_Mathimul(ah9,bh1),lo=0|lo+_Mathimul(al8,bl2),mid=0|mid+_Mathimul(al8,bh2),mid=0|mid+_Mathimul(ah8,bl2),hi=0|hi+_Mathimul(ah8,bh2),lo=0|lo+_Mathimul(al7,bl3),mid=0|mid+_Mathimul(al7,bh3),mid=0|mid+_Mathimul(ah7,bl3),hi=0|hi+_Mathimul(ah7,bh3),lo=0|lo+_Mathimul(al6,bl4),mid=0|mid+_Mathimul(al6,bh4),mid=0|mid+_Mathimul(ah6,bl4),hi=0|hi+_Mathimul(ah6,bh4),lo=0|lo+_Mathimul(al5,bl5),mid=0|mid+_Mathimul(al5,bh5),mid=0|mid+_Mathimul(ah5,bl5),hi=0|hi+_Mathimul(ah5,bh5),lo=0|lo+_Mathimul(al4,bl6),mid=0|mid+_Mathimul(al4,bh6),mid=0|mid+_Mathimul(ah4,bl6),hi=0|hi+_Mathimul(ah4,bh6),lo=0|lo+_Mathimul(al3,bl7),mid=0|mid+_Mathimul(al3,bh7),mid=0|mid+_Mathimul(ah3,bl7),hi=0|hi+_Mathimul(ah3,bh7),lo=0|lo+_Mathimul(al2,bl8),mid=0|mid+_Mathimul(al2,bh8),mid=0|mid+_Mathimul(ah2,bl8),hi=0|hi+_Mathimul(ah2,bh8),lo=0|lo+_Mathimul(al1,bl9),mid=0|mid+_Mathimul(al1,bh9),mid=0|mid+_Mathimul(ah1,bl9),hi=0|hi+_Mathimul(ah1,bh9);var w10=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w10>>>26),w10&=67108863,lo=_Mathimul(al9,bl2),mid=_Mathimul(al9,bh2),mid=0|mid+_Mathimul(ah9,bl2),hi=_Mathimul(ah9,bh2),lo=0|lo+_Mathimul(al8,bl3),mid=0|mid+_Mathimul(al8,bh3),mid=0|mid+_Mathimul(ah8,bl3),hi=0|hi+_Mathimul(ah8,bh3),lo=0|lo+_Mathimul(al7,bl4),mid=0|mid+_Mathimul(al7,bh4),mid=0|mid+_Mathimul(ah7,bl4),hi=0|hi+_Mathimul(ah7,bh4),lo=0|lo+_Mathimul(al6,bl5),mid=0|mid+_Mathimul(al6,bh5),mid=0|mid+_Mathimul(ah6,bl5),hi=0|hi+_Mathimul(ah6,bh5),lo=0|lo+_Mathimul(al5,bl6),mid=0|mid+_Mathimul(al5,bh6),mid=0|mid+_Mathimul(ah5,bl6),hi=0|hi+_Mathimul(ah5,bh6),lo=0|lo+_Mathimul(al4,bl7),mid=0|mid+_Mathimul(al4,bh7),mid=0|mid+_Mathimul(ah4,bl7),hi=0|hi+_Mathimul(ah4,bh7),lo=0|lo+_Mathimul(al3,bl8),mid=0|mid+_Mathimul(al3,bh8),mid=0|mid+_Mathimul(ah3,bl8),hi=0|hi+_Mathimul(ah3,bh8),lo=0|lo+_Mathimul(al2,bl9),mid=0|mid+_Mathimul(al2,bh9),mid=0|mid+_Mathimul(ah2,bl9),hi=0|hi+_Mathimul(ah2,bh9);var w11=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w11>>>26),w11&=67108863,lo=_Mathimul(al9,bl3),mid=_Mathimul(al9,bh3),mid=0|mid+_Mathimul(ah9,bl3),hi=_Mathimul(ah9,bh3),lo=0|lo+_Mathimul(al8,bl4),mid=0|mid+_Mathimul(al8,bh4),mid=0|mid+_Mathimul(ah8,bl4),hi=0|hi+_Mathimul(ah8,bh4),lo=0|lo+_Mathimul(al7,bl5),mid=0|mid+_Mathimul(al7,bh5),mid=0|mid+_Mathimul(ah7,bl5),hi=0|hi+_Mathimul(ah7,bh5),lo=0|lo+_Mathimul(al6,bl6),mid=0|mid+_Mathimul(al6,bh6),mid=0|mid+_Mathimul(ah6,bl6),hi=0|hi+_Mathimul(ah6,bh6),lo=0|lo+_Mathimul(al5,bl7),mid=0|mid+_Mathimul(al5,bh7),mid=0|mid+_Mathimul(ah5,bl7),hi=0|hi+_Mathimul(ah5,bh7),lo=0|lo+_Mathimul(al4,bl8),mid=0|mid+_Mathimul(al4,bh8),mid=0|mid+_Mathimul(ah4,bl8),hi=0|hi+_Mathimul(ah4,bh8),lo=0|lo+_Mathimul(al3,bl9),mid=0|mid+_Mathimul(al3,bh9),mid=0|mid+_Mathimul(ah3,bl9),hi=0|hi+_Mathimul(ah3,bh9);var w12=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w12>>>26),w12&=67108863,lo=_Mathimul(al9,bl4),mid=_Mathimul(al9,bh4),mid=0|mid+_Mathimul(ah9,bl4),hi=_Mathimul(ah9,bh4),lo=0|lo+_Mathimul(al8,bl5),mid=0|mid+_Mathimul(al8,bh5),mid=0|mid+_Mathimul(ah8,bl5),hi=0|hi+_Mathimul(ah8,bh5),lo=0|lo+_Mathimul(al7,bl6),mid=0|mid+_Mathimul(al7,bh6),mid=0|mid+_Mathimul(ah7,bl6),hi=0|hi+_Mathimul(ah7,bh6),lo=0|lo+_Mathimul(al6,bl7),mid=0|mid+_Mathimul(al6,bh7),mid=0|mid+_Mathimul(ah6,bl7),hi=0|hi+_Mathimul(ah6,bh7),lo=0|lo+_Mathimul(al5,bl8),mid=0|mid+_Mathimul(al5,bh8),mid=0|mid+_Mathimul(ah5,bl8),hi=0|hi+_Mathimul(ah5,bh8),lo=0|lo+_Mathimul(al4,bl9),mid=0|mid+_Mathimul(al4,bh9),mid=0|mid+_Mathimul(ah4,bl9),hi=0|hi+_Mathimul(ah4,bh9);var w13=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w13>>>26),w13&=67108863,lo=_Mathimul(al9,bl5),mid=_Mathimul(al9,bh5),mid=0|mid+_Mathimul(ah9,bl5),hi=_Mathimul(ah9,bh5),lo=0|lo+_Mathimul(al8,bl6),mid=0|mid+_Mathimul(al8,bh6),mid=0|mid+_Mathimul(ah8,bl6),hi=0|hi+_Mathimul(ah8,bh6),lo=0|lo+_Mathimul(al7,bl7),mid=0|mid+_Mathimul(al7,bh7),mid=0|mid+_Mathimul(ah7,bl7),hi=0|hi+_Mathimul(ah7,bh7),lo=0|lo+_Mathimul(al6,bl8),mid=0|mid+_Mathimul(al6,bh8),mid=0|mid+_Mathimul(ah6,bl8),hi=0|hi+_Mathimul(ah6,bh8),lo=0|lo+_Mathimul(al5,bl9),mid=0|mid+_Mathimul(al5,bh9),mid=0|mid+_Mathimul(ah5,bl9),hi=0|hi+_Mathimul(ah5,bh9);var w14=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w14>>>26),w14&=67108863,lo=_Mathimul(al9,bl6),mid=_Mathimul(al9,bh6),mid=0|mid+_Mathimul(ah9,bl6),hi=_Mathimul(ah9,bh6),lo=0|lo+_Mathimul(al8,bl7),mid=0|mid+_Mathimul(al8,bh7),mid=0|mid+_Mathimul(ah8,bl7),hi=0|hi+_Mathimul(ah8,bh7),lo=0|lo+_Mathimul(al7,bl8),mid=0|mid+_Mathimul(al7,bh8),mid=0|mid+_Mathimul(ah7,bl8),hi=0|hi+_Mathimul(ah7,bh8),lo=0|lo+_Mathimul(al6,bl9),mid=0|mid+_Mathimul(al6,bh9),mid=0|mid+_Mathimul(ah6,bl9),hi=0|hi+_Mathimul(ah6,bh9);var w15=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w15>>>26),w15&=67108863,lo=_Mathimul(al9,bl7),mid=_Mathimul(al9,bh7),mid=0|mid+_Mathimul(ah9,bl7),hi=_Mathimul(ah9,bh7),lo=0|lo+_Mathimul(al8,bl8),mid=0|mid+_Mathimul(al8,bh8),mid=0|mid+_Mathimul(ah8,bl8),hi=0|hi+_Mathimul(ah8,bh8),lo=0|lo+_Mathimul(al7,bl9),mid=0|mid+_Mathimul(al7,bh9),mid=0|mid+_Mathimul(ah7,bl9),hi=0|hi+_Mathimul(ah7,bh9);var w16=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w16>>>26),w16&=67108863,lo=_Mathimul(al9,bl8),mid=_Mathimul(al9,bh8),mid=0|mid+_Mathimul(ah9,bl8),hi=_Mathimul(ah9,bh8),lo=0|lo+_Mathimul(al8,bl9),mid=0|mid+_Mathimul(al8,bh9),mid=0|mid+_Mathimul(ah8,bl9),hi=0|hi+_Mathimul(ah8,bh9);var w17=0|(0|c+lo)+((8191&mid)<<13);c=0|(0|hi+(mid>>>13))+(w17>>>26),w17&=67108863,lo=_Mathimul(al9,bl9),mid=_Mathimul(al9,bh9),mid=0|mid+_Mathimul(ah9,bl9),hi=_Mathimul(ah9,bh9);var w18=0|(0|c+lo)+((8191&mid)<<13);return c=0|(0|hi+(mid>>>13))+(w18>>>26),w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};_Mathimul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length,res;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):63>len?smallMulTo(this,num,out):1024>len?bigMulTo(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=Array(N),l=BN.prototype._countBits(N)-1,i=0;i<N;i++)t[i]=this.revBin(i,l,N);return t},FFTM.prototype.revBin=function revBin(x,l,N){if(0===x||x===N-1)return x;for(var rb=0,i=0;i<l;i++)rb|=(1&x)<<l-i-1,x>>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i<N;i++)rtws[i]=rws[rbt[i]],itws[i]=iws[rbt[i]]},FFTM.prototype.transform=function transform(rws,iws,rtws,itws,N,rbt){this.permute(rbt,rws,iws,rtws,itws,N);for(var s=1;s<N;s<<=1)for(var l=s<<1,rtwdf=_Mathcos(2*_MathPI/l),itwdf=_Mathsin(2*_MathPI/l),p=0;p<N;p+=l)for(var rtwdf_=rtwdf,itwdf_=itwdf,j=0;j<s;j++){var re=rtws[p+j],ie=itws[p+j],ro=rtws[p+j+s],io=itws[p+j+s],rx=rtwdf_*ro-itwdf_*io;io=rtwdf_*io+itwdf_*ro,ro=rx,rtws[p+j]=re+ro,itws[p+j]=ie+io,rtws[p+j+s]=re-ro,itws[p+j+s]=ie-io,j!==l&&(rx=rtwdf*rtwdf_-itwdf*itwdf_,itwdf_=rtwdf*itwdf_+itwdf*rtwdf_,rtwdf_=rx)}},FFTM.prototype.guessLen13b=function guessLen13b(n,m){var N=1|_Mathmax(m,n),odd=1&N,i=0;for(N=0|N/2;N;N>>>=1)i++;return 1<<i+1+odd},FFTM.prototype.conjugate=function conjugate(rws,iws,N){if(!(1>=N))for(var i=0,t;i<N/2;i++)t=rws[i],rws[i]=rws[N-i-1],rws[N-i-1]=t,t=iws[i],iws[i]=-iws[N-i-1],iws[N-i-1]=-t},FFTM.prototype.normalize13b=function normalize13b(ws,N){for(var carry=0,i=0,w;i<N/2;i++)w=8192*_Mathround(ws[2*i+1]/N)+_Mathround(ws[2*i]/N)+carry,ws[i]=67108863&w,carry=67108864>w?0:0|w/67108864;return ws},FFTM.prototype.convert13b=function convert13b(ws,len,rws,N){for(var carry=0,i=0;i<len;i++)carry+=0|ws[i],rws[2*i]=8191&carry,carry>>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i<N;++i)rws[i]=0;assert(0===carry),assert(0==(-8192&carry))},FFTM.prototype.stub=function stub(N){for(var ph=Array(N),i=0;i<N;i++)ph[i]=0;return ph},FFTM.prototype.mulp=function mulp(x,y,out){var N=2*this.guessLen13b(x.length,y.length),rbt=this.makeRBT(N),_=this.stub(N),rws=Array(N),rwst=Array(N),iwst=Array(N),nrws=Array(N),nrwst=Array(N),niwst=Array(N),rmws=out.words;rmws.length=N,this.convert13b(x.words,x.length,rws,N),this.convert13b(y.words,y.length,nrws,N),this.transform(rws,_,rwst,iwst,N,rbt),this.transform(nrws,_,nrwst,niwst,N,rbt);for(var i=0,rx;i<N;i++)rx=rwst[i]*nrwst[i]-iwst[i]*niwst[i],iwst[i]=rwst[i]*niwst[i]+iwst[i]*nrwst[i],rwst[i]=rx;return this.conjugate(rwst,iwst,N),this.transform(rwst,iwst,rmws,_,N,rbt),this.conjugate(rmws,_,N),this.normalize13b(rmws,N),out.negative=x.negative^y.negative,out.length=x.length+y.length,out._strip()},BN.prototype.mul=function mul(num){var out=new BN(null);return out.words=Array(this.length+num.length),this.mulTo(num,out)},BN.prototype.mulf=function mulf(num){var out=new BN(null);return out.words=Array(this.length+num.length),jumboMulTo(this,num,out)},BN.prototype.imul=function imul(num){return this.clone().mulTo(num,this)},BN.prototype.imuln=function imuln(num){var isNegNum=0>num;isNegNum&&(num=-num),assert("number"==typeof num),assert(67108864>num);for(var carry=0,i=0;i<this.length;i++){var w=(0|this.words[i])*num,lo=(67108863&w)+(67108863&carry);carry>>=26,carry+=0|w/67108864,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i<w.length&&0===w[i];i++,res=res.sqr());if(++i<w.length)for(var q=res.sqr();i<w.length;i++,q=q.sqr())0!==w[i]&&(res=res.mul(q));return res},BN.prototype.iushln=function iushln(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(0!=r){var carry=0;for(i=0;i<this.length;i++){var newCarry=this.words[i]&carryMask,c=(0|this.words[i])-newCarry<<r;this.words[i]=c|carry,carry=newCarry>>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;0<=i;i--)this.words[i+s]=this.words[i];for(i=0;i<s;i++)this.words[i]=0;this.length+=s}return this._strip()},BN.prototype.ishln=function ishln(bits){return assert(0===this.negative),this.iushln(bits)},BN.prototype.iushrn=function iushrn(bits,hint,extended){assert("number"==typeof bits&&0<=bits);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=_Mathmin((bits-r)/26,this.length),mask=67108863^67108863>>>r<<r,maskedWords=extended;if(h-=s,h=_Mathmax(0,h),maskedWords){for(var i=0;i<s;i++)maskedWords.words[i]=this.words[i];maskedWords.length=s}if(0===s);else if(this.length>s)for(this.length-=s,i=0;i<this.length;i++)this.words[i]=this.words[i+s];else this.words[0]=0,this.length=1;var carry=0;for(i=this.length-1;0<=i&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&0<=bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return!1;var w=this.words[s];return!!(w&q)},BN.prototype.imaskn=function imaskn(bits){assert("number"==typeof bits&&0<=bits);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!=r&&s++,this.length=_Mathmin(s,this.length),0!=r){var mask=67108863^67108863>>>r<<r;this.words[this.length-1]&=mask}return this._strip()},BN.prototype.maskn=function maskn(bits){return this.clone().imaskn(bits)},BN.prototype.iaddn=function iaddn(num){return assert("number"==typeof num),assert(67108864>num),0>num?this.isubn(-num):0===this.negative?this._iaddn(num):1===this.length&&(0|this.words[0])<=num?(this.words[0]=num-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(num),this.negative=1,this)},BN.prototype._iaddn=function _iaddn(num){this.words[0]+=num;for(var i=0;i<this.length&&67108864<=this.words[i];i++)this.words[i]-=67108864,i==this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=_Mathmax(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(67108864>num),0>num)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&0>this.words[0])this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i<this.length&&0>this.words[i];i++)this.words[i]+=67108864,this.words[i+1]-=1;return this._strip()},BN.prototype.addn=function addn(num){return this.clone().iaddn(num)},BN.prototype.subn=function subn(num){return this.clone().isubn(num)},BN.prototype.iabs=function iabs(){return this.negative=0,this},BN.prototype.abs=function abs(){return this.clone().iabs()},BN.prototype._ishlnsubmul=function _ishlnsubmul(num,mul,shift){var len=num.length+shift,i;this._expand(len);var carry=0,w;for(i=0;i<num.length;i++){w=(0|this.words[i+shift])+carry;var right=(0|num.words[i])*mul;w-=67108863&right,carry=(w>>26)-(0|right/67108864),this.words[i+shift]=67108863&w}for(;i<this.length-shift;i++)w=(0|this.words[i+shift])+carry,carry=w>>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i<this.length;i++)w=-(0|this.words[i])+carry,carry=w>>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!=shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var m=a.length-b.length,q;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=Array(q.length);for(var i=0;i<q.length;i++)q.words[i]=0}var diff=a.clone()._ishlnsubmul(b,1,m);0===diff.negative&&(a=diff,q&&(q.words[m]=1));for(var j=m-1,qj;0<=j;j--){for(qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]),qj=_Mathmin(0|qj/bhi,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0==(this.negative&num.negative)?num.length>this.length||0>this.cmp(num)?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode):(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod})},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0===dm.div.negative?dm.mod:dm.mod.isub(num),half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return 0>cmp||1===r2&&0===cmp?dm.div:0===dm.div.negative?dm.div.iaddn(1):dm.div.isubn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var p=67108864%num,acc=0,i=this.length-1;0<=i;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=0>num;isNegNum&&(num=-num),assert(67108863>=num);for(var carry=0,i=this.length-1,w;0<=i;i--)w=(0|this.words[i])+67108864*carry,this.words[i]=0|w/num,carry=w%num;return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0===x.negative?x.clone():x.umod(p);for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(x.iushrn(i);0<i--;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(y.iushrn(j);0<j--;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);0<=x.cmp(y)?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0===a.negative?a.clone():a.umod(p);for(var x1=new BN(1),x2=new BN(0),delta=b.clone();0<a.cmpn(1)&&0<b.cmpn(1);){for(var i=0,im=1;0==(a.words[0]&im)&&26>i;++i,im<<=1);if(0<i)for(a.iushrn(i);0<i--;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&26>j;++j,jm<<=1);if(0<j)for(b.iushrn(j);0<j--;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);0<=a.cmp(b)?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,0>res.cmpn(0)&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(0>r){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<<r;if(this.length<=s)return this._expand(s+1),this.words[s]|=q,this;for(var carry=q,i=s,w;0!==carry&&i<this.length;i++)w=0|this.words[i],w+=carry,carry=w>>>26,w&=67108863,this.words[i]=w;return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var negative=0>num;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this._strip();var res;if(1<this.length)res=1;else{negative&&(num=-num),assert(67108863>=num,"Number is too big");var w=0|this.words[0];res=w===num?0:w<num?-1:1}return 0===this.negative?res:0|-res},BN.prototype.cmp=function cmp(num){if(0!==this.negative&&0===num.negative)return-1;if(0===this.negative&&0!==num.negative)return 1;var res=this.ucmp(num);return 0===this.negative?res:0|-res},BN.prototype.ucmp=function ucmp(num){if(this.length>num.length)return 1;if(this.length<num.length)return-1;for(var res=0,i=this.length-1;0<=i;i--){var a=0|this.words[i],b=0|num.words[i];if(a!=b){a<b?res=-1:a>b&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return 0<=this.cmpn(num)},BN.prototype.gte=function gte(num){return 0<=this.cmp(num)},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return 0>=this.cmpn(num)},BN.prototype.lte=function lte(num){return 0>=this.cmp(num)},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=Array(_Mathceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen<this.n?-1:r.ucmp(this.p);return 0===cmp?(r.words[0]=0,r.length=1):0<cmp?r.isub(this.p):void 0===r.strip?r._strip():r.strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var mask=4194303,outLen=_Mathmin(input.length,9),i=0;i<outLen;i++)output.words[i]=input.words[i];if(output.length=outLen,9>=input.length)return input.words[0]=0,void(input.length=1);var prev=input.words[9];for(output.words[output.length++]=prev&mask,i=10;i<input.length;i++){var next=0|input.words[i];input.words[i-10]=(next&mask)<<4|prev>>>22,prev=next}prev>>>=22,input.words[i-10]=prev,input.length-=0===prev&&10<input.length?10:9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0,w;i<num.length;i++)w=0|num.words[i],lo+=977*w,num.words[i]=67108863&lo,lo=64*w+(0|lo/67108864);return 0===num.words[num.length-1]&&(num.length--,0===num.words[num.length-1]&&num.length--),num},inherits(P224,MPrime),inherits(P192,MPrime),inherits(P25519,MPrime),P25519.prototype.imulK=function imulK(num){for(var carry=0,i=0;i<num.length;i++){var hi=19*(0|num.words[i])+carry,lo=67108863&hi;hi>>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else if("p25519"===name)prime=new P25519;else throw new Error("Unknown prime "+name);return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return 0<=res.cmp(this.m)&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return 0>res.cmpn(0)&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(1==mod3%2),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i<m);var b=this.pow(c,new BN(1).iushln(m-i-1));r=r.redMul(b),c=b.redSqr(),t=t.redMul(c),m=i}return r},Red.prototype.invm=function invm(a){var inv=a._invmp(this.m);return 0===inv.negative?this.imod(inv):(inv.negative=0,this.imod(inv).redNeg())},Red.prototype.pow=function pow(a,num){if(num.isZero())return new BN(1).toRed(this);if(0===num.cmpn(1))return a.clone();var windowSize=4,wnd=Array(16);wnd[0]=new BN(1).toRed(this),wnd[1]=a;for(var i=2;i<wnd.length;i++)wnd[i]=this.mul(wnd[i-1],a);var res=wnd[0],current=0,currentLen=0,start=num.bitLength()%26;for(0===start&&(start=26),i=num.length-1;0<=i;i--){for(var word=num.words[i],j=start-1,bit;0<=j;j--){if(bit=1&word>>j,res!==wnd[0]&&(res=this.sqr(res)),0===bit&&0===current){currentLen=0;continue}current<<=1,current|=bit,currentLen++,(4===currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return 0<=u.cmp(this.m)?res=u.isub(this.m):0>u.cmpn(0)&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})("undefined"==typeof module||module,this)},{buffer:41}],40:[function(require,module,exports){function Rand(rand){this.rand=rand}var r;if(module.exports=function rand(len){return r||(r=new Rand(null)),r.generate(len)},module.exports.Rand=Rand,Rand.prototype.generate=function generate(len){return this._rand(len)},Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);for(var res=new Uint8Array(n),i=0;i<res.length;i++)res[i]=this.rand.getByte();return res},"object"==typeof self)self.crypto&&self.crypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.crypto.getRandomValues(arr),arr}:self.msCrypto&&self.msCrypto.getRandomValues?Rand.prototype._rand=function _rand(n){var arr=new Uint8Array(n);return self.msCrypto.getRandomValues(arr),arr}:"object"==typeof window&&(Rand.prototype._rand=function(){throw new Error("Not implemented yet")});else try{var crypto=require("crypto");if("function"!=typeof crypto.randomBytes)throw new Error("Not supported");Rand.prototype._rand=function _rand(n){return crypto.randomBytes(n)}}catch(e){}},{crypto:41}],41:[function(require,module,exports){},{}],42:[function(require,module,exports){function asUInt32Array(buf){Buffer.isBuffer(buf)||(buf=Buffer.from(buf));for(var len=0|buf.length/4,out=Array(len),i=0;i<len;i++)out[i]=buf.readUInt32BE(4*i);return out}function scrubVec(v){for(var i=0;i<v.length;v++)v[i]=0}function cryptBlock(M,keySchedule,SUB_MIX,SBOX,nRounds){for(var SUB_MIX0=SUB_MIX[0],SUB_MIX1=SUB_MIX[1],SUB_MIX2=SUB_MIX[2],SUB_MIX3=SUB_MIX[3],s0=M[0]^keySchedule[0],s1=M[1]^keySchedule[1],s2=M[2]^keySchedule[2],s3=M[3]^keySchedule[3],ksRow=4,round=1,t0,t1,t2,t3;round<nRounds;round++)t0=SUB_MIX0[s0>>>24]^SUB_MIX1[255&s1>>>16]^SUB_MIX2[255&s2>>>8]^SUB_MIX3[255&s3]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[255&s2>>>16]^SUB_MIX2[255&s3>>>8]^SUB_MIX3[255&s0]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[255&s3>>>16]^SUB_MIX2[255&s0>>>8]^SUB_MIX3[255&s1]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[255&s0>>>16]^SUB_MIX2[255&s1>>>8]^SUB_MIX3[255&s2]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[255&s1>>>16]<<16|SBOX[255&s2>>>8]<<8|SBOX[255&s3])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[255&s2>>>16]<<16|SBOX[255&s3>>>8]<<8|SBOX[255&s0])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[255&s3>>>16]<<16|SBOX[255&s0>>>8]<<8|SBOX[255&s1])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[255&s0>>>16]<<16|SBOX[255&s1>>>8]<<8|SBOX[255&s2])^keySchedule[ksRow++],t0>>>=0,t1>>>=0,t2>>>=0,t3>>>=0,[t0,t1,t2,t3]}function AES(key){this._key=asUInt32Array(key),this._reset()}var Buffer=require("safe-buffer").Buffer,RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=Array(256),j=0;256>j;j++)d[j]=128>j?j<<1:283^j<<1;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0,sx;256>i;++i){sx=xi^xi<<1^xi<<2^xi<<3^xi<<4,sx=99^(sx>>>8^255&sx),SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,0===x?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX:SBOX,INV_SBOX:INV_SBOX,SUB_MIX:SUB_MIX,INV_SUB_MIX:INV_SUB_MIX}}();AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=4*(nRounds+1),keySchedule=[],k=0;k<keySize;k++)keySchedule[k]=keyWords[k];for(k=keySize;k<ksRows;k++){var t=keySchedule[k-1];0==k%keySize?(t=t<<8|t>>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t],t^=RCON[0|k/keySize]<<24):6<keySize&&4==k%keySize&&(t=G.SBOX[t>>>24]<<24|G.SBOX[255&t>>>16]<<16|G.SBOX[255&t>>>8]<<8|G.SBOX[255&t]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik<ksRows;ik++){var ksR=ksRows-ik,tt=keySchedule[ksR-(ik%4?0:4)];invKeySchedule[ik]=4>ik||4>=ksR?tt:G.INV_SUB_MIX[0][G.SBOX[tt>>>24]]^G.INV_SUB_MIX[1][G.SBOX[255&tt>>>16]]^G.INV_SUB_MIX[2][G.SBOX[255&tt>>>8]]^G.INV_SUB_MIX[3][G.SBOX[255&tt]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES},{"safe-buffer":234}],43:[function(require,module,exports){function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=_Mathmin(a.length,b.length),i=0;i<len;++i)out+=a[i]^b[i];return out}function calcIv(self,iv,ck){if(12===iv.length)return self._finID=Buffer.concat([iv,Buffer.from([0,0,0,1])]),Buffer.concat([iv,Buffer.from([0,0,0,2])]);var ghash=new GHASH(ck),len=iv.length,toPad=len%16;ghash.update(iv),toPad&&(toPad=16-toPad,ghash.update(Buffer.alloc(toPad,0))),ghash.update(Buffer.alloc(8,0));var ivBits=8*len,tail=Buffer.alloc(8);tail.writeUIntBE(ivBits,0,8),ghash.update(tail),self._finID=ghash.state;var out=Buffer.from(self._finID);return incr32(out),out}function StreamCipher(mode,key,iv,decrypt){Transform.call(this);var h=Buffer.alloc(4,0);this._cipher=new aes.AES(key);var ck=this._cipher.encryptBlock(h);this._ghash=new GHASH(ck),iv=calcIv(this,iv,ck),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._alen=0,this._len=0,this._mode=mode,this._authTag=null,this._called=!1}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits"),GHASH=require("./ghash"),xor=require("buffer-xor"),incr32=require("./incr32");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;16>rump&&(rump=Buffer.alloc(rump,0),this._ghash.update(rump))}this._called=!0;var out=this._mode.encrypt(this,chunk);return this._decrypt?this._ghash.update(chunk):this._ghash.update(out),this._len+=chunk.length,out},StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var tag=xor(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&xorTest(tag,this._authTag))throw new Error("Unsupported state or unable to authenticate data");this._authTag=tag,this._cipher.scrub()},StreamCipher.prototype.getAuthTag=function getAuthTag(){if(this._decrypt||!Buffer.isBuffer(this._authTag))throw new Error("Attempting to get auth tag in unsupported state");return this._authTag},StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(!this._decrypt)throw new Error("Attempting to set auth tag in unsupported state");this._authTag=tag},StreamCipher.prototype.setAAD=function setAAD(buf){if(this._called)throw new Error("Attempting to set AAD in unsupported state");this._ghash.update(buf),this._alen+=buf.length},module.exports=StreamCipher},{"./aes":42,"./ghash":47,"./incr32":48,"buffer-xor":74,"cipher-base":79,inherits:145,"safe-buffer":234}],44:[function(require,module,exports){function getCiphers(){return Object.keys(modes)}var ciphers=require("./encrypter"),deciphers=require("./decrypter"),modes=require("./modes/list.json");exports.createCipher=exports.Cipher=ciphers.createCipher,exports.createCipheriv=exports.Cipheriv=ciphers.createCipheriv,exports.createDecipher=exports.Decipher=deciphers.createDecipher,exports.createDecipheriv=exports.Decipheriv=deciphers.createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"./decrypter":45,"./encrypter":46,"./modes/list.json":56}],45:[function(require,module,exports){function Decipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function unpad(last){var padded=last[15];if(1>padded||16<padded)throw new Error("unable to decrypt data");for(var i=-1;++i<padded;)if(last[i+(16-padded)]!==padded)throw new Error("unable to decrypt data");return 16===padded?void 0:last.slice(0,16-padded)}function createDecipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);return"stream"===config.type?new StreamCipher(config.module,password,iv,!0):"auth"===config.type?new AuthCipher(config.module,password,iv,!0):new Decipher(config.module,password,iv)}function createDecipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createDecipheriv(suite,keys.key,keys.iv)}var AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,MODES=require("./modes"),StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Decipher,Transform),Decipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get(this._autopadding);)thing=this._mode.decrypt(this,chunk),out.push(thing);return Buffer.concat(out)},Decipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return unpad(this._mode.decrypt(this,chunk));if(chunk)throw new Error("data not multiple of block length")},Decipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(autoPadding){var out;if(autoPadding){if(16<this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;}else if(16<=this.cache.length)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache},exports.createDecipher=createDecipher,exports.createDecipheriv=createDecipheriv},{"./aes":42,"./authCipher":43,"./modes":55,"./streamCipher":58,"cipher-base":79,evp_bytestokey:123,inherits:145,"safe-buffer":234}],46:[function(require,module,exports){function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function createCipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);return"stream"===config.type?new StreamCipher(config.module,password,iv):"auth"===config.type?new AuthCipher(config.module,password,iv):new Cipher(config.module,password,iv)}function createCipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createCipheriv(suite,keys.key,keys.iv)}var MODES=require("./modes"),AuthCipher=require("./authCipher"),Buffer=require("safe-buffer").Buffer,StreamCipher=require("./streamCipher"),Transform=require("cipher-base"),aes=require("./aes"),ebtk=require("evp_bytestokey"),inherits=require("inherits");inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var out=[],chunk,thing;chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer.concat(out)};var PADDING=Buffer.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error("data not multiple of block length")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(){if(15<this.cache.length){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer.allocUnsafe(len),i=-1;++i<len;)padBuff.writeUInt8(len,i);return Buffer.concat([this.cache,padBuff])},exports.createCipheriv=createCipheriv,exports.createCipher=createCipher},{"./aes":42,"./authCipher":43,"./modes":55,"./streamCipher":58,"cipher-base":79,evp_bytestokey:123,inherits:145,"safe-buffer":234}],47:[function(require,module,exports){function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer.alloc(16,0),this.cache=Buffer.allocUnsafe(0)}var Buffer=require("safe-buffer").Buffer,ZEROES=Buffer.alloc(16,0);GHASH.prototype.ghash=function(block){for(var i=-1;++i<block.length;)this.state[i]^=block[i];this._multiply()},GHASH.prototype._multiply=function(){for(var Vi=toArray(this.h),Zi=[0,0,0,0],i=-1,j,xi,lsbVi;128>++i;){for(xi=0!=(this.state[~~(i/8)]&1<<7-i%8),xi&&(Zi[0]^=Vi[0],Zi[1]^=Vi[1],Zi[2]^=Vi[2],Zi[3]^=Vi[3]),lsbVi=0!=(1&Vi[3]),j=3;0<j;j--)Vi[j]=Vi[j]>>>1|(1&Vi[j-1])<<31;Vi[0]>>>=1,lsbVi&&(Vi[0]^=-520093696)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);for(var chunk;16<=this.cache.length;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH},{"safe-buffer":234}],48:[function(require,module,exports){function incr32(iv){for(var len=iv.length,item;len--;)if(item=iv.readUInt8(len),255===item)iv.writeUInt8(0,len);else{item++,iv.writeUInt8(item,len);break}}module.exports=incr32},{}],49:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);return self._prev=self._cipher.encryptBlock(data),self._prev},exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":74}],50:[function(require,module,exports){function encryptStart(self,data,decrypt){var len=data.length,out=xor(data,self._cache);return self._cache=self._cache.slice(len),self._prev=Buffer.concat([self._prev,decrypt?data:out]),out}var Buffer=require("safe-buffer").Buffer,xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){for(var out=Buffer.allocUnsafe(0),len;data.length;)if(0===self._cache.length&&(self._cache=self._cipher.encryptBlock(self._prev),self._prev=Buffer.allocUnsafe(0)),self._cache.length<=data.length)len=self._cache.length,out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]),data=data.slice(len);else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}return out}},{"buffer-xor":74,"safe-buffer":234}],51:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){for(var i=-1,len=8,out=0,pad,bit,value;++i<len;)pad=self._cipher.encryptBlock(self._prev),bit=byteParam&1<<7-i?128:0,value=pad[0]^bit,out+=(128&value)>>i%8,self._prev=shiftIn(self._prev,decrypt?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer.allocUnsafe(buffer.length);for(buffer=Buffer.concat([buffer,Buffer.from([value])]);++i<len;)out[i]=buffer[i]<<1|buffer[i+1]>>7;return out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":234}],52:[function(require,module,exports){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev),out=pad[0]^byteParam;return self._prev=Buffer.concat([self._prev.slice(1),Buffer.from([decrypt?byteParam:out])]),out}var Buffer=require("safe-buffer").Buffer;exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i<len;)out[i]=encryptByte(self,chunk[i],decrypt);return out}},{"safe-buffer":234}],53:[function(require,module,exports){function getBlock(self){var out=self._cipher.encryptBlockRaw(self._prev);return incr32(self._prev),out}var xor=require("buffer-xor"),Buffer=require("safe-buffer").Buffer,incr32=require("../incr32"),blockSize=16;exports.encrypt=function(self,chunk){var chunkNum=_Mathceil(chunk.length/blockSize),start=self._cache.length;self._cache=Buffer.concat([self._cache,Buffer.allocUnsafe(chunkNum*blockSize)]);for(var i=0;i<chunkNum;i++){var out=getBlock(self),offset=start+i*blockSize;self._cache.writeUInt32BE(out[0],offset+0),self._cache.writeUInt32BE(out[1],offset+4),self._cache.writeUInt32BE(out[2],offset+8),self._cache.writeUInt32BE(out[3],offset+12)}var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}},{"../incr32":48,"buffer-xor":74,"safe-buffer":234}],54:[function(require,module,exports){exports.encrypt=function(self,block){return self._cipher.encryptBlock(block)},exports.decrypt=function(self,block){return self._cipher.decryptBlock(block)}},{}],55:[function(require,module,exports){var modeModules={ECB:require("./ecb"),CBC:require("./cbc"),CFB:require("./cfb"),CFB8:require("./cfb8"),CFB1:require("./cfb1"),OFB:require("./ofb"),CTR:require("./ctr"),GCM:require("./ctr")},modes=require("./list.json");for(var key in modes)modes[key].module=modeModules[modes[key].mode];module.exports=modes},{"./cbc":49,"./cfb":50,"./cfb1":51,"./cfb8":52,"./ctr":53,"./ecb":54,"./list.json":56,"./ofb":57}],56:[function(require,module,exports){module.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}},{}],57:[function(require,module,exports){(function(Buffer){(function(){function getBlock(self){return self._prev=self._cipher.encryptBlock(self._prev),self._prev}var xor=require("buffer-xor");exports.encrypt=function(self,chunk){for(;self._cache.length<chunk.length;)self._cache=Buffer.concat([self._cache,getBlock(self)]);var pad=self._cache.slice(0,chunk.length);return self._cache=self._cache.slice(chunk.length),xor(chunk,pad)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"buffer-xor":74}],58:[function(require,module,exports){function StreamCipher(mode,key,iv,decrypt){Transform.call(this),this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._mode=mode}var aes=require("./aes"),Buffer=require("safe-buffer").Buffer,Transform=require("cipher-base"),inherits=require("inherits");inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){return this._mode.encrypt(this,chunk,this._decrypt)},StreamCipher.prototype._final=function(){this._cipher.scrub()},module.exports=StreamCipher},{"./aes":42,"cipher-base":79,inherits:145,"safe-buffer":234}],59:[function(require,module,exports){function createCipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){suite=suite.toLowerCase();var keyLen,ivLen;if(aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else if(desModes[suite])keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv;else throw new TypeError("invalid suite type");var keys=ebtk(password,!1,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createCipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite});throw new TypeError("invalid suite type")}function createDecipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createDecipheriv(suite,key,iv);if(desModes[suite])return new DES({key:key,iv:iv,mode:suite,decrypt:!0});throw new TypeError("invalid suite type")}function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}var DES=require("browserify-des"),aes=require("browserify-aes/browser"),aesModes=require("browserify-aes/modes"),desModes=require("browserify-des/modes"),ebtk=require("evp_bytestokey");exports.createCipher=exports.Cipher=createCipher,exports.createCipheriv=exports.Cipheriv=createCipheriv,exports.createDecipher=exports.Decipher=createDecipher,exports.createDecipheriv=exports.Decipheriv=createDecipheriv,exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":44,"browserify-aes/modes":55,"browserify-des":60,"browserify-des/modes":61,evp_bytestokey:123}],60:[function(require,module,exports){function DES(opts){CipherBase.call(this);var modeName=opts.mode.toLowerCase(),mode=modes[modeName],type;type=opts.decrypt?"decrypt":"encrypt";var key=opts.key;Buffer.isBuffer(key)||(key=Buffer.from(key)),("des-ede"===modeName||"des-ede-cbc"===modeName)&&(key=Buffer.concat([key,key.slice(0,8)]));var iv=opts.iv;Buffer.isBuffer(iv)||(iv=Buffer.from(iv)),this._des=mode.create({key:key,iv:iv,type:type})}var CipherBase=require("cipher-base"),des=require("des.js"),inherits=require("inherits"),Buffer=require("safe-buffer").Buffer,modes={"des-ede3-cbc":des.CBC.instantiate(des.EDE),"des-ede3":des.EDE,"des-ede-cbc":des.CBC.instantiate(des.EDE),"des-ede":des.EDE,"des-cbc":des.CBC.instantiate(des.DES),"des-ecb":des.DES};modes.des=modes["des-cbc"],modes.des3=modes["des-ede3-cbc"],module.exports=DES,inherits(DES,CipherBase),DES.prototype._update=function(data){return Buffer.from(this._des.update(data))},DES.prototype._final=function(){return Buffer.from(this._des.final())}},{"cipher-base":79,"des.js":92,inherits:145,"safe-buffer":234}],61:[function(require,module,exports){exports["des-ecb"]={key:8,iv:0},exports["des-cbc"]=exports.des={key:8,iv:8},exports["des-ede3-cbc"]=exports.des3={key:24,iv:8},exports["des-ede3"]={key:24,iv:0},exports["des-ede-cbc"]={key:16,iv:8},exports["des-ede"]={key:16,iv:0}},{}],62:[function(require,module,exports){(function(Buffer){(function(){function blind(priv){var r=getr(priv),blinder=r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function getr(priv){var len=priv.modulus.byteLength(),r;do r=new BN(randomBytes(len));while(0<=r.cmp(priv.modulus)||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,"be",len)}var BN=require("bn.js"),randomBytes=require("randombytes");crt.getr=getr,module.exports=crt}).call(this)}).call(this,require("buffer").Buffer)},{"bn.js":39,buffer:75,randombytes:208}],63:[function(require,module,exports){module.exports=require("./browser/algorithms.json")},{"./browser/algorithms.json":64}],64:[function(require,module,exports){module.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],65:[function(require,module,exports){module.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],66:[function(require,module,exports){function Sign(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function Verify(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}var Buffer=require("safe-buffer").Buffer,createHash=require("create-hash"),stream=require("readable-stream"),inherits=require("inherits"),sign=require("./sign"),verify=require("./verify"),algorithms=require("./algorithms.json");Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer.from(algorithms[key].id,"hex"),algorithms[key.toLowerCase()]=algorithms[key]}),inherits(Sign,stream.Writable),Sign.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function signMethod(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc?sig.toString(enc):sig},inherits(Verify,stream.Writable),Verify.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function verifyMethod(key,sig,enc){"string"==typeof sig&&(sig=Buffer.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)},module.exports={Sign:createSign,Verify:createVerify,createSign:createSign,createVerify:createVerify}},{"./algorithms.json":64,"./sign":67,"./verify":68,"create-hash":84,inherits:145,"readable-stream":227,"safe-buffer":234}],67:[function(require,module,exports){function sign(hash,key,hashType,signType,tag){var priv=parseKeys(key);if(priv.curve){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");return ecSign(hash,priv)}if("dsa"===priv.type){if("dsa"!==signType)throw new Error("wrong private key type");return dsaSign(hash,priv,hashType)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong private key type");hash=Buffer.concat([tag,hash]);for(var len=priv.modulus.byteLength(),pad=[0,1];hash.length+pad.length+1<len;)pad.push(255);pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);var out=crt(pad,priv);return out}function ecSign(hash,priv){var curveId=curves[priv.curve.join(".")];if(!curveId)throw new Error("unknown curve "+priv.curve.join("."));var curve=new EC(curveId),key=curve.keyFromPrivate(priv.privateKey),out=key.sign(hash);return Buffer.from(out.toDER())}function dsaSign(hash,priv,algo){for(var x=priv.params.priv_key,p=priv.params.p,q=priv.params.q,g=priv.params.g,r=new BN(0),H=bits2int(hash,q).mod(q),s=!1,kv=getKey(x,q,hash,algo),k;!1===s;)k=makeKey(q,kv,algo),r=makeR(g,k,p,q),s=k.invm(q).imul(H.add(x.mul(r))).mod(q),0===s.cmpn(0)&&(s=!1,r=new BN(0));return toDER(r,s)}function toDER(r,s){r=r.toArray(),s=s.toArray(),128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s));var total=r.length+s.length+4,res=[48,total,2,r.length];return res=res.concat(r,[2,s.length],s),Buffer.from(res)}function getKey(x,q,hash,algo){if(x=Buffer.from(x.toArray()),x.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-x.length);x=Buffer.concat([zeros,x])}var hlen=hash.length,hbits=bits2octets(hash,q),v=Buffer.alloc(hlen);v.fill(1);var k=Buffer.alloc(hlen);return k=createHmac(algo,k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),k=createHmac(algo,k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(),v=createHmac(algo,k).update(v).digest(),{k:k,v:v}}function bits2int(obits,q){var bits=new BN(obits),shift=(obits.length<<3)-q.bitLength();return 0<shift&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer.from(bits.toArray());if(out.length<q.byteLength()){var zeros=Buffer.alloc(q.byteLength()-out.length);out=Buffer.concat([zeros,out])}return out}function makeKey(q,kv,algo){var t,k;do{for(t=Buffer.alloc(0);8*t.length<q.bitLength();)kv.v=createHmac(algo,kv.k).update(kv.v).digest(),t=Buffer.concat([t,kv.v]);k=bits2int(t,q),kv.k=createHmac(algo,kv.k).update(kv.v).update(Buffer.from([0])).digest(),kv.v=createHmac(algo,kv.k).update(kv.v).digest()}while(-1!==k.cmp(q));return k}function makeR(g,k,p,q){return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)}var Buffer=require("safe-buffer").Buffer,createHmac=require("create-hmac"),crt=require("browserify-rsa"),EC=require("elliptic").ec,BN=require("bn.js"),parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=sign,module.exports.getKey=getKey,module.exports.makeKey=makeKey},{"./curves.json":65,"bn.js":39,"browserify-rsa":62,"create-hmac":86,elliptic:103,"parse-asn1":182,"safe-buffer":234}],68:[function(require,module,exports){function verify(sig,hash,key,signType,tag){var pub=parseKeys(key);if("ec"===pub.type){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");return ecVerify(sig,hash,pub)}if("dsa"===pub.type){if("dsa"!==signType)throw new Error("wrong public key type");return dsaVerify(sig,hash,pub)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");hash=Buffer.concat([tag,hash]);for(var len=pub.modulus.byteLength(),pad=[1],padNum=0;hash.length+pad.length+2<len;)pad.push(255),padNum++;pad.push(0);for(var i=-1;++i<hash.length;)pad.push(hash[i]);pad=Buffer.from(pad);var red=BN.mont(pub.modulus);sig=new BN(sig).toRed(red),sig=sig.redPow(new BN(pub.publicExponent)),sig=Buffer.from(sig.fromRed().toArray());var out=8>padNum?1:0;for(len=_Mathmin(sig.length,pad.length),sig.length!==pad.length&&(out=1),i=-1;++i<len;)out|=sig[i]^pad[i];return 0==out}function ecVerify(sig,hash,pub){var curveId=curves[pub.data.algorithm.curve.join(".")];if(!curveId)throw new Error("unknown curve "+pub.data.algorithm.curve.join("."));var curve=new EC(curveId),pubkey=pub.data.subjectPrivateKey.data;return curve.verify(hash,sig,pubkey)}function dsaVerify(sig,hash,pub){var p=pub.data.p,q=pub.data.q,g=pub.data.g,y=pub.data.pub_key,unpacked=parseKeys.signature.decode(sig,"der"),s=unpacked.s,r=unpacked.r;checkValue(s,q),checkValue(r,q);var montp=BN.mont(p),w=s.invm(q),v=g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q);return 0===v.cmp(r)}function checkValue(b,q){if(0>=b.cmpn(0))throw new Error("invalid sig");if(b.cmp(q)>=q)throw new Error("invalid sig")}var Buffer=require("safe-buffer").Buffer,BN=require("bn.js"),EC=require("elliptic").ec,parseKeys=require("parse-asn1"),curves=require("./curves.json");module.exports=verify},{"./curves.json":65,"bn.js":39,elliptic:103,"parse-asn1":182,"safe-buffer":234}],69:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),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}],70:[function(require,module,exports){"use strict";function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;!0;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);return 0<=nb?(0<nb&&(self.lastNeed=nb-1),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb)?(0<nb&&(self.lastNeed=nb-2),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb?(0<nb&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"\uFFFD";if(1<self.lastNeed&&1<buf.length){if(128!=(192&buf[1]))return self.lastNeed=1,"\uFFFD";if(2<self.lastNeed&&2<buf.length&&128!=(192&buf[2]))return self.lastNeed=2,"\uFFFD"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0===r?this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,p,0,buf.length),this.lastNeed-=buf.length):r}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"\uFFFD":r}function utf16Text(buf,i){if(0==(buf.length-i)%2){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(55296<=c&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<buf.length?r?r+this.text(buf,i):this.text(buf,i):r||""},StringDecoder.prototype.end=utf8End,StringDecoder.prototype.text=utf8Text,StringDecoder.prototype.fillLast=function(buf){return this.lastNeed<=buf.length?(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length)}},{"safe-buffer":69}],71:[function(require,module,exports){(function(Buffer){(function(){function allocUnsafe(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}module.exports=allocUnsafe}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],72:[function(require,module,exports){(function(Buffer){(function(){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function alloc(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"buffer-alloc-unsafe":71,"buffer-fill":73}],73:[function(require,module,exports){(function(Buffer){(function(){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}function fill(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=fill}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],74:[function(require,module,exports){(function(Buffer){(function(){module.exports=function xor(a,b){for(var length=_Mathmin(a.length,b.length),buffer=new Buffer(length),i=0;i<length;++i)buffer[i]=a[i]^b[i];return buffer}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],75:[function(require,module,exports){(function(Buffer){(function(){/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
@@ -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;i<arr.length;i++){var range=arr[i].split("-"),start=parseInt(range[0],10),end=parseInt(range[1],10);(isNaN(start)?(start=size-end,end=size-1):isNaN(end)&&(end=size-1),end>size-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;i<ordered.length;i++){var range=ordered[i],current=ordered[j];range.start>current.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;i<N;i++)s[i]=i;return s}function seed(key){if(void 0===key){key=Array(N);for(var k=0;k<N;k++)key[k]=_Mathfloor(Math.random()*N)}else if("string"==typeof key)key=""+key,key=key.split("").map(function(c){return c.charCodeAt(0)%N});else if(!Array.isArray(key))throw new TypeError("invalid seed key specified");else if(!key.every(function(v){return"number"==typeof v&&v===(0|v)}))throw new TypeError("invalid seed key specified: not array of integers");for(var keylen=key.length,s=identityPermutation(),j=0,i=0;i<N;i++){j=(j+s[i]+key[i%keylen])%N;var tmp=s[i];s[i]=s[j],s[j]=tmp}return s}function RC4(key){this.s=seed(key),this.i=0,this.j=0}return RC4.prototype.randomNative=function(){this.i=(this.i+1)%N,this.j=(this.j+this.s[this.i])%N;var tmp=this.s[this.i];this.s[this.i]=this.s[this.j],this.s[this.j]=tmp;var k=this.s[(this.s[this.i]+this.s[this.j])%N];return k},RC4.prototype.randomUInt32=function(){var a=this.randomByte(),b=this.randomByte(),c=this.randomByte(),d=this.randomByte();return 256*(256*(256*a+b)+c)+d},RC4.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},RC4.prototype.random=function(){var a,b;if(1===arguments.length)a=0,b=arguments[0];else if(2===arguments.length)a=arguments[0],b=arguments[1];else throw new TypeError("random takes one or two integer arguments");if(!isInteger(a)||!isInteger(b))throw new TypeError("random takes one or two integer arguments");return a+this.randomUInt32()%(b-a+1)},RC4.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},RC4.prototype.setState=function(state){var s=state.s,i=state.i,j=state.j;if(!(i===(0|i)&&0<=i&&i<N))throw new Error("state.i should be integer [0, "+(N-1)+"]");if(!(j===(0|j)&&0<=j&&j<N))throw new Error("state.j should be integer [0, "+(N-1)+"]");if(!Array.isArray(s)||s.length!==N)throw new Error("state should be array of length "+N);for(var k=0;k<N;k++)if(-1===s.indexOf(k))throw new Error("state should be permutation of 0.."+(N-1)+": "+k+" is missing");this.i=i,this.j=j,this.s=s.slice()},RC4}function toHex(n){return 10>n?_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+""}),2<len?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(expected+"")}function startsWith(str,search,pos){return str.substr(!pos||0>pos?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<keys.length;v++)method=keys[v],Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method]);Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this)}).call(this,require("_process"))},{"./_stream_readable":216,"./_stream_writable":218,_process:192,inherits:145}],215:[function(require,module,exports){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform");require("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":217,inherits:145}],216:[function(require,module,exports){(function(process,global){(function(){"use strict";function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(!StringDecoder&&(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else{var er;if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(!(state.objectMode||chunk&&0<chunk.length))addToFront||(state.reading=!1,maybeReadMore(stream,state));else if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return 1073741824<=n?n=1073741824:(n--,n|=n>>>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.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self){var state=self._readableState;state.readableListening=0<self.listenerCount("readable"),state.resumeScheduled&&!state.paused?state.flowing=!0:0<self.listenerCount("data")&&self.resume()}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){if(0===state.length)return null;var ret;return state.objectMode?ret=state.buffer.shift():!n||n>=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<l;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter,EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},debugUtil=require("util"),debug;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var BufferList=require("./internal/streams/buffer_list"),destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,StringDecoder,createReadableStreamAsyncIterator,from;require("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&this._readableState.destroyed},set:function set(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var state=this._readableState,skipChunkCheck;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this};var MAX_HWM=1073741824;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0===state.highWaterMark?0<state.length:state.length>=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<state.highWaterMark)&&(doRead=!0,debug("length less than watermark",doRead)),state.ended||state.reading?(doRead=!1,debug("reading or ended",doRead)):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,!state.reading&&(n=howMuchToRead(nOrig,state)));var ret;return ret=0<n?fromList(n,state):null,null===ret?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(!state.ended&&(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||1<state.pipesCount&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=0<this.listenerCount("readable"),!1!==state.flowing&&this.resume()):"readable"==ev&&!state.endEmitted&&!state.readableListening&&(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):!state.reading&&process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){if((debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),!(state.objectMode&&(null===chunk||void 0===chunk)))&&(state.objectMode||chunk&&chunk.length)){var ret=_this.push(chunk);ret||(paused=!0,stream.pause())}}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function get(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function get(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function get(){return this._readableState.flowing},set:function set(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function get(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":213,"./_stream_duplex":214,"./internal/streams/async_iterator":219,"./internal/streams/buffer_list":220,"./internal/streams/destroy":221,"./internal/streams/from":223,"./internal/streams/state":225,"./internal/streams/stream":226,_process:192,buffer:75,events:122,inherits:145,"string_decoder/":264,util:41}],217:[function(require,module,exports){"use strict";function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){return this instanceof Transform?void(Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)):new Transform(options)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}module.exports=Transform;var _require$codes=require("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require("./_stream_duplex");require("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":213,"./_stream_duplex":214,inherits:145}],218:[function(require,module,exports){(function(process,global){(function(){"use strict";function WriteReq(chunk,encoding,cb){this.chunk=chunk,this.encoding=encoding,this.callback=cb,this.next=null}function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){Duplex=Duplex||require("./_stream_duplex");var isDuplex=this instanceof Duplex;return isDuplex||realHasInstance.call(Writable,this)?void(this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)):new Writable(options)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"!=typeof chunk&&!state.objectMode&&(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}module.exports=Writable;var Duplex;Writable.WritableState=WritableState;var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;require("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function writableStateBufferGetter(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||!(this!==Writable)&&object&&object._writableState instanceof WritableState}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":!encoding&&(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,!state.writing&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest&&clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":213,"./_stream_duplex":214,"./internal/streams/destroy":221,"./internal/streams/state":225,"./internal/streams/stream":226,_process:192,buffer:75,inherits:145,"util-deprecate":277}],219:[function(require,module,exports){(function(process){(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){return iter[kEnded]?void resolve(createIterResult(void 0,!0)):void iter[kHandlePromise](resolve,reject)},reject)}}var finished=require("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream"),AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var _this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise],promise;if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},_defineProperty(_Object$setPrototypeO,Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function _return(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){return err?void reject(err):void resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype),createReadableStreamAsyncIterator=function createReadableStreamAsyncIterator(stream){var iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_Object$create={},_defineProperty(_Object$create,kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create)),_Object$create;return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];return null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),void(iterator[kError]=err)}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator},_Object$setPrototypeO;module.exports=createReadableStreamAsyncIterator}).call(this)}).call(this,require("_process"))},{"./end-of-stream":222,_process:192}],220:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1,source;i<arguments.length;i++)source=null==arguments[i]?{}:arguments[i],i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))});return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}var _require=require("buffer"),Buffer=_require.Buffer,_require2=require("util"),inspect=_require2.inspect,custom=inspect&&inspect.custom||"inspect";module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};0<this.length?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(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 n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):n===this.head.data.length?ret=this.shift():ret=hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.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=i<streams.length-1,writing=0<i;return destroyer(stream,reading,writing,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})}),error;return streams.reduce(pipe)}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=pipeline},{"../../../errors":213,"./end-of-stream":222}],225:[function(require,module,exports){"use strict";function highWaterMarkFrom(options,isDuplex,duplexKey){return null==options.highWaterMark?isDuplex?options[duplexKey]:null:options.highWaterMark}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&_Mathfloor(hwm)===hwm)||0>hwm){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":146,mediasource:158,path:184,"stream-to-blob-url":260,videostream:279}],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<<n|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<this._blockOffset&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.alloc?Buffer.alloc(20):new Buffer(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer},module.exports=RIPEMD160},{buffer:75,"hash-base":128,inherits:145}],231:[function(require,module,exports){function runParallelLimit(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next<len){let key;keys?(key=keys[next],next+=1,tasks[key](function(err,result){each(key,err,result)})):(key=next,next+=1,tasks[key](function(err,result){each(key,err,result)}))}}if("number"!=typeof limit)throw new Error("second argument must be a Number");let isSync=!0,results,len,pending,keys,isErrored,next;Array.isArray(tasks)?(results=[],pending=len=tasks.length):(keys=Object.keys(tasks),results={},pending=len=keys.length),next=limit,pending?keys?keys.some(function(key,i){return tasks[key](function(err,result){each(key,err,result)}),i===limit-1}):tasks.some(function(task,i){return task(function(err,result){each(i,err,result)}),i===limit-1}):done(null),isSync=!1}module.exports=runParallelLimit;const queueMicrotask=require("queue-microtask")},{"queue-microtask":205}],232:[function(require,module,exports){function runParallel(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}let isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}module.exports=runParallel;const queueMicrotask=require("queue-microtask")},{"queue-microtask":205}],233:[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<len%64;len+=1);return len},padZeroes=function(bin,len){var h8=new Uint8Array(bin.buffer),om=len%4,align=len-om;switch(om){case 0:h8[align+3]=0;case 1:h8[align+2]=0;case 2:h8[align+1]=0;case 3:h8[align+0]=0;}for(var i=(len>>2)+1;i<bin.length;i++)bin[i]=0},padData=function(bin,chunkLen,msgLen){bin[chunkLen>>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<chunkSize%64)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=chunkSize,this._padMaxChunkLen=padlen(chunkSize),this._heap=new ArrayBuffer(ceilHeapSize(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new RushaCore({Int32Array:Int32Array},{},this._heap)}return Rusha.prototype._initState=function _initState(heap,padMsgLen){this._offset=0;var io=new Int32Array(heap,padMsgLen+320,5);io[0]=1732584193,io[1]=-271733879,io[2]=-1732584194,io[3]=271733878,io[4]=-1009589776},Rusha.prototype._padChunk=function _padChunk(chunkLen,msgLen){var padChunkLen=padlen(chunkLen),view=new Int32Array(this._heap,0,padChunkLen>>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;chunkOffset<chunkLen;)inputLen=_Mathmin(chunkLen-chunkOffset,this._maxChunkLen-turnOffset),this._write(chunk,chunkOffset,inputLen,turnOffset),turnOffset+=inputLen,chunkOffset+=inputLen,turnOffset===this._maxChunkLen&&(this._core.hash(this._maxChunkLen,this._padMaxChunkLen),turnOffset=0);return this},Rusha.prototype.getState=function getState(){var turnOffset=this._offset%this._maxChunkLen,heap=void 0;if(!turnOffset){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);heap=io.buffer.slice(io.byteOffset,io.byteOffset+io.byteLength)}else heap=this._heap.slice(0);return{offset:this._offset,heap:heap}},Rusha.prototype.setState=function setState(state){if(this._offset=state.offset,20===state.heap.byteLength){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);io.set(new Int32Array(state.heap))}else this._h32.set(new Int32Array(state.heap));return this},Rusha.prototype.rawEnd=function rawEnd(){var msgLen=this._offset,chunkLen=msgLen%this._maxChunkLen,padChunkLen=this._padChunk(chunkLen,msgLen);this._core.hash(padChunkLen,this._padMaxChunkLen);var result=getRawDigest(this._heap,this._padMaxChunkLen);return this._initState(this._heap,this._padMaxChunkLen),result},Rusha.prototype.end=function end(){return toHex(this.rawEnd().buffer)},Rusha}();module.exports=Rusha,module.exports._core=RushaCore},function(module,exports){for(var precomputedHex=Array(256),i=0;256>i;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<res.length;_i++)res[_i]=precomputedHex[binarray[_i]];return res.join("")},module.exports.ceilHeapSize=function(v){var p=0;if(65536>=v)return 65536;if(16777216>v)for(p=1;p<v;p<<=1);else for(p=16777216;p<v;p+=16777216);return p},module.exports.isDedicatedWorkerScope=function(self){var isRunningInWorker="WorkerGlobalScope"in self&&self instanceof self.WorkerGlobalScope,isRunningInSharedWorker="SharedWorkerGlobalScope"in self&&self instanceof self.SharedWorkerGlobalScope,isRunningInServiceWorker="ServiceWorkerGlobalScope"in self&&self instanceof self.ServiceWorkerGlobalScope;return isRunningInWorker&&!isRunningInSharedWorker&&!isRunningInServiceWorker}},function(module,exports,__webpack_require__){module.exports=function(){var Rusha=__webpack_require__(0),hashData=function(hasher,data,cb){try{return cb(null,hasher.digest(data))}catch(e){return cb(e)}},hashFile=function(hasher,readTotal,blockSize,file,cb){var reader=new self.FileReader;reader.onloadend=function onloadend(){if(reader.error)return cb(reader.error);var buffer=reader.result;readTotal+=reader.result.byteLength;try{hasher.append(buffer)}catch(e){return void cb(e)}readTotal<file.size?hashFile(hasher,readTotal,blockSize,file,cb):cb(null,hasher.end())},reader.readAsArrayBuffer(file.slice(readTotal,readTotal+blockSize))},workerBehaviourEnabled=!0;return self.onmessage=function(event){if(workerBehaviourEnabled){var data=event.data.data,file=event.data.file,id=event.data.id;if("undefined"!=typeof id&&(file||data)){var blockSize=event.data.blockSize||4194304,hasher=new Rusha(blockSize);hasher.resetState();var done=function(err,hash){err?self.postMessage({id:id,error:err.name}):self.postMessage({id:id,hash:hash})};data&&hashData(hasher,data,done),file&&hashFile(hasher,0,blockSize,file,done)}}},function(){workerBehaviourEnabled=!1}}},function(module,exports,__webpack_require__){var work=__webpack_require__(4),Rusha=__webpack_require__(0),createHash=__webpack_require__(7),runWorker=__webpack_require__(2),_require=__webpack_require__(1),isDedicatedWorkerScope=_require.isDedicatedWorkerScope,isRunningInDedicatedWorker="undefined"!=typeof self&&isDedicatedWorkerScope(self);Rusha.disableWorkerBehaviour=isRunningInDedicatedWorker?runWorker():function(){},Rusha.createWorker=function(){var worker=work(2),terminate=worker.terminate;return worker.terminate=function(){URL.revokeObjectURL(worker.objectURL),terminate.call(worker)},worker},Rusha.createHash=createHash,module.exports=Rusha},function(module,exports,__webpack_require__){function webpackBootstrapFunc(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={};__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.r=function(exports){Object.defineProperty(exports,"__esModule",{value:!0})},__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__.oe=function(err){throw console.error(err),err};var f=__webpack_require__(__webpack_require__.s=ENTRY_MODULE);return f.default||f}function quoteRegExp(str){return(str+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function getModuleDependencies(sources,module,queueName){var retval={};retval[queueName]=[];var fnString=module.toString(),wrapperSignature=fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!wrapperSignature)return retval;for(var webpackRequireName=wrapperSignature[1],re=new RegExp("(\\\\n|\\W)"+quoteRegExp(webpackRequireName)+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g"),match;match=re.exec(fnString);)"dll-reference"!==match[3]&&retval[queueName].push(match[3]);for(re=new RegExp("\\("+quoteRegExp(webpackRequireName)+"\\(\"(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))\"\\)\\)\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");match=re.exec(fnString);)sources[match[2]]||(retval[queueName].push(match[1]),sources[match[2]]=__webpack_require__(match[1]).m),retval[match[2]]=retval[match[2]]||[],retval[match[2]].push(match[4]);return retval}function hasValuesInQueues(queues){var keys=Object.keys(queues);return keys.reduce(function(hasValues,key){return hasValues||0<queues[key].length},!1)}function getRequiredModules(sources,moduleId){for(var modulesQueue={main:[moduleId]},requiredModules={main:[]},seenModules={main:{}};hasValuesInQueues(modulesQueue);)for(var queues=Object.keys(modulesQueue),i=0;i<queues.length;i++){var queueName=queues[i],queue=modulesQueue[queueName],moduleToCheck=queue.pop();if(seenModules[queueName]=seenModules[queueName]||{},!seenModules[queueName][moduleToCheck]&&sources[queueName][moduleToCheck]){seenModules[queueName][moduleToCheck]=!0,requiredModules[queueName]=requiredModules[queueName]||[],requiredModules[queueName].push(moduleToCheck);for(var newModules=getModuleDependencies(sources,sources[queueName][moduleToCheck],queueName),newModulesKeys=Object.keys(newModules),j=0;j<newModulesKeys.length;j++)modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]]||[],modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])}}return requiredModules}var moduleNameReqExp="[\\.|\\-|\\+|\\w|/|@]+",dependencyRegExp="\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";module.exports=function(moduleId,options){options=options||{};var sources={main:__webpack_require__.m},requiredModules=options.all?{main:Object.keys(sources)}:getRequiredModules(sources,moduleId),src="";Object.keys(requiredModules).filter(function(m){return"main"!==m}).forEach(function(module){for(var entryModule=0;requiredModules[module][entryModule];)entryModule++;requiredModules[module].push(entryModule),sources[module][entryModule]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",src=src+"var "+module+" = ("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(entryModule))+")({"+requiredModules[module].map(function(id){return""+JSON.stringify(id)+": "+sources[module][id].toString()}).join(",")+"});\n"}),src=src+"("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(moduleId))+")({"+requiredModules.main.map(function(id){return""+JSON.stringify(id)+": "+sources.main[id].toString()}).join(",")+"})(self);";var blob=new window.Blob([src],{type:"text/javascript"});if(options.bare)return blob;var URL=window.URL||window.webkitURL||window.mozURL||window.msURL,workerUrl=URL.createObjectURL(blob),worker=new window.Worker(workerUrl);return worker.objectURL=workerUrl,worker}},function(module,exports){module.exports=function RushaCore(stdlib$840,foreign$841,heap$842){"use asm";function hash$844(k$845,x$846){k$845|=0,x$846|=0;var i$847=0,j$848=0,y0$849=0,z0$850=0,y1$851=0,z1$852=0,y2$853=0,z2$854=0,y3$855=0,z3$856=0,y4$857=0,z4$858=0,t0$859=0,t1$860=0;for(y0$849=0|H$843[x$846+320>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function update(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},_createClass(Hash,[{key:"state",get:function(){return this._rusha.getState()},set:function(state){this._rusha.setState(state)}}]),Hash}();module.exports=function(){return new Hash}}])})},{}],234:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<length;){for(var assigned=accum%blockSize,remainder=_Mathmin(length-offset,blockSize-assigned),i=0;i<remainder;i++)block[assigned+i]=data[offset+i];accum+=remainder,offset+=remainder,0==accum%blockSize&&this._update(block)}return this._len+=length,this},Hash.prototype.digest=function(enc){var rem=this._len%this._blockSize;this._block[rem]=128,this._block.fill(0,rem+1),rem>=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:145,"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:145,"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:145,"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:145,"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:145,"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<b>>>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:145,"safe-buffer":234}],244:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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:142,once:177,querystring:204,"simple-concat":244,url:274}],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 <https://feross.org/opensource> */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<this._pc.getStats.length?this._pc.getStats(res=>{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":127,"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<l;i++)array[i]=s.charCodeAt(i);return array}function hex(buf){const l=buf.length,chars=[];for(let i=0;i<l;i++){const bite=buf[i];chars.push((bite>>>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 <https://feross.org/opensource> */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),0<rate&&chunksize>rate)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),0<rate&&chunksize>rate)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<index&&this.throttles.splice(index,1)}}module.exports=ThrottleGroup},{"./throttle":252,limiter:150}],252:[function(require,module,exports){const{EventEmitter}=require("events"),{Transform}=require("streamx"),{wait}=require("./utils");class Throttle extends Transform{constructor(opts={}){if(super(),"object"!=typeof opts)throw new Error("Options must be an object");const params=Object.assign({},opts);if(params.group&&!(params.group instanceof ThrottleGroup))throw new Error("Group must be an instanece of ThrottleGroup");else params.group||(params.group=new ThrottleGroup(params));this._setEnabled(params.enabled||params.group.enabled),this._group=params.group,this._emitter=new EventEmitter,this._destroyed=!1,this._group._addThrottle(this)}getEnabled(){return this._enabled}getGroup(){return this._group}_setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val}setEnabled(val){this._setEnabled(val),this._enabled?this._emitter.emit("enabled"):this._emitter.emit("disabled")}_transform(chunk,done){this._processChunk(chunk,done)}async _waitForTokens(amount){return new Promise((resolve,reject)=>{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(;0<slice.length;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await wait(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(slice.length)&&(await this._waitForTokens(slice.length),this._destroyed))return}catch(err){return done(err)}this.push(slice),pos+=chunksize,chunksize=this._areBothEnabled()?this._group.getChunksize():chunk.length-pos,slice=chunk.slice(pos,pos+chunksize)}return done()}destroy(...args){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...args)}}module.exports=Throttle;const ThrottleGroup=require("./throttle-group")},{"./throttle-group":251,"./utils":253,events:122,streamx:263}],253:[function(require,module,exports){function wait(time){return new Promise(resolve=>setTimeout(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.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],255:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter,inherits=require("inherits");inherits(Stream,EE),Stream.Readable=require("readable-stream/lib/_stream_readable.js"),Stream.Writable=require("readable-stream/lib/_stream_writable.js"),Stream.Duplex=require("readable-stream/lib/_stream_duplex.js"),Stream.Transform=require("readable-stream/lib/_stream_transform.js"),Stream.PassThrough=require("readable-stream/lib/_stream_passthrough.js"),Stream.finished=require("readable-stream/lib/internal/streams/end-of-stream.js"),Stream.pipeline=require("readable-stream/lib/internal/streams/pipeline.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:122,inherits:145,"readable-stream/lib/_stream_duplex.js":214,"readable-stream/lib/_stream_passthrough.js":215,"readable-stream/lib/_stream_readable.js":216,"readable-stream/lib/_stream_transform.js":217,"readable-stream/lib/_stream_writable.js":218,"readable-stream/lib/internal/streams/end-of-stream.js":222,"readable-stream/lib/internal/streams/pipeline.js":224}],256:[function(require,module,exports){(function(global){(function(){var ClientRequest=require("./lib/request"),response=require("./lib/response"),extend=require("xtend"),statusCodes=require("builtin-status-codes"),url=require("url"),http=exports;http.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},http.get=function get(opts,cb){var req=http.request(opts,cb);return req.end(),req},http.ClientRequest=ClientRequest,http.IncomingMessage=response.IncomingMessage,http.Agent=function(){},http.Agent.defaultMaxSockets=4,http.globalAgent=new http.Agent,http.STATUS_CODES=statusCodes,http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./lib/request":258,"./lib/response":259,"builtin-status-codes":76,url:274,xtend:281}],257:[function(require,module,exports){(function(global){(function(){function getXHR(){if(xhr!==void 0)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}function isFunction(value){return"function"==typeof value}exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController);var xhr;exports.arraybuffer=exports.fetch||checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),xhr=null}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],258:[function(require,module,exports){(function(process,global,Buffer){(function(){function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":"text"}function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}var capability=require("./capability"),inherits=require("inherits"),response=require("./response"),stream=require("readable-stream"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates,ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self),self._opts=opts,self._body=[],self._headers={},opts.auth&&self.setHeader("Authorization","Basic "+Buffer.from(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var useFetch=!0,preferBinary;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(!opts.mode||"default"===opts.mode||"prefer-fast"===opts.mode)preferBinary=!0;else throw new Error("Invalid value for opts.mode");self._mode=decideMode(preferBinary,useFetch),self._fetchTimer=null,self._socketTimeout=null,self._socketTimer=null,self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var self=this,lowerName=name.toLowerCase();-1!==unsafeHeaders.indexOf(lowerName)||(self._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self=this;if(!self._destroyed){var opts=self._opts;"timeout"in opts&&0!==opts.timeout&&self.setTimeout(opts.timeout);var headersObj=self._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=new Blob(self._body,{type:(headersObj["content-type"]||{}).value||""}));var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout"),self._fetchAbortController&&self._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response,self._resetTimers(!1),self._connect()},function(reason){self._resetTimers(!0),self._destroyed||self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,!0)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}"responseType"in xhr&&(xhr.responseType=self._mode),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();}},"moz-chunked-arraybuffer"===self._mode&&(xhr.onprogress=function(){self._onXHRProgress()}),xhr.onerror=function(){self._destroyed||(self._resetTimers(!0),self.emit("error",new Error("XHR error")))};try{xhr.send(body)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}}}},ClientRequest.prototype._onXHRProgress=function(){var self=this;self._resetTimers(!1);!statusValid(self._xhr)||self._destroyed||(!self._response&&self._connect(),self._response._onXHRProgress(self._resetTimers.bind(self)))},ClientRequest.prototype._connect=function(){var self=this;self._destroyed||(self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._resetTimers.bind(self)),self._response.on("error",function(err){self.emit("error",err)}),self.emit("response",self._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk),cb()},ClientRequest.prototype._resetTimers=function(done){var self=this;global.clearTimeout(self._socketTimer),self._socketTimer=null,done?(global.clearTimeout(self._fetchTimer),self._fetchTimer=null):self._socketTimeout&&(self._socketTimer=global.setTimeout(function(){self.emit("timeout")},self._socketTimeout))},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(err){var self=this;self._destroyed=!0,self._resetTimers(!0),self._response&&(self._response._destroyed=!0),self._xhr?self._xhr.abort():self._fetchAbortController&&self._fetchAbortController.abort(),err&&self.emit("error",err)},ClientRequest.prototype.end=function(data,encoding,cb){var self=this;"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(self,data,encoding,cb)},ClientRequest.prototype.setTimeout=function(timeout,cb){var self=this;cb&&self.once("timeout",cb),self._socketTimeout=timeout,self._resetTimers(!1)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":257,"./response":259,_process:192,buffer:75,inherits:145,"readable-stream":227}],259:[function(require,module,exports){(function(process,global,Buffer){(function(){var capability=require("./capability"),inherits=require("inherits"),stream=require("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,resetTimers){var self=this;if(stream.Readable.call(self),self._mode=mode,self.headers={},self.rawHeaders=[],self.trailers={},self.rawTrailers=[],self.on("end",function(){process.nextTick(function(){self.emit("close")})}),"fetch"===mode){function read(){reader.read().then(function(result){if(!self._destroyed)return resetTimers(result.done),result.done?void self.push(null):void(self.push(Buffer.from(result.value)),read())}).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}if(self._fetchResponse=response,self.url=response.url,self.statusCode=response.status,self.statusMessage=response.statusText,response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header,self.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return resetTimers(!1),new Promise(function(resolve,reject){self._destroyed?reject():self.push(Buffer.from(chunk))?resolve():self._resumeFetch=resolve})},close:function(){resetTimers(!0),self._destroyed||self.push(null)},abort:function(err){resetTimers(!0),self._destroyed||self.emit("error",err)}});try{return void response.body.pipeTo(writable).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}catch(e){}}var reader=response.body.getReader();read()}else{self._xhr=xhr,self._pos=0,self.url=xhr.responseURL,self.statusCode=xhr.status,self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);if(headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self.headers[key]&&(self.headers[key]=[]),self.headers[key].push(matches[2])):void 0===self.headers[key]?self.headers[key]=matches[2]:self.headers[key]+=", "+matches[2],self.rawHeaders.push(matches[1],matches[2])}}),self._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self._charset=charsetMatch[1].toLowerCase())}self._charset||(self._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var self=this,resolve=self._resumeFetch;resolve&&(self._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(resetTimers){var self=this,xhr=self._xhr,response=null;switch(self._mode){case"text":if(response=xhr.responseText,response.length>self._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self.push(buffer)}else self.push(newData,self._charset);self._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self.push(Buffer.from(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self.push(Buffer.from(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self._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:145,"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 <https://feross.org/opensource> */module.exports=streamToBlob},{}],262:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<all.length;i++)dest=all[i],isStreamx(src)?src.pipe(dest,onerror):(errorHandle(src,!0,1<i,onerror),src.pipe(dest)),src=dest;if(done){let fin=!1;dest.on("finish",()=>{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<this.highWaterMark)?(this.stream._duplexState|=WRITE_QUEUED,!0):(this.stream._duplexState|=WRITE_QUEUED_AND_UNDRAINED,!1)}shift(){const data=this.queue.shift(),stream=this.stream;return this.buffered-=this.byteLength(data),0===this.buffered&&(stream._duplexState&=WRITE_NOT_QUEUED),data}end(data){"function"==typeof data?this.stream.once("finish",data):data!==void 0&&null!==data&&this.push(data),this.stream._duplexState=(this.stream._duplexState|WRITE_FINISHING)&WRITE_NON_PRIMARY}autoBatch(data,cb){const buffer=[],stream=this.stream;for(buffer.push(data);(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED_AND_ACTIVE;)buffer.push(stream._writableState.shift());return 0==(stream._duplexState&OPEN_STATUS)?void stream._writev(buffer,cb):cb(null)}update(){const stream=this.stream;for(;(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED;){const data=this.shift();stream._duplexState|=WRITE_ACTIVE_AND_SYNC,stream._write(data,this.afterWrite),stream._duplexState&=WRITE_NOT_SYNC}0==(stream._duplexState&WRITE_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&WRITE_FINISHING_STATUS)===WRITE_FINISHING?(stream._duplexState=(stream._duplexState|WRITE_ACTIVE)&WRITE_NOT_FINISHING,void stream._final(afterFinal.bind(this))):(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&WRITE_NEXT_TICK)||(this.stream._duplexState|=WRITE_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class ReadableState{constructor(stream,{highWaterMark=16384,map=null,mapReadable,byteLength,byteLengthReadable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthReadable||byteLength||defaultByteLength,this.map=mapReadable||map,this.pipeTo=null,this.afterRead=afterRead.bind(this),this.afterUpdateNextTick=updateReadNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&READ_DONE)}pipe(pipeTo,cb){if(null!==this.pipeTo)throw new Error("Can only pipe to one destination");if("function"!=typeof cb&&(cb=null),this.stream._duplexState|=READ_PIPE_DRAINED,this.pipeTo=pipeTo,this.pipeline=new Pipeline(this.stream,pipeTo,cb),cb&&this.stream.on("error",noop),isStreamx(pipeTo))pipeTo._writableState.pipeline=this.pipeline,cb&&pipeTo.on("error",noop),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline));else{const onerror=this.pipeline.done.bind(this.pipeline,pipeTo),onclose=this.pipeline.done.bind(this.pipeline,pipeTo,null);pipeTo.on("error",onerror),pipeTo.on("close",onclose),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline))}pipeTo.on("drain",afterDrain.bind(this)),this.stream.emit("piping",pipeTo),pipeTo.emit("pipe",this.stream)}push(data){const stream=this.stream;return null===data?(this.highWaterMark=0,stream._duplexState=(stream._duplexState|READ_ENDING)&READ_NON_PRIMARY_AND_PUSHED,!1):(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),stream._duplexState=(stream._duplexState|READ_QUEUED)&READ_PUSHED,this.buffered<this.highWaterMark)}shift(){const data=this.queue.shift();return this.buffered-=this.byteLength(data),0===this.buffered&&(this.stream._duplexState&=READ_NOT_QUEUED),data}unshift(data){let tail;const pending=[];for(;(tail=this.queue.shift())!==void 0;)pending.push(tail);this.push(data);for(let i=0;i<pending.length;i++)this.queue.push(pending[i])}read(){const stream=this.stream;if((stream._duplexState&READ_STATUS)===READ_QUEUED){const data=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data),data}return null}drain(){for(const stream=this.stream;(stream._duplexState&READ_STATUS)===READ_QUEUED&&0!=(stream._duplexState&READ_FLOWING);){const data=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data)}}update(){const stream=this.stream;for(this.drain();this.buffered<this.highWaterMark&&0==(stream._duplexState&SHOULD_NOT_READ);)stream._duplexState|=READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH,stream._read(this.afterRead),stream._duplexState&=READ_NOT_SYNC,0==(stream._duplexState&READ_ACTIVE)&&this.drain();(stream._duplexState&READ_READABLE_STATUS)===READ_EMIT_READABLE_AND_QUEUED&&(stream._duplexState|=READ_EMITTED_READABLE,stream.emit("readable")),0==(stream._duplexState&READ_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&READ_ENDING_STATUS)===READ_ENDING&&(stream._duplexState=(stream._duplexState|READ_DONE)&READ_NOT_ENDING,stream.emit("end"),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),null!==this.pipeTo&&this.pipeTo.end()),(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&READ_NEXT_TICK)||(this.stream._duplexState|=READ_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class TransformState{constructor(stream){this.data=null,this.afterTransform=afterTransform.bind(stream),this.afterFinal=null}}class Pipeline{constructor(src,dst,cb){this.from=src,this.to=dst,this.afterPipe=cb,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(stream,err){return err&&(this.error=err),stream===this.to&&(this.to=null,null!==this.from)?void(0!=(this.from._duplexState&READ_DONE)&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))):stream===this.from&&(this.from=null,null!==this.to)?void(0==(stream._duplexState&READ_DONE)&&this.to.destroy(this.error||new Error("Readable stream closed before ending"))):void(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null)}}class Stream extends EventEmitter{constructor(opts){super(),this._duplexState=0,this._readableState=null,this._writableState=null,opts&&(opts.open&&(this._open=opts.open),opts.destroy&&(this._destroy=opts.destroy),opts.predestroy&&(this._predestroy=opts.predestroy),opts.signal&&opts.signal.addEventListener("abort",abort.bind(this)))}_open(cb){cb(null)}_destroy(cb){cb(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return 0!=(this._duplexState&DESTROYED)}get destroying(){return 0!=(this._duplexState&DESTROY_STATUS)}destroy(err){0==(this._duplexState&DESTROY_STATUS)&&(!err&&(err=STREAM_DESTROYED),this._duplexState=(this._duplexState|DESTROYING)&NON_PRIMARY,null!==this._readableState&&(this._readableState.error=err,this._readableState.updateNextTick()),null!==this._writableState&&(this._writableState.error=err,this._writableState.updateNextTick()),this._predestroy())}on(name,fn){return null!==this._readableState&&("data"===name&&(this._duplexState|=READ_EMIT_DATA|READ_RESUMED,this._readableState.updateNextTick()),"readable"===name&&(this._duplexState|=READ_EMIT_READABLE,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===name&&(this._duplexState|=WRITE_EMIT_DRAIN,this._writableState.updateNextTick()),super.on(name,fn)}}class Readable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|WRITE_DONE,this._readableState=new ReadableState(this,opts),opts&&(opts.read&&(this._read=opts.read),opts.eagerOpen&&this.resume().pause())}_read(cb){cb(null)}pipe(dest,cb){return this._readableState.pipe(dest,cb),this._readableState.updateNextTick(),dest}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(data){return this._readableState.updateNextTick(),this._readableState.push(data)}unshift(data){return this._readableState.updateNextTick(),this._readableState.unshift(data)}resume(){return this._duplexState|=READ_RESUMED,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=READ_PAUSED,this}static _fromAsyncIterator(ite,opts){function push(data){data.done?rs.push(null):rs.push(data.value)}let destroy;const rs=new Readable({...opts,read(cb){ite.next().then(push).then(cb.bind(null,null)).catch(cb)},predestroy(){destroy=ite.return()},destroy(cb){return destroy?void destroy.then(cb.bind(null,null)).catch(cb):cb(null)}});return rs}static from(data,opts){if(isReadStreamx(data))return data;if(data[asyncIterator])return this._fromAsyncIterator(data[asyncIterator](),opts);Array.isArray(data)||(data=data===void 0?[]:[data]);let i=0;return new Readable({...opts,read(cb){this.push(i===data.length?null:data[i++]),cb(null)}})}static isBackpressured(rs){return 0!=(rs._duplexState&READ_BACKPRESSURE_STATUS)||rs._readableState.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":125,"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<plain.length;){var current=plain[i];3<shiftIndex?(digit=current&255>>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<<shiftIndex|(i+1<plain.length?plain[i+1]:0)>>8-shiftIndex,i++):(digit=31&current>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i<encoded.length;i++)encoded[i]=61;return encoded},exports.decode=function(encoded){var shiftIndex=0,plainDigit=0,plainPos=0,plainChar;Buffer.isBuffer(encoded)||(encoded=new Buffer(encoded));for(var decoded=new Buffer(_Mathceil(5*encoded.length/8)),i=0;i<encoded.length&&!(61===encoded[i]);i++){var encodedByte=encoded[i]-48;if(encodedByte<byteTable.length)plainDigit=byteTable[encodedByte],3>=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<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],268:[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<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw new Error("Argument must be a Buffer")}},{buffer:75}],269:[function(require,module,exports){(function(process){(function(){/*! torrent-discovery. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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 <https://webtorrent.io/opensource> */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<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._cancellations.length||this._reservations<this._chunks){let min=this._reservations;for(;this._cancellations.length;)min=_Mathmin(min,this._cancellations.pop());return this._reservations=this._chunks,min}return-1}cancel(i){this.init()&&this._cancellations.push(i)}cancelRemaining(i){this.init()&&(this._reservations=i)}get(i){return this.init()?this._buffer[i]:null}set(i,data,source){if(!this.init())return!1;const len=data.length,blocks=_Mathceil(len/BLOCK_LENGTH);for(let j=0;j<blocks;j++)if(!this._buffer[i+j]){const offset=j*BLOCK_LENGTH,splitData=data.slice(offset,offset+BLOCK_LENGTH);this._buffered++,this._buffer[i+j]=splitData,this.missing-=splitData.length,this.sources.includes(source)||this.sources.push(source)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const buffer=Buffer.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,buffer}init(){return!this._flushed&&(!!this._buffer||(this._buffer=Array(this._chunks),this._cancellations=[],this.sources=[],!0))}}Object.defineProperty(Piece,"BLOCK_LENGTH",{value:16384}),module.exports=Piece}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],271:[function(require,module,exports){(function(Buffer){(function(){var isTypedArray=require("is-typedarray").strict;module.exports=function typedarrayToBuffer(arr){if(isTypedArray(arr)){var buf=Buffer.from(arr.buffer);return arr.byteLength!==arr.buffer.byteLength&&(buf=buf.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)),buf}return Buffer.from(arr)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"is-typedarray":148}],272:[function(require,module,exports){var bufferAlloc=require("buffer-alloc"),UINT_32_MAX=_Mathpow(2,32);exports.encodingLength=function(){return 8},exports.encode=function(num,buf,offset){buf||(buf=bufferAlloc(8)),offset||(offset=0);var top=_Mathfloor(num/UINT_32_MAX),rem=num-top*UINT_32_MAX;return buf.writeUInt32BE(top,offset),buf.writeUInt32BE(rem,offset+4),buf},exports.decode=function(buf,offset){offset||(offset=0);var top=buf.readUInt32BE(offset),rem=buf.readUInt32BE(offset+4);return top*UINT_32_MAX+rem},exports.encode.bytes=8,exports.decode.bytes=8},{"buffer-alloc":72}],273:[function(require,module,exports){function remove(arr,i){if(!(i>=arr.length||0>i)){var last=arr.pop();if(i<arr.length){var tmp=arr[i];return arr[i]=last,tmp}return last}}module.exports=remove},{}],274:[function(require,module,exports){"use strict";function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}var punycode=require("punycode"),util=require("./util");exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">","\"","`"," ","\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&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/"),url=uSplit.join(splitter);var rest=url;if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=simplePathPattern.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],this.query=parseQueryString?querystring.parse(this.search.substr(1)):this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0,hec;i<hostEndingChars.length;i++)hec=rest.indexOf(hostEndingChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0,hec;i<nonHostChars.length;i++)hec=rest.indexOf(nonHostChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length,part;i<l;i++)if(part=hostparts[i],part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)newpart+=127<part.charCodeAt(j)?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}this.hostname=255<this.hostname.length?"":this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length,ae;i<l;i++)if(ae=autoEscape[i],-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1===qm?parseQueryString&&(this.search="",this.query={}):(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):!host&&(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0,tkey;tk<tkeys.length;tk++)tkey=tkeys[tk],result[tkey]=this[tkey];if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0,rkey;rk<rkeys.length;rk++)rkey=rkeys[rk],"protocol"!==rkey&&(result[rkey]=relative[rkey]);return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0,k;v<keys.length;v++)k=keys[v],result[k]=relative[k];return result.href=result.format(),result}if(result.protocol=relative.protocol,!relative.host&&!hostlessProtocol[relative.protocol]){for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),2>relPath.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<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.path=result.search?"/"+result.search:null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||1<srcPath.length)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;0<=i;i--)last=srcPath[i],"."===last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&0<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":275,punycode:201,querystring:204}],275:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],276:[function(require,module,exports){(function(Buffer){(function(){/*! ut_metadata. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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||0>=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<this._remainingRejects&&this._fetching?(this._request(piece),this._remainingRejects-=1):this.emit("warning",new Error("Peer sent \"reject\" too much"))}_requestPieces(){if(this._fetching){this.metadata=Buffer.alloc(this._metadataSize);for(let piece=0;piece<this._numPieces;piece++)this._request(piece)}}_checkDone(){let done=!0;for(let piece=0;piece<this._numPieces;piece++)if(!this._bitfield.get(piece)){done=!1;break}if(done){const success=this.setMetadata(this.metadata);success||this._failedMetadata()}}_failedMetadata(){this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),this._remainingRejects-=this._numPieces,0<this._remainingRejects?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return utMetadata.prototype.name="ut_metadata",utMetadata}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:27,bitfield:31,buffer:75,debug:90,events:122,"simple-sha1":247}],277:[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)},{}],278:[function(require,module,exports){(function(Buffer){(function(){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream"),FIND_MOOV_SEEK_SIZE=4096;class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"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<FIND_MOOV_SEEK_SIZE?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i<traks.length;i++){const trak=traks[i],stbl=trak.mdia.minf.stbl,stsdEntry=stbl.stsd.entries[0],handlerType=trak.mdia.hdlr.handlerType;let codec,mime;if("vide"===handlerType&&"avc1"===stsdEntry.type){if(this._hasVideo)continue;this._hasVideo=!0,codec="avc1",stsdEntry.avcC&&(codec+=`.${stsdEntry.avcC.mimeCodec}`),mime=`video/mp4; codecs="${codec}"`}else if("soun"===handlerType&&"mp4a"===stsdEntry.type){if(this._hasAudio)continue;this._hasAudio=!0,codec="mp4a",stsdEntry.esds&&stsdEntry.esds.mimeCodec&&(codec+=`.${stsdEntry.esds.mimeCodec}`),mime=`audio/mp4; codecs="${codec}"`}else continue;const samples=[];let sample=0,sampleInChunk=0,chunk=0,offsetInChunk=0,sampleToChunkIndex=0,dts=0;const decodingTimeEntry=new RunLengthIndex(stbl.stts.entries);let presentationOffsetEntry=null;stbl.ctts&&(presentationOffsetEntry=new RunLengthIndex(stbl.ctts.entries));for(let syncSampleIndex=0;!0;){var currChunkEntry=stbl.stsc.entries[sampleToChunkIndex];const size=stbl.stsz.entries[sample],duration=decodingTimeEntry.value.duration,presentationOffset=presentationOffsetEntry?presentationOffsetEntry.value.compositionOffset:0;let sync=!0;stbl.stss&&(sync=stbl.stss.entries[syncSampleIndex]===sample+1);const chunkOffsetTable=stbl.stco||stbl.co64;if(samples.push({size,duration,dts,presentationOffset,sync,offset:offsetInChunk+chunkOffsetTable.entries[chunk]}),sample++,sample>=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<startOffset)&&(startOffset=fragment.ranges[0].start);const writeFragment=frag=>{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.samples.length;currSample++){const sample=currTrack.samples[currSample];if(sample.sync&&sample.dts-startDts>=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;j<lastSample;j++){const currSample=currTrack.samples[j];0>currSample.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":170,"mp4-stream":173,"range-slice-stream":211}],279:[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":278,mediasource:158,pump:200}],280:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];var ret=fn.apply(this,args),cb=args[args.length-1];return"function"==typeof ret&&ret!==cb&&Object.keys(cb).forEach(function(k){ret[k]=cb[k]}),ret}if(fn&&cb)return wrappy(fn)(cb);if("function"!=typeof fn)throw new TypeError("need wrapper function");return Object.keys(fn).forEach(function(k){wrapper[k]=fn[k]}),wrapper}module.exports=wrappy},{}],281:[function(require,module,exports){function extend(){for(var target={},i=0,source;i<arguments.length;i++)for(var key in source=arguments[i],source)hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target}module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty},{}],282:[function(require,module,exports){module.exports={version:"1.8.21"}},{}],283:[function(require,module,exports){(function(Buffer){(function(){function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}/*! webtorrent. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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)}),cb(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 void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},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":282,"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}]},{},[283])(283)}); \ 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;i<arr.length;i++){var range=arr[i].split("-"),start=parseInt(range[0],10),end=parseInt(range[1],10);(isNaN(start)?(start=size-end,end=size-1):isNaN(end)&&(end=size-1),end>size-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;i<ordered.length;i++){var range=ordered[i],current=ordered[j];range.start>current.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;i<N;i++)s[i]=i;return s}function seed(key){if(void 0===key){key=Array(N);for(var k=0;k<N;k++)key[k]=_Mathfloor(Math.random()*N)}else if("string"==typeof key)key=""+key,key=key.split("").map(function(c){return c.charCodeAt(0)%N});else if(!Array.isArray(key))throw new TypeError("invalid seed key specified");else if(!key.every(function(v){return"number"==typeof v&&v===(0|v)}))throw new TypeError("invalid seed key specified: not array of integers");for(var keylen=key.length,s=identityPermutation(),j=0,i=0;i<N;i++){j=(j+s[i]+key[i%keylen])%N;var tmp=s[i];s[i]=s[j],s[j]=tmp}return s}function RC4(key){this.s=seed(key),this.i=0,this.j=0}return RC4.prototype.randomNative=function(){this.i=(this.i+1)%N,this.j=(this.j+this.s[this.i])%N;var tmp=this.s[this.i];this.s[this.i]=this.s[this.j],this.s[this.j]=tmp;var k=this.s[(this.s[this.i]+this.s[this.j])%N];return k},RC4.prototype.randomUInt32=function(){var a=this.randomByte(),b=this.randomByte(),c=this.randomByte(),d=this.randomByte();return 256*(256*(256*a+b)+c)+d},RC4.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},RC4.prototype.random=function(){var a,b;if(1===arguments.length)a=0,b=arguments[0];else if(2===arguments.length)a=arguments[0],b=arguments[1];else throw new TypeError("random takes one or two integer arguments");if(!isInteger(a)||!isInteger(b))throw new TypeError("random takes one or two integer arguments");return a+this.randomUInt32()%(b-a+1)},RC4.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},RC4.prototype.setState=function(state){var s=state.s,i=state.i,j=state.j;if(!(i===(0|i)&&0<=i&&i<N))throw new Error("state.i should be integer [0, "+(N-1)+"]");if(!(j===(0|j)&&0<=j&&j<N))throw new Error("state.j should be integer [0, "+(N-1)+"]");if(!Array.isArray(s)||s.length!==N)throw new Error("state should be array of length "+N);for(var k=0;k<N;k++)if(-1===s.indexOf(k))throw new Error("state should be permutation of 0.."+(N-1)+": "+k+" is missing");this.i=i,this.j=j,this.s=s.slice()},RC4}function toHex(n){return 10>n?_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+""}),2<len?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(expected+"")}function startsWith(str,search,pos){return str.substr(!pos||0>pos?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<keys.length;v++)method=keys[v],Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method]);Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function set(value){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this)}).call(this,require("_process"))},{"./_stream_readable":216,"./_stream_writable":218,_process:192,inherits:145}],215:[function(require,module,exports){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform");require("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":217,inherits:145}],216:[function(require,module,exports){(function(process,global){(function(){"use strict";function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(!StringDecoder&&(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else{var er;if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(!(state.objectMode||chunk&&0<chunk.length))addToFront||(state.reading=!1,maybeReadMore(stream,state));else if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return 1073741824<=n?n=1073741824:(n--,n|=n>>>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.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self){var state=self._readableState;state.readableListening=0<self.listenerCount("readable"),state.resumeScheduled&&!state.paused?state.flowing=!0:0<self.listenerCount("data")&&self.resume()}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){if(0===state.length)return null;var ret;return state.objectMode?ret=state.buffer.shift():!n||n>=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<l;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter,EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},debugUtil=require("util"),debug;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var BufferList=require("./internal/streams/buffer_list"),destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,StringDecoder,createReadableStreamAsyncIterator,from;require("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._readableState&&this._readableState.destroyed},set:function set(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var state=this._readableState,skipChunkCheck;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this};var MAX_HWM=1073741824;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0===state.highWaterMark?0<state.length:state.length>=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<state.highWaterMark)&&(doRead=!0,debug("length less than watermark",doRead)),state.ended||state.reading?(doRead=!1,debug("reading or ended",doRead)):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,!state.reading&&(n=howMuchToRead(nOrig,state)));var ret;return ret=0<n?fromList(n,state):null,null===ret?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(!state.ended&&(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||1<state.pipesCount&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=0<this.listenerCount("readable"),!1!==state.flowing&&this.resume()):"readable"==ev&&!state.endEmitted&&!state.readableListening&&(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):!state.reading&&process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){if((debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),!(state.objectMode&&(null===chunk||void 0===chunk)))&&(state.objectMode||chunk&&chunk.length)){var ret=_this.push(chunk);ret||(paused=!0,stream.pause())}}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function get(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function get(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function get(){return this._readableState.flowing},set:function set(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function get(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":213,"./_stream_duplex":214,"./internal/streams/async_iterator":219,"./internal/streams/buffer_list":220,"./internal/streams/destroy":221,"./internal/streams/from":223,"./internal/streams/state":225,"./internal/streams/stream":226,_process:192,buffer:75,events:122,inherits:145,"string_decoder/":264,util:41}],217:[function(require,module,exports){"use strict";function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){return this instanceof Transform?void(Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)):new Transform(options)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}module.exports=Transform;var _require$codes=require("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require("./_stream_duplex");require("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":213,"./_stream_duplex":214,inherits:145}],218:[function(require,module,exports){(function(process,global){(function(){"use strict";function WriteReq(chunk,encoding,cb){this.chunk=chunk,this.encoding=encoding,this.callback=cb,this.next=null}function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){Duplex=Duplex||require("./_stream_duplex");var isDuplex=this instanceof Duplex;return isDuplex||realHasInstance.call(Writable,this)?void(this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)):new Writable(options)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"!=typeof chunk&&!state.objectMode&&(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}module.exports=Writable;var Duplex;Writable.WritableState=WritableState;var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;require("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function writableStateBufferGetter(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||!(this!==Writable)&&object&&object._writableState instanceof WritableState}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":!encoding&&(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,!state.writing&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest&&clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":213,"./_stream_duplex":214,"./internal/streams/destroy":221,"./internal/streams/state":225,"./internal/streams/stream":226,_process:192,buffer:75,inherits:145,"util-deprecate":277}],219:[function(require,module,exports){(function(process){(function(){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){return iter[kEnded]?void resolve(createIterResult(void 0,!0)):void iter[kHandlePromise](resolve,reject)},reject)}}var finished=require("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream"),AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var _this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise],promise;if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},_defineProperty(_Object$setPrototypeO,Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function _return(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){return err?void reject(err):void resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype),createReadableStreamAsyncIterator=function createReadableStreamAsyncIterator(stream){var iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_Object$create={},_defineProperty(_Object$create,kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create)),_Object$create;return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];return null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),void(iterator[kError]=err)}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator},_Object$setPrototypeO;module.exports=createReadableStreamAsyncIterator}).call(this)}).call(this,require("_process"))},{"./end-of-stream":222,_process:192}],220:[function(require,module,exports){"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1,source;i<arguments.length;i++)source=null==arguments[i]?{}:arguments[i],i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))});return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}var _require=require("buffer"),Buffer=_require.Buffer,_require2=require("util"),inspect=_require2.inspect,custom=inspect&&inspect.custom||"inspect";module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function push(v){var entry={data:v,next:null};0<this.length?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(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 n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):n===this.head.data.length?ret=this.shift():ret=hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function first(){return this.head.data}},{key:"_getString",value:function _getString(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.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=i<streams.length-1,writing=0<i;return destroyer(stream,reading,writing,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})}),error;return streams.reduce(pipe)}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=pipeline},{"../../../errors":213,"./end-of-stream":222}],225:[function(require,module,exports){"use strict";function highWaterMarkFrom(options,isDuplex,duplexKey){return null==options.highWaterMark?isDuplex?options[duplexKey]:null:options.highWaterMark}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&_Mathfloor(hwm)===hwm)||0>hwm){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":146,mediasource:158,path:184,"stream-to-blob-url":260,videostream:279}],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<<n|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<this._blockOffset&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.alloc?Buffer.alloc(20):new Buffer(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer},module.exports=RIPEMD160},{buffer:75,"hash-base":128,inherits:145}],231:[function(require,module,exports){function runParallelLimit(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next<len){let key;keys?(key=keys[next],next+=1,tasks[key](function(err,result){each(key,err,result)})):(key=next,next+=1,tasks[key](function(err,result){each(key,err,result)}))}}if("number"!=typeof limit)throw new Error("second argument must be a Number");let isSync=!0,results,len,pending,keys,isErrored,next;Array.isArray(tasks)?(results=[],pending=len=tasks.length):(keys=Object.keys(tasks),results={},pending=len=keys.length),next=limit,pending?keys?keys.some(function(key,i){return tasks[key](function(err,result){each(key,err,result)}),i===limit-1}):tasks.some(function(task,i){return task(function(err,result){each(i,err,result)}),i===limit-1}):done(null),isSync=!1}module.exports=runParallelLimit;const queueMicrotask=require("queue-microtask")},{"queue-microtask":205}],232:[function(require,module,exports){function runParallel(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?queueMicrotask(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}let isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}module.exports=runParallel;const queueMicrotask=require("queue-microtask")},{"queue-microtask":205}],233:[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<len%64;len+=1);return len},padZeroes=function(bin,len){var h8=new Uint8Array(bin.buffer),om=len%4,align=len-om;switch(om){case 0:h8[align+3]=0;case 1:h8[align+2]=0;case 2:h8[align+1]=0;case 3:h8[align+0]=0;}for(var i=(len>>2)+1;i<bin.length;i++)bin[i]=0},padData=function(bin,chunkLen,msgLen){bin[chunkLen>>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<chunkSize%64)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=chunkSize,this._padMaxChunkLen=padlen(chunkSize),this._heap=new ArrayBuffer(ceilHeapSize(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new RushaCore({Int32Array:Int32Array},{},this._heap)}return Rusha.prototype._initState=function _initState(heap,padMsgLen){this._offset=0;var io=new Int32Array(heap,padMsgLen+320,5);io[0]=1732584193,io[1]=-271733879,io[2]=-1732584194,io[3]=271733878,io[4]=-1009589776},Rusha.prototype._padChunk=function _padChunk(chunkLen,msgLen){var padChunkLen=padlen(chunkLen),view=new Int32Array(this._heap,0,padChunkLen>>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;chunkOffset<chunkLen;)inputLen=_Mathmin(chunkLen-chunkOffset,this._maxChunkLen-turnOffset),this._write(chunk,chunkOffset,inputLen,turnOffset),turnOffset+=inputLen,chunkOffset+=inputLen,turnOffset===this._maxChunkLen&&(this._core.hash(this._maxChunkLen,this._padMaxChunkLen),turnOffset=0);return this},Rusha.prototype.getState=function getState(){var turnOffset=this._offset%this._maxChunkLen,heap=void 0;if(!turnOffset){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);heap=io.buffer.slice(io.byteOffset,io.byteOffset+io.byteLength)}else heap=this._heap.slice(0);return{offset:this._offset,heap:heap}},Rusha.prototype.setState=function setState(state){if(this._offset=state.offset,20===state.heap.byteLength){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);io.set(new Int32Array(state.heap))}else this._h32.set(new Int32Array(state.heap));return this},Rusha.prototype.rawEnd=function rawEnd(){var msgLen=this._offset,chunkLen=msgLen%this._maxChunkLen,padChunkLen=this._padChunk(chunkLen,msgLen);this._core.hash(padChunkLen,this._padMaxChunkLen);var result=getRawDigest(this._heap,this._padMaxChunkLen);return this._initState(this._heap,this._padMaxChunkLen),result},Rusha.prototype.end=function end(){return toHex(this.rawEnd().buffer)},Rusha}();module.exports=Rusha,module.exports._core=RushaCore},function(module,exports){for(var precomputedHex=Array(256),i=0;256>i;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<res.length;_i++)res[_i]=precomputedHex[binarray[_i]];return res.join("")},module.exports.ceilHeapSize=function(v){var p=0;if(65536>=v)return 65536;if(16777216>v)for(p=1;p<v;p<<=1);else for(p=16777216;p<v;p+=16777216);return p},module.exports.isDedicatedWorkerScope=function(self){var isRunningInWorker="WorkerGlobalScope"in self&&self instanceof self.WorkerGlobalScope,isRunningInSharedWorker="SharedWorkerGlobalScope"in self&&self instanceof self.SharedWorkerGlobalScope,isRunningInServiceWorker="ServiceWorkerGlobalScope"in self&&self instanceof self.ServiceWorkerGlobalScope;return isRunningInWorker&&!isRunningInSharedWorker&&!isRunningInServiceWorker}},function(module,exports,__webpack_require__){module.exports=function(){var Rusha=__webpack_require__(0),hashData=function(hasher,data,cb){try{return cb(null,hasher.digest(data))}catch(e){return cb(e)}},hashFile=function(hasher,readTotal,blockSize,file,cb){var reader=new self.FileReader;reader.onloadend=function onloadend(){if(reader.error)return cb(reader.error);var buffer=reader.result;readTotal+=reader.result.byteLength;try{hasher.append(buffer)}catch(e){return void cb(e)}readTotal<file.size?hashFile(hasher,readTotal,blockSize,file,cb):cb(null,hasher.end())},reader.readAsArrayBuffer(file.slice(readTotal,readTotal+blockSize))},workerBehaviourEnabled=!0;return self.onmessage=function(event){if(workerBehaviourEnabled){var data=event.data.data,file=event.data.file,id=event.data.id;if("undefined"!=typeof id&&(file||data)){var blockSize=event.data.blockSize||4194304,hasher=new Rusha(blockSize);hasher.resetState();var done=function(err,hash){err?self.postMessage({id:id,error:err.name}):self.postMessage({id:id,hash:hash})};data&&hashData(hasher,data,done),file&&hashFile(hasher,0,blockSize,file,done)}}},function(){workerBehaviourEnabled=!1}}},function(module,exports,__webpack_require__){var work=__webpack_require__(4),Rusha=__webpack_require__(0),createHash=__webpack_require__(7),runWorker=__webpack_require__(2),_require=__webpack_require__(1),isDedicatedWorkerScope=_require.isDedicatedWorkerScope,isRunningInDedicatedWorker="undefined"!=typeof self&&isDedicatedWorkerScope(self);Rusha.disableWorkerBehaviour=isRunningInDedicatedWorker?runWorker():function(){},Rusha.createWorker=function(){var worker=work(2),terminate=worker.terminate;return worker.terminate=function(){URL.revokeObjectURL(worker.objectURL),terminate.call(worker)},worker},Rusha.createHash=createHash,module.exports=Rusha},function(module,exports,__webpack_require__){function webpackBootstrapFunc(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={};__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.r=function(exports){Object.defineProperty(exports,"__esModule",{value:!0})},__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__.oe=function(err){throw console.error(err),err};var f=__webpack_require__(__webpack_require__.s=ENTRY_MODULE);return f.default||f}function quoteRegExp(str){return(str+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function getModuleDependencies(sources,module,queueName){var retval={};retval[queueName]=[];var fnString=module.toString(),wrapperSignature=fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!wrapperSignature)return retval;for(var webpackRequireName=wrapperSignature[1],re=new RegExp("(\\\\n|\\W)"+quoteRegExp(webpackRequireName)+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g"),match;match=re.exec(fnString);)"dll-reference"!==match[3]&&retval[queueName].push(match[3]);for(re=new RegExp("\\("+quoteRegExp(webpackRequireName)+"\\(\"(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))\"\\)\\)\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");match=re.exec(fnString);)sources[match[2]]||(retval[queueName].push(match[1]),sources[match[2]]=__webpack_require__(match[1]).m),retval[match[2]]=retval[match[2]]||[],retval[match[2]].push(match[4]);return retval}function hasValuesInQueues(queues){var keys=Object.keys(queues);return keys.reduce(function(hasValues,key){return hasValues||0<queues[key].length},!1)}function getRequiredModules(sources,moduleId){for(var modulesQueue={main:[moduleId]},requiredModules={main:[]},seenModules={main:{}};hasValuesInQueues(modulesQueue);)for(var queues=Object.keys(modulesQueue),i=0;i<queues.length;i++){var queueName=queues[i],queue=modulesQueue[queueName],moduleToCheck=queue.pop();if(seenModules[queueName]=seenModules[queueName]||{},!seenModules[queueName][moduleToCheck]&&sources[queueName][moduleToCheck]){seenModules[queueName][moduleToCheck]=!0,requiredModules[queueName]=requiredModules[queueName]||[],requiredModules[queueName].push(moduleToCheck);for(var newModules=getModuleDependencies(sources,sources[queueName][moduleToCheck],queueName),newModulesKeys=Object.keys(newModules),j=0;j<newModulesKeys.length;j++)modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]]||[],modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])}}return requiredModules}var moduleNameReqExp="[\\.|\\-|\\+|\\w|/|@]+",dependencyRegExp="\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)";module.exports=function(moduleId,options){options=options||{};var sources={main:__webpack_require__.m},requiredModules=options.all?{main:Object.keys(sources)}:getRequiredModules(sources,moduleId),src="";Object.keys(requiredModules).filter(function(m){return"main"!==m}).forEach(function(module){for(var entryModule=0;requiredModules[module][entryModule];)entryModule++;requiredModules[module].push(entryModule),sources[module][entryModule]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",src=src+"var "+module+" = ("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(entryModule))+")({"+requiredModules[module].map(function(id){return""+JSON.stringify(id)+": "+sources[module][id].toString()}).join(",")+"});\n"}),src=src+"("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(moduleId))+")({"+requiredModules.main.map(function(id){return""+JSON.stringify(id)+": "+sources.main[id].toString()}).join(",")+"})(self);";var blob=new window.Blob([src],{type:"text/javascript"});if(options.bare)return blob;var URL=window.URL||window.webkitURL||window.mozURL||window.msURL,workerUrl=URL.createObjectURL(blob),worker=new window.Worker(workerUrl);return worker.objectURL=workerUrl,worker}},function(module,exports){module.exports=function RushaCore(stdlib$840,foreign$841,heap$842){"use asm";function hash$844(k$845,x$846){k$845|=0,x$846|=0;var i$847=0,j$848=0,y0$849=0,z0$850=0,y1$851=0,z1$852=0,y2$853=0,z2$854=0,y3$855=0,z3$856=0,y4$857=0,z4$858=0,t0$859=0,t1$860=0;for(y0$849=0|H$843[x$846+320>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>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<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function update(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},_createClass(Hash,[{key:"state",get:function(){return this._rusha.getState()},set:function(state){this._rusha.setState(state)}}]),Hash}();module.exports=function(){return new Hash}}])})},{}],234:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<length;){for(var assigned=accum%blockSize,remainder=_Mathmin(length-offset,blockSize-assigned),i=0;i<remainder;i++)block[assigned+i]=data[offset+i];accum+=remainder,offset+=remainder,0==accum%blockSize&&this._update(block)}return this._len+=length,this},Hash.prototype.digest=function(enc){var rem=this._len%this._blockSize;this._block[rem]=128,this._block.fill(0,rem+1),rem>=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:145,"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:145,"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:145,"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:145,"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:145,"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<b>>>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:145,"safe-buffer":234}],244:[function(require,module,exports){(function(Buffer){(function(){/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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:142,once:177,querystring:204,"simple-concat":244,url:274}],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 <https://feross.org/opensource> */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<this._pc.getStats.length?this._pc.getStats(res=>{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":127,"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<l;i++)array[i]=s.charCodeAt(i);return array}function hex(buf){const l=buf.length,chars=[];for(let i=0;i<l;i++){const bite=buf[i];chars.push((bite>>>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 <https://feross.org/opensource> */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),0<rate&&chunksize>rate)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),0<rate&&chunksize>rate)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<index&&this.throttles.splice(index,1)}}module.exports=ThrottleGroup},{"./throttle":252,limiter:150}],252:[function(require,module,exports){const{EventEmitter}=require("events"),{Transform}=require("streamx"),{wait}=require("./utils");class Throttle extends Transform{constructor(opts={}){if(super(),"object"!=typeof opts)throw new Error("Options must be an object");const params=Object.assign({},opts);if(params.group&&!(params.group instanceof ThrottleGroup))throw new Error("Group must be an instanece of ThrottleGroup");else params.group||(params.group=new ThrottleGroup(params));this._setEnabled(params.enabled||params.group.enabled),this._group=params.group,this._emitter=new EventEmitter,this._destroyed=!1,this._group._addThrottle(this)}getEnabled(){return this._enabled}getGroup(){return this._group}_setEnabled(val=!0){if("boolean"!=typeof val)throw new Error("Enabled must be a boolean");this._enabled=val}setEnabled(val){this._setEnabled(val),this._enabled?this._emitter.emit("enabled"):this._emitter.emit("disabled")}_transform(chunk,done){this._processChunk(chunk,done)}async _waitForTokens(amount){return new Promise((resolve,reject)=>{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(;0<slice.length;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await wait(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(slice.length)&&(await this._waitForTokens(slice.length),this._destroyed))return}catch(err){return done(err)}this.push(slice),pos+=chunksize,chunksize=this._areBothEnabled()?this._group.getChunksize():chunk.length-pos,slice=chunk.slice(pos,pos+chunksize)}return done()}destroy(...args){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...args)}}module.exports=Throttle;const ThrottleGroup=require("./throttle-group")},{"./throttle-group":251,"./utils":253,events:122,streamx:263}],253:[function(require,module,exports){function wait(time){return new Promise(resolve=>setTimeout(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.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],255:[function(require,module,exports){function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").EventEmitter,inherits=require("inherits");inherits(Stream,EE),Stream.Readable=require("readable-stream/lib/_stream_readable.js"),Stream.Writable=require("readable-stream/lib/_stream_writable.js"),Stream.Duplex=require("readable-stream/lib/_stream_duplex.js"),Stream.Transform=require("readable-stream/lib/_stream_transform.js"),Stream.PassThrough=require("readable-stream/lib/_stream_passthrough.js"),Stream.finished=require("readable-stream/lib/internal/streams/end-of-stream.js"),Stream.pipeline=require("readable-stream/lib/internal/streams/pipeline.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:122,inherits:145,"readable-stream/lib/_stream_duplex.js":214,"readable-stream/lib/_stream_passthrough.js":215,"readable-stream/lib/_stream_readable.js":216,"readable-stream/lib/_stream_transform.js":217,"readable-stream/lib/_stream_writable.js":218,"readable-stream/lib/internal/streams/end-of-stream.js":222,"readable-stream/lib/internal/streams/pipeline.js":224}],256:[function(require,module,exports){(function(global){(function(){var ClientRequest=require("./lib/request"),response=require("./lib/response"),extend=require("xtend"),statusCodes=require("builtin-status-codes"),url=require("url"),http=exports;http.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},http.get=function get(opts,cb){var req=http.request(opts,cb);return req.end(),req},http.ClientRequest=ClientRequest,http.IncomingMessage=response.IncomingMessage,http.Agent=function(){},http.Agent.defaultMaxSockets=4,http.globalAgent=new http.Agent,http.STATUS_CODES=statusCodes,http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./lib/request":258,"./lib/response":259,"builtin-status-codes":76,url:274,xtend:281}],257:[function(require,module,exports){(function(global){(function(){function getXHR(){if(xhr!==void 0)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}function isFunction(value){return"function"==typeof value}exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController);var xhr;exports.arraybuffer=exports.fetch||checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),xhr=null}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],258:[function(require,module,exports){(function(process,global,Buffer){(function(){function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":"text"}function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}var capability=require("./capability"),inherits=require("inherits"),response=require("./response"),stream=require("readable-stream"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates,ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self),self._opts=opts,self._body=[],self._headers={},opts.auth&&self.setHeader("Authorization","Basic "+Buffer.from(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var useFetch=!0,preferBinary;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(!opts.mode||"default"===opts.mode||"prefer-fast"===opts.mode)preferBinary=!0;else throw new Error("Invalid value for opts.mode");self._mode=decideMode(preferBinary,useFetch),self._fetchTimer=null,self._socketTimeout=null,self._socketTimer=null,self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var self=this,lowerName=name.toLowerCase();-1!==unsafeHeaders.indexOf(lowerName)||(self._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self=this;if(!self._destroyed){var opts=self._opts;"timeout"in opts&&0!==opts.timeout&&self.setTimeout(opts.timeout);var headersObj=self._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=new Blob(self._body,{type:(headersObj["content-type"]||{}).value||""}));var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout"),self._fetchAbortController&&self._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response,self._resetTimers(!1),self._connect()},function(reason){self._resetTimers(!0),self._destroyed||self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,!0)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}"responseType"in xhr&&(xhr.responseType=self._mode),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();}},"moz-chunked-arraybuffer"===self._mode&&(xhr.onprogress=function(){self._onXHRProgress()}),xhr.onerror=function(){self._destroyed||(self._resetTimers(!0),self.emit("error",new Error("XHR error")))};try{xhr.send(body)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}}}},ClientRequest.prototype._onXHRProgress=function(){var self=this;self._resetTimers(!1);!statusValid(self._xhr)||self._destroyed||(!self._response&&self._connect(),self._response._onXHRProgress(self._resetTimers.bind(self)))},ClientRequest.prototype._connect=function(){var self=this;self._destroyed||(self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._resetTimers.bind(self)),self._response.on("error",function(err){self.emit("error",err)}),self.emit("response",self._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk),cb()},ClientRequest.prototype._resetTimers=function(done){var self=this;global.clearTimeout(self._socketTimer),self._socketTimer=null,done?(global.clearTimeout(self._fetchTimer),self._fetchTimer=null):self._socketTimeout&&(self._socketTimer=global.setTimeout(function(){self.emit("timeout")},self._socketTimeout))},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(err){var self=this;self._destroyed=!0,self._resetTimers(!0),self._response&&(self._response._destroyed=!0),self._xhr?self._xhr.abort():self._fetchAbortController&&self._fetchAbortController.abort(),err&&self.emit("error",err)},ClientRequest.prototype.end=function(data,encoding,cb){var self=this;"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(self,data,encoding,cb)},ClientRequest.prototype.setTimeout=function(timeout,cb){var self=this;cb&&self.once("timeout",cb),self._socketTimeout=timeout,self._resetTimers(!1)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":257,"./response":259,_process:192,buffer:75,inherits:145,"readable-stream":227}],259:[function(require,module,exports){(function(process,global,Buffer){(function(){var capability=require("./capability"),inherits=require("inherits"),stream=require("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,resetTimers){var self=this;if(stream.Readable.call(self),self._mode=mode,self.headers={},self.rawHeaders=[],self.trailers={},self.rawTrailers=[],self.on("end",function(){process.nextTick(function(){self.emit("close")})}),"fetch"===mode){function read(){reader.read().then(function(result){if(!self._destroyed)return resetTimers(result.done),result.done?void self.push(null):void(self.push(Buffer.from(result.value)),read())}).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}if(self._fetchResponse=response,self.url=response.url,self.statusCode=response.status,self.statusMessage=response.statusText,response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header,self.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return resetTimers(!1),new Promise(function(resolve,reject){self._destroyed?reject():self.push(Buffer.from(chunk))?resolve():self._resumeFetch=resolve})},close:function(){resetTimers(!0),self._destroyed||self.push(null)},abort:function(err){resetTimers(!0),self._destroyed||self.emit("error",err)}});try{return void response.body.pipeTo(writable).catch(function(err){resetTimers(!0),self._destroyed||self.emit("error",err)})}catch(e){}}var reader=response.body.getReader();read()}else{self._xhr=xhr,self._pos=0,self.url=xhr.responseURL,self.statusCode=xhr.status,self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);if(headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self.headers[key]&&(self.headers[key]=[]),self.headers[key].push(matches[2])):void 0===self.headers[key]?self.headers[key]=matches[2]:self.headers[key]+=", "+matches[2],self.rawHeaders.push(matches[1],matches[2])}}),self._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self._charset=charsetMatch[1].toLowerCase())}self._charset||(self._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var self=this,resolve=self._resumeFetch;resolve&&(self._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(resetTimers){var self=this,xhr=self._xhr,response=null;switch(self._mode){case"text":if(response=xhr.responseText,response.length>self._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self.push(buffer)}else self.push(newData,self._charset);self._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self.push(Buffer.from(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self.push(Buffer.from(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self._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:145,"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 <https://feross.org/opensource> */module.exports=streamToBlob},{}],262:[function(require,module,exports){(function(Buffer){(function(){/*! stream-with-known-length-to-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */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<all.length;i++)dest=all[i],isStreamx(src)?src.pipe(dest,onerror):(errorHandle(src,!0,1<i,onerror),src.pipe(dest)),src=dest;if(done){let fin=!1;dest.on("finish",()=>{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<this.highWaterMark)?(this.stream._duplexState|=WRITE_QUEUED,!0):(this.stream._duplexState|=WRITE_QUEUED_AND_UNDRAINED,!1)}shift(){const data=this.queue.shift(),stream=this.stream;return this.buffered-=this.byteLength(data),0===this.buffered&&(stream._duplexState&=WRITE_NOT_QUEUED),data}end(data){"function"==typeof data?this.stream.once("finish",data):data!==void 0&&null!==data&&this.push(data),this.stream._duplexState=(this.stream._duplexState|WRITE_FINISHING)&WRITE_NON_PRIMARY}autoBatch(data,cb){const buffer=[],stream=this.stream;for(buffer.push(data);(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED_AND_ACTIVE;)buffer.push(stream._writableState.shift());return 0==(stream._duplexState&OPEN_STATUS)?void stream._writev(buffer,cb):cb(null)}update(){const stream=this.stream;for(;(stream._duplexState&WRITE_STATUS)===WRITE_QUEUED;){const data=this.shift();stream._duplexState|=WRITE_ACTIVE_AND_SYNC,stream._write(data,this.afterWrite),stream._duplexState&=WRITE_NOT_SYNC}0==(stream._duplexState&WRITE_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&WRITE_FINISHING_STATUS)===WRITE_FINISHING?(stream._duplexState=(stream._duplexState|WRITE_ACTIVE)&WRITE_NOT_FINISHING,void stream._final(afterFinal.bind(this))):(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&WRITE_NEXT_TICK)||(this.stream._duplexState|=WRITE_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class ReadableState{constructor(stream,{highWaterMark=16384,map=null,mapReadable,byteLength,byteLengthReadable}={}){this.stream=stream,this.queue=new FIFO,this.highWaterMark=highWaterMark,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=byteLengthReadable||byteLength||defaultByteLength,this.map=mapReadable||map,this.pipeTo=null,this.afterRead=afterRead.bind(this),this.afterUpdateNextTick=updateReadNT.bind(this)}get ended(){return 0!=(this.stream._duplexState&READ_DONE)}pipe(pipeTo,cb){if(null!==this.pipeTo)throw new Error("Can only pipe to one destination");if("function"!=typeof cb&&(cb=null),this.stream._duplexState|=READ_PIPE_DRAINED,this.pipeTo=pipeTo,this.pipeline=new Pipeline(this.stream,pipeTo,cb),cb&&this.stream.on("error",noop),isStreamx(pipeTo))pipeTo._writableState.pipeline=this.pipeline,cb&&pipeTo.on("error",noop),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline));else{const onerror=this.pipeline.done.bind(this.pipeline,pipeTo),onclose=this.pipeline.done.bind(this.pipeline,pipeTo,null);pipeTo.on("error",onerror),pipeTo.on("close",onclose),pipeTo.on("finish",this.pipeline.finished.bind(this.pipeline))}pipeTo.on("drain",afterDrain.bind(this)),this.stream.emit("piping",pipeTo),pipeTo.emit("pipe",this.stream)}push(data){const stream=this.stream;return null===data?(this.highWaterMark=0,stream._duplexState=(stream._duplexState|READ_ENDING)&READ_NON_PRIMARY_AND_PUSHED,!1):(null!==this.map&&(data=this.map(data)),this.buffered+=this.byteLength(data),this.queue.push(data),stream._duplexState=(stream._duplexState|READ_QUEUED)&READ_PUSHED,this.buffered<this.highWaterMark)}shift(){const data=this.queue.shift();return this.buffered-=this.byteLength(data),0===this.buffered&&(this.stream._duplexState&=READ_NOT_QUEUED),data}unshift(data){let tail;const pending=[];for(;(tail=this.queue.shift())!==void 0;)pending.push(tail);this.push(data);for(let i=0;i<pending.length;i++)this.queue.push(pending[i])}read(){const stream=this.stream;if((stream._duplexState&READ_STATUS)===READ_QUEUED){const data=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data),data}return null}drain(){for(const stream=this.stream;(stream._duplexState&READ_STATUS)===READ_QUEUED&&0!=(stream._duplexState&READ_FLOWING);){const data=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(data)&&(stream._duplexState&=READ_PIPE_NOT_DRAINED),0!=(stream._duplexState&READ_EMIT_DATA)&&stream.emit("data",data)}}update(){const stream=this.stream;for(this.drain();this.buffered<this.highWaterMark&&0==(stream._duplexState&SHOULD_NOT_READ);)stream._duplexState|=READ_ACTIVE_AND_SYNC_AND_NEEDS_PUSH,stream._read(this.afterRead),stream._duplexState&=READ_NOT_SYNC,0==(stream._duplexState&READ_ACTIVE)&&this.drain();(stream._duplexState&READ_READABLE_STATUS)===READ_EMIT_READABLE_AND_QUEUED&&(stream._duplexState|=READ_EMITTED_READABLE,stream.emit("readable")),0==(stream._duplexState&READ_PRIMARY_AND_ACTIVE)&&this.updateNonPrimary()}updateNonPrimary(){const stream=this.stream;return(stream._duplexState&READ_ENDING_STATUS)===READ_ENDING&&(stream._duplexState=(stream._duplexState|READ_DONE)&READ_NOT_ENDING,stream.emit("end"),(stream._duplexState&AUTO_DESTROY)===DONE&&(stream._duplexState|=DESTROYING),null!==this.pipeTo&&this.pipeTo.end()),(stream._duplexState&DESTROY_STATUS)===DESTROYING?void(0==(stream._duplexState&ACTIVE_OR_TICKING)&&(stream._duplexState|=ACTIVE,stream._destroy(afterDestroy.bind(this)))):void((stream._duplexState&IS_OPENING)===OPENING&&(stream._duplexState=(stream._duplexState|ACTIVE)&NOT_OPENING,stream._open(afterOpen.bind(this))))}updateNextTick(){0!=(this.stream._duplexState&READ_NEXT_TICK)||(this.stream._duplexState|=READ_NEXT_TICK,queueTick(this.afterUpdateNextTick))}}class TransformState{constructor(stream){this.data=null,this.afterTransform=afterTransform.bind(stream),this.afterFinal=null}}class Pipeline{constructor(src,dst,cb){this.from=src,this.to=dst,this.afterPipe=cb,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(stream,err){return err&&(this.error=err),stream===this.to&&(this.to=null,null!==this.from)?void(0!=(this.from._duplexState&READ_DONE)&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))):stream===this.from&&(this.from=null,null!==this.to)?void(0==(stream._duplexState&READ_DONE)&&this.to.destroy(this.error||new Error("Readable stream closed before ending"))):void(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null)}}class Stream extends EventEmitter{constructor(opts){super(),this._duplexState=0,this._readableState=null,this._writableState=null,opts&&(opts.open&&(this._open=opts.open),opts.destroy&&(this._destroy=opts.destroy),opts.predestroy&&(this._predestroy=opts.predestroy),opts.signal&&opts.signal.addEventListener("abort",abort.bind(this)))}_open(cb){cb(null)}_destroy(cb){cb(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return 0!=(this._duplexState&DESTROYED)}get destroying(){return 0!=(this._duplexState&DESTROY_STATUS)}destroy(err){0==(this._duplexState&DESTROY_STATUS)&&(!err&&(err=STREAM_DESTROYED),this._duplexState=(this._duplexState|DESTROYING)&NON_PRIMARY,null!==this._readableState&&(this._readableState.error=err,this._readableState.updateNextTick()),null!==this._writableState&&(this._writableState.error=err,this._writableState.updateNextTick()),this._predestroy())}on(name,fn){return null!==this._readableState&&("data"===name&&(this._duplexState|=READ_EMIT_DATA|READ_RESUMED,this._readableState.updateNextTick()),"readable"===name&&(this._duplexState|=READ_EMIT_READABLE,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===name&&(this._duplexState|=WRITE_EMIT_DRAIN,this._writableState.updateNextTick()),super.on(name,fn)}}class Readable extends Stream{constructor(opts){super(opts),this._duplexState|=OPENING|WRITE_DONE,this._readableState=new ReadableState(this,opts),opts&&(opts.read&&(this._read=opts.read),opts.eagerOpen&&this.resume().pause())}_read(cb){cb(null)}pipe(dest,cb){return this._readableState.pipe(dest,cb),this._readableState.updateNextTick(),dest}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(data){return this._readableState.updateNextTick(),this._readableState.push(data)}unshift(data){return this._readableState.updateNextTick(),this._readableState.unshift(data)}resume(){return this._duplexState|=READ_RESUMED,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=READ_PAUSED,this}static _fromAsyncIterator(ite,opts){function push(data){data.done?rs.push(null):rs.push(data.value)}let destroy;const rs=new Readable({...opts,read(cb){ite.next().then(push).then(cb.bind(null,null)).catch(cb)},predestroy(){destroy=ite.return()},destroy(cb){return destroy?void destroy.then(cb.bind(null,null)).catch(cb):cb(null)}});return rs}static from(data,opts){if(isReadStreamx(data))return data;if(data[asyncIterator])return this._fromAsyncIterator(data[asyncIterator](),opts);Array.isArray(data)||(data=data===void 0?[]:[data]);let i=0;return new Readable({...opts,read(cb){this.push(i===data.length?null:data[i++]),cb(null)}})}static isBackpressured(rs){return 0!=(rs._duplexState&READ_BACKPRESSURE_STATUS)||rs._readableState.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":125,"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<plain.length;){var current=plain[i];3<shiftIndex?(digit=current&255>>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<<shiftIndex|(i+1<plain.length?plain[i+1]:0)>>8-shiftIndex,i++):(digit=31&current>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i<encoded.length;i++)encoded[i]=61;return encoded},exports.decode=function(encoded){var shiftIndex=0,plainDigit=0,plainPos=0,plainChar;Buffer.isBuffer(encoded)||(encoded=new Buffer(encoded));for(var decoded=new Buffer(_Mathceil(5*encoded.length/8)),i=0;i<encoded.length&&!(61===encoded[i]);i++){var encodedByte=encoded[i]-48;if(encodedByte<byteTable.length)plainDigit=byteTable[encodedByte],3>=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<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],268:[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<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw new Error("Argument must be a Buffer")}},{buffer:75}],269:[function(require,module,exports){(function(process){(function(){/*! torrent-discovery. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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 <https://webtorrent.io/opensource> */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<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._cancellations.length||this._reservations<this._chunks){let min=this._reservations;for(;this._cancellations.length;)min=_Mathmin(min,this._cancellations.pop());return this._reservations=this._chunks,min}return-1}cancel(i){this.init()&&this._cancellations.push(i)}cancelRemaining(i){this.init()&&(this._reservations=i)}get(i){return this.init()?this._buffer[i]:null}set(i,data,source){if(!this.init())return!1;const len=data.length,blocks=_Mathceil(len/BLOCK_LENGTH);for(let j=0;j<blocks;j++)if(!this._buffer[i+j]){const offset=j*BLOCK_LENGTH,splitData=data.slice(offset,offset+BLOCK_LENGTH);this._buffered++,this._buffer[i+j]=splitData,this.missing-=splitData.length,this.sources.includes(source)||this.sources.push(source)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const buffer=Buffer.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,buffer}init(){return!this._flushed&&(!!this._buffer||(this._buffer=Array(this._chunks),this._cancellations=[],this.sources=[],!0))}}Object.defineProperty(Piece,"BLOCK_LENGTH",{value:16384}),module.exports=Piece}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75}],271:[function(require,module,exports){(function(Buffer){(function(){var isTypedArray=require("is-typedarray").strict;module.exports=function typedarrayToBuffer(arr){if(isTypedArray(arr)){var buf=Buffer.from(arr.buffer);return arr.byteLength!==arr.buffer.byteLength&&(buf=buf.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)),buf}return Buffer.from(arr)}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:75,"is-typedarray":148}],272:[function(require,module,exports){var bufferAlloc=require("buffer-alloc"),UINT_32_MAX=_Mathpow(2,32);exports.encodingLength=function(){return 8},exports.encode=function(num,buf,offset){buf||(buf=bufferAlloc(8)),offset||(offset=0);var top=_Mathfloor(num/UINT_32_MAX),rem=num-top*UINT_32_MAX;return buf.writeUInt32BE(top,offset),buf.writeUInt32BE(rem,offset+4),buf},exports.decode=function(buf,offset){offset||(offset=0);var top=buf.readUInt32BE(offset),rem=buf.readUInt32BE(offset+4);return top*UINT_32_MAX+rem},exports.encode.bytes=8,exports.decode.bytes=8},{"buffer-alloc":72}],273:[function(require,module,exports){function remove(arr,i){if(!(i>=arr.length||0>i)){var last=arr.pop();if(i<arr.length){var tmp=arr[i];return arr[i]=last,tmp}return last}}module.exports=remove},{}],274:[function(require,module,exports){"use strict";function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}var punycode=require("punycode"),util=require("./util");exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">","\"","`"," ","\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&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/"),url=uSplit.join(splitter);var rest=url;if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=simplePathPattern.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],this.query=parseQueryString?querystring.parse(this.search.substr(1)):this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0,hec;i<hostEndingChars.length;i++)hec=rest.indexOf(hostEndingChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0,hec;i<nonHostChars.length;i++)hec=rest.indexOf(nonHostChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length,part;i<l;i++)if(part=hostparts[i],part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)newpart+=127<part.charCodeAt(j)?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}this.hostname=255<this.hostname.length?"":this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length,ae;i<l;i++)if(ae=autoEscape[i],-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1===qm?parseQueryString&&(this.search="",this.query={}):(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):!host&&(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0,tkey;tk<tkeys.length;tk++)tkey=tkeys[tk],result[tkey]=this[tkey];if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0,rkey;rk<rkeys.length;rk++)rkey=rkeys[rk],"protocol"!==rkey&&(result[rkey]=relative[rkey]);return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0,k;v<keys.length;v++)k=keys[v],result[k]=relative[k];return result.href=result.format(),result}if(result.protocol=relative.protocol,!relative.host&&!hostlessProtocol[relative.protocol]){for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),2>relPath.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<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.path=result.search?"/"+result.search:null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||1<srcPath.length)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;0<=i;i--)last=srcPath[i],"."===last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&0<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":275,punycode:201,querystring:204}],275:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],276:[function(require,module,exports){(function(Buffer){(function(){/*! ut_metadata. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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||0>=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<this._remainingRejects&&this._fetching?(this._request(piece),this._remainingRejects-=1):this.emit("warning",new Error("Peer sent \"reject\" too much"))}_requestPieces(){if(this._fetching){this.metadata=Buffer.alloc(this._metadataSize);for(let piece=0;piece<this._numPieces;piece++)this._request(piece)}}_checkDone(){let done=!0;for(let piece=0;piece<this._numPieces;piece++)if(!this._bitfield.get(piece)){done=!1;break}if(done){const success=this.setMetadata(this.metadata);success||this._failedMetadata()}}_failedMetadata(){this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),this._remainingRejects-=this._numPieces,0<this._remainingRejects?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return utMetadata.prototype.name="ut_metadata",utMetadata}}).call(this)}).call(this,require("buffer").Buffer)},{bencode:27,bitfield:31,buffer:75,debug:90,events:122,"simple-sha1":247}],277:[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)},{}],278:[function(require,module,exports){(function(Buffer){(function(){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream"),FIND_MOOV_SEEK_SIZE=4096;class MP4Remuxer extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"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<FIND_MOOV_SEEK_SIZE?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i<traks.length;i++){const trak=traks[i],stbl=trak.mdia.minf.stbl,stsdEntry=stbl.stsd.entries[0],handlerType=trak.mdia.hdlr.handlerType;let codec,mime;if("vide"===handlerType&&"avc1"===stsdEntry.type){if(this._hasVideo)continue;this._hasVideo=!0,codec="avc1",stsdEntry.avcC&&(codec+=`.${stsdEntry.avcC.mimeCodec}`),mime=`video/mp4; codecs="${codec}"`}else if("soun"===handlerType&&"mp4a"===stsdEntry.type){if(this._hasAudio)continue;this._hasAudio=!0,codec="mp4a",stsdEntry.esds&&stsdEntry.esds.mimeCodec&&(codec+=`.${stsdEntry.esds.mimeCodec}`),mime=`audio/mp4; codecs="${codec}"`}else continue;const samples=[];let sample=0,sampleInChunk=0,chunk=0,offsetInChunk=0,sampleToChunkIndex=0,dts=0;const decodingTimeEntry=new RunLengthIndex(stbl.stts.entries);let presentationOffsetEntry=null;stbl.ctts&&(presentationOffsetEntry=new RunLengthIndex(stbl.ctts.entries));for(let syncSampleIndex=0;!0;){var currChunkEntry=stbl.stsc.entries[sampleToChunkIndex];const size=stbl.stsz.entries[sample],duration=decodingTimeEntry.value.duration,presentationOffset=presentationOffsetEntry?presentationOffsetEntry.value.compositionOffset:0;let sync=!0;stbl.stss&&(sync=stbl.stss.entries[syncSampleIndex]===sample+1);const chunkOffsetTable=stbl.stco||stbl.co64;if(samples.push({size,duration,dts,presentationOffset,sync,offset:offsetInChunk+chunkOffsetTable.entries[chunk]}),sample++,sample>=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<startOffset)&&(startOffset=fragment.ranges[0].start);const writeFragment=frag=>{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.samples.length;currSample++){const sample=currTrack.samples[currSample];if(sample.sync&&sample.dts-startDts>=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;j<lastSample;j++){const currSample=currTrack.samples[j];0>currSample.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":170,"mp4-stream":173,"range-slice-stream":211}],279:[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":278,mediasource:158,pump:200}],280:[function(require,module,exports){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];var ret=fn.apply(this,args),cb=args[args.length-1];return"function"==typeof ret&&ret!==cb&&Object.keys(cb).forEach(function(k){ret[k]=cb[k]}),ret}if(fn&&cb)return wrappy(fn)(cb);if("function"!=typeof fn)throw new TypeError("need wrapper function");return Object.keys(fn).forEach(function(k){wrapper[k]=fn[k]}),wrapper}module.exports=wrappy},{}],281:[function(require,module,exports){function extend(){for(var target={},i=0,source;i<arguments.length;i++)for(var key in source=arguments[i],source)hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target}module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty},{}],282:[function(require,module,exports){module.exports={version:"1.8.22"}},{}],283:[function(require,module,exports){(function(Buffer){(function(){function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}/*! webtorrent. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */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)}),cb(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 void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},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":282,"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}]},{},[283])(283)}); \ No newline at end of file