@hamim_4444/pulsar 0.0.0-stage → 1.0.1

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.
Files changed (176) hide show
  1. package/README.md +14 -2
  2. package/dist/cluster/Nebula.d.ts +30 -0
  3. package/dist/cluster/Nebula.d.ts.map +1 -0
  4. package/dist/dispatch/ConsumerDispatch.d.ts +9 -0
  5. package/dist/dispatch/ConsumerDispatch.d.ts.map +1 -0
  6. package/dist/dispatch/Dispatcher.d.ts +6 -0
  7. package/dist/dispatch/Dispatcher.d.ts.map +1 -0
  8. package/dist/dispatch/HandlerDispatcher.d.ts +7 -0
  9. package/dist/dispatch/HandlerDispatcher.d.ts.map +1 -0
  10. package/dist/dispatch/HttpDispatcher.d.ts +7 -0
  11. package/dist/dispatch/HttpDispatcher.d.ts.map +1 -0
  12. package/dist/dispatch/dispatchTypes.d.ts +12 -0
  13. package/dist/dispatch/dispatchTypes.d.ts.map +1 -0
  14. package/dist/helpers/computeConfigDelta.d.ts +18 -0
  15. package/dist/helpers/computeConfigDelta.d.ts.map +1 -0
  16. package/dist/helpers/defineQueue.d.ts +13 -0
  17. package/dist/helpers/defineQueue.d.ts.map +1 -0
  18. package/dist/helpers/generateShaHash.d.ts +2 -0
  19. package/dist/helpers/generateShaHash.d.ts.map +1 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +47 -0
  23. package/dist/index.js.map +42 -0
  24. package/dist/integrations/PulsarEventsIntegrations.d.ts +7 -0
  25. package/dist/integrations/PulsarEventsIntegrations.d.ts.map +1 -0
  26. package/dist/integrations/PulsarLoggerIntegrations.d.ts +12 -0
  27. package/dist/integrations/PulsarLoggerIntegrations.d.ts.map +1 -0
  28. package/dist/integrations/index.d.ts +4 -0
  29. package/dist/integrations/index.d.ts.map +1 -0
  30. package/dist/integrations/index.js +3 -0
  31. package/dist/integrations/index.js.map +15 -0
  32. package/dist/modules/Queue.module.d.ts +45 -0
  33. package/dist/modules/Queue.module.d.ts.map +1 -0
  34. package/dist/modules/Scheduler.module.d.ts +42 -0
  35. package/dist/modules/Scheduler.module.d.ts.map +1 -0
  36. package/dist/modules/Tick.module.d.ts +38 -0
  37. package/dist/modules/Tick.module.d.ts.map +1 -0
  38. package/dist/modules/TickController.module.d.ts +36 -0
  39. package/dist/modules/TickController.module.d.ts.map +1 -0
  40. package/dist/monitoring/PulsarMonitoringStreamProducer.d.ts +2 -0
  41. package/dist/monitoring/PulsarMonitoringStreamProducer.d.ts.map +1 -0
  42. package/dist/monitoring/index.d.ts +2 -0
  43. package/dist/monitoring/index.d.ts.map +1 -0
  44. package/dist/monitoring/server/PulsarMonitoringStream.d.ts +2 -0
  45. package/dist/monitoring/server/PulsarMonitoringStream.d.ts.map +1 -0
  46. package/dist/network/NetworkInterface.d.ts +12 -0
  47. package/dist/network/NetworkInterface.d.ts.map +1 -0
  48. package/dist/network/UnifiedTransportManager.d.ts +19 -0
  49. package/dist/network/UnifiedTransportManager.d.ts.map +1 -0
  50. package/dist/network/abstract/BaseNetworkDriver.d.ts +18 -0
  51. package/dist/network/abstract/BaseNetworkDriver.d.ts.map +1 -0
  52. package/dist/network/auth/Authenticator.d.ts +2 -0
  53. package/dist/network/auth/Authenticator.d.ts.map +1 -0
  54. package/dist/network/drivers/HttpNetworkDriver.d.ts +30 -0
  55. package/dist/network/drivers/HttpNetworkDriver.d.ts.map +1 -0
  56. package/dist/network/drivers/ServerlessNetworkDriver.d.ts +13 -0
  57. package/dist/network/drivers/ServerlessNetworkDriver.d.ts.map +1 -0
  58. package/dist/network/drivers/WebSocketNetworkDriver.d.ts +24 -0
  59. package/dist/network/drivers/WebSocketNetworkDriver.d.ts.map +1 -0
  60. package/dist/network/helpers/httpQueueOperations.d.ts +2 -0
  61. package/dist/network/helpers/httpQueueOperations.d.ts.map +1 -0
  62. package/dist/network/interfaces/network.types.d.ts +13 -0
  63. package/dist/network/interfaces/network.types.d.ts.map +1 -0
  64. package/dist/run/Queues.d.ts +2 -0
  65. package/dist/run/Queues.d.ts.map +1 -0
  66. package/dist/run/index.d.ts +2 -0
  67. package/dist/run/index.d.ts.map +1 -0
  68. package/dist/run/index2.d.ts +2 -0
  69. package/dist/run/index2.d.ts.map +1 -0
  70. package/dist/runtimes/IsolateRuntime.d.ts +17 -0
  71. package/dist/runtimes/IsolateRuntime.d.ts.map +1 -0
  72. package/dist/runtimes/PersistentRuntime.d.ts +21 -0
  73. package/dist/runtimes/PersistentRuntime.d.ts.map +1 -0
  74. package/dist/runtimes/ServerlessRuntime.d.ts +15 -0
  75. package/dist/runtimes/ServerlessRuntime.d.ts.map +1 -0
  76. package/dist/runtimes/runtimeTypes.d.ts +15 -0
  77. package/dist/runtimes/runtimeTypes.d.ts.map +1 -0
  78. package/dist/server/PulsarRequestHandler.d.ts +41 -0
  79. package/dist/server/PulsarRequestHandler.d.ts.map +1 -0
  80. package/dist/server/helpers/acquireRedisLock.d.ts +14 -0
  81. package/dist/server/helpers/acquireRedisLock.d.ts.map +1 -0
  82. package/dist/server/helpers/checkFencingValidity.d.ts +14 -0
  83. package/dist/server/helpers/checkFencingValidity.d.ts.map +1 -0
  84. package/dist/server/helpers/performIsolateRestart.d.ts +20 -0
  85. package/dist/server/helpers/performIsolateRestart.d.ts.map +1 -0
  86. package/dist/server/index.d.ts +3 -0
  87. package/dist/server/index.d.ts.map +1 -0
  88. package/dist/server/index.js +53 -0
  89. package/dist/server/index.js.map +20 -0
  90. package/dist/server/parser/parseRequest.d.ts +10 -0
  91. package/dist/server/parser/parseRequest.d.ts.map +1 -0
  92. package/dist/server/utility/extract-headers.d.ts +13 -0
  93. package/dist/server/utility/extract-headers.d.ts.map +1 -0
  94. package/dist/service/ConfigurationStore.d.ts +23 -0
  95. package/dist/service/ConfigurationStore.d.ts.map +1 -0
  96. package/dist/service/Isolate.service.d.ts +12 -0
  97. package/dist/service/Isolate.service.d.ts.map +1 -0
  98. package/dist/service/Pulsar.service.d.ts +40 -0
  99. package/dist/service/Pulsar.service.d.ts.map +1 -0
  100. package/dist/service/PulsarBaseService.d.ts +51 -0
  101. package/dist/service/PulsarBaseService.d.ts.map +1 -0
  102. package/dist/service/PulsarEventBus.d.ts +33 -0
  103. package/dist/service/PulsarEventBus.d.ts.map +1 -0
  104. package/dist/service/SwarmBudgetTracker.d.ts +14 -0
  105. package/dist/service/SwarmBudgetTracker.d.ts.map +1 -0
  106. package/dist/service/consumers/PulsarWorker.d.ts +10 -0
  107. package/dist/service/consumers/PulsarWorker.d.ts.map +1 -0
  108. package/dist/shared/PulsarRuntimeCore.d.ts +55 -0
  109. package/dist/shared/PulsarRuntimeCore.d.ts.map +1 -0
  110. package/dist/static/TimingProfile.d.ts +9 -0
  111. package/dist/static/TimingProfile.d.ts.map +1 -0
  112. package/dist/static/static.d.ts +3 -0
  113. package/dist/static/static.d.ts.map +1 -0
  114. package/dist/storage/PulsarStorage.d.ts +42 -0
  115. package/dist/storage/PulsarStorage.d.ts.map +1 -0
  116. package/dist/storage/drivers/PostgresDriver.d.ts +20 -0
  117. package/dist/storage/drivers/PostgresDriver.d.ts.map +1 -0
  118. package/dist/storage/drivers/RedisDriver.d.ts +20 -0
  119. package/dist/storage/drivers/RedisDriver.d.ts.map +1 -0
  120. package/dist/storage/drivers/types.d.ts +27 -0
  121. package/dist/storage/drivers/types.d.ts.map +1 -0
  122. package/dist/storage/index.d.ts +4 -0
  123. package/dist/storage/index.d.ts.map +1 -0
  124. package/dist/storage/index.js +393 -0
  125. package/dist/storage/index.js.map +25 -0
  126. package/dist/storage/repositories/PostgresEngineOperationRepository.d.ts +39 -0
  127. package/dist/storage/repositories/PostgresEngineOperationRepository.d.ts.map +1 -0
  128. package/dist/storage/repositories/PostgresQueueRepository.d.ts +25 -0
  129. package/dist/storage/repositories/PostgresQueueRepository.d.ts.map +1 -0
  130. package/dist/storage/repositories/QueueRepository.d.ts +19 -0
  131. package/dist/storage/repositories/QueueRepository.d.ts.map +1 -0
  132. package/dist/storage/repositories/RedisQueueRepository.d.ts +27 -0
  133. package/dist/storage/repositories/RedisQueueRepository.d.ts.map +1 -0
  134. package/dist/subsys/DeferredTickEvaluator.d.ts +23 -0
  135. package/dist/subsys/DeferredTickEvaluator.d.ts.map +1 -0
  136. package/dist/subsys/EventBus.d.ts +13 -0
  137. package/dist/subsys/EventBus.d.ts.map +1 -0
  138. package/dist/subsys/ExecutionProfileSwitcher.d.ts +10 -0
  139. package/dist/subsys/ExecutionProfileSwitcher.d.ts.map +1 -0
  140. package/dist/subsys/LoggerService.d.ts +15 -0
  141. package/dist/subsys/LoggerService.d.ts.map +1 -0
  142. package/dist/subsys/PulsarClock.d.ts +32 -0
  143. package/dist/subsys/PulsarClock.d.ts.map +1 -0
  144. package/dist/subsys/RuntimeCacheStorage.d.ts +18 -0
  145. package/dist/subsys/RuntimeCacheStorage.d.ts.map +1 -0
  146. package/dist/subsys/RuntimeEventBridge.d.ts +14 -0
  147. package/dist/subsys/RuntimeEventBridge.d.ts.map +1 -0
  148. package/dist/transport/PulsarTransportManager.d.ts +10 -0
  149. package/dist/transport/PulsarTransportManager.d.ts.map +1 -0
  150. package/dist/transport/strategies/PollingTransport.d.ts +13 -0
  151. package/dist/transport/strategies/PollingTransport.d.ts.map +1 -0
  152. package/dist/transport/strategies/TcpListenTransport.d.ts +11 -0
  153. package/dist/transport/strategies/TcpListenTransport.d.ts.map +1 -0
  154. package/dist/transport/strategies/WebhookTransport.d.ts +9 -0
  155. package/dist/transport/strategies/WebhookTransport.d.ts.map +1 -0
  156. package/dist/transport/types.d.ts +41 -0
  157. package/dist/transport/types.d.ts.map +1 -0
  158. package/dist/types/base.types.d.ts +54 -0
  159. package/dist/types/base.types.d.ts.map +1 -0
  160. package/dist/types/config.types.d.ts +54 -0
  161. package/dist/types/config.types.d.ts.map +1 -0
  162. package/dist/types/consumer.types.d.ts +36 -0
  163. package/dist/types/consumer.types.d.ts.map +1 -0
  164. package/dist/types/engine.types.d.ts +115 -0
  165. package/dist/types/engine.types.d.ts.map +1 -0
  166. package/dist/types/eventTriggerStrategry.types.d.ts +34 -0
  167. package/dist/types/eventTriggerStrategry.types.d.ts.map +1 -0
  168. package/dist/types/integrations.types.d.ts +16 -0
  169. package/dist/types/integrations.types.d.ts.map +1 -0
  170. package/dist/types/nebula.types.d.ts +65 -0
  171. package/dist/types/nebula.types.d.ts.map +1 -0
  172. package/dist/types/queue.types.d.ts +95 -0
  173. package/dist/types/queue.types.d.ts.map +1 -0
  174. package/dist/types/runtime.types.d.ts +89 -0
  175. package/dist/types/runtime.types.d.ts.map +1 -0
  176. package/package.json +72 -5
@@ -0,0 +1,393 @@
1
+ var EW=Object.create;var{getPrototypeOf:FW,defineProperty:n,getOwnPropertyNames:AW}=Object;var _W=Object.prototype.hasOwnProperty;function jW(Y){return this[Y]}var BW,PW,u$=(Y,W,$)=>{var G=Y!=null&&typeof Y==="object";if(G){var Q=W?BW??=new WeakMap:PW??=new WeakMap,V=Q.get(Y);if(V)return V}$=Y!=null?EW(FW(Y)):{};let z=W||!Y||!Y.__esModule?n($,"default",{value:Y,enumerable:!0}):$;for(let H of AW(Y))if(!_W.call(z,H))n(z,H,{get:jW.bind(Y,H),enumerable:!0});if(G)Q.set(Y,z);return z};var i$=(Y,W)=>()=>(W||Y((W={exports:{}}).exports,W),W.exports);var A=90000;class E{}var IW="9223372036854775807";class x extends E{driver;constructor(Y){super();this.driver=Y;this.driver=Y}get sql(){return this.driver.getNativeClient()}get prefix(){if(!this.driver.prefix)throw Error("[PostgresQueueRepository] Driver prefix is missing. Ensure the prefix is configured by calling driver.setPrefix(string).");return this.driver.prefix}async registerWorker(Y,W,$,G=1/0){let Q=`${this.prefix}:queues:${Y}:worker_registry`,V=`${this.prefix}:global_worker_registry`,z=W.map((T)=>T.workerId);if(z.length===0)return[];let H=G===1/0?2147483647:G;return(await this.sql`
2
+ SELECT granted_worker_id
3
+ FROM register_workers(
4
+ ${Q}::varchar,
5
+ ${V}::varchar,
6
+ ${$}::int,
7
+ ${H}::int,
8
+ ${A}::bigint,
9
+ ${this.sql.array(z)}::varchar[]
10
+ )
11
+ `).map((T)=>T.granted_worker_id)}async deregisterWorker(Y,W){if(!Y)return;let $=`${this.prefix}:queues:${W}:worker_registry`,G=`${this.prefix}:global_worker_registry`,Q=`${$}:${Y}`;await this.sql`
12
+ DELETE FROM pulsar.queue_cache
13
+ WHERE (key = ${$} AND field = ${Y})
14
+ OR (key = ${G} AND field = ${Q})
15
+ `}async getActiveWorkersCount(Y){let W=`${this.prefix}:queues:${Y}:worker_registry`,[$]=await this.sql`
16
+ SELECT COUNT(*)::int AS count
17
+ FROM pulsar.queue_cache
18
+ WHERE key = ${W} AND expires_at > pulsar.now_ms()
19
+ `;return $?.count??0}async setFutureSchedule(Y,W){let $=`${this.prefix}:queues:${Y}:next_ready_at`;await this.sql`
20
+ INSERT INTO pulsar.queue_cache (key, field, value, expires_at)
21
+ VALUES (${$}, '', ${W}, ${IW})
22
+ ON CONFLICT (key, field)
23
+ DO UPDATE SET value = EXCLUDED.value
24
+ `}async getGlobalActiveWorkersCount(){let Y=`${this.prefix}:global_worker_registry`,[W]=await this.sql`
25
+ SELECT COUNT(*)::int AS count
26
+ FROM pulsar.queue_cache
27
+ WHERE key = ${Y} AND expires_at > pulsar.now_ms()
28
+ `;return W?.count??0}async refundGlobalJobBudget(Y,W){if(Y<=0)return;let $=`${this.budgetKeyPrefix()}${W}`;await this.sql`
29
+ UPDATE pulsar.queue_cache
30
+ SET value = GREATEST(0, value::int - ${Y})::text
31
+ WHERE key = ${$} AND field = 'count'
32
+ `}budgetKeyPrefix(){return`${this.prefix}:global:job_budget`}async claimGlobalJobBudget(Y,W){if(W===1/0||W<=0)return{granted:Y,window:""};let $=this.budgetKeyPrefix();return await this.sql.begin(async(G)=>{await G`SELECT pg_advisory_xact_lock(hashtext(${$}))`;let[Q]=await G`
33
+ SELECT floor(pulsar.now_ms() / 1000)::float8 AS second
34
+ `,V=Q.second,z=`${$}${V}`,H=(V+2)*1000;await G`
35
+ DELETE FROM pulsar.queue_cache
36
+ WHERE starts_with(key, ${$})
37
+ AND expires_at <= pulsar.now_ms()
38
+ `;let[Z]=await G`
39
+ SELECT COALESCE(
40
+ (SELECT value::int FROM pulsar.queue_cache WHERE key = ${z} AND field = 'count'),
41
+ 0
42
+ ) AS used
43
+ `,T=Math.max(0,Math.min(Y,W-(Z?.used??0)));if(T>0)await G`
44
+ INSERT INTO pulsar.queue_cache (key, field, value, expires_at)
45
+ VALUES (${z}, 'count', ${String(T)}, ${H}::bigint)
46
+ ON CONFLICT (key, field) DO UPDATE
47
+ SET value = (pulsar.queue_cache.value::int + ${T})::text
48
+ `;return{granted:T,window:String(V)}})}async acquireQueueLock(Y,W,$){let G=Date.now(),Q=G+$;return(await this.sql`
49
+ INSERT INTO pulsar.queue_cache (key, field, value, expires_at)
50
+ VALUES (${`${this.prefix}:${Y}`}, '', ${W}, ${Q})
51
+ ON CONFLICT (key, field) DO UPDATE
52
+ SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at
53
+ WHERE pulsar.queue_cache.expires_at IS NULL
54
+ OR pulsar.queue_cache.expires_at <= ${G}
55
+ OR pulsar.queue_cache.value = EXCLUDED.value
56
+ RETURNING 1
57
+ `).length>0}async releaseQueueLock(Y,W){let $=Date.now();return(await this.sql`
58
+ DELETE FROM pulsar.queue_cache
59
+ WHERE key = ${`${this.prefix}:${Y}`}
60
+ AND field = ''
61
+ AND value = ${W}
62
+ AND (expires_at IS NULL OR expires_at > ${$})
63
+ RETURNING 1
64
+ `).length===1}async evaluateDeadRun(Y,W,$,G,Q=15000,V="lock:idp",z="lock:edp:"){let H=Date.now(),Z=`${this.prefix}:${V}`,T=`${this.prefix}:${z}`,X=await this.sql.begin(async(M)=>{await M`SELECT pg_advisory_xact_lock(hashtext(${`dead_run:${Y}`}))`;let J=async(w)=>{let[N]=await M`
65
+ SELECT value FROM pulsar.queue_cache
66
+ WHERE key = ${w} AND field = ''
67
+ AND (expires_at IS NULL OR expires_at > ${H})
68
+ `;return N?.value??null};if(W==="interval-driven-pooler"){let w=await J(Z);if(w!==null&&w!==G)return"IDP_LOCKED";return"ALLOWED"}if(W==="event-driven-pooler"){if($<=0)return"NO_JOBS";let w=`${T}${Y}`,N=await J(w);if(N!==null)return N===G?"ALLOWED":"EDP_LOCKED";if(await J(`${w}:pending`)!==null)return"EDP_DISPATCH_PENDING";return await M`
69
+ INSERT INTO pulsar.queue_cache (key, field, value, expires_at)
70
+ VALUES (${`${w}:pending`}, '', '1', ${H+Q})
71
+ ON CONFLICT (key, field) DO UPDATE
72
+ SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at
73
+ `,"ALLOWED"}return"UNKNOWN_POOLER"});if(X!=="ALLOWED")console.log(`DEAD_RUN STOP REASON : ${X}`);return X==="ALLOWED"}async clearDispatchPending(Y){let W=`${Y}:pending`;await this.sql`
74
+ DELETE FROM pulsar.queue_cache
75
+ WHERE key = ${W} AND field = ''
76
+ `}}var S=`--[[\r
77
+ * Lua Script for Atomic Multi-Queue Worker Registration:\r
78
+ * 1. Purges expired workers from the target Queue Hash and the Global Sorted Set.\r
79
+ * 2. Checks active counts against both queue-level and swarm-level global concurrency.\r
80
+ * 3. Atomic check: slotsAvailable = MIN(localSlots, globalSlots).\r
81
+ * 4. Grants candidate IDs up to slotsAvailable and registers them in both Hash and ZSET.\r
82
+ * 5. Returns array of granted worker IDs.\r
83
+ ]]\r
84
+ \r
85
+ local queueKey = KEYS[1]\r
86
+ local globalKey = KEYS[2]\r
87
+ \r
88
+ local localConcurrency = tonumber(ARGV[1])\r
89
+ local globalConcurrency = tonumber(ARGV[2])\r
90
+ local now = tonumber(ARGV[3])\r
91
+ local ttlMs = tonumber(ARGV[4])\r
92
+ \r
93
+ local newExpireAt = now + ttlMs\r
94
+ \r
95
+ -- 1. Purge expired workers from Global Sorted Set\r
96
+ -- redis.call('ZREMRANGEBYSCORE', globalKey, '-inf', now)\r
97
+ \r
98
+ -- Optional defensive cleanup:\r
99
+ -- removes expired local fields on Redis versions/providers where expiration\r
100
+ -- may not have been processed before this script runs.\r
101
+ local localEntries = redis.call('HGETALL', queueKey)\r
102
+ local localActiveCount = 0\r
103
+ \r
104
+ for i = 1, #localEntries, 2 do\r
105
+ local workerId = localEntries[i]\r
106
+ local expireAt = tonumber(localEntries[i + 1]) or 0\r
107
+ \r
108
+ if expireAt <= now then\r
109
+ redis.call('HDEL', queueKey, workerId)\r
110
+ else\r
111
+ localActiveCount = localActiveCount + 1\r
112
+ end\r
113
+ end\r
114
+ \r
115
+ -- 3. Check active count against Global Concurrency\r
116
+ local globalActiveCount = redis.call('HLEN', globalKey)\r
117
+ local globalAvailable = globalConcurrency - globalActiveCount\r
118
+ \r
119
+ if globalAvailable <= 0 then\r
120
+ return {}\r
121
+ end\r
122
+ \r
123
+ -- 4. Check active count against Queue Local Concurrency\r
124
+ local localAvailable = localConcurrency - localActiveCount\r
125
+ \r
126
+ if localAvailable <= 0 then\r
127
+ return {}\r
128
+ end\r
129
+ \r
130
+ -- 5. Calculate true atomic capacity\r
131
+ local availableSlots = math.min(globalAvailable, localAvailable)\r
132
+ \r
133
+ -- 6. Grant candidate worker IDs up to available capacity\r
134
+ local grantedWorkers = {}\r
135
+ local candidateCount = #ARGV - 4\r
136
+ local toGrant = math.min(availableSlots, candidateCount)\r
137
+ local newExpireAt = now + ttlMs\r
138
+ \r
139
+ for i = 1, toGrant do\r
140
+ local candidateId = ARGV[4 + i]\r
141
+ \r
142
+ -- Important:\r
143
+ -- A global ID must be unique across every queue.\r
144
+ -- See the TypeScript section below.\r
145
+ local globalWorkerId = queueKey .. ':' .. candidateId\r
146
+ \r
147
+ -- Add to Queue Hash\r
148
+ redis.call('HSET', queueKey, candidateId, newExpireAt)\r
149
+ local expireResult = redis.call(\r
150
+ 'HPEXPIRE',\r
151
+ queueKey,\r
152
+ ttlMs,\r
153
+ 'FIELDS',\r
154
+ 1,\r
155
+ candidateId\r
156
+ )\r
157
+ \r
158
+ -- Add to Global ZSET (Score = Expiration Timestamp)\r
159
+ -- Global registration\r
160
+ redis.call('HSET', globalKey, globalWorkerId, newExpireAt)\r
161
+ redis.call(\r
162
+ 'HPEXPIREAT',\r
163
+ globalKey,\r
164
+ newExpireAt,\r
165
+ 'FIELDS',\r
166
+ 1,\r
167
+ globalWorkerId\r
168
+ )\r
169
+ \r
170
+ table.insert(grantedWorkers, candidateId)\r
171
+ end\r
172
+ \r
173
+ return grantedWorkers`;var t=`local lockKey = KEYS[1]\r
174
+ local ownerId = ARGV[1]\r
175
+ local ttl = tonumber(ARGV[2])\r
176
+ \r
177
+ local currentOwner = redis.call("GET", lockKey)\r
178
+ \r
179
+ if not currentOwner then\r
180
+ redis.call("SET", lockKey, ownerId, "PX", ttl)\r
181
+ return 1\r
182
+ elseif currentOwner == ownerId then\r
183
+ redis.call("PEXPIRE", lockKey, ttl)\r
184
+ return 1\r
185
+ else\r
186
+ return 0\r
187
+ end`;var d=`-- KEYS[1]: Lock key\r
188
+ -- ARGV[1]: Isolate Owner ID\r
189
+ \r
190
+ local lockKey = KEYS[1]\r
191
+ local ownerId = ARGV[1]\r
192
+ \r
193
+ if redis.call("GET", lockKey) == ownerId then\r
194
+ return redis.call("DEL", lockKey)\r
195
+ else\r
196
+ return 0\r
197
+ end`;var r=`-- KEYS[1]: IDP lock key\r
198
+ -- KEYS[2]: EDP lock key prefix\r
199
+ -- ARGV[1]: queue name\r
200
+ -- ARGV[2]: pooler type\r
201
+ -- ARGV[3]: total jobs (ready + delayed)\r
202
+ -- ARGV[4]: continuation owner id\r
203
+ -- ARGV[5]: dispatch-pending TTL (ms)\r
204
+ \r
205
+ local idpLockKey = KEYS[1]\r
206
+ local edpLockPrefix = KEYS[2]\r
207
+ local queueName = ARGV[1]\r
208
+ local poolerType = ARGV[2]\r
209
+ local totalJobs = tonumber(ARGV[3])\r
210
+ local continuationOwnerId = ARGV[4]\r
211
+ local dispatchTtlMs = tonumber(ARGV[5])\r
212
+ \r
213
+ if poolerType == "interval-driven-pooler" then\r
214
+ local idpOwner = redis.call("GET", idpLockKey)\r
215
+ \r
216
+ -- No lock: an external invocation may be started.\r
217
+ if not idpOwner then\r
218
+ return "ALLOWED"\r
219
+ end\r
220
+ \r
221
+ -- The current lock belongs to the engine continuation.\r
222
+ -- Allow the continuation to proceed.\r
223
+ if idpOwner == continuationOwnerId then\r
224
+ return "ALLOWED"\r
225
+ end\r
226
+ \r
227
+ return "IDP_LOCKED"\r
228
+ \r
229
+ elseif poolerType == "event-driven-pooler" then \r
230
+ if totalJobs <= 0 then\r
231
+ return "NO_JOBS"\r
232
+ end\r
233
+ \r
234
+ local edpLockKey = edpLockPrefix .. queueName\r
235
+ local dispatchKey = edpLockKey .. ":pending"\r
236
+ \r
237
+ local edpOwner = redis.call("GET", edpLockKey)\r
238
+ \r
239
+ -- The current execution already owns this queue lock.\r
240
+ if edpOwner then\r
241
+ if edpOwner == continuationOwnerId then\r
242
+ return "ALLOWED"\r
243
+ end\r
244
+ \r
245
+ return "EDP_LOCKED"\r
246
+ end\r
247
+ \r
248
+ -- A previous dispatch has not landed yet.\r
249
+ local dispatchPending = redis.call("GET", dispatchKey)\r
250
+ \r
251
+ if dispatchPending then\r
252
+ return "EDP_DISPATCH_PENDING"\r
253
+ end\r
254
+ \r
255
+ -- Reserve the dispatch slot atomically.\r
256
+ redis.call("SET", dispatchKey, "1", "PX", dispatchTtlMs)\r
257
+ \r
258
+ return "ALLOWED"\r
259
+ end\r
260
+ \r
261
+ return "UNKNOWN_POOLER"`;var o=`-- KEYS[1]: window key prefix (e.g. "pulsar::global:job_budget"); window second is appended here\r
262
+ -- ARGV[1]: requested\r
263
+ -- ARGV[2]: limit per window\r
264
+ -- Returns: { granted, windowSecond }\r
265
+ --\r
266
+ -- The window is derived from the Redis server clock and RETURNED, so the caller\r
267
+ -- can refund against the exact window it claimed from (even if the second rolls over).\r
268
+ \r
269
+ local prefix = KEYS[1]\r
270
+ local requested = tonumber(ARGV[1])\r
271
+ local limit = tonumber(ARGV[2])\r
272
+ \r
273
+ local t = redis.call('TIME')\r
274
+ local window = tostring(t[1])\r
275
+ local key = prefix .. ':' .. window\r
276
+ \r
277
+ local current = tonumber(redis.call('GET', key) or "0")\r
278
+ local remaining = limit - current\r
279
+ \r
280
+ if remaining <= 0 then\r
281
+ return { 0, window }\r
282
+ end\r
283
+ \r
284
+ local granted = math.min(requested, remaining)\r
285
+ redis.call('INCRBY', key, granted)\r
286
+ \r
287
+ -- Keep the window key alive for 2 seconds. Check TTL instead of "current == 0"\r
288
+ -- so a key is never left without an expiry.\r
289
+ if redis.call('TTL', key) == -1 then\r
290
+ redis.call('EXPIRE', key, 2)\r
291
+ end\r
292
+ \r
293
+ return { granted, window }`;var a=`local key = KEYS[1]\r
294
+ local refund = tonumber(ARGV[1])\r
295
+ local current = tonumber(redis.call('GET', key) or "0")\r
296
+ \r
297
+ if current > 0 then\r
298
+ local new_val = math.max(0, current - refund)\r
299
+ redis.call('SET', key, new_val, 'KEEPTTL')\r
300
+ end`;var b=`-- KEYS[1]: worker registry hash (workerId -> expireAtMs)\r
301
+ -- Returns the number of live (non-expired) entries and purges expired ones.\r
302
+ -- Replaces HLEN, which can include expired-but-not-yet-reclaimed fields.\r
303
+ \r
304
+ local key = KEYS[1]\r
305
+ \r
306
+ local t = redis.call('TIME')\r
307
+ local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\r
308
+ \r
309
+ local entries = redis.call('HGETALL', key)\r
310
+ local active = 0\r
311
+ \r
312
+ for i = 1, #entries, 2 do\r
313
+ local expireAt = tonumber(entries[i + 1]) or 0\r
314
+ if expireAt <= now then\r
315
+ redis.call('HDEL', key, entries[i])\r
316
+ else\r
317
+ active = active + 1\r
318
+ end\r
319
+ end\r
320
+ \r
321
+ return active`;class q extends E{driver;protocol;constructor(Y){super();this.driver=Y;this.protocol=Y.options.protocol,this.driver=Y}get redis(){return this.driver.getNativeClient()}get prefix(){if(!this.driver.prefix)throw Error("[RedisQueueRepository] Driver prefix is missing. Ensure the prefix is configured by calling driver.setPrefix(string).");return this.driver.prefix}async registerWorker(Y,W,$,G=1/0){let Q=`${this.prefix}:queues:${Y}:worker_registry`,V=`${this.prefix}:global_worker_registry`,z=Date.now(),H=[Q,V],Z=[$,G===1/0?999999999:G,z,A,...W.map((T)=>T.workerId)];if(this.protocol==="http")return await this.redis.eval(S,H,Z)??[];else return await this.redis.eval(S,H.length,...H,...Z)??[]}async deregisterWorker(Y,W){if(!Y)return;let $=`${this.prefix}:queues:${W}:worker_registry`,G=`${this.prefix}:global_worker_registry`,Q=`${$}:${Y}`,V=this.redis.pipeline();V.hdel($,Y),V.hdel(G,Q),await V.exec()}async getActiveWorkersCount(Y){let W=`${this.prefix}:queues:${Y}:worker_registry`,$=await this.evalScript(b,[W],[]);return Number($??0)}async getGlobalActiveWorkersCount(){let Y=`${this.prefix}:global_worker_registry`,W=await this.evalScript(b,[Y],[]);return Number(W??0)}async setFutureSchedule(Y,W){let $=`${this.prefix}:queues:${Y}:next_ready_at`;await this.redis.set($,W)}budgetKeyPrefix(){return`${this.prefix}:global:job_budget`}async claimGlobalJobBudget(Y,W){if(W===1/0||W<=0)return{granted:Y,window:""};let $=await this.evalScript(o,[this.budgetKeyPrefix()],[Y,W]),[G,Q]=$??[0,""];return{granted:Number(G??0),window:String(Q??"")}}async refundGlobalJobBudget(Y,W){if(Y<=0||!W)return;let $=`${this.budgetKeyPrefix()}:${W}`;await this.evalScript(a,[$],[Y])}async acquireQueueLock(Y,W,$){let G=await this.evalScript(t,[`${this.prefix}:${Y}`],[W,$]);return Boolean(G)}async releaseQueueLock(Y,W){return await this.evalScript(d,[`${this.prefix}:${Y}`],[W])===1}async clearDispatchPending(Y){let W=`${Y}:pending`;await this.redis.del(W)}async evaluateDeadRun(Y,W,$,G,Q=15000,V="lock:idp",z="lock:edp:"){let H=`${this.prefix}:${V}`,Z=`${this.prefix}:${z}`,T=[H,Z],X=[Y,W,$,G,Q],M=await this.evalScript(r,T,X);if(M!=="ALLOWED")console.log(`DEAD_RUN STOP REASON : ${M}`);return M==="ALLOWED"}async evalScript(Y,W,$){if(this.protocol==="http")return await this.redis.eval(Y,W,$);return await this.redis.eval(Y,W.length,...W,...$)}}function e(Y,W){let $=Y.self_url!==W.self_url,G=new Map(Y.queues.map((Z)=>[Z.queue,Z.pooler])),Q=new Map(W.queues.map((Z)=>[Z.queue,Z.pooler])),V=[],z=[],H=[];for(let[Z,T]of Q.entries())if(!G.has(Z))V.push({queue:Z,pooler:T});else{let X=G.get(Z);if(X!==T)H.push({queue:Z,oldPooler:X,newPooler:T})}for(let[Z,T]of G.entries())if(!Q.has(Z))z.push({queue:Z,pooler:T});return{urlChanged:$,addedQueues:V,removedQueues:z,modifiedQueues:H}}class m{log(Y,...W){console.log(Y,...W)}warn(Y,...W){console.warn(Y,...W)}error(Y,...W){console.error(Y,...W)}debug(Y,...W){console.debug(Y,...W)}}class L{static provider=new m;setProvider(Y){L.provider=Y}log(Y,...W){L.provider.log(Y,...W)}warn(Y,...W){L.provider.warn(Y,...W)}error(Y,...W){L.provider.error(Y,...W)}debug(Y,...W){if(L.provider.debug)L.provider.debug(Y,...W)}}var O;((G)=>{G.V8_ISOLATE="v8-isolate";G.SERVERLESS_VM="serverless-vm";G.PERSISTENT="persistent"})(O||={});var R;((G)=>{G.POSTGRES_NOTIFY="POSTGRES_NOTIFY";G.WEBHOOK="WEBHOOK";G.POLLING="POLLING"})(R||={});var fW=new Set(["storage","runtime","onEvents","isolate","queue"]),kW=new Set(["queue","deadLetterQueue"]);class U{static instance;_config;initialSnapshot;logger;constructor(){this.logger=new L}static getInstance(){if(!U.instance)U.instance=new U;return U.instance}initialize(Y){this._config={swarmConfig:{globalMaxJobsPerTick:1e5,maxGlobalConcurrency:1e4,spawnerAlgorithm:"ROUND_ROBIN",...Y.swarmConfig},...Y,engine:{...Y.runtime=="persistent"?{poolingIntervalSec:5}:{},...Y.runtime=="serverless-vm"||"v8-isolate"?{selfInvocationMethod:"auto_using_pgnet",selfInvocationIntervalSec:1,healthCheckIntervalSec:15,selfRestartIntervalSec:60}:{},tickConcurrency:"sequential",cycleTickLimit:1000,...Y.engine},queues:Y.queues.map((W)=>({stateTransitionPolicy:{enabled:!0,idleThresholdTicks:10,idleTimingProfile:"RELAXED"},...W}))},this.throwExpectionOnInvalidConfiguration(this._config),this.initialSnapshot=Object.freeze(JSON.parse(JSON.stringify(this._config)))}throwExpectionOnInvalidConfiguration(Y){let W=Y.queues;if(W.length==0)throw this.logger.error('[Pulsar] Runtime configuration error: "queues" atleast 1 queue is required to operate.'),Error('[Pulsar] Runtime configuration error: "queues" atleast 1 queue is required to operate.');if(Y.runtime==="v8-isolate"&&!Y.isolate)throw this.logger.error(`[Pulsar] Runtime configuration error: "isolate" instance is required when running in "${"v8-isolate"}" mode.`),Error(`[Pulsar] Runtime configuration error: "isolate" instance is required when running in "${"v8-isolate"}" mode.`);let $=W.reduce((V,z)=>{return V[z.queue]=(V[z.queue]||0)+1,V},{}),G=Object.keys($).filter((V)=>$[V]>1);if(G.length>0)throw this.logger.error("[ConfigurationStore]: Duplicate queues found -> ",G),Error("Duplicate queue names detected in the configuration.");let Q=W.map((V)=>V.consumer);if(Y.runtime!=="persistent"){let V=Q.find((z)=>z.type=="socket");if(V)throw this.logger.error(`${JSON.stringify(V)}`),Error("Consumers do not support non-persistent socket types. Please either remove the 'socket' type from the consumer or update the runtime to PERSISTENT.")}for(let V of Q)if(V.type=="http")try{let z=new URL(V.url);if(z.protocol!=="http:"&&z.protocol!=="https:")throw this.logger.error(`${V.queue} - ${V.url}`),Error(`Invalid protocol '${z.protocol}' for consumer URL. Only HTTP and HTTPS are supported.`)}catch(z){this.logger.error(`${V.queue} - ${V.url}`);let H=z instanceof Error?z.message:"An unknown error occurred while parsing the consumer URL.";throw Error(`Failed to validate consumer URL: ${H}`)}else if(V.type=="callback"){if(!V.handler)throw Error("Consumer handler is required. Please provide a valid handler function.")}}ensureInitialized(){if(!this._config)throw Error("[ConfigurationStore]: Engine configuration store is not initialized. Call initialize() first.");if(!this.initialSnapshot)throw Error("[ConfigurationStore]: Engine initial snapshot is not initialized")}get raw(){return this.ensureInitialized(),this._config}get(Y){this.ensureInitialized();let W=Y.split("."),$=this._config;for(let G of W){if($===void 0||$===null)return;$=$[G]}return $}getInitialSnapshot(){return this.ensureInitialized(),Object.freeze({...this.initialSnapshot})}set(Y,W){this.ensureInitialized();let $=Y.split("."),G=$[0];if(fW.has(G))throw Error(`[ConfigurationStore]: Modifying path '${Y}' via set() is forbidden.`);let Q=this._config;for(let V=0;V<$.length-1;V++){let z=$[V];if(!(z in Q)||typeof Q[z]!=="object")Q[z]={};Q=Q[z]}Q[$[$.length-1]]=W}modifyQueue(Y,W,$){if(this.ensureInitialized(),kW.has(W))throw Error(`[ConfigurationStore]: Property '${String(W)}' on queue '${Y}' cannot be modified at runtime.`);let G=this._config.queues.findIndex((Q)=>Q.queue==Y);if(!this._config.queues[G])throw Error(`[ConfigurationStore]: Modifying queue '${Y}' not found.`);this._config.queues[G][W]=$}async reconcileConfiguration(Y){let W=this.getInitialSnapshot(),$=W.runtime==="serverless-vm"||W.runtime==="v8-isolate"?W.engine.selfURL:"NOT_REQUIRED",G={queues:W.queues.map((V)=>({queue:V.queue,pooler:V.pooler})),runtime:W.runtime,event_trigger_strategy:W.runtime=="persistent"?W.eventTriggerStrategy:"WEBHOOK",self_url:$},Q=await Y.verifyAndSyncConfiguration("PULSAR_STANDALONE",W.instanceId,$,G);if(!Q.isChanged&&!Q.isNew)return this.logger.log("[Configuration] status : [VALID]."),"[Configuration] status : [VALID].";else return this.logger.log("[Configuration] status : [INVALID & Reconciled]."),"[Configuration] status : [INVALID & Reconciled]."}}var v=U.getInstance();class f{driver;logger;constructor(Y){this.driver=Y;this.logger=new L}get sql(){return this.driver.getNativeClient()}async addRestart(Y){if(Y.length==0)return;if(Y.some((G)=>G.pooler=="interval-driven-pooler"))await this.sql`
322
+ WITH clear_all AS (
323
+ DELETE FROM pulsar.pulsar_restart
324
+ )
325
+ INSERT INTO pulsar.pulsar_restart (queue_name, type, created_at)
326
+ VALUES ('__GLOBAL__', 'interval-driven-pooler', NOW())
327
+ ON CONFLICT (queue_name)
328
+ DO UPDATE SET type = EXCLUDED.type, created_at = NOW();
329
+ `,this.logger.log("[Storage] : Restart added for [interval-driven-pooler].");let $=Y.filter((G)=>G.pooler=="event-driven-pooler");for(let{queue:G}of $)await this.sql`
330
+ INSERT INTO pulsar.pulsar_restart (queue_name, type, created_at, owner)
331
+ VALUES (${G}, 'event-driven-pooler', NOW(), 'engine')
332
+ ON CONFLICT (queue_name)
333
+ DO UPDATE SET type = EXCLUDED.type, created_at = NOW();
334
+ `,this.logger.log(`[Storage] : Restart added for queue (${G}) for [event-driven-pooler]`)}async updateRestartOwnership(Y=null,W){let $=!Y?"__GLOBAL__":Y;await this.sql`
335
+ UPDATE pulsar.pulsar_restart
336
+ SET owner = ${W}
337
+ WHERE queue_name = ${$}
338
+ `,this.logger.log(`[Storage] : Ownership updated for restart [${Y}]`)}async deleteRestart(Y){await this.sql`
339
+ DELETE FROM pulsar.pulsar_restart
340
+ WHERE queue_name = ${Y} OR queue_name = '__GLOBAL__'
341
+ `}async pingHealthCheck(){await this.sql`
342
+ INSERT INTO pulsar.health_check (id, last_health_checked_at)
343
+ OVERRIDING SYSTEM VALUE
344
+ VALUES (1, NOW())
345
+ ON CONFLICT (id)
346
+ DO UPDATE SET last_health_checked_at = EXCLUDED.last_health_checked_at;
347
+ `}async checkFencingTokenValidity(Y,W){let $=typeof W==="string"?parseInt(W,10):W;if(isNaN($))return!1;return(await this.sql`
348
+ UPDATE pulsar.queue_locks
349
+ SET last_valid_token = ${$}
350
+ WHERE queue_name = ${Y}
351
+ AND fencing_token = ${$}
352
+ AND last_valid_token <= ${$}
353
+ RETURNING true AS is_valid;
354
+ `)[0]?.is_valid??!1}async verifyAndSyncConfiguration(Y,W,$,G){let Q=this.sql.json(G);return await this.sql.begin(async(V)=>{let H=(await this.sql`
355
+ WITH existing AS (
356
+ SELECT configurations, hash FROM pulsar.meta WHERE instance_id = ${W}
357
+ ),
358
+ updated AS (
359
+ INSERT INTO pulsar.meta (host, version, url, configurations, is_active, instance_id)
360
+ VALUES (${Y}, '1.0.0', ${$}, ${Q}::jsonb, true, ${W})
361
+ ON CONFLICT (instance_id)
362
+ DO UPDATE SET
363
+ host = EXCLUDED.host,
364
+ url = EXCLUDED.url,
365
+ configurations = EXCLUDED.configurations,
366
+ updated_at = CURRENT_TIMESTAMP
367
+ WHERE pulsar.meta.hash <> pulsar.generate_sha256(${Q}::text)
368
+ RETURNING *
369
+ )
370
+ SELECT
371
+ (SELECT configurations FROM existing) AS old_configurations,
372
+ EXISTS (SELECT 1 FROM updated) AS is_changed,
373
+ EXISTS (SELECT 1 FROM existing) AS was_existing;
374
+ `)[0],Z=!H.was_existing,T=H.is_changed,X=H.old_configurations,M=void 0;if(T&&!Z&&X)M=e(X,G);if(T||Z)await this.synchronizeQueueTriggers(V,X,G,W);return{isChanged:T,isNew:Z,oldConfigurations:X,delta:M}})}async synchronizeQueueTriggers(Y,W,$,G){let V=new Map((W?.queues||[]).filter((H)=>H.pooler==="event-driven-pooler").map((H)=>[H.queue,H.pooler])),z=new Map($.queues.filter((H)=>H.pooler==="event-driven-pooler").map((H)=>[H.queue,H.pooler]));if($.runtime==="persistent"){let H=v.get("eventTriggerStrategy");if(H==="POSTGRES_NOTIFY"||H==="WEBHOOK"){let Z=$.queues.filter((T)=>T.pooler==="event-driven-pooler");for(let{queue:T}of Z){let X=`pulsar_edp_trigger_${T}_on_pgmq`,M=`pgmq.q_${T}`;this.logger.log(`[Configuration] : Dropping trigger ${X} on ${M} due to runtime config changes`),await Y.unsafe(`DROP TRIGGER IF EXISTS ${X} ON ${M};`)}}}for(let[H]of V.entries())if(!z.has(H)){let Z=`pulsar_edp_trigger_${H}_on_pgmq`,T=`pgmq.q_${H}`;await Y.unsafe(`DROP TRIGGER IF EXISTS ${Z} ON ${T};`)}for(let[H]of z.entries()){let Z=`pulsar_edp_trigger_${H}_on_pgmq`,T=`pgmq.q_${H}`;await Y.unsafe(`DROP TRIGGER IF EXISTS ${Z} ON ${T};`);let X=v.get("eventTriggerStrategy"),M=$.runtime==="serverless-vm"||$.runtime==="v8-isolate",J=$.runtime==="persistent"&&(X==="POSTGRES_NOTIFY"||X==="WEBHOOK"),w=M||J;await Y.unsafe(`
375
+ CREATE TRIGGER ${Z}
376
+ AFTER INSERT ON ${T}
377
+ REFERENCING NEW TABLE AS new_table
378
+ FOR EACH STATEMENT
379
+ EXECUTE FUNCTION pulsar.handle_edp_queue_dispatch('${H}', '${G}');
380
+ `)}}async subscribeToDatabaseEvents(Y,W,$){await this.sql.listen(Y,async(G)=>{try{let Q=JSON.parse(G);await W(Q)}catch(Q){this.logger.error("[TcpListenTransport] : Failed to parse payload:",Q)}},$)}async getPollingQueueEntries(Y,W=10){return(await this.sql`
381
+ SELECT *
382
+ FROM pulsar.pool_queue_entries
383
+ WHERE queue = ${Y}
384
+ ORDER BY created_at ASC
385
+ LIMIT ${W}
386
+ FOR UPDATE SKIP LOCKED;
387
+ `).map((G)=>G)}async deletePollingQueueEntry(Y){await this.sql`
388
+ DELETE FROM pulsar.pool_queue_entries
389
+ WHERE id = ${Y}
390
+ `}}class s{repository;cache;db;ops;logger;strategy;syncIntervalMs;isConnected=!1;constructor(Y){if(this.logger=new L,!Y.db)throw Error("[PulsarUnifiedStorage] PostgresDriver is required for core engine to operate.");this.cache=Y.cache,this.db=Y.db,this.syncIntervalMs=Y.syncIntervalMs??500,this.ops=new f(this.db);let W=Y.strategy??"AUTO";if(W==="AUTO")W=this.cache?"REDIS_CACHE":"PG_UNLOGGED";switch(this.strategy=W,this.strategy){case"REDIS_CACHE":if(!this.cache)throw Error("[PulsarUnifiedStorage] Strategy 'REDIS_CACHE' requires a valid Redis cache driver.");this.repository=new q(this.cache);break;case"PG_UNLOGGED":this.repository=new x(this.db);break;default:throw Error(`[PulsarUnifiedStorage] Unsupported storage strategy: '${this.strategy}'`)}}bindInstanceId(Y){if(this.cache)this.cache.setKeyPrefix(Y);if(this.db)this.db.setKeyPrefix(Y)}async connect(){if(this.isConnected)return;let Y=[];if(this.cache)Y.push(this.cache.connect());if(this.db)Y.push(this.db.connect());await Promise.all(Y),this.logger.log(`[PulsarStorage] Storage layer active [Strategy: ${this.strategy}]`),this.isConnected=!0}async disconnect(){this.isConnected=!1;let Y=[];if(this.cache)Y.push(this.cache.disconnect());if(this.db)Y.push(this.db.disconnect());await Promise.all(Y)}async healthCheck(){let Y={};if(this.db)Y.db=await this.db.healthCheck();return Y}}import lW from"postgres";class Y1{options;type="database";name="PostgresDriver";sql;isConnected=!1;prefix;logger;constructor(Y){this.options=Y;this.logger=new L}initClient(){if(this.isConnected)return;this.sql=lW(this.options.connectionString),this.isConnected=!0}setKeyPrefix(Y){this.prefix=Y}async connect(){if(!this.isConnected){this.initClient();try{await this.sql`SELECT 1`,this.logger.log(`[PostgresDriver] : Pool connected with : ${this.options.connectionProtocol??"TCP"}`)}catch(Y){throw this.logger.log("[PostgresDriver] : Health check failed:",Y),Y}}}async disconnect(){if(this.isConnected)await this.sql.end(),this.isConnected=!1,this.logger.log("[PostgresDriver] : Pool disconnected.")}async healthCheck(){let Y=Date.now();try{if(!this.isConnected)throw Error("Connection pool is closed.");return await this.sql`SELECT 1`,{status:"up",latencyMs:Date.now()-Y}}catch(W){return{status:"down",latencyMs:Date.now()-Y,details:{error:W.message}}}}getNativeClient(){if(!this.sql)throw Error("[PostgresDriver] : Client is not initialized. Call connect() first.");return this.sql}async close(){await this.disconnect()}}import{Redis as C$}from"ioredis";import yW from"node:crypto";var _=yW.webcrypto?.subtle||{};var CW=Object.defineProperty,uW=(Y,W)=>{for(var $ in W)CW(Y,$,{get:W[$],enumerable:!0})},z1={};uW(z1,{UpstashError:()=>h,UpstashJSONParseError:()=>l,UrlError:()=>H1});var h=class extends Error{constructor(Y,W){super(Y,W);this.name="UpstashError"}},H1=class extends Error{constructor(Y){super(`Upstash Redis client was passed an invalid URL. You should pass a URL starting with https. Received: "${Y}". `);this.name="UrlError"}},l=class extends h{constructor(Y,W){let $=Y.length>200?Y.slice(0,200)+"...":Y;super(`Unable to parse response body: ${$}`,W);this.name="UpstashJSONParseError"}};function Z1(Y){let W=Array.isArray(Y)?Y.map(($)=>{try{return Z1($)}catch{return $}}):JSON.parse(Y);if(typeof W==="number"&&W.toString()!==Y)return Y;return W}function P(Y){try{return Z1(Y)}catch{return Y}}function I(Y){return[Y[0],...P(Y.slice(1))]}function iW(Y){let[W,$]=Y,G=[];for(let Q=0;Q<$.length;Q+=2)G.push({key:$[Q],type:$[Q+1]});return[W,G]}function gW(...Y){let W={};for(let $ of Y){if(!$)continue;for(let[G,Q]of Object.entries($))if(Q!==void 0&&Q!==null)W[G]=Q}return W}function F(Y){if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))return Y;if(!Array.isArray(Y))return{};let W={};for(let $=0;$<Y.length;$+=2)if(typeof Y[$]==="string")W[Y[$]]=Y[$+1];return W}var cW=1048576,T1=class{baseUrl;headers;options;readYourWrites;upstashSyncToken="";hasCredentials;retry;constructor(Y){this.options={backend:Y.options?.backend,agent:Y.agent,responseEncoding:Y.responseEncoding??"base64",cache:Y.cache,signal:Y.signal,keepAlive:Y.keepAlive??!0},this.upstashSyncToken="",this.readYourWrites=Y.readYourWrites??!0,this.baseUrl=(Y.baseUrl||"").replace(/\/$/,"");let W=/^https?:\/\/[^\s#$./?].\S*$/;if(this.baseUrl&&!W.test(this.baseUrl))throw new H1(this.baseUrl);if(this.headers={"Content-Type":"application/json",...Y.headers},this.hasCredentials=Boolean(this.baseUrl&&this.headers.authorization.split(" ")[1]),this.options.responseEncoding==="base64")this.headers["Upstash-Encoding"]="base64";this.retry=typeof Y.retry==="boolean"&&!Y.retry?{attempts:1,backoff:()=>0}:{attempts:Y.retry?.retries??5,backoff:Y.retry?.backoff??(($)=>Math.exp($)*50)}}mergeTelemetry(Y){this.headers=k(this.headers,"Upstash-Telemetry-Runtime",Y.runtime),this.headers=k(this.headers,"Upstash-Telemetry-Platform",Y.platform),this.headers=k(this.headers,"Upstash-Telemetry-Sdk",Y.sdk)}async request(Y){if(this.readYourWrites)this.headers["upstash-sync-token"]=this.upstashSyncToken;let W=gW(this.headers,Y.headers??{}),$=[this.baseUrl,...Y.path??[]].join("/"),G=W.Accept==="text/event-stream",Q=Y.signal??this.options.signal,V=typeof Q==="function",z={cache:this.options.cache,method:"POST",headers:W,body:JSON.stringify(Y.body),keepalive:this.options.keepAlive,agent:this.options.agent,signal:V?Q():Q,backend:this.options.backend};if(!this.hasCredentials)console.warn("[Upstash Redis] Redis client was initialized without url or token. Failed to execute command.");let H=null,Z=null;for(let M=0;M<=this.retry.attempts;M++){if(M>0&&W["Upstash-Telemetry-Sdk"])W["Upstash-Telemetry-Retry"]=String(M);try{H=await fetch($,z);break}catch(J){if(z.signal?.aborted&&V)throw J;else if(z.signal?.aborted){let w=new Blob([JSON.stringify({result:z.signal.reason??"Aborted"})]),N={status:200,statusText:z.signal.reason??"Aborted"};H=new Response(w,N);break}if(Z=J,M<this.retry.attempts)await new Promise((w)=>setTimeout(w,this.retry.backoff(M)))}}if(!H)throw Z??Error("Exhausted all retries");if(!H.ok){let M,J=await H.text();try{M=JSON.parse(J)}catch(w){throw new l(J,{cause:w})}throw new h(`${M.error}, command was: ${JSON.stringify(Y.body)}`)}if(this.readYourWrites){let M=H.headers;this.upstashSyncToken=M.get("upstash-sync-token")??""}if(G&&Y&&Y.onMessage&&H.body){let M=H.body.getReader(),J=new TextDecoder;return(async()=>{try{let w="";while(!0){let{value:N,done:g}=await M.read();if(g)break;w+=J.decode(N,{stream:!0});let c=w.split(`
391
+ `);if(w=c.pop()||"",w.length>cW)throw Error("Buffer size exceeded (1MB)");for(let p of c)if(p.startsWith("data: ")){let hW=p.slice(6);Y.onMessage?.(hW)}}}catch(w){if(w instanceof Error&&w.name==="AbortError");else console.error("Stream reading error:",w)}finally{try{await M.cancel()}catch{}}})(),{result:1}}let T,X=await H.text();try{T=JSON.parse(X)}catch(M){throw new l(X,{cause:M})}if(this.readYourWrites){let M=H.headers;this.upstashSyncToken=M.get("upstash-sync-token")??""}if(this.options.responseEncoding==="base64"){if(Array.isArray(T))return T.map(({result:J,error:w})=>({result:y(J),error:w}));return{result:y(T.result),error:T.error}}return T}};function W1(Y){let W="";try{let $=atob(Y),G=$.length,Q=new Uint8Array(G);for(let V=0;V<G;V++)Q[V]=$.charCodeAt(V);W=new TextDecoder().decode(Q)}catch{W=Y}return W}function y(Y){let W=void 0;switch(typeof Y){case"undefined":return Y;case"number":{W=Y;break}case"object":{if(Array.isArray(Y))W=Y.map(($)=>typeof $==="string"?W1($):Array.isArray($)?$.map((G)=>y(G)):$);else W=null;break}case"string":{W=Y==="OK"?"OK":W1(Y);break}default:break}return W}function k(Y,W,$){if(!$)return Y;if(!Y[W])return Y[W]=$,Y;if(!Y[W].split(",").map((Q)=>Q.trim()).includes($.trim()))Y[W]=[Y[W],$].join(",");return Y}var pW=(Y)=>{switch(typeof Y){case"string":case"number":case"boolean":return Y;default:return JSON.stringify(Y)}},D=class{command;serialize;deserialize;headers;path;onMessage;isStreaming;signal;constructor(Y,W){if(this.serialize=pW,this.deserialize=W?.automaticDeserialization===void 0||W.automaticDeserialization?W?.deserialize??P:($)=>$,this.command=Y.map(($)=>this.serialize($)),this.headers=W?.headers,this.path=W?.path,this.onMessage=W?.streamOptions?.onMessage,this.isStreaming=W?.streamOptions?.isStreaming??!1,this.signal=W?.streamOptions?.signal,W?.latencyLogging){let $=this.exec.bind(this);this.exec=async(G)=>{let Q=performance.now(),V=await $(G),H=(performance.now()-Q).toFixed(2);return console.log(`Latency for \x1B[38;2;19;185;39m${this.command[0].toString().toUpperCase()}\x1B[0m: \x1B[38;2;0;255;255m${H} ms\x1B[0m`),V}}}async exec(Y){let{result:W,error:$}=await Y.request({body:this.command,path:this.path,upstashSyncToken:Y.upstashSyncToken,headers:this.headers,onMessage:this.onMessage,isStreaming:this.isStreaming,signal:this.signal});if($)throw new h($);if(W===void 0)throw TypeError("Request did not return a result");return this.deserialize(W)}},K=class extends D{constructor(Y,W){let $=Y.map((G)=>typeof G==="string"?G:String(G));super($,W)}},nW=["TEXT","U64","I64","F64","BOOL","DATE","KEYWORD","FACET"];function X1(Y){return typeof Y==="string"&&nW.includes(Y)}function M1(Y){return typeof Y==="object"&&Y!==null&&"type"in Y&&X1(Y.type)}function tW(Y){return typeof Y==="object"&&Y!==null&&!M1(Y)}function w1(Y,W=[]){let $=[];for(let[G,Q]of Object.entries(Y)){let V=[...W,G],z=V.join(".");if(X1(Q))$.push({path:z,type:Q});else if(M1(Q))$.push({path:z,type:Q.type,fast:"fast"in Q?Q.fast:void 0,noTokenize:"noTokenize"in Q?Q.noTokenize:void 0,noStem:"noStem"in Q?Q.noStem:void 0,from:"from"in Q?Q.from:void 0});else if(tW(Q)){let H=w1(Q,V);$.push(...H)}}return $}function dW(Y){return Y.map((W)=>{let $=W,G=$[0],Q=Number($[1]),V=$[2];if(V===void 0)return{key:G,score:Q};if(!Array.isArray(V)||V.length===0)return{key:G,score:Q,data:{}};let z={};for(let H of V){let Z=H[0],T=H[1],X=Z.split(".");if(X.length===1)z[Z]=T;else{let M=z;for(let J=0;J<X.length-1;J++){let w=X[J];if(!(w in M))M[w]={};M=M[w]}M[X.at(-1)]=T}}if("$"in z)z=z.$;return{key:G,score:Q,data:z}})}function rW(Y){let W={};for(let $=0;$<Y.length;$+=2)switch(Y[$]){case"name":{W.name=Y[$+1];break}case"type":{W.dataType=Y[$+1].toLowerCase();break}case"prefixes":{W.prefixes=Y[$+1];break}case"language":{W.language=Y[$+1];break}case"schema":{let Q={};for(let V of Y[$+1]){let z=V[0],H={type:V[1]};if(V.length>2)for(let Z=2;Z<V.length;Z++)switch(V[Z]){case"NOSTEM":{H.noStem=!0;break}case"NOTOKENIZE":{H.noTokenize=!0;break}case"FAST":{H.fast=!0;break}case"FROM":{H.from=V[++Z];break}}Q[z]=H}W.schema=Q;break}}return W}function oW(Y){return typeof Y==="number"?Y:Number.parseInt(Y,10)}function aW(Y){return J1(Y)}function J1(Y){let W={};for(let $=0;$<Y.length;$+=2){let G=Y[$],Q=Y[$+1];if(Array.isArray(Q))if(Q.length>0&&typeof Q[0]==="string")W[G]=Q[0]==="buckets"?mW(Q):j(Q);else W[G]=J1(Q);else W[G]=Q}return W}function eW(Y){if(typeof Y==="string"&&Y!==""&&!Number.isNaN(Number(Y)))return Number(Y);return Y}function j(Y){let W={};for(let $=0;$<Y.length;$+=2){let G=Y[$],Q=Y[$+1];if(Array.isArray(Q)&&Q.length>0)if(typeof Q[0]==="string")W[G]=j(Q);else if(Array.isArray(Q[0])&&typeof Q[0][0]==="string")W[G]=Q.map((V)=>j(V));else W[G]=Q;else W[G]=eW(Q)}return W}function mW(Y){if(Y[0]==="buckets"&&Array.isArray(Y[1])){let W={buckets:Y[1].map(($)=>{let G={};for(let Q=0;Q<$.length;Q+=2){let V=$[Q],z=$[Q+1];G[V]=Array.isArray(z)&&z.length>0&&typeof z[0]==="string"?j(z):z}return G})};for(let $=2;$<Y.length;$+=2)W[Y[$]]=Y[$+1];return W}return Y}function $1(Y,W,$){let G=JSON.stringify($?.filter??{}),Q=[Y,W,G];if($?.limit!==void 0)Q.push("LIMIT",$.limit.toString());if($?.offset!==void 0)Q.push("OFFSET",$.offset.toString());if($?.select&&Object.keys($.select).length===0)Q.push("NOCONTENT");if($){if("orderBy"in $&&$.orderBy){Q.push("ORDERBY");for(let[V,z]of Object.entries($.orderBy))Q.push(V,z)}else if("scoreFunc"in $&&$.scoreFunc)Q.push("SCOREFUNC",...sW($.scoreFunc))}if($?.highlight){if(Q.push("HIGHLIGHT","FIELDS",$.highlight.fields.length.toString(),...$.highlight.fields),$.highlight.preTag&&$.highlight.postTag)Q.push("TAGS",$.highlight.preTag,$.highlight.postTag)}if($?.select&&Object.keys($.select).length>0)Q.push("SELECT",Object.keys($.select).length.toString(),...Object.keys($.select));return Q}function sW(Y){let W=[];if(typeof Y==="string")W.push("FIELDVALUE",Y);else if("fields"in Y){if(Y.combineMode)W.push("COMBINEMODE",Y.combineMode.toUpperCase());if(Y.scoreMode)W.push("SCOREMODE",Y.scoreMode.toUpperCase());for(let $ of Y.fields)W.push(...G1($))}else W.push(...G1(Y));return W}function G1(Y){let W=[];if(typeof Y==="string")W.push("FIELDVALUE",Y);else{if(Y.scoreMode)W.push("SCOREMODE",Y.scoreMode.toUpperCase());if(W.push("FIELDVALUE",Y.field),Y.modifier)W.push("MODIFIER",Y.modifier.toUpperCase());if(Y.factor!==void 0)W.push("FACTOR",Y.factor.toString());if(Y.missing!==void 0)W.push("MISSING",Y.missing.toString())}return W}function Y$(Y){let{name:W,schema:$,dataType:G,language:Q,skipInitialScan:V,existsOk:z}=Y,H;if(Y.dataType==="stream")H=["ON","STREAM",Y.stream];else{let X=Array.isArray(Y.prefix)?Y.prefix:[Y.prefix];H=["ON",G.toUpperCase(),"PREFIX",X.length.toString(),...X]}let Z=[W,...V?["SKIPINITIALSCAN"]:[],...z?["EXISTSOK"]:[],...H,...Q?["LANGUAGE",Q]:[],"SCHEMA"],T=w1($);for(let X of T){if(Z.push(X.path,X.type),X.fast)Z.push("FAST");if(X.noTokenize)Z.push("NOTOKENIZE");if(X.noStem)Z.push("NOSTEM");if(X.from)Z.push("FROM",X.from)}return["SEARCH.CREATE",...Z]}function W$(Y,W){let $=JSON.stringify(W?.filter??{}),G=JSON.stringify(W.aggregations);return["SEARCH.AGGREGATE",Y,$,G]}var L1=class{name;schema;client;constructor({name:Y,schema:W,client:$}){this.name=Y,this.schema=W,this.client=$}async waitIndexing(){let Y=["SEARCH.WAITINDEXING",this.name];return await new K(Y).exec(this.client)}async describe(){let Y=["SEARCH.DESCRIBE",this.name],W=await new K(Y).exec(this.client);if(!W)return null;return rW(W)}async query(Y){let W=$1("SEARCH.QUERY",this.name,Y),$=await new K(W).exec(this.client);if(!$)return $;return dW($)}async aggregate(Y){let W=W$(this.name,Y),$=await new K(W).exec(this.client);return aW($)}async count({filter:Y}){let W=$1("SEARCH.COUNT",this.name,{filter:Y}),$=await new K(W).exec(this.client);return{count:oW($)}}async drop(){let Y=["SEARCH.DROP",this.name];return await new K(Y).exec(this.client)}async addAlias({alias:Y}){let W=["SEARCH.ALIASADD",Y,this.name];return await new K(W).exec(this.client)}};async function $$(Y,W){let{name:$,schema:G}=W,Q=Y$(W);return await new K(Q).exec(Y),K1(Y,{name:$,schema:G})}function K1(Y,W){let{name:$,schema:G}=W;return new L1({name:$,schema:G,client:Y})}async function G$(Y){let $=await new K(["SEARCH.LISTALIASES"]).exec(Y);if($===0||Array.isArray($)&&$.length===0)return{};if(!Array.isArray($))return{};let G={};for(let Q of $)if(Array.isArray(Q)&&Q.length===2){let[V,z]=Q;G[V]=z}return G}async function Q$(Y,{indexName:W,alias:$}){return await new K(["SEARCH.ALIASADD",$,W]).exec(Y)}async function V$(Y,{alias:W}){return await new K(["SEARCH.ALIASDEL",W]).exec(Y)}function D$(Y){let W=new Uint8Array(Y.length*4),$=new DataView(W.buffer);for(let[V,z]of Y.entries())$.setFloat32(V*4,z,!0);let G="",Q=32768;for(let V=0;V<W.length;V+=Q)G+=String.fromCodePoint(...W.subarray(V,V+Q));return btoa(G)}function N1(Y){if(Array.isArray(Y))return["VALUES",Y.length,...Y];if(Y instanceof Float32Array)return["BASE64-FP32",D$(Y)];return["BASE64-FP32",Y.base64]}function z$(Y){if(Y===null)return null;return Y.map(Number)}function H$(Y){return Y.map(([W,$])=>({id:String(W),score:Number($)}))}function Z$(Y){if(Y===null)return null;let W=Array.isArray(Y)?Object.fromEntries(Array.from({length:Math.floor(Y.length/2)},($,G)=>[String(Y[G*2]),Y[G*2+1]])):Y;return{dimension:Number(W.dimension),metric:String(W.metric).toUpperCase()}}var T$=class extends D{constructor([Y,W,$],G){super(["VECTOR.ADD",Y,W,...N1($)],G)}},X$=class extends D{constructor([Y],W){super(["VECTOR.COUNT",Y],W)}},M$=class extends D{constructor([Y,W],$){let G=["VECTOR.CREATE",Y,"DIM",W.dimension,"METRIC",W.metric];if(W.existsOk)G.push("EXISTSOK");super(G,$)}},w$=class extends D{constructor([Y,W],$){super(["VECTOR.DEL",Y,W],$)}},J$=class extends D{constructor([Y],W){super(["VECTOR.DROP",Y],W)}},L$=class extends D{constructor([Y,W],$){super(["VECTOR.GET",Y,W],{deserialize:z$,...$})}},K$=class extends D{constructor([Y],W){super(["VECTOR.INFO",Y],{deserialize:Z$,...W})}},N$=class extends D{constructor([Y,W],$){let G=["VECTOR.QUERY",Y,"TOPK",W.topK];if(W.profile)G.push("PROFILE",W.profile);G.push(...N1(W.vector));super(G,{deserialize:H$,...$})}},u=class{name;client;commandOptions;constructor({name:Y,client:W,commandOptions:$}){this.name=Y,this.client=W,this.commandOptions=$}add(Y,W){return new T$([this.name,Y,W],this.commandOptions).exec(this.client)}get(Y){return new L$([this.name,Y],this.commandOptions).exec(this.client)}query(Y){return new N$([this.name,Y],this.commandOptions).exec(this.client)}delete(Y){return new w$([this.name,Y],this.commandOptions).exec(this.client)}count(){return new X$([this.name],this.commandOptions).exec(this.client)}info(){return new K$([this.name],this.commandOptions).exec(this.client)}drop(){return new J$([this.name],this.commandOptions).exec(this.client)}};async function U$(Y,{name:W,...$},G){return await new M$([W,$],G).exec(Y),new u({name:W,client:Y,commandOptions:G})}function h$(Y,W,$){return new u({name:W,client:Y,commandOptions:$})}function E$(Y){if(Y.length===0)return null;let W={};for(let $=0;$<Y.length;$+=2){let G=Y[$],Q=Y[$+1];try{W[G]=JSON.parse(Q)}catch{W[G]=Q}}return W}var U1=class extends D{constructor(Y,W){let $=["hrandfield",Y[0]];if(typeof Y[1]==="number")$.push(Y[1]);if(Y[2])$.push("WITHVALUES");super($,{deserialize:Y[2]?(G)=>E$(G):W?.deserialize,...W})}},h1=class extends D{constructor(Y,W){super(["append",...Y],W)}},E1=class extends D{constructor(Y,W){super(["ARCOUNT",...Y],W)}},F1=class extends D{constructor(Y,W){super(["ARDEL",...Y],W)}},A1=class extends D{constructor([Y,...W],$){super(["ARDELRANGE",Y,...W.flat()],$)}},_1=class extends D{constructor(Y,W){super(["ARGET",...Y],W)}},j1=class extends D{constructor(Y,W){super(["ARGETRANGE",...Y],W)}},B1=class extends D{constructor([Y,W,$,G],Q){let V=["ARGREP",Y,W,$];for(let z of G.predicates)if("exact"in z)V.push("EXACT",z.exact);else if("match"in z)V.push("MATCH",z.match);else if("glob"in z)V.push("GLOB",z.glob);else V.push("RE",z.re);if(G.combine)V.push(G.combine.toUpperCase());if(G.noCase)V.push("NOCASE");if(G.withValues)V.push("WITHVALUES");if(G.limit!==void 0)V.push("LIMIT",G.limit);super(V,{deserialize:(z)=>P(z).map((H)=>Array.isArray(H)?[String(H[0]),H[1]]:String(H)),...Q})}};function F$(Y){return Y.replaceAll(/-([a-z])/g,(W,$)=>$.toUpperCase())}function A$(Y){let W=Array.isArray(Y)?Array.from({length:Math.floor(Y.length/2)},(Q,V)=>[Y[V*2],Y[V*2+1]]):Object.entries(Y),$=new Set(["len","nextInsertIndex"]),G={};for(let[Q,V]of W){let z=F$(String(Q));if($.has(z)){G[z]=String(V);continue}let H=typeof V==="number"?V:Number(V);G[z]=Number.isNaN(H)?V:H}return G}var P1=class extends D{constructor([Y,W],$){let G=["ARINFO",Y];if(W?.full)G.push("FULL");super(G,{deserialize:A$,...$})}},I1=class extends D{constructor(Y,W){super(["ARINSERT",...Y],{deserialize:String,...W})}},x1=class extends D{constructor([Y,W,$],G){let Q=["ARLASTITEMS",Y,W];if($?.rev)Q.push("REV");super(Q,G)}},S1=class extends D{constructor(Y,W){super(["ARLEN",...Y],{deserialize:String,...W})}},b1=class extends D{constructor(Y,W){super(["ARMGET",...Y],W)}},q1=class extends D{constructor([Y,W],$){let G=Array.isArray(W)?W:Object.entries(W);super(["ARMSET",Y,...G.flatMap(([Q,V])=>[Q,V])],$)}},O1=class extends D{constructor(Y,W){super(["ARNEXT",...Y],{deserialize:($)=>$===null?null:String($),...W})}},R1=class extends D{constructor([Y,W,$,G],Q){let V=["AROP",Y,W,$];if(typeof G==="string")V.push(G.toUpperCase());else V.push("MATCH",G.match);super(V,{deserialize:(z)=>z===null?null:Number(z),...Q})}},v1=class extends D{constructor(Y,W){super(["ARRING",...Y],{deserialize:String,...W})}},f1=class extends D{constructor([Y,W,$,G],Q){let V=["ARSCAN",Y,W,$];if(G?.limit!==void 0)V.push("LIMIT",G.limit);super(V,{deserialize:(z)=>P(z).map(([H,Z])=>[String(H),Z]),...Q})}},k1=class extends D{constructor(Y,W){super(["ARSEEK",...Y],W)}},l1=class extends D{constructor(Y,W){super(["ARSET",...Y],W)}},y1=class extends D{constructor([Y,W,$],G){let Q=["bitcount",Y];if(typeof W==="number")Q.push(W);if(typeof $==="number")Q.push($);super(Q,G)}},C1=class{constructor(Y,W,$,G=(Q)=>Q.exec(this.client)){this.client=W,this.opts=$,this.execOperation=G,this.command=["bitfield",...Y]}command;chain(...Y){return this.command.push(...Y),this}get(...Y){return this.chain("get",...Y)}set(...Y){return this.chain("set",...Y)}incrby(...Y){return this.chain("incrby",...Y)}overflow(Y){return this.chain("overflow",Y)}exec(){let Y=new D(this.command,this.opts);return this.execOperation(Y)}},u1=class extends D{constructor(Y,W){super(["bitop",...Y],W)}},i1=class extends D{constructor(Y,W){super(["bitpos",...Y],W)}},g1=class extends D{constructor([Y,W],$){super(["CLIENT","SETINFO",Y.toUpperCase(),W],$)}},c1=class extends D{constructor([Y,W,$],G){super(["COPY",Y,W,...$?.replace?["REPLACE"]:[]],{...G,deserialize(Q){if(Q>0)return"COPIED";return"NOT_COPIED"}})}},p1=class extends D{constructor(Y){super(["dbsize"],Y)}},n1=class extends D{constructor(Y,W){super(["decr",...Y],W)}},t1=class extends D{constructor(Y,W){super(["decrby",...Y],W)}},d1=class extends D{constructor(Y,W){super(["del",...Y],W)}},r1=class extends D{constructor(Y,W){super(["echo",...Y],W)}},o1=class extends D{constructor([Y,W,$],G){super(["eval_ro",Y,W.length,...W,...$??[]],G)}},a1=class extends D{constructor([Y,W,$],G){super(["eval",Y,W.length,...W,...$??[]],G)}},e1=class extends D{constructor([Y,W,$],G){super(["evalsha_ro",Y,W.length,...W,...$??[]],G)}},m1=class extends D{constructor([Y,W,$],G){super(["evalsha",Y,W.length,...W,...$??[]],G)}},s1=class extends D{constructor(Y,W){super(["exists",...Y],W)}},Y0=class extends D{constructor(Y,W){super(["expire",...Y.filter(Boolean)],W)}},W0=class extends D{constructor(Y,W){super(["expireat",...Y],W)}},$0=class extends D{constructor([Y,W,$],G){super(["fcall",Y,...W?[W.length,...W]:[0],...$??[]],G)}},G0=class extends D{constructor([Y,W,$],G){super(["fcall_ro",Y,...W?[W.length,...W]:[0],...$??[]],G)}},Q0=class extends D{constructor(Y,W){let $=["flushall"];if(Y&&Y.length>0&&Y[0].async)$.push("async");super($,W)}},V0=class extends D{constructor([Y],W){let $=["flushdb"];if(Y?.async)$.push("async");super($,W)}},D0=class extends D{constructor([Y],W){super(["function","delete",Y],W)}},z0=class extends D{constructor(Y){super(["function","flush"],Y)}},H0=class extends D{constructor([Y],W){let $=["function","list"];if(Y?.libraryName)$.push("libraryname",Y.libraryName);if(Y?.withCode)$.push("withcode");super($,{deserialize:_$,...W})}};function _$(Y){if(!Array.isArray(Y))return[];return Y.map((W)=>{let $=F(W),G=$.functions.map((Q)=>F(Q));return{libraryName:$.library_name,engine:$.engine,functions:G.map((Q)=>({name:Q.name,description:Q.description??void 0,flags:Q.flags})),libraryCode:$.library_code}})}var Z0=class extends D{constructor([Y],W){super(["function","load",...Y.replace?["replace"]:[],Y.code],W)}},T0=class extends D{constructor(Y){super(["function","stats"],{deserialize:j$,...Y})}};function j$(Y){let W=F(F(Y).engines),$=Object.fromEntries(Object.entries(W).map(([Q,V])=>[Q,F(V)]));return{engines:Object.fromEntries(Object.entries($).map(([Q,V])=>[Q,{librariesCount:V.libraries_count,functionsCount:V.functions_count}]))}}var X0=class extends D{constructor([Y,W,...$],G){let Q=["geoadd",Y];if("nx"in W&&W.nx)Q.push("nx");else if("xx"in W&&W.xx)Q.push("xx");if("ch"in W&&W.ch)Q.push("ch");if("latitude"in W&&W.latitude)Q.push(W.longitude,W.latitude,W.member);Q.push(...$.flatMap(({latitude:V,longitude:z,member:H})=>[z,V,H]));super(Q,G)}},M0=class extends D{constructor([Y,W,$,G="M"],Q){super(["GEODIST",Y,W,$,G],Q)}},w0=class extends D{constructor(Y,W){let[$]=Y,G=Array.isArray(Y[1])?Y[1]:Y.slice(1);super(["GEOHASH",$,...G],W)}},J0=class extends D{constructor(Y,W){let[$]=Y,G=Array.isArray(Y[1])?Y[1]:Y.slice(1);super(["GEOPOS",$,...G],{deserialize:(Q)=>B$(Q),...W})}};function B$(Y){let W=[];for(let $ of Y){if(!$?.[0]||!$?.[1])continue;W.push({lng:Number.parseFloat($[0]),lat:Number.parseFloat($[1])})}return W}var L0=class extends D{constructor([Y,W,$,G,Q],V){let z=["GEOSEARCH",Y];if(W.type==="FROMMEMBER"||W.type==="frommember")z.push(W.type,W.member);if(W.type==="FROMLONLAT"||W.type==="fromlonlat")z.push(W.type,W.coordinate.lon,W.coordinate.lat);if($.type==="BYRADIUS"||$.type==="byradius")z.push($.type,$.radius,$.radiusType);if($.type==="BYBOX"||$.type==="bybox")z.push($.type,$.rect.width,$.rect.height,$.rectType);if(z.push(G),Q?.count)z.push("COUNT",Q.count.limit,...Q.count.any?["ANY"]:[]);let H=(Z)=>{if(!Q?.withCoord&&!Q?.withDist&&!Q?.withHash)return Z.map((T)=>{try{return{member:JSON.parse(T)}}catch{return{member:T}}});return Z.map((T)=>{let X=1,M={};try{M.member=JSON.parse(T[0])}catch{M.member=T[0]}if(Q.withDist)M.dist=Number.parseFloat(T[X++]);if(Q.withHash)M.hash=T[X++].toString();if(Q.withCoord)M.coord={long:Number.parseFloat(T[X][0]),lat:Number.parseFloat(T[X][1])};return M})};super([...z,...Q?.withCoord?["WITHCOORD"]:[],...Q?.withDist?["WITHDIST"]:[],...Q?.withHash?["WITHHASH"]:[]],{deserialize:H,...V})}},K0=class extends D{constructor([Y,W,$,G,Q,V],z){let H=["GEOSEARCHSTORE",Y,W];if($.type==="FROMMEMBER"||$.type==="frommember")H.push($.type,$.member);if($.type==="FROMLONLAT"||$.type==="fromlonlat")H.push($.type,$.coordinate.lon,$.coordinate.lat);if(G.type==="BYRADIUS"||G.type==="byradius")H.push(G.type,G.radius,G.radiusType);if(G.type==="BYBOX"||G.type==="bybox")H.push(G.type,G.rect.width,G.rect.height,G.rectType);if(H.push(Q),V?.count)H.push("COUNT",V.count.limit,...V.count.any?["ANY"]:[]);super([...H,...V?.storeDist?["STOREDIST"]:[]],z)}},N0=class extends D{constructor(Y,W){super(["get",...Y],W)}},U0=class extends D{constructor(Y,W){super(["getbit",...Y],W)}},h0=class extends D{constructor(Y,W){super(["getdel",...Y],W)}},E0=class extends D{constructor([Y,W],$){let G=["getex",Y];if(W){if("ex"in W&&typeof W.ex==="number")G.push("ex",W.ex);else if("px"in W&&typeof W.px==="number")G.push("px",W.px);else if("exat"in W&&typeof W.exat==="number")G.push("exat",W.exat);else if("pxat"in W&&typeof W.pxat==="number")G.push("pxat",W.pxat);else if("persist"in W&&W.persist)G.push("persist")}super(G,$)}},F0=class extends D{constructor(Y,W){super(["getrange",...Y],W)}},A0=class extends D{constructor(Y,W){super(["getset",...Y],W)}},_0=class extends D{constructor(Y,W){super(["hdel",...Y],W)}},j0=class extends D{constructor(Y,W){super(["hexists",...Y],W)}},B0=class extends D{constructor(Y,W){let[$,G,Q,V]=Y,z=Array.isArray(G)?G:[G];super(["hexpire",$,Q,...V?[V]:[],"FIELDS",z.length,...z],W)}},P0=class extends D{constructor(Y,W){let[$,G,Q,V]=Y,z=Array.isArray(G)?G:[G];super(["hexpireat",$,Q,...V?[V]:[],"FIELDS",z.length,...z],W)}},I0=class extends D{constructor(Y,W){let[$,G]=Y,Q=Array.isArray(G)?G:[G];super(["hexpiretime",$,"FIELDS",Q.length,...Q],W)}},x0=class extends D{constructor(Y,W){let[$,G]=Y,Q=Array.isArray(G)?G:[G];super(["hpersist",$,"FIELDS",Q.length,...Q],W)}},S0=class extends D{constructor(Y,W){let[$,G,Q,V]=Y,z=Array.isArray(G)?G:[G];super(["hpexpire",$,Q,...V?[V]:[],"FIELDS",z.length,...z],W)}},b0=class extends D{constructor(Y,W){let[$,G,Q,V]=Y,z=Array.isArray(G)?G:[G];super(["hpexpireat",$,Q,...V?[V]:[],"FIELDS",z.length,...z],W)}},q0=class extends D{constructor(Y,W){let[$,G]=Y,Q=Array.isArray(G)?G:[G];super(["hpexpiretime",$,"FIELDS",Q.length,...Q],W)}},O0=class extends D{constructor(Y,W){let[$,G]=Y,Q=Array.isArray(G)?G:[G];super(["hpttl",$,"FIELDS",Q.length,...Q],W)}},R0=class extends D{constructor(Y,W){super(["hget",...Y],W)}};function P$(Y){if(Y.length===0)return null;let W={};for(let $=0;$<Y.length;$+=2){let G=Y[$],Q=Y[$+1];try{let V=!Number.isNaN(Number(Q))&&!Number.isSafeInteger(Number(Q));W[G]=V?Q:JSON.parse(Q)}catch{W[G]=Q}}return W}var v0=class extends D{constructor(Y,W){super(["hgetall",...Y],{deserialize:($)=>P$($),...W})}};function i(Y,W){if(W.every((G)=>G===null))return null;let $={};for(let[G,Q]of Y.entries())try{$[Q]=JSON.parse(W[G])}catch{$[Q]=W[G]}return $}var f0=class extends D{constructor([Y,...W],$){super(["hmget",Y,...W],{deserialize:(G)=>i(W,G),...$})}},k0=class extends D{constructor([Y,...W],$){super(["hgetdel",Y,"FIELDS",W.length,...W],{deserialize:(G)=>i(W.map(String),G),...$})}},l0=class extends D{constructor([Y,W,...$],G){let Q=["hgetex",Y];if("ex"in W&&typeof W.ex==="number")Q.push("EX",W.ex);else if("px"in W&&typeof W.px==="number")Q.push("PX",W.px);else if("exat"in W&&typeof W.exat==="number")Q.push("EXAT",W.exat);else if("pxat"in W&&typeof W.pxat==="number")Q.push("PXAT",W.pxat);else if("persist"in W&&W.persist)Q.push("PERSIST");Q.push("FIELDS",$.length,...$);super(Q,{deserialize:(V)=>i($.map(String),V),...G})}},y0=class extends D{constructor(Y,W){super(["hincrby",...Y],W)}},C0=class extends D{constructor(Y,W){super(["hincrbyfloat",...Y],W)}},u0=class extends D{constructor([Y],W){super(["hkeys",Y],W)}},i0=class extends D{constructor(Y,W){super(["hlen",...Y],W)}},g0=class extends D{constructor([Y,W],$){super(["hmset",Y,...Object.entries(W).flatMap(([G,Q])=>[G,Q])],$)}},c0=class extends D{constructor([Y,W,$],G){let Q=["hscan",Y,W];if($?.match)Q.push("match",$.match);if(typeof $?.count==="number")Q.push("count",$.count);super(Q,{deserialize:I,...G})}},p0=class extends D{constructor([Y,W],$){super(["hset",Y,...Object.entries(W).flatMap(([G,Q])=>[G,Q])],$)}},n0=class extends D{constructor([Y,W,$],G){let Q=["hsetex",Y];if(W.conditional)Q.push(W.conditional.toUpperCase());if(W.expiration){if("ex"in W.expiration&&typeof W.expiration.ex==="number")Q.push("EX",W.expiration.ex);else if("px"in W.expiration&&typeof W.expiration.px==="number")Q.push("PX",W.expiration.px);else if("exat"in W.expiration&&typeof W.expiration.exat==="number")Q.push("EXAT",W.expiration.exat);else if("pxat"in W.expiration&&typeof W.expiration.pxat==="number")Q.push("PXAT",W.expiration.pxat);else if("keepttl"in W.expiration&&W.expiration.keepttl)Q.push("KEEPTTL")}let V=Object.entries($);Q.push("FIELDS",V.length);for(let[z,H]of V)Q.push(z,H);super(Q,G)}},t0=class extends D{constructor(Y,W){super(["hsetnx",...Y],W)}},d0=class extends D{constructor(Y,W){super(["hstrlen",...Y],W)}},r0=class extends D{constructor(Y,W){let[$,G]=Y,Q=Array.isArray(G)?G:[G];super(["httl",$,"FIELDS",Q.length,...Q],W)}},o0=class extends D{constructor(Y,W){super(["hvals",...Y],W)}},a0=class extends D{constructor(Y,W){super(["incr",...Y],W)}},e0=class extends D{constructor(Y,W){super(["incrby",...Y],W)}},m0=class extends D{constructor(Y,W){super(["incrbyfloat",...Y],W)}},s0=class extends D{constructor(Y,W){super(["JSON.ARRAPPEND",...Y],W)}},YY=class extends D{constructor(Y,W){super(["JSON.ARRINDEX",...Y],W)}},WY=class extends D{constructor(Y,W){super(["JSON.ARRINSERT",...Y],W)}},$Y=class extends D{constructor(Y,W){super(["JSON.ARRLEN",Y[0],Y[1]??"$"],W)}},GY=class extends D{constructor(Y,W){super(["JSON.ARRPOP",...Y],W)}},QY=class extends D{constructor(Y,W){let $=Y[1]??"$",G=Y[2]??0,Q=Y[3]??0;super(["JSON.ARRTRIM",Y[0],$,G,Q],W)}},VY=class extends D{constructor(Y,W){super(["JSON.CLEAR",...Y],W)}},DY=class extends D{constructor(Y,W){super(["JSON.DEL",...Y],W)}},zY=class extends D{constructor(Y,W){super(["JSON.FORGET",...Y],W)}},HY=class extends D{constructor(Y,W){let $=["JSON.GET"];if(typeof Y[1]==="string")$.push(...Y);else{if($.push(Y[0]),Y[1]){if(Y[1].indent)$.push("INDENT",Y[1].indent);if(Y[1].newline)$.push("NEWLINE",Y[1].newline);if(Y[1].space)$.push("SPACE",Y[1].space)}$.push(...Y.slice(2))}super($,W)}},ZY=class extends D{constructor(Y,W){let $=["JSON.MERGE",...Y];super($,W)}},TY=class extends D{constructor(Y,W){super(["JSON.MGET",...Y[0],Y[1]],W)}},XY=class extends D{constructor(Y,W){let $=["JSON.MSET"];for(let G of Y)$.push(G.key,G.path,G.value);super($,W)}},MY=class extends D{constructor(Y,W){super(["JSON.NUMINCRBY",...Y],W)}},wY=class extends D{constructor(Y,W){super(["JSON.NUMMULTBY",...Y],W)}},JY=class extends D{constructor(Y,W){super(["JSON.OBJKEYS",...Y],W)}},LY=class extends D{constructor(Y,W){super(["JSON.OBJLEN",...Y],W)}},KY=class extends D{constructor(Y,W){super(["JSON.RESP",...Y],W)}},NY=class extends D{constructor(Y,W){let $=["JSON.SET",Y[0],Y[1],Y[2]];if(Y[3]){if(Y[3].nx)$.push("NX");else if(Y[3].xx)$.push("XX")}super($,W)}},UY=class extends D{constructor(Y,W){super(["JSON.STRAPPEND",...Y],W)}},hY=class extends D{constructor(Y,W){super(["JSON.STRLEN",...Y],W)}},EY=class extends D{constructor(Y,W){super(["JSON.TOGGLE",...Y],W)}},FY=class extends D{constructor(Y,W){super(["JSON.TYPE",...Y],W)}},AY=class extends D{constructor(Y,W){super(["keys",...Y],W)}},_Y=class extends D{constructor(Y,W){super(["lindex",...Y],W)}},jY=class extends D{constructor(Y,W){super(["linsert",...Y],W)}},BY=class extends D{constructor(Y,W){super(["llen",...Y],W)}},PY=class extends D{constructor(Y,W){super(["lmove",...Y],W)}},IY=class extends D{constructor(Y,W){let[$,G,Q,V]=Y;super(["LMPOP",$,...G,Q,...V?["COUNT",V]:[]],W)}},xY=class extends D{constructor(Y,W){super(["lpop",...Y],W)}},SY=class extends D{constructor(Y,W){let $=["lpos",Y[0],Y[1]];if(typeof Y[2]?.rank==="number")$.push("rank",Y[2].rank);if(typeof Y[2]?.count==="number")$.push("count",Y[2].count);if(typeof Y[2]?.maxLen==="number")$.push("maxLen",Y[2].maxLen);super($,W)}},bY=class extends D{constructor(Y,W){super(["lpush",...Y],W)}},qY=class extends D{constructor(Y,W){super(["lpushx",...Y],W)}},OY=class extends D{constructor(Y,W){super(["lrange",...Y],W)}},RY=class extends D{constructor(Y,W){super(["lrem",...Y],W)}},vY=class extends D{constructor(Y,W){super(["lset",...Y],W)}},fY=class extends D{constructor(Y,W){super(["ltrim",...Y],W)}},kY=class extends D{constructor(Y,W){let $=Array.isArray(Y[0])?Y[0]:Y;super(["mget",...$],W)}},lY=class extends D{constructor([Y],W){super(["mset",...Object.entries(Y).flatMap(([$,G])=>[$,G])],W)}},yY=class extends D{constructor([Y],W){super(["msetnx",...Object.entries(Y).flat()],W)}},CY=class extends D{constructor(Y,W){super(["persist",...Y],W)}},uY=class extends D{constructor(Y,W){super(["pexpire",...Y],W)}},iY=class extends D{constructor(Y,W){super(["pexpireat",...Y],W)}},gY=class extends D{constructor(Y,W){super(["pfadd",...Y],W)}},cY=class extends D{constructor(Y,W){super(["pfcount",...Y],W)}},pY=class extends D{constructor(Y,W){super(["pfmerge",...Y],W)}},nY=class extends D{constructor(Y,W){let $=["ping"];if(Y?.[0]!==void 0)$.push(Y[0]);super($,W)}},tY=class extends D{constructor(Y,W){super(["psetex",...Y],W)}},dY=class extends D{constructor(Y,W){super(["pttl",...Y],W)}},rY=class extends D{constructor(Y,W){super(["publish",...Y],W)}},oY=class extends D{constructor(Y){super(["randomkey"],Y)}},aY=class extends D{constructor(Y,W){super(["rename",...Y],W)}},eY=class extends D{constructor(Y,W){super(["renamenx",...Y],W)}},mY=class extends D{constructor(Y,W){super(["rpop",...Y],W)}},sY=class extends D{constructor(Y,W){super(["rpush",...Y],W)}},Y4=class extends D{constructor(Y,W){super(["rpushx",...Y],W)}},W4=class extends D{constructor(Y,W){super(["sadd",...Y],W)}},$4=class extends D{constructor([Y,W],$){let G=["scan",Y];if(W?.match)G.push("match",W.match);if(typeof W?.count==="number")G.push("count",W.count);if(W&&"withType"in W&&W.withType===!0)G.push("withtype");else if(W&&"type"in W&&W.type&&W.type.length>0)G.push("type",W.type);super(G,{deserialize:W?.withType?iW:I,...$})}},G4=class extends D{constructor(Y,W){super(["scard",...Y],W)}},Q4=class extends D{constructor(Y,W){super(["script","exists",...Y],{deserialize:($)=>$,...W})}},V4=class extends D{constructor([Y],W){let $=["script","flush"];if(Y?.sync)$.push("sync");else if(Y?.async)$.push("async");super($,W)}},D4=class extends D{constructor(Y,W){super(["script","load",...Y],W)}},z4=class extends D{constructor(Y,W){super(["sdiff",...Y],W)}},H4=class extends D{constructor(Y,W){super(["sdiffstore",...Y],W)}},Z4=class extends D{constructor([Y,W,$],G){let Q=["set",Y,W];if($){if("nx"in $&&$.nx)Q.push("nx");else if("xx"in $&&$.xx)Q.push("xx");if("get"in $&&$.get)Q.push("get");if("ex"in $&&typeof $.ex==="number")Q.push("ex",$.ex);else if("px"in $&&typeof $.px==="number")Q.push("px",$.px);else if("exat"in $&&typeof $.exat==="number")Q.push("exat",$.exat);else if("pxat"in $&&typeof $.pxat==="number")Q.push("pxat",$.pxat);else if("keepTtl"in $&&$.keepTtl)Q.push("keepTtl")}super(Q,G)}},T4=class extends D{constructor(Y,W){super(["setbit",...Y],W)}},X4=class extends D{constructor(Y,W){super(["setex",...Y],W)}},M4=class extends D{constructor(Y,W){super(["setnx",...Y],W)}},w4=class extends D{constructor(Y,W){super(["setrange",...Y],W)}},J4=class extends D{constructor(Y,W){super(["sinter",...Y],W)}},L4=class extends D{constructor(Y,W){let[$,G]=Y,Q=["sintercard",$.length,...$];if(G?.limit!==void 0)Q.push("LIMIT",G.limit);super(Q,W)}},K4=class extends D{constructor(Y,W){super(["sinterstore",...Y],W)}},N4=class extends D{constructor(Y,W){super(["sismember",...Y],W)}},U4=class extends D{constructor(Y,W){super(["smembers",...Y],W)}},h4=class extends D{constructor(Y,W){super(["smismember",Y[0],...Y[1]],W)}},E4=class extends D{constructor(Y,W){super(["smove",...Y],W)}},F4=class extends D{constructor([Y,W],$){let G=["spop",Y];if(typeof W==="number")G.push(W);super(G,$)}},A4=class extends D{constructor([Y,W],$){let G=["srandmember",Y];if(typeof W==="number")G.push(W);super(G,$)}},_4=class extends D{constructor(Y,W){super(["srem",...Y],W)}},j4=class extends D{constructor([Y,W,$],G){let Q=["sscan",Y,W];if($?.match)Q.push("match",$.match);if(typeof $?.count==="number")Q.push("count",$.count);super(Q,{deserialize:I,...G})}},B4=class extends D{constructor(Y,W){super(["strlen",...Y],W)}},P4=class extends D{constructor(Y,W){super(["sunion",...Y],W)}},I4=class extends D{constructor(Y,W){super(["sunionstore",...Y],W)}},x4=class extends D{constructor(Y){super(["time"],Y)}},S4=class extends D{constructor(Y,W){super(["touch",...Y],W)}},b4=class extends D{constructor(Y,W){super(["ttl",...Y],W)}},q4=class extends D{constructor(Y,W){super(["type",...Y],W)}},O4=class extends D{constructor(Y,W){super(["unlink",...Y],W)}},R4=class extends D{constructor([Y,W,$],G){let Q=Array.isArray($)?[...$]:[$];super(["XACK",Y,W,...Q],G)}},v4=class extends D{constructor([Y,W,$,...G],Q){let V=["XACKDEL",Y,W];V.push($.toUpperCase(),"IDS",G.length,...G);super(V,Q)}},f4=class extends D{constructor([Y,W,$,G],Q){let V=["XADD",Y];if(G){if(G.nomkStream)V.push("NOMKSTREAM");if(G.trim){if(V.push(G.trim.type,G.trim.comparison,G.trim.threshold),G.trim.limit!==void 0)V.push("LIMIT",G.trim.limit)}}V.push(W);for(let[z,H]of Object.entries($))V.push(z,H);super(V,Q)}},k4=class extends D{constructor([Y,W,$,G,Q,V],z){let H=[];if(V?.count)H.push("COUNT",V.count);if(V?.justId)H.push("JUSTID");super(["XAUTOCLAIM",Y,W,$,G,Q,...H],z)}},l4=class extends D{constructor([Y,W,$,G,Q,V],z){let H=Array.isArray(Q)?[...Q]:[Q],Z=[];if(V?.idleMS)Z.push("IDLE",V.idleMS);if(V?.idleMS)Z.push("TIME",V.timeMS);if(V?.retryCount)Z.push("RETRYCOUNT",V.retryCount);if(V?.force)Z.push("FORCE");if(V?.justId)Z.push("JUSTID");if(V?.lastId)Z.push("LASTID",V.lastId);super(["XCLAIM",Y,W,$,G,...H,...Z],z)}},y4=class extends D{constructor([Y,W],$){let G=Array.isArray(W)?[...W]:[W];super(["XDEL",Y,...G],$)}},C4=class extends D{constructor([Y,W,...$],G){let Q=["XDELEX",Y];if(W)Q.push(W.toUpperCase());Q.push("IDS",$.length,...$);super(Q,G)}},u4=class extends D{constructor([Y,W],$){let G=["XGROUP"];switch(W.type){case"CREATE":{if(G.push("CREATE",Y,W.group,W.id),W.options){if(W.options.MKSTREAM)G.push("MKSTREAM");if(W.options.ENTRIESREAD!==void 0)G.push("ENTRIESREAD",W.options.ENTRIESREAD.toString())}break}case"CREATECONSUMER":{G.push("CREATECONSUMER",Y,W.group,W.consumer);break}case"DELCONSUMER":{G.push("DELCONSUMER",Y,W.group,W.consumer);break}case"DESTROY":{G.push("DESTROY",Y,W.group);break}case"SETID":{if(G.push("SETID",Y,W.group,W.id),W.options?.ENTRIESREAD!==void 0)G.push("ENTRIESREAD",W.options.ENTRIESREAD.toString());break}default:throw Error("Invalid XGROUP")}super(G,$)}},i4=class extends D{constructor([Y,W],$){let G=[];if(W.type==="CONSUMERS")G.push("CONSUMERS",Y,W.group);else G.push("GROUPS",Y);super(["XINFO",...G],$)}},g4=class extends D{constructor(Y,W){super(["XLEN",...Y],W)}},c4=class extends D{constructor([Y,W,$,G,Q,V],z){let H=V?.consumer===void 0?[]:Array.isArray(V.consumer)?[...V.consumer]:[V.consumer];super(["XPENDING",Y,W,...V?.idleTime?["IDLE",V.idleTime]:[],$,G,Q,...H],z)}};function I$(Y){let W={};for(let $ of Y)for(let G=0;G<$.length;G+=2){let Q=$[G],V=$[G+1];if(!(Q in W))W[Q]={};for(let z=0;z<V.length;z+=2){let H=V[z],Z=V[z+1];try{W[Q][H]=JSON.parse(Z)}catch{W[Q][H]=Z}}}return W}var p4=class extends D{constructor([Y,W,$,G],Q){let V=["XRANGE",Y,W,$];if(typeof G==="number")V.push("COUNT",G);super(V,{deserialize:(z)=>I$(z),...Q})}},x$="ERR Unbalanced XREAD list of streams: for each stream key an ID or '$' must be specified",n4=class extends D{constructor([Y,W,$],G){if(Array.isArray(Y)&&Array.isArray(W)&&Y.length!==W.length)throw Error(x$);let Q=[];if(typeof $?.count==="number")Q.push("COUNT",$.count);if(typeof $?.blockMS==="number")Q.push("BLOCK",$.blockMS);Q.push("STREAMS",...Array.isArray(Y)?[...Y]:[Y],...Array.isArray(W)?[...W]:[W]);super(["XREAD",...Q],G)}},S$="ERR Unbalanced XREADGROUP list of streams: for each stream key an ID or '$' must be specified",t4=class extends D{constructor([Y,W,$,G,Q],V){if(Array.isArray($)&&Array.isArray(G)&&$.length!==G.length)throw Error(S$);let z=[];if(typeof Q?.count==="number")z.push("COUNT",Q.count);if(typeof Q?.blockMS==="number")z.push("BLOCK",Q.blockMS);if(typeof Q?.NOACK==="boolean"&&Q.NOACK)z.push("NOACK");z.push("STREAMS",...Array.isArray($)?[...$]:[$],...Array.isArray(G)?[...G]:[G]);super(["XREADGROUP","GROUP",Y,W,...z],V)}},d4=class extends D{constructor([Y,W,$,G],Q){let V=["XREVRANGE",Y,W,$];if(typeof G==="number")V.push("COUNT",G);super(V,{deserialize:(z)=>b$(z),...Q})}};function b$(Y){let W={};for(let $ of Y)for(let G=0;G<$.length;G+=2){let Q=$[G],V=$[G+1];if(!(Q in W))W[Q]={};for(let z=0;z<V.length;z+=2){let H=V[z],Z=V[z+1];try{W[Q][H]=JSON.parse(Z)}catch{W[Q][H]=Z}}}return W}var r4=class extends D{constructor([Y,W],$){let{limit:G,strategy:Q,threshold:V,exactness:z="~"}=W;super(["XTRIM",Y,Q,z,V,...G?["LIMIT",G]:[]],$)}},B=class extends D{constructor([Y,W,...$],G){let Q=["zadd",Y];if("nx"in W&&W.nx)Q.push("nx");else if("xx"in W&&W.xx)Q.push("xx");if("ch"in W&&W.ch)Q.push("ch");if("incr"in W&&W.incr)Q.push("incr");if("lt"in W&&W.lt)Q.push("lt");else if("gt"in W&&W.gt)Q.push("gt");if("score"in W&&"member"in W)Q.push(W.score,W.member);Q.push(...$.flatMap(({score:V,member:z})=>[V,z]));super(Q,G)}},o4=class extends D{constructor(Y,W){super(["zcard",...Y],W)}},a4=class extends D{constructor(Y,W){super(["zcount",...Y],W)}},e4=class extends D{constructor(Y,W){super(["zincrby",...Y],W)}},m4=class extends D{constructor([Y,W,$,G],Q){let V=["zinterstore",Y,W];if(Array.isArray($))V.push(...$);else V.push($);if(G){if("weights"in G&&G.weights)V.push("weights",...G.weights);else if("weight"in G&&typeof G.weight==="number")V.push("weights",G.weight);if("aggregate"in G)V.push("aggregate",G.aggregate)}super(V,Q)}},s4=class extends D{constructor(Y,W){super(["zlexcount",...Y],W)}},YW=class extends D{constructor([Y,W],$){let G=["zpopmax",Y];if(typeof W==="number")G.push(W);super(G,$)}},WW=class extends D{constructor([Y,W],$){let G=["zpopmin",Y];if(typeof W==="number")G.push(W);super(G,$)}},$W=class extends D{constructor([Y,W,$,G],Q){let V=["zrange",Y,W,$];if(G?.byScore)V.push("byscore");if(G?.byLex)V.push("bylex");if(G?.rev)V.push("rev");if(G?.count!==void 0&&G.offset!==void 0)V.push("limit",G.offset,G.count);if(G?.withScores)V.push("withscores");super(V,Q)}},GW=class extends D{constructor(Y,W){super(["zrank",...Y],W)}},QW=class extends D{constructor(Y,W){super(["zrem",...Y],W)}},VW=class extends D{constructor(Y,W){super(["zremrangebylex",...Y],W)}},DW=class extends D{constructor(Y,W){super(["zremrangebyrank",...Y],W)}},zW=class extends D{constructor(Y,W){super(["zremrangebyscore",...Y],W)}},HW=class extends D{constructor(Y,W){super(["zrevrank",...Y],W)}},ZW=class extends D{constructor([Y,W,$],G){let Q=["zscan",Y,W];if($?.match)Q.push("match",$.match);if(typeof $?.count==="number")Q.push("count",$.count);super(Q,{deserialize:I,...G})}},TW=class extends D{constructor(Y,W){super(["zscore",...Y],W)}},XW=class extends D{constructor([Y,W,$],G){let Q=["zunion",Y];if(Array.isArray(W))Q.push(...W);else Q.push(W);if($){if("weights"in $&&$.weights)Q.push("weights",...$.weights);else if("weight"in $&&typeof $.weight==="number")Q.push("weights",$.weight);if("aggregate"in $)Q.push("aggregate",$.aggregate);if($.withScores)Q.push("withscores")}super(Q,G)}},MW=class extends D{constructor([Y,W,$,G],Q){let V=["zunionstore",Y,W];if(Array.isArray($))V.push(...$);else V.push($);if(G){if("weights"in G&&G.weights)V.push("weights",...G.weights);else if("weight"in G&&typeof G.weight==="number")V.push("weights",G.weight);if("aggregate"in G)V.push("aggregate",G.aggregate)}super(V,Q)}},wW=class extends D{constructor(Y,W){super(["zdiffstore",...Y],W)}},JW=class extends D{constructor(Y,W){let[$,G]=Y;super(["zmscore",$,...G],W)}},Q1=class{client;commands;commandOptions;multiExec;constructor(Y){if(this.client=Y.client,this.commands=[],this.commandOptions=Y.commandOptions,this.multiExec=Y.multiExec??!1,this.commandOptions?.latencyLogging){let W=this.exec.bind(this);this.exec=async($)=>{let G=performance.now(),Q=await($?W($):W()),z=(performance.now()-G).toFixed(2);return console.log(`Latency for \x1B[38;2;19;185;39m${this.multiExec?["MULTI-EXEC"]:["PIPELINE"].toString().toUpperCase()}\x1B[0m: \x1B[38;2;0;255;255m${z} ms\x1B[0m`),Q}}}exec=async(Y)=>{if(this.commands.length===0)throw Error("Pipeline is empty");let W=this.multiExec?["multi-exec"]:["pipeline"],$=await this.client.request({path:W,body:Object.values(this.commands).map((G)=>G.command)});return Y?.keepErrors?$.map(({error:G,result:Q},V)=>{return{error:G,result:this.commands[V].deserialize(Q)}}):$.map(({error:G,result:Q},V)=>{if(G)throw new h(`Command ${V+1} [ ${this.commands[V].command[0]} ] failed: ${G}`);return this.commands[V].deserialize(Q)})};length(){return this.commands.length}chain(Y){return this.commands.push(Y),this}append=(...Y)=>this.chain(new h1(Y,this.commandOptions));arcount=(...Y)=>this.chain(new E1(Y,this.commandOptions));ardel=(...Y)=>this.chain(new F1(Y,this.commandOptions));ardelrange=(...Y)=>this.chain(new A1(Y,this.commandOptions));arget=(...Y)=>this.chain(new _1(Y,this.commandOptions));argetrange=(...Y)=>this.chain(new j1(Y,this.commandOptions));argrep=(Y,W,$,G)=>this.chain(new B1([Y,W,$,G],this.commandOptions));arinfo=(...Y)=>this.chain(new P1(Y,this.commandOptions));arinsert=(Y,...W)=>this.chain(new I1([Y,...W],this.commandOptions));arlastitems=(...Y)=>this.chain(new x1(Y,this.commandOptions));arlen=(...Y)=>this.chain(new S1(Y,this.commandOptions));armget=(...Y)=>this.chain(new b1(Y,this.commandOptions));armset=(Y,W)=>this.chain(new q1([Y,W],this.commandOptions));arnext=(...Y)=>this.chain(new O1(Y,this.commandOptions));arop=(Y,W,$,G)=>this.chain(new R1([Y,W,$,G],this.commandOptions));arring=(Y,W,...$)=>this.chain(new v1([Y,W,...$],this.commandOptions));arscan=(...Y)=>this.chain(new f1(Y,this.commandOptions));arseek=(...Y)=>this.chain(new k1(Y,this.commandOptions));arset=(Y,W,...$)=>this.chain(new l1([Y,W,...$],this.commandOptions));bitcount=(...Y)=>this.chain(new y1(Y,this.commandOptions));bitfield=(...Y)=>new C1(Y,this.client,this.commandOptions,this.chain.bind(this));bitop=(Y,W,$,...G)=>this.chain(new u1([Y,W,$,...G],this.commandOptions));bitpos=(...Y)=>this.chain(new i1(Y,this.commandOptions));clientSetinfo=(...Y)=>this.chain(new g1(Y,this.commandOptions));copy=(...Y)=>this.chain(new c1(Y,this.commandOptions));zdiffstore=(...Y)=>this.chain(new wW(Y,this.commandOptions));dbsize=()=>this.chain(new p1(this.commandOptions));decr=(...Y)=>this.chain(new n1(Y,this.commandOptions));decrby=(...Y)=>this.chain(new t1(Y,this.commandOptions));del=(...Y)=>this.chain(new d1(Y,this.commandOptions));echo=(...Y)=>this.chain(new r1(Y,this.commandOptions));evalRo=(...Y)=>this.chain(new o1(Y,this.commandOptions));eval=(...Y)=>this.chain(new a1(Y,this.commandOptions));evalshaRo=(...Y)=>this.chain(new e1(Y,this.commandOptions));evalsha=(...Y)=>this.chain(new m1(Y,this.commandOptions));exists=(...Y)=>this.chain(new s1(Y,this.commandOptions));expire=(...Y)=>this.chain(new Y0(Y,this.commandOptions));expireat=(...Y)=>this.chain(new W0(Y,this.commandOptions));flushall=(Y)=>this.chain(new Q0(Y,this.commandOptions));flushdb=(...Y)=>this.chain(new V0(Y,this.commandOptions));geoadd=(...Y)=>this.chain(new X0(Y,this.commandOptions));geodist=(...Y)=>this.chain(new M0(Y,this.commandOptions));geopos=(...Y)=>this.chain(new J0(Y,this.commandOptions));geohash=(...Y)=>this.chain(new w0(Y,this.commandOptions));geosearch=(...Y)=>this.chain(new L0(Y,this.commandOptions));geosearchstore=(...Y)=>this.chain(new K0(Y,this.commandOptions));get=(...Y)=>this.chain(new N0(Y,this.commandOptions));getbit=(...Y)=>this.chain(new U0(Y,this.commandOptions));getdel=(...Y)=>this.chain(new h0(Y,this.commandOptions));getex=(...Y)=>this.chain(new E0(Y,this.commandOptions));getrange=(...Y)=>this.chain(new F0(Y,this.commandOptions));getset=(Y,W)=>this.chain(new A0([Y,W],this.commandOptions));hdel=(...Y)=>this.chain(new _0(Y,this.commandOptions));hexists=(...Y)=>this.chain(new j0(Y,this.commandOptions));hexpire=(...Y)=>this.chain(new B0(Y,this.commandOptions));hexpireat=(...Y)=>this.chain(new P0(Y,this.commandOptions));hexpiretime=(...Y)=>this.chain(new I0(Y,this.commandOptions));httl=(...Y)=>this.chain(new r0(Y,this.commandOptions));hpexpire=(...Y)=>this.chain(new S0(Y,this.commandOptions));hpexpireat=(...Y)=>this.chain(new b0(Y,this.commandOptions));hpexpiretime=(...Y)=>this.chain(new q0(Y,this.commandOptions));hpttl=(...Y)=>this.chain(new O0(Y,this.commandOptions));hpersist=(...Y)=>this.chain(new x0(Y,this.commandOptions));hget=(...Y)=>this.chain(new R0(Y,this.commandOptions));hgetall=(...Y)=>this.chain(new v0(Y,this.commandOptions));hgetdel=(...Y)=>this.chain(new k0(Y,this.commandOptions));hgetex=(...Y)=>this.chain(new l0(Y,this.commandOptions));hincrby=(...Y)=>this.chain(new y0(Y,this.commandOptions));hincrbyfloat=(...Y)=>this.chain(new C0(Y,this.commandOptions));hkeys=(...Y)=>this.chain(new u0(Y,this.commandOptions));hlen=(...Y)=>this.chain(new i0(Y,this.commandOptions));hmget=(...Y)=>this.chain(new f0(Y,this.commandOptions));hmset=(Y,W)=>this.chain(new g0([Y,W],this.commandOptions));hrandfield=(Y,W,$)=>this.chain(new U1([Y,W,$],this.commandOptions));hscan=(...Y)=>this.chain(new c0(Y,this.commandOptions));hset=(Y,W)=>this.chain(new p0([Y,W],this.commandOptions));hsetex=(...Y)=>this.chain(new n0(Y,this.commandOptions));hsetnx=(Y,W,$)=>this.chain(new t0([Y,W,$],this.commandOptions));hstrlen=(...Y)=>this.chain(new d0(Y,this.commandOptions));hvals=(...Y)=>this.chain(new o0(Y,this.commandOptions));incr=(...Y)=>this.chain(new a0(Y,this.commandOptions));incrby=(...Y)=>this.chain(new e0(Y,this.commandOptions));incrbyfloat=(...Y)=>this.chain(new m0(Y,this.commandOptions));keys=(...Y)=>this.chain(new AY(Y,this.commandOptions));lindex=(...Y)=>this.chain(new _Y(Y,this.commandOptions));linsert=(Y,W,$,G)=>this.chain(new jY([Y,W,$,G],this.commandOptions));llen=(...Y)=>this.chain(new BY(Y,this.commandOptions));lmove=(...Y)=>this.chain(new PY(Y,this.commandOptions));lpop=(...Y)=>this.chain(new xY(Y,this.commandOptions));lmpop=(...Y)=>this.chain(new IY(Y,this.commandOptions));lpos=(...Y)=>this.chain(new SY(Y,this.commandOptions));lpush=(Y,...W)=>this.chain(new bY([Y,...W],this.commandOptions));lpushx=(Y,...W)=>this.chain(new qY([Y,...W],this.commandOptions));lrange=(...Y)=>this.chain(new OY(Y,this.commandOptions));lrem=(Y,W,$)=>this.chain(new RY([Y,W,$],this.commandOptions));lset=(Y,W,$)=>this.chain(new vY([Y,W,$],this.commandOptions));ltrim=(...Y)=>this.chain(new fY(Y,this.commandOptions));mget=(...Y)=>this.chain(new kY(Y,this.commandOptions));mset=(Y)=>this.chain(new lY([Y],this.commandOptions));msetnx=(Y)=>this.chain(new yY([Y],this.commandOptions));persist=(...Y)=>this.chain(new CY(Y,this.commandOptions));pexpire=(...Y)=>this.chain(new uY(Y,this.commandOptions));pexpireat=(...Y)=>this.chain(new iY(Y,this.commandOptions));pfadd=(...Y)=>this.chain(new gY(Y,this.commandOptions));pfcount=(...Y)=>this.chain(new cY(Y,this.commandOptions));pfmerge=(...Y)=>this.chain(new pY(Y,this.commandOptions));ping=(Y)=>this.chain(new nY(Y,this.commandOptions));psetex=(Y,W,$)=>this.chain(new tY([Y,W,$],this.commandOptions));pttl=(...Y)=>this.chain(new dY(Y,this.commandOptions));publish=(...Y)=>this.chain(new rY(Y,this.commandOptions));randomkey=()=>this.chain(new oY(this.commandOptions));rename=(...Y)=>this.chain(new aY(Y,this.commandOptions));renamenx=(...Y)=>this.chain(new eY(Y,this.commandOptions));rpop=(...Y)=>this.chain(new mY(Y,this.commandOptions));rpush=(Y,...W)=>this.chain(new sY([Y,...W],this.commandOptions));rpushx=(Y,...W)=>this.chain(new Y4([Y,...W],this.commandOptions));sadd=(Y,W,...$)=>this.chain(new W4([Y,W,...$],this.commandOptions));scan=(...Y)=>this.chain(new $4(Y,this.commandOptions));scard=(...Y)=>this.chain(new G4(Y,this.commandOptions));scriptExists=(...Y)=>this.chain(new Q4(Y,this.commandOptions));scriptFlush=(...Y)=>this.chain(new V4(Y,this.commandOptions));scriptLoad=(...Y)=>this.chain(new D4(Y,this.commandOptions));sdiff=(...Y)=>this.chain(new z4(Y,this.commandOptions));sdiffstore=(...Y)=>this.chain(new H4(Y,this.commandOptions));set=(Y,W,$)=>this.chain(new Z4([Y,W,$],this.commandOptions));setbit=(...Y)=>this.chain(new T4(Y,this.commandOptions));setex=(Y,W,$)=>this.chain(new X4([Y,W,$],this.commandOptions));setnx=(Y,W)=>this.chain(new M4([Y,W],this.commandOptions));setrange=(...Y)=>this.chain(new w4(Y,this.commandOptions));sinter=(...Y)=>this.chain(new J4(Y,this.commandOptions));sintercard=(...Y)=>this.chain(new L4(Y,this.commandOptions));sinterstore=(...Y)=>this.chain(new K4(Y,this.commandOptions));sismember=(Y,W)=>this.chain(new N4([Y,W],this.commandOptions));smembers=(...Y)=>this.chain(new U4(Y,this.commandOptions));smismember=(Y,W)=>this.chain(new h4([Y,W],this.commandOptions));smove=(Y,W,$)=>this.chain(new E4([Y,W,$],this.commandOptions));spop=(...Y)=>this.chain(new F4(Y,this.commandOptions));srandmember=(...Y)=>this.chain(new A4(Y,this.commandOptions));srem=(Y,...W)=>this.chain(new _4([Y,...W],this.commandOptions));sscan=(...Y)=>this.chain(new j4(Y,this.commandOptions));strlen=(...Y)=>this.chain(new B4(Y,this.commandOptions));sunion=(...Y)=>this.chain(new P4(Y,this.commandOptions));sunionstore=(...Y)=>this.chain(new I4(Y,this.commandOptions));time=()=>this.chain(new x4(this.commandOptions));touch=(...Y)=>this.chain(new S4(Y,this.commandOptions));ttl=(...Y)=>this.chain(new b4(Y,this.commandOptions));type=(...Y)=>this.chain(new q4(Y,this.commandOptions));unlink=(...Y)=>this.chain(new O4(Y,this.commandOptions));zadd=(...Y)=>{if("score"in Y[1])return this.chain(new B([Y[0],Y[1],...Y.slice(2)],this.commandOptions));return this.chain(new B([Y[0],Y[1],...Y.slice(2)],this.commandOptions))};xadd=(...Y)=>this.chain(new f4(Y,this.commandOptions));xack=(...Y)=>this.chain(new R4(Y,this.commandOptions));xackdel=(...Y)=>this.chain(new v4(Y,this.commandOptions));xdel=(...Y)=>this.chain(new y4(Y,this.commandOptions));xdelex=(...Y)=>this.chain(new C4(Y,this.commandOptions));xgroup=(...Y)=>this.chain(new u4(Y,this.commandOptions));xread=(...Y)=>this.chain(new n4(Y,this.commandOptions));xreadgroup=(...Y)=>this.chain(new t4(Y,this.commandOptions));xinfo=(...Y)=>this.chain(new i4(Y,this.commandOptions));xlen=(...Y)=>this.chain(new g4(Y,this.commandOptions));xpending=(...Y)=>this.chain(new c4(Y,this.commandOptions));xclaim=(...Y)=>this.chain(new l4(Y,this.commandOptions));xautoclaim=(...Y)=>this.chain(new k4(Y,this.commandOptions));xtrim=(...Y)=>this.chain(new r4(Y,this.commandOptions));xrange=(...Y)=>this.chain(new p4(Y,this.commandOptions));xrevrange=(...Y)=>this.chain(new d4(Y,this.commandOptions));zcard=(...Y)=>this.chain(new o4(Y,this.commandOptions));zcount=(...Y)=>this.chain(new a4(Y,this.commandOptions));zincrby=(Y,W,$)=>this.chain(new e4([Y,W,$],this.commandOptions));zinterstore=(...Y)=>this.chain(new m4(Y,this.commandOptions));zlexcount=(...Y)=>this.chain(new s4(Y,this.commandOptions));zmscore=(...Y)=>this.chain(new JW(Y,this.commandOptions));zpopmax=(...Y)=>this.chain(new YW(Y,this.commandOptions));zpopmin=(...Y)=>this.chain(new WW(Y,this.commandOptions));zrange=(...Y)=>this.chain(new $W(Y,this.commandOptions));zrank=(Y,W)=>this.chain(new GW([Y,W],this.commandOptions));zrem=(Y,...W)=>this.chain(new QW([Y,...W],this.commandOptions));zremrangebylex=(...Y)=>this.chain(new VW(Y,this.commandOptions));zremrangebyrank=(...Y)=>this.chain(new DW(Y,this.commandOptions));zremrangebyscore=(...Y)=>this.chain(new zW(Y,this.commandOptions));zrevrank=(Y,W)=>this.chain(new HW([Y,W],this.commandOptions));zscan=(...Y)=>this.chain(new ZW(Y,this.commandOptions));zscore=(Y,W)=>this.chain(new TW([Y,W],this.commandOptions));zunionstore=(...Y)=>this.chain(new MW(Y,this.commandOptions));zunion=(...Y)=>this.chain(new XW(Y,this.commandOptions));get json(){return{arrappend:(...Y)=>this.chain(new s0(Y,this.commandOptions)),arrindex:(...Y)=>this.chain(new YY(Y,this.commandOptions)),arrinsert:(...Y)=>this.chain(new WY(Y,this.commandOptions)),arrlen:(...Y)=>this.chain(new $Y(Y,this.commandOptions)),arrpop:(...Y)=>this.chain(new GY(Y,this.commandOptions)),arrtrim:(...Y)=>this.chain(new QY(Y,this.commandOptions)),clear:(...Y)=>this.chain(new VY(Y,this.commandOptions)),del:(...Y)=>this.chain(new DY(Y,this.commandOptions)),forget:(...Y)=>this.chain(new zY(Y,this.commandOptions)),get:(...Y)=>this.chain(new HY(Y,this.commandOptions)),merge:(...Y)=>this.chain(new ZY(Y,this.commandOptions)),mget:(...Y)=>this.chain(new TY(Y,this.commandOptions)),mset:(...Y)=>this.chain(new XY(Y,this.commandOptions)),numincrby:(...Y)=>this.chain(new MY(Y,this.commandOptions)),nummultby:(...Y)=>this.chain(new wY(Y,this.commandOptions)),objkeys:(...Y)=>this.chain(new JY(Y,this.commandOptions)),objlen:(...Y)=>this.chain(new LY(Y,this.commandOptions)),resp:(...Y)=>this.chain(new KY(Y,this.commandOptions)),set:(...Y)=>this.chain(new NY(Y,this.commandOptions)),strappend:(...Y)=>this.chain(new UY(Y,this.commandOptions)),strlen:(...Y)=>this.chain(new hY(Y,this.commandOptions)),toggle:(...Y)=>this.chain(new EY(Y,this.commandOptions)),type:(...Y)=>this.chain(new FY(Y,this.commandOptions))}}get functions(){return{load:(...Y)=>this.chain(new Z0(Y,this.commandOptions)),list:(...Y)=>this.chain(new H0(Y,this.commandOptions)),delete:(...Y)=>this.chain(new D0(Y,this.commandOptions)),flush:()=>this.chain(new z0(this.commandOptions)),stats:()=>this.chain(new T0(this.commandOptions)),call:(...Y)=>this.chain(new $0(Y,this.commandOptions)),callRo:(...Y)=>this.chain(new G0(Y,this.commandOptions))}}},V1=1000,q$=new Set(["arcount","arget","argetrange","argrep","arinfo","arlastitems","arlen","armget","arnext","arop","arscan","get","getrange","mget","strlen","bitcount","bitpos","getbit","hexists","hget","hgetall","hkeys","hlen","hmget","hrandfield","hscan","hstrlen","httl","hvals","hexpiretime","hpexpiretime","hpttl","lindex","llen","lpos","lrange","scard","sdiff","sinter","sintercard","sismember","smembers","smismember","srandmember","sscan","sunion","zcard","zcount","zlexcount","zmscore","zrange","zrank","zrevrank","zscan","zscore","zunion","exists","type","ttl","pttl","randomkey","touch","pfcount","xinfo","xlen","xpending","xrange","xread","xrevrange","geodist","geohash","geopos","geosearch","scriptExists","evalRo","evalshaRo","dbsize","echo","ping","time","scan","keys","arrindex","arrlen","objkeys","objlen","resp","list","stats","callRo"]),O$=new Set(["scan","keys","flushdb","flushall","dbsize","hscan","hgetall","hkeys","lrange","sscan","smembers","xrange","xrevrange","zscan","zrange","exec"]);function C(Y,W="root"){let $=Y;if(!$.autoPipelineExecutor)$.autoPipelineExecutor=new R$($);return new Proxy($,{get:(G,Q)=>{if(Q==="pipelineCounter")return G.autoPipelineExecutor.pipelineCounter;if(W==="root"&&Q==="json")return C(G,"json");if(W==="root"&&Q==="functions")return C(G,"functions");if(W==="root"){let Z=Q in G&&!(Q in G.autoPipelineExecutor.pipeline),T=O$.has(Q);if(Z||T)return G[Q]}let V=G.autoPipelineExecutor.pipeline,z=W==="json"?V.json[Q]:W==="functions"?V.functions[Q]:V[Q];if(typeof z==="function")return(...Z)=>{let T=q$.has(Q)?"read":"write";return G.autoPipelineExecutor.withAutoPipeline(T,(X)=>{(W==="json"?X.json[Q]:W==="functions"?X.functions[Q]:X[Q])(...Z)})};return z}})}var R$=class{pipelinePromises=new WeakMap;activeReadPipeline=null;activeWritePipeline=null;readIndex=0;writeIndex=0;redis;pipeline;pipelineCounter=0;constructor(Y){this.redis=Y,this.pipeline=Y.pipeline()}async withAutoPipeline(Y,W){let $=Y==="read",G=$?this.activeReadPipeline:this.activeWritePipeline,Q=G??this.redis.pipeline();if(!G)if($)this.activeReadPipeline=Q,this.readIndex=0;else this.activeWritePipeline=Q,this.writeIndex=0;let V=$?this.readIndex++:this.writeIndex++;if(W(Q),$&&this.readIndex>=V1)this.activeReadPipeline=null;else if(!$&&this.writeIndex>=V1)this.activeWritePipeline=null;let Z=(await this.deferExecution().then(()=>{if(!this.pipelinePromises.has(Q)){let T=Q.exec({keepErrors:!0});if(this.pipelineCounter+=1,this.pipelinePromises.set(Q,T),this.activeReadPipeline===Q)this.activeReadPipeline=null;if(this.activeWritePipeline===Q)this.activeWritePipeline=null}return this.pipelinePromises.get(Q)}))[V];if(Z.error)throw new h(`Command failed: ${Z.error}`);return Z.result}async deferExecution(){await Promise.resolve(),await Promise.resolve()}},v$=class extends D{constructor(Y,W){let $={Accept:"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};super([],{...W,headers:$,path:["psubscribe",...Y],streamOptions:{isStreaming:!0,onMessage:W?.streamOptions?.onMessage,signal:W?.streamOptions?.signal}})}},D1=class extends EventTarget{subscriptions;client;listeners;opts;constructor(Y,W,$=!1,G){super();this.client=Y,this.subscriptions=new Map,this.listeners=new Map,this.opts=G;for(let Q of W)if($)this.subscribeToPattern(Q);else this.subscribeToChannel(Q)}subscribeToChannel(Y){let W=new AbortController,$=new f$([Y],{streamOptions:{signal:W.signal,onMessage:(G)=>this.handleMessage(G,!1)}});$.exec(this.client).catch((G)=>{if(G.name!=="AbortError")this.dispatchToListeners("error",G)}),this.subscriptions.set(Y,{command:$,controller:W,isPattern:!1})}subscribeToPattern(Y){let W=new AbortController,$=new v$([Y],{streamOptions:{signal:W.signal,onMessage:(G)=>this.handleMessage(G,!0)}});$.exec(this.client).catch((G)=>{if(G.name!=="AbortError")this.dispatchToListeners("error",G)}),this.subscriptions.set(Y,{command:$,controller:W,isPattern:!0})}handleMessage(Y,W){let $=Y.replace(/^data:\s*/,""),G=$.indexOf(","),Q=$.indexOf(",",G+1),V=W?$.indexOf(",",Q+1):-1;if(G!==-1&&Q!==-1){let z=$.slice(0,G);if(W&&z==="pmessage"&&V!==-1){let H=$.slice(G+1,Q),Z=$.slice(Q+1,V),T=$.slice(V+1);try{let X=this.opts?.automaticDeserialization===!1?T:JSON.parse(T);this.dispatchToListeners("pmessage",{pattern:H,channel:Z,message:X}),this.dispatchToListeners(`pmessage:${H}`,{pattern:H,channel:Z,message:X})}catch(X){this.dispatchToListeners("error",Error(`Failed to parse message: ${X}`))}}else{let H=$.slice(G+1,Q),Z=$.slice(Q+1);try{if(z==="subscribe"||z==="psubscribe"||z==="unsubscribe"||z==="punsubscribe"){let T=Number.parseInt(Z);this.dispatchToListeners(z,T)}else{let T=this.opts?.automaticDeserialization===!1?Z:k$(Z);this.dispatchToListeners(z,{channel:H,message:T}),this.dispatchToListeners(`${z}:${H}`,{channel:H,message:T})}}catch(T){this.dispatchToListeners("error",Error(`Failed to parse message: ${T}`))}}}}dispatchToListeners(Y,W){let $=this.listeners.get(Y);if($)for(let G of $)G(W)}on(Y,W){if(!this.listeners.has(Y))this.listeners.set(Y,new Set);this.listeners.get(Y)?.add(W)}removeAllListeners(){this.listeners.clear()}async unsubscribe(Y){if(Y)for(let W of Y){let $=this.subscriptions.get(W);if($){try{$.controller.abort()}catch{}this.subscriptions.delete(W)}}else{for(let W of this.subscriptions.values())try{W.controller.abort()}catch{}this.subscriptions.clear(),this.removeAllListeners()}}getSubscribedChannels(){return[...this.subscriptions.keys()]}},f$=class extends D{constructor(Y,W){let $={Accept:"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};super([],{...W,headers:$,path:["subscribe",...Y],streamOptions:{isStreaming:!0,onMessage:W?.streamOptions?.onMessage,signal:W?.streamOptions?.signal}})}},k$=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},l$=class{script;sha1;initPromise;redis;constructor(Y,W){this.redis=Y,this.script=W,this.sha1="",this.init(W)}init(Y){if(!this.initPromise)this.initPromise=this.digest(Y).then((W)=>{this.sha1=W});return this.initPromise}async eval(Y,W){return await this.init(this.script),await this.redis.eval(this.script,Y,W)}async evalsha(Y,W){return await this.init(this.script),await this.redis.evalsha(this.sha1,Y,W)}async exec(Y,W){return await this.init(this.script),await this.redis.evalsha(this.sha1,Y,W).catch(async(G)=>{if(G instanceof Error&&G.message.toLowerCase().includes("noscript"))return await this.redis.eval(this.script,Y,W);throw G})}async digest(Y){let W=new TextEncoder().encode(Y),$=await _.digest("SHA-1",W);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}},y$=class{script;sha1;initPromise;redis;constructor(Y,W){this.redis=Y,this.sha1="",this.script=W,this.init(W)}init(Y){if(!this.initPromise)this.initPromise=this.digest(Y).then((W)=>{this.sha1=W});return this.initPromise}async evalRo(Y,W){return await this.init(this.script),await this.redis.evalRo(this.script,Y,W)}async evalshaRo(Y,W){return await this.init(this.script),await this.redis.evalshaRo(this.sha1,Y,W)}async exec(Y,W){return await this.init(this.script),await this.redis.evalshaRo(this.sha1,Y,W).catch(async(G)=>{if(G instanceof Error&&G.message.toLowerCase().includes("noscript"))return await this.redis.evalRo(this.script,Y,W);throw G})}async digest(Y){let W=new TextEncoder().encode(Y),$=await _.digest("SHA-1",W);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}},LW=class{client;opts;enableTelemetry;enableAutoPipelining;constructor(Y,W){if(this.client=Y,this.opts=W,this.enableTelemetry=W?.enableTelemetry??!0,W?.readYourWrites===!1)this.client.readYourWrites=!1;this.enableAutoPipelining=W?.enableAutoPipelining??!0}get readYourWritesSyncToken(){return this.client.upstashSyncToken}set readYourWritesSyncToken(Y){this.client.upstashSyncToken=Y}get json(){return{arrappend:(...Y)=>new s0(Y,this.opts).exec(this.client),arrindex:(...Y)=>new YY(Y,this.opts).exec(this.client),arrinsert:(...Y)=>new WY(Y,this.opts).exec(this.client),arrlen:(...Y)=>new $Y(Y,this.opts).exec(this.client),arrpop:(...Y)=>new GY(Y,this.opts).exec(this.client),arrtrim:(...Y)=>new QY(Y,this.opts).exec(this.client),clear:(...Y)=>new VY(Y,this.opts).exec(this.client),del:(...Y)=>new DY(Y,this.opts).exec(this.client),forget:(...Y)=>new zY(Y,this.opts).exec(this.client),get:(...Y)=>new HY(Y,this.opts).exec(this.client),merge:(...Y)=>new ZY(Y,this.opts).exec(this.client),mget:(...Y)=>new TY(Y,this.opts).exec(this.client),mset:(...Y)=>new XY(Y,this.opts).exec(this.client),numincrby:(...Y)=>new MY(Y,this.opts).exec(this.client),nummultby:(...Y)=>new wY(Y,this.opts).exec(this.client),objkeys:(...Y)=>new JY(Y,this.opts).exec(this.client),objlen:(...Y)=>new LY(Y,this.opts).exec(this.client),resp:(...Y)=>new KY(Y,this.opts).exec(this.client),set:(...Y)=>new NY(Y,this.opts).exec(this.client),strappend:(...Y)=>new UY(Y,this.opts).exec(this.client),strlen:(...Y)=>new hY(Y,this.opts).exec(this.client),toggle:(...Y)=>new EY(Y,this.opts).exec(this.client),type:(...Y)=>new FY(Y,this.opts).exec(this.client)}}get functions(){return{load:(...Y)=>new Z0(Y,this.opts).exec(this.client),list:(...Y)=>new H0(Y,this.opts).exec(this.client),delete:(...Y)=>new D0(Y,this.opts).exec(this.client),flush:()=>new z0(this.opts).exec(this.client),stats:()=>new T0(this.opts).exec(this.client),call:(...Y)=>new $0(Y,this.opts).exec(this.client),callRo:(...Y)=>new G0(Y,this.opts).exec(this.client)}}use=(Y)=>{let W=this.client.request.bind(this.client);this.client.request=($)=>Y($,W)};addTelemetry=(Y)=>{if(!this.enableTelemetry)return;try{this.client.mergeTelemetry(Y)}catch{}};createScript(Y,W){return W?.readonly?new y$(this,Y):new l$(this,Y)}get search(){return{createIndex:(Y)=>{return $$(this.client,Y)},index:(Y)=>{return K1(this.client,Y)},alias:{list:()=>{return G$(this.client)},add:({indexName:Y,alias:W})=>{return Q$(this.client,{indexName:Y,alias:W})},delete:({alias:Y})=>{return V$(this.client,{alias:Y})}}}}get vector(){return{createIndex:(Y)=>{return U$(this.client,Y,this.opts)},index:(Y)=>{return h$(this.client,Y,this.opts)}}}pipeline=()=>new Q1({client:this.client,commandOptions:this.opts,multiExec:!1});autoPipeline=()=>{return C(this)};multi=()=>new Q1({client:this.client,commandOptions:this.opts,multiExec:!0});bitfield=(...Y)=>new C1(Y,this.client,this.opts);append=(...Y)=>new h1(Y,this.opts).exec(this.client);arcount=(...Y)=>new E1(Y,this.opts).exec(this.client);ardel=(...Y)=>new F1(Y,this.opts).exec(this.client);ardelrange=(...Y)=>new A1(Y,this.opts).exec(this.client);arget=(...Y)=>new _1(Y,this.opts).exec(this.client);argetrange=(...Y)=>new j1(Y,this.opts).exec(this.client);argrep=(Y,W,$,G)=>new B1([Y,W,$,G],this.opts).exec(this.client);arinfo=(...Y)=>new P1(Y,this.opts).exec(this.client);arinsert=(Y,...W)=>new I1([Y,...W],this.opts).exec(this.client);arlastitems=(...Y)=>new x1(Y,this.opts).exec(this.client);arlen=(...Y)=>new S1(Y,this.opts).exec(this.client);armget=(...Y)=>new b1(Y,this.opts).exec(this.client);armset=(Y,W)=>new q1([Y,W],this.opts).exec(this.client);arnext=(...Y)=>new O1(Y,this.opts).exec(this.client);arop=(Y,W,$,G)=>new R1([Y,W,$,G],this.opts).exec(this.client);arring=(Y,W,...$)=>new v1([Y,W,...$],this.opts).exec(this.client);arscan=(...Y)=>new f1(Y,this.opts).exec(this.client);arseek=(...Y)=>new k1(Y,this.opts).exec(this.client);arset=(Y,W,...$)=>new l1([Y,W,...$],this.opts).exec(this.client);bitcount=(...Y)=>new y1(Y,this.opts).exec(this.client);bitop=(Y,W,$,...G)=>new u1([Y,W,$,...G],this.opts).exec(this.client);bitpos=(...Y)=>new i1(Y,this.opts).exec(this.client);clientSetinfo=(...Y)=>new g1(Y,this.opts).exec(this.client);copy=(...Y)=>new c1(Y,this.opts).exec(this.client);dbsize=()=>new p1(this.opts).exec(this.client);decr=(...Y)=>new n1(Y,this.opts).exec(this.client);decrby=(...Y)=>new t1(Y,this.opts).exec(this.client);del=(...Y)=>new d1(Y,this.opts).exec(this.client);echo=(...Y)=>new r1(Y,this.opts).exec(this.client);evalRo=(...Y)=>new o1(Y,this.opts).exec(this.client);eval=(...Y)=>new a1(Y,this.opts).exec(this.client);evalshaRo=(...Y)=>new e1(Y,this.opts).exec(this.client);evalsha=(...Y)=>new m1(Y,this.opts).exec(this.client);exec=(Y)=>new K(Y,this.opts).exec(this.client);exists=(...Y)=>new s1(Y,this.opts).exec(this.client);expire=(...Y)=>new Y0(Y,this.opts).exec(this.client);expireat=(...Y)=>new W0(Y,this.opts).exec(this.client);flushall=(Y)=>new Q0(Y,this.opts).exec(this.client);flushdb=(...Y)=>new V0(Y,this.opts).exec(this.client);geoadd=(...Y)=>new X0(Y,this.opts).exec(this.client);geopos=(...Y)=>new J0(Y,this.opts).exec(this.client);geodist=(...Y)=>new M0(Y,this.opts).exec(this.client);geohash=(...Y)=>new w0(Y,this.opts).exec(this.client);geosearch=(...Y)=>new L0(Y,this.opts).exec(this.client);geosearchstore=(...Y)=>new K0(Y,this.opts).exec(this.client);get=(...Y)=>new N0(Y,this.opts).exec(this.client);getbit=(...Y)=>new U0(Y,this.opts).exec(this.client);getdel=(...Y)=>new h0(Y,this.opts).exec(this.client);getex=(...Y)=>new E0(Y,this.opts).exec(this.client);getrange=(...Y)=>new F0(Y,this.opts).exec(this.client);getset=(Y,W)=>new A0([Y,W],this.opts).exec(this.client);hdel=(...Y)=>new _0(Y,this.opts).exec(this.client);hexists=(...Y)=>new j0(Y,this.opts).exec(this.client);hexpire=(...Y)=>new B0(Y,this.opts).exec(this.client);hexpireat=(...Y)=>new P0(Y,this.opts).exec(this.client);hexpiretime=(...Y)=>new I0(Y,this.opts).exec(this.client);httl=(...Y)=>new r0(Y,this.opts).exec(this.client);hpexpire=(...Y)=>new S0(Y,this.opts).exec(this.client);hpexpireat=(...Y)=>new b0(Y,this.opts).exec(this.client);hpexpiretime=(...Y)=>new q0(Y,this.opts).exec(this.client);hpttl=(...Y)=>new O0(Y,this.opts).exec(this.client);hpersist=(...Y)=>new x0(Y,this.opts).exec(this.client);hget=(...Y)=>new R0(Y,this.opts).exec(this.client);hgetall=(...Y)=>new v0(Y,this.opts).exec(this.client);hgetdel=(...Y)=>new k0(Y,this.opts).exec(this.client);hgetex=(...Y)=>new l0(Y,this.opts).exec(this.client);hincrby=(...Y)=>new y0(Y,this.opts).exec(this.client);hincrbyfloat=(...Y)=>new C0(Y,this.opts).exec(this.client);hkeys=(...Y)=>new u0(Y,this.opts).exec(this.client);hlen=(...Y)=>new i0(Y,this.opts).exec(this.client);hmget=(...Y)=>new f0(Y,this.opts).exec(this.client);hmset=(Y,W)=>new g0([Y,W],this.opts).exec(this.client);hrandfield=(Y,W,$)=>new U1([Y,W,$],this.opts).exec(this.client);hscan=(...Y)=>new c0(Y,this.opts).exec(this.client);hset=(Y,W)=>new p0([Y,W],this.opts).exec(this.client);hsetex=(...Y)=>new n0(Y,this.opts).exec(this.client);hsetnx=(Y,W,$)=>new t0([Y,W,$],this.opts).exec(this.client);hstrlen=(...Y)=>new d0(Y,this.opts).exec(this.client);hvals=(...Y)=>new o0(Y,this.opts).exec(this.client);incr=(...Y)=>new a0(Y,this.opts).exec(this.client);incrby=(...Y)=>new e0(Y,this.opts).exec(this.client);incrbyfloat=(...Y)=>new m0(Y,this.opts).exec(this.client);keys=(...Y)=>new AY(Y,this.opts).exec(this.client);lindex=(...Y)=>new _Y(Y,this.opts).exec(this.client);linsert=(Y,W,$,G)=>new jY([Y,W,$,G],this.opts).exec(this.client);llen=(...Y)=>new BY(Y,this.opts).exec(this.client);lmove=(...Y)=>new PY(Y,this.opts).exec(this.client);lpop=(...Y)=>new xY(Y,this.opts).exec(this.client);lmpop=(...Y)=>new IY(Y,this.opts).exec(this.client);lpos=(...Y)=>new SY(Y,this.opts).exec(this.client);lpush=(Y,...W)=>new bY([Y,...W],this.opts).exec(this.client);lpushx=(Y,...W)=>new qY([Y,...W],this.opts).exec(this.client);lrange=(...Y)=>new OY(Y,this.opts).exec(this.client);lrem=(Y,W,$)=>new RY([Y,W,$],this.opts).exec(this.client);lset=(Y,W,$)=>new vY([Y,W,$],this.opts).exec(this.client);ltrim=(...Y)=>new fY(Y,this.opts).exec(this.client);mget=(...Y)=>new kY(Y,this.opts).exec(this.client);mset=(Y)=>new lY([Y],this.opts).exec(this.client);msetnx=(Y)=>new yY([Y],this.opts).exec(this.client);persist=(...Y)=>new CY(Y,this.opts).exec(this.client);pexpire=(...Y)=>new uY(Y,this.opts).exec(this.client);pexpireat=(...Y)=>new iY(Y,this.opts).exec(this.client);pfadd=(...Y)=>new gY(Y,this.opts).exec(this.client);pfcount=(...Y)=>new cY(Y,this.opts).exec(this.client);pfmerge=(...Y)=>new pY(Y,this.opts).exec(this.client);ping=(Y)=>new nY(Y,this.opts).exec(this.client);psetex=(Y,W,$)=>new tY([Y,W,$],this.opts).exec(this.client);psubscribe=(Y)=>{let W=Array.isArray(Y)?Y:[Y];return new D1(this.client,W,!0,this.opts)};pttl=(...Y)=>new dY(Y,this.opts).exec(this.client);publish=(...Y)=>new rY(Y,this.opts).exec(this.client);randomkey=()=>new oY().exec(this.client);rename=(...Y)=>new aY(Y,this.opts).exec(this.client);renamenx=(...Y)=>new eY(Y,this.opts).exec(this.client);rpop=(...Y)=>new mY(Y,this.opts).exec(this.client);rpush=(Y,...W)=>new sY([Y,...W],this.opts).exec(this.client);rpushx=(Y,...W)=>new Y4([Y,...W],this.opts).exec(this.client);sadd=(Y,W,...$)=>new W4([Y,W,...$],this.opts).exec(this.client);scan(Y,W){return new $4([Y,W],this.opts).exec(this.client)}scard=(...Y)=>new G4(Y,this.opts).exec(this.client);scriptExists=(...Y)=>new Q4(Y,this.opts).exec(this.client);scriptFlush=(...Y)=>new V4(Y,this.opts).exec(this.client);scriptLoad=(...Y)=>new D4(Y,this.opts).exec(this.client);sdiff=(...Y)=>new z4(Y,this.opts).exec(this.client);sdiffstore=(...Y)=>new H4(Y,this.opts).exec(this.client);set=(Y,W,$)=>new Z4([Y,W,$],this.opts).exec(this.client);setbit=(...Y)=>new T4(Y,this.opts).exec(this.client);setex=(Y,W,$)=>new X4([Y,W,$],this.opts).exec(this.client);setnx=(Y,W)=>new M4([Y,W],this.opts).exec(this.client);setrange=(...Y)=>new w4(Y,this.opts).exec(this.client);sinter=(...Y)=>new J4(Y,this.opts).exec(this.client);sintercard=(...Y)=>new L4(Y,this.opts).exec(this.client);sinterstore=(...Y)=>new K4(Y,this.opts).exec(this.client);sismember=(Y,W)=>new N4([Y,W],this.opts).exec(this.client);smismember=(Y,W)=>new h4([Y,W],this.opts).exec(this.client);smembers=(...Y)=>new U4(Y,this.opts).exec(this.client);smove=(Y,W,$)=>new E4([Y,W,$],this.opts).exec(this.client);spop=(...Y)=>new F4(Y,this.opts).exec(this.client);srandmember=(...Y)=>new A4(Y,this.opts).exec(this.client);srem=(Y,...W)=>new _4([Y,...W],this.opts).exec(this.client);sscan=(...Y)=>new j4(Y,this.opts).exec(this.client);strlen=(...Y)=>new B4(Y,this.opts).exec(this.client);subscribe=(Y)=>{let W=Array.isArray(Y)?Y:[Y];return new D1(this.client,W,!1,this.opts)};sunion=(...Y)=>new P4(Y,this.opts).exec(this.client);sunionstore=(...Y)=>new I4(Y,this.opts).exec(this.client);time=()=>new x4().exec(this.client);touch=(...Y)=>new S4(Y,this.opts).exec(this.client);ttl=(...Y)=>new b4(Y,this.opts).exec(this.client);type=(...Y)=>new q4(Y,this.opts).exec(this.client);unlink=(...Y)=>new O4(Y,this.opts).exec(this.client);xadd=(...Y)=>new f4(Y,this.opts).exec(this.client);xack=(...Y)=>new R4(Y,this.opts).exec(this.client);xackdel=(...Y)=>new v4(Y,this.opts).exec(this.client);xdel=(...Y)=>new y4(Y,this.opts).exec(this.client);xdelex=(...Y)=>new C4(Y,this.opts).exec(this.client);xgroup=(...Y)=>new u4(Y,this.opts).exec(this.client);xread=(...Y)=>new n4(Y,this.opts).exec(this.client);xreadgroup=(...Y)=>new t4(Y,this.opts).exec(this.client);xinfo=(...Y)=>new i4(Y,this.opts).exec(this.client);xlen=(...Y)=>new g4(Y,this.opts).exec(this.client);xpending=(...Y)=>new c4(Y,this.opts).exec(this.client);xclaim=(...Y)=>new l4(Y,this.opts).exec(this.client);xautoclaim=(...Y)=>new k4(Y,this.opts).exec(this.client);xtrim=(...Y)=>new r4(Y,this.opts).exec(this.client);xrange=(...Y)=>new p4(Y,this.opts).exec(this.client);xrevrange=(...Y)=>new d4(Y,this.opts).exec(this.client);zadd=(...Y)=>{if("score"in Y[1])return new B([Y[0],Y[1],...Y.slice(2)],this.opts).exec(this.client);return new B([Y[0],Y[1],...Y.slice(2)],this.opts).exec(this.client)};zcard=(...Y)=>new o4(Y,this.opts).exec(this.client);zcount=(...Y)=>new a4(Y,this.opts).exec(this.client);zdiffstore=(...Y)=>new wW(Y,this.opts).exec(this.client);zincrby=(Y,W,$)=>new e4([Y,W,$],this.opts).exec(this.client);zinterstore=(...Y)=>new m4(Y,this.opts).exec(this.client);zlexcount=(...Y)=>new s4(Y,this.opts).exec(this.client);zmscore=(...Y)=>new JW(Y,this.opts).exec(this.client);zpopmax=(...Y)=>new YW(Y,this.opts).exec(this.client);zpopmin=(...Y)=>new WW(Y,this.opts).exec(this.client);zrange=(...Y)=>new $W(Y,this.opts).exec(this.client);zrank=(Y,W)=>new GW([Y,W],this.opts).exec(this.client);zrem=(Y,...W)=>new QW([Y,...W],this.opts).exec(this.client);zremrangebylex=(...Y)=>new VW(Y,this.opts).exec(this.client);zremrangebyrank=(...Y)=>new DW(Y,this.opts).exec(this.client);zremrangebyscore=(...Y)=>new zW(Y,this.opts).exec(this.client);zrevrank=(Y,W)=>new HW([Y,W],this.opts).exec(this.client);zscan=(...Y)=>new ZW(Y,this.opts).exec(this.client);zscore=(Y,W)=>new TW([Y,W],this.opts).exec(this.client);zunion=(...Y)=>new XW(Y,this.opts).exec(this.client);zunionstore=(...Y)=>new MW(Y,this.opts).exec(this.client)},KW="v1.39.0";if(typeof atob>"u")global.atob=(Y)=>Buffer.from(Y,"base64").toString("utf8");var NW=class Y extends LW{constructor(W){if("request"in W){super(W);return}if(!W.url)console.warn("[Upstash Redis] The 'url' property is missing or undefined in your Redis config. To create a database instantly (no signup needed), run: curl -X POST https://upstash.com/start-redis");else if(W.url.startsWith(" ")||W.url.endsWith(" ")||/\r|\n/.test(W.url))console.warn("[Upstash Redis] The redis url contains whitespace or newline, which can cause errors!");if(!W.token)console.warn("[Upstash Redis] The 'token' property is missing or undefined in your Redis config. To create a database instantly (no signup needed), run: curl -X POST https://upstash.com/start-redis");else if(W.token.startsWith(" ")||W.token.endsWith(" ")||/\r|\n/.test(W.token))console.warn("[Upstash Redis] The redis token contains whitespace or newline, which can cause errors!");let $=new T1({baseUrl:W.url,retry:W.retry,headers:{authorization:`Bearer ${W.token}`},agent:W.agent,responseEncoding:W.responseEncoding,cache:W.cache??"no-store",signal:W.signal,keepAlive:W.keepAlive,readYourWrites:W.readYourWrites}),G=typeof process==="object"&&process&&typeof process.env==="object"&&process.env?process.env:{};super($,{automaticDeserialization:W.automaticDeserialization,enableTelemetry:W.enableTelemetry??!G.UPSTASH_DISABLE_TELEMETRY,latencyLogging:W.latencyLogging,enableAutoPipelining:W.enableAutoPipelining});let Q=typeof process==="object"&&process?process.version:void 0;if(this.addTelemetry({runtime:typeof EdgeRuntime==="string"?"edge-light":Q?`node@${Q}`:"unknown",platform:G.UPSTASH_CONSOLE?"console":G.VERCEL?"vercel":G.AWS_REGION?"aws":"unknown",sdk:`@upstash/redis@${KW}`}),this.enableAutoPipelining)return this.autoPipeline()}static fromEnv(W){if(typeof process!=="object"||!process||typeof process.env!=="object"||!process.env)throw TypeError('[Upstash Redis] Unable to get environment variables, `process.env` is undefined. If you are deploying to cloudflare, please import from "@upstash/redis/cloudflare" instead');let $=process.env.UPSTASH_REDIS_REST_URL||process.env.KV_REST_API_URL;if(!$)console.warn("[Upstash Redis] Unable to find environment variable: `UPSTASH_REDIS_REST_URL`. To create a database instantly (no signup needed), run: curl -X POST https://upstash.com/start-redis");let G=process.env.UPSTASH_REDIS_REST_TOKEN||process.env.KV_REST_API_TOKEN;if(!G)console.warn("[Upstash Redis] Unable to find environment variable: `UPSTASH_REDIS_REST_TOKEN`. To create a database instantly (no signup needed), run: curl -X POST https://upstash.com/start-redis");return new Y({...W,url:$,token:G})}};class UW{options;type="cache";name="RedisDriver";tcpClient;httpClient;prefix;logger;constructor(Y){this.options=Y;this.logger=new L}initClients(){if(this.options.protocol==="http")this.httpClient=new NW({url:this.options.url,token:this.options.token});else this.tcpClient=new C$(this.options.connectionString,{lazyConnect:!0,maxRetriesPerRequest:3})}setKeyPrefix(Y){this.prefix=Y}async connect(){if(this.options.protocol=="tcp"){if(!this.tcpClient)this.initClients();if(!this.tcpClient)throw Error("TCP Client could not found");let Y=this.tcpClient.status;if(Y==="end"||Y==="close")this.initClients();if(this.tcpClient.status==="wait")await this.tcpClient.connect(),this.logger.log(`[RedisDriver] : TCP Connected to ${this.options.connectionString}`)}else if(this.options.protocol=="http"){if(!this.httpClient)this.initClients();let Y=await this.httpClient.ping();if(Y.toLowerCase()==="pong")this.logger.log("[RedisDriver] : HTTP REST client initialized.");else this.logger.warn("[RedisDriver] : HTTP REST client initialized, but ping failed with unexpected response:",Y)}}async disconnect(){if(this.options.protocol=="tcp"&&this.tcpClient){let Y=this.tcpClient.status;if(Y!=="end"&&Y!=="close")try{await this.tcpClient.quit(),this.logger.log("[RedisDriver] : TCP Disconnected.")}catch(W){this.tcpClient.disconnect()}}}async healthCheck(){let Y=Date.now();try{if(this.options.protocol==="tcp")await this.tcpClient.ping();else await this.httpClient.ping();return{status:"up",latencyMs:Date.now()-Y}}catch(W){return{status:"down",latencyMs:Date.now()-Y,details:{error:W.message}}}}getNativeClient(Y){if((Y??this.options.protocol)==="tcp"){if(!this.tcpClient)throw Error("[RedisDriver] : TCP client is not initialized.");return this.tcpClient}if(!this.httpClient)throw Error("[RedisDriver] : REST client is not initialized.");return this.httpClient}}export{UW as RedisDriver,s as PulsarUnifiedStorage,Y1 as PostgresDriver};
392
+
393
+ //# debugId=B8D815BEE0FC7A9E64756E2164756E21