redis-smq-common 3.0.0-rc.0 → 3.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,102 @@
1
1
 
2
2
 
3
- ## [3.0.0-rc.0](https://github.com/weyoss/redis-smq-common/compare/v2.0.0...v3.0.0-rc.0) (2023-11-19)
3
+ ## [3.0.0-rc.10](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.9...v3.0.0-rc.10) (2024-02-01)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * do not throw errors within async functions
9
+
10
+ ### Documentation
11
+
12
+ * update documentation ([a513ea8](https://github.com/weyoss/redis-smq-common/commit/a513ea83cf1284e3dcba09351674006bb3193aef))
13
+
14
+
15
+ ### Codebase Refactoring
16
+
17
+ * do not throw errors within async functions ([74dfbb6](https://github.com/weyoss/redis-smq-common/commit/74dfbb654a9a62d1802b3ed80485b76a40c85976))
18
+
19
+
20
+ ### Tests
21
+
22
+ * do not throw errors within async function ([a77eaf2](https://github.com/weyoss/redis-smq-common/commit/a77eaf28c384114f02aef22ffe8abe93da692d91))
23
+
24
+ ## [3.0.0-rc.9](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.8...v3.0.0-rc.9) (2024-01-25)
25
+
26
+
27
+ ### Misc
28
+
29
+ * update package-lock.json ([d001ba1](https://github.com/weyoss/redis-smq-common/commit/d001ba1938ed34e4a76f5da1814de56dde72ca99))
30
+
31
+ ## [3.0.0-rc.8](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.7...v3.0.0-rc.8) (2024-01-25)
32
+
33
+
34
+ ### ⚠ BREAKING CHANGES
35
+
36
+ * drop support for node-redis v3
37
+
38
+ ### Documentation
39
+
40
+ * drop support for node-redis v3 ([3481d53](https://github.com/weyoss/redis-smq-common/commit/3481d53de1df805e9a4fc9ec244c6f6b7e131947))
41
+
42
+
43
+ ### Codebase Refactoring
44
+
45
+ * drop support for node-redis v3 ([0b89843](https://github.com/weyoss/redis-smq-common/commit/0b8984396ec0ccb57eb1e183e9b7b0a6f1935e9b))
46
+
47
+ ## [3.0.0-rc.7](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.6...v3.0.0-rc.7) (2023-11-26)
48
+
49
+
50
+ ### ⚠ BREAKING CHANGES
51
+
52
+ * **event-emitter:** add typed EventEmitter, remove legacy events
53
+
54
+ ### Features
55
+
56
+ * **event-emitter:** add typed EventEmitter, remove legacy events ([65d57c3](https://github.com/weyoss/redis-smq-common/commit/65d57c31639add4808edfb5d2db4ed6a4cb6bf58))
57
+
58
+
59
+ ### Documentation
60
+
61
+ * add typed EventEmitter, remove legacy events ([a9f979a](https://github.com/weyoss/redis-smq-common/commit/a9f979a24f334ed345b6e0caf15357d4a5a1fd92))
62
+
63
+
64
+ ### Tests
65
+
66
+ * add typed EventEmitter, remove legacy events ([4ba6ec8](https://github.com/weyoss/redis-smq-common/commit/4ba6ec8bf8c1d37e849e6f25de70ea0b660506d0))
67
+
68
+ ## [3.0.0-rc.6](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.5...v3.0.0-rc.6) (2023-11-20)
69
+
70
+
71
+ ### ⚠ BREAKING CHANGES
72
+
73
+ * **redis-client:** support redis server starting from 4.0.0
74
+
75
+ ### Features
76
+
77
+ * **redis-client:** support redis server starting from 4.0.0 ([84d6b66](https://github.com/weyoss/redis-smq-common/commit/84d6b6686e366568002b58a454d7684fa4e7a646))
78
+
79
+
80
+ ### Continuous Integration
81
+
82
+ * drop support for redis server 2.8 and 3 ([444d1fd](https://github.com/weyoss/redis-smq-common/commit/444d1fde37385f21576dc4f8b9cada07bff1c373))
83
+
84
+ ## [3.0.0-rc.5](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.4...v3.0.0-rc.5) (2023-11-19)
85
+
86
+
87
+ ### Documentation
88
+
89
+ * remove logs.md and redis.md, update README.md ([be2ebd8](https://github.com/weyoss/redis-smq-common/commit/be2ebd8ef0b8acbbcb37572363528dfcf968679a))
90
+
91
+ ## [3.0.0-rc.4](https://github.com/weyoss/redis-smq-common/compare/v3.0.0-rc.3...v3.0.0-rc.4) (2023-11-19)
92
+
93
+
94
+ ### Misc
95
+
96
+ * add typescript declaration file entry ([453f103](https://github.com/weyoss/redis-smq-common/commit/453f1036cb0c89cf10372c14d44b336b19add370))
97
+ * update .npmignore ([6b41b6d](https://github.com/weyoss/redis-smq-common/commit/6b41b6dad1c9d587001b331f29d401d653c066b3))
98
+
99
+ ## [3.0.0-rc.3](https://github.com/weyoss/redis-smq-common/compare/v2.0.0...v3.0.0-rc.3) (2023-11-19)
4
100
 
5
101
 
6
102
  ### ⚠ BREAKING CHANGES
package/dist/index.cjs CHANGED
@@ -1,4 +1,3 @@
1
- "use strict";var xt=Object.create;var D=Object.defineProperty,Tt=Object.defineProperties,Rt=Object.getOwnPropertyDescriptor,yt=Object.getOwnPropertyDescriptors,Et=Object.getOwnPropertyNames,nt=Object.getOwnPropertySymbols,St=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty,Ot=Object.prototype.propertyIsEnumerable;var st=(o,r,t)=>r in o?D(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,V=(o,r)=>{for(var t in r||(r={}))ot.call(r,t)&&st(o,t,r[t]);if(nt)for(var t of nt(r))Ot.call(r,t)&&st(o,t,r[t]);return o},lt=(o,r)=>Tt(o,yt(r));var Nt=(o,r)=>{for(var t in r)D(o,t,{get:r[t],enumerable:!0})},at=(o,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of Et(r))!ot.call(o,e)&&e!==t&&D(o,e,{get:()=>r[e],enumerable:!(i=Rt(r,e))||i.enumerable});return o};var j=(o,r,t)=>(t=o!=null?xt(St(o)):{},at(r||!o||!o.__esModule?D(t,"default",{value:o,enumerable:!0}):t,o)),Lt=o=>at(D({},"__esModule",{value:!0}),o);var Xt={};Nt(Xt,{CallbackEmptyReplyError:()=>b,CallbackInvalidReplyError:()=>G,ERedisConfigClient:()=>Y,Lock:()=>F,LockAbortError:()=>x,LockAcquireError:()=>y,LockError:()=>h,LockExtendError:()=>L,LockMethodNotAllowedError:()=>M,LockNotAcquiredError:()=>A,LockNotReleasedError:()=>U,LoggerError:()=>P,PanicError:()=>R,PowerSwitch:()=>I,PowerSwitchError:()=>T,RedisClient:()=>k,RedisClientError:()=>u,RedisSMQError:()=>g,Ticker:()=>S,TickerError:()=>N,WatchedKeysChangedError:()=>f,Worker:()=>X,WorkerError:()=>E,WorkerPool:()=>W,WorkerRunner:()=>q,async:()=>v,events:()=>p,logger:()=>pt,redis:()=>It});module.exports=Lt(Xt);var Y=(i=>(i.REDIS="redis",i.IOREDIS="ioredis",i.REDIS_V4="redis_v4",i))(Y||{});var g=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var b=class extends g{constructor(){super("Expected a non-empty reply")}};var G=class extends g{constructor(){super("Invalid reply type")}};var R=class extends g{};var P=class extends g{};var N=class extends g{};var h=class extends g{};var x=class extends h{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var y=class extends h{constructor(r="Could not acquire a lock"){super(r)}};var L=class extends h{constructor(r="Acquired lock could not be extended"){super(r)}};var M=class extends h{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var A=class extends h{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var U=class extends h{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends g{};var f=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var E=class extends R{};var T=class extends g{};var ut=require("uuid");var et=j(require("fs"),1),rt=require("path");var gt=require("events");var ct=(o,r,t)=>{if(o.length){let i=0,e=()=>{r(o[i],i,n=>{i+=1,n||i>=o.length?t(n):setTimeout(()=>e(),0)})};e()}else t()},dt=(o,r,t)=>{let i=Object.keys(o);if(i.length){let e=0,n=()=>{let s=i[e];r(o[s],s,l=>{e+=1,l||e>=i.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},Mt=(o,r,t)=>{Array.isArray(o)?ct(o,r,t):dt(o,r,t)},At=(o,r)=>{if(o.length){let t=0,i=(e,...n)=>{t+=1,e?r(e):t<o.length?setTimeout(()=>{n.length?o[t](...n,i):o[t](i)},0):n.length?r(null,n[0]):r()};o[t](i)}else r()},v={each:Mt,eachIn:dt,eachOf:ct,waterfall:At};var tt=j(require("fs"),1),it=require("path");var z=class z{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",tt.default.readFileSync((0,it.resolve)(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",tt.default.readFileSync((0,it.resolve)(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let i=[];this.scripts.forEach(e=>i.push(n=>{e.id?n():r.loadScript(e.content,(s,l)=>{s?n(s):l?(e.id=l,n()):n(new b)})})),v.waterfall(i,e=>{e?t(e):(this.isLoaded=!0,t())})}}getScriptId(r){var i;let{id:t}=(i=this.scripts.get(r))!=null?i:{};if(!t)throw new u(`ID of script [${r}] is missing`);return t}static getInstance(){return z.instance||(z.instance=new z),z.instance}};z.instance=null;var H=z;var zt=[2,8,0],C=class C extends gt.EventEmitter{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,i=0,e=0){if(!C.redisServerVersion)throw new u("UNKNOWN_REDIS_SERVER_VERSION");return C.redisServerVersion[0]>t||C.redisServerVersion[0]===t&&C.redisServerVersion[1]>=i&&C.redisServerVersion[2]>=e}validateRedisServerSupport(t){let i=e=>{let[n,s,l]=zt;this.validateRedisVersion(n,s,l)?e():e(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};C.redisServerVersion?i(t):this.updateServerVersion(e=>{e?t(e):i(t)})}sscanAll(t,i,e){let n=new Set,s=l=>{this.sscan(t,l,i,(a,c)=>{a?e(a):c?(c.items.forEach(d=>n.add(d)),c.cursor==="0"?e(null,[...n]):s(c.cursor)):e(new b)})};s("0")}hscanAll(t,i,e){let n={},s=l=>{this.hscan(t,l,i,(a,c)=>{a?e(a):c?(Object.assign(n,c.result),c.cursor==="0"?e(null,n):s(c.cursor)):e(new b)})};s("0")}zpoprpush(t,i,e){this.runScript("ZPOPRPUSH",[t,i],[],(n,s)=>{n?e(n):e(null,typeof s=="string"?s:null)})}lpoprpush(t,i,e){this.validateRedisVersion(6,2)?this.lmove(t,i,"LEFT","RIGHT",e):this.runScript("LPOPRPUSH",[t,i],[],(n,s)=>{n?e(n):e(null,typeof s=="string"?s:null)})}updateServerVersion(t){C.redisServerVersion?t():this.getInfo((i,e)=>{i?t(i):e?(C.redisServerVersion=e.split(`\r
2
- `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new b)})}loadScripts(t){H.getInstance().loadScripts(this,t)}runScript(t,i,e,n){let s=H.getInstance().getScriptId(t);this.evalsha(s,[i.length,...i,...e],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,i){if(!H.getInstance().addScript(t,i))throw new u(`A script with name [${t}] already exists`)}};C.redisServerVersion=null;var k=C;k.addScript("RELEASE_LOCK",et.default.readFileSync((0,rt.resolve)(__dirname,"./lua/release-lock.lua")).toString());k.addScript("EXTEND_LOCK",et.default.readFileSync((0,rt.resolve)(__dirname,"./lua/extend-lock.lua")).toString());var F=class{constructor(r,t,i,e=!1,n=!1,s=!0){this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.throwExceptions=!0;this.lockKey=t,this.ttl=i,this.retryOnFail=e,this.lockId=(0,ut.v4)(),this.redisClient=r,this.autoExtend=n,this.throwExceptions=s}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(r){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(t,i)=>{t?r(t):this.status===4?i?(this.setExtended(),r()):(this.setUnlocked(),r(new L)):r(new x)})):r(new A)}runAutoExtendTimer(){let r=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(t=>{if(!t)this.runAutoExtendTimer();else if(this.throwExceptions&&!(t instanceof x))throw t}),r)}acquireLock(r){if(!this.isReleased())r(new U);else{this.status=1;let t=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(i,e)=>{i?r(i):this.status===1?e?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),r()):this.retryOnFail?this.lockingTimer=setTimeout(t,1e3):(this.setUnlocked(),r(new y)):r(new x)}):r(new x)};t()}}extendLock(r){this.autoExtend?r(new M):this.extend(r)}releaseLock(r){this.status===0?r():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],i=>{i?r(i):(this.setUnlocked(),r())})):r(new A)}acquireOrExtend(r){if(this.autoExtend)r(new M);else{let t=()=>{this.acquireLock(i=>{i?r(i):r(null,2)})};this.isLocked()?this.extend(i=>{i?i instanceof L?t():r(i):r(null,5)}):t()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var I=class{constructor(r=!0){this.isPowered=!1;this.pendingState=null;this.throwExceptionOnError=r}switch(r){if(this.pendingState!==null){if(this.throwExceptionOnError)throw new T("Can not switch state while another state transition is in progress.");return!1}if(r===this.isPowered){if(this.throwExceptionOnError)throw new T("Can not switch to the same current state.");return!1}return this.pendingState=r,!0}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){if(this.pendingState===null)throw new T("Expected a pending state");this.isPowered=this.pendingState,this.pendingState=null}rollback(){if(this.pendingState===null)throw new T("Expected a pending state");this.pendingState=null}};var ht=require("events");var p={GOING_UP:"going_up",UP:"up",GOING_DOWN:"going_down",DOWN:"down",ERROR:"error",TICK:"tick"};var S=class extends ht.EventEmitter{constructor(t=()=>{},i=1e3){super();this.powerManager=new I;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=i,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit(p.DOWN)}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let i=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,i()}else this.emit(p.ERROR,new R("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit(p.DOWN)):this.aborted&&this.powerManager.isDown()?this.emit(p.DOWN):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){if(this.isTicking())throw new N("A timer is already running");this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){if(this.isTicking())throw new N("A timer is already running");this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time))}};var X=class{constructor(r,t=1e3){this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new E("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(r=>{if(r)throw r;this.getTicker().nextTick()})};this.run=()=>{if(this.managed)throw new E("You can not run a managed worker");let r=this.getPowerManager();r.goingUp(),this.getTicker().nextTick(),r.commit()};this.quit=r=>{if(this.managed)r();else{let t=this.getPowerManager();t.goingDown();let i=this.getTicker();i.on(p.DOWN,()=>{t.commit(),r()}),i.quit()}};this.managed=r,r||(this.ticker=new S(this.onTick,t),this.powerManager=new I)}getPowerManager(){if(!this.powerManager)throw new E("Expected an instance of PowerSwitch");return this.powerManager}};var mt=require("events");var q=class extends mt.EventEmitter{constructor(t,i,e,n){super();this.onTick=()=>{v.waterfall([t=>{this.lock.acquireOrExtend((i,e)=>{e===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(i)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof y?this.ticker.nextTick():this.emit(p.ERROR,t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once(p.DOWN,t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=()=>{this.emit(p.UP),this.ticker.nextTick()};this.quit=t=>{v.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit(p.DOWN),t()})};this.powerManager=new I,this.redisClient=t,this.logger=n,this.lock=new F(t,i,6e4),this.ticker=new S(this.onTick),this.workerPool=e}addWorker(t){this.workerPool.add(t)}};var W=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(i=>e=>i.work(e));v.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{v.each(this.pool,(t,i,e)=>{t.quit(e)},()=>{this.pool=[],r()})}}};var bt=require("bunyan");var _=()=>{},Pt={debug:_,warn:_,info:_,error:_},w=null;function Ut(){w=null}function Ht(o){if(w)throw new P("Logger has been already initialized.");w=o}function Ft(o,r){var t;if(!o.enabled)return Pt;if(w||(w=(0,bt.createLogger)(lt(V({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let i=(e,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[e](a,...l)};return{info:i("info",w),warn:i("warn",w),debug:i("debug",w),error:i("error",w)}}return w}var pt={getLogger:Ft,setLogger:Ht,destroy:Ut};var kt=require("redis");var K=class{constructor(r){this.multi=r.multi()}lrem(r,t,i){return this.multi.lrem(r,t,i),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,i){return this.multi.ltrim(r,t,i),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,i){return this.multi.zadd(r,t,i),this}zrem(r,t){return this.multi.zrem(r,t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,t),this}hset(r,t,i){return this.multi.hset(r,t,String(i)),this}hdel(r,t){return this.multi.hdel(r,t),this}hincrby(r,t,i){return this.multi.hincrby(r,t,i),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec((t,i)=>{t?r(t):i?r(null,i):r(new f)})}};var Dt=function(o){return o?this.flush_and_error({message:"Connection forcefully ended and command aborted.",code:"NR_CLOSED"}):arguments.length===0&&this.warn(`Using .end() without the flush parameter is deprecated and throws from v.3.0.0 on.
3
- Please check the doku (https://github.com/NodeRedis/node_redis) and explictly use flush.`),this.retry_timer&&(clearTimeout(this.retry_timer),this.retry_timer=null),this.stream.removeAllListeners(),this.stream.once("close",()=>{this.emit("end"),this.emitted_end=!0}),this.stream.on("error",()=>{}),this.connected=!1,this.ready=!1,this.closing=!0,this.stream.destroySoon()},Q=class extends k{constructor(t={}){super();this.client=(0,kt.createClient)(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.end=Dt}set(t,i,e,n){e.exists&&e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,e.exists,n):e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,n):e.exists?this.client.set(t,i,e.exists,n):this.client.set(t,i,n)}zadd(t,i,e,n){this.client.zadd(t,i,e,n)}multi(){return new K(this.client)}watch(t,i){this.client.watch(t,i)}unwatch(t){this.client.unwatch(t)}sismember(t,i,e){this.client.sismember(t,i,e)}sscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new b);else{let c=new Set,[d,m]=a;for(;m.length;){let O=String(m.shift()),wt=String(m.shift());c.add(O)}n(null,{cursor:d,items:[...c]})}})}zcard(t,i){this.client.zcard(t,i)}zrange(t,i,e,n){this.client.zrange(t,i,e,n)}zrevrange(t,i,e,n){this.client.zrevrange(t,i,e,n)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,i,e,n,s,l){this.client.zrangebyscore(t,i,e,"LIMIT",n,s,l)}zrem(t,i,e){this.client.zrem(t,i,e)}smembers(t,i){this.client.smembers(t,i)}sadd(t,i,e){this.client.sadd(t,i,e)}srem(t,i,e){this.client.srem(t,i,e)}hgetall(t,i){this.client.hgetall(t,(e,n)=>{e?i(e):i(null,n!=null?n:{})})}hscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let d={};for(;c.length;){let m=String(c.shift());d[m]=String(c.shift())}n(null,{cursor:a,result:d})}})}hget(t,i,e){this.client.hget(t,i,e)}hset(t,i,e,n){this.client.hset(t,i,String(e),n)}hdel(t,i,e){this.client.hdel(t,...typeof i=="string"?[i]:i,e)}lrange(t,i,e,n){this.client.lrange(t,i,e,n)}hkeys(t,i){this.client.hkeys(t,i)}hlen(t,i){this.client.hlen(t,i)}brpoplpush(t,i,e,n){this.client.brpoplpush(t,i,e,n)}rpoplpush(t,i,e){this.client.rpoplpush(t,i,e)}zrangebyscorewithscores(t,i,e,n){this.client.zrangebyscore(t,i,e,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let d=a.splice(0,2);d.length>0;d=a.splice(0,2)){let[m,O]=d;c[O]=m}n(null,c)}})}rpop(t,i){this.client.rpop(t,i)}lrem(t,i,e,n){this.client.lrem(t,i,e,n)}publish(t,i,e){this.client.publish(t,i,e)}flushall(t){this.client.flushall(t)}loadScript(t,i){this.client.script("load",t,i)}evalsha(t,i,e){let n=[t],s=Array.isArray(i)?i:[i];this.client.evalsha(n.concat(s),(l,a)=>e(l,a))}get(t,i){this.client.get(t,i)}del(t,i){this.client.del(...typeof t=="string"?[t]:t,i)}llen(t,i){this.client.llen(t,i)}lmove(t,i,e,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,i,e,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,i,e,n){this.client.zremrangebyscore(t,i,e,n)}hmget(t,i,e){this.client.hmget(t,i,e)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end(!0))}end(t){this.connectionClosed||this.client.end(t)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,i){return this.client.on(t,i),this}};var Ct=require("@redis/client");var vt=require("@redis/client");var $=class{constructor(r){this.multi=r.multi()}lrem(r,t,i){return this.multi.lRem(r,t,i),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,i){return this.multi.lTrim(r,t,i),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,i){return this.multi.zAdd(r,{score:t,value:i}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,i){return this.multi.hSet(r,t,i),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,i){return this.multi.hIncrBy(r,t,i),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof vt.WatchError?r(new f):r(t)})}};var J=class extends k{constructor(t={}){super();this.client=(0,Ct.createClient)(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,i,e,n){this.client.set(t,i,V(V({},e.expire?{[e.expire.mode]:e.expire.value}:{}),e.exists?{[e.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,i,e,n){this.client.zAdd(t,{score:i,value:e}).then(s=>n(null,s)).catch(n)}multi(){return new $(this.client)}watch(t,i){this.client.watch(t).then(e=>i(null,e)).catch(i)}unwatch(t){this.client.unwatch().then(i=>t(null,i)).catch(t)}sismember(t,i,e){this.client.sIsMember(t,i).then(n=>e(null,Number(n))).catch(e)}zcard(t,i){this.client.zCard(t).then(e=>i(null,e)).catch(i)}zrange(t,i,e,n){this.client.zRange(t,i,e).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,i,e,n){this.client.sendCommand(["ZREVRANGE",t,String(i),String(e)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,i,e){this.client.zRem(t,i).then(n=>e(null,n)).catch(e)}psubscribe(t){this.client.pSubscribe(t,(i,e)=>{this.client.emit("pmessage",t,e,i)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(i,e)=>{this.client.emit("message",e,i)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,i,e,n,s,l){this.client.zRangeByScore(t,i,e,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,i){this.client.sMembers(t).then(e=>i(null,e)).catch(i)}sscan(t,i,e,n){let s=[t,Number(i),e];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,i,e,n){let s=[t,Number(i),e];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let d of a)c.add(d.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,i,e){this.client.sAdd(t,i).then(n=>e(null,n)).catch(e)}srem(t,i,e){this.client.sRem(t,i).then(n=>e(null,n)).catch(e)}hgetall(t,i){this.client.hGetAll(t).then(e=>i(null,e)).catch(i)}hscan(t,i,e,n){let s=[t,Number(i),e];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let d=a.shift();d&&(c[d.field]=d.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,i,e){this.client.hGet(t,i).then(n=>e(null,n!=null?n:null)).catch(e)}hset(t,i,e,n){this.client.hSet(t,i,e).then(s=>n(null,s)).catch(n)}hdel(t,i,e){this.client.hDel(t,i).then(n=>e(null,Number(n))).catch(e)}lrange(t,i,e,n){this.client.lRange(t,i,e).then(s=>n(null,s)).catch(n)}hkeys(t,i){this.client.hKeys(t).then(e=>i(null,e)).catch(i)}hlen(t,i){this.client.hLen(t).then(e=>i(null,e)).catch(i)}brpoplpush(t,i,e,n){this.client.brPopLPush(t,i,e).then(s=>n(null,s)).catch(n)}rpoplpush(t,i,e){this.client.rPopLPush(t,i).then(n=>e(null,n)).catch(e)}zrangebyscorewithscores(t,i,e,n){this.client.zRangeByScoreWithScores(t,i,e).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,i){this.client.rPop(t).then(e=>i(null,e)).catch(i)}lrem(t,i,e,n){this.client.lRem(t,i,e).then(s=>n(null,s)).catch(n)}publish(t,i,e){this.client.publish(t,i).then(n=>e(null,n)).catch(e)}flushall(t){this.client.flushAll().then(i=>t(null,i)).catch(t)}loadScript(t,i){this.client.sendCommand(["SCRIPT","LOAD",t]).then(e=>i(null,typeof e=="string"?e:String(e))).catch(i)}evalsha(t,i,e){let n=[t],s=Array.isArray(i)?i:[i];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?e(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?e(null,l.toString()):e(null,l)}).catch(e)}get(t,i){this.client.sendCommand(["get",t]).then(e=>i(null,typeof e=="string"?e:null)).catch(i)}del(t,i){this.client.del(t).then(e=>i(null,e)).catch(i)}llen(t,i){this.client.sendCommand(["llen",t]).then(e=>i(null,Number(e))).catch(i)}lmove(t,i,e,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,i,e,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,i,e,n){this.client.sendCommand(["zremrangebyscore",t,`${i}`,`${e}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,i,e){this.client.hmGet(t,i).then(n=>e(null,n)).catch(e)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(i=>t(null,i)).catch(t)}on(t,i){return this.client.on(t,i),this}};var ft=j(require("ioredis"),1);var B=class{constructor(r){this.multi=r.multi()}lrem(r,t,i){return this.multi.lrem(r,t,i),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,i){return this.multi.ltrim(r,t,i),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,i){return this.multi.zadd(r,t,i),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,i){return this.multi.hset(r,t,i),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,i){return this.multi.hincrby(r,t,i),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,i)=>{if(t)r(t);else if(!i)r(new f);else{let e=[],n=null;for(let s of i){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}e.push(a)}n?r(n):r(null,e)}})}};var Z=class extends k{constructor(t={}){super();this.client=new ft.default(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,i,e,n){e.exists&&e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,e.exists,n):e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,n):e.exists?this.client.set(t,i,e.exists,n):this.client.set(t,i,n)}zadd(t,i,e,n){this.client.zadd(t,i,e,n)}multi(){return new B(this.client)}watch(t,i){this.client.watch(t,i)}unwatch(t){this.client.unwatch(t)}sismember(t,i,e){this.client.sismember(t,i,e)}sscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,i){this.client.zcard(t,i)}zrange(t,i,e,n){this.client.zrange(t,i,e,n)}zscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new b);else{let c=new Set,[d,m]=a;for(;m.length;){let O=String(m.shift()),wt=String(m.shift());c.add(O)}n(null,{cursor:d,items:[...c]})}})}zrevrange(t,i,e,n){this.client.zrevrange(t,i,e,n)}zrem(t,i,e){this.client.zrem(t,i,e)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,i,e,n,s,l){this.client.zrangebyscore(t,i,e,"LIMIT",n,s,l)}smembers(t,i){this.client.smembers(t,i)}sadd(t,i,e){this.client.sadd(t,i,e)}srem(t,i,e){this.client.srem(t,i,e)}hgetall(t,i){this.client.hgetall(t,i)}hscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let d={};for(;c.length;){let m=String(c.shift());d[m]=String(c.shift())}n(null,{cursor:a,result:d})}})}hget(t,i,e){this.client.hget(t,i,e)}hset(t,i,e,n){this.client.hset(t,i,e,n)}hdel(t,i,e){this.client.hdel(t,i,e)}lrange(t,i,e,n){this.client.lrange(t,i,e,n)}hkeys(t,i){this.client.hkeys(t,i)}hlen(t,i){this.client.hlen(t,i)}brpoplpush(t,i,e,n){this.client.brpoplpush(t,i,e,n)}rpoplpush(t,i,e){this.client.rpoplpush(t,i,e)}zrangebyscorewithscores(t,i,e,n){this.client.zrangebyscore(t,i,e,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let d=a.splice(0,2);d.length>0;d=a.splice(0,2)){let[m,O]=d;c[O]=m}n(null,c)}})}rpop(t,i){this.client.rpop(t,i)}lrem(t,i,e,n){this.client.lrem(t,i,e,n)}publish(t,i,e){this.client.publish(t,i,e)}flushall(t){this.client.flushall(t)}loadScript(t,i){this.client.script("load",t,i)}evalsha(t,i,e){let n=[t],s=Array.isArray(i)?i:[i];this.client.evalsha(n.concat(s),e)}get(t,i){this.client.get(t,i)}del(t,i){this.client.del(t,i)}llen(t,i){this.client.llen(t,i)}lmove(t,i,e,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,i,e,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,i,e,n){this.client.zremrangebyscore(t,i,e,n)}hmget(t,i,e){this.client.hmget(t,i,e)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,i){return this.client.on(t,i),this}};function Vt(o){return o.client==="redis"?new Q(o.options):o.client==="redis_v4"?new J(o.options):new Z(o.options)}function Gt(o,r){let t=Vt(o);t.once("ready",()=>{v.waterfall([i=>t.validateRedisServerSupport(i),i=>t.loadScripts(i)],i=>{if(i)throw i;r(null,t)})})}var It={createInstance:Gt};0&&(module.exports={CallbackEmptyReplyError,CallbackInvalidReplyError,ERedisConfigClient,Lock,LockAbortError,LockAcquireError,LockError,LockExtendError,LockMethodNotAllowedError,LockNotAcquiredError,LockNotReleasedError,LoggerError,PanicError,PowerSwitch,PowerSwitchError,RedisClient,RedisClientError,RedisSMQError,Ticker,TickerError,WatchedKeysChangedError,Worker,WorkerError,WorkerPool,WorkerRunner,async,events,logger,redis});
1
+ "use strict";var ft=Object.create;var F=Object.defineProperty,Ct=Object.defineProperties,It=Object.getOwnPropertyDescriptor,xt=Object.getOwnPropertyDescriptors,Tt=Object.getOwnPropertyNames,rt=Object.getOwnPropertySymbols,wt=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty,Et=Object.prototype.propertyIsEnumerable;var nt=(o,r,t)=>r in o?F(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,D=(o,r)=>{for(var t in r||(r={}))st.call(r,t)&&nt(o,t,r[t]);if(rt)for(var t of rt(r))Et.call(r,t)&&nt(o,t,r[t]);return o},ot=(o,r)=>Ct(o,xt(r));var yt=(o,r)=>{for(var t in r)F(o,t,{get:r[t],enumerable:!0})},lt=(o,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Tt(r))!st.call(o,i)&&i!==t&&F(o,i,{get:()=>r[i],enumerable:!(e=It(r,i))||e.enumerable});return o};var J=(o,r,t)=>(t=o!=null?ft(wt(o)):{},lt(r||!o||!o.__esModule?F(t,"default",{value:o,enumerable:!0}):t,o)),Rt=o=>lt(F({},"__esModule",{value:!0}),o);var Ht={};yt(Ht,{CallbackEmptyReplyError:()=>h,CallbackInvalidReplyError:()=>q,ERedisConfigClient:()=>Z,EventEmitter:()=>x,Lock:()=>H,LockAbortError:()=>I,LockAcquireError:()=>w,LockError:()=>m,LockExtendError:()=>M,LockMethodNotAllowedError:()=>A,LockNotAcquiredError:()=>N,LockNotReleasedError:()=>z,LoggerError:()=>O,PanicError:()=>T,PowerSwitch:()=>f,RedisClient:()=>v,RedisClientError:()=>u,RedisSMQError:()=>d,Ticker:()=>R,TickerError:()=>L,WatchedKeysChangedError:()=>E,Worker:()=>X,WorkerError:()=>y,WorkerPool:()=>V,WorkerRunner:()=>G,async:()=>b,getEventBusInstance:()=>p,logger:()=>ht,redis:()=>vt});module.exports=Rt(Ht);var Z=(t=>(t.IOREDIS="ioredis",t.REDIS="redis",t))(Z||{});var d=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var h=class extends d{constructor(){super("Expected a non-empty reply")}};var q=class extends d{constructor(){super("Invalid reply type")}};var T=class extends d{};var O=class extends d{};var L=class extends d{};var m=class extends d{};var I=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var w=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var M=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var A=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var N=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var z=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends d{};var E=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var y=class extends T{};var gt=require("uuid");var et=J(require("fs"),1),it=require("path");var ut=require("events");var at=(o,r,t)=>{if(o.length){let e=0,i=()=>{r(o[e],e,n=>{e+=1,n||e>=o.length?t(n):setTimeout(()=>i(),0)})};i()}else t()},ct=(o,r,t)=>{let e=Object.keys(o);if(e.length){let i=0,n=()=>{let s=e[i];r(o[s],s,l=>{i+=1,l||i>=e.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},St=(o,r,t)=>{Array.isArray(o)?at(o,r,t):ct(o,r,t)},Lt=(o,r)=>{if(o.length){let t=0,e=(i,...n)=>{t+=1,i?r(i):t<o.length?setTimeout(()=>{n.length?o[t](...n,e):o[t](e)},0):n.length?r(null,n[0]):r()};o[t](e)}else r()},b={each:St,eachIn:ct,eachOf:at,waterfall:Lt};var j=J(require("fs"),1),Y=require("path");var P=class P{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",j.default.readFileSync((0,Y.resolve)(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",j.default.readFileSync((0,Y.resolve)(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let e=[];this.scripts.forEach(i=>e.push(n=>{i.id?n():r.loadScript(i.content,(s,l)=>{s?n(s):l?(i.id=l,n()):n(new h)})})),b.waterfall(e,i=>{i?t(i):(this.isLoaded=!0,t())})}}getScriptId(r){var e;let{id:t}=(e=this.scripts.get(r))!=null?e:{};return t||new u(`ID of script [${r}] is missing`)}static getInstance(){return P.instance||(P.instance=new P),P.instance}};P.instance=null;var U=P;var dt=require("events"),x=class extends dt.EventEmitter{};var tt=null;function p(){return tt||(tt=new x),tt}var Mt=[4,0,0],k=class k extends ut.EventEmitter{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,e=0,i=0){return k.redisServerVersion?k.redisServerVersion[0]>t||k.redisServerVersion[0]===t&&k.redisServerVersion[1]>=e&&k.redisServerVersion[2]>=i:(p().emit("error",new u("UNKNOWN_REDIS_SERVER_VERSION")),!1)}validateRedisServerSupport(t){let e=i=>{let[n,s,l]=Mt;this.validateRedisVersion(n,s,l)?i():i(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};k.redisServerVersion?e(t):this.updateServerVersion(i=>{i?t(i):e(t)})}sscanAll(t,e,i){let n=new Set,s=l=>{this.sscan(t,l,e,(a,c)=>{a?i(a):c?(c.items.forEach(g=>n.add(g)),c.cursor==="0"?i(null,[...n]):s(c.cursor)):i(new h)})};s("0")}hscanAll(t,e,i){let n={},s=l=>{this.hscan(t,l,e,(a,c)=>{a?i(a):c?(Object.assign(n,c.result),c.cursor==="0"?i(null,n):s(c.cursor)):i(new h)})};s("0")}zpoprpush(t,e,i){this.runScript("ZPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}lpoprpush(t,e,i){this.validateRedisVersion(6,2)?this.lmove(t,e,"LEFT","RIGHT",i):this.runScript("LPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}updateServerVersion(t){k.redisServerVersion?t():this.getInfo((e,i)=>{e?t(e):i?(k.redisServerVersion=i.split(`\r
2
+ `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new h)})}loadScripts(t){U.getInstance().loadScripts(this,t)}runScript(t,e,i,n){let s=U.getInstance().getScriptId(t);s instanceof Error?n(s):this.evalsha(s,[e.length,...e,...i],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,e){if(!U.getInstance().addScript(t,e))throw new u(`A script with name [${t}] already exists`)}};k.redisServerVersion=null;var v=k;v.addScript("RELEASE_LOCK",et.default.readFileSync((0,it.resolve)(__dirname,"./lua/release-lock.lua")).toString());v.addScript("EXTEND_LOCK",et.default.readFileSync((0,it.resolve)(__dirname,"./lua/extend-lock.lua")).toString());var H=class{constructor(r,t,e,i=!1,n=!1){this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.lockKey=t,this.ttl=e,this.retryOnFail=i,this.lockId=(0,gt.v4)(),this.redisClient=r,this.autoExtend=n}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(r){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(t,e)=>{t?r(t):this.status===4?e?(this.setExtended(),r()):(this.setUnlocked(),r(new M)):r(new I)})):r(new N)}runAutoExtendTimer(){let r=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(t=>{t?t instanceof I||p().emit("error",t):this.runAutoExtendTimer()}),r)}acquireLock(r){if(!this.isReleased())r(new z);else{this.status=1;let t=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(e,i)=>{e?r(e):this.status===1?i?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),r()):this.retryOnFail?this.lockingTimer=setTimeout(t,1e3):(this.setUnlocked(),r(new w)):r(new I)}):r(new I)};t()}}extendLock(r){this.autoExtend?r(new A):this.extend(r)}releaseLock(r){this.status===0?r():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],e=>{e?r(e):(this.setUnlocked(),r())})):r(new N)}acquireOrExtend(r){if(this.autoExtend)r(new A);else{let t=()=>{this.acquireLock(e=>{e?r(e):r(null,2)})};this.isLocked()?this.extend(e=>{e?e instanceof M?t():r(e):r(null,5)}):t()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var f=class{constructor(){this.isPowered=!1;this.pendingState=null}switch(r){return this.pendingState!==null||r===this.isPowered?!1:(this.pendingState=r,!0)}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){return this.pendingState===null?!1:(this.isPowered=this.pendingState,this.pendingState=null,!0)}rollback(){return this.pendingState===null?!1:(this.pendingState=null,!0)}};var R=class extends x{constructor(t=()=>{},e=1e3){super();this.powerManager=new f;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=e,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit("down")}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let e=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,e()}else p().emit("error",new T("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit("down")):this.aborted&&this.powerManager.isDown()?this.emit("down"):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){this.isTicking()?p().emit("error",new L("A timer is already running")):this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){this.isTicking()?p().emit("error",new L("A timer is already running")):(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time)))}};var X=class{constructor(r,t=1e3){this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new y("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(r=>{r?p().emit("error",r):this.getTicker().nextTick()})};this.run=r=>{if(this.managed)r(new y("You can not run a managed worker"));else{let t=this.getPowerManager();t.goingUp(),this.getTicker().nextTick(),t.commit(),r()}};this.quit=r=>{if(this.managed)r();else{let t=this.getPowerManager();t.goingDown();let e=this.getTicker();e.on("down",()=>{t.commit(),r()}),e.quit()}};this.managed=r,r||(this.ticker=new R(this.onTick,t),this.powerManager=new f)}getPowerManager(){if(!this.powerManager)throw new y("Expected an instance of PowerSwitch");return this.powerManager}};var G=class extends x{constructor(t,e,i,n){super();this.onTick=()=>{b.waterfall([t=>{this.lock.acquireOrExtend((e,i)=>{i===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(e)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof w?this.ticker.nextTick():this.emit("error",t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once("down",t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=t=>{this.ticker.nextTick(),this.emit("up"),t()};this.quit=t=>{b.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit("down"),t()})};this.powerManager=new f,this.redisClient=t,this.logger=n,this.lock=new H(t,e,6e4),this.ticker=new R(this.onTick),this.workerPool=i}addWorker(t){this.workerPool.add(t)}};var V=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(e=>i=>e.work(i));b.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{b.each(this.pool,(t,e,i)=>{t.quit(i)},()=>{this.pool=[],r()})}}};var mt=require("bunyan");var W=()=>{},At={debug:W,warn:W,info:W,error:W},C=null;function Nt(){C=null}function Pt(o){if(C)throw new O("Logger has been already initialized.");C=o}function Ot(o,r){var t;if(!o.enabled)return At;if(C||(C=(0,mt.createLogger)(ot(D({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let e=(i,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[i](a,...l)};return{info:e("info",C),warn:e("warn",C),debug:e("debug",C),error:e("error",C)}}return C}var ht={getLogger:Ot,setLogger:Pt,destroy:Nt};var pt=require("@redis/client");var bt=require("@redis/client");var K=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lRem(r,t,e),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,e){return this.multi.lTrim(r,t,e),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,e){return this.multi.zAdd(r,{score:t,value:e}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,e){return this.multi.hSet(r,t,e),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,e){return this.multi.hIncrBy(r,t,e),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof bt.WatchError?r(new E):r(t)})}};var B=class extends v{constructor(t={}){super();this.client=(0,pt.createClient)(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,e,i,n){this.client.set(t,e,D(D({},i.expire?{[i.expire.mode]:i.expire.value}:{}),i.exists?{[i.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,e,i,n){this.client.zAdd(t,{score:e,value:i}).then(s=>n(null,s)).catch(n)}multi(){return new K(this.client)}watch(t,e){this.client.watch(t).then(i=>e(null,i)).catch(e)}unwatch(t){this.client.unwatch().then(e=>t(null,e)).catch(t)}sismember(t,e,i){this.client.sIsMember(t,e).then(n=>i(null,Number(n))).catch(i)}zcard(t,e){this.client.zCard(t).then(i=>e(null,i)).catch(e)}zrange(t,e,i,n){this.client.zRange(t,e,i).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,e,i,n){this.client.sendCommand(["ZREVRANGE",t,String(e),String(i)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,e,i){this.client.zRem(t,e).then(n=>i(null,n)).catch(i)}psubscribe(t){this.client.pSubscribe(t,(e,i)=>{this.client.emit("pmessage",t,i,e)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(e,i)=>{this.client.emit("message",i,e)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,e,i,n,s,l){this.client.zRangeByScore(t,e,i,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,e){this.client.sMembers(t).then(i=>e(null,i)).catch(e)}sscan(t,e,i,n){let s=[t,Number(e),i];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,e,i,n){let s=[t,Number(e),i];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let g of a)c.add(g.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,e,i){this.client.sAdd(t,e).then(n=>i(null,n)).catch(i)}srem(t,e,i){this.client.sRem(t,e).then(n=>i(null,n)).catch(i)}hgetall(t,e){this.client.hGetAll(t).then(i=>e(null,i)).catch(e)}hscan(t,e,i,n){let s=[t,Number(e),i];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let g=a.shift();g&&(c[g.field]=g.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,e,i){this.client.hGet(t,e).then(n=>i(null,n!=null?n:null)).catch(i)}hset(t,e,i,n){this.client.hSet(t,e,i).then(s=>n(null,s)).catch(n)}hdel(t,e,i){this.client.hDel(t,e).then(n=>i(null,Number(n))).catch(i)}lrange(t,e,i,n){this.client.lRange(t,e,i).then(s=>n(null,s)).catch(n)}hkeys(t,e){this.client.hKeys(t).then(i=>e(null,i)).catch(e)}hlen(t,e){this.client.hLen(t).then(i=>e(null,i)).catch(e)}brpoplpush(t,e,i,n){this.client.brPopLPush(t,e,i).then(s=>n(null,s)).catch(n)}rpoplpush(t,e,i){this.client.rPopLPush(t,e).then(n=>i(null,n)).catch(i)}zrangebyscorewithscores(t,e,i,n){this.client.zRangeByScoreWithScores(t,e,i).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,e){this.client.rPop(t).then(i=>e(null,i)).catch(e)}lrem(t,e,i,n){this.client.lRem(t,e,i).then(s=>n(null,s)).catch(n)}publish(t,e,i){this.client.publish(t,e).then(n=>i(null,n)).catch(i)}flushall(t){this.client.flushAll().then(e=>t(null,e)).catch(t)}loadScript(t,e){this.client.sendCommand(["SCRIPT","LOAD",t]).then(i=>e(null,typeof i=="string"?i:String(i))).catch(e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?i(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?i(null,l.toString()):i(null,l)}).catch(i)}get(t,e){this.client.sendCommand(["get",t]).then(i=>e(null,typeof i=="string"?i:null)).catch(e)}del(t,e){this.client.del(t).then(i=>e(null,i)).catch(e)}llen(t,e){this.client.sendCommand(["llen",t]).then(i=>e(null,Number(i))).catch(e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,e,i,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.sendCommand(["zremrangebyscore",t,`${e}`,`${i}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,e,i){this.client.hmGet(t,e).then(n=>i(null,n)).catch(i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(e=>t(null,e)).catch(t)}on(t,e){return this.client.on(t,e),this}};var kt=J(require("ioredis"),1);var _=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lrem(r,t,e),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,e){return this.multi.ltrim(r,t,e),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,e){return this.multi.zadd(r,t,e),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,e){return this.multi.hset(r,t,e),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,e){return this.multi.hincrby(r,t,e),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,e)=>{if(t)r(t);else if(!e)r(new E);else{let i=[],n=null;for(let s of e){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}i.push(a)}n?r(n):r(null,i)}})}};var Q=class extends v{constructor(t={}){super();this.client=new kt.default(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,e,i,n){i.exists&&i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,i.exists,n):i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,n):i.exists?this.client.set(t,e,i.exists,n):this.client.set(t,e,n)}zadd(t,e,i,n){this.client.zadd(t,e,i,n)}multi(){return new _(this.client)}watch(t,e){this.client.watch(t,e)}unwatch(t){this.client.unwatch(t)}sismember(t,e,i){this.client.sismember(t,e,i)}sscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,e){this.client.zcard(t,e)}zrange(t,e,i,n){this.client.zrange(t,e,i,n)}zscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new h);else{let c=new Set,[g,S]=a;for(;S.length;){let $=String(S.shift()),Ft=String(S.shift());c.add($)}n(null,{cursor:g,items:[...c]})}})}zrevrange(t,e,i,n){this.client.zrevrange(t,e,i,n)}zrem(t,e,i){this.client.zrem(t,e,i)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,e,i,n,s,l){this.client.zrangebyscore(t,e,i,"LIMIT",n,s,l)}smembers(t,e){this.client.smembers(t,e)}sadd(t,e,i){this.client.sadd(t,e,i)}srem(t,e,i){this.client.srem(t,e,i)}hgetall(t,e){this.client.hgetall(t,e)}hscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let g={};for(;c.length;){let S=String(c.shift());g[S]=String(c.shift())}n(null,{cursor:a,result:g})}})}hget(t,e,i){this.client.hget(t,e,i)}hset(t,e,i,n){this.client.hset(t,e,i,n)}hdel(t,e,i){this.client.hdel(t,e,i)}lrange(t,e,i,n){this.client.lrange(t,e,i,n)}hkeys(t,e){this.client.hkeys(t,e)}hlen(t,e){this.client.hlen(t,e)}brpoplpush(t,e,i,n){this.client.brpoplpush(t,e,i,n)}rpoplpush(t,e,i){this.client.rpoplpush(t,e,i)}zrangebyscorewithscores(t,e,i,n){this.client.zrangebyscore(t,e,i,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let g=a.splice(0,2);g.length>0;g=a.splice(0,2)){let[S,$]=g;c[$]=S}n(null,c)}})}rpop(t,e){this.client.rpop(t,e)}lrem(t,e,i,n){this.client.lrem(t,e,i,n)}publish(t,e,i){this.client.publish(t,e,i)}flushall(t){this.client.flushall(t)}loadScript(t,e){this.client.script("load",t,e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.evalsha(n.concat(s),i)}get(t,e){this.client.get(t,e)}del(t,e){this.client.del(t,e)}llen(t,e){this.client.llen(t,e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,e,i,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.zremrangebyscore(t,e,i,n)}hmget(t,e,i){this.client.hmget(t,e,i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,e){return this.client.on(t,e),this}};function zt(o){return o.client==="redis"?new B(o.options):new Q(o.options)}function Ut(o,r){let t=zt(o);t.once("ready",()=>{b.waterfall([e=>t.validateRedisServerSupport(e),e=>t.loadScripts(e)],e=>{e?r(e):r(null,t)})})}var vt={createInstance:Ut};0&&(module.exports={CallbackEmptyReplyError,CallbackInvalidReplyError,ERedisConfigClient,EventEmitter,Lock,LockAbortError,LockAcquireError,LockError,LockExtendError,LockMethodNotAllowedError,LockNotAcquiredError,LockNotReleasedError,LoggerError,PanicError,PowerSwitch,RedisClient,RedisClientError,RedisSMQError,Ticker,TickerError,WatchedKeysChangedError,Worker,WorkerError,WorkerPool,WorkerRunner,async,getEventBusInstance,logger,redis});
4
3
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { RedisClientMultiCommandType } from '@redis/client/dist/lib/client/multi-command';
2
2
  import { RedisClientOptions, RedisModules, RedisFunctions, RedisScripts, RedisClientType } from '@redis/client';
3
- import { EventEmitter } from 'events';
3
+ import { EventEmitter as EventEmitter$1 } from 'events';
4
4
  import * as Logger from 'bunyan';
5
5
  import { RedisOptions } from 'ioredis';
6
- import { ClientOpts } from 'redis';
7
6
 
8
7
  interface ICallback<T> {
9
8
  (err?: Error | null, reply?: T): void;
@@ -17,22 +16,17 @@ interface IRedisConfigIORedis {
17
16
  options?: RedisOptions;
18
17
  }
19
18
  declare enum ERedisConfigClient {
20
- REDIS = "redis",
21
19
  IOREDIS = "ioredis",
22
- REDIS_V4 = "redis_v4"
20
+ REDIS = "redis"
23
21
  }
24
22
  interface IRedisConfigNodeRedis {
25
23
  client: ERedisConfigClient.REDIS;
26
- options?: ClientOpts;
27
- }
28
- interface IRedisConfigNodeRedisV4 {
29
- client: ERedisConfigClient.REDIS_V4;
30
24
  options?: RedisClientOptions;
31
25
  }
32
- type IRedisConfig = IRedisConfigIORedis | IRedisConfigNodeRedis | IRedisConfigNodeRedisV4;
26
+ type IRedisConfig = IRedisConfigIORedis | IRedisConfigNodeRedis;
33
27
 
34
- type TRedisTransactionNodeRedisV4 = RedisClientMultiCommandType<RedisModules, RedisFunctions, RedisScripts>;
35
- type TRedisClientNodeRedisV4 = RedisClientType<RedisModules, RedisFunctions, RedisScripts>;
28
+ type TRedisTransactionNodeRedis = RedisClientMultiCommandType<RedisModules, RedisFunctions, RedisScripts>;
29
+ type TRedisClientNodeRedis = RedisClientType<RedisModules, RedisFunctions, RedisScripts>;
36
30
  interface IRedisClient {
37
31
  validateRedisVersion(major: number, feature?: number, minor?: number): boolean;
38
32
  validateRedisServerSupport(cb: ICallback<void>): void;
@@ -146,15 +140,6 @@ declare module 'ioredis' {
146
140
  lmove(source: string, destination: string, from: 'LEFT' | 'RIGHT', to: 'LEFT' | 'RIGHT', cb: ICallback<string>): void;
147
141
  }
148
142
  }
149
- declare module 'redis' {
150
- interface Commands<R> {
151
- info(cb?: Callback<string>): R;
152
- info(section?: string | string[], cb?: Callback<string>): R;
153
- INFO(cb?: Callback<string>): R;
154
- INFO(section?: string | string[], cb?: Callback<string>): R;
155
- lmove(source: string, destination: string, from: 'LEFT' | 'RIGHT', to: 'LEFT' | 'RIGHT', cb: ICallback<string>): void;
156
- }
157
- }
158
143
 
159
144
  interface ILoggerConfig {
160
145
  enabled: boolean;
@@ -168,6 +153,16 @@ interface ILogger {
168
153
  debug(message: unknown, ...params: unknown[]): void;
169
154
  }
170
155
 
156
+ type TEvent = {
157
+ error: (err: Error) => void;
158
+ next: () => void;
159
+ up: () => void;
160
+ down: () => void;
161
+ goingUp: () => void;
162
+ goingDown: () => void;
163
+ tick: () => void;
164
+ };
165
+
171
166
  declare abstract class RedisSMQError extends Error {
172
167
  constructor(message?: string);
173
168
  get name(): string;
@@ -227,10 +222,7 @@ declare class WatchedKeysChangedError extends RedisClientError {
227
222
  declare class WorkerError extends PanicError {
228
223
  }
229
224
 
230
- declare class PowerSwitchError extends RedisSMQError {
231
- }
232
-
233
- declare abstract class RedisClient extends EventEmitter implements IRedisClient {
225
+ declare abstract class RedisClient extends EventEmitter$1 implements IRedisClient {
234
226
  protected static redisServerVersion: number[] | null;
235
227
  protected connectionClosed: boolean;
236
228
  validateRedisVersion(major: number, feature?: number, minor?: number): boolean;
@@ -340,8 +332,7 @@ declare class Lock {
340
332
  protected status: ELockStatus;
341
333
  protected lockingTimer: NodeJS.Timeout | null;
342
334
  protected autoExtendTimer: NodeJS.Timeout | null;
343
- protected throwExceptions: boolean;
344
- constructor(redisClient: RedisClient, lockKey: string, ttl: number, retryOnFail?: boolean, autoExtend?: boolean, throwExceptions?: boolean);
335
+ constructor(redisClient: RedisClient, lockKey: string, ttl: number, retryOnFail?: boolean, autoExtend?: boolean);
345
336
  protected resetTimers(): void;
346
337
  protected setUnlocked(): void;
347
338
  protected setLocked(): void;
@@ -358,10 +349,8 @@ declare class Lock {
358
349
  }
359
350
 
360
351
  declare class PowerSwitch {
361
- protected throwExceptionOnError: boolean;
362
352
  protected isPowered: boolean;
363
353
  protected pendingState: boolean | null;
364
- constructor(throwExceptionOnError?: boolean);
365
354
  protected switch(s: boolean): boolean;
366
355
  isUp(): boolean;
367
356
  isDown(): boolean;
@@ -370,11 +359,23 @@ declare class PowerSwitch {
370
359
  isRunning(): boolean;
371
360
  goingUp(): boolean;
372
361
  goingDown(): boolean;
373
- commit(): void;
374
- rollback(): void;
362
+ commit(): boolean;
363
+ rollback(): boolean;
364
+ }
365
+
366
+ type TEventEmitterEvent = Record<string | symbol, (...args: any) => any>;
367
+ declare interface EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
368
+ on<E extends keyof Events>(event: E, listener: Events[E]): this;
369
+ once<E extends keyof Events>(event: E, listener: Events[E]): this;
370
+ emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
371
+ removeAllListeners<E extends keyof Events>(event?: E): this;
372
+ }
373
+ declare class EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
375
374
  }
376
375
 
377
- declare class Ticker extends EventEmitter {
376
+ declare function getEventBusInstance<T extends TEvent>(): EventEmitter<TEvent>;
377
+
378
+ declare class Ticker extends EventEmitter<TEvent> {
378
379
  protected powerManager: PowerSwitch;
379
380
  protected onTickFn: TFunction;
380
381
  protected onNextTickFn: TFunction | null;
@@ -402,7 +403,7 @@ declare abstract class Worker {
402
403
  private getTicker;
403
404
  private getPowerManager;
404
405
  private onTick;
405
- run: () => void;
406
+ run: (cb: ICallback<void>) => void;
406
407
  quit: (cb: ICallback<void>) => void;
407
408
  abstract work(cb: ICallback<void>): void;
408
409
  }
@@ -414,7 +415,7 @@ declare class WorkerPool {
414
415
  clear: (cb: ICallback<void>) => void;
415
416
  }
416
417
 
417
- declare class WorkerRunner extends EventEmitter {
418
+ declare class WorkerRunner extends EventEmitter<TEvent> {
418
419
  private readonly powerManager;
419
420
  private readonly ticker;
420
421
  private readonly lock;
@@ -427,19 +428,10 @@ declare class WorkerRunner extends EventEmitter {
427
428
  private stopTicker;
428
429
  private releaseLock;
429
430
  addWorker(instance: Worker): void;
430
- run: () => void;
431
+ run: (cb: ICallback<void>) => void;
431
432
  quit: (cb: ICallback<void>) => void;
432
433
  }
433
434
 
434
- declare const events: {
435
- GOING_UP: string;
436
- UP: string;
437
- GOING_DOWN: string;
438
- DOWN: string;
439
- ERROR: string;
440
- TICK: string;
441
- };
442
-
443
435
  declare function destroy(): void;
444
436
  declare function setLogger<T extends ILogger>(logger: T): void;
445
437
  declare function getLogger(cfg: ILoggerConfig, ns?: string): ILogger;
@@ -461,4 +453,4 @@ declare const redis: {
461
453
  createInstance: typeof createInstance;
462
454
  };
463
455
 
464
- export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisConfigNodeRedisV4, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, PowerSwitchError, RedisClient, RedisClientError, RedisSMQError, type TFunction, type TRedisClientNodeRedisV4, type TRedisTransactionNodeRedisV4, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, events, logger, redis };
456
+ export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, EventEmitter, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, RedisClient, RedisClientError, RedisSMQError, type TEvent, type TEventEmitterEvent, type TFunction, type TRedisClientNodeRedis, type TRedisTransactionNodeRedis, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, getEventBusInstance, logger, redis };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { RedisClientMultiCommandType } from '@redis/client/dist/lib/client/multi-command';
2
2
  import { RedisClientOptions, RedisModules, RedisFunctions, RedisScripts, RedisClientType } from '@redis/client';
3
- import { EventEmitter } from 'events';
3
+ import { EventEmitter as EventEmitter$1 } from 'events';
4
4
  import * as Logger from 'bunyan';
5
5
  import { RedisOptions } from 'ioredis';
6
- import { ClientOpts } from 'redis';
7
6
 
8
7
  interface ICallback<T> {
9
8
  (err?: Error | null, reply?: T): void;
@@ -17,22 +16,17 @@ interface IRedisConfigIORedis {
17
16
  options?: RedisOptions;
18
17
  }
19
18
  declare enum ERedisConfigClient {
20
- REDIS = "redis",
21
19
  IOREDIS = "ioredis",
22
- REDIS_V4 = "redis_v4"
20
+ REDIS = "redis"
23
21
  }
24
22
  interface IRedisConfigNodeRedis {
25
23
  client: ERedisConfigClient.REDIS;
26
- options?: ClientOpts;
27
- }
28
- interface IRedisConfigNodeRedisV4 {
29
- client: ERedisConfigClient.REDIS_V4;
30
24
  options?: RedisClientOptions;
31
25
  }
32
- type IRedisConfig = IRedisConfigIORedis | IRedisConfigNodeRedis | IRedisConfigNodeRedisV4;
26
+ type IRedisConfig = IRedisConfigIORedis | IRedisConfigNodeRedis;
33
27
 
34
- type TRedisTransactionNodeRedisV4 = RedisClientMultiCommandType<RedisModules, RedisFunctions, RedisScripts>;
35
- type TRedisClientNodeRedisV4 = RedisClientType<RedisModules, RedisFunctions, RedisScripts>;
28
+ type TRedisTransactionNodeRedis = RedisClientMultiCommandType<RedisModules, RedisFunctions, RedisScripts>;
29
+ type TRedisClientNodeRedis = RedisClientType<RedisModules, RedisFunctions, RedisScripts>;
36
30
  interface IRedisClient {
37
31
  validateRedisVersion(major: number, feature?: number, minor?: number): boolean;
38
32
  validateRedisServerSupport(cb: ICallback<void>): void;
@@ -146,15 +140,6 @@ declare module 'ioredis' {
146
140
  lmove(source: string, destination: string, from: 'LEFT' | 'RIGHT', to: 'LEFT' | 'RIGHT', cb: ICallback<string>): void;
147
141
  }
148
142
  }
149
- declare module 'redis' {
150
- interface Commands<R> {
151
- info(cb?: Callback<string>): R;
152
- info(section?: string | string[], cb?: Callback<string>): R;
153
- INFO(cb?: Callback<string>): R;
154
- INFO(section?: string | string[], cb?: Callback<string>): R;
155
- lmove(source: string, destination: string, from: 'LEFT' | 'RIGHT', to: 'LEFT' | 'RIGHT', cb: ICallback<string>): void;
156
- }
157
- }
158
143
 
159
144
  interface ILoggerConfig {
160
145
  enabled: boolean;
@@ -168,6 +153,16 @@ interface ILogger {
168
153
  debug(message: unknown, ...params: unknown[]): void;
169
154
  }
170
155
 
156
+ type TEvent = {
157
+ error: (err: Error) => void;
158
+ next: () => void;
159
+ up: () => void;
160
+ down: () => void;
161
+ goingUp: () => void;
162
+ goingDown: () => void;
163
+ tick: () => void;
164
+ };
165
+
171
166
  declare abstract class RedisSMQError extends Error {
172
167
  constructor(message?: string);
173
168
  get name(): string;
@@ -227,10 +222,7 @@ declare class WatchedKeysChangedError extends RedisClientError {
227
222
  declare class WorkerError extends PanicError {
228
223
  }
229
224
 
230
- declare class PowerSwitchError extends RedisSMQError {
231
- }
232
-
233
- declare abstract class RedisClient extends EventEmitter implements IRedisClient {
225
+ declare abstract class RedisClient extends EventEmitter$1 implements IRedisClient {
234
226
  protected static redisServerVersion: number[] | null;
235
227
  protected connectionClosed: boolean;
236
228
  validateRedisVersion(major: number, feature?: number, minor?: number): boolean;
@@ -340,8 +332,7 @@ declare class Lock {
340
332
  protected status: ELockStatus;
341
333
  protected lockingTimer: NodeJS.Timeout | null;
342
334
  protected autoExtendTimer: NodeJS.Timeout | null;
343
- protected throwExceptions: boolean;
344
- constructor(redisClient: RedisClient, lockKey: string, ttl: number, retryOnFail?: boolean, autoExtend?: boolean, throwExceptions?: boolean);
335
+ constructor(redisClient: RedisClient, lockKey: string, ttl: number, retryOnFail?: boolean, autoExtend?: boolean);
345
336
  protected resetTimers(): void;
346
337
  protected setUnlocked(): void;
347
338
  protected setLocked(): void;
@@ -358,10 +349,8 @@ declare class Lock {
358
349
  }
359
350
 
360
351
  declare class PowerSwitch {
361
- protected throwExceptionOnError: boolean;
362
352
  protected isPowered: boolean;
363
353
  protected pendingState: boolean | null;
364
- constructor(throwExceptionOnError?: boolean);
365
354
  protected switch(s: boolean): boolean;
366
355
  isUp(): boolean;
367
356
  isDown(): boolean;
@@ -370,11 +359,23 @@ declare class PowerSwitch {
370
359
  isRunning(): boolean;
371
360
  goingUp(): boolean;
372
361
  goingDown(): boolean;
373
- commit(): void;
374
- rollback(): void;
362
+ commit(): boolean;
363
+ rollback(): boolean;
364
+ }
365
+
366
+ type TEventEmitterEvent = Record<string | symbol, (...args: any) => any>;
367
+ declare interface EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
368
+ on<E extends keyof Events>(event: E, listener: Events[E]): this;
369
+ once<E extends keyof Events>(event: E, listener: Events[E]): this;
370
+ emit<E extends keyof Events>(event: E, ...args: Parameters<Events[E]>): boolean;
371
+ removeAllListeners<E extends keyof Events>(event?: E): this;
372
+ }
373
+ declare class EventEmitter<Events extends TEventEmitterEvent> extends EventEmitter$1 {
375
374
  }
376
375
 
377
- declare class Ticker extends EventEmitter {
376
+ declare function getEventBusInstance<T extends TEvent>(): EventEmitter<TEvent>;
377
+
378
+ declare class Ticker extends EventEmitter<TEvent> {
378
379
  protected powerManager: PowerSwitch;
379
380
  protected onTickFn: TFunction;
380
381
  protected onNextTickFn: TFunction | null;
@@ -402,7 +403,7 @@ declare abstract class Worker {
402
403
  private getTicker;
403
404
  private getPowerManager;
404
405
  private onTick;
405
- run: () => void;
406
+ run: (cb: ICallback<void>) => void;
406
407
  quit: (cb: ICallback<void>) => void;
407
408
  abstract work(cb: ICallback<void>): void;
408
409
  }
@@ -414,7 +415,7 @@ declare class WorkerPool {
414
415
  clear: (cb: ICallback<void>) => void;
415
416
  }
416
417
 
417
- declare class WorkerRunner extends EventEmitter {
418
+ declare class WorkerRunner extends EventEmitter<TEvent> {
418
419
  private readonly powerManager;
419
420
  private readonly ticker;
420
421
  private readonly lock;
@@ -427,19 +428,10 @@ declare class WorkerRunner extends EventEmitter {
427
428
  private stopTicker;
428
429
  private releaseLock;
429
430
  addWorker(instance: Worker): void;
430
- run: () => void;
431
+ run: (cb: ICallback<void>) => void;
431
432
  quit: (cb: ICallback<void>) => void;
432
433
  }
433
434
 
434
- declare const events: {
435
- GOING_UP: string;
436
- UP: string;
437
- GOING_DOWN: string;
438
- DOWN: string;
439
- ERROR: string;
440
- TICK: string;
441
- };
442
-
443
435
  declare function destroy(): void;
444
436
  declare function setLogger<T extends ILogger>(logger: T): void;
445
437
  declare function getLogger(cfg: ILoggerConfig, ns?: string): ILogger;
@@ -461,4 +453,4 @@ declare const redis: {
461
453
  createInstance: typeof createInstance;
462
454
  };
463
455
 
464
- export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisConfigNodeRedisV4, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, PowerSwitchError, RedisClient, RedisClientError, RedisSMQError, type TFunction, type TRedisClientNodeRedisV4, type TRedisTransactionNodeRedisV4, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, events, logger, redis };
456
+ export { CallbackEmptyReplyError, CallbackInvalidReplyError, ERedisConfigClient, EventEmitter, type ICallback, type ILogger, type ILoggerConfig, type IRedisClient, type IRedisConfig, type IRedisConfigIORedis, type IRedisConfigNodeRedis, type IRedisTransaction, Lock, LockAbortError, LockAcquireError, LockError, LockExtendError, LockMethodNotAllowedError, LockNotAcquiredError, LockNotReleasedError, LoggerError, PanicError, PowerSwitch, RedisClient, RedisClientError, RedisSMQError, type TEvent, type TEventEmitterEvent, type TFunction, type TRedisClientNodeRedis, type TRedisTransactionNodeRedis, type TUnaryFunction, Ticker, TickerError, WatchedKeysChangedError, Worker, WorkerError, WorkerPool, WorkerRunner, async, getEventBusInstance, logger, redis };
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- var at=Object.defineProperty,ct=Object.defineProperties;var dt=Object.getOwnPropertyDescriptors;var Z=Object.getOwnPropertySymbols;var gt=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var j=(l,r,t)=>r in l?at(l,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[r]=t,U=(l,r)=>{for(var t in r||(r={}))gt.call(r,t)&&j(l,t,r[t]);if(Z)for(var t of Z(r))ut.call(r,t)&&j(l,t,r[t]);return l},Y=(l,r)=>ct(l,dt(r));var tt=(i=>(i.REDIS="redis",i.IOREDIS="ioredis",i.REDIS_V4="redis_v4",i))(tt||{});var g=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var b=class extends g{constructor(){super("Expected a non-empty reply")}};var Q=class extends g{constructor(){super("Invalid reply type")}};var y=class extends g{};var H=class extends g{};var L=class extends g{};var m=class extends g{};var x=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var E=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var M=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var A=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var z=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var F=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends g{};var I=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var S=class extends y{};var T=class extends g{};import{v4 as kt}from"uuid";import st from"fs";import{resolve as ot}from"path";import{EventEmitter as bt}from"events";var it=(l,r,t)=>{if(l.length){let i=0,e=()=>{r(l[i],i,n=>{i+=1,n||i>=l.length?t(n):setTimeout(()=>e(),0)})};e()}else t()},et=(l,r,t)=>{let i=Object.keys(l);if(i.length){let e=0,n=()=>{let s=i[e];r(l[s],s,o=>{e+=1,o||e>=i.length?t(o):setTimeout(()=>n(),0)})};n()}else t()},ht=(l,r,t)=>{Array.isArray(l)?it(l,r,t):et(l,r,t)},mt=(l,r)=>{if(l.length){let t=0,i=(e,...n)=>{t+=1,e?r(e):t<l.length?setTimeout(()=>{n.length?l[t](...n,i):l[t](i)},0):n.length?r(null,n[0]):r()};l[t](i)}else r()},v={each:ht,eachIn:et,eachOf:it,waterfall:mt};import rt from"fs";import{resolve as nt}from"path";var O=class O{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",rt.readFileSync(nt(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",rt.readFileSync(nt(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let i=[];this.scripts.forEach(e=>i.push(n=>{e.id?n():r.loadScript(e.content,(s,o)=>{s?n(s):o?(e.id=o,n()):n(new b)})})),v.waterfall(i,e=>{e?t(e):(this.isLoaded=!0,t())})}}getScriptId(r){var i;let{id:t}=(i=this.scripts.get(r))!=null?i:{};if(!t)throw new u(`ID of script [${r}] is missing`);return t}static getInstance(){return O.instance||(O.instance=new O),O.instance}};O.instance=null;var P=O;var pt=[2,8,0],C=class C extends bt{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,i=0,e=0){if(!C.redisServerVersion)throw new u("UNKNOWN_REDIS_SERVER_VERSION");return C.redisServerVersion[0]>t||C.redisServerVersion[0]===t&&C.redisServerVersion[1]>=i&&C.redisServerVersion[2]>=e}validateRedisServerSupport(t){let i=e=>{let[n,s,o]=pt;this.validateRedisVersion(n,s,o)?e():e(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};C.redisServerVersion?i(t):this.updateServerVersion(e=>{e?t(e):i(t)})}sscanAll(t,i,e){let n=new Set,s=o=>{this.sscan(t,o,i,(a,c)=>{a?e(a):c?(c.items.forEach(d=>n.add(d)),c.cursor==="0"?e(null,[...n]):s(c.cursor)):e(new b)})};s("0")}hscanAll(t,i,e){let n={},s=o=>{this.hscan(t,o,i,(a,c)=>{a?e(a):c?(Object.assign(n,c.result),c.cursor==="0"?e(null,n):s(c.cursor)):e(new b)})};s("0")}zpoprpush(t,i,e){this.runScript("ZPOPRPUSH",[t,i],[],(n,s)=>{n?e(n):e(null,typeof s=="string"?s:null)})}lpoprpush(t,i,e){this.validateRedisVersion(6,2)?this.lmove(t,i,"LEFT","RIGHT",e):this.runScript("LPOPRPUSH",[t,i],[],(n,s)=>{n?e(n):e(null,typeof s=="string"?s:null)})}updateServerVersion(t){C.redisServerVersion?t():this.getInfo((i,e)=>{i?t(i):e?(C.redisServerVersion=e.split(`\r
2
- `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new b)})}loadScripts(t){P.getInstance().loadScripts(this,t)}runScript(t,i,e,n){let s=P.getInstance().getScriptId(t);this.evalsha(s,[i.length,...i,...e],(o,a)=>{o?n(o):n(null,a)})}static addScript(t,i){if(!P.getInstance().addScript(t,i))throw new u(`A script with name [${t}] already exists`)}};C.redisServerVersion=null;var k=C;k.addScript("RELEASE_LOCK",st.readFileSync(ot(__dirname,"./lua/release-lock.lua")).toString());k.addScript("EXTEND_LOCK",st.readFileSync(ot(__dirname,"./lua/extend-lock.lua")).toString());var D=class{constructor(r,t,i,e=!1,n=!1,s=!0){this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.throwExceptions=!0;this.lockKey=t,this.ttl=i,this.retryOnFail=e,this.lockId=kt(),this.redisClient=r,this.autoExtend=n,this.throwExceptions=s}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(r){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(t,i)=>{t?r(t):this.status===4?i?(this.setExtended(),r()):(this.setUnlocked(),r(new M)):r(new x)})):r(new z)}runAutoExtendTimer(){let r=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(t=>{if(!t)this.runAutoExtendTimer();else if(this.throwExceptions&&!(t instanceof x))throw t}),r)}acquireLock(r){if(!this.isReleased())r(new F);else{this.status=1;let t=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(i,e)=>{i?r(i):this.status===1?e?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),r()):this.retryOnFail?this.lockingTimer=setTimeout(t,1e3):(this.setUnlocked(),r(new E)):r(new x)}):r(new x)};t()}}extendLock(r){this.autoExtend?r(new A):this.extend(r)}releaseLock(r){this.status===0?r():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],i=>{i?r(i):(this.setUnlocked(),r())})):r(new z)}acquireOrExtend(r){if(this.autoExtend)r(new A);else{let t=()=>{this.acquireLock(i=>{i?r(i):r(null,2)})};this.isLocked()?this.extend(i=>{i?i instanceof M?t():r(i):r(null,5)}):t()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var w=class{constructor(r=!0){this.isPowered=!1;this.pendingState=null;this.throwExceptionOnError=r}switch(r){if(this.pendingState!==null){if(this.throwExceptionOnError)throw new T("Can not switch state while another state transition is in progress.");return!1}if(r===this.isPowered){if(this.throwExceptionOnError)throw new T("Can not switch to the same current state.");return!1}return this.pendingState=r,!0}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){if(this.pendingState===null)throw new T("Expected a pending state");this.isPowered=this.pendingState,this.pendingState=null}rollback(){if(this.pendingState===null)throw new T("Expected a pending state");this.pendingState=null}};import{EventEmitter as vt}from"events";var p={GOING_UP:"going_up",UP:"up",GOING_DOWN:"going_down",DOWN:"down",ERROR:"error",TICK:"tick"};var N=class extends vt{constructor(t=()=>{},i=1e3){super();this.powerManager=new w;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=i,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit(p.DOWN)}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let i=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,i()}else this.emit(p.ERROR,new y("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit(p.DOWN)):this.aborted&&this.powerManager.isDown()?this.emit(p.DOWN):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){if(this.isTicking())throw new L("A timer is already running");this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){if(this.isTicking())throw new L("A timer is already running");this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time))}};var $=class{constructor(r,t=1e3){this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new S("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(r=>{if(r)throw r;this.getTicker().nextTick()})};this.run=()=>{if(this.managed)throw new S("You can not run a managed worker");let r=this.getPowerManager();r.goingUp(),this.getTicker().nextTick(),r.commit()};this.quit=r=>{if(this.managed)r();else{let t=this.getPowerManager();t.goingDown();let i=this.getTicker();i.on(p.DOWN,()=>{t.commit(),r()}),i.quit()}};this.managed=r,r||(this.ticker=new N(this.onTick,t),this.powerManager=new w)}getPowerManager(){if(!this.powerManager)throw new S("Expected an instance of PowerSwitch");return this.powerManager}};import{EventEmitter as Ct}from"events";var J=class extends Ct{constructor(t,i,e,n){super();this.onTick=()=>{v.waterfall([t=>{this.lock.acquireOrExtend((i,e)=>{e===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(i)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof E?this.ticker.nextTick():this.emit(p.ERROR,t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once(p.DOWN,t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=()=>{this.emit(p.UP),this.ticker.nextTick()};this.quit=t=>{v.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit(p.DOWN),t()})};this.powerManager=new w,this.redisClient=t,this.logger=n,this.lock=new D(t,i,6e4),this.ticker=new N(this.onTick),this.workerPool=e}addWorker(t){this.workerPool.add(t)}};var B=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(i=>e=>i.work(e));v.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{v.each(this.pool,(t,i,e)=>{t.quit(e)},()=>{this.pool=[],r()})}}};import{createLogger as ft}from"bunyan";var V=()=>{},It={debug:V,warn:V,info:V,error:V},f=null;function wt(){f=null}function xt(l){if(f)throw new H("Logger has been already initialized.");f=l}function Tt(l,r){var t;if(!l.enabled)return It;if(f||(f=ft(Y(U({},(t=l.options)!=null?t:{}),{name:"redis-smq"}))),r){let i=(e,n)=>(s,...o)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[e](a,...o)};return{info:i("info",f),warn:i("warn",f),debug:i("debug",f),error:i("error",f)}}return f}var Rt={getLogger:Tt,setLogger:xt,destroy:wt};import{createClient as yt}from"redis";var G=class{constructor(r){this.multi=r.multi()}lrem(r,t,i){return this.multi.lrem(r,t,i),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,i){return this.multi.ltrim(r,t,i),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,i){return this.multi.zadd(r,t,i),this}zrem(r,t){return this.multi.zrem(r,t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,t),this}hset(r,t,i){return this.multi.hset(r,t,String(i)),this}hdel(r,t){return this.multi.hdel(r,t),this}hincrby(r,t,i){return this.multi.hincrby(r,t,i),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec((t,i)=>{t?r(t):i?r(null,i):r(new I)})}};var Et=function(l){return l?this.flush_and_error({message:"Connection forcefully ended and command aborted.",code:"NR_CLOSED"}):arguments.length===0&&this.warn(`Using .end() without the flush parameter is deprecated and throws from v.3.0.0 on.
3
- Please check the doku (https://github.com/NodeRedis/node_redis) and explictly use flush.`),this.retry_timer&&(clearTimeout(this.retry_timer),this.retry_timer=null),this.stream.removeAllListeners(),this.stream.once("close",()=>{this.emit("end"),this.emitted_end=!0}),this.stream.on("error",()=>{}),this.connected=!1,this.ready=!1,this.closing=!0,this.stream.destroySoon()},X=class extends k{constructor(t={}){super();this.client=yt(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.end=Et}set(t,i,e,n){e.exists&&e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,e.exists,n):e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,n):e.exists?this.client.set(t,i,e.exists,n):this.client.set(t,i,n)}zadd(t,i,e,n){this.client.zadd(t,i,e,n)}multi(){return new G(this.client)}watch(t,i){this.client.watch(t,i)}unwatch(t){this.client.unwatch(t)}sismember(t,i,e){this.client.sismember(t,i,e)}sscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.sscan(...s,(o,[a,c])=>{o?n(o):n(null,{cursor:a,items:c})})}zscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.zscan(...s,(o,a)=>{if(o)n(o);else if(!a)n(new b);else{let c=new Set,[d,h]=a;for(;h.length;){let R=String(h.shift()),lt=String(h.shift());c.add(R)}n(null,{cursor:d,items:[...c]})}})}zcard(t,i){this.client.zcard(t,i)}zrange(t,i,e,n){this.client.zrange(t,i,e,n)}zrevrange(t,i,e,n){this.client.zrevrange(t,i,e,n)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,i,e,n,s,o){this.client.zrangebyscore(t,i,e,"LIMIT",n,s,o)}zrem(t,i,e){this.client.zrem(t,i,e)}smembers(t,i){this.client.smembers(t,i)}sadd(t,i,e){this.client.sadd(t,i,e)}srem(t,i,e){this.client.srem(t,i,e)}hgetall(t,i){this.client.hgetall(t,(e,n)=>{e?i(e):i(null,n!=null?n:{})})}hscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.hscan(...s,(o,[a,c])=>{if(o)n(o);else{let d={};for(;c.length;){let h=String(c.shift());d[h]=String(c.shift())}n(null,{cursor:a,result:d})}})}hget(t,i,e){this.client.hget(t,i,e)}hset(t,i,e,n){this.client.hset(t,i,String(e),n)}hdel(t,i,e){this.client.hdel(t,...typeof i=="string"?[i]:i,e)}lrange(t,i,e,n){this.client.lrange(t,i,e,n)}hkeys(t,i){this.client.hkeys(t,i)}hlen(t,i){this.client.hlen(t,i)}brpoplpush(t,i,e,n){this.client.brpoplpush(t,i,e,n)}rpoplpush(t,i,e){this.client.rpoplpush(t,i,e)}zrangebyscorewithscores(t,i,e,n){this.client.zrangebyscore(t,i,e,"WITHSCORES",(s,o)=>{if(s)n(s);else{let a=o!=null?o:[],c={};for(let d=a.splice(0,2);d.length>0;d=a.splice(0,2)){let[h,R]=d;c[R]=h}n(null,c)}})}rpop(t,i){this.client.rpop(t,i)}lrem(t,i,e,n){this.client.lrem(t,i,e,n)}publish(t,i,e){this.client.publish(t,i,e)}flushall(t){this.client.flushall(t)}loadScript(t,i){this.client.script("load",t,i)}evalsha(t,i,e){let n=[t],s=Array.isArray(i)?i:[i];this.client.evalsha(n.concat(s),(o,a)=>e(o,a))}get(t,i){this.client.get(t,i)}del(t,i){this.client.del(...typeof t=="string"?[t]:t,i)}llen(t,i){this.client.llen(t,i)}lmove(t,i,e,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,i,e,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,i,e,n){this.client.zremrangebyscore(t,i,e,n)}hmget(t,i,e){this.client.hmget(t,i,e)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end(!0))}end(t){this.connectionClosed||this.client.end(t)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,i){return this.client.on(t,i),this}};import{createClient as Ot}from"@redis/client";import{WatchError as St}from"@redis/client";var q=class{constructor(r){this.multi=r.multi()}lrem(r,t,i){return this.multi.lRem(r,t,i),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,i){return this.multi.lTrim(r,t,i),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,i){return this.multi.zAdd(r,{score:t,value:i}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,i){return this.multi.hSet(r,t,i),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,i){return this.multi.hIncrBy(r,t,i),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof St?r(new I):r(t)})}};var W=class extends k{constructor(t={}){super();this.client=Ot(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,i,e,n){this.client.set(t,i,U(U({},e.expire?{[e.expire.mode]:e.expire.value}:{}),e.exists?{[e.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,i,e,n){this.client.zAdd(t,{score:i,value:e}).then(s=>n(null,s)).catch(n)}multi(){return new q(this.client)}watch(t,i){this.client.watch(t).then(e=>i(null,e)).catch(i)}unwatch(t){this.client.unwatch().then(i=>t(null,i)).catch(t)}sismember(t,i,e){this.client.sIsMember(t,i).then(n=>e(null,Number(n))).catch(e)}zcard(t,i){this.client.zCard(t).then(e=>i(null,e)).catch(i)}zrange(t,i,e,n){this.client.zRange(t,i,e).then(s=>n(null,(Array.isArray(s)?s:[]).map(o=>String(o)))).catch(n)}zrevrange(t,i,e,n){this.client.sendCommand(["ZREVRANGE",t,String(i),String(e)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(o=>String(o)))).catch(n)}zrem(t,i,e){this.client.zRem(t,i).then(n=>e(null,n)).catch(e)}psubscribe(t){this.client.pSubscribe(t,(i,e)=>{this.client.emit("pmessage",t,e,i)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(i,e)=>{this.client.emit("message",e,i)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,i,e,n,s,o){this.client.zRangeByScore(t,i,e,{LIMIT:{offset:n,count:s}}).then(a=>o(null,a)).catch(o)}smembers(t,i){this.client.sMembers(t).then(e=>i(null,e)).catch(i)}sscan(t,i,e,n){let s=[t,Number(i),e];this.client.sScan(...s).then(({cursor:o,members:a})=>{n(null,{cursor:String(o),items:a})}).catch(n)}zscan(t,i,e,n){let s=[t,Number(i),e];this.client.zScan(...s).then(({cursor:o,members:a})=>{let c=new Set;for(let d of a)c.add(d.value);n(null,{cursor:String(o),items:[...c]})}).catch(n)}sadd(t,i,e){this.client.sAdd(t,i).then(n=>e(null,n)).catch(e)}srem(t,i,e){this.client.sRem(t,i).then(n=>e(null,n)).catch(e)}hgetall(t,i){this.client.hGetAll(t).then(e=>i(null,e)).catch(i)}hscan(t,i,e,n){let s=[t,Number(i),e];this.client.hScan(...s).then(({cursor:o,tuples:a})=>{let c={};for(;a.length;){let d=a.shift();d&&(c[d.field]=d.value)}n(null,{cursor:String(o),result:c})}).catch(n)}hget(t,i,e){this.client.hGet(t,i).then(n=>e(null,n!=null?n:null)).catch(e)}hset(t,i,e,n){this.client.hSet(t,i,e).then(s=>n(null,s)).catch(n)}hdel(t,i,e){this.client.hDel(t,i).then(n=>e(null,Number(n))).catch(e)}lrange(t,i,e,n){this.client.lRange(t,i,e).then(s=>n(null,s)).catch(n)}hkeys(t,i){this.client.hKeys(t).then(e=>i(null,e)).catch(i)}hlen(t,i){this.client.hLen(t).then(e=>i(null,e)).catch(i)}brpoplpush(t,i,e,n){this.client.brPopLPush(t,i,e).then(s=>n(null,s)).catch(n)}rpoplpush(t,i,e){this.client.rPopLPush(t,i).then(n=>e(null,n)).catch(e)}zrangebyscorewithscores(t,i,e,n){this.client.zRangeByScoreWithScores(t,i,e).then(s=>{let o={};for(let{score:a,value:c}of s)o[a]=c;n(null,o)}).catch(n)}rpop(t,i){this.client.rPop(t).then(e=>i(null,e)).catch(i)}lrem(t,i,e,n){this.client.lRem(t,i,e).then(s=>n(null,s)).catch(n)}publish(t,i,e){this.client.publish(t,i).then(n=>e(null,n)).catch(e)}flushall(t){this.client.flushAll().then(i=>t(null,i)).catch(t)}loadScript(t,i){this.client.sendCommand(["SCRIPT","LOAD",t]).then(e=>i(null,typeof e=="string"?e:String(e))).catch(i)}evalsha(t,i,e){let n=[t],s=Array.isArray(i)?i:[i];this.client.sendCommand(["evalsha",...n.concat(s).map(o=>String(o))]).then(o=>{Array.isArray(o)?e(null,o.map(a=>a instanceof Buffer?a.toString():a)):o instanceof Buffer?e(null,o.toString()):e(null,o)}).catch(e)}get(t,i){this.client.sendCommand(["get",t]).then(e=>i(null,typeof e=="string"?e:null)).catch(i)}del(t,i){this.client.del(t).then(e=>i(null,e)).catch(i)}llen(t,i){this.client.sendCommand(["llen",t]).then(e=>i(null,Number(e))).catch(i)}lmove(t,i,e,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,i,e,n).then(o=>s(null,o)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,i,e,n){this.client.sendCommand(["zremrangebyscore",t,`${i}`,`${e}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,i,e){this.client.hmGet(t,i).then(n=>e(null,n)).catch(e)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(i=>t(null,i)).catch(t)}on(t,i){return this.client.on(t,i),this}};import Nt from"ioredis";var _=class{constructor(r){this.multi=r.multi()}lrem(r,t,i){return this.multi.lrem(r,t,i),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,i){return this.multi.ltrim(r,t,i),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,i){return this.multi.zadd(r,t,i),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,i){return this.multi.hset(r,t,i),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,i){return this.multi.hincrby(r,t,i),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,i)=>{if(t)r(t);else if(!i)r(new I);else{let e=[],n=null;for(let s of i){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[o,a]=s;if(o instanceof Error){n=o;break}e.push(a)}n?r(n):r(null,e)}})}};var K=class extends k{constructor(t={}){super();this.client=new Nt(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,i,e,n){e.exists&&e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,e.exists,n):e.expire?this.client.set(t,i,e.expire.mode,e.expire.value,n):e.exists?this.client.set(t,i,e.exists,n):this.client.set(t,i,n)}zadd(t,i,e,n){this.client.zadd(t,i,e,n)}multi(){return new _(this.client)}watch(t,i){this.client.watch(t,i)}unwatch(t){this.client.unwatch(t)}sismember(t,i,e){this.client.sismember(t,i,e)}sscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.sscan(...s,(o,[a,c])=>{o?n(o):n(null,{cursor:a,items:c})})}zcard(t,i){this.client.zcard(t,i)}zrange(t,i,e,n){this.client.zrange(t,i,e,n)}zscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.zscan(...s,(o,a)=>{if(o)n(o);else if(!a)n(new b);else{let c=new Set,[d,h]=a;for(;h.length;){let R=String(h.shift()),lt=String(h.shift());c.add(R)}n(null,{cursor:d,items:[...c]})}})}zrevrange(t,i,e,n){this.client.zrevrange(t,i,e,n)}zrem(t,i,e){this.client.zrem(t,i,e)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,i,e,n,s,o){this.client.zrangebyscore(t,i,e,"LIMIT",n,s,o)}smembers(t,i){this.client.smembers(t,i)}sadd(t,i,e){this.client.sadd(t,i,e)}srem(t,i,e){this.client.srem(t,i,e)}hgetall(t,i){this.client.hgetall(t,i)}hscan(t,i,e,n){let s=[t,i];e.MATCH&&s.push("MATCH",e.MATCH),e.COUNT&&s.push("COUNT",String(e.COUNT)),this.client.hscan(...s,(o,[a,c])=>{if(o)n(o);else{let d={};for(;c.length;){let h=String(c.shift());d[h]=String(c.shift())}n(null,{cursor:a,result:d})}})}hget(t,i,e){this.client.hget(t,i,e)}hset(t,i,e,n){this.client.hset(t,i,e,n)}hdel(t,i,e){this.client.hdel(t,i,e)}lrange(t,i,e,n){this.client.lrange(t,i,e,n)}hkeys(t,i){this.client.hkeys(t,i)}hlen(t,i){this.client.hlen(t,i)}brpoplpush(t,i,e,n){this.client.brpoplpush(t,i,e,n)}rpoplpush(t,i,e){this.client.rpoplpush(t,i,e)}zrangebyscorewithscores(t,i,e,n){this.client.zrangebyscore(t,i,e,"WITHSCORES",(s,o)=>{if(s)n(s);else{let a=o!=null?o:[],c={};for(let d=a.splice(0,2);d.length>0;d=a.splice(0,2)){let[h,R]=d;c[R]=h}n(null,c)}})}rpop(t,i){this.client.rpop(t,i)}lrem(t,i,e,n){this.client.lrem(t,i,e,n)}publish(t,i,e){this.client.publish(t,i,e)}flushall(t){this.client.flushall(t)}loadScript(t,i){this.client.script("load",t,i)}evalsha(t,i,e){let n=[t],s=Array.isArray(i)?i:[i];this.client.evalsha(n.concat(s),e)}get(t,i){this.client.get(t,i)}del(t,i){this.client.del(t,i)}llen(t,i){this.client.llen(t,i)}lmove(t,i,e,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,i,e,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,i,e,n){this.client.zremrangebyscore(t,i,e,n)}hmget(t,i,e){this.client.hmget(t,i,e)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,i){return this.client.on(t,i),this}};function Lt(l){return l.client==="redis"?new X(l.options):l.client==="redis_v4"?new W(l.options):new K(l.options)}function Mt(l,r){let t=Lt(l);t.once("ready",()=>{v.waterfall([i=>t.validateRedisServerSupport(i),i=>t.loadScripts(i)],i=>{if(i)throw i;r(null,t)})})}var At={createInstance:Mt};export{b as CallbackEmptyReplyError,Q as CallbackInvalidReplyError,tt as ERedisConfigClient,D as Lock,x as LockAbortError,E as LockAcquireError,m as LockError,M as LockExtendError,A as LockMethodNotAllowedError,z as LockNotAcquiredError,F as LockNotReleasedError,H as LoggerError,y as PanicError,w as PowerSwitch,T as PowerSwitchError,k as RedisClient,u as RedisClientError,g as RedisSMQError,N as Ticker,L as TickerError,I as WatchedKeysChangedError,$ as Worker,S as WorkerError,B as WorkerPool,J as WorkerRunner,v as async,p as events,Rt as logger,At as redis};
1
+ var ot=Object.defineProperty,lt=Object.defineProperties;var at=Object.getOwnPropertyDescriptors;var J=Object.getOwnPropertySymbols;var ct=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var Z=(o,r,t)=>r in o?ot(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,z=(o,r)=>{for(var t in r||(r={}))ct.call(r,t)&&Z(o,t,r[t]);if(J)for(var t of J(r))dt.call(r,t)&&Z(o,t,r[t]);return o},j=(o,r)=>lt(o,at(r));var Y=(t=>(t.IOREDIS="ioredis",t.REDIS="redis",t))(Y||{});var d=class extends Error{constructor(r){super(r)}get name(){return this.constructor.name}};var h=class extends d{constructor(){super("Expected a non-empty reply")}};var K=class extends d{constructor(){super("Invalid reply type")}};var w=class extends d{};var U=class extends d{};var M=class extends d{};var m=class extends d{};var I=class extends m{constructor(r="releaseLock() may have been called. Abandoning."){super(r)}};var E=class extends m{constructor(r="Could not acquire a lock"){super(r)}};var A=class extends m{constructor(r="Acquired lock could not be extended"){super(r)}};var N=class extends m{constructor(r="This method can not be used when autoExtend is enabled"){super(r)}};var P=class extends m{constructor(r="Can not extend a lock which has not been yet acquired. Maybe a pending operation is in progress."){super(r)}};var H=class extends m{constructor(r="A lock has been already obtained but not yet released or maybe a pending operation is in progress."){super(r)}};var u=class extends d{};var y=class extends u{constructor(r="One (or more) of the watched keys has been changed"){super(r)}};var R=class extends w{};import{v4 as pt}from"uuid";import nt from"fs";import{resolve as st}from"path";import{EventEmitter as ht}from"events";var tt=(o,r,t)=>{if(o.length){let e=0,i=()=>{r(o[e],e,n=>{e+=1,n||e>=o.length?t(n):setTimeout(()=>i(),0)})};i()}else t()},et=(o,r,t)=>{let e=Object.keys(o);if(e.length){let i=0,n=()=>{let s=e[i];r(o[s],s,l=>{i+=1,l||i>=e.length?t(l):setTimeout(()=>n(),0)})};n()}else t()},ut=(o,r,t)=>{Array.isArray(o)?tt(o,r,t):et(o,r,t)},gt=(o,r)=>{if(o.length){let t=0,e=(i,...n)=>{t+=1,i?r(i):t<o.length?setTimeout(()=>{n.length?o[t](...n,e):o[t](e)},0):n.length?r(null,n[0]):r()};o[t](e)}else r()},b={each:ut,eachIn:et,eachOf:tt,waterfall:gt};import it from"fs";import{resolve as rt}from"path";var S=class S{constructor(){this.isLoaded=!1;this.scripts=new Map,this.addScript("ZPOPRPUSH",it.readFileSync(rt(__dirname,"./lua/zpoprpush.lua")).toString()),this.addScript("LPOPRPUSH",it.readFileSync(rt(__dirname,"./lua/lpoprpush.lua")).toString())}hasScript(r){return this.scripts.has(r)}addScript(r,t){return this.hasScript(r)?!1:(this.scripts.set(r,{content:t}),this.isLoaded=!1,!0)}loadScripts(r,t){if(this.isLoaded)t();else{let e=[];this.scripts.forEach(i=>e.push(n=>{i.id?n():r.loadScript(i.content,(s,l)=>{s?n(s):l?(i.id=l,n()):n(new h)})})),b.waterfall(e,i=>{i?t(i):(this.isLoaded=!0,t())})}}getScriptId(r){var e;let{id:t}=(e=this.scripts.get(r))!=null?e:{};return t||new u(`ID of script [${r}] is missing`)}static getInstance(){return S.instance||(S.instance=new S),S.instance}};S.instance=null;var O=S;import{EventEmitter as mt}from"events";var x=class extends mt{};var B=null;function k(){return B||(B=new x),B}var bt=[4,0,0],p=class p extends ht{constructor(){super(...arguments);this.connectionClosed=!0}validateRedisVersion(t,e=0,i=0){return p.redisServerVersion?p.redisServerVersion[0]>t||p.redisServerVersion[0]===t&&p.redisServerVersion[1]>=e&&p.redisServerVersion[2]>=i:(k().emit("error",new u("UNKNOWN_REDIS_SERVER_VERSION")),!1)}validateRedisServerSupport(t){let e=i=>{let[n,s,l]=bt;this.validateRedisVersion(n,s,l)?i():i(new u("UNSUPPORTED_REDIS_SERVER_VERSION"))};p.redisServerVersion?e(t):this.updateServerVersion(i=>{i?t(i):e(t)})}sscanAll(t,e,i){let n=new Set,s=l=>{this.sscan(t,l,e,(a,c)=>{a?i(a):c?(c.items.forEach(g=>n.add(g)),c.cursor==="0"?i(null,[...n]):s(c.cursor)):i(new h)})};s("0")}hscanAll(t,e,i){let n={},s=l=>{this.hscan(t,l,e,(a,c)=>{a?i(a):c?(Object.assign(n,c.result),c.cursor==="0"?i(null,n):s(c.cursor)):i(new h)})};s("0")}zpoprpush(t,e,i){this.runScript("ZPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}lpoprpush(t,e,i){this.validateRedisVersion(6,2)?this.lmove(t,e,"LEFT","RIGHT",i):this.runScript("LPOPRPUSH",[t,e],[],(n,s)=>{n?i(n):i(null,typeof s=="string"?s:null)})}updateServerVersion(t){p.redisServerVersion?t():this.getInfo((e,i)=>{e?t(e):i?(p.redisServerVersion=i.split(`\r
2
+ `)[1].split(":")[1].split(".").map(n=>Number(n)),t()):t(new h)})}loadScripts(t){O.getInstance().loadScripts(this,t)}runScript(t,e,i,n){let s=O.getInstance().getScriptId(t);s instanceof Error?n(s):this.evalsha(s,[e.length,...e,...i],(l,a)=>{l?n(l):n(null,a)})}static addScript(t,e){if(!O.getInstance().addScript(t,e))throw new u(`A script with name [${t}] already exists`)}};p.redisServerVersion=null;var v=p;v.addScript("RELEASE_LOCK",nt.readFileSync(st(__dirname,"./lua/release-lock.lua")).toString());v.addScript("EXTEND_LOCK",nt.readFileSync(st(__dirname,"./lua/extend-lock.lua")).toString());var F=class{constructor(r,t,e,i=!1,n=!1){this.status=0;this.lockingTimer=null;this.autoExtendTimer=null;this.lockKey=t,this.ttl=e,this.retryOnFail=i,this.lockId=pt(),this.redisClient=r,this.autoExtend=n}resetTimers(){this.lockingTimer&&(clearTimeout(this.lockingTimer),this.lockingTimer=null),this.autoExtendTimer&&(clearTimeout(this.autoExtendTimer),this.autoExtendTimer=null)}setUnlocked(){this.status=0}setLocked(){this.status=2}setExtended(){this.status=5}extend(r){this.isLocked()?(this.status=4,this.redisClient.runScript("EXTEND_LOCK",[this.lockKey],[this.lockId,this.ttl],(t,e)=>{t?r(t):this.status===4?e?(this.setExtended(),r()):(this.setUnlocked(),r(new A)):r(new I)})):r(new P)}runAutoExtendTimer(){let r=Math.ceil(this.ttl/2);this.autoExtendTimer=setTimeout(()=>this.extend(t=>{t?t instanceof I||k().emit("error",t):this.runAutoExtendTimer()}),r)}acquireLock(r){if(!this.isReleased())r(new H);else{this.status=1;let t=()=>{this.status===1?this.redisClient.set(this.lockKey,this.lockId,{expire:{mode:"PX",value:this.ttl},exists:"NX"},(e,i)=>{e?r(e):this.status===1?i?(this.setLocked(),this.autoExtend&&this.runAutoExtendTimer(),r()):this.retryOnFail?this.lockingTimer=setTimeout(t,1e3):(this.setUnlocked(),r(new E)):r(new I)}):r(new I)};t()}}extendLock(r){this.autoExtend?r(new N):this.extend(r)}releaseLock(r){this.status===0?r():this.isLocked()?(this.resetTimers(),this.status=3,this.redisClient.runScript("RELEASE_LOCK",[this.lockKey],[this.lockId],e=>{e?r(e):(this.setUnlocked(),r())})):r(new P)}acquireOrExtend(r){if(this.autoExtend)r(new N);else{let t=()=>{this.acquireLock(e=>{e?r(e):r(null,2)})};this.isLocked()?this.extend(e=>{e?e instanceof A?t():r(e):r(null,5)}):t()}}isLocked(){return this.status===2||this.status===5}isReleased(){return this.status===0}getId(){return this.lockId}};var C=class{constructor(){this.isPowered=!1;this.pendingState=null}switch(r){return this.pendingState!==null||r===this.isPowered?!1:(this.pendingState=r,!0)}isUp(){return this.isPowered}isDown(){return!this.isPowered}isGoingUp(){return this.pendingState===!0}isGoingDown(){return this.pendingState===!1}isRunning(){return this.isUp()&&this.pendingState===null}goingUp(){return this.switch(!0)}goingDown(){return this.switch(!1)}commit(){return this.pendingState===null?!1:(this.isPowered=this.pendingState,this.pendingState=null,!0)}rollback(){return this.pendingState===null?!1:(this.pendingState=null,!0)}};var L=class extends x{constructor(t=()=>{},e=1e3){super();this.powerManager=new C;this.onNextTickFn=null;this.timeout=null;this.interval=null;this.shutdownTimeout=null;this.aborted=!1;this.onTickFn=t,this.time=e,this.powerManager.goingUp()}shutdown(){this.shutdownTimeout&&clearTimeout(this.shutdownTimeout),this.powerManager.commit(),this.emit("down")}onTick(){var t;if(this.powerManager.isGoingDown())this.shutdown();else if(this.powerManager.isRunning()){let e=(t=this.onNextTickFn)!=null?t:this.onTickFn;this.onNextTickFn=null,e()}else k().emit("error",new w("Unexpected call"))}abort(){this.aborted||(this.aborted=!0,this.powerManager.isGoingDown()?this.shutdown():this.quit())}quit(){this.powerManager.isGoingUp()?(this.powerManager.rollback(),this.emit("down")):this.aborted&&this.powerManager.isDown()?this.emit("down"):(this.powerManager.goingDown(),this.timeout?(clearTimeout(this.timeout),this.shutdown()):this.interval?(clearInterval(this.interval),this.shutdown()):this.aborted?this.shutdown():this.shutdownTimeout=setTimeout(()=>{this.powerManager.isGoingDown()&&this.shutdown()},6e4))}isTicking(){return!!(this.timeout||this.interval)}nextTick(){this.isTicking()?k().emit("error",new M("A timer is already running")):this.powerManager.isGoingDown()?this.shutdown():(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.timeout=setTimeout(()=>{this.timeout=null,this.onTick()},this.time)))}nextTickFn(t){this.onNextTickFn=t,this.nextTick()}runTimer(){this.isTicking()?k().emit("error",new M("A timer is already running")):(this.powerManager.isGoingUp()&&this.powerManager.commit(),this.powerManager.isRunning()&&(this.interval=setInterval(()=>this.onTick(),this.time)))}};var _=class{constructor(r,t=1e3){this.ticker=null;this.powerManager=null;this.getTicker=()=>{if(!this.ticker)throw new R("Expected an instance of Ticker");return this.ticker};this.onTick=()=>{this.work(r=>{r?k().emit("error",r):this.getTicker().nextTick()})};this.run=r=>{if(this.managed)r(new R("You can not run a managed worker"));else{let t=this.getPowerManager();t.goingUp(),this.getTicker().nextTick(),t.commit(),r()}};this.quit=r=>{if(this.managed)r();else{let t=this.getPowerManager();t.goingDown();let e=this.getTicker();e.on("down",()=>{t.commit(),r()}),e.quit()}};this.managed=r,r||(this.ticker=new L(this.onTick,t),this.powerManager=new C)}getPowerManager(){if(!this.powerManager)throw new R("Expected an instance of PowerSwitch");return this.powerManager}};var Q=class extends x{constructor(t,e,i,n){super();this.onTick=()=>{b.waterfall([t=>{this.lock.acquireOrExtend((e,i)=>{i===2&&this.logger.info(`Workers are exclusively running from this instance (Lock ID ${this.lock.getId()}).`),t(e)})},t=>{this.workerPool.work(t)}],t=>{!t||t instanceof E?this.ticker.nextTick():this.emit("error",t)})};this.clearWorkerPool=t=>{this.workerPool.clear(t)};this.stopTicker=t=>{this.ticker.once("down",t),this.ticker.quit()};this.releaseLock=t=>{this.lock.releaseLock(t)};this.run=t=>{this.ticker.nextTick(),this.emit("up"),t()};this.quit=t=>{b.waterfall([this.stopTicker,this.clearWorkerPool,this.releaseLock],()=>{this.emit("down"),t()})};this.powerManager=new C,this.redisClient=t,this.logger=n,this.lock=new F(t,e,6e4),this.ticker=new L(this.onTick),this.workerPool=i}addWorker(t){this.workerPool.add(t)}};var $=class{constructor(){this.pool=[];this.work=r=>{if(this.pool.length){let t=this.pool.map(e=>i=>e.work(i));b.waterfall(t,r)}else r()};this.add=r=>(this.pool.push(r),this.pool.length);this.clear=r=>{b.each(this.pool,(t,e,i)=>{t.quit(i)},()=>{this.pool=[],r()})}}};import{createLogger as kt}from"bunyan";var D=()=>{},vt={debug:D,warn:D,info:D,error:D},f=null;function ft(){f=null}function Ct(o){if(f)throw new U("Logger has been already initialized.");f=o}function It(o,r){var t;if(!o.enabled)return vt;if(f||(f=kt(j(z({},(t=o.options)!=null?t:{}),{name:"redis-smq"}))),r){let e=(i,n)=>(s,...l)=>{let a=typeof s=="string"?`${r} | ${s}`:s;return n[i](a,...l)};return{info:e("info",f),warn:e("warn",f),debug:e("debug",f),error:e("error",f)}}return f}var xt={getLogger:It,setLogger:Ct,destroy:ft};import{createClient as wt}from"@redis/client";import{WatchError as Tt}from"@redis/client";var q=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lRem(r,t,e),this}lpop(r){return this.multi.lPop(r),this}lpush(r,t){return this.multi.lPush(r,t),this}ltrim(r,t,e){return this.multi.lTrim(r,t,e),this}rpop(r){return this.multi.rPop(r),this}rpush(r,t){return this.multi.rPush(r,t),this}zadd(r,t,e){return this.multi.zAdd(r,{score:t,value:e}),this}zrem(r,t){return this.multi.zRem(r,t),this}sadd(r,t){return this.multi.sAdd(r,t),this}srem(r,t){return this.multi.sRem(r,t),this}hset(r,t,e){return this.multi.hSet(r,t,e),this}hdel(r,t){return this.multi.hDel(r,t),this}hincrby(r,t,e){return this.multi.hIncrBy(r,t,e),this}pexpire(r,t){return this.multi.pExpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rPopLPush(r,t),this}del(r){return this.multi.del(r),this}exec(r){this.multi.exec().then(t=>r(null,t)).catch(t=>{t instanceof Tt?r(new y):r(t)})}};var X=class extends v{constructor(t={}){super();this.client=wt(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")}),this.client.connect()}set(t,e,i,n){this.client.set(t,e,z(z({},i.expire?{[i.expire.mode]:i.expire.value}:{}),i.exists?{[i.exists]:!0}:{})).then(s=>n(null,s)).catch(n)}zadd(t,e,i,n){this.client.zAdd(t,{score:e,value:i}).then(s=>n(null,s)).catch(n)}multi(){return new q(this.client)}watch(t,e){this.client.watch(t).then(i=>e(null,i)).catch(e)}unwatch(t){this.client.unwatch().then(e=>t(null,e)).catch(t)}sismember(t,e,i){this.client.sIsMember(t,e).then(n=>i(null,Number(n))).catch(i)}zcard(t,e){this.client.zCard(t).then(i=>e(null,i)).catch(e)}zrange(t,e,i,n){this.client.zRange(t,e,i).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrevrange(t,e,i,n){this.client.sendCommand(["ZREVRANGE",t,String(e),String(i)]).then(s=>n(null,(Array.isArray(s)?s:[]).map(l=>String(l)))).catch(n)}zrem(t,e,i){this.client.zRem(t,e).then(n=>i(null,n)).catch(i)}psubscribe(t){this.client.pSubscribe(t,(e,i)=>{this.client.emit("pmessage",t,i,e)})}punsubscribe(t){this.client.pUnsubscribe(t).catch(()=>{})}subscribe(t){this.client.subscribe(t,(e,i)=>{this.client.emit("message",i,e)})}unsubscribe(t){this.client.unsubscribe(t).catch(()=>{})}zrangebyscore(t,e,i,n,s,l){this.client.zRangeByScore(t,e,i,{LIMIT:{offset:n,count:s}}).then(a=>l(null,a)).catch(l)}smembers(t,e){this.client.sMembers(t).then(i=>e(null,i)).catch(e)}sscan(t,e,i,n){let s=[t,Number(e),i];this.client.sScan(...s).then(({cursor:l,members:a})=>{n(null,{cursor:String(l),items:a})}).catch(n)}zscan(t,e,i,n){let s=[t,Number(e),i];this.client.zScan(...s).then(({cursor:l,members:a})=>{let c=new Set;for(let g of a)c.add(g.value);n(null,{cursor:String(l),items:[...c]})}).catch(n)}sadd(t,e,i){this.client.sAdd(t,e).then(n=>i(null,n)).catch(i)}srem(t,e,i){this.client.sRem(t,e).then(n=>i(null,n)).catch(i)}hgetall(t,e){this.client.hGetAll(t).then(i=>e(null,i)).catch(e)}hscan(t,e,i,n){let s=[t,Number(e),i];this.client.hScan(...s).then(({cursor:l,tuples:a})=>{let c={};for(;a.length;){let g=a.shift();g&&(c[g.field]=g.value)}n(null,{cursor:String(l),result:c})}).catch(n)}hget(t,e,i){this.client.hGet(t,e).then(n=>i(null,n!=null?n:null)).catch(i)}hset(t,e,i,n){this.client.hSet(t,e,i).then(s=>n(null,s)).catch(n)}hdel(t,e,i){this.client.hDel(t,e).then(n=>i(null,Number(n))).catch(i)}lrange(t,e,i,n){this.client.lRange(t,e,i).then(s=>n(null,s)).catch(n)}hkeys(t,e){this.client.hKeys(t).then(i=>e(null,i)).catch(e)}hlen(t,e){this.client.hLen(t).then(i=>e(null,i)).catch(e)}brpoplpush(t,e,i,n){this.client.brPopLPush(t,e,i).then(s=>n(null,s)).catch(n)}rpoplpush(t,e,i){this.client.rPopLPush(t,e).then(n=>i(null,n)).catch(i)}zrangebyscorewithscores(t,e,i,n){this.client.zRangeByScoreWithScores(t,e,i).then(s=>{let l={};for(let{score:a,value:c}of s)l[a]=c;n(null,l)}).catch(n)}rpop(t,e){this.client.rPop(t).then(i=>e(null,i)).catch(e)}lrem(t,e,i,n){this.client.lRem(t,e,i).then(s=>n(null,s)).catch(n)}publish(t,e,i){this.client.publish(t,e).then(n=>i(null,n)).catch(i)}flushall(t){this.client.flushAll().then(e=>t(null,e)).catch(t)}loadScript(t,e){this.client.sendCommand(["SCRIPT","LOAD",t]).then(i=>e(null,typeof i=="string"?i:String(i))).catch(e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.sendCommand(["evalsha",...n.concat(s).map(l=>String(l))]).then(l=>{Array.isArray(l)?i(null,l.map(a=>a instanceof Buffer?a.toString():a)):l instanceof Buffer?i(null,l.toString()):i(null,l)}).catch(i)}get(t,e){this.client.sendCommand(["get",t]).then(i=>e(null,typeof i=="string"?i:null)).catch(e)}del(t,e){this.client.del(t).then(i=>e(null,i)).catch(e)}llen(t,e){this.client.sendCommand(["llen",t]).then(i=>e(null,Number(i))).catch(e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lMove(t,e,i,n).then(l=>s(null,l)).catch(s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.sendCommand(["zremrangebyscore",t,`${e}`,`${i}`]).then(s=>n(null,Number(s))).catch(n)}hmget(t,e,i){this.client.hmGet(t,e).then(n=>i(null,n)).catch(i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect().catch(()=>{})}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info().then(e=>t(null,e)).catch(t)}on(t,e){return this.client.on(t,e),this}};import Et from"ioredis";var G=class{constructor(r){this.multi=r.multi()}lrem(r,t,e){return this.multi.lrem(r,t,e),this}lpop(r){return this.multi.lpop(r),this}lpush(r,t){return this.multi.lpush(r,t),this}ltrim(r,t,e){return this.multi.ltrim(r,t,e),this}rpop(r){return this.multi.rpop(r),this}rpush(r,t){return this.multi.rpush(r,t),this}zadd(r,t,e){return this.multi.zadd(r,t,e),this}zrem(r,t){return this.multi.zrem(r,...typeof t=="string"?[t]:t),this}sadd(r,t){return this.multi.sadd(r,t),this}srem(r,t){return this.multi.srem(r,...typeof t=="string"?[t]:t),this}hset(r,t,e){return this.multi.hset(r,t,e),this}hdel(r,t){return this.multi.hdel(r,...typeof t=="string"?[t]:t),this}hincrby(r,t,e){return this.multi.hincrby(r,t,e),this}pexpire(r,t){return this.multi.pexpire(r,t),this}expire(r,t){return this.multi.expire(r,t),this}rpoplpush(r,t){return this.multi.rpoplpush(r,t),this}del(r){return this.multi.del(...typeof r=="string"?[r]:r),this}exec(r){this.multi.exec((t,e)=>{if(t)r(t);else if(!e)r(new y);else{let i=[],n=null;for(let s of e){if(!Array.isArray(s)){n=new u("Expected an array reply from multi.exec()");break}let[l,a]=s;if(l instanceof Error){n=l;break}i.push(a)}n?r(n):r(null,i)}})}};var V=class extends v{constructor(t={}){super();this.client=new Et(t),this.client.once("ready",()=>{this.connectionClosed=!1,this.emit("ready")}),this.client.once("end",()=>{this.connectionClosed=!0,this.emit("end")})}set(t,e,i,n){i.exists&&i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,i.exists,n):i.expire?this.client.set(t,e,i.expire.mode,i.expire.value,n):i.exists?this.client.set(t,e,i.exists,n):this.client.set(t,e,n)}zadd(t,e,i,n){this.client.zadd(t,e,i,n)}multi(){return new G(this.client)}watch(t,e){this.client.watch(t,e)}unwatch(t){this.client.unwatch(t)}sismember(t,e,i){this.client.sismember(t,e,i)}sscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.sscan(...s,(l,[a,c])=>{l?n(l):n(null,{cursor:a,items:c})})}zcard(t,e){this.client.zcard(t,e)}zrange(t,e,i,n){this.client.zrange(t,e,i,n)}zscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.zscan(...s,(l,a)=>{if(l)n(l);else if(!a)n(new h);else{let c=new Set,[g,T]=a;for(;T.length;){let W=String(T.shift()),Lt=String(T.shift());c.add(W)}n(null,{cursor:g,items:[...c]})}})}zrevrange(t,e,i,n){this.client.zrevrange(t,e,i,n)}zrem(t,e,i){this.client.zrem(t,e,i)}psubscribe(t){this.client.psubscribe(t)}punsubscribe(t){this.client.punsubscribe(t)}subscribe(t){this.client.subscribe(t)}unsubscribe(t){this.client.unsubscribe(t)}zrangebyscore(t,e,i,n,s,l){this.client.zrangebyscore(t,e,i,"LIMIT",n,s,l)}smembers(t,e){this.client.smembers(t,e)}sadd(t,e,i){this.client.sadd(t,e,i)}srem(t,e,i){this.client.srem(t,e,i)}hgetall(t,e){this.client.hgetall(t,e)}hscan(t,e,i,n){let s=[t,e];i.MATCH&&s.push("MATCH",i.MATCH),i.COUNT&&s.push("COUNT",String(i.COUNT)),this.client.hscan(...s,(l,[a,c])=>{if(l)n(l);else{let g={};for(;c.length;){let T=String(c.shift());g[T]=String(c.shift())}n(null,{cursor:a,result:g})}})}hget(t,e,i){this.client.hget(t,e,i)}hset(t,e,i,n){this.client.hset(t,e,i,n)}hdel(t,e,i){this.client.hdel(t,e,i)}lrange(t,e,i,n){this.client.lrange(t,e,i,n)}hkeys(t,e){this.client.hkeys(t,e)}hlen(t,e){this.client.hlen(t,e)}brpoplpush(t,e,i,n){this.client.brpoplpush(t,e,i,n)}rpoplpush(t,e,i){this.client.rpoplpush(t,e,i)}zrangebyscorewithscores(t,e,i,n){this.client.zrangebyscore(t,e,i,"WITHSCORES",(s,l)=>{if(s)n(s);else{let a=l!=null?l:[],c={};for(let g=a.splice(0,2);g.length>0;g=a.splice(0,2)){let[T,W]=g;c[W]=T}n(null,c)}})}rpop(t,e){this.client.rpop(t,e)}lrem(t,e,i,n){this.client.lrem(t,e,i,n)}publish(t,e,i){this.client.publish(t,e,i)}flushall(t){this.client.flushall(t)}loadScript(t,e){this.client.script("load",t,e)}evalsha(t,e,i){let n=[t],s=Array.isArray(e)?e:[e];this.client.evalsha(n.concat(s),i)}get(t,e){this.client.get(t,e)}del(t,e){this.client.del(t,e)}llen(t,e){this.client.llen(t,e)}lmove(t,e,i,n,s){this.validateRedisVersion(6,2)?this.client.lmove(t,e,i,n,s):s(new u("Command not supported by your Redis server. Minimal required Redis server version is 6.2.0."))}zremrangebyscore(t,e,i,n){this.client.zremrangebyscore(t,e,i,n)}hmget(t,e,i){this.client.hmget(t,e,i)}halt(t){this.connectionClosed?t():(this.client.once("end",t),this.end())}end(){this.connectionClosed||this.client.disconnect(!1)}quit(t=()=>{}){this.connectionClosed?t():(this.client.once("end",t),this.client.quit())}getInfo(t){this.client.info(t)}on(t,e){return this.client.on(t,e),this}};function yt(o){return o.client==="redis"?new X(o.options):new V(o.options)}function Rt(o,r){let t=yt(o);t.once("ready",()=>{b.waterfall([e=>t.validateRedisServerSupport(e),e=>t.loadScripts(e)],e=>{e?r(e):r(null,t)})})}var St={createInstance:Rt};export{h as CallbackEmptyReplyError,K as CallbackInvalidReplyError,Y as ERedisConfigClient,x as EventEmitter,F as Lock,I as LockAbortError,E as LockAcquireError,m as LockError,A as LockExtendError,N as LockMethodNotAllowedError,P as LockNotAcquiredError,H as LockNotReleasedError,U as LoggerError,w as PanicError,C as PowerSwitch,v as RedisClient,u as RedisClientError,d as RedisSMQError,L as Ticker,M as TickerError,y as WatchedKeysChangedError,_ as Worker,R as WorkerError,$ as WorkerPool,Q as WorkerRunner,b as async,k as getEventBusInstance,xt as logger,St as redis};
4
3
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "redis-smq-common",
3
- "version": "3.0.0-rc.0",
3
+ "version": "3.0.0-rc.10",
4
4
  "description": "RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.",
5
5
  "author": "Weyoss <weyoss@protonmail.com>",
6
6
  "license": "MIT",
@@ -33,16 +33,15 @@
33
33
  "type": "module",
34
34
  "main": "dist/index.cjs",
35
35
  "module": "dist/index.js",
36
+ "types": "dist/index.d.ts",
36
37
  "dependencies": {
37
38
  "@redis/client": "1.1.0",
38
39
  "@types/bunyan": "1.8.7",
39
40
  "@types/ioredis": "4.28.1",
40
- "@types/redis": "2.8.32",
41
41
  "bluebird": "3.7.2",
42
42
  "bunyan": "1.8.15",
43
43
  "ioredis": "4.28.0",
44
44
  "lodash": "4.17.21",
45
- "redis": "3.1.2",
46
45
  "uuid": "8.3.2"
47
46
  },
48
47
  "devDependencies": {
package/docs/README.md DELETED
@@ -1,13 +0,0 @@
1
- > [RedisSMQ Common Library](../README.md) / Docs
2
-
3
- # Docs
4
-
5
- ## API
6
-
7
- See for [API](./api/README.md) referencce for details
8
-
9
- ## Misc
10
-
11
- * [Logs](./logs.md)
12
-
13
- * [Redis](redis.md)