text: import Stream from"stream";import http from"http";import Url from"url";import https from"https";import zlib from"zlib";import EventEmitter from"events";import net from"net";import tls from"tls";import require$$0$2 from"crypto";import fs from"fs";import path from"path";import os from"os";function __awaiter(e,t,r,n){return new(r||(r=Promise))((function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}var load=function(e,t,r={}){var n,s,i;for(n in t)i=t[n],r[n]=null!=(s=e[n])?s:i;return r},overwrite=function(e,t,r={}){var n,s;for(n in e)s=e[n],void 0!==t[n]&&(r[n]=s);return r},parser={load:load,overwrite:overwrite},DLList;DLList=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,s;for(e=this._first,s=[];null!=e;)s.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 s}};var DLList_1=DLList,Events;function asyncGeneratorStep(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep(i,n,s,o,a,"throw",e)}o(void 0)}))}}Events=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((function*(){var n,s;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})),s=r._events[e].map(function(){var e=_asyncToGenerator((function*(e){var n,s;if("none"!==e.status){"once"===e.status&&(e.status="none");try{return"function"==typeof(null!=(s="function"==typeof e.cb?e.cb(...t):void 0)?s.then:void 0)?yield s:s}catch(e){return n=e,r.trigger("error",n),null}}}));return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(s)).find((function(e){return null!=e}))}catch(e){return n=e,r.trigger("error",n),null}}))()}};var Events_1=Events,DLList$1,Events$1,Queues;DLList$1=DLList_1,Events$1=Events_1,Queues=class{constructor(e){this.Events=new Events$1(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,BottleneckError;BottleneckError=class extends Error{};var BottleneckError_1=BottleneckError,BottleneckError$1,DEFAULT_PRIORITY,Job,NUM_PRIORITIES,parser$1;function asyncGeneratorStep$1(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$1(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$1(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$1(i,n,s,o,a,"throw",e)}o(void 0)}))}}NUM_PRIORITIES=10,DEFAULT_PRIORITY=5,parser$1=parser,BottleneckError$1=BottleneckError_1,Job=class{constructor(e,t,r,n,s,i,o,a){this.task=e,this.args=t,this.rejectOnDrop=s,this.Events=i,this._states=o,this.Promise=a,this.options=parser$1.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:e)<0?0:t>NUM_PRIORITIES-1?NUM_PRIORITIES-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$1(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$1(`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 s=this;return _asyncToGenerator$1((function*(){var i,o,a;0===s.retryCount?(s._assertStatus("RUNNING"),s._states.next(s.options.id)):s._assertStatus("EXECUTING"),o={args:s.args,options:s.options,retryCount:s.retryCount},s.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(s.options,s.task,...s.args):s.task(...s.args),t())return s.doDone(o),yield n(s.options,o),s._assertStatus("DONE"),s._resolve(a)}catch(e){return i=e,s._onFailure(i,o,t,r,n)}}))()}doExpire(e,t,r){var n,s;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),s={args:this.args,options:this.options,retryCount:this.retryCount},n=new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(n,s,e,t,r)}_onFailure(e,t,r,n,s){var i=this;return _asyncToGenerator$1((function*(){var o,a;if(r())return null!=(o=yield i.Events.trigger("failed",e,t))?(a=~~o,i.Events.trigger("retry",`Retrying ${i.options.id} after ${a} ms`,t),i.retryCount++,n(a)):(i.doDone(t),yield s(i.options,t),i._assertStatus("DONE"),i._reject(e))}))()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}};var Job_1=Job,BottleneckError$2,LocalDatastore,parser$2;function asyncGeneratorStep$2(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$2(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$2(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$2(i,n,s,o,a,"throw",e)}o(void 0)}))}}parser$2=parser,BottleneckError$2=BottleneckError_1,LocalDatastore=class{constructor(e,t,r){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),parser$2.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,s;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 i=this.storeOptions;if(e=i.reservoirIncreaseAmount,r=i.reservoirIncreaseMaximum,s=i.reservoir,this._lastReservoirIncrease=n,(t=null!=r?Math.min(e,r-s):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$2((function*(){return yield t.yieldLoop(),t.instance.Events.trigger("message",e.toString())}))()}__disconnect__(e){var t=this;return _asyncToGenerator$2((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$2((function*(){return yield t.yieldLoop(),parser$2.overwrite(e,e,t.storeOptions),t._startHeartbeat(),t.instance._drainAll(t.computeCapacity()),!0}))()}__running__(){var e=this;return _asyncToGenerator$2((function*(){return yield e.yieldLoop(),e._running}))()}__queued__(){var e=this;return _asyncToGenerator$2((function*(){return yield e.yieldLoop(),e.instance.queued()}))()}__done__(){var e=this;return _asyncToGenerator$2((function*(){return yield e.yieldLoop(),e._done}))()}__groupCheck__(e){var t=this;return _asyncToGenerator$2((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$2((function*(){var r;return yield t.yieldLoop(),r=t.storeOptions.reservoir+=e,t.instance._drainAll(t.computeCapacity()),r}))()}__currentReservoir__(){var e=this;return _asyncToGenerator$2((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$2((function*(){var r;return yield t.yieldLoop(),r=Date.now(),t.check(e,r)}))()}__register__(e,t,r){var n=this;return _asyncToGenerator$2((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$2((function*(){var n,s,i;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 s=Date.now(),i=null!=r.storeOptions.highWater&&e===r.storeOptions.highWater&&!r.check(t,s),(n=r.strategyIsBlock()&&(i||r.isBlocked(s)))&&(r._unblockTime=s+r.computePenalty(),r._nextRequest=r._unblockTime+r.storeOptions.minTime,r.instance._dropAllQueued()),{reachedHWM:i,blocked:n,strategy:r.storeOptions.strategy}}))()}__free__(e,t){var r=this;return _asyncToGenerator$2((function*(){return yield r.yieldLoop(),r._running-=t,r._done+=t,r.instance._drainAll(r.computeCapacity()),{running:r._running}}))()}};var LocalDatastore_1=LocalDatastore,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}function commonjsRequire(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.')}var require$$0={"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=createCommonjsModule((function(e,t){var r,n,s;r={refs:(n=require$$0)["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`]},s={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(s),t.keys=function(e,t){return s[e].keys(t)},t.payload=function(e){var t;return t=s[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$2,RedisConnection,Scripts$1,parser$3;function asyncGeneratorStep$3(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$3(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$3(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$3(i,n,s,o,a,"throw",e)}o(void 0)}))}}parser$3=parser,Events$2=Events_1,Scripts$1=Scripts,RedisConnection=function(){class RedisConnection{constructor(options={}){parser$3.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events$2(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$1.payload(e),this.client.multi([["script","load",n]]).exec(((n,s)=>null!=n?r(n):(this.shas[e]=s[0],t(s[0]))))}))}_loadScripts(){return this.Promise.all(Scripts$1.names.map((e=>this._loadScript(e))))}__runCommand__(e){var t=this;return _asyncToGenerator$3((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 s;return s=n=>{if(n===t)return this.subscriber.removeListener("subscribe",s),this.limiters[t]=e,r()},this.subscriber.on("subscribe",s),this.subscriber.subscribe(t)})))))}__removeLimiter__(e){var t=this;return this.Promise.all([e.channel(),e.channel_client()].map(function(){var e=_asyncToGenerator$3((function*(e){return t.terminated||(yield new t.Promise(((r,n)=>t.subscriber.unsubscribe(e,(function(t,s){return null!=t?n(t):s===e?r():void 0}))))),delete t.limiters[e]}));return function(t){return e.apply(this,arguments)}}()))}__scriptArgs__(e,t,r,n){var s;return s=Scripts$1.keys(e,t),[this.shas[e],s.length].concat(s,r,n)}__scriptFn__(e){return this.client.evalsha.bind(this.client)}disconnect(e=!0){var t,r,n,s;for(t=0,n=(s=Object.keys(this.limiters)).length;t<n;t++)r=s[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,Events$3,IORedisConnection,Scripts$2,parser$4;function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit(e,t){var r=[],n=!0,s=!1,i=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){s=!0,i=e}finally{try{n||null==a.return||a.return()}finally{if(s)throw i}}return r}function _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep$4(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$4(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$4(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$4(i,n,s,o,a,"throw",e)}o(void 0)}))}}parser$4=parser,Events$3=Events_1,Scripts$2=Scripts,IORedisConnection=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$2.names.forEach((e=>this.client.defineCommand(e,{lua:Scripts$2.payload(e)})))}__runCommand__(e){var t=this;return _asyncToGenerator$4((function*(){yield t.ready;var r=_slicedToArray(yield t.client.pipeline([e]).exec(),1),n=_slicedToArray(r[0],2);return n[0],n[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 s;return[(s=Scripts$2.keys(e,t)).length].concat(s,r,n)}__scriptFn__(e){return this.client[e].bind(this.client)}disconnect(e=!0){var t,r,n,s;for(t=0,n=(s=Object.keys(this.limiters)).length;t<n;t++)r=s[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,BottleneckError$3,IORedisConnection$1,RedisConnection$1,RedisDatastore,parser$5;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,s=!1,i=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){s=!0,i=e}finally{try{n||null==a.return||a.return()}finally{if(s)throw i}}return r}function _arrayWithHoles$1(e){if(Array.isArray(e))return e}function asyncGeneratorStep$5(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$5(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$5(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$5(i,n,s,o,a,"throw",e)}o(void 0)}))}}parser$5=parser,BottleneckError$3=BottleneckError_1,RedisConnection$1=RedisConnection_1,IORedisConnection$1=IORedisConnection_1,RedisDatastore=class{constructor(e,t,r){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),parser$5.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$5((function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)}))()}onMessage(e,t){var r=this;return _asyncToGenerator$5((function*(){var e,n,s,i,o,a,c,l,u,h;try{c=t.indexOf(":");var d=[t.slice(0,c),t.slice(c+1)];if(s=d[1],"capacity"===(h=d[0]))return yield r.instance._drainAll(s.length>0?~~s:void 0);if("capacity-priority"===h){var f=_slicedToArray$1(s.split(":"),3);return u=f[0],l=f[1],n=f[2],e=u.length>0?~~u:void 0,l===r.clientId?(i=yield r.instance._drainAll(e),a=null!=e?e-(i||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$5((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"===h)return r.instance.Events.trigger("message",s);if("blocked"===h)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$5((function*(){return"init"!==e&&"register_client"!==e&&(yield r.ready),new r.Promise(((n,s)=>{var i,o;return i=[Date.now(),r.clientId].concat(t),r.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,i),o=r.connection.__scriptArgs__(e,r.originalId,i,(function(e,t){return null!=e?s(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,s;for(n=[],t=0,r=e.length;t<r;t++)s=e[t],n.push(null!=s?s.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$5((function*(){return yield t.runScript("update_settings",t.prepareObject(e)),parser$5.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$5((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$5((function*(){return t.convertBool(yield t.runScript("check",t.prepareArray([e])))}))()}__register__(e,t,r){var n=this;return _asyncToGenerator$5((function*(){var s,i,o,a=_slicedToArray$1(yield n.runScript("register",n.prepareArray([e,t,r])),3);return i=a[0],o=a[1],s=a[2],{success:n.convertBool(i),wait:o,reservoir:s}}))()}__submit__(e,t){var r=this;return _asyncToGenerator$5((function*(){var n,s,i,o,a;try{var c=_slicedToArray$1(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===(s=e).message.indexOf("OVERWEIGHT")){var l=_slicedToArray$1(s.message.split(":"),3);throw l[0],t=l[1],i=l[2],new BottleneckError$3(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${i}`)}throw s}}))()}__free__(e,t){var r=this;return _asyncToGenerator$5((function*(){return{running:yield r.runScript("free",r.prepareArray([e]))}}))()}};var RedisDatastore_1=RedisDatastore,BottleneckError$4,States;BottleneckError$4=BottleneckError_1,States=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,s;if(null!=e){if((r=this.status.indexOf(e))<0)throw new BottleneckError$4(`status must be one of ${this.status.join(", ")}`);for(t in s=[],n=this._jobs)n[t]===r&&s.push(t);return s}return Object.keys(this._jobs)}statusCounts(){return this.counts.reduce(((e,t,r)=>(e[this.status[r]]=t,e)),{})}};var States_1=States,DLList$2,Sync;function asyncGeneratorStep$6(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$6(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$6(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$6(i,n,s,o,a,"throw",e)}o(void 0)}))}}DLList$2=DLList_1,Sync=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new DLList$2}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return _asyncToGenerator$6((function*(){var t,r,n,s,i,o,a;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return a=c.task,t=c.args,i=c.resolve,s=c.reject,r=yield _asyncToGenerator$6((function*(){try{return o=yield a(...t),function(){return i(o)}}catch(e){return n=e,function(){return s(n)}}}))(),e._running--,e._tryToRun(),r()}}))()}schedule(e,...t){var r,n,s;return s=n=null,r=new this.Promise((function(e,t){return s=e,n=t})),this._queue.push({task:e,args:t,resolve:s,reject:n}),this._tryToRun(),r}};var Sync_1=Sync,version="2.19.5",require$$8={version:version},Events$4,Group,IORedisConnection$2,RedisConnection$2,Scripts$3,parser$6;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,s=!1,i=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){s=!0,i=e}finally{try{n||null==a.return||a.return()}finally{if(s)throw i}}return r}function _arrayWithHoles$2(e){if(Array.isArray(e))return e}function asyncGeneratorStep$7(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$7(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$7(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$7(i,n,s,o,a,"throw",e)}o(void 0)}))}}parser$6=parser,Events$4=Events_1,RedisConnection$2=RedisConnection_1,IORedisConnection$2=IORedisConnection_1,Scripts$3=Scripts,Group=function(){class e{constructor(e={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=e,parser$6.load(this.limiterOptions,this.defaults,this),this.Events=new Events$4(this),this.instances={},this.Bottleneck=Bottleneck_1,this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new RedisConnection$2(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new IORedisConnection$2(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$7((function*(){var r,n;return n=t.instances[e],t.connection&&(r=yield t.connection.__runCommand__(["del",...Scripts$3.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$7((function*(){var t,r,n,s,i,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$2(yield e.connection.__runCommand__(["scan",null!=t?t:0,"match",`b_${e.id}-*_settings`,"count",1e4]),2);for(t=~~l[0],s=0,a=(n=l[1]).length;s<a;s++)i=n[s],o.push(i.slice(c,-r))}return o}))()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(_asyncToGenerator$7((function*(){var e,r,n,s,i,o;for(r in i=Date.now(),s=[],n=t.instances){o=n[r];try{(yield o._store.__groupCheck__(i))?s.push(t.deleteKey(r)):s.push(void 0)}catch(t){e=t,s.push(o.Events.trigger("error",e))}}return s})),this.timeout/2)).unref?e.unref():void 0}updateSettings(e={}){if(parser$6.overwrite(e,this.defaults,this),parser$6.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$5,parser$7;parser$7=parser,Events$5=Events_1,Batcher=function(){class e{constructor(e={}){this.options=e,parser$7.load(this.options,this.defaults,this),this.Events=new Events$5(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$3(e,t){return _arrayWithHoles$3(e)||_iterableToArrayLimit$3(e,t)||_nonIterableRest$3()}function _iterableToArrayLimit$3(e,t){var r=[],n=!0,s=!1,i=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){s=!0,i=e}finally{try{n||null==a.return||a.return()}finally{if(s)throw i}}return r}function _toArray(e){return _arrayWithHoles$3(e)||_iterableToArray(e)||_nonIterableRest$3()}function _nonIterableRest$3(){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$3(e){if(Array.isArray(e))return e}function asyncGeneratorStep$8(e,t,r,n,s,i,o){try{var a=e[i](o),c=a.value}catch(e){return void r(e)}a.done?t(c):Promise.resolve(c).then(n,s)}function _asyncToGenerator$8(e){return function(){var t=this,r=arguments;return new Promise((function(n,s){var i=e.apply(t,r);function o(e){asyncGeneratorStep$8(i,n,s,o,a,"next",e)}function a(e){asyncGeneratorStep$8(i,n,s,o,a,"throw",e)}o(void 0)}))}}var Bottleneck,DEFAULT_PRIORITY$1,Events$6,Job$1,LocalDatastore$1,NUM_PRIORITIES$1,Queues$1,RedisDatastore$1,States$1,Sync$1,parser$8,splice=[].splice;NUM_PRIORITIES$1=10,DEFAULT_PRIORITY$1=5,parser$8=parser,Queues$1=Queues_1,Job$1=Job_1,LocalDatastore$1=LocalDatastore_1,RedisDatastore$1=RedisDatastore_1,Events$6=Events_1,States$1=States_1,Sync$1=Sync_1,Bottleneck=function(){class e{constructor(t={},...r){var n,s;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(t,r),parser$8.load(t,this.instanceDefaults,this),this._queues=new Queues$1(NUM_PRIORITIES$1),this._scheduled={},this._states=new States$1(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new Events$6(this),this._submitLock=new Sync$1("submit",this.Promise),this._registerLock=new Sync$1("register",this.Promise),s=parser$8.load(t,this.storeDefaults,{}),this._store=function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return n=parser$8.load(t,this.redisStoreDefaults,{}),new RedisDatastore$1(this,s,n);if("local"===this.datastore)return n=parser$8.load(t,this.localStoreDefaults,{}),new LocalDatastore$1(this,s,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 s=this;return _asyncToGenerator$8((function*(){var t,i;try{if(i=(yield s._store.__free__(e,r.weight)).running,s.Events.trigger("debug",`Freed ${r.id}`,n),0===i&&s.empty())return s.Events.trigger("idle")}catch(e){return t=e,s.Events.trigger("error",t)}}))()}_run(e,t,r){var n,s,i;return t.doRun(),n=this._clearGlobalState.bind(this,e),i=this._run.bind(this,e,t),s=this._free.bind(this,e,t),this._scheduled[e]={timeout:setTimeout((()=>t.doExecute(this._limiter,n,i,s)),r),expiration:null!=t.options.expiration?setTimeout((function(){return t.doExpire(n,i,s)}),r+t.options.expiration):void 0,job:t}}_drainOne(e){return this._registerLock.schedule((()=>{var t,r,n,s,i;if(0===this.queued())return this.Promise.resolve(null);i=this._queues.getFirst();var o=n=i.first();return s=o.options,t=o.args,null!=e&&s.weight>e?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${s.id}`,{args:t,options:s}),r=this._randomIndex(),this._store.__register__(r,s.weight,s.expiration).then((({success:e,wait:o,reservoir:a})=>{var c;return this.Events.trigger("debug",`Drained ${s.id}`,{success:e,args:t,options:s}),e?(i.shift(),(c=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",c),this._run(r,n,o),this.Promise.resolve(s.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$8.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,s;for(e in r=this._scheduled)s=r[e],"RUNNING"===this.jobStatus(s.job.options.id)&&(clearTimeout(s.timeout),clearTimeout(s.expiration),s.job.doDrop({message:t.dropErrorMessage}));return this._dropAllQueued(t.dropErrorMessage),n(0)}))))):this.schedule({priority:NUM_PRIORITIES$1-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$8((function*(){var n,s,i,o,a,c,l;n=t.args,o=t.options;try{var u=yield r._store.__submit__(r.queued(),o.weight);a=u.reachedHWM,s=u.blocked,l=u.strategy}catch(e){return i=e,r.Events.trigger("debug",`Could not queue ${o.id}`,{args:n,options:o,error:i}),t.doDrop({error:i}),!1}return s?(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,s),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,s,i,o,a,c;"function"==typeof e[0]?(i=_toArray(e),r=i[0],e=i.slice(1),o=_slicedToArray$3(splice.call(e,-1),1),t=o[0],s=parser$8.load({},this.jobDefaults)):(s=(a=_toArray(e))[0],r=a[1],e=a.slice(2),c=_slicedToArray$3(splice.call(e,-1),1),t=c[0],s=parser$8.load(s,this.jobDefaults));return(n=new Job$1(((...e)=>new this.Promise((function(t,n){return r(...e,(function(...e){return(null!=e[0]?n:t)(e)}))}))),e,s,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 s=_toArray(e);n=s[0],e=s.slice(1),r={}}else{var i=_toArray(e);r=i[0],n=i[1],e=i.slice(2)}return t=new Job$1(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$8((function*(){return yield t._store.__updateSettings__(parser$8.overwrite(e,t.storeDefaults)),parser$8.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$6,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$1,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=Bottleneck_1,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=Object.prototype.hasOwnProperty,isArray=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(r)){for(var n=[],s=0;s<r.length;++s)void 0!==r[s]&&n.push(r[s]);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(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(n&&(n.plainObjects||n.allowPrototypes)||!has.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var s=t;return isArray(t)&&!isArray(r)&&(s=arrayToObject(t,n)),isArray(t)&&isArray(r)?(r.forEach((function(r,s){if(has.call(t,s)){var i=t[s];i&&"object"==typeof i&&r&&"object"==typeof r?t[s]=e(i,r,n):t.push(r)}else t[s]=r})),t):Object.keys(r).reduce((function(t,s){var i=r[s];return has.call(t,s)?t[s]=e(t[s],i,n):t[s]=i,t}),s)},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,s){if(0===e.length)return e;var i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===r)return escape(i).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<i.length;++a){var c=i.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===formats.RFC1738&&(40===c||41===c)?o+=i.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&i.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 s=t[n],i=s.obj[s.prop],o=Object.keys(i),a=0;a<o.length;++a){var c=o[a],l=i[c];"object"==typeof l&&null!==l&&-1===r.indexOf(l)&&(t.push({obj:i,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(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={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,s,i,o,a,c,l,u,h,d,f,p){var _=t;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(s)return o&&!f?o(r,defaults.encoder,p,"key",h):r;_=""}if(isNonNullishPrimitive(_)||utils.isBuffer(_))return o?[d(f?r:o(r,defaults.encoder,p,"key",h))+"="+d(o(_,defaults.encoder,p,"value",h))]:[d(r)+"="+d(String(_))];var m,y=[];if(void 0===_)return y;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 g=0;g<m.length;++g){var b=m[g],k="object"==typeof b&&void 0!==b.value?b.value:_[b];if(!i||null!==k){var w=isArray$1(_)?"function"==typeof n?n(r,b):r:r+(l?"."+b:"["+b+"]");pushToArray(y,e(k,w,n,s,i,o,a,c,l,u,h,d,f,p))}}return y},normalizeStringifyOptions=function(e){if(!e)return defaults;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.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],s=defaults.filter;return("function"==typeof e.filter||isArray$1(e.filter))&&(s=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:defaults.addQueryPrefix,allowDots:void 0===e.allowDots?defaults.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults.charsetSentinel,delimiter:void 0===e.delimiter?defaults.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:defaults.encode,encoder:"function"==typeof e.encoder?e.encoder:defaults.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:defaults.encodeValuesOnly,filter:s,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:defaults.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:defaults.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults.strictNullHandling}},stringify_1=function(e,t){var r,n=e,s=normalizeStringifyOptions(t);"function"==typeof s.filter?n=(0,s.filter)("",n):isArray$1(s.filter)&&(r=s.filter);var i,o=[];if("object"!=typeof n||null===n)return"";i=t&&t.arrayFormat in arrayPrefixGenerators?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=arrayPrefixGenerators[i];r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);for(var c=0;c<r.length;++c){var l=r[c];s.skipNulls&&null===n[l]||pushToArray(o,stringify(n[l],l,a,s.strictNullHandling,s.skipNulls,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset))}var u=o.join(s.delimiter),h=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""},has$2=Object.prototype.hasOwnProperty,isArray$2=Array.isArray,defaults$1={allowDots:!1,allowPrototypes:!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={},s=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,o=s.split(t.delimiter,i),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,h=o[r],d=h.indexOf("]="),f=-1===d?h.indexOf("="):d+1;-1===f?(l=t.decoder(h,defaults$1.decoder,c,"key"),u=t.strictNullHandling?null:""):(l=t.decoder(h.slice(0,f),defaults$1.decoder,c,"key"),u=utils.maybeMap(parseArrayValue(h.slice(f+1),t),(function(e){return t.decoder(e,defaults$1.decoder,c,"value")}))),u&&t.interpretNumericEntities&&"iso-8859-1"===c&&(u=interpretNumericEntities(u)),h.indexOf("[]=")>-1&&(u=isArray$2(u)?[u]:u),has$2.call(n,l)?n[l]=utils.combine(n[l],u):n[l]=u}return n},parseObject=function(e,t,r,n){for(var s=n?t:parseArrayValue(t,r),i=e.length-1;i>=0;--i){var o,a=e[i];if("[]"===a&&r.parseArrays)o=[].concat(s);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]=s:o[c]=s:o={0:s}}s=o}return s},parseKeys=function(e,t,r,n){if(e){var s=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(s),a=o?s.slice(0,o.index):s,c=[];if(a){if(!r.plainObjects&&has$2.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var l=0;r.depth>0&&null!==(o=i.exec(s))&&l<r.depth;){if(l+=1,!r.plainObjects&&has$2.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+s.slice(o.index)+"]"),parseObject(c,t,r,n)}},normalizeParseOptions=function(e){if(!e)return defaults$1;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$1.charset:e.charset;return{allowDots:void 0===e.allowDots?defaults$1.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:defaults$1.allowPrototypes,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:defaults$1.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults$1.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:defaults$1.comma,decoder:"function"==typeof e.decoder?e.decoder:defaults$1.decoder,delimiter:"string"==typeof e.delimiter||utils.isRegExp(e.delimiter)?e.delimiter:defaults$1.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:defaults$1.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:defaults$1.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:defaults$1.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:defaults$1.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults$1.strictNullHandling}},parse=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,s=r.plainObjects?Object.create(null):{},i=Object.keys(n),o=0;o<i.length;++o){var a=i[o],c=parseKeys(a,n[a],r,"string"==typeof e);s=utils.merge(s,c,r)}return utils.compact(s)},lib$1={formats:formats,parse:parse,stringify:stringify_1};function unfetch_module(e,t){return t=t||{},new Promise((function(r,n){var s=new XMLHttpRequest,i=[],o=[],a={},c=function(){return{ok:2==(s.status/100|0),statusText:s.statusText,status:s.status,url:s.responseURL,text:function(){return Promise.resolve(s.responseText)},json:function(){return Promise.resolve(s.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([s.response]))},clone:c,headers:{keys:function(){return i},entries:function(){return o},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var l in s.open(t.method||"get",e,!0),s.onload=function(){s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(e,t,r){i.push(t=t.toLowerCase()),o.push([t,r]),a[t]=a[t]?a[t]+","+r:r})),r(c())},s.onerror=n,s.withCredentials="include"==t.credentials,t.headers)s.setRequestHeader(l,t.headers[l]);s.send(t.body||null)}))}var unfetch_module$1=Object.freeze({__proto__:null,default:unfetch_module});const Readable=Stream.Readable,BUFFER=Symbol("buffer"),TYPE=Symbol("type");class Blob$1{constructor(){this[TYPE]="";const e=arguments[0],t=arguments[1],r=[];let n=0;if(e){const t=e,s=Number(t.length);for(let e=0;e<s;e++){const s=t[e];let i;i=s instanceof Buffer?s:ArrayBuffer.isView(s)?Buffer.from(s.buffer,s.byteOffset,s.byteLength):s instanceof ArrayBuffer?Buffer.from(s):s instanceof Blob$1?s[BUFFER]:Buffer.from("string"==typeof s?s:String(s)),n+=i.length,r.push(i)}}this[BUFFER]=Buffer.concat(r);let s=t&&void 0!==t.type&&String(t.type).toLowerCase();s&&!/[^\u0020-\u007E]/.test(s)&&(this[TYPE]=s)}get size(){return this[BUFFER].length}get type(){return this[TYPE]}text(){return Promise.resolve(this[BUFFER].toString())}arrayBuffer(){const e=this[BUFFER],t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return Promise.resolve(t)}stream(){const e=new Readable;return e._read=function(){},e.push(this[BUFFER]),e.push(null),e}toString(){return"[object Blob]"}slice(){const e=this.size,t=arguments[0],r=arguments[1];let n,s;n=void 0===t?0:t<0?Math.max(e+t,0):Math.min(t,e),s=void 0===r?e:r<0?Math.max(e+r,0):Math.min(r,e);const i=Math.max(s-n,0),o=this[BUFFER].slice(n,n+i),a=new Blob$1([],{type:arguments[2]});return a[BUFFER]=o,a}}function FetchError(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}let convert;Object.defineProperties(Blob$1.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}}),Object.defineProperty(Blob$1.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0}),FetchError.prototype=Object.create(Error.prototype),FetchError.prototype.constructor=FetchError,FetchError.prototype.name="FetchError";try{convert=require("encoding").convert}catch(e){}const INTERNALS=Symbol("Body internals"),PassThrough=Stream.PassThrough;function Body(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size;let s=void 0===n?0:n;var i=r.timeout;let o=void 0===i?0:i;null==e?e=null:isURLSearchParams(e)?e=Buffer.from(e.toString()):isBlob(e)||Buffer.isBuffer(e)||("[object ArrayBuffer]"===Object.prototype.toString.call(e)?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Stream||(e=Buffer.from(String(e)))),this[INTERNALS]={body:e,disturbed:!1,error:null},this.size=s,this.timeout=o,e instanceof Stream&&e.on("error",(function(e){const r="AbortError"===e.name?e:new FetchError(`Invalid response body while trying to fetch ${t.url}: ${e.message}`,"system",e);t[INTERNALS].error=r}))}function consumeBody(){var e=this;if(this[INTERNALS].disturbed)return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[INTERNALS].disturbed=!0,this[INTERNALS].error)return Body.Promise.reject(this[INTERNALS].error);let t=this.body;if(null===t)return Body.Promise.resolve(Buffer.alloc(0));if(isBlob(t)&&(t=t.stream()),Buffer.isBuffer(t))return Body.Promise.resolve(t);if(!(t instanceof Stream))return Body.Promise.resolve(Buffer.alloc(0));let r=[],n=0,s=!1;return new Body.Promise((function(i,o){let a;e.timeout&&(a=setTimeout((function(){s=!0,o(new FetchError(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))}),e.timeout)),t.on("error",(function(t){"AbortError"===t.name?(s=!0,o(t)):o(new FetchError(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,"system",t))})),t.on("data",(function(t){if(!s&&null!==t){if(e.size&&n+t.length>e.size)return s=!0,void o(new FetchError(`content size at ${e.url} over limit: ${e.size}`,"max-size"));n+=t.length,r.push(t)}})),t.on("end",(function(){if(!s){clearTimeout(a);try{i(Buffer.concat(r,n))}catch(t){o(new FetchError(`Could not create Buffer from response body for ${e.url}: ${t.message}`,"system",t))}}}))}))}function convertBody(e,t){if("function"!=typeof convert)throw new Error("The package `encoding` must be installed to use the textConverted() function");const r=t.get("content-type");let n,s,i="utf-8";return r&&(n=/charset=([^;]*)/i.exec(r)),s=e.slice(0,1024).toString(),!n&&s&&(n=/<meta.+?charset=(['"])(.+?)\1/i.exec(s)),!n&&s&&(n=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(s),n||(n=/<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(s),n&&n.pop()),n&&(n=/charset=(.*)/i.exec(n.pop()))),!n&&s&&(n=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(s)),n&&(i=n.pop(),"gb2312"!==i&&"gbk"!==i||(i="gb18030")),convert(e,"UTF-8",i).toString()}function isURLSearchParams(e){return"object"==typeof e&&"function"==typeof e.append&&"function"==typeof e.delete&&"function"==typeof e.get&&"function"==typeof e.getAll&&"function"==typeof e.has&&"function"==typeof e.set&&("URLSearchParams"===e.constructor.name||"[object URLSearchParams]"===Object.prototype.toString.call(e)||"function"==typeof e.sort)}function isBlob(e){return"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}function clone(e){let t,r,n=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return n instanceof Stream&&"function"!=typeof n.getBoundary&&(t=new PassThrough,r=new PassThrough,n.pipe(t),n.pipe(r),e[INTERNALS].body=t,n=r),n}function extractContentType(e){return null===e?null:"string"==typeof e?"text/plain;charset=UTF-8":isURLSearchParams(e)?"application/x-www-form-urlencoded;charset=UTF-8":isBlob(e)?e.type||null:Buffer.isBuffer(e)||"[object ArrayBuffer]"===Object.prototype.toString.call(e)||ArrayBuffer.isView(e)?null:"function"==typeof e.getBoundary?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof Stream?null:"text/plain;charset=UTF-8"}function getTotalBytes(e){const t=e.body;return null===t?0:isBlob(t)?t.size:Buffer.isBuffer(t)?t.length:t&&"function"==typeof t.getLengthSync&&(t._lengthRetrievers&&0==t._lengthRetrievers.length||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}function writeToStream(e,t){const r=t.body;null===r?e.end():isBlob(r)?r.stream().pipe(e):Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}Body.prototype={get body(){return this[INTERNALS].body},get bodyUsed(){return this[INTERNALS].disturbed},arrayBuffer(){return consumeBody.call(this).then((function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}))},blob(){let e=this.headers&&this.headers.get("content-type")||"";return consumeBody.call(this).then((function(t){return Object.assign(new Blob$1([],{type:e.toLowerCase()}),{[BUFFER]:t})}))},json(){var e=this;return consumeBody.call(this).then((function(t){try{return JSON.parse(t.toString())}catch(t){return Body.Promise.reject(new FetchError(`invalid json response body at ${e.url} reason: ${t.message}`,"invalid-json"))}}))},text(){return consumeBody.call(this).then((function(e){return e.toString()}))},buffer(){return consumeBody.call(this)},textConverted(){var e=this;return consumeBody.call(this).then((function(t){return convertBody(t,e.headers)}))}},Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}}),Body.mixIn=function(e){for(const t of Object.getOwnPropertyNames(Body.prototype))if(!(t in e)){const r=Object.getOwnPropertyDescriptor(Body.prototype,t);Object.defineProperty(e,t,r)}},Body.Promise=global.Promise;const invalidTokenRegex=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,invalidHeaderCharRegex=/[^\t\x20-\x7e\x80-\xff]/;function validateName(e){if(e=`${e}`,invalidTokenRegex.test(e)||""===e)throw new TypeError(`${e} is not a legal HTTP header name`)}function validateValue(e){if(e=`${e}`,invalidHeaderCharRegex.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function find(e,t){t=t.toLowerCase();for(const r in e)if(r.toLowerCase()===t)return r}const MAP=Symbol("map");class Headers{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;if(this[MAP]=Object.create(null),e instanceof Headers){const t=e.raw(),r=Object.keys(t);for(const e of r)for(const r of t[e])this.append(e,r)}else if(null==e);else{if("object"!=typeof e)throw new TypeError("Provided initializer must be an object");{const t=e[Symbol.iterator];if(null!=t){if("function"!=typeof t)throw new TypeError("Header pairs must be iterable");const r=[];for(const t of e){if("object"!=typeof t||"function"!=typeof t[Symbol.iterator])throw new TypeError("Each header pair must be iterable");r.push(Array.from(t))}for(const e of r){if(2!==e.length)throw new TypeError("Each header pair must be a name/value tuple");this.append(e[0],e[1])}}else for(const t of Object.keys(e)){const r=e[t];this.append(t,r)}}}}get(e){validateName(e=`${e}`);const t=find(this[MAP],e);return void 0===t?null:this[MAP][t].join(", ")}forEach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,r=getHeaders(this),n=0;for(;n<r.length;){var s=r[n];const i=s[0],o=s[1];e.call(t,o,i,this),r=getHeaders(this),n++}}set(e,t){t=`${t}`,validateName(e=`${e}`),validateValue(t);const r=find(this[MAP],e);this[MAP][void 0!==r?r:e]=[t]}append(e,t){t=`${t}`,validateName(e=`${e}`),validateValue(t);const r=find(this[MAP],e);void 0!==r?this[MAP][r].push(t):this[MAP][e]=[t]}has(e){return validateName(e=`${e}`),void 0!==find(this[MAP],e)}delete(e){validateName(e=`${e}`);const t=find(this[MAP],e);void 0!==t&&delete this[MAP][t]}raw(){return this[MAP]}keys(){return createHeadersIterator(this,"key")}values(){return createHeadersIterator(this,"value")}[Symbol.iterator](){return createHeadersIterator(this,"key+value")}}function getHeaders(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"key+value";const r=Object.keys(e[MAP]).sort();return r.map("key"===t?function(e){return e.toLowerCase()}:"value"===t?function(t){return e[MAP][t].join(", ")}:function(t){return[t.toLowerCase(),e[MAP][t].join(", ")]})}Headers.prototype.entries=Headers.prototype[Symbol.iterator],Object.defineProperty(Headers.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(Headers.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});const INTERNAL=Symbol("internal");function createHeadersIterator(e,t){const r=Object.create(HeadersIteratorPrototype);return r[INTERNAL]={target:e,kind:t,index:0},r}const HeadersIteratorPrototype=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==HeadersIteratorPrototype)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[INTERNAL];const t=e.target,r=e.kind,n=e.index,s=getHeaders(t,r);return n>=s.length?{value:void 0,done:!0}:(this[INTERNAL].index=n+1,{value:s[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));function exportNodeCompatibleHeaders(e){const t=Object.assign({__proto__:null},e[MAP]),r=find(e[MAP],"Host");return void 0!==r&&(t[r]=t[r][0]),t}function createHeadersLenient(e){const t=new Headers;for(const r of Object.keys(e))if(!invalidTokenRegex.test(r))if(Array.isArray(e[r]))for(const n of e[r])invalidHeaderCharRegex.test(n)||(void 0===t[MAP][r]?t[MAP][r]=[n]:t[MAP][r].push(n));else invalidHeaderCharRegex.test(e[r])||(t[MAP][r]=[e[r]]);return t}Object.defineProperty(HeadersIteratorPrototype,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});const INTERNALS$1=Symbol("Response internals"),STATUS_CODES=http.STATUS_CODES;class Response{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Body.call(this,e,t);const r=t.status||200,n=new Headers(t.headers);if(null!=e&&!n.has("Content-Type")){const t=extractContentType(e);t&&n.append("Content-Type",t)}this[INTERNALS$1]={url:t.url,status:r,statusText:t.statusText||STATUS_CODES[r],headers:n,counter:t.counter}}get url(){return this[INTERNALS$1].url||""}get status(){return this[INTERNALS$1].status}get ok(){return this[INTERNALS$1].status>=200&&this[INTERNALS$1].status<300}get redirected(){return this[INTERNALS$1].counter>0}get statusText(){return this[INTERNALS$1].statusText}get headers(){return this[INTERNALS$1].headers}clone(){return new Response(clone(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected})}}Body.mixIn(Response.prototype),Object.defineProperties(Response.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}}),Object.defineProperty(Response.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});const INTERNALS$2=Symbol("Request internals"),parse_url=Url.parse,format_url=Url.format,streamDestructionSupported="destroy"in Stream.Readable.prototype;function isRequest(e){return"object"==typeof e&&"object"==typeof e[INTERNALS$2]}function isAbortSignal(e){const t=e&&"object"==typeof e&&Object.getPrototypeOf(e);return!(!t||"AbortSignal"!==t.constructor.name)}class Request{constructor(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};isRequest(e)?t=parse_url(e.url):(t=e&&e.href?parse_url(e.href):parse_url(`${e}`),e={});let n=r.method||e.method||"GET";if(n=n.toUpperCase(),(null!=r.body||isRequest(e)&&null!==e.body)&&("GET"===n||"HEAD"===n))throw new TypeError("Request with GET/HEAD method cannot have body");let s=null!=r.body?r.body:isRequest(e)&&null!==e.body?clone(e):null;Body.call(this,s,{timeout:r.timeout||e.timeout||0,size:r.size||e.size||0});const i=new Headers(r.headers||e.headers||{});if(null!=s&&!i.has("Content-Type")){const e=extractContentType(s);e&&i.append("Content-Type",e)}let o=isRequest(e)?e.signal:null;if("signal"in r&&(o=r.signal),null!=o&&!isAbortSignal(o))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[INTERNALS$2]={method:n,redirect:r.redirect||e.redirect||"follow",headers:i,parsedURL:t,signal:o},this.follow=void 0!==r.follow?r.follow:void 0!==e.follow?e.follow:20,this.compress=void 0!==r.compress?r.compress:void 0===e.compress||e.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent}get method(){return this[INTERNALS$2].method}get url(){return format_url(this[INTERNALS$2].parsedURL)}get headers(){return this[INTERNALS$2].headers}get redirect(){return this[INTERNALS$2].redirect}get signal(){return this[INTERNALS$2].signal}clone(){return new Request(this)}}function getNodeRequestOptions(e){const t=e[INTERNALS$2].parsedURL,r=new Headers(e[INTERNALS$2].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof Stream.Readable&&!streamDestructionSupported)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let n=null;if(null==e.body&&/^(POST|PUT)$/i.test(e.method)&&(n="0"),null!=e.body){const t=getTotalBytes(e);"number"==typeof t&&(n=String(t))}n&&r.set("Content-Length",n),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate");let s=e.agent;return"function"==typeof s&&(s=s(t)),r.has("Connection")||s||r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:exportNodeCompatibleHeaders(r),agent:s})}function AbortError(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}Body.mixIn(Request.prototype),Object.defineProperty(Request.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(Request.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}}),AbortError.prototype=Object.create(Error.prototype),AbortError.prototype.constructor=AbortError,AbortError.prototype.name="AbortError";const PassThrough$1=Stream.PassThrough,resolve_url=Url.resolve;function fetch$1(e,t){if(!fetch$1.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return Body.Promise=fetch$1.Promise,new fetch$1.Promise((function(r,n){const s=new Request(e,t),i=getNodeRequestOptions(s),o=("https:"===i.protocol?https:http).request,a=s.signal;let c=null;const l=function(){let e=new AbortError("The user aborted a request.");n(e),s.body&&s.body instanceof Stream.Readable&&s.body.destroy(e),c&&c.body&&c.body.emit("error",e)};if(a&&a.aborted)return void l();const u=function(){l(),f()},h=o(i);let d;function f(){h.abort(),a&&a.removeEventListener("abort",u),clearTimeout(d)}a&&a.addEventListener("abort",u),s.timeout&&h.once("socket",(function(e){d=setTimeout((function(){n(new FetchError(`network timeout at: ${s.url}`,"request-timeout")),f()}),s.timeout)})),h.on("error",(function(e){n(new FetchError(`request to ${s.url} failed, reason: ${e.message}`,"system",e)),f()})),h.on("response",(function(e){clearTimeout(d);const t=createHeadersLenient(e.headers);if(fetch$1.isRedirect(e.statusCode)){const i=t.get("Location"),o=null===i?null:resolve_url(s.url,i);switch(s.redirect){case"error":return n(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${s.url}`,"no-redirect")),void f();case"manual":if(null!==o)try{t.set("Location",o)}catch(e){n(e)}break;case"follow":if(null===o)break;if(s.counter>=s.follow)return n(new FetchError(`maximum redirect reached at: ${s.url}`,"max-redirect")),void f();const i={headers:new Headers(s.headers),follow:s.follow,counter:s.counter+1,agent:s.agent,compress:s.compress,method:s.method,body:s.body,signal:s.signal,timeout:s.timeout,size:s.size};return 303!==e.statusCode&&s.body&&null===getTotalBytes(s)?(n(new FetchError("Cannot follow redirect with body being a readable stream","unsupported-redirect")),void f()):(303!==e.statusCode&&(301!==e.statusCode&&302!==e.statusCode||"POST"!==s.method)||(i.method="GET",i.body=void 0,i.headers.delete("content-length")),r(fetch$1(new Request(o,i))),void f())}}e.once("end",(function(){a&&a.removeEventListener("abort",u)}));let i=e.pipe(new PassThrough$1);const o={url:s.url,status:e.statusCode,statusText:e.statusMessage,headers:t,size:s.size,timeout:s.timeout,counter:s.counter},l=t.get("Content-Encoding");if(!s.compress||"HEAD"===s.method||null===l||204===e.statusCode||304===e.statusCode)return c=new Response(i,o),void r(c);const h={flush:zlib.Z_SYNC_FLUSH,finishFlush:zlib.Z_SYNC_FLUSH};if("gzip"==l||"x-gzip"==l)return i=i.pipe(zlib.createGunzip(h)),c=new Response(i,o),void r(c);if("deflate"!=l&&"x-deflate"!=l){if("br"==l&&"function"==typeof zlib.createBrotliDecompress)return i=i.pipe(zlib.createBrotliDecompress()),c=new Response(i,o),void r(c);c=new Response(i,o),r(c)}else{e.pipe(new PassThrough$1).once("data",(function(e){i=8==(15&e[0])?i.pipe(zlib.createInflate()):i.pipe(zlib.createInflateRaw()),c=new Response(i,o),r(c)}))}})),writeToStream(h,s)}))}fetch$1.isRedirect=function(e){return 301===e||302===e||303===e||307===e||308===e},fetch$1.Promise=global.Promise;var lib$2=Object.freeze({__proto__:null,default:fetch$1,Headers:Headers,Request:Request,Response:Response,FetchError:FetchError}),require$$0$1=getAugmentedNamespace(unfetch_module$1),require$$1=getAugmentedNamespace(lib$2);function r(e){return e&&e.default||e}var isomorphicUnfetch=commonjsGlobal.fetch=commonjsGlobal.fetch||("undefined"==typeof process?r(require$$0$1):function(e,t){return r(require$$1)(String(e).replace(/^\/\//g,"https://"),t)}),urls={rest:{account:"https://api.alpaca.markets/v2",market_data:"https://data.alpaca.markets/v1"},websocket:{account:"wss://api.alpaca.markets/stream",account_paper:"wss://paper-api.alpaca.markets/stream",market_data:"wss://data.alpaca.markets/stream"}};function account(e){if(e)try{return Object.assign(Object.assign({},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 order(e){if(e)try{return Object.assign(Object.assign({},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)})}catch(e){throw new Error(`Order parsing failed. ${e.message}`)}}function orders(e){return e?e.map((e=>order(e))):void 0}function position(e){if(e)try{return Object.assign(Object.assign({},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 Object.assign(Object.assign({},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 Object.assign(Object.assign({},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 number(e){return void 0===e?e:parseFloat(e)}var parse$1={account:account,activities:activities,clock:clock,nonTradeActivity:nonTradeActivity,order:order,orders:orders,position:position,positions:positions,tradeActivity:tradeActivity};const unifetch="undefined"!=typeof fetch?fetch:isomorphicUnfetch;class AlpacaClient{constructor(e){if(this.params=e,this.limiter=new lib({reservoir:200,reservoirRefreshAmount:200,reservoirRefreshInterval:6e4,maxConcurrent:1,minTime:200}),"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")}isAuthenticated(){return __awaiter(this,void 0,void 0,(function*(){try{return yield this.getAccount(),!0}catch(e){return!1}}))}getAccount(){return __awaiter(this,void 0,void 0,(function*(){return parse$1.account(yield this.request("GET",urls.rest.account,"account"))}))}getOrder(e){return __awaiter(this,void 0,void 0,(function*(){return parse$1.order(yield this.request("GET",urls.rest.account,`orders/${e.order_id||e.client_order_id}?${lib$1.stringify({nested:e.nested})}`))}))}getOrders(e){return __awaiter(this,void 0,void 0,(function*(){return parse$1.orders(yield this.request("GET",urls.rest.account,`orders?${lib$1.stringify(e)}`))}))}placeOrder(e){return __awaiter(this,void 0,void 0,(function*(){return parse$1.order(yield this.request("POST",urls.rest.account,"orders",e))}))}replaceOrder(e){return __awaiter(this,void 0,void 0,(function*(){return parse$1.order(yield this.request("PATCH",urls.rest.account,`orders/${e.order_id}`,e))}))}cancelOrder(e){return this.request("DELETE",urls.rest.account,`orders/${e.order_id}`,void 0,!1)}cancelOrders(){return __awaiter(this,void 0,void 0,(function*(){return parse$1.orders(yield this.request("DELETE",urls.rest.account,"orders"))}))}getPosition(e){return __awaiter(this,void 0,void 0,(function*(){return parse$1.position(yield this.request("GET",urls.rest.account,`positions/${e.symbol}`))}))}getPositions(){return __awaiter(this,void 0,void 0,(function*(){return parse$1.positions(yield this.request("GET",urls.rest.account,"positions"))}))}closePosition(e){return __awaiter(this,void 0,void 0,(function*(){return parse$1.order(yield this.request("DELETE",urls.rest.account,`positions/${e.symbol}`))}))}closePositions(){return __awaiter(this,void 0,void 0,(function*(){return parse$1.orders(yield this.request("DELETE",urls.rest.account,"positions"))}))}getAsset(e){return this.request("GET",urls.rest.account,`assets/${e.asset_id_or_symbol}`)}getAssets(e){return this.request("GET",urls.rest.account,`assets?${lib$1.stringify(e)}`)}getWatchlist(e){return this.request("GET",urls.rest.account,`watchlists/${e.uuid}`)}getWatchlists(){return this.request("GET",urls.rest.account,"watchlists")}createWatchlist(e){return this.request("POST",urls.rest.account,"watchlists",e)}updateWatchlist(e){return this.request("PUT",urls.rest.account,`watchlists/${e.uuid}`,e)}addToWatchlist(e){return this.request("POST",urls.rest.account,`watchlists/${e.uuid}`,e)}removeFromWatchlist(e){return this.request("DELETE",urls.rest.account,`watchlists/${e.uuid}/${e.symbol}`,void 0,!1)}deleteWatchlist(e){return this.request("DELETE",urls.rest.account,`watchlists/${e.uuid}`,void 0,!1)}getCalendar(e){return this.request("GET",urls.rest.account,`calendar?${lib$1.stringify(e)}`)}getClock(){return __awaiter(this,void 0,void 0,(function*(){return parse$1.clock(yield this.request("GET",urls.rest.account,"clock"))}))}getAccountConfigurations(){return this.request("GET",urls.rest.account,"account/configurations")}updateAccountConfigurations(e){return this.request("PATCH",urls.rest.account,"account/configurations",e)}getAccountActivities(e){return __awaiter(this,void 0,void 0,(function*(){return e.activity_types&&Array.isArray(e.activity_types)&&(e.activity_types=e.activity_types.join(",")),parse$1.activities(yield this.request("GET",urls.rest.account,`account/activities${e.activity_type?"/".concat(e.activity_type):""}?${lib$1.stringify(e)}`))}))}getPortfolioHistory(e){return this.request("GET",urls.rest.account,`account/portfolio/history?${lib$1.stringify(e)}`)}getBars(e){const t=Object.assign(Object.assign({},e),{symbols:e.symbols.join(",")});return this.request("GET",urls.rest.market_data,`bars/${e.timeframe}?${lib$1.stringify(t)}`)}getLastTrade(e){return this.request("GET",urls.rest.market_data,`last/stocks/${e.symbol}`)}getLastQuote(e){return this.request("GET",urls.rest.market_data,`last_quote/stocks/${e.symbol}`)}request(e,t,r,n,s=!0){return __awaiter(this,void 0,void 0,(function*(){let i={};if("access_token"in this.params.credentials?i.Authorization=`Bearer ${this.params.credentials.access_token}`:(i["APCA-API-KEY-ID"]=this.params.credentials.key,i["APCA-API-SECRET-KEY"]=this.params.credentials.secret,this.params.credentials.paper&&t==urls.rest.account&&(t=urls.rest.account.replace("api.","paper-api."))),n)for(let[e,t]of Object.entries(n))t instanceof Date&&(n[e]=t.toISOString());const o=()=>unifetch(`${t}/${r}`,{method:e,headers:i,body:JSON.stringify(n)}),a=this.params.rate_limit?()=>this.limiter.schedule(o):o;let c,l={};try{if(c=yield a(),!s)return c.ok;l=yield c.json()}catch(e){throw console.error(e),l}if("code"in l&&"message"in l)throw l;return l}))}}var constants={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),EMPTY_BUFFER:Buffer.alloc(0),NOOP:()=>{}},runtimeRequire="function"==typeof __webpack_require__?__non_webpack_require__:commonjsRequire,vars=process.config&&process.config.variables||{},prebuildsOnly=!!process.env.PREBUILDS_ONLY,abi=process.versions.modules,runtime=isElectron()?"electron":"node",arch=os.arch(),platform=os.platform(),libc=process.env.LIBC||(isAlpine(platform)?"musl":"glibc"),armv=process.env.ARM_VERSION||("arm64"===arch?"8":vars.arm_version)||"",uv=(process.versions.uv||"").split(".")[0],nodeGypBuild=load$1;function load$1(e){return runtimeRequire(load$1.path(e))}function readdirSync(e){try{return fs.readdirSync(e)}catch(e){return[]}}function getFirst(e,t){var r=readdirSync(e).filter(t);return r[0]&&path.join(e,r[0])}function matchBuild(e){return/\.node$/.test(e)}function parseTags(e){var t=e.split("."),r={file:e,specificity:0};if("node"===t.pop()){for(var n=0;n<t.length;n++){var s=t[n];if("node"===s||"electron"===s||"node-webkit"===s)r.runtime=s;else if("napi"===s)r.napi=!0;else if("abi"===s.slice(0,3))r.abi=s.slice(3);else if("uv"===s.slice(0,2))r.uv=s.slice(2);else if("armv"===s.slice(0,4))r.armv=s.slice(4);else{if("glibc"!==s&&"musl"!==s)continue;r.libc=s}r.specificity++}return r}}function matchTags(e,t){return function(r){return null!=r&&(!(r.runtime!==e&&!runtimeAgnostic(r))&&(!(r.abi!==t&&!r.napi)&&((!r.uv||r.uv===uv)&&((!r.armv||r.armv===armv)&&(!r.libc||r.libc===libc)))))}}function runtimeAgnostic(e){return"node"===e.runtime&&e.napi}function compareTags(e){return function(t,r){return t.runtime!==r.runtime?t.runtime===e?-1:1:t.abi!==r.abi?t.abi?-1:1:t.specificity!==r.specificity?t.specificity>r.specificity?-1:1:0}}function isElectron(){return!(!process.versions||!process.versions.electron)||(!!process.env.ELECTRON_RUN_AS_NODE||"undefined"!=typeof window&&window.process&&"renderer"===window.process.type)}function isAlpine(e){return"linux"===e&&fs.existsSync("/etc/alpine-release")}load$1.path=function(e){e=path.resolve(e||".");try{var t=runtimeRequire(path.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[t+"_PREBUILD"]&&(e=process.env[t+"_PREBUILD"])}catch(e){}if(!prebuildsOnly){var r=getFirst(path.join(e,"build/Release"),matchBuild);if(r)return r;var n=getFirst(path.join(e,"build/Debug"),matchBuild);if(n)return n}var s=a(e);if(s)return s;var i=a(path.dirname(process.execPath));if(i)return i;var o=["platform="+platform,"arch="+arch,"runtime="+runtime,"abi="+abi,"uv="+uv,armv?"armv="+armv:"","libc="+libc,"node="+process.versions.node,process.versions&&process.versions.electron?"electron="+process.versions.electron:"","function"==typeof __webpack_require__?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+o+"\n    loaded from: "+e+"\n");function a(e){var t=path.join(e,"prebuilds",platform+"-"+arch),r=readdirSync(t).map(parseTags).filter(matchTags(runtime,abi)).sort(compareTags(runtime))[0];if(r)return path.join(t,r.file)}},load$1.parseTags=parseTags,load$1.matchTags=matchTags,load$1.compareTags=compareTags;const mask=(e,t,r,n,s)=>{for(var i=0;i<s;i++)r[n+i]=e[i]^t[3&i]},unmask=(e,t)=>{const r=e.length;for(var n=0;n<r;n++)e[n]^=t[3&n]};var fallback={mask:mask,unmask:unmask},bufferutil=createCommonjsModule((function(e){try{e.exports=nodeGypBuild(__dirname)}catch(t){e.exports=fallback}})),bufferUtil=createCommonjsModule((function(e){const{EMPTY_BUFFER:t}=constants;function r(e,r){if(0===e.length)return t;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(r);let s=0;for(let t=0;t<e.length;t++){const r=e[t];n.set(r,s),s+=r.length}return s<r?n.slice(0,s):n}function n(e,t,r,n,s){for(let i=0;i<s;i++)r[n+i]=e[i]^t[3&i]}function s(e,t){const r=e.length;for(let n=0;n<r;n++)e[n]^=t[3&n]}function i(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function o(e){if(o.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=Buffer.from(e):ArrayBuffer.isView(e)?t=Buffer.from(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),o.readOnly=!1),t}try{const t=bufferutil,a=t.BufferUtil||t;e.exports={concat:r,mask(e,t,r,s,i){i<48?n(e,t,r,s,i):a.mask(e,t,r,s,i)},toArrayBuffer:i,toBuffer:o,unmask(e,t){e.length<32?s(e,t):a.unmask(e,t)}}}catch(t){e.exports={concat:r,mask:n,toArrayBuffer:i,toBuffer:o,unmask:s}}}));const kDone=Symbol("kDone"),kRun=Symbol("kRun");class Limiter{constructor(e){this[kDone]=()=>{this.pending--,this[kRun]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[kRun]()}[kRun](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[kDone])}}}var limiter=Limiter;const{kStatusCode:kStatusCode,NOOP:NOOP}=constants,TRAILER=Buffer.from([0,0,255,255]),kPerMessageDeflate=Symbol("permessage-deflate"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error");let zlibLimiter;class PerMessageDeflate{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;zlibLimiter=new limiter(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[kCallback];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r}))})),e}decompress(e,t,r){zlibLimiter.add((n=>{this._decompress(e,t,((e,t)=>{n(),r(e,t)}))}))}compress(e,t,r){zlibLimiter.add((n=>{this._compress(e,t,((e,t)=>{n(),r(e,t)}))}))}_decompress(e,t,r){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?zlib.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=r,this._inflate.write(e),t&&this._inflate.write(TRAILER),this._inflate.flush((()=>{const e=this._inflate[kError];if(e)return this._inflate.close(),this._inflate=null,void r(e);const s=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset(),r(null,s)}))}_compress(e,t,r){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?zlib.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("error",NOOP),this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=r,this._deflate.write(e),this._deflate.flush(zlib.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);t&&(e=e.slice(0,e.length-4)),this._deflate[kCallback]=null,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),r(null,e)}))}}var permessageDeflate=PerMessageDeflate;function deflateOnData(e){this[kBuffers].push(e),this[kTotalLength]+=e.length}function inflateOnData(e){this[kTotalLength]+=e.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload?this[kBuffers].push(e):(this[kError]=new RangeError("Max payload size exceeded"),this[kError][kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset())}function inflateOnError(e){this[kPerMessageDeflate]._inflate=null,e[kStatusCode]=1007,this[kCallback](e)}const isValidUTF8=e=>{for(var t=e.length,r=0;r<t;)if(e[r]<128)r++;else if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}return!0};var fallback$1=isValidUTF8,utf8Validate=createCommonjsModule((function(e){try{e.exports=nodeGypBuild(__dirname)}catch(t){e.exports=fallback$1}})),validation=createCommonjsModule((function(e,t){try{const e=utf8Validate;t.isValidUTF8="object"==typeof e?e.Validation.isValidUTF8:e}catch(e){t.isValidUTF8=()=>!0}t.isValidStatusCode=e=>e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999}));const{Writable:Writable}=Stream,{BINARY_TYPES:BINARY_TYPES,EMPTY_BUFFER:EMPTY_BUFFER,kStatusCode:kStatusCode$1,kWebSocket:kWebSocket}=constants,{concat:concat,toArrayBuffer:toArrayBuffer,unmask:unmask$1}=bufferUtil,{isValidStatusCode:isValidStatusCode,isValidUTF8:isValidUTF8$1}=validation,GET_INFO=0,GET_PAYLOAD_LENGTH_16=1,GET_PAYLOAD_LENGTH_64=2,GET_MASK=3,GET_DATA=4,INFLATING=5;class Receiver extends Writable{constructor(e,t,r,n){super(),this._binaryType=e||BINARY_TYPES[0],this[kWebSocket]=void 0,this._extensions=t||{},this._isServer=!!r,this._maxPayload=0|n,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=GET_INFO,this._loop=!1}_write(e,t,r){if(8===this._opcode&&this._state==GET_INFO)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=t.slice(e),t.slice(0,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=r.slice(e)),e-=r.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case GET_INFO:t=this.getInfo();break;case GET_PAYLOAD_LENGTH_16:t=this.getPayloadLength16();break;case GET_PAYLOAD_LENGTH_64:t=this.getPayloadLength64();break;case GET_MASK:this.getMask();break;case GET_DATA:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,error(RangeError,"RSV2 and RSV3 must be clear",!0,1002);const t=64==(64&e[0]);if(t&&!this._extensions[permessageDeflate.extensionName])return this._loop=!1,error(RangeError,"RSV1 must be clear",!0,1002);if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,error(RangeError,"RSV1 must be clear",!0,1002);if(!this._fragmented)return this._loop=!1,error(RangeError,"invalid opcode 0",!0,1002);this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,error(RangeError,`invalid opcode ${this._opcode}`,!0,1002);this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,error(RangeError,`invalid opcode ${this._opcode}`,!0,1002);if(!this._fin)return this._loop=!1,error(RangeError,"FIN must be set",!0,1002);if(t)return this._loop=!1,error(RangeError,"RSV1 must be clear",!0,1002);if(this._payloadLength>125)return this._loop=!1,error(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002)}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,error(RangeError,"MASK must be set",!0,1002)}else if(this._masked)return this._loop=!1,error(RangeError,"MASK must be clear",!0,1002);if(126===this._payloadLength)this._state=GET_PAYLOAD_LENGTH_16;else{if(127!==this._payloadLength)return this.haveLength();this._state=GET_PAYLOAD_LENGTH_64}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,error(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009)):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,error(RangeError,"Max payload size exceeded",!1,1009);this._masked?this._state=GET_MASK:this._state=GET_DATA}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=GET_DATA)}getData(e){let t=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&unmask$1(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=INFLATING,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[permessageDeflate.extensionName].decompress(e,this._fin,((e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(error(RangeError,"Max payload size exceeded",!1,1009));this._fragments.push(r)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?concat(t,e):"arraybuffer"===this._binaryType?toArrayBuffer(concat(t,e)):t,this.emit("message",r)}else{const r=concat(t,e);if(!isValidUTF8$1(r))return this._loop=!1,error(Error,"invalid UTF-8 sequence",!0,1007);this.emit("message",r.toString())}}this._state=GET_INFO}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,""),this.end();else{if(1===e.length)return error(RangeError,"invalid payload length 1",!0,1002);{const t=e.readUInt16BE(0);if(!isValidStatusCode(t))return error(RangeError,`invalid status code ${t}`,!0,1002);const r=e.slice(2);if(!isValidUTF8$1(r))return error(Error,"invalid UTF-8 sequence",!0,1007);this.emit("conclude",t,r.toString()),this.end()}}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=GET_INFO}}var receiver=Receiver;function error(e,t,r,n){const s=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,error),s[kStatusCode$1]=n,s}const{randomFillSync:randomFillSync}=require$$0$2,{EMPTY_BUFFER:EMPTY_BUFFER$1}=constants,{isValidStatusCode:isValidStatusCode$1}=validation,{mask:applyMask,toBuffer:toBuffer}=bufferUtil,mask$1=Buffer.alloc(4);class Sender{constructor(e,t){this._extensions=t||{},this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){const r=t.mask&&t.readOnly;let n=t.mask?6:2,s=e.length;e.length>=65536?(n+=8,s=127):e.length>125&&(n+=2,s=126);const i=Buffer.allocUnsafe(r?e.length+n:n);return i[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(i[0]|=64),i[1]=s,126===s?i.writeUInt16BE(e.length,2):127===s&&(i.writeUInt32BE(0,2),i.writeUInt32BE(e.length,6)),t.mask?(randomFillSync(mask$1,0,4),i[1]|=128,i[n-4]=mask$1[0],i[n-3]=mask$1[1],i[n-2]=mask$1[2],i[n-1]=mask$1[3],r?(applyMask(e,mask$1,i,n,e.length),[i]):(applyMask(e,mask$1,e,0,e.length),[i,e])):[i,e]}close(e,t,r,n){let s;if(void 0===e)s=EMPTY_BUFFER$1;else{if("number"!=typeof e||!isValidStatusCode$1(e))throw new TypeError("First argument must be a valid error code number");if(void 0===t||""===t)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+r),s.writeUInt16BE(e,0),s.write(t,2)}}this._deflating?this.enqueue([this.doClose,s,r,n]):this.doClose(s,r,n)}doClose(e,t,r){this.sendFrame(Sender.frame(e,{fin:!0,rsv1:!1,opcode:8,mask:t,readOnly:!1}),r)}ping(e,t,r){const n=toBuffer(e);if(n.length>125)throw new RangeError("The data size must not be greater than 125 bytes");this._deflating?this.enqueue([this.doPing,n,t,toBuffer.readOnly,r]):this.doPing(n,t,toBuffer.readOnly,r)}doPing(e,t,r,n){this.sendFrame(Sender.frame(e,{fin:!0,rsv1:!1,opcode:9,mask:t,readOnly:r}),n)}pong(e,t,r){const n=toBuffer(e);if(n.length>125)throw new RangeError("The data size must not be greater than 125 bytes");this._deflating?this.enqueue([this.doPong,n,t,toBuffer.readOnly,r]):this.doPong(n,t,toBuffer.readOnly,r)}doPong(e,t,r,n){this.sendFrame(Sender.frame(e,{fin:!0,rsv1:!1,opcode:10,mask:t,readOnly:r}),n)}send(e,t,r){const n=toBuffer(e),s=this._extensions[permessageDeflate.extensionName];let i=t.binary?2:1,o=t.compress;if(this._firstFragment?(this._firstFragment=!1,o&&s&&(o=n.length>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0),s){const e={fin:t.fin,rsv1:o,opcode:i,mask:t.mask,readOnly:toBuffer.readOnly};this._deflating?this.enqueue([this.dispatch,n,this._compress,e,r]):this.dispatch(n,this._compress,e,r)}else this.sendFrame(Sender.frame(n,{fin:t.fin,rsv1:!1,opcode:i,mask:t.mask,readOnly:toBuffer.readOnly}),r)}dispatch(e,t,r,n){if(!t)return void this.sendFrame(Sender.frame(e,r),n);const s=this._extensions[permessageDeflate.extensionName];this._bufferedBytes+=e.length,this._deflating=!0,s.compress(e,r.fin,((t,s)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const r=this._queue[t][4];"function"==typeof r&&r(e)}}else this._bufferedBytes-=e.length,this._deflating=!1,r.readOnly=!1,this.sendFrame(Sender.frame(s,r),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[1].length,Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[1].length,this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var sender=Sender;class Event{constructor(e,t){this.target=t,this.type=e}}class MessageEvent extends Event{constructor(e,t){super("message",t),this.data=e}}class CloseEvent extends Event{constructor(e,t,r){super("close",r),this.wasClean=r._closeFrameReceived&&r._closeFrameSent,this.reason=t,this.code=e}}class OpenEvent extends Event{constructor(e){super("open",e)}}class ErrorEvent extends Event{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}const EventTarget={addEventListener(e,t,r){if("function"!=typeof t)return;function n(e){t.call(this,new MessageEvent(e,this))}function s(e,r){t.call(this,new CloseEvent(e,r,this))}function i(e){t.call(this,new ErrorEvent(e,this))}function o(){t.call(this,new OpenEvent(this))}const a=r&&r.once?"once":"on";"message"===e?(n._listener=t,this[a](e,n)):"close"===e?(s._listener=t,this[a](e,s)):"error"===e?(i._listener=t,this[a](e,i)):"open"===e?(o._listener=t,this[a](e,o)):this[a](e,t)},removeEventListener(e,t){const r=this.listeners(e);for(let n=0;n<r.length;n++)r[n]!==t&&r[n]._listener!==t||this.removeListener(e,r[n])}};var eventTarget=EventTarget;const tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function push$1(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}function parse$2(e){const t=Object.create(null);if(void 0===e||""===e)return t;let r,n,s=Object.create(null),i=!1,o=!1,a=!1,c=-1,l=-1,u=0;for(;u<e.length;u++){const h=e.charCodeAt(u);if(void 0===r)if(-1===l&&1===tokenChars[h])-1===c&&(c=u);else if(32===h||9===h)-1===l&&-1!==c&&(l=u);else{if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);const n=e.slice(c,l);44===h?(push$1(t,n,s),s=Object.create(null)):r=n,c=l=-1}}else if(void 0===n)if(-1===l&&1===tokenChars[h])-1===c&&(c=u);else if(32===h||9===h)-1===l&&-1!==c&&(l=u);else if(59===h||44===h){if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u),push$1(s,e.slice(c,l),!0),44===h&&(push$1(t,r,s),s=Object.create(null),r=void 0),c=l=-1}else{if(61!==h||-1===c||-1!==l)throw new SyntaxError(`Unexpected character at index ${u}`);n=e.slice(c,u),c=l=-1}else if(o){if(1!==tokenChars[h])throw new SyntaxError(`Unexpected character at index ${u}`);-1===c?c=u:i||(i=!0),o=!1}else if(a)if(1===tokenChars[h])-1===c&&(c=u);else if(34===h&&-1!==c)a=!1,l=u;else{if(92!==h)throw new SyntaxError(`Unexpected character at index ${u}`);o=!0}else if(34===h&&61===e.charCodeAt(u-1))a=!0;else if(-1===l&&1===tokenChars[h])-1===c&&(c=u);else if(-1===c||32!==h&&9!==h){if(59!==h&&44!==h)throw new SyntaxError(`Unexpected character at index ${u}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${u}`);-1===l&&(l=u);let o=e.slice(c,l);i&&(o=o.replace(/\\/g,""),i=!1),push$1(s,n,o),44===h&&(push$1(t,r,s),s=Object.create(null),r=void 0),n=void 0,c=l=-1}}else-1===l&&(l=u)}if(-1===c||a)throw new SyntaxError("Unexpected end of input");-1===l&&(l=u);const h=e.slice(c,l);return void 0===r?push$1(t,h,s):(void 0===n?push$1(s,h,!0):push$1(s,n,i?h.replace(/\\/g,""):h),push$1(t,r,s)),t}function format(e){return Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>[t].concat(Object.keys(e).map((t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")}var extension={format:format,parse:parse$2};const{randomBytes:randomBytes,createHash:createHash}=require$$0$2,{URL:URL}=Url,{BINARY_TYPES:BINARY_TYPES$1,EMPTY_BUFFER:EMPTY_BUFFER$2,GUID:GUID,kStatusCode:kStatusCode$2,kWebSocket:kWebSocket$1,NOOP:NOOP$1}=constants,{addEventListener:addEventListener,removeEventListener:removeEventListener}=eventTarget,{format:format$1,parse:parse$3}=extension,{toBuffer:toBuffer$1}=bufferUtil,readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],protocolVersions=[8,13],closeTimeout=3e4;class WebSocket extends EventEmitter{constructor(e,t,r){super(),this._binaryType=BINARY_TYPES$1[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage="",this._closeTimer=null,this._extensions={},this._protocol="",this._readyState=WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,Array.isArray(t)?t=t.join(", "):"object"==typeof t&&null!==t&&(r=t,t=void 0),initAsClient(this,e,t,r)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){BINARY_TYPES$1.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new receiver(this.binaryType,this._extensions,this._isServer,r);this._sender=new sender(e,this._extensions),this._receiver=n,this._socket=e,n[kWebSocket$1]=this,e[kWebSocket$1]=this,n.on("conclude",receiverOnConclude),n.on("drain",receiverOnDrain),n.on("error",receiverOnError),n.on("message",receiverOnMessage),n.on("ping",receiverOnPing),n.on("pong",receiverOnPong),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",socketOnClose),e.on("data",socketOnData),e.on("end",socketOnEnd),e.on("error",socketOnError),this._readyState=WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=WebSocket.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[permessageDeflate.extensionName]&&this._extensions[permessageDeflate.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==WebSocket.CLOSED){if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return abortHandshake(this,this._req,e)}this.readyState!==WebSocket.CLOSING?(this._readyState=WebSocket.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,this._closeFrameReceived&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),closeTimeout)):this._closeFrameSent&&this._closeFrameReceived&&this._socket.end()}}ping(e,t,r){if(this.readyState===WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===WebSocket.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||EMPTY_BUFFER$2,t,r)):sendAfterClose(this,e,r)}pong(e,t,r){if(this.readyState===WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===WebSocket.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||EMPTY_BUFFER$2,t,r)):sendAfterClose(this,e,r)}send(e,t,r){if(this.readyState===WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==WebSocket.OPEN)return void sendAfterClose(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[permessageDeflate.extensionName]||(n.compress=!1),this._sender.send(e||EMPTY_BUFFER$2,n,r)}terminate(){if(this.readyState!==WebSocket.CLOSED){if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return abortHandshake(this,this._req,e)}this._socket&&(this._readyState=WebSocket.CLOSING,this._socket.destroy())}}}readyStates.forEach(((e,t)=>{const r={enumerable:!0,value:t};Object.defineProperty(WebSocket.prototype,e,r),Object.defineProperty(WebSocket,e,r)})),["binaryType","bufferedAmount","extensions","protocol","readyState","url"].forEach((e=>{Object.defineProperty(WebSocket.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(WebSocket.prototype,`on${e}`,{configurable:!0,enumerable:!0,get(){const t=this.listeners(e);for(let e=0;e<t.length;e++)if(t[e]._listener)return t[e]._listener},set(t){const r=this.listeners(e);for(let t=0;t<r.length;t++)r[t]._listener&&this.removeListener(e,r[t]);this.addEventListener(e,t)}})})),WebSocket.prototype.addEventListener=addEventListener,WebSocket.prototype.removeEventListener=removeEventListener;var websocket=WebSocket;function initAsClient(e,t,r,n){const s={protocolVersion:protocolVersions[1],maxPayload:104857600,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:void 0,host:void 0,path:void 0,port:void 0};if(!protocolVersions.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let i;t instanceof URL?(i=t,e._url=t.href):(i=new URL(t),e._url=t);const o="ws+unix:"===i.protocol;if(!(i.host||o&&i.pathname))throw new Error(`Invalid URL: ${e.url}`);const a="wss:"===i.protocol||"https:"===i.protocol,c=a?443:80,l=randomBytes(16).toString("base64"),u=a?https.get:http.get;let h;if(s.createConnection=a?tlsConnect:netConnect,s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket",...s.headers},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new permessageDeflate(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=format$1({[permessageDeflate.extensionName]:h.offer()})),r&&(s.headers["Sec-WebSocket-Protocol"]=r),s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),o){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}let d=e._req=u(s);s.timeout&&d.on("timeout",(()=>{abortHandshake(e,d,"Opening handshake has timed out")})),d.on("error",(t=>{null===d||d.aborted||(d=e._req=null,e._readyState=WebSocket.CLOSING,e.emit("error",t),e.emitClose())})),d.on("response",(i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void abortHandshake(e,d,"Maximum redirects exceeded");d.abort();const i=new URL(o,t);initAsClient(e,i,r,n)}else e.emit("unexpected-response",d,i)||abortHandshake(e,d,`Unexpected server response: ${i.statusCode}`)})),d.on("upgrade",((t,n,i)=>{if(e.emit("upgrade",t),e.readyState!==WebSocket.CONNECTING)return;d=e._req=null;const o=createHash("sha1").update(l+GUID).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void abortHandshake(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"],c=(r||"").split(/, */);let u;if(!r&&a?u="Server sent a subprotocol but none was requested":r&&!a?u="Server sent no subprotocol":a&&!c.includes(a)&&(u="Server sent an invalid subprotocol"),u)abortHandshake(e,n,u);else{if(a&&(e._protocol=a),h)try{const r=parse$3(t.headers["sec-websocket-extensions"]);r[permessageDeflate.extensionName]&&(h.accept(r[permessageDeflate.extensionName]),e._extensions[permessageDeflate.extensionName]=h)}catch(t){return void abortHandshake(e,n,"Invalid Sec-WebSocket-Extensions header")}e.setSocket(n,i,s.maxPayload)}}))}function netConnect(e){return e.path=e.socketPath,net.connect(e)}function tlsConnect(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=net.isIP(e.host)?"":e.host),tls.connect(e)}function abortHandshake(e,t,r){e._readyState=WebSocket.CLOSING;const n=new Error(r);Error.captureStackTrace(n,abortHandshake),t.setHeader?(t.abort(),t.once("abort",e.emitClose.bind(e)),e.emit("error",n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function sendAfterClose(e,t,r){if(t){const r=toBuffer$1(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){r(new Error(`WebSocket is not open: readyState ${e.readyState} (${readyStates[e.readyState]})`))}}function receiverOnConclude(e,t){const r=this[kWebSocket$1];r._socket.removeListener("data",socketOnData),r._socket.resume(),r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,1005===e?r.close():r.close(e,t)}function receiverOnDrain(){this[kWebSocket$1]._socket.resume()}function receiverOnError(e){const t=this[kWebSocket$1];t._socket.removeListener("data",socketOnData),t._readyState=WebSocket.CLOSING,t._closeCode=e[kStatusCode$2],t.emit("error",e),t._socket.destroy()}function receiverOnFinish(){this[kWebSocket$1].emitClose()}function receiverOnMessage(e){this[kWebSocket$1].emit("message",e)}function receiverOnPing(e){const t=this[kWebSocket$1];t.pong(e,!t._isServer,NOOP$1),t.emit("ping",e)}function receiverOnPong(e){this[kWebSocket$1].emit("pong",e)}function socketOnClose(){const e=this[kWebSocket$1];this.removeListener("close",socketOnClose),this.removeListener("end",socketOnEnd),e._readyState=WebSocket.CLOSING,e._socket.read(),e._receiver.end(),this.removeListener("data",socketOnData),this[kWebSocket$1]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",receiverOnFinish),e._receiver.on("finish",receiverOnFinish))}function socketOnData(e){this[kWebSocket$1]._receiver.write(e)||this.pause()}function socketOnEnd(){const e=this[kWebSocket$1];e._readyState=WebSocket.CLOSING,e._receiver.end(),this.end()}function socketOnError(){const e=this[kWebSocket$1];this.removeListener("error",socketOnError),this.on("error",NOOP$1),e&&(e._readyState=WebSocket.CLOSING,this.destroy())}const{Duplex:Duplex}=Stream;function emitClose(e){e.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(e){this.removeListener("error",duplexOnError),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}function createWebSocketStream(e,t){let r=!0;function n(){r&&e._socket.resume()}e.readyState===e.CONNECTING?e.once("open",(function(){e._receiver.removeAllListeners("drain"),e._receiver.on("drain",n)})):(e._receiver.removeAllListeners("drain"),e._receiver.on("drain",n));const s=new Duplex({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",(function(t){s.push(t)||(r=!1,e._socket.pause())})),e.once("error",(function(e){s.destroyed||s.destroy(e)})),e.once("close",(function(){s.destroyed||s.push(null)})),s._destroy=function(t,r){if(e.readyState===e.CLOSED)return r(t),void process.nextTick(emitClose,s);let n=!1;e.once("error",(function(e){n=!0,r(e)})),e.once("close",(function(){n||r(t),process.nextTick(emitClose,s)})),e.terminate()},s._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once("finish",(function(){t()})),e.close())):e.once("open",(function(){s._final(t)}))},s._read=function(){e.readyState!==e.OPEN||r||(r=!0,e._receiver._writableState.needDrain||e._socket.resume())},s._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",(function(){s._write(t,r,n)}))},s.on("end",duplexOnEnd),s.on("error",duplexOnError),s}var stream=createWebSocketStream;const{createHash:createHash$1}=require$$0$2,{createServer:createServer,STATUS_CODES:STATUS_CODES$1}=http,{format:format$2,parse:parse$4}=extension,{GUID:GUID$1,kWebSocket:kWebSocket$2}=constants,keyRegex=/^[+/0-9A-Za-z]{22}==$/;class WebSocketServer extends EventEmitter{constructor(e,t){if(super(),null==(e={maxPayload:104857600,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,...e}).port&&!e.server&&!e.noServer)throw new TypeError('One of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=createServer(((e,t)=>{const r=STATUS_CODES$1[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set),this.options=e}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(e&&this.once("close",e),this.clients)for(const e of this.clients)e.terminate();const t=this._server;t&&(this._removeListeners(),this._removeListeners=this._server=null,null!=this.options.port)?t.close((()=>this.emit("close"))):process.nextTick(emitClose$1,this)}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",socketOnError$1);const s=void 0!==e.headers["sec-websocket-key"]&&e.headers["sec-websocket-key"].trim(),i=+e.headers["sec-websocket-version"],o={};if("GET"!==e.method||"websocket"!==e.headers.upgrade.toLowerCase()||!s||!keyRegex.test(s)||8!==i&&13!==i||!this.shouldHandle(e))return abortHandshake$1(t,400);if(this.options.perMessageDeflate){const r=new permessageDeflate(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const t=parse$4(e.headers["sec-websocket-extensions"]);t[permessageDeflate.extensionName]&&(r.accept(t[permessageDeflate.extensionName]),o[permessageDeflate.extensionName]=r)}catch(e){return abortHandshake$1(t,400)}}if(this.options.verifyClient){const a={origin:e.headers[""+(8===i?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(a,((i,a,c,l)=>{if(!i)return abortHandshake$1(t,a||401,c,l);this.completeUpgrade(s,o,e,t,r,n)}));if(!this.options.verifyClient(a))return abortHandshake$1(t,401)}this.completeUpgrade(s,o,e,t,r,n)}completeUpgrade(e,t,r,n,s,i){if(!n.readable||!n.writable)return n.destroy();if(n[kWebSocket$2])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");const o=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash$1("sha1").update(e+GUID$1).digest("base64")}`],a=new websocket(null);let c=r.headers["sec-websocket-protocol"];if(c&&(c=c.trim().split(/ *, */),c=this.options.handleProtocols?this.options.handleProtocols(c,r):c[0],c&&(o.push(`Sec-WebSocket-Protocol: ${c}`),a._protocol=c)),t[permessageDeflate.extensionName]){const e=t[permessageDeflate.extensionName].params,r=format$2({[permessageDeflate.extensionName]:[e]});o.push(`Sec-WebSocket-Extensions: ${r}`),a._extensions=t}this.emit("headers",o,r),n.write(o.concat("\r\n").join("\r\n")),n.removeListener("error",socketOnError$1),a.setSocket(n,s,this.options.maxPayload),this.clients&&(this.clients.add(a),a.on("close",(()=>this.clients.delete(a)))),i(a,r)}}var websocketServer=WebSocketServer;function addListeners(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}function emitClose$1(e){e.emit("close")}function socketOnError$1(){this.destroy()}function abortHandshake$1(e,t,r,n){e.writable&&(r=r||STATUS_CODES$1[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.write(`HTTP/1.1 ${t} ${STATUS_CODES$1[t]}\r\n`+Object.keys(n).map((e=>`${e}: ${n[e]}`)).join("\r\n")+"\r\n\r\n"+r)),e.removeListener("error",socketOnError$1),e.destroy()}websocket.createWebSocketStream=stream,websocket.Server=websocketServer,websocket.Receiver=receiver,websocket.Sender=sender;var ws=websocket,node=ws,eventemitter3=createCommonjsModule((function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||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,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},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 s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].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,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){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,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=new Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,f=u.length;for(l=0;l<f;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){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,s);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}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{constructor(e){switch(super(),this.params=e,this.subscriptions=[],this.authenticated=!1,e.stream){case"account":this.host=e.credentials.key.startsWith("PK")?urls.websocket.account_paper:urls.websocket.account;break;case"market_data":this.host=urls.websocket.market_data;break;default:this.host="unknown"}this.connection=new node(this.host),this.connection.onopen=()=>{this.authenticated||this.connection.send(JSON.stringify({action:"authenticate",data:{key_id:e.credentials.key,secret_key:e.credentials.secret}})),this.emit("open",this)},this.connection.onclose=()=>this.emit("close",this),this.connection.onmessage=e=>{const t=JSON.parse(e.data);if("stream"in t&&"authorization"==t.stream){if("authorized"!=t.data.status)throw this.connection.close(),new Error("There was an error in authorizing your websocket connection. Object received: "+JSON.stringify(t,null,2));this.authenticated=!0,this.emit("authenticated",this),console.log("Connected to the websocket.")}if(this.emit("message",t),"stream"in t){const e={trade_updates:"trade_updates",account_updates:"account_updates",T:"trade",Q:"quote",AM:"aggregate_minute"};this.emit(e[t.stream.split(".")[0]],t.data)}},this.connection.onerror=e=>{this.emit("error",e)}}on(e,t){return super.on(e,t)}send(e){if(!this.authenticated)throw new Error("You can't send a message until you are authenticated!");return"object"==typeof e&&(e=JSON.stringify(e)),this.connection.send(e),this}subscribe(e){return this.subscriptions.push(...e),this.send(JSON.stringify({action:"listen",data:{streams:e}}))}unsubscribe(e){for(let t=0,r=this.subscriptions.length;t<r;t++)e.includes(this.subscriptions[t])&&this.subscriptions.splice(t,1);return this.send(JSON.stringify({action:"unlisten",data:{streams:e}}))}}var index={AlpacaClient:AlpacaClient,AlpacaStream:AlpacaStream};export default index;export{AlpacaClient,AlpacaStream};
  