UNPKG

119 kBJavaScriptView Raw
1import require$$0$3 from"util";var shams=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0},origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbols$1=function(){return"function"==typeof origSymbol&&("function"==typeof Symbol&&("symbol"==typeof origSymbol("foo")&&("symbol"==typeof Symbol("bar")&&shams())))},ERROR_MESSAGE="Function.prototype.bind called on incompatible ",slice=Array.prototype.slice,toStr$1=Object.prototype.toString,funcType="[object Function]",implementation=function(e){var t=this;if("function"!=typeof t||toStr$1.call(t)!==funcType)throw new TypeError(ERROR_MESSAGE+t);for(var r,n=slice.call(arguments,1),i=function(){if(this instanceof r){var i=t.apply(this,n.concat(slice.call(arguments)));return Object(i)===i?i:this}return t.apply(e,n.concat(slice.call(arguments)))},s=Math.max(0,t.length-n.length),o=[],a=0;a<s;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},functionBind=Function.prototype.bind||implementation,src=functionBind.call(Function.call,Object.prototype.hasOwnProperty),undefined$1,$SyntaxError=SyntaxError,$Function=Function,$TypeError$1=TypeError,getEvalledConstructor=function(e){try{return $Function('"use strict"; return ('+e+").constructor;")()}catch(e){}},$gOPD=Object.getOwnPropertyDescriptor;if($gOPD)try{$gOPD({},"")}catch(e){$gOPD=null}var throwTypeError=function(){throw new $TypeError$1},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(e){try{return $gOPD(arguments,"callee").get}catch(e){return throwTypeError}}}():throwTypeError,hasSymbols=hasSymbols$1(),getProto=Object.getPrototypeOf||function(e){return e.__proto__},needsEval={},TypedArray="undefined"==typeof Uint8Array?undefined$1:getProto(Uint8Array),INTRINSICS={"%AggregateError%":"undefined"==typeof AggregateError?undefined$1:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined$1:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):undefined$1,"%AsyncFromSyncIteratorPrototype%":undefined$1,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined$1:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined$1:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined$1:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined$1:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined$1:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined$1:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined$1:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined$1:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined$1:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):undefined$1,"%JSON%":"object"==typeof JSON?JSON:undefined$1,"%Map%":"undefined"==typeof Map?undefined$1:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols?getProto((new Map)[Symbol.iterator]()):undefined$1,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined$1:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined$1:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined$1:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined$1:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols?getProto((new Set)[Symbol.iterator]()):undefined$1,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined$1:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):undefined$1,"%Symbol%":hasSymbols?Symbol:undefined$1,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError$1,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined$1:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined$1:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined$1:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined$1:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined$1:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined$1:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined$1:WeakSet},doEval=function e(t){var r;if("%AsyncFunction%"===t)r=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===t)r=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=getProto(i.prototype))}return INTRINSICS[t]=r,r},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"]},$concat=functionBind.call(Function.call,Array.prototype.concat),$spliceApply=functionBind.call(Function.apply,Array.prototype.splice),$replace=functionBind.call(Function.call,String.prototype.replace),$strSlice=functionBind.call(Function.call,String.prototype.slice),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function(e){var t=$strSlice(e,0,1),r=$strSlice(e,-1);if("%"===t&&"%"!==r)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var n=[];return $replace(e,rePropName,(function(e,t,r,i){n[n.length]=r?$replace(i,reEscapeChar,"$1"):t||e})),n},getBaseIntrinsic=function(e,t){var r,n=e;if(src(LEGACY_ALIASES,n)&&(n="%"+(r=LEGACY_ALIASES[n])[0]+"%"),src(INTRINSICS,n)){var i=INTRINSICS[n];if(i===needsEval&&(i=doEval(n)),void 0===i&&!t)throw new $TypeError$1("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new $SyntaxError("intrinsic "+e+" does not exist!")},getIntrinsic=function(e,t){if("string"!=typeof e||0===e.length)throw new $TypeError$1("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new $TypeError$1('"allowMissing" argument must be a boolean');var r=stringToPath(e),n=r.length>0?r[0]:"",i=getBaseIntrinsic("%"+n+"%",t),s=i.name,o=i.value,a=!1,c=i.alias;c&&(n=c[0],$spliceApply(r,$concat([0,1],c)));for(var l=1,u=!0;l<r.length;l+=1){var p=r[l],d=$strSlice(p,0,1),h=$strSlice(p,-1);if(('"'===d||"'"===d||"`"===d||'"'===h||"'"===h||"`"===h)&&d!==h)throw new $SyntaxError("property names with quotes must have matching quotes");if("constructor"!==p&&u||(a=!0),src(INTRINSICS,s="%"+(n+="."+p)+"%"))o=INTRINSICS[s];else if(null!=o){if(!(p in o)){if(!t)throw new $TypeError$1("base intrinsic for "+e+" exists, but the property is not available.");return}if($gOPD&&l+1>=r.length){var y=$gOPD(o,p);o=(u=!!y)&&"get"in y&&!("originalValue"in y.get)?y.get:o[p]}else u=src(o,p),o=o[p];u&&!a&&(INTRINSICS[s]=o)}}return o},commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getAugmentedNamespace(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})})),t}function createCommonjsModule(e){var t={exports:{}};return e(t,t.exports),t.exports}var callBind=createCommonjsModule((function(e){var t=getIntrinsic("%Function.prototype.apply%"),r=getIntrinsic("%Function.prototype.call%"),n=getIntrinsic("%Reflect.apply%",!0)||functionBind.call(r,t),i=getIntrinsic("%Object.getOwnPropertyDescriptor%",!0),s=getIntrinsic("%Object.defineProperty%",!0),o=getIntrinsic("%Math.max%");if(s)try{s({},"a",{value:1})}catch(e){s=null}e.exports=function(e){var t=n(functionBind,r,arguments);if(i&&s){var a=i(t,"length");a.configurable&&s(t,"length",{value:1+o(0,e.length-(arguments.length-1))})}return t};var a=function(){return n(functionBind,t,arguments)};s?s(e.exports,"apply",{value:a}):e.exports.apply=a})),$indexOf=callBind(getIntrinsic("String.prototype.indexOf")),callBound=function(e,t){var r=getIntrinsic(e,!!t);return"function"==typeof r&&$indexOf(e,".prototype.")>-1?callBind(r):r},util_inspect=require$$0$3.inspect,hasMap="function"==typeof Map&&Map.prototype,mapSizeDescriptor=Object.getOwnPropertyDescriptor&&hasMap?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,mapSize=hasMap&&mapSizeDescriptor&&"function"==typeof mapSizeDescriptor.get?mapSizeDescriptor.get:null,mapForEach=hasMap&&Map.prototype.forEach,hasSet="function"==typeof Set&&Set.prototype,setSizeDescriptor=Object.getOwnPropertyDescriptor&&hasSet?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,setSize=hasSet&&setSizeDescriptor&&"function"==typeof setSizeDescriptor.get?setSizeDescriptor.get:null,setForEach=hasSet&&Set.prototype.forEach,hasWeakMap="function"==typeof WeakMap&&WeakMap.prototype,weakMapHas=hasWeakMap?WeakMap.prototype.has:null,hasWeakSet="function"==typeof WeakSet&&WeakSet.prototype,weakSetHas=hasWeakSet?WeakSet.prototype.has:null,hasWeakRef="function"==typeof WeakRef&&WeakRef.prototype,weakRefDeref=hasWeakRef?WeakRef.prototype.deref:null,booleanValueOf=Boolean.prototype.valueOf,objectToString=Object.prototype.toString,functionToString=Function.prototype.toString,match=String.prototype.match,bigIntValueOf="function"==typeof BigInt?BigInt.prototype.valueOf:null,gOPS=Object.getOwnPropertySymbols,symToString="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,hasShammedSymbols="function"==typeof Symbol&&"object"==typeof Symbol.iterator,isEnumerable=Object.prototype.propertyIsEnumerable,gPO=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),inspectCustom=util_inspect.custom,inspectSymbol=inspectCustom&&isSymbol(inspectCustom)?inspectCustom:null,toStringTag="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null,objectInspect=function e(t,r,n,i){var s=r||{};if(has$3(s,"quoteStyle")&&"single"!==s.quoteStyle&&"double"!==s.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has$3(s,"maxStringLength")&&("number"==typeof s.maxStringLength?s.maxStringLength<0&&s.maxStringLength!==1/0:null!==s.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!has$3(s,"customInspect")||s.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has$3(s,"indent")&&null!==s.indent&&"\t"!==s.indent&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,s);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===s.depth?5:s.depth;if(void 0===n&&(n=0),n>=a&&a>0&&"object"==typeof t)return isArray$3(t)?"[Array]":"[Object]";var c=getIndent(s,n);if(void 0===i)i=[];else if(indexOf(i,t)>=0)return"[Circular]";function l(t,r,o){if(r&&(i=i.slice()).push(r),o){var a={depth:s.depth};return has$3(s,"quoteStyle")&&(a.quoteStyle=s.quoteStyle),e(t,a,n+1,i)}return e(t,s,n+1,i)}if("function"==typeof t){var u=nameOf(t),p=arrObjKeys(t,l);return"[Function"+(u?": "+u:" (anonymous)")+"]"+(p.length>0?" { "+p.join(", ")+" }":"")}if(isSymbol(t)){var d=hasShammedSymbols?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(t);return"object"!=typeof t||hasShammedSymbols?d:markBoxed(d)}if(isElement(t)){for(var h="<"+String(t.nodeName).toLowerCase(),y=t.attributes||[],f=0;f<y.length;f++)h+=" "+y[f].name+"="+wrapQuotes(quote(y[f].value),"double",s);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(isArray$3(t)){if(0===t.length)return"[]";var _=arrObjKeys(t,l);return c&&!singleLineValues(_)?"["+indentedJoin(_,c)+"]":"[ "+_.join(", ")+" ]"}if(isError(t)){var m=arrObjKeys(t,l);return 0===m.length?"["+String(t)+"]":"{ ["+String(t)+"] "+m.join(", ")+" }"}if("object"==typeof t&&o){if(inspectSymbol&&"function"==typeof t[inspectSymbol])return t[inspectSymbol]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(isMap(t)){var g=[];return mapForEach.call(t,(function(e,r){g.push(l(r,t,!0)+" => "+l(e,t))})),collectionOf("Map",mapSize.call(t),g,c)}if(isSet(t)){var v=[];return setForEach.call(t,(function(e){v.push(l(e,t))})),collectionOf("Set",setSize.call(t),v,c)}if(isWeakMap(t))return weakCollectionOf("WeakMap");if(isWeakSet(t))return weakCollectionOf("WeakSet");if(isWeakRef(t))return weakCollectionOf("WeakRef");if(isNumber(t))return markBoxed(l(Number(t)));if(isBigInt(t))return markBoxed(l(bigIntValueOf.call(t)));if(isBoolean(t))return markBoxed(booleanValueOf.call(t));if(isString(t))return markBoxed(l(String(t)));if(!isDate(t)&&!isRegExp$1(t)){var b=arrObjKeys(t,l),w=gPO?gPO(t)===Object.prototype:t instanceof Object||t.constructor===Object,$=t instanceof Object?"":"null prototype",S=!w&&toStringTag&&Object(t)===t&&toStringTag in t?toStr(t).slice(8,-1):$?"Object":"",k=(w||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(S||$?"["+[].concat(S||[],$||[]).join(": ")+"] ":"");return 0===b.length?k+"{}":c?k+"{"+indentedJoin(b,c)+"}":k+"{ "+b.join(", ")+" }"}return String(t)};function wrapQuotes(e,t,r){var n="double"===(r.quoteStyle||t)?'"':"'";return n+e+n}function quote(e){return String(e).replace(/"/g,"&quot;")}function isArray$3(e){return!("[object Array]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isDate(e){return!("[object Date]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isRegExp$1(e){return!("[object RegExp]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isError(e){return!("[object Error]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isString(e){return!("[object String]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isNumber(e){return!("[object Number]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isBoolean(e){return!("[object Boolean]"!==toStr(e)||toStringTag&&"object"==typeof e&&toStringTag in e)}function isSymbol(e){if(hasShammedSymbols)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!symToString)return!1;try{return symToString.call(e),!0}catch(e){}return!1}function isBigInt(e){if(!e||"object"!=typeof e||!bigIntValueOf)return!1;try{return bigIntValueOf.call(e),!0}catch(e){}return!1}var hasOwn=Object.prototype.hasOwnProperty||function(e){return e in this};function has$3(e,t){return hasOwn.call(e,t)}function toStr(e){return objectToString.call(e)}function nameOf(e){if(e.name)return e.name;var t=match.call(functionToString.call(e),/^function\s*([\w$]+)/);return t?t[1]:null}function indexOf(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}function isMap(e){if(!mapSize||!e||"object"!=typeof e)return!1;try{mapSize.call(e);try{setSize.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}function isWeakMap(e){if(!weakMapHas||!e||"object"!=typeof e)return!1;try{weakMapHas.call(e,weakMapHas);try{weakSetHas.call(e,weakSetHas)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}function isWeakRef(e){if(!weakRefDeref||!e||"object"!=typeof e)return!1;try{return weakRefDeref.call(e),!0}catch(e){}return!1}function isSet(e){if(!setSize||!e||"object"!=typeof e)return!1;try{setSize.call(e);try{mapSize.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}function isWeakSet(e){if(!weakSetHas||!e||"object"!=typeof e)return!1;try{weakSetHas.call(e,weakSetHas);try{weakMapHas.call(e,weakMapHas)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}function isElement(e){return!(!e||"object"!=typeof e)&&("undefined"!=typeof HTMLElement&&e instanceof HTMLElement||"string"==typeof e.nodeName&&"function"==typeof e.getAttribute)}function inspectString(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return inspectString(e.slice(0,t.maxStringLength),t)+n}return wrapQuotes(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,lowbyte),"single",t)}function lowbyte(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function markBoxed(e){return"Object("+e+")"}function weakCollectionOf(e){return e+" { ? }"}function collectionOf(e,t,r,n){return e+" ("+t+") {"+(n?indentedJoin(r,n):r.join(", "))+"}"}function singleLineValues(e){for(var t=0;t<e.length;t++)if(indexOf(e[t],"\n")>=0)return!1;return!0}function getIndent(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}function indentedJoin(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function arrObjKeys(e,t){var r=isArray$3(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=has$3(e,i)?t(e[i],e):""}var s,o="function"==typeof gOPS?gOPS(e):[];if(hasShammedSymbols){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)has$3(e,c)&&(r&&String(Number(c))===c&&c<e.length||hasShammedSymbols&&s["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?n.push(t(c,e)+": "+t(e[c],e)):n.push(c+": "+t(e[c],e))));if("function"==typeof gOPS)for(var l=0;l<o.length;l++)isEnumerable.call(e,o[l])&&n.push("["+t(o[l])+"]: "+t(e[o[l]],e));return n}var $TypeError=getIntrinsic("%TypeError%"),$WeakMap=getIntrinsic("%WeakMap%",!0),$Map=getIntrinsic("%Map%",!0),$weakMapGet=callBound("WeakMap.prototype.get",!0),$weakMapSet=callBound("WeakMap.prototype.set",!0),$weakMapHas=callBound("WeakMap.prototype.has",!0),$mapGet=callBound("Map.prototype.get",!0),$mapSet=callBound("Map.prototype.set",!0),$mapHas=callBound("Map.prototype.has",!0),listGetNode=function(e,t){for(var r,n=e;null!==(r=n.next);n=r)if(r.key===t)return n.next=r.next,r.next=e.next,e.next=r,r},listGet=function(e,t){var r=listGetNode(e,t);return r&&r.value},listSet=function(e,t,r){var n=listGetNode(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}},listHas=function(e,t){return!!listGetNode(e,t)},sideChannel=function(){var e,t,r,n={assert:function(e){if(!n.has(e))throw new $TypeError("Side channel does not contain "+objectInspect(e))},get:function(n){if($WeakMap&&n&&("object"==typeof n||"function"==typeof n)){if(e)return $weakMapGet(e,n)}else if($Map){if(t)return $mapGet(t,n)}else if(r)return listGet(r,n)},has:function(n){if($WeakMap&&n&&("object"==typeof n||"function"==typeof n)){if(e)return $weakMapHas(e,n)}else if($Map){if(t)return $mapHas(t,n)}else if(r)return listHas(r,n);return!1},set:function(n,i){$WeakMap&&n&&("object"==typeof n||"function"==typeof n)?(e||(e=new $WeakMap),$weakMapSet(e,n,i)):$Map?(t||(t=new $Map),$mapSet(t,n,i)):(r||(r={key:{},next:null}),listSet(r,n,i))}};return n},replace=String.prototype.replace,percentTwenties=/%20/g,Format={RFC1738:"RFC1738",RFC3986:"RFC3986"},formats={default:Format.RFC3986,formatters:{RFC1738:function(e){return replace.call(e,percentTwenties,"+")},RFC3986:function(e){return String(e)}},RFC1738:Format.RFC1738,RFC3986:Format.RFC3986},has$2=Object.prototype.hasOwnProperty,isArray$2=Array.isArray,hexTable=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),compactQueue=function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(isArray$2(r)){for(var n=[],i=0;i<r.length;++i)void 0!==r[i]&&n.push(r[i]);t.obj[t.prop]=n}}},arrayToObject=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},merge=function e(t,r,n){if(!r)return t;if("object"!=typeof r){if(isArray$2(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!has$2.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var i=t;return isArray$2(t)&&!isArray$2(r)&&(i=arrayToObject(t,n)),isArray$2(t)&&isArray$2(r)?(r.forEach((function(r,i){if(has$2.call(t,i)){var s=t[i];s&&"object"==typeof s&&r&&"object"==typeof r?t[i]=e(s,r,n):t.push(r)}else t[i]=r})),t):Object.keys(r).reduce((function(t,i){var s=r[i];return has$2.call(t,i)?t[i]=e(t[i],s,n):t[i]=s,t}),i)},assign=function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},decode=function(e,t,r){var n=e.replace(/\+/g," ");if("iso-8859-1"===r)return n.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(n)}catch(e){return n}},encode=function(e,t,r,n,i){if(0===e.length)return e;var s=e;if("symbol"==typeof e?s=Symbol.prototype.toString.call(e):"string"!=typeof e&&(s=String(e)),"iso-8859-1"===r)return escape(s).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<s.length;++a){var c=s.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||i===formats.RFC1738&&(40===c||41===c)?o+=s.charAt(a):c<128?o+=hexTable[c]:c<2048?o+=hexTable[192|c>>6]+hexTable[128|63&c]:c<55296||c>=57344?o+=hexTable[224|c>>12]+hexTable[128|c>>6&63]+hexTable[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&s.charCodeAt(a)),o+=hexTable[240|c>>18]+hexTable[128|c>>12&63]+hexTable[128|c>>6&63]+hexTable[128|63&c])}return o},compact=function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],n=0;n<t.length;++n)for(var i=t[n],s=i.obj[i.prop],o=Object.keys(s),a=0;a<o.length;++a){var c=o[a],l=s[c];"object"==typeof l&&null!==l&&-1===r.indexOf(l)&&(t.push({obj:s,prop:c}),r.push(l))}return compactQueue(t),e},isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},isBuffer=function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},combine=function(e,t){return[].concat(e,t)},maybeMap=function(e,t){if(isArray$2(e)){for(var r=[],n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)},utils={arrayToObject:arrayToObject,assign:assign,combine:combine,compact:compact,decode:decode,encode:encode,isBuffer:isBuffer,isRegExp:isRegExp,maybeMap:maybeMap,merge:merge},has$1=Object.prototype.hasOwnProperty,arrayPrefixGenerators={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},isArray$1=Array.isArray,push=Array.prototype.push,pushToArray=function(e,t){push.apply(e,isArray$1(t)?t:[t])},toISO=Date.prototype.toISOString,defaultFormat=formats.default,defaults$1={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:utils.encode,encodeValuesOnly:!1,format:defaultFormat,formatter:formats.formatters[defaultFormat],indices:!1,serializeDate:function(e){return toISO.call(e)},skipNulls:!1,strictNullHandling:!1},isNonNullishPrimitive=function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e},stringify=function e(t,r,n,i,s,o,a,c,l,u,p,d,h,y,f){var _=t;if(f.has(t))throw new RangeError("Cyclic object value");if("function"==typeof a?_=a(r,_):_ instanceof Date?_=u(_):"comma"===n&&isArray$1(_)&&(_=utils.maybeMap(_,(function(e){return e instanceof Date?u(e):e}))),null===_){if(i)return o&&!h?o(r,defaults$1.encoder,y,"key",p):r;_=""}if(isNonNullishPrimitive(_)||utils.isBuffer(_))return o?[d(h?r:o(r,defaults$1.encoder,y,"key",p))+"="+d(o(_,defaults$1.encoder,y,"value",p))]:[d(r)+"="+d(String(_))];var m,g=[];if(void 0===_)return g;if("comma"===n&&isArray$1(_))m=[{value:_.length>0?_.join(",")||null:void 0}];else if(isArray$1(a))m=a;else{var v=Object.keys(_);m=c?v.sort(c):v}for(var b=0;b<m.length;++b){var w=m[b],$="object"==typeof w&&void 0!==w.value?w.value:_[w];if(!s||null!==$){var S=isArray$1(_)?"function"==typeof n?n(r,w):r:r+(l?"."+w:"["+w+"]");f.set(t,!0);var k=sideChannel();pushToArray(g,e($,S,n,i,s,o,a,c,l,u,p,d,h,y,k))}}return g},normalizeStringifyOptions=function(e){if(!e)return defaults$1;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||defaults$1.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=formats.default;if(void 0!==e.format){if(!has$1.call(formats.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var n=formats.formatters[r],i=defaults$1.filter;return("function"==typeof e.filter||isArray$1(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:defaults$1.addQueryPrefix,allowDots:void 0===e.allowDots?defaults$1.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults$1.charsetSentinel,delimiter:void 0===e.delimiter?defaults$1.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:defaults$1.encode,encoder:"function"==typeof e.encoder?e.encoder:defaults$1.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:defaults$1.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:defaults$1.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:defaults$1.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults$1.strictNullHandling}},stringify_1=function(e,t){var r,n=e,i=normalizeStringifyOptions(t);"function"==typeof i.filter?n=(0,i.filter)("",n):isArray$1(i.filter)&&(r=i.filter);var s,o=[];if("object"!=typeof n||null===n)return"";s=t&&t.arrayFormat in arrayPrefixGenerators?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=arrayPrefixGenerators[s];r||(r=Object.keys(n)),i.sort&&r.sort(i.sort);for(var c=sideChannel(),l=0;l<r.length;++l){var u=r[l];i.skipNulls&&null===n[u]||pushToArray(o,stringify(n[u],u,a,i.strictNullHandling,i.skipNulls,i.encode?i.encoder:null,i.filter,i.sort,i.allowDots,i.serializeDate,i.format,i.formatter,i.encodeValuesOnly,i.charset,c))}var p=o.join(i.delimiter),d=!0===i.addQueryPrefix?"?":"";return i.charsetSentinel&&("iso-8859-1"===i.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),p.length>0?d+p:""},has=Object.prototype.hasOwnProperty,isArray=Array.isArray,defaults={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:utils.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},interpretNumericEntities=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},parseArrayValue=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},isoSentinel="utf8=%26%2310003%3B",charsetSentinel="utf8=%E2%9C%93",parseValues=function(e,t){var r,n={},i=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=t.parameterLimit===1/0?void 0:t.parameterLimit,o=i.split(t.delimiter,s),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&(o[r]===charsetSentinel?c="utf-8":o[r]===isoSentinel&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var l,u,p=o[r],d=p.indexOf("]="),h=-1===d?p.indexOf("="):d+1;-1===h?(l=t.decoder(p,defaults.decoder,c,"key"),u=t.strictNullHandling?null:""):(l=t.decoder(p.slice(0,h),defaults.decoder,c,"key"),u=utils.maybeMap(parseArrayValue(p.slice(h+1),t),(function(e){return t.decoder(e,defaults.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=interpretNumericEntities(u)),p.indexOf("[]=")>-1&&(u=isArray(u)?[u]:u),has.call(n,l)?n[l]=utils.combine(n[l],u):n[l]=u}return n},parseObject=function(e,t,r,n){for(var i=n?t:parseArrayValue(t,r),s=e.length-1;s>=0;--s){var o,a=e[s];if("[]"===a&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,l=parseInt(c,10);r.parseArrays||""!==c?!isNaN(l)&&a!==c&&String(l)===c&&l>=0&&r.parseArrays&&l<=r.arrayLimit?(o=[])[l]=i:o[c]=i:o={0:i}}i=o}return i},parseKeys=function(e,t,r,n){if(e){var i=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,s=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(i),a=o?i.slice(0,o.index):i,c=[];if(a){if(!r.plainObjects&&has.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var l=0;r.depth>0&&null!==(o=s.exec(i))&&l<r.depth;){if(l+=1,!r.plainObjects&&has.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+i.slice(o.index)+"]"),parseObject(c,t,r,n)}},normalizeParseOptions=function(e){if(!e)return defaults;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?defaults.charset:e.charset;return{allowDots:void 0===e.allowDots?defaults.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:defaults.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:defaults.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:defaults.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:defaults.comma,decoder:"function"==typeof e.decoder?e.decoder:defaults.decoder,delimiter:"string"==typeof e.delimiter||utils.isRegExp(e.delimiter)?e.delimiter:defaults.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:defaults.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:defaults.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:defaults.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:defaults.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults.strictNullHandling}},parse$1=function(e,t){var r=normalizeParseOptions(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var n="string"==typeof e?parseValues(e,r):e,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o<s.length;++o){var a=s[o],c=parseKeys(a,n[a],r,"string"==typeof e);i=utils.merge(i,c,r)}return!0===r.allowSparse?i:utils.compact(i)},lib$1={formats:formats,parse:parse$1,stringify:stringify_1};function account(e){if(e)try{return{...e,raw:()=>e,buying_power:number(e.buying_power),regt_buying_power:number(e.regt_buying_power),daytrading_buying_power:number(e.daytrading_buying_power),cash:number(e.cash),created_at:new Date(e.created_at),portfolio_value:number(e.portfolio_value),multiplier:number(e.multiplier),equity:number(e.equity),last_equity:number(e.last_equity),long_market_value:number(e.long_market_value),short_market_value:number(e.short_market_value),initial_margin:number(e.initial_margin),maintenance_margin:number(e.maintenance_margin),last_maintenance_margin:number(e.last_maintenance_margin),sma:number(e.sma),status:e.status}}catch(e){throw new Error(`Account parsing failed. ${e.message}`)}}function clock(e){if(e)try{return{raw:()=>e,timestamp:new Date(e.timestamp),is_open:e.is_open,next_open:new Date(e.next_open),next_close:new Date(e.next_close)}}catch(e){throw new Error(`Order parsing failed. ${e.message}`)}}function latestTrade(e){if(e)try{return{...e,raw:()=>e,trade:{...e.trade,t:new Date(e.trade.t)}}}catch(e){throw new Error(`Latest trade parsing failed. ${e.message}`)}}function order(e){if(e)try{return{...e,raw:()=>e,created_at:new Date(e.created_at),updated_at:new Date(e.updated_at),submitted_at:new Date(e.submitted_at),filled_at:new Date(e.filled_at),expired_at:new Date(e.expired_at),canceled_at:new Date(e.canceled_at),failed_at:new Date(e.failed_at),replaced_at:new Date(e.replaced_at),qty:number(e.qty),filled_qty:number(e.filled_qty),type:e.type,side:e.side,time_in_force:e.time_in_force,limit_price:number(e.limit_price),stop_price:number(e.stop_price),filled_avg_price:number(e.filled_avg_price),status:e.status,legs:orders(e.legs),trail_price:number(e.trail_price),trail_percent:number(e.trail_percent),hwm:number(e.hwm),order_class:e.order_class}}catch(e){throw new Error(`Order parsing failed. ${e.message}`)}}function orders(e){return e?e.map((e=>order(e))):void 0}function canceled_order(e){if(!e)return;let t=e.body;delete e.body;try{return{...e,order:{...t,raw:()=>t,created_at:new Date(t.created_at),updated_at:new Date(t.updated_at),submitted_at:new Date(t.submitted_at),filled_at:new Date(t.filled_at),expired_at:new Date(t.expired_at),canceled_at:new Date(t.canceled_at),failed_at:new Date(t.failed_at),replaced_at:new Date(t.replaced_at),qty:number(t.qty),filled_qty:number(t.filled_qty),type:t.type,side:t.side,time_in_force:t.time_in_force,limit_price:number(t.limit_price),stop_price:number(t.stop_price),filled_avg_price:number(t.filled_avg_price),status:t.status,legs:orders(t.legs),trail_price:number(t.trail_price),trail_percent:number(t.trail_percent),hwm:number(t.hwm),order_class:t.order_class}}}catch(e){throw new Error(`Order parsing failed. ${e.message}`)}}function canceled_orders(e){return e?e.map((e=>canceled_order(e))):void 0}function position(e){if(e)try{return{...e,raw:()=>e,avg_entry_price:number(e.avg_entry_price),qty:number(e.qty),side:e.side,market_value:number(e.market_value),cost_basis:number(e.cost_basis),unrealized_pl:number(e.unrealized_pl),unrealized_plpc:number(e.unrealized_plpc),unrealized_intraday_pl:number(e.unrealized_intraday_pl),unrealized_intraday_plpc:number(e.unrealized_intraday_plpc),current_price:number(e.current_price),lastday_price:number(e.lastday_price),change_today:number(e.change_today)}}catch(e){throw new Error(`Position parsing failed. ${e.message}`)}}function positions(e){return e?e.map((e=>position(e))):void 0}function tradeActivity(e){if(e)try{return{...e,raw:()=>e,cum_qty:number(e.cum_qty),leaves_qty:number(e.leaves_qty),price:number(e.price),qty:number(e.qty),side:e.side,type:e.type}}catch(e){throw new Error(`TradeActivity parsing failed. ${e.message}`)}}function nonTradeActivity(e){if(e)try{return{...e,raw:()=>e,net_amount:number(e.net_amount),qty:number(e.qty),per_share_amount:number(e.per_share_amount)}}catch(e){throw new Error(`NonTradeActivity parsing failed. ${e.message}`)}}function activities(e){if(e)try{return e.map((e=>"FILL"===e.activity_type?tradeActivity(e):nonTradeActivity(e)))}catch(e){throw new Error(`Activity parsing failed. ${e.message}`)}}function pageOfTrades(e){if(e)try{return{raw:()=>e,trades:(null==e.trades?[]:e.trades).map((e=>({raw:()=>e,...e,t:new Date(e.t)}))),symbol:e.symbol,next_page_token:e.next_page_token}}catch(e){throw new Error(`PageOfTrades parsing failed "${e.message}"`)}}function pageOfQuotes(e){if(e)try{return{raw:()=>e,quotes:(null==e.quotes?[]:e.quotes).map((e=>({raw:()=>e,...e,t:new Date(e.t)}))),symbol:e.symbol,next_page_token:e.next_page_token}}catch(e){throw new Error(`PageOfTrades parsing failed "${e.message}"`)}}function pageOfBars(e){if(e)try{return{raw:()=>e,bars:(null==e.bars?[]:e.bars).map((e=>({raw:()=>e,...e,t:new Date(e.t)}))),symbol:e.symbol,next_page_token:e.next_page_token}}catch(e){throw new Error(`PageOfTrades parsing failed "${e.message}"`)}}function snapshot(e){if(e)try{return{...e,raw:()=>e,latestTrade:e.latestTrade?{...e.latestTrade,t:new Date(e.latestTrade.t)}:null,latestQuote:e.latestQuote?{...e.latestQuote,t:new Date(e.latestQuote.t)}:null,minuteBar:e.minuteBar?{...e.minuteBar,t:new Date(e.minuteBar.t)}:null,dailyBar:e.dailyBar?{...e.dailyBar,t:new Date(e.dailyBar.t)}:null,prevDailyBar:e.prevDailyBar?{...e.prevDailyBar,t:new Date(e.prevDailyBar.t)}:null}}catch(e){throw new Error(`Snapshot parsing failed "${e.message}"`)}}function snapshots(e){let t={};for(let[r,n]of Object.entries(e))t[r]=snapshot(n);return t}function number(e){if(void 0===e||null==e)return e;const t=parseFloat(e);return Number.isNaN(t)?null:t}function trade_update(e){if(e)return{raw:()=>e,event:e.event,execution_id:e.execution_id,order:order(e.order),...e.event_id&&{event_id:number(e.event_id)},...e.at&&{at:new Date(e.at)},...e.timestamp&&{timestamp:new Date(e.timestamp)},...e.position_qty&&{position_qty:number(e.position_qty)},...e.price&&{price:number(e.price)},...e.qty&&{qty:number(e.qty)}}}var parse={account:account,activities:activities,clock:clock,nonTradeActivity:nonTradeActivity,order:order,orders:orders,canceled_orders:canceled_orders,position:position,positions:positions,tradeActivity:tradeActivity,pageOfTrades:pageOfTrades,pageOfQuotes:pageOfQuotes,pageOfBars:pageOfBars,snapshot:snapshot,snapshots:snapshots,trade_update:trade_update,latestTrade:latestTrade};function unfetch_module(e,t){return t=t||{},new Promise((function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},c=function(){return{ok:2==(i.status/100|0),statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var l in i.open(t.method||"get",e,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,r){s.push(t=t.toLowerCase()),o.push([t,r]),a[t]=a[t]?a[t]+","+r:r})),r(c())},i.onerror=n,i.withCredentials="include"==t.credentials,t.headers)i.setRequestHeader(l,t.headers[l]);i.send(t.body||null)}))}var unfetch_module$1=Object.freeze({__proto__:null,default:unfetch_module}),require$$0$2=getAugmentedNamespace(unfetch_module$1),browser$1=self.fetch||(self.fetch=require$$0$2.default||require$$0$2);const endpoints={rest:{beta:"https://data.alpaca.markets/v1beta1",account:"https://api.alpaca.markets/v2",market_data_v2:"https://data.alpaca.markets/v2",market_data_v1:"https://data.alpaca.markets/v1"},websocket:{account:"wss://api.alpaca.markets/stream",market_data:(e="iex")=>`wss://stream.data.alpaca.markets/v2/${e}`}};var load=function(e,t,r={}){var n,i,s;for(n in t)s=t[n],r[n]=null!=(i=e[n])?i:s;return r},overwrite=function(e,t,r={}){var n,i;for(n in e)i=e[n],void 0!==t[n]&&(r[n]=i);return r},parser$8={load:load,overwrite:overwrite},DLList$2;DLList$2=class{constructor(e,t){this.incr=e,this.decr=t,this._first=null,this._last=null,this.length=0}push(e){var t;this.length++,"function"==typeof this.incr&&this.incr(),t={value:e,prev:this._last,next:null},null!=this._last?(this._last.next=t,this._last=t):this._first=this._last=t}shift(){var e;if(null!=this._first)return this.length--,"function"==typeof this.decr&&this.decr(),e=this._first.value,null!=(this._first=this._first.next)?this._first.prev=null:this._last=null,e}first(){if(null!=this._first)return this._first.value}getArray(){var e,t,r;for(e=this._first,r=[];null!=e;)r.push((t=e,e=e.next,t.value));return r}forEachShift(e){var t;for(t=this.shift();null!=t;)e(t),t=this.shift()}debug(){var e,t,r,n,i;for(e=this._first,i=[];null!=e;)i.push((t=e,e=e.next,{value:t.value,prev:null!=(r=t.prev)?r.value:void 0,next:null!=(n=t.next)?n.value:void 0}));return i}};var DLList_1=DLList$2,Events$6;function asyncGeneratorStep$8(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$8(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$8(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$8(s,n,i,o,a,"throw",e)}o(void 0)}))}}Events$6=class{constructor(e){if(this.instance=e,this._events={},null!=this.instance.on||null!=this.instance.once||null!=this.instance.removeAllListeners)throw new Error("An Emitter already exists for this object");this.instance.on=(e,t)=>this._addListener(e,"many",t),this.instance.once=(e,t)=>this._addListener(e,"once",t),this.instance.removeAllListeners=(e=null)=>null!=e?delete this._events[e]:this._events={}}_addListener(e,t,r){var n;return null==(n=this._events)[e]&&(n[e]=[]),this._events[e].push({cb:r,status:t}),this.instance}listenerCount(e){return null!=this._events[e]?this._events[e].length:0}trigger(e,...t){var r=this;return _asyncToGenerator$8((function*(){var n,i;try{if("debug"!==e&&r.trigger("debug",`Event triggered: ${e}`,t),null==r._events[e])return;return r._events[e]=r._events[e].filter((function(e){return"none"!==e.status})),i=r._events[e].map(function(){var e=_asyncToGenerator$8((function*(e){var n,i;if("none"!==e.status){"once"===e.status&&(e.status="none");try{return"function"==typeof(null!=(i="function"==typeof e.cb?e.cb(...t):void 0)?i.then:void 0)?yield i:i}catch(e){return n=e,r.trigger("error",n),null}}}));return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(i)).find((function(e){return null!=e}))}catch(e){return n=e,r.trigger("error",n),null}}))()}};var Events_1=Events$6,DLList$1,Events$5,Queues$1;DLList$1=DLList_1,Events$5=Events_1,Queues$1=class{constructor(e){this.Events=new Events$5(this),this._length=0,this._lists=function(){var t,r,n;for(n=[],t=1,r=e;1<=r?t<=r:t>=r;1<=r?++t:--t)n.push(new DLList$1((()=>this.incr()),(()=>this.decr())));return n}.call(this)}incr(){if(0==this._length++)return this.Events.trigger("leftzero")}decr(){if(0==--this._length)return this.Events.trigger("zero")}push(e){return this._lists[e.options.priority].push(e)}queued(e){return null!=e?this._lists[e].length:this._length}shiftAll(e){return this._lists.forEach((function(t){return t.forEachShift(e)}))}getFirst(e=this._lists){var t,r,n;for(t=0,r=e.length;t<r;t++)if((n=e[t]).length>0)return n;return[]}shiftLastFrom(e){return this.getFirst(this._lists.slice(e).reverse()).shift()}};var Queues_1=Queues$1,BottleneckError$4;BottleneckError$4=class extends Error{};var BottleneckError_1=BottleneckError$4,BottleneckError$3,DEFAULT_PRIORITY$1,Job$1,NUM_PRIORITIES$1,parser$7;function asyncGeneratorStep$7(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$7(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$7(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$7(s,n,i,o,a,"throw",e)}o(void 0)}))}}NUM_PRIORITIES$1=10,DEFAULT_PRIORITY$1=5,parser$7=parser$8,BottleneckError$3=BottleneckError_1,Job$1=class{constructor(e,t,r,n,i,s,o,a){this.task=e,this.args=t,this.rejectOnDrop=i,this.Events=s,this._states=o,this.Promise=a,this.options=parser$7.load(r,n),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===n.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise(((e,t)=>{this._resolve=e,this._reject=t})),this.retryCount=0}_sanitizePriority(e){var t;return(t=~~e!==e?DEFAULT_PRIORITY$1:e)<0?0:t>NUM_PRIORITIES$1-1?NUM_PRIORITIES$1-1:t}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:e,message:t="This job has been dropped by Bottleneck"}={}){return!!this._states.remove(this.options.id)&&(this.rejectOnDrop&&this._reject(null!=e?e:new BottleneckError$3(t)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0)}_assertStatus(e){var t;if((t=this._states.jobStatus(this.options.id))!==e&&("DONE"!==e||null!==t))throw new BottleneckError$3(`Invalid job status ${t}, expected ${e}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(e,t){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:e,blocked:t})}doRun(){return 0===this.retryCount?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}doExecute(e,t,r,n){var i=this;return _asyncToGenerator$7((function*(){var s,o,a;0===i.retryCount?(i._assertStatus("RUNNING"),i._states.next(i.options.id)):i._assertStatus("EXECUTING"),o={args:i.args,options:i.options,retryCount:i.retryCount},i.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(i.options,i.task,...i.args):i.task(...i.args),t())return i.doDone(o),yield n(i.options,o),i._assertStatus("DONE"),i._resolve(a)}catch(e){return s=e,i._onFailure(s,o,t,r,n)}}))()}doExpire(e,t,r){var n,i;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),i={args:this.args,options:this.options,retryCount:this.retryCount},n=new BottleneckError$3(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(n,i,e,t,r)}_onFailure(e,t,r,n,i){var s=this;return _asyncToGenerator$7((function*(){var o,a;if(r())return null!=(o=yield s.Events.trigger("failed",e,t))?(a=~~o,s.Events.trigger("retry",`Retrying ${s.options.id} after ${a} ms`,t),s.retryCount++,n(a)):(s.doDone(t),yield i(s.options,t),s._assertStatus("DONE"),s._reject(e))}))()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}};var Job_1=Job$1,BottleneckError$2,LocalDatastore$1,parser$6;function asyncGeneratorStep$6(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$6(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$6(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$6(s,n,i,o,a,"throw",e)}o(void 0)}))}}parser$6=parser$8,BottleneckError$2=BottleneckError_1,LocalDatastore$1=class{constructor(e,t,r){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),parser$6.load(r,r,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var e;return null==this.heartbeat&&(null!=this.storeOptions.reservoirRefreshInterval&&null!=this.storeOptions.reservoirRefreshAmount||null!=this.storeOptions.reservoirIncreaseInterval&&null!=this.storeOptions.reservoirIncreaseAmount)?"function"==typeof(e=this.heartbeat=setInterval((()=>{var e,t,r,n,i;if(n=Date.now(),null!=this.storeOptions.reservoirRefreshInterval&&n>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=n,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),null!=this.storeOptions.reservoirIncreaseInterval&&n>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval){var s=this.storeOptions;if(e=s.reservoirIncreaseAmount,r=s.reservoirIncreaseMaximum,i=s.reservoir,this._lastReservoirIncrease=n,(t=null!=r?Math.min(e,r-i):e)>0)return this.storeOptions.reservoir+=t,this.instance._drainAll(this.computeCapacity())}}),this.heartbeatInterval)).unref?e.unref():void 0:clearInterval(this.heartbeat)}__publish__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),t.instance.Events.trigger("message",e.toString())}))()}__disconnect__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),clearInterval(t.heartbeat),t.Promise.resolve()}))()}yieldLoop(e=0){return new this.Promise((function(t,r){return setTimeout(t,e)}))}computePenalty(){var e;return null!=(e=this.storeOptions.penalty)?e:15*this.storeOptions.minTime||5e3}__updateSettings__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),parser$6.overwrite(e,e,t.storeOptions),t._startHeartbeat(),t.instance._drainAll(t.computeCapacity()),!0}))()}__running__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e._running}))()}__queued__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e.instance.queued()}))()}__done__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e._done}))()}__groupCheck__(e){var t=this;return _asyncToGenerator$6((function*(){return yield t.yieldLoop(),t._nextRequest+t.timeout<e}))()}computeCapacity(){var e,t,r=this.storeOptions;return e=r.maxConcurrent,t=r.reservoir,null!=e&&null!=t?Math.min(e-this._running,t):null!=e?e-this._running:null!=t?t:null}conditionsCheck(e){var t;return null==(t=this.computeCapacity())||e<=t}__incrementReservoir__(e){var t=this;return _asyncToGenerator$6((function*(){var r;return yield t.yieldLoop(),r=t.storeOptions.reservoir+=e,t.instance._drainAll(t.computeCapacity()),r}))()}__currentReservoir__(){var e=this;return _asyncToGenerator$6((function*(){return yield e.yieldLoop(),e.storeOptions.reservoir}))()}isBlocked(e){return this._unblockTime>=e}check(e,t){return this.conditionsCheck(e)&&this._nextRequest-t<=0}__check__(e){var t=this;return _asyncToGenerator$6((function*(){var r;return yield t.yieldLoop(),r=Date.now(),t.check(e,r)}))()}__register__(e,t,r){var n=this;return _asyncToGenerator$6((function*(){var e,r;return yield n.yieldLoop(),e=Date.now(),n.conditionsCheck(t)?(n._running+=t,null!=n.storeOptions.reservoir&&(n.storeOptions.reservoir-=t),r=Math.max(n._nextRequest-e,0),n._nextRequest=e+r+n.storeOptions.minTime,{success:!0,wait:r,reservoir:n.storeOptions.reservoir}):{success:!1}}))()}strategyIsBlock(){return 3===this.storeOptions.strategy}__submit__(e,t){var r=this;return _asyncToGenerator$6((function*(){var n,i,s;if(yield r.yieldLoop(),null!=r.storeOptions.maxConcurrent&&t>r.storeOptions.maxConcurrent)throw new BottleneckError$2(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${r.storeOptions.maxConcurrent}`);return i=Date.now(),s=null!=r.storeOptions.highWater&&e===r.storeOptions.highWater&&!r.check(t,i),(n=r.strategyIsBlock()&&(s||r.isBlocked(i)))&&(r._unblockTime=i+r.computePenalty(),r._nextRequest=r._unblockTime+r.storeOptions.minTime,r.instance._dropAllQueued()),{reachedHWM:s,blocked:n,strategy:r.storeOptions.strategy}}))()}__free__(e,t){var r=this;return _asyncToGenerator$6((function*(){return yield r.yieldLoop(),r._running-=t,r._done+=t,r.instance._drainAll(r.computeCapacity()),{running:r._running}}))()}};var LocalDatastore_1=LocalDatastore$1,require$$0$1={"blacklist_client.lua":"local blacklist = ARGV[num_static_argv + 1]\n\nif redis.call('zscore', client_last_seen_key, blacklist) then\n redis.call('zadd', client_last_seen_key, 0, blacklist)\nend\n\n\nreturn {}\n","check.lua":"local weight = tonumber(ARGV[num_static_argv + 1])\n\nlocal capacity = process_tick(now, false)['capacity']\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\n\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\n","conditions_check.lua":"local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n","current_reservoir.lua":"return process_tick(now, false)['reservoir']\n","done.lua":"process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n","free.lua":"local index = ARGV[num_static_argv + 1]\n\nredis.call('zadd', job_expirations_key, 0, index)\n\nreturn process_tick(now, false)['running']\n","get_time.lua":"redis.replicate_commands()\n\nlocal get_time = function ()\n local time = redis.call('time')\n\n return tonumber(time[1]..string.sub(time[2], 1, 3))\nend\n","group_check.lua":"return not (redis.call('exists', settings_key) == 1)\n","heartbeat.lua":"process_tick(now, true)\n","increment_reservoir.lua":"local incr = tonumber(ARGV[num_static_argv + 1])\n\nredis.call('hincrby', settings_key, 'reservoir', incr)\n\nlocal reservoir = process_tick(now, true)['reservoir']\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn reservoir\n","init.lua":"local clear = tonumber(ARGV[num_static_argv + 1])\nlocal limiter_version = ARGV[num_static_argv + 2]\nlocal num_local_argv = num_static_argv + 2\n\nif clear == 1 then\n redis.call('del', unpack(KEYS))\nend\n\nif redis.call('exists', settings_key) == 0 then\n -- Create\n local args = {'hmset', settings_key}\n\n for i = num_local_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\n end\n\n redis.call(unpack(args))\n redis.call('hmset', settings_key,\n 'nextRequest', now,\n 'lastReservoirRefresh', now,\n 'lastReservoirIncrease', now,\n 'running', 0,\n 'done', 0,\n 'unblockTime', 0,\n 'capacityPriorityCounter', 0\n )\n\nelse\n -- Apply migrations\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'version'\n )\n local id = settings[1]\n local current_version = settings[2]\n\n if current_version ~= limiter_version then\n local version_digits = {}\n for k, v in string.gmatch(current_version, \"([^.]+)\") do\n table.insert(version_digits, tonumber(k))\n end\n\n -- 2.10.0\n if version_digits[2] < 10 then\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\n redis.call('hsetnx', settings_key, 'done', 0)\n redis.call('hset', settings_key, 'version', '2.10.0')\n end\n\n -- 2.11.1\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\n redis.call('hmset', settings_key,\n 'lastReservoirRefresh', now,\n 'version', '2.11.1'\n )\n end\n end\n\n -- 2.14.0\n if version_digits[2] < 14 then\n local old_running_key = 'b_'..id..'_running'\n local old_executing_key = 'b_'..id..'_executing'\n\n if redis.call('exists', old_running_key) == 1 then\n redis.call('rename', old_running_key, job_weights_key)\n end\n if redis.call('exists', old_executing_key) == 1 then\n redis.call('rename', old_executing_key, job_expirations_key)\n end\n redis.call('hset', settings_key, 'version', '2.14.0')\n end\n\n -- 2.15.2\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\n redis.call('hset', settings_key, 'version', '2.15.2')\n end\n\n -- 2.17.0\n if version_digits[2] < 17 then\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\n redis.call('hset', settings_key, 'version', '2.17.0')\n end\n\n -- 2.18.0\n if version_digits[2] < 18 then\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\n redis.call('hset', settings_key, 'version', '2.18.0')\n end\n\n end\n\n process_tick(now, false)\nend\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","process_tick.lua":"local process_tick = function (now, always_publish)\n\n local compute_capacity = function (maxConcurrent, running, reservoir)\n if maxConcurrent ~= nil and reservoir ~= nil then\n return math.min((maxConcurrent - running), reservoir)\n elseif maxConcurrent ~= nil then\n return maxConcurrent - running\n elseif reservoir ~= nil then\n return reservoir\n else\n return nil\n end\n end\n\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'running',\n 'reservoir',\n 'reservoirRefreshInterval',\n 'reservoirRefreshAmount',\n 'lastReservoirRefresh',\n 'reservoirIncreaseInterval',\n 'reservoirIncreaseAmount',\n 'reservoirIncreaseMaximum',\n 'lastReservoirIncrease',\n 'capacityPriorityCounter',\n 'clientTimeout'\n )\n local id = settings[1]\n local maxConcurrent = tonumber(settings[2])\n local running = tonumber(settings[3])\n local reservoir = tonumber(settings[4])\n local reservoirRefreshInterval = tonumber(settings[5])\n local reservoirRefreshAmount = tonumber(settings[6])\n local lastReservoirRefresh = tonumber(settings[7])\n local reservoirIncreaseInterval = tonumber(settings[8])\n local reservoirIncreaseAmount = tonumber(settings[9])\n local reservoirIncreaseMaximum = tonumber(settings[10])\n local lastReservoirIncrease = tonumber(settings[11])\n local capacityPriorityCounter = tonumber(settings[12])\n local clientTimeout = tonumber(settings[13])\n\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n --\n -- Process 'running' changes\n --\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\n\n if #expired > 0 then\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\n\n local flush_batch = function (batch, acc)\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\n redis.call('hdel', job_weights_key, unpack(batch))\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\n redis.call('hdel', job_clients_key, unpack(batch))\n\n -- Calculate sum of removed weights\n for i = 1, #weights do\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\n end\n\n -- Calculate sum of removed weights by client\n local client_weights = {}\n for i = 1, #clients do\n local removed = tonumber(weights[i]) or 0\n if removed > 0 then\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\n end\n end\n end\n\n local acc = {\n ['total'] = 0,\n ['client_weights'] = {}\n }\n local batch_size = 1000\n\n -- Compute changes to Zsets and apply changes to Hashes\n for i = 1, #expired, batch_size do\n local batch = {}\n for j = i, math.min(i + batch_size - 1, #expired) do\n table.insert(batch, expired[j])\n end\n\n flush_batch(batch, acc)\n end\n\n -- Apply changes to Zsets\n if acc['total'] > 0 then\n redis.call('hincrby', settings_key, 'done', acc['total'])\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\n end\n\n for client, weight in pairs(acc['client_weights']) do\n redis.call('zincrby', client_running_key, -weight, client)\n end\n end\n\n --\n -- Process 'reservoir' changes\n --\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\n reservoir = reservoirRefreshAmount\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirRefresh', now\n )\n end\n\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\n local incr = reservoirIncreaseAmount * num_intervals\n if reservoirIncreaseMaximum ~= nil then\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\n end\n if incr > 0 then\n reservoir = (reservoir or 0) + incr\n end\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\n )\n end\n\n --\n -- Clear unresponsive clients\n --\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\n local unresponsive_lookup = {}\n local terminated_clients = {}\n for i = 1, #unresponsive do\n unresponsive_lookup[unresponsive[i]] = true\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\n table.insert(terminated_clients, unresponsive[i])\n end\n end\n if #terminated_clients > 0 then\n redis.call('zrem', client_running_key, unpack(terminated_clients))\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\n end\n\n --\n -- Broadcast capacity changes\n --\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\n -- always_publish or was not unlimited, now unlimited\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\n -- capacity was increased\n -- send the capacity message to the limiter having the lowest number of running jobs\n -- the tiebreaker is the limiter having not registered a job in the longest time\n\n local lowest_concurrency_value = nil\n local lowest_concurrency_clients = {}\n local lowest_concurrency_last_registered = {}\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\n\n for i = 1, #client_concurrencies, 2 do\n local client = client_concurrencies[i]\n local concurrency = tonumber(client_concurrencies[i+1])\n\n if (\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\n ) and (\n not unresponsive_lookup[client]\n ) and (\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\n ) then\n lowest_concurrency_value = concurrency\n table.insert(lowest_concurrency_clients, client)\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\n table.insert(lowest_concurrency_last_registered, last_registered)\n end\n end\n\n if #lowest_concurrency_clients > 0 then\n local position = 1\n local earliest = lowest_concurrency_last_registered[1]\n\n for i,v in ipairs(lowest_concurrency_last_registered) do\n if v < earliest then\n position = i\n earliest = v\n end\n end\n\n local next_client = lowest_concurrency_clients[position]\n redis.call('publish', 'b_'..id,\n 'capacity-priority:'..(final_capacity or '')..\n ':'..next_client..\n ':'..capacityPriorityCounter\n )\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\n else\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n end\n end\n\n return {\n ['capacity'] = final_capacity,\n ['running'] = running,\n ['reservoir'] = reservoir\n }\nend\n","queued.lua":"local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\n\nlocal sum = 0\nfor i = 1, #client_queued do\n sum = sum + tonumber(client_queued[i])\nend\n\nreturn sum\n","refresh_expiration.lua":"local refresh_expiration = function (now, nextRequest, groupTimeout)\n\n if groupTimeout ~= nil then\n local ttl = (nextRequest + groupTimeout) - now\n\n for i = 1, #KEYS do\n redis.call('pexpire', KEYS[i], ttl)\n end\n end\n\nend\n","refs.lua":"local settings_key = KEYS[1]\nlocal job_weights_key = KEYS[2]\nlocal job_expirations_key = KEYS[3]\nlocal job_clients_key = KEYS[4]\nlocal client_running_key = KEYS[5]\nlocal client_num_queued_key = KEYS[6]\nlocal client_last_registered_key = KEYS[7]\nlocal client_last_seen_key = KEYS[8]\n\nlocal now = tonumber(ARGV[1])\nlocal client = ARGV[2]\n\nlocal num_static_argv = 2\n","register.lua":"local index = ARGV[num_static_argv + 1]\nlocal weight = tonumber(ARGV[num_static_argv + 2])\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\n\nlocal state = process_tick(now, false)\nlocal capacity = state['capacity']\nlocal reservoir = state['reservoir']\n\nlocal settings = redis.call('hmget', settings_key,\n 'nextRequest',\n 'minTime',\n 'groupTimeout'\n)\nlocal nextRequest = tonumber(settings[1])\nlocal minTime = tonumber(settings[2])\nlocal groupTimeout = tonumber(settings[3])\n\nif conditions_check(capacity, weight) then\n\n redis.call('hincrby', settings_key, 'running', weight)\n redis.call('hset', job_weights_key, index, weight)\n if expiration ~= nil then\n redis.call('zadd', job_expirations_key, now + expiration, index)\n end\n redis.call('hset', job_clients_key, index, client)\n redis.call('zincrby', client_running_key, weight, client)\n redis.call('hincrby', client_num_queued_key, client, -1)\n redis.call('zadd', client_last_registered_key, now, client)\n\n local wait = math.max(nextRequest - now, 0)\n local newNextRequest = now + wait + minTime\n\n if reservoir == nil then\n redis.call('hset', settings_key,\n 'nextRequest', newNextRequest\n )\n else\n reservoir = reservoir - weight\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'nextRequest', newNextRequest\n )\n end\n\n refresh_expiration(now, newNextRequest, groupTimeout)\n\n return {true, wait, reservoir}\n\nelse\n return {false}\nend\n","register_client.lua":"local queued = tonumber(ARGV[num_static_argv + 1])\n\n-- Could have been re-registered concurrently\nif not redis.call('zscore', client_last_seen_key, client) then\n redis.call('zadd', client_running_key, 0, client)\n redis.call('hset', client_num_queued_key, client, queued)\n redis.call('zadd', client_last_registered_key, 0, client)\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n\nreturn {}\n","running.lua":"return process_tick(now, false)['running']\n","submit.lua":"local queueLength = tonumber(ARGV[num_static_argv + 1])\nlocal weight = tonumber(ARGV[num_static_argv + 2])\n\nlocal capacity = process_tick(now, false)['capacity']\n\nlocal settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'highWater',\n 'nextRequest',\n 'strategy',\n 'unblockTime',\n 'penalty',\n 'minTime',\n 'groupTimeout'\n)\nlocal id = settings[1]\nlocal maxConcurrent = tonumber(settings[2])\nlocal highWater = tonumber(settings[3])\nlocal nextRequest = tonumber(settings[4])\nlocal strategy = tonumber(settings[5])\nlocal unblockTime = tonumber(settings[6])\nlocal penalty = tonumber(settings[7])\nlocal minTime = tonumber(settings[8])\nlocal groupTimeout = tonumber(settings[9])\n\nif maxConcurrent ~= nil and weight > maxConcurrent then\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\nend\n\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\n and not (\n conditions_check(capacity, weight)\n and nextRequest - now <= 0\n )\n)\n\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\n\nif blocked then\n local computedPenalty = penalty\n if computedPenalty == nil then\n if minTime == 0 then\n computedPenalty = 5000\n else\n computedPenalty = 15 * minTime\n end\n end\n\n local newNextRequest = now + computedPenalty + minTime\n\n redis.call('hmset', settings_key,\n 'unblockTime', now + computedPenalty,\n 'nextRequest', newNextRequest\n )\n\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\n local queued_reset = {}\n for i = 1, #clients_queued_reset do\n table.insert(queued_reset, clients_queued_reset[i])\n table.insert(queued_reset, 0)\n end\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\n\n redis.call('publish', 'b_'..id, 'blocked:')\n\n refresh_expiration(now, newNextRequest, groupTimeout)\nend\n\nif not blocked and not reachedHWM then\n redis.call('hincrby', client_num_queued_key, client, 1)\nend\n\nreturn {reachedHWM, blocked, strategy}\n","update_settings.lua":"local args = {'hmset', settings_key}\n\nfor i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\nend\n\nredis.call(unpack(args))\n\nprocess_tick(now, true)\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","validate_client.lua":"if not redis.call('zscore', client_last_seen_key, client) then\n return redis.error_reply('UNKNOWN_CLIENT')\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n","validate_keys.lua":"if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"},Scripts$3=createCommonjsModule((function(e,t){var r,n,i;r={refs:(n=require$$0$1)["refs.lua"],validate_keys:n["validate_keys.lua"],validate_client:n["validate_client.lua"],refresh_expiration:n["refresh_expiration.lua"],process_tick:n["process_tick.lua"],conditions_check:n["conditions_check.lua"],get_time:n["get_time.lua"]},t.allKeys=function(e){return[`b_${e}_settings`,`b_${e}_job_weights`,`b_${e}_job_expirations`,`b_${e}_job_clients`,`b_${e}_client_running`,`b_${e}_client_num_queued`,`b_${e}_client_last_registered`,`b_${e}_client_last_seen`]},i={init:{keys:t.allKeys,headers:["process_tick"],refresh_expiration:!0,code:n["init.lua"]},group_check:{keys:t.allKeys,headers:[],refresh_expiration:!1,code:n["group_check.lua"]},register_client:{keys:t.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:n["register_client.lua"]},blacklist_client:{keys:t.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:n["blacklist_client.lua"]},heartbeat:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["heartbeat.lua"]},update_settings:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["update_settings.lua"]},running:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["running.lua"]},queued:{keys:t.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:n["queued.lua"]},done:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["done.lua"]},check:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:n["check.lua"]},submit:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:n["submit.lua"]},register:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:n["register.lua"]},free:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["free.lua"]},current_reservoir:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:n["current_reservoir.lua"]},increment_reservoir:{keys:t.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:n["increment_reservoir.lua"]}},t.names=Object.keys(i),t.keys=function(e,t){return i[e].keys(t)},t.payload=function(e){var t;return t=i[e],Array.prototype.concat(r.refs,t.headers.map((function(e){return r[e]})),t.refresh_expiration?r.refresh_expiration:"",t.code).join("\n")}})),Events$4,RedisConnection$2,Scripts$2,parser$5;function asyncGeneratorStep$5(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$5(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$5(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$5(s,n,i,o,a,"throw",e)}o(void 0)}))}}parser$5=parser$8,Events$4=Events_1,Scripts$2=Scripts$3,RedisConnection$2=function(){class RedisConnection{constructor(options={}){parser$5.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events$4(this)),this.terminated=!1,null==this.client&&(this.client=this.Redis.createClient(this.clientOptions)),this.subscriber=this.client.duplicate(),this.limiters={},this.shas={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then((()=>this._loadScripts())).then((()=>({client:this.client,subscriber:this.subscriber})))}_setup(e,t){return e.setMaxListeners(0),new this.Promise(((r,n)=>(e.on("error",(e=>this.Events.trigger("error",e))),t&&e.on("message",((e,t)=>{var r;return null!=(r=this.limiters[e])?r._store.onMessage(e,t):void 0})),e.ready?r():e.once("ready",r))))}_loadScript(e){return new this.Promise(((t,r)=>{var n;return n=Scripts$2.payload(e),this.client.multi([["script","load",n]]).exec(((n,i)=>null!=n?r(n):(this.shas[e]=i[0],t(i[0]))))}))}_loadScripts(){return this.Promise.all(Scripts$2.names.map((e=>this._loadScript(e))))}__runCommand__(e){var t=this;return _asyncToGenerator$5((function*(){return yield t.ready,new t.Promise(((r,n)=>t.client.multi([e]).exec_atomic((function(e,t){return null!=e?n(e):r(t[0])}))))}))()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map((t=>new this.Promise(((r,n)=>{var i;return i=n=>{if(n===t)return this.subscriber.removeListener("subscribe",i),this.limiters[t]=e,r()},this.subscriber.on("subscribe",i),this.subscriber.subscribe(t)})))))}__removeLimiter__(e){var t=this;return this.Promise.all([e.channel(),e.channel_client()].map(function(){var e=_asyncToGenerator$5((function*(e){return t.terminated||(yield new t.Promise(((r,n)=>t.subscriber.unsubscribe(e,(function(t,i){return null!=t?n(t):i===e?r():void 0}))))),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}()))}__scriptArgs__(e,t,r,n){var i;return i=Scripts$2.keys(e,t),[this.shas[e],i.length].concat(i,r,n)}__scriptFn__(e){return this.client.evalsha.bind(this.client)}disconnect(e=!0){var t,r,n,i;for(t=0,n=(i=Object.keys(this.limiters)).length;t<n;t++)r=i[t],clearInterval(this.limiters[r]._store.heartbeat);return this.limiters={},this.terminated=!0,this.client.end(e),this.subscriber.end(e),this.Promise.resolve()}}return RedisConnection.prototype.datastore="redis",RedisConnection.prototype.defaults={Redis:null,clientOptions:{},client:null,Promise:Promise,Events:null},RedisConnection}.call(void 0);var RedisConnection_1=RedisConnection$2,Events$3,IORedisConnection$2,Scripts$1,parser$4;function _slicedToArray$3(e,t){return _arrayWithHoles$3(e)||_iterableToArrayLimit$3(e,t)||_nonIterableRest$3()}function _nonIterableRest$3(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$3(e,t){var r=[],n=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(n=(o=a.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{n||null==a.return||a.return()}finally{if(i)throw s}}return r}function _arrayWithHoles$3(e){if(Array.isArray(e))return e}function asyncGeneratorStep$4(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$4(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$4(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$4(s,n,i,o,a,"throw",e)}o(void 0)}))}}parser$4=parser$8,Events$3=Events_1,Scripts$1=Scripts$3,IORedisConnection$2=function(){class IORedisConnection{constructor(options={}){parser$4.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("ioredis")),null==this.Events&&(this.Events=new Events$3(this)),this.terminated=!1,null!=this.clusterNodes?(this.client=new this.Redis.Cluster(this.clusterNodes,this.clientOptions),this.subscriber=new this.Redis.Cluster(this.clusterNodes,this.clientOptions)):null!=this.client&&null==this.client.duplicate?this.subscriber=new this.Redis.Cluster(this.client.startupNodes,this.client.options):(null==this.client&&(this.client=new this.Redis(this.clientOptions)),this.subscriber=this.client.duplicate()),this.limiters={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then((()=>(this._loadScripts(),{client:this.client,subscriber:this.subscriber})))}_setup(e,t){return e.setMaxListeners(0),new this.Promise(((r,n)=>(e.on("error",(e=>this.Events.trigger("error",e))),t&&e.on("message",((e,t)=>{var r;return null!=(r=this.limiters[e])?r._store.onMessage(e,t):void 0})),"ready"===e.status?r():e.once("ready",r))))}_loadScripts(){return Scripts$1.names.forEach((e=>this.client.defineCommand(e,{lua:Scripts$1.payload(e)})))}__runCommand__(e){var t=this;return _asyncToGenerator$4((function*(){yield t.ready;var r=_slicedToArray$3(yield t.client.pipeline([e]).exec(),1);return _slicedToArray$3(r[0],2)[1]}))()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map((t=>new this.Promise(((r,n)=>this.subscriber.subscribe(t,(()=>(this.limiters[t]=e,r()))))))))}__removeLimiter__(e){var t=this;return[e.channel(),e.channel_client()].forEach(function(){var e=_asyncToGenerator$4((function*(e){return t.terminated||(yield t.subscriber.unsubscribe(e)),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}())}__scriptArgs__(e,t,r,n){var i;return[(i=Scripts$1.keys(e,t)).length].concat(i,r,n)}__scriptFn__(e){return this.client[e].bind(this.client)}disconnect(e=!0){var t,r,n,i;for(t=0,n=(i=Object.keys(this.limiters)).length;t<n;t++)r=i[t],clearInterval(this.limiters[r]._store.heartbeat);return this.limiters={},this.terminated=!0,e?this.Promise.all([this.client.quit(),this.subscriber.quit()]):(this.client.disconnect(),this.subscriber.disconnect(),this.Promise.resolve())}}return IORedisConnection.prototype.datastore="ioredis",IORedisConnection.prototype.defaults={Redis:null,clientOptions:{},clusterNodes:null,client:null,Promise:Promise,Events:null},IORedisConnection}.call(void 0);var IORedisConnection_1=IORedisConnection$2,BottleneckError$1,IORedisConnection$1,RedisConnection$1,RedisDatastore$1,parser$3;function _slicedToArray$2(e,t){return _arrayWithHoles$2(e)||_iterableToArrayLimit$2(e,t)||_nonIterableRest$2()}function _nonIterableRest$2(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$2(e,t){var r=[],n=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(n=(o=a.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{n||null==a.return||a.return()}finally{if(i)throw s}}return r}function _arrayWithHoles$2(e){if(Array.isArray(e))return e}function asyncGeneratorStep$3(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$3(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$3(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$3(s,n,i,o,a,"throw",e)}o(void 0)}))}}parser$3=parser$8,BottleneckError$1=BottleneckError_1,RedisConnection$1=RedisConnection_1,IORedisConnection$1=IORedisConnection_1,RedisDatastore$1=class{constructor(e,t,r){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),parser$3.load(r,r,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=null!=this.connection,null==this.connection&&(this.connection="redis"===this.instance.datastore?new RedisConnection$1({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):"ioredis"===this.instance.datastore?new IORedisConnection$1({Redis:this.Redis,clientOptions:this.clientOptions,clusterNodes:this.clusterNodes,Promise:this.Promise,Events:this.instance.Events}):void 0),this.instance.connection=this.connection,this.instance.datastore=this.connection.datastore,this.ready=this.connection.ready.then((e=>(this.clients=e,this.runScript("init",this.prepareInitSettings(this.clearDatastore))))).then((()=>this.connection.__addLimiter__(this.instance))).then((()=>this.runScript("register_client",[this.instance.queued()]))).then((()=>{var e;return"function"==typeof(e=this.heartbeat=setInterval((()=>this.runScript("heartbeat",[]).catch((e=>this.instance.Events.trigger("error",e)))),this.heartbeatInterval)).unref&&e.unref(),this.clients}))}__publish__(e){var t=this;return _asyncToGenerator$3((function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)}))()}onMessage(e,t){var r=this;return _asyncToGenerator$3((function*(){var e,n,i,s,o,a,c,l,u,p;try{c=t.indexOf(":");var d=[t.slice(0,c),t.slice(c+1)];if(i=d[1],"capacity"===(p=d[0]))return yield r.instance._drainAll(i.length>0?~~i:void 0);if("capacity-priority"===p){var h=_slicedToArray$2(i.split(":"),3);return u=h[0],l=h[1],n=h[2],e=u.length>0?~~u:void 0,l===r.clientId?(s=yield r.instance._drainAll(e),a=null!=e?e-(s||0):"",yield r.clients.client.publish(r.instance.channel(),`capacity-priority:${a}::${n}`)):""===l?(clearTimeout(r.capacityPriorityCounters[n]),delete r.capacityPriorityCounters[n],r.instance._drainAll(e)):r.capacityPriorityCounters[n]=setTimeout(_asyncToGenerator$3((function*(){var t;try{return delete r.capacityPriorityCounters[n],yield r.runScript("blacklist_client",[l]),yield r.instance._drainAll(e)}catch(e){return t=e,r.instance.Events.trigger("error",t)}})),1e3)}if("message"===p)return r.instance.Events.trigger("message",i);if("blocked"===p)return yield r.instance._dropAllQueued()}catch(e){return o=e,r.instance.Events.trigger("error",o)}}))()}__disconnect__(e){return clearInterval(this.heartbeat),this.sharedConnection?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(e)}runScript(e,t){var r=this;return _asyncToGenerator$3((function*(){return"init"!==e&&"register_client"!==e&&(yield r.ready),new r.Promise(((n,i)=>{var s,o;return s=[Date.now(),r.clientId].concat(t),r.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,s),o=r.connection.__scriptArgs__(e,r.originalId,s,(function(e,t){return null!=e?i(e):n(t)})),r.connection.__scriptFn__(e)(...o)})).catch((n=>"SETTINGS_KEY_NOT_FOUND"===n.message?"heartbeat"===e?r.Promise.resolve():r.runScript("init",r.prepareInitSettings(!1)).then((()=>r.runScript(e,t))):"UNKNOWN_CLIENT"===n.message?r.runScript("register_client",[r.instance.queued()]).then((()=>r.runScript(e,t))):r.Promise.reject(n)))}))()}prepareArray(e){var t,r,n,i;for(n=[],t=0,r=e.length;t<r;t++)i=e[t],n.push(null!=i?i.toString():"");return n}prepareObject(e){var t,r,n;for(r in t=[],e)n=e[r],t.push(r,null!=n?n.toString():"");return t}prepareInitSettings(e){var t;return(t=this.prepareObject(Object.assign({},this.storeOptions,{id:this.originalId,version:this.instance.version,groupTimeout:this.timeout,clientTimeout:this.clientTimeout}))).unshift(e?1:0,this.instance.version),t}convertBool(e){return!!e}__updateSettings__(e){var t=this;return _asyncToGenerator$3((function*(){return yield t.runScript("update_settings",t.prepareObject(e)),parser$3.overwrite(e,e,t.storeOptions)}))()}__running__(){return this.runScript("running",[])}__queued__(){return this.runScript("queued",[])}__done__(){return this.runScript("done",[])}__groupCheck__(){var e=this;return _asyncToGenerator$3((function*(){return e.convertBool(yield e.runScript("group_check",[]))}))()}__incrementReservoir__(e){return this.runScript("increment_reservoir",[e])}__currentReservoir__(){return this.runScript("current_reservoir",[])}__check__(e){var t=this;return _asyncToGenerator$3((function*(){return t.convertBool(yield t.runScript("check",t.prepareArray([e])))}))()}__register__(e,t,r){var n=this;return _asyncToGenerator$3((function*(){var i,s,o,a=_slicedToArray$2(yield n.runScript("register",n.prepareArray([e,t,r])),3);return s=a[0],o=a[1],i=a[2],{success:n.convertBool(s),wait:o,reservoir:i}}))()}__submit__(e,t){var r=this;return _asyncToGenerator$3((function*(){var n,i,s,o,a;try{var c=_slicedToArray$2(yield r.runScript("submit",r.prepareArray([e,t])),3);return o=c[0],n=c[1],a=c[2],{reachedHWM:r.convertBool(o),blocked:r.convertBool(n),strategy:a}}catch(e){if(0===(i=e).message.indexOf("OVERWEIGHT")){var l=_slicedToArray$2(i.message.split(":"),3);throw t=l[1],s=l[2],new BottleneckError$1(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${s}`)}throw i}}))()}__free__(e,t){var r=this;return _asyncToGenerator$3((function*(){return{running:yield r.runScript("free",r.prepareArray([e]))}}))()}};var RedisDatastore_1=RedisDatastore$1,BottleneckError,States$1;BottleneckError=BottleneckError_1,States$1=class{constructor(e){this.status=e,this._jobs={},this.counts=this.status.map((function(){return 0}))}next(e){var t,r;return r=(t=this._jobs[e])+1,null!=t&&r<this.status.length?(this.counts[t]--,this.counts[r]++,this._jobs[e]++):null!=t?(this.counts[t]--,delete this._jobs[e]):void 0}start(e){return 0,this._jobs[e]=0,this.counts[0]++}remove(e){var t;return null!=(t=this._jobs[e])&&(this.counts[t]--,delete this._jobs[e]),null!=t}jobStatus(e){var t;return null!=(t=this.status[this._jobs[e]])?t:null}statusJobs(e){var t,r,n,i;if(null!=e){if((r=this.status.indexOf(e))<0)throw new BottleneckError(`status must be one of ${this.status.join(", ")}`);for(t in i=[],n=this._jobs)n[t]===r&&i.push(t);return i}return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce(((e,t,r)=>(e[this.status[r]]=t,e)),{})}};var States_1=States$1,DLList,Sync$1;function asyncGeneratorStep$2(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$2(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$2(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$2(s,n,i,o,a,"throw",e)}o(void 0)}))}}DLList=DLList_1,Sync$1=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new DLList}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return _asyncToGenerator$2((function*(){var t,r,n,i,s,o,a;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return a=c.task,t=c.args,s=c.resolve,i=c.reject,r=yield _asyncToGenerator$2((function*(){try{return o=yield a(...t),function(){return s(o)}}catch(e){return n=e,function(){return i(n)}}}))(),e._running--,e._tryToRun(),r()}}))()}schedule(e,...t){var r,n,i;return i=n=null,r=new this.Promise((function(e,t){return i=e,n=t})),this._queue.push({task:e,args:t,resolve:i,reject:n}),this._tryToRun(),r}};var Sync_1=Sync$1,version="2.19.5",require$$8={version:version},require$$0=Bottleneck_1,Events$2,Group,IORedisConnection,RedisConnection,Scripts,parser$2;function _slicedToArray$1(e,t){return _arrayWithHoles$1(e)||_iterableToArrayLimit$1(e,t)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit$1(e,t){var r=[],n=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(n=(o=a.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{n||null==a.return||a.return()}finally{if(i)throw s}}return r}function _arrayWithHoles$1(e){if(Array.isArray(e))return e}function asyncGeneratorStep$1(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator$1(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep$1(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep$1(s,n,i,o,a,"throw",e)}o(void 0)}))}}parser$2=parser$8,Events$2=Events_1,RedisConnection=RedisConnection_1,IORedisConnection=IORedisConnection_1,Scripts=Scripts$3,Group=function(){class e{constructor(e={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=e,parser$2.load(this.limiterOptions,this.defaults,this),this.Events=new Events$2(this),this.instances={},this.Bottleneck=require$$0,this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new RedisConnection(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new IORedisConnection(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(e=""){var t;return null!=(t=this.instances[e])?t:(()=>{var t;return t=this.instances[e]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${e}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",t,e),t})()}deleteKey(e=""){var t=this;return _asyncToGenerator$1((function*(){var r,n;return n=t.instances[e],t.connection&&(r=yield t.connection.__runCommand__(["del",...Scripts.allKeys(`${t.id}-${e}`)])),null!=n&&(delete t.instances[e],yield n.disconnect()),null!=n||r>0}))()}limiters(){var e,t,r,n;for(e in r=[],t=this.instances)n=t[e],r.push({key:e,limiter:n});return r}keys(){return Object.keys(this.instances)}clusterKeys(){var e=this;return _asyncToGenerator$1((function*(){var t,r,n,i,s,o,a,c;if(null==e.connection)return e.Promise.resolve(e.keys());for(o=[],t=null,c=`b_${e.id}-`.length,r="_settings".length;0!==t;){var l=_slicedToArray$1(yield e.connection.__runCommand__(["scan",null!=t?t:0,"match",`b_${e.id}-*_settings`,"count",1e4]),2);for(t=~~l[0],i=0,a=(n=l[1]).length;i<a;i++)s=n[i],o.push(s.slice(c,-r))}return o}))()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(_asyncToGenerator$1((function*(){var e,r,n,i,s,o;for(r in s=Date.now(),i=[],n=t.instances){o=n[r];try{(yield o._store.__groupCheck__(s))?i.push(t.deleteKey(r)):i.push(void 0)}catch(t){e=t,i.push(o.Events.trigger("error",e))}}return i})),this.timeout/2)).unref?e.unref():void 0}updateSettings(e={}){if(parser$2.overwrite(e,this.defaults,this),parser$2.overwrite(e,e,this.limiterOptions),null!=e.timeout)return this._startAutoCleanup()}disconnect(e=!0){var t;if(!this.sharedConnection)return null!=(t=this.connection)?t.disconnect(e):void 0}}return e.prototype.defaults={timeout:3e5,connection:null,Promise:Promise,id:"group-key"},e}.call(void 0);var Group_1=Group,Batcher,Events$1,parser$1;parser$1=parser$8,Events$1=Events_1,Batcher=function(){class e{constructor(e={}){this.options=e,parser$1.load(this.options,this.defaults,this),this.Events=new Events$1(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise(((e,t)=>this._resolve=e))}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(e){var t;return this._arr.push(e),t=this._promise,this._arr.length===this.maxSize?this._flush():null!=this.maxTime&&1===this._arr.length&&(this._timeout=setTimeout((()=>this._flush()),this.maxTime)),t}}return e.prototype.defaults={maxTime:null,maxSize:null,Promise:Promise},e}.call(void 0);var Batcher_1=Batcher;function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _iterableToArrayLimit(e,t){var r=[],n=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(n=(o=a.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{n||null==a.return||a.return()}finally{if(i)throw s}}return r}function _toArray(e){return _arrayWithHoles(e)||_iterableToArray(e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,i)}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var s=e.apply(t,r);function o(e){asyncGeneratorStep(s,n,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,n,i,o,a,"throw",e)}o(void 0)}))}}var Bottleneck,DEFAULT_PRIORITY,Events,Job,LocalDatastore,NUM_PRIORITIES,Queues,RedisDatastore,States,Sync,parser,splice=[].splice;NUM_PRIORITIES=10,DEFAULT_PRIORITY=5,parser=parser$8,Queues=Queues_1,Job=Job_1,LocalDatastore=LocalDatastore_1,RedisDatastore=RedisDatastore_1,Events=Events_1,States=States_1,Sync=Sync_1,Bottleneck=function(){class e{constructor(t={},...r){var n,i;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(t,r),parser.load(t,this.instanceDefaults,this),this._queues=new Queues(NUM_PRIORITIES),this._scheduled={},this._states=new States(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new Events(this),this._submitLock=new Sync("submit",this.Promise),this._registerLock=new Sync("register",this.Promise),i=parser.load(t,this.storeDefaults,{}),this._store=function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return n=parser.load(t,this.redisStoreDefaults,{}),new RedisDatastore(this,i,n);if("local"===this.datastore)return n=parser.load(t,this.localStoreDefaults,{}),new LocalDatastore(this,i,n);throw new e.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}.call(this),this._queues.on("leftzero",(()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.ref?e.ref():void 0})),this._queues.on("zero",(()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.unref?e.unref():void 0}))}_validateOptions(t,r){if(null==t||"object"!=typeof t||0!==r.length)throw new e.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(e){return this._store.__publish__(e)}disconnect(e=!0){return this._store.__disconnect__(e)}chain(e){return this._limiter=e,this}queued(e){return this._queues.queued(e)}clusterQueued(){return this._store.__queued__()}empty(){return 0===this.queued()&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(e){return this._states.jobStatus(e)}jobs(e){return this._states.statusJobs(e)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(e=1){return this._store.__check__(e)}_clearGlobalState(e){return null!=this._scheduled[e]&&(clearTimeout(this._scheduled[e].expiration),delete this._scheduled[e],!0)}_free(e,t,r,n){var i=this;return _asyncToGenerator((function*(){var t,s;try{if(s=(yield i._store.__free__(e,r.weight)).running,i.Events.trigger("debug",`Freed ${r.id}`,n),0===s&&i.empty())return i.Events.trigger("idle")}catch(e){return t=e,i.Events.trigger("error",t)}}))()}_run(e,t,r){var n,i,s;return t.doRun(),n=this._clearGlobalState.bind(this,e),s=this._run.bind(this,e,t),i=this._free.bind(this,e,t),this._scheduled[e]={timeout:setTimeout((()=>t.doExecute(this._limiter,n,s,i)),r),expiration:null!=t.options.expiration?setTimeout((function(){return t.doExpire(n,s,i)}),r+t.options.expiration):void 0,job:t}}_drainOne(e){return this._registerLock.schedule((()=>{var t,r,n,i,s;if(0===this.queued())return this.Promise.resolve(null);s=this._queues.getFirst();var o=n=s.first();return i=o.options,t=o.args,null!=e&&i.weight>e?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${i.id}`,{args:t,options:i}),r=this._randomIndex(),this._store.__register__(r,i.weight,i.expiration).then((({success:e,wait:o,reservoir:a})=>{var c;return this.Events.trigger("debug",`Drained ${i.id}`,{success:e,args:t,options:i}),e?(s.shift(),(c=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",c),this._run(r,n,o),this.Promise.resolve(i.weight)):this.Promise.resolve(null)})))}))}_drainAll(e,t=0){return this._drainOne(e).then((r=>{var n;return null!=r?(n=null!=e?e-r:e,this._drainAll(n,t+r)):this.Promise.resolve(t)})).catch((e=>this.Events.trigger("error",e)))}_dropAllQueued(e){return this._queues.shiftAll((function(t){return t.doDrop({message:e})}))}stop(t={}){var r,n;return t=parser.load(t,this.stopDefaults),n=e=>{var t;return t=()=>{var t;return(t=this._states.counts)[0]+t[1]+t[2]+t[3]===e},new this.Promise(((e,r)=>t()?e():this.on("done",(()=>{if(t())return this.removeAllListeners("done"),e()}))))},r=t.dropWaitingJobs?(this._run=function(e,r){return r.doDrop({message:t.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule((()=>this._submitLock.schedule((()=>{var e,r,i;for(e in r=this._scheduled)i=r[e],"RUNNING"===this.jobStatus(i.job.options.id)&&(clearTimeout(i.timeout),clearTimeout(i.expiration),i.job.doDrop({message:t.dropErrorMessage}));return this._dropAllQueued(t.dropErrorMessage),n(0)}))))):this.schedule({priority:NUM_PRIORITIES-1,weight:0},(()=>n(1))),this._receive=function(r){return r._reject(new e.prototype.BottleneckError(t.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new e.prototype.BottleneckError("stop() has already been called")),r}_addToQueue(t){var r=this;return _asyncToGenerator((function*(){var n,i,s,o,a,c,l;n=t.args,o=t.options;try{var u=yield r._store.__submit__(r.queued(),o.weight);a=u.reachedHWM,i=u.blocked,l=u.strategy}catch(e){return s=e,r.Events.trigger("debug",`Could not queue ${o.id}`,{args:n,options:o,error:s}),t.doDrop({error:s}),!1}return i?(t.doDrop(),!0):a&&(null!=(c=l===e.prototype.strategy.LEAK?r._queues.shiftLastFrom(o.priority):l===e.prototype.strategy.OVERFLOW_PRIORITY?r._queues.shiftLastFrom(o.priority+1):l===e.prototype.strategy.OVERFLOW?t:void 0)&&c.doDrop(),null==c||l===e.prototype.strategy.OVERFLOW)?(null==c&&t.doDrop(),a):(t.doQueue(a,i),r._queues.push(t),yield r._drainAll(),a)}))()}_receive(t){return null!=this._states.jobStatus(t.options.id)?(t._reject(new e.prototype.BottleneckError(`A job with the same id already exists (id=${t.options.id})`)),!1):(t.doReceive(),this._submitLock.schedule(this._addToQueue,t))}submit(...e){var t,r,n,i,s,o,a,c;"function"==typeof e[0]?(s=_toArray(e),r=s[0],e=s.slice(1),o=_slicedToArray(splice.call(e,-1),1),t=o[0],i=parser.load({},this.jobDefaults)):(i=(a=_toArray(e))[0],r=a[1],e=a.slice(2),c=_slicedToArray(splice.call(e,-1),1),t=c[0],i=parser.load(i,this.jobDefaults));return(n=new Job(((...e)=>new this.Promise((function(t,n){return r(...e,(function(...e){return(null!=e[0]?n:t)(e)}))}))),e,i,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise)).promise.then((function(e){return"function"==typeof t?t(...e):void 0})).catch((function(e){return Array.isArray(e)?"function"==typeof t?t(...e):void 0:"function"==typeof t?t(e):void 0})),this._receive(n)}schedule(...e){var t,r,n;if("function"==typeof e[0]){var i=_toArray(e);n=i[0],e=i.slice(1),r={}}else{var s=_toArray(e);r=s[0],n=s[1],e=s.slice(2)}return t=new Job(n,e,r,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(t),t.promise}wrap(e){var t,r;return t=this.schedule.bind(this),(r=function(...r){return t(e.bind(this),...r)}).withOptions=function(r,...n){return t(r,e,...n)},r}updateSettings(e={}){var t=this;return _asyncToGenerator((function*(){return yield t._store.__updateSettings__(parser.overwrite(e,t.storeDefaults)),parser.overwrite(e,t.instanceDefaults,t),t}))()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(e=0){return this._store.__incrementReservoir__(e)}}return e.default=e,e.Events=Events,e.version=e.prototype.version=require$$8.version,e.strategy=e.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},e.BottleneckError=e.prototype.BottleneckError=BottleneckError_1,e.Group=e.prototype.Group=Group_1,e.RedisConnection=e.prototype.RedisConnection=RedisConnection_1,e.IORedisConnection=e.prototype.IORedisConnection=IORedisConnection_1,e.Batcher=e.prototype.Batcher=Batcher_1,e.prototype.jobDefaults={priority:DEFAULT_PRIORITY,weight:1,expiration:null,id:"<no-id>"},e.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:e.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},e.prototype.localStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:250},e.prototype.redisStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},e.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise:Promise},e.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},e}.call(void 0);var Bottleneck_1=Bottleneck,lib=require$$0;const unifetch="undefined"!=typeof fetch?fetch:browser$1;class AlpacaClient{params;baseURLs=endpoints;limiter=new lib({reservoir:200,reservoirRefreshAmount:200,reservoirRefreshInterval:6e4,maxConcurrent:1,minTime:200});constructor(e){if(this.params=e,"endpoints"in e&&(this.baseURLs=Object.assign(endpoints,e.endpoints)),"paper"in e.credentials||"key"in e.credentials&&e.credentials.key.startsWith("A")||(e.credentials.paper=!0),"access_token"in e.credentials&&("key"in e.credentials||"secret"in e.credentials))throw new Error("can't create client with both default and oauth credentials")}async isAuthenticated(){try{return await this.getAccount(),!0}catch{return!1}}async getAccount(){return parse.account(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/account`}))}async getOrder(e){return parse.order(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/orders/${e.order_id||e.client_order_id}`,data:{nested:e.nested}}))}async getOrders(e={}){return parse.orders(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/orders`,data:{...e,symbols:e.symbols?e.symbols.join(","):void 0}}))}async placeOrder(e){return parse.order(await this.request({method:"POST",url:`${this.baseURLs.rest.account}/orders`,data:e}))}async replaceOrder(e){return parse.order(await this.request({method:"PATCH",url:`${this.baseURLs.rest.account}/orders/${e.order_id}`,data:e}))}cancelOrder(e){return this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/orders/${e.order_id}`,isJSON:!1})}async cancelOrders(){return parse.canceled_orders(await this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/orders`}))}async getPosition(e){return parse.position(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/positions/${e.symbol}`}))}async getPositions(){return parse.positions(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/positions`}))}async closePosition(e){return parse.order(await this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/positions/${e.symbol}`,data:e}))}async closePositions(e){return parse.orders(await this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/positions?cancel_orders=${JSON.stringify(e.cancel_orders??!1)}`}))}getAsset(e){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/assets/${e.asset_id_or_symbol}`})}getAssets(e){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/assets`,data:e})}getWatchlist(e){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/watchlists/${e.uuid}`})}getWatchlists(){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/watchlists`})}createWatchlist(e){return this.request({method:"POST",url:`${this.baseURLs.rest.account}/watchlists`,data:e})}updateWatchlist(e){return this.request({method:"PUT",url:`${this.baseURLs.rest.account}/watchlists/${e.uuid}`,data:e})}addToWatchlist(e){return this.request({method:"POST",url:`${this.baseURLs.rest.account}/watchlists/${e.uuid}`,data:e})}removeFromWatchlist(e){return this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/watchlists/${e.uuid}/${e.symbol}`})}deleteWatchlist(e){return this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/watchlists/${e.uuid}`})}getCalendar(e){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/calendar`,data:e})}getNews(e){return"symbols"in e&&Array.isArray(e.symbols)&&(e.symbols=e.symbols.join(",")),this.request({method:"GET",url:`${this.baseURLs.rest.beta}/news`,data:e})}async getClock(){return parse.clock(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/clock`}))}getAccountConfigurations(){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/account/configurations`})}updateAccountConfigurations(e){return this.request({method:"PATCH",url:`${this.baseURLs.rest.account}/account/configurations`,data:e})}async getAccountActivities(e){return e.activity_types&&Array.isArray(e.activity_types)&&(e.activity_types=e.activity_types.join(",")),parse.activities(await this.request({method:"GET",url:`${this.baseURLs.rest.account}/account/activities${e.activity_type?"/".concat(e.activity_type):""}`,data:{...e,activity_type:void 0}}))}getPortfolioHistory(e){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/account/portfolio/history`,data:e})}async getBars_v1(e){const t={...e,symbols:e.symbols.join(",")};return await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v1}/bars/${e.timeframe}`,data:t})}async getLastTrade_v1(e){return await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v1}/last/stocks/${e.symbol}`})}async getLastQuote_v1(e){return await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v1}/last_quote/stocks/${e.symbol}`})}async getTrades(e){return parse.pageOfTrades(await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${e.symbol}/trades`,data:{...e,symbol:void 0}}))}async getQuotes(e){return parse.pageOfQuotes(await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${e.symbol}/quotes`,data:{...e,symbol:void 0}}))}async getBars(e){return parse.pageOfBars(await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${e.symbol}/bars`,data:{...e,symbol:void 0}}))}async getLatestTrade({symbol:e,feed:t,limit:r}){let n="";return(t||r)&&(n="?".concat(lib$1.stringify({feed:t,limit:r}))),parse.latestTrade(await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${e}/trades/latest`.concat(n)}))}async getSnapshot(e){return parse.snapshot(await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${e.symbol}/snapshot`}))}async getSnapshots(e){return parse.snapshots(await this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/snapshots?symbols=${e.symbols.join(",")}`}))}async request(e){let t={};"access_token"in this.params.credentials?t.Authorization=`Bearer ${this.params.credentials.access_token}`:(t["APCA-API-KEY-ID"]=this.params.credentials.key,t["APCA-API-SECRET-KEY"]=this.params.credentials.secret),this.params.credentials.paper&&(e.url=e.url.replace("api.","paper-api."));let r="";if(e.data){for(let[t,r]of Object.entries(e.data))r instanceof Date&&(e.data[t]=r.toISOString());["POST","PATCH","PUT"].includes(e.method)||(r="?".concat(lib$1.stringify(e.data)),e.data=void 0)}const n=()=>unifetch(e.url.concat(r),{method:e.method,headers:t,body:JSON.stringify(e.data)}),i=this.params.rate_limit?()=>this.limiter.schedule(n):n;let s,o={};try{if(s=await i(),null!=e.isJSON&&!e.isJSON)return s.ok;o=await s.json()}catch(e){throw console.error(e),o}if("code"in o||"message"in o)throw o;return o}}var isBlob=e=>"undefined"!=typeof Blob&&(e instanceof Blob||"[object Blob]"===Object.prototype.toString.call(e)),ws=null;"undefined"!=typeof WebSocket?ws=WebSocket:"undefined"!=typeof MozWebSocket?ws=MozWebSocket:void 0!==commonjsGlobal?ws=commonjsGlobal.WebSocket||commonjsGlobal.MozWebSocket:"undefined"!=typeof window?ws=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(ws=self.WebSocket||self.MozWebSocket);var browser=ws,eventemitter3=createCommonjsModule((function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,s||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,i,s,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],p=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),p){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,i),!0;case 5:return u.fn.call(u.context,t,n,i,s),!0;case 6:return u.fn.call(u.context,t,n,i,s,o),!0}for(l=1,c=new Array(p-1);l<p;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,h=u.length;for(l=0;l<h;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),p){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,i);break;default:if(!c)for(d=1,c=new Array(p-1);d<p;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,i){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||n&&a.context!==n||o(this,s);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||i&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[s]=1===l.length?l[0]:l:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}));class AlpacaStream extends eventemitter3{params;host;connection;authenticated;baseURLs=endpoints;constructor(e){switch(super(),this.params=e,"endpoints"in e&&(this.baseURLs=Object.assign(endpoints,e.endpoints)),"paper"in e.credentials||"key"in e.credentials&&e.credentials.key.startsWith("A")||(e.credentials.paper=!0),e.type){case"account":this.host=e.credentials.paper?this.baseURLs.websocket.account.replace("api.","paper-api."):this.baseURLs.websocket.account;break;case"market_data":this.host=this.baseURLs.websocket.market_data(this.params.source);break;default:this.host="unknown"}this.connection=new browser(this.host),this.connection.onopen=()=>{let t={};switch(this.params.type){case"account":t={action:"authenticate",data:{key_id:e.credentials.key,secret_key:e.credentials.secret}};break;case"market_data":t={action:"auth",...e.credentials}}this.connection.send(JSON.stringify(t)),this.emit("open",this)},this.connection.onclose=()=>this.emit("close",this),this.connection.onmessage=async e=>{let t=e.data;isBlob(t)?t=await e.data.text():t instanceof ArrayBuffer&&(t=String.fromCharCode(...new Uint8Array(e.data)));let r=JSON.parse(t);("account"==this.params.type?[r]:r).forEach((e=>{this.emit("message",e),("T"in e&&"authenticated"==e.msg||"stream"in e&&"authorization"==e.stream&&"authorized"==e.data.status)&&(this.authenticated=!0,this.emit("authenticated",this)),"stream"in e&&"trade_updates"==e.stream&&this.emit("trade_updates",parse.trade_update(e.data));const t={success:"success",subscription:"subscription",error:"error",t:"trade",q:"quote",b:"bar"};"T"in e&&this.emit(t[e.T.split(".")[0]],e)}))},this.connection.onerror=e=>{this.emit("error",e)}}getConnection(){return this.connection}subscribe(e,t=[]){switch(this.params.type){case"account":this.send(JSON.stringify({action:"listen",data:{streams:[e]}}));break;case"market_data":let r={action:"subscribe"};r[e]=t,this.send(JSON.stringify(r))}return this}unsubscribe(e,t=[]){switch(this.params.type){case"account":this.send(JSON.stringify({action:"unlisten",data:{streams:[e]}}));break;case"market_data":let r={action:"unsubscribe"};r[e]=t,this.send(JSON.stringify(r))}return this}send(e){if(!this.authenticated)throw new Error("not authenticated");return"object"==typeof e&&(e=JSON.stringify(e)),this.connection.send(e),this}}var index={AlpacaClient:AlpacaClient,AlpacaStream:AlpacaStream};export{AlpacaClient,AlpacaStream,index as default};