libaria2-ts
Version:
A full-typing wrapper around `aria2`, `The next generation download utility`.
3 lines (2 loc) • 35.1 kB
JavaScript
function e(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var t,n=new Uint8Array(16);function r(){if(!t&&!(t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}var o=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function i(e){return"string"==typeof e&&o.test(e)}for(var s=[],a=0;a<256;++a)s.push((a+256).toString(16).substr(1));function u(e,t,n){var o=(e=e||{}).random||(e.rng||r)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){n=n||0;for(var a=0;a<16;++a)t[n+a]=o[a];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase();if(!i(n))throw TypeError("Stringified UUID is invalid");return n}(o)}var l,c="object"==typeof Reflect?Reflect:null,f=c&&"function"==typeof c.apply?c.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};l=c&&"function"==typeof c.ownKeys?c.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var h=Number.isNaN||function(e){return e!=e};function p(){p.init.call(this)}var d=p,m=function(e,t){return new Promise((function(n,r){function o(n){e.removeListener(t,i),r(n)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",o),n([].slice.call(arguments))}L(e,t,i,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&L(e,"error",t,n)}(e,o,{once:!0})}))};p.EventEmitter=p,p.prototype._events=void 0,p.prototype._eventsCount=0,p.prototype._maxListeners=void 0;var v,w=10;function g(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function y(e){return void 0===e._maxListeners?p.defaultMaxListeners:e._maxListeners}function b(e,t,n,r){var o,i,s,a;if(g(n),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),i=e._events),s=i[t]),void 0===s)s=i[t]=n,++e._eventsCount;else if("function"==typeof s?s=i[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(o=y(e))>0&&s.length>o&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,a=u,console&&console.warn&&console.warn(a)}return e}function S(){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 _(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=S.bind(r);return o.listener=n,r.wrapFn=o,o}function C(e,t,n){var r=e._events;if(void 0===r)return[];var o=r[t];return void 0===o?[]:"function"==typeof o?n?[o.listener||o]:[o]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(o):E(o,o.length)}function O(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function E(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function L(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function o(i){r.once&&e.removeEventListener(t,o),n(i)}))}}function j(e){return e.toString()}function x(e){return e.toString()}function R(e){if(/^(false|true)$/.test(e))return"true"==e;throw"Unknown Boolean Value: "+e}function P(e){return Number(e)}function A(e){return BigInt(e)}function T(e){let t={};for(const n in e)if(null!=e[n])if("string"==typeof e[n])t[n]=e[n];else if("boolean"==typeof e[n])t[n]=e[n].toString();else if("number"==typeof e[n])t[n]=x(e[n]);else{if("bigint"!=typeof e[n])throw"Unknown Value: "+e[n];t[n]=j(e[n])}return t}function N(e){let t={};for(const n in e)if(null!=e[n])if("string"==typeof e[n])t[n]=e[n];else if("boolean"==typeof e[n])t[n]=R(e[n]);else if("number"==typeof e[n])t[n]=P(e[n]);else{if("bigint"!=typeof e[n])throw"Unknown Value: "+e[n];t[n]=A(e[n])}return t}function U(e){let t=Object.assign({},e);if(null!=e.totalLength&&(t.totalLength=A(e.totalLength)),null!=e.totalLength&&(t.completedLength=A(e.completedLength)),null!=e.totalLength&&(t.uploadLength=A(e.uploadLength)),null!=e.totalLength&&(t.downloadSpeed=A(e.downloadSpeed)),null!=e.totalLength&&(t.uploadSpeed=A(e.uploadSpeed)),null!=e.numSeeders&&(t.numSeeders=A(e.numSeeders)),null!=e.seeder&&(t.seeder=R(e.seeder)),null!=e.totalLength&&(t.pieceLength=A(e.pieceLength)),null!=e.totalLength&&(t.numPieces=A(e.numPieces)),null!=e.totalLength&&(t.connections=A(e.connections)),null!=e.errorCode&&(t.errorCode=P(e.errorCode)),null!=e.bittorrent&&null!=e.bittorrent.creationDate&&(t.bittorrent.creationDate=A(e.bittorrent.creationDate)),null!=e.files)for(const n in e.files)t.files[n]=k(e.files[n]);return t}function k(e){let t=Object.assign({},e);return t.length=A(e.length),t.completedLength=A(e.completedLength),t.index=P(e.index),t.selected=R(e.selected),t}function D(e){let t=Object.assign({},e);return t.amChoking=R(e.amChoking),t.downloadSpeed=A(e.downloadSpeed),t.peerChoking=R(e.peerChoking),t.port=P(e.port),t.seeder=R(e.seeder),t.uploadSpeed=A(e.uploadSpeed),t}function B(e){let t=Object.assign({},e);return t.downloadSpeed=A(e.downloadSpeed),t}function M(e){let t=Object.assign({},e);t.index=P(e.index);for(const n in e.servers)t.servers[n]=B(e.servers[n]);return t}Object.defineProperty(p,"defaultMaxListeners",{enumerable:!0,get:function(){return w},set:function(e){if("number"!=typeof e||e<0||h(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");w=e}}),p.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},p.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||h(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},p.prototype.getMaxListeners=function(){return y(this)},p.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,o=this._events;if(void 0!==o)r=r&&void 0===o.error;else if(!r)return!1;if(r){var i;if(t.length>0&&(i=t[0]),i instanceof Error)throw i;var s=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw s.context=i,s}var a=o[e];if(void 0===a)return!1;if("function"==typeof a)f(a,this,t);else{var u=a.length,l=E(a,u);for(n=0;n<u;++n)f(l[n],this,t)}return!0},p.prototype.addListener=function(e,t){return b(this,e,t,!1)},p.prototype.on=p.prototype.addListener,p.prototype.prependListener=function(e,t){return b(this,e,t,!0)},p.prototype.once=function(e,t){return g(t),this.on(e,_(this,e,t)),this},p.prototype.prependOnceListener=function(e,t){return g(t),this.prependListener(e,_(this,e,t)),this},p.prototype.removeListener=function(e,t){var n,r,o,i,s;if(g(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,i=n.length-1;i>=0;i--)if(n[i]===t||n[i].listener===t){s=n[i].listener,o=i;break}if(o<0)return this;0===o?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,o),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},p.prototype.off=p.prototype.removeListener,p.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var o,i=Object.keys(n);for(r=0;r<i.length;++r)"removeListener"!==(o=i[r])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},p.prototype.listeners=function(e){return C(this,e,!0)},p.prototype.rawListeners=function(e){return C(this,e,!1)},p.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):O.call(e,t)},p.prototype.listenerCount=O,p.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]},d.once=m,function(e){e.atob=function(e){return Buffer.from(e,"base64").toString()},e.btoa=function(e){return Buffer.from(e).toString("base64")}}(v||(v={}));const q=()=>{var e,t;return"string"==typeof(null===globalThis||void 0===globalThis||null===(e=globalThis.process)||void 0===e||null===(t=e.versions)||void 0===t?void 0:t.node)};class $ extends d.EventEmitter{constructor(){super()}async addMetalink(e,t,n){q()&&e instanceof Buffer&&(e=e.toString("base64"));let r=[e];if(null!=t&&r.push(t),null!=t&&null!=n)r.push(n);else if(null!=n)throw"Require `options`!";return await this.rawCall("aria2.addMetalink",...r)}async remove(e){return await this.rawCall("aria2.remove",e)}async forceRemove(e){return await this.rawCall("aria2.forceRemove",e)}async pause(e){return await this.rawCall("aria2.pause",e)}async forcePause(e){return await this.rawCall("aria2.forcePause",e)}async pauseAll(){return await this.rawCall("aria2.pauseAll")}async forcePauseAll(){return await this.rawCall("aria2.forcePauseAll")}async unpause(e){return await this.rawCall("aria2.unpause",e)}async unpauseAll(){return await this.rawCall("aria2.unpauseAll")}async tellStatus(e,t){if(null!=t){return U(await this.rawCall("aria2.tellStatus",e,t))}return U(await this.rawCall("aria2.tellStatus",e))}async getUris(e){return await this.rawCall("aria2.getUris",e)}async getFiles(e){return await this.rawCall("aria2.getFiles",e)}async getPeers(e){return(await this.rawCall("aria2.getPeers",e)).map(D)}async getServers(e){return(await this.rawCall("aria2.getServers",e)).map(M)}async tellActive(e){if(null!=e){return(await this.rawCall("aria2.tellActive",e)).map(U)}return(await this.rawCall("aria2.tellActive")).map(U)}async tellWaiting(e,t,n){if(null!=n){return(await this.rawCall("aria2.tellWaiting",e,t,n)).map(U)}return(await this.rawCall("aria2.tellWaiting",e,t)).map(U)}async tellStopped(e,t,n){if(null!=n){return(await this.rawCall("aria2.tellStopped",e,t,n)).map(U)}return(await this.rawCall("aria2.tellStopped",e,t)).map(U)}async changePosition(e,t,n){return await this.rawCall("aria2.changePosition",e,t,n)}async changeUri(e,t,n,r,o){return await this.rawCall("aria2.changeUri",e,t,n,r,o)}async getOption(e){return N(await this.rawCall("aria2.getOption",e))}async changeOption(e,t){return await this.rawCall("aria2.changeOption",e,T(t))}async getGlobalOption(){return N(await this.rawCall("aria2.getGlobalOption"))}async changeGlobalOption(e){return await this.rawCall("aria2.changeGlobalOption",T(e))}async getGlobalStat(){return function(e){let t=Object.assign({},e);return t.downloadSpeed=A(e.downloadSpeed),t.uploadSpeed=A(e.uploadSpeed),t.numActive=P(e.numActive),t.numWaiting=P(e.numWaiting),t.numStopped=P(e.numStopped),t.numStoppedTotal=P(e.numStoppedTotal),t}(await this.rawCall("aria2.getGlobalStat"))}async purgeDownloadResult(){return await this.rawCall("aria2.purgeDownloadResult")}async removeDownloadResult(e){return await this.rawCall("aria2.removeDownloadResult",e)}async getVersion(){return await this.rawCall("aria2.getVersion")}async shutdown(){return await this.rawCall("aria2.shutdown")}async forceShutdown(){return await this.rawCall("aria2.forceShutdown")}async saveSession(){return await this.rawCall("aria2.saveSession")}async getSessionInfo(){return await this.rawCall("aria2.getSessioninfo")}async addUri(e,t,n){"string"==typeof e&&(e=[e]);let r=[e];if(null!=t&&r.push(T(t)),null!=t&&null!=n)r.push(n);else if(null!=n)throw"Require `options`!";return await this.rawCall("aria2.addUri",...r)}async addTorrent(e,t,n,r){e instanceof Buffer&&(e=e.toString("base64")),"string"==typeof t&&(t=[t]);let o=[e,t];if(null!=n&&o.push(n),null!=n&&null!=r)o.push(r);else if(null!=r)throw"Require `options`!";return await this.rawCall("aria2.addTorrent",...o)}addListener(e,t){return super.on(e,t),this}on(e,t){return super.on(e,t),this}once(e,t){return super.once(e,t),this}}var F,J,I,V;!function(e){e.Set="POS_SET",e.Cur="POS_CUR",e.End="POS_END"}(F||(F={})),function(e){e.Active="active",e.Waiting="waiting",e.Paused="paused",e.Error="error",e.Complete="complete",e.Removed="removed"}(J||(J={})),function(e){e.Waiting="waiting",e.Used="used"}(I||(I={})),function(e){e.Single="single",e.Multi="multi"}(V||(V={}));class W{constructor(t){e(this,"_client",void 0),this._client=t}}var H=Object.freeze({__proto__:null,Aria2ClientBaseClass:$,get EAria2ChangePositionHow(){return F},get EAria2DownloadState(){return J},get EAria2UriStatusEnum(){return I},get EAria2DownloadBitTorrentMode(){return V},Aria2ClientSystemMethodsBaseClass:W});const z=null!=globalThis.WebSocket?class extends globalThis.WebSocket{constructor(e){super(e)}}:require("ws"),G=(()=>{if(q())return v.btoa;if(null!=globalThis.btoa)return globalThis.btoa;throw new Error("`btoa()` is not defined!")})();(()=>{if(q())return v.atob;if(null!=globalThis.atob)return globalThis.atob;throw new Error("`atob()` is not defined!")})();var X=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}},K=Object.prototype.toString;function Q(e){return"[object Array]"===K.call(e)}function Y(e){return void 0===e}function Z(e){return null!==e&&"object"==typeof e}function ee(e){if("[object Object]"!==K.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function te(e){return"[object Function]"===K.call(e)}function ne(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Q(e))for(var n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.call(null,e[o],o,e)}var re={isArray:Q,isArrayBuffer:function(e){return"[object ArrayBuffer]"===K.call(e)},isBuffer:function(e){return null!==e&&!Y(e)&&null!==e.constructor&&!Y(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Z,isPlainObject:ee,isUndefined:Y,isDate:function(e){return"[object Date]"===K.call(e)},isFile:function(e){return"[object File]"===K.call(e)},isBlob:function(e){return"[object Blob]"===K.call(e)},isFunction:te,isStream:function(e){return Z(e)&&te(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:ne,merge:function e(){var t={};function n(n,r){ee(t[r])&&ee(n)?t[r]=e(t[r],n):ee(n)?t[r]=e({},n):Q(n)?t[r]=n.slice():t[r]=n}for(var r=0,o=arguments.length;r<o;r++)ne(arguments[r],n);return t},extend:function(e,t,n){return ne(t,(function(t,r){e[r]=n&&"function"==typeof t?X(t,n):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}};function oe(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var ie=function(e,t,n){if(!t)return e;var r;if(n)r=n(t);else if(re.isURLSearchParams(t))r=t.toString();else{var o=[];re.forEach(t,(function(e,t){null!=e&&(re.isArray(e)?t+="[]":e=[e],re.forEach(e,(function(e){re.isDate(e)?e=e.toISOString():re.isObject(e)&&(e=JSON.stringify(e)),o.push(oe(t)+"="+oe(e))})))})),r=o.join("&")}if(r){var i=e.indexOf("#");-1!==i&&(e=e.slice(0,i)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e};function se(){this.handlers=[]}se.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},se.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},se.prototype.forEach=function(e){re.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var ae=se,ue=function(e,t){re.forEach(e,(function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])}))},le=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}},e},ce=function(e,t,n,r,o){var i=new Error(e);return le(i,t,n,r,o)},fe=re.isStandardBrowserEnv()?{write:function(e,t,n,r,o,i){var s=[];s.push(e+"="+encodeURIComponent(t)),re.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),re.isString(r)&&s.push("path="+r),re.isString(o)&&s.push("domain="+o),!0===i&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},he=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],pe=re.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function r(e){var r=e;return t&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return e=r(window.location.href),function(t){var n=re.isString(t)?r(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0};function de(e){this.message=e}de.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},de.prototype.__CANCEL__=!0;var me=de,ve=Se,we=function(e){return new Promise((function(t,n){var r,o=e.data,i=e.headers,s=e.responseType;function a(){e.cancelToken&&e.cancelToken.unsubscribe(r),e.signal&&e.signal.removeEventListener("abort",r)}re.isFormData(o)&&delete i["Content-Type"];var u=new XMLHttpRequest;if(e.auth){var l=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.Authorization="Basic "+btoa(l+":"+c)}var f,h,p=(f=e.baseURL,h=e.url,f&&!/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(h)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(f,h):h);function d(){if(u){var r="getAllResponseHeaders"in u?function(e){var t,n,r,o={};return e?(re.forEach(e.split("\n"),(function(e){if(r=e.indexOf(":"),t=re.trim(e.substr(0,r)).toLowerCase(),n=re.trim(e.substr(r+1)),t){if(o[t]&&he.indexOf(t)>=0)return;o[t]="set-cookie"===t?(o[t]?o[t]:[]).concat([n]):o[t]?o[t]+", "+n:n}})),o):o}(u.getAllResponseHeaders()):null;!function(e,t,n){var r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(ce("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}((function(e){t(e),a()}),(function(e){n(e),a()}),{data:s&&"text"!==s&&"json"!==s?u.response:u.responseText,status:u.status,statusText:u.statusText,headers:r,config:e,request:u}),u=null}}if(u.open(e.method.toUpperCase(),ie(p,e.params,e.paramsSerializer),!0),u.timeout=e.timeout,"onloadend"in u?u.onloadend=d:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(d)},u.onabort=function(){u&&(n(ce("Request aborted",e,"ECONNABORTED",u)),u=null)},u.onerror=function(){n(ce("Network Error",e,null,u)),u=null},u.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded",r=e.transitional||ve.transitional;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(ce(t,e,r.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",u)),u=null},re.isStandardBrowserEnv()){var m=(e.withCredentials||pe(p))&&e.xsrfCookieName?fe.read(e.xsrfCookieName):void 0;m&&(i[e.xsrfHeaderName]=m)}"setRequestHeader"in u&&re.forEach(i,(function(e,t){void 0===o&&"content-type"===t.toLowerCase()?delete i[t]:u.setRequestHeader(t,e)})),re.isUndefined(e.withCredentials)||(u.withCredentials=!!e.withCredentials),s&&"json"!==s&&(u.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&u.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",e.onUploadProgress),(e.cancelToken||e.signal)&&(r=function(e){u&&(n(!e||e&&e.type?new me("canceled"):e),u.abort(),u=null)},e.cancelToken&&e.cancelToken.subscribe(r),e.signal&&(e.signal.aborted?r():e.signal.addEventListener("abort",r))),o||(o=null),u.send(o)}))},ge={"Content-Type":"application/x-www-form-urlencoded"};function ye(e,t){!re.isUndefined(e)&&re.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var be={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:function(){var e;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(e=we),e}(),transformRequest:[function(e,t){return ue(t,"Accept"),ue(t,"Content-Type"),re.isFormData(e)||re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e)?e:re.isArrayBufferView(e)?e.buffer:re.isURLSearchParams(e)?(ye(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):re.isObject(e)||t&&"application/json"===t["Content-Type"]?(ye(t,"application/json"),function(e,t,n){if(re.isString(e))try{return(t||JSON.parse)(e),re.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||be.transitional,n=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,o=!n&&"json"===this.responseType;if(o||r&&re.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(o){if("SyntaxError"===e.name)throw le(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};re.forEach(["delete","get","head"],(function(e){be.headers[e]={}})),re.forEach(["post","put","patch"],(function(e){be.headers[e]=re.merge(ge)}));var Se=be,_e=function(e,t,n){var r=this||ve;return re.forEach(n,(function(n){e=n.call(r,e,t)})),e},Ce=function(e){return!(!e||!e.__CANCEL__)};function Oe(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new me("canceled")}var Ee=function(e){return Oe(e),e.headers=e.headers||{},e.data=_e.call(e,e.data,e.headers,e.transformRequest),e.headers=re.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),re.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||ve.adapter)(e).then((function(t){return Oe(e),t.data=_e.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return Ce(t)||(Oe(e),t&&t.response&&(t.response.data=_e.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},Le=function(e,t){t=t||{};var n={};function r(e,t){return re.isPlainObject(e)&&re.isPlainObject(t)?re.merge(e,t):re.isPlainObject(t)?re.merge({},t):re.isArray(t)?t.slice():t}function o(n){return re.isUndefined(t[n])?re.isUndefined(e[n])?void 0:r(void 0,e[n]):r(e[n],t[n])}function i(e){if(!re.isUndefined(t[e]))return r(void 0,t[e])}function s(n){return re.isUndefined(t[n])?re.isUndefined(e[n])?void 0:r(void 0,e[n]):r(void 0,t[n])}function a(n){return n in t?r(e[n],t[n]):n in e?r(void 0,e[n]):void 0}var u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return re.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=u[e]||o,r=t(e);re.isUndefined(r)&&t!==a||(n[e]=r)})),n},je="0.22.0",xe=je,Re={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Re[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var Pe={};Re.transitional=function(e,t,n){function r(e,t){return"[Axios v"+xe+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,o,i){if(!1===e)throw new Error(r(o," has been removed"+(t?" in "+t:"")));return t&&!Pe[o]&&(Pe[o]=!0,console.warn(r(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,o,i)}};var Ae={assertOptions:function(e,t,n){if("object"!=typeof e)throw new TypeError("options must be an object");for(var r=Object.keys(e),o=r.length;o-- >0;){var i=r[o],s=t[i];if(s){var a=e[i],u=void 0===a||s(a,i,e);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==n)throw Error("Unknown option "+i)}},validators:Re},Te=Ae.validators;function Ne(e){this.defaults=e,this.interceptors={request:new ae,response:new ae}}Ne.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=Le(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&Ae.assertOptions(t,{silentJSONParsing:Te.transitional(Te.boolean),forcedJSONParsing:Te.transitional(Te.boolean),clarifyTimeoutError:Te.transitional(Te.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(r=r&&t.synchronous,n.unshift(t.fulfilled,t.rejected))}));var o,i=[];if(this.interceptors.response.forEach((function(e){i.push(e.fulfilled,e.rejected)})),!r){var s=[Ee,void 0];for(Array.prototype.unshift.apply(s,n),s=s.concat(i),o=Promise.resolve(e);s.length;)o=o.then(s.shift(),s.shift());return o}for(var a=e;n.length;){var u=n.shift(),l=n.shift();try{a=u(a)}catch(e){l(e);break}}try{o=Ee(a)}catch(e){return Promise.reject(e)}for(;i.length;)o=o.then(i.shift(),i.shift());return o},Ne.prototype.getUri=function(e){return e=Le(this.defaults,e),ie(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},re.forEach(["delete","get","head","options"],(function(e){Ne.prototype[e]=function(t,n){return this.request(Le(n||{},{method:e,url:t,data:(n||{}).data}))}})),re.forEach(["post","put","patch"],(function(e){Ne.prototype[e]=function(t,n,r){return this.request(Le(r||{},{method:e,url:t,data:n}))}}));var Ue=Ne;function ke(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;this.promise.then((function(e){if(n._listeners){var t,r=n._listeners.length;for(t=0;t<r;t++)n._listeners[t](e);n._listeners=null}})),this.promise.then=function(e){var t,r=new Promise((function(e){n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e((function(e){n.reason||(n.reason=new me(e),t(n.reason))}))}ke.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},ke.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},ke.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},ke.source=function(){var e;return{token:new ke((function(t){e=t})),cancel:e}};var De=ke;var Be=function e(t){var n=new Ue(t),r=X(Ue.prototype.request,n);return re.extend(r,Ue.prototype,n),re.extend(r,n),r.create=function(n){return e(Le(t,n))},r}(ve);Be.Axios=Ue,Be.Cancel=me,Be.CancelToken=De,Be.isCancel=Ce,Be.VERSION=je,Be.all=function(e){return Promise.all(e)},Be.spread=function(e){return function(t){return e.apply(null,t)}},Be.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError};var Me=Be,qe=Be;Me.default=qe;var $e,Fe,Je=Me;!function(t){t.Client=class extends ${constructor(t){var r,o,i;super(),e(this,"_conn",void 0),e(this,"_options",void 0),e(this,"_cbs",new Map),e(this,"_open_cbs",[]),e(this,"_opened",!1),e(this,"_systemMethods",new n(this)),this._options=Object.assign({},t),this._conn=new z(`${null!==(r=t.protocol)&&void 0!==r?r:"ws"}://${t.host}:${t.port}${null!==(o=t.path)&&void 0!==o?o:"/jsonrpc"}`,q()?null!==(i=t.wsOptions)&&void 0!==i?i:{}:void 0),this._conn.onclose=()=>{this.emit("ws.close"),this._opened=!1,this._open_cbs=[]},this._conn.onopen=()=>{for(this.emit("ws.open"),this._opened=!0;this._open_cbs.length>0;){let e=this._open_cbs.pop();null!=e&&1==this._conn.readyState&&e()}},this._conn.onmessage=e=>{var t,n,r,o,i,s,a;("message"==(null===(t=e)||void 0===t?void 0:t.type)||q())&&(e=e.data);try{this.emit("ws.message",e);let t=JSON.parse(e.toString());if(t instanceof Array){let e=this._cbs.get(t[0].id);null!=e&&e(t),this._cbs.delete(t[0].id)}else if(null!=t.id&&this._cbs.has(null==t?void 0:t.id)){let e=this._cbs.get(t.id);null!=e&&e(t),this._cbs.delete(t.id)}else if(null!=t.method)switch(null==t?void 0:t.method){case"aria2.onDownloadStart":this.emit("aria2.onDownloadStart",...null!==(n=t.params)&&void 0!==n?n:[]);break;case"aria2.onDownloadPause":this.emit("aria2.onDownloadPause",...null!==(r=t.params)&&void 0!==r?r:[]);break;case"aria2.onDownloadStop":this.emit("aria2.onDownloadStop",...null!==(o=t.params)&&void 0!==o?o:[]);break;case"aria2.onDownloadComplete":this.emit("aria2.onDownloadComplete",...null!==(i=t.params)&&void 0!==i?i:[]);break;case"aria2.onDownloadError":this.emit("aria2.onDownloadError",...null!==(s=t.params)&&void 0!==s?s:[]);break;case"aria2.onBtDownloadComplete":this.emit("aria2.onBtDownloadComplete",...null!==(a=t.params)&&void 0!==a?a:[])}}catch(e){throw this.$errorHandle(e),e}}}$errorHandle(e){}_waitOpened(){return new Promise(((e,t)=>{this._opened&&1==this._conn.readyState?e():this._conn.readyState<1&&this._conn.readyState>1?t(this._conn.readyState):this._open_cbs.push(e)}))}_sendRaw(e){return new Promise(((t,n)=>{try{this._conn.send(e)}catch(e){n(e)}}))}_sendJson(e,...t){return new Promise((async(n,r)=>{var o,i;await this._waitOpened();let s=u(),a={jsonrpc:"2.0",id:s,method:e,params:[]};null!=(null===(o=this._options)||void 0===o||null===(i=o.auth)||void 0===i?void 0:i.secret)&&a.params.push("token:"+this._options.auth.secret),a.params=[...a.params,...t],this._cbs.set(s,n),this._sendRaw(JSON.stringify(a)).catch(r)}))}get system(){return this._systemMethods}async rawCall(e,...t){let n=await this._sendJson(e,...t);if(null!=n.error)throw n.error;return n.result}async rawSend(e){return await this._sendRaw(e)}async getCreateOptions(){return Object.freeze(this._options)}async close(e,t){this._conn.close(e,t)}on(e,t){return super.on(e,t),this}once(e,t){return super.once(e,t),this}addListener(e,t){return super.on(e,t),this}};class n extends W{async listMethods(){return await this._client.rawCall("system.listMethods")}async listNotifications(){return await this._client.rawCall("system.listNotifications")}multicall(...e){return new Promise((async(t,n)=>{var r;let o=u(),i=!1,s=[],a=await this._client.getCreateOptions();var l;null!=(null==a||null===(r=a.auth)||void 0===r?void 0:r.secret)&&s.push("token:"+(null==a||null===(l=a.auth)||void 0===l?void 0:l.secret));let c=[];for(const t of e)1!=i?(c.push({jsonrpc:"2.0",id:o,method:t.methodName,params:[...s,...t.params]}),i=!0):c.push({jsonrpc:"2.0",id:u(),method:t.methodName,params:[...s,...t.params]});await this._client._waitOpened(),this._client._cbs.set(o,(e=>{let n=[];for(const t of e)null!=t.error?n.push(Promise.reject(t.error)):n.push(Promise.resolve(t.result));t(n)})),this._client.rawSend(JSON.stringify(c)).catch(n)}))}}t.SystemMethods=n}($e||($e={})),function(t){t.Client=class extends ${constructor(t){super(),e(this,"_options",void 0),e(this,"_system",void 0),this._options=t,this._system=new n(this)}get system(){return this._system}async rawCall(e,...t){var n,r,o;let i=u(),s=[...t];null!=(null===(n=this._options)||void 0===n||null===(r=n.auth)||void 0===r?void 0:r.secret)&&s.push("token:"+this._options.auth.secret);let a=`${null!==(o=this._options.protocol)&&void 0!==o?o:"http"}://${this._options.host}:${this._options.port}/jsonrpc?method=${decodeURIComponent(e)}&id=${decodeURIComponent(i)}¶ms=${G(JSON.stringify(s))}`,l=(await Je(a,{method:"GET",...this._options.fetchOptions})).data;if(null==l.error)return l.result;throw l.error}async rawSend(e){throw new Error("Method not implemented.")}async getCreateOptions(){return this._options}};class n extends W{async multicall(...e){let t={},n=[],r=[],o=await this._client.getCreateOptions();for(const a of e){var i,s;let e=u(),l=[];null!=(null==o||null===(i=o.auth)||void 0===i?void 0:i.secret)&&l.push(null==o||null===(s=o.auth)||void 0===s?void 0:s.secret),n.push({jsonrpc:"2.0",id:e,params:[...l,...a.params],method:a.methodName}),r.push(new Promise(((n,r)=>{t[e]={r:n,j:r}})))}return new Promise((async()=>{var e;let r=`${null!==(e=o.protocol)&&void 0!==e?e:"http"}://${o.host}:${o.port}/jsonrpc?method=&id=¶ms=${G(JSON.stringify(n))}`,i=await Je(r,{method:"GET",...o.fetchOptions});for(const e of i.data)null!=e.id&&null!=t[e.id]&&(null!=e.error?t[e.id].j(e.error):t[e.id].r(e.result))})),r}async listMethods(){return await this._client.rawCall("system.listMethods")}async listNotifications(){return await this._client.rawCall("system.listNotifications")}}t.SystemMethods=n}(Fe||(Fe={}));export{H as Adapter,Fe as Http,$e as WebSocket};
//# sourceMappingURL=libaria2.browser.esm.js.map