@crvouga/mockingbird-service-redis 2.14.0 → 2.15.0

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.
@@ -10,6 +10,7 @@ import {
10
10
  err,
11
11
  execAbort,
12
12
  execWithoutMulti,
13
+ formatScore,
13
14
  fromLatin1,
14
15
  globMatch,
15
16
  int,
@@ -42,7 +43,7 @@ import {
42
43
  utf8Text,
43
44
  wrongPass,
44
45
  wrongType
45
- } from "./chunk-PJCRB2CA.js";
46
+ } from "./chunk-G64ZBC4S.js";
46
47
 
47
48
  // src/clock.ts
48
49
  function manualClock(start = 0) {
@@ -100,12 +101,182 @@ function controlledClock(start) {
100
101
  };
101
102
  }
102
103
 
104
+ // src/bits.ts
105
+ var BITS_WRITES = ["setbit", "pfadd", "pfmerge"];
106
+ var text = (bytes2) => bytes2 ? latin1(bytes2) : "";
107
+ var MAX_BIT_OFFSET = 4294967295n;
108
+ function stringAt(database, key) {
109
+ const value = database.get(key);
110
+ if (!value) return null;
111
+ return value.kind === "string" ? value.bytes : wrongType();
112
+ }
113
+ var isReply = (value) => typeof value === "object" && value !== null && "t" in value && !(value instanceof Uint8Array);
114
+ function bitOffset(raw2) {
115
+ const parsed = parseI64(raw2 ?? utf8(""));
116
+ if (parsed === null || parsed < 0n || parsed > MAX_BIT_OFFSET) return null;
117
+ return Number(parsed);
118
+ }
119
+ var offsetError = () => err("ERR bit offset is not an integer or out of range");
120
+ function cmdSetbit(database, args, apply) {
121
+ if (args.length !== 3) return arityError("setbit");
122
+ const offset = bitOffset(args[1]);
123
+ if (offset === null) return offsetError();
124
+ const bitText = text(args[2]);
125
+ if (bitText !== "0" && bitText !== "1") return err("ERR bit is not an integer or out of range");
126
+ const key = text(args[0]);
127
+ const current = stringAt(database, key);
128
+ if (isReply(current)) return current;
129
+ if (!apply) return queued();
130
+ const byte = offset >> 3;
131
+ const mask = 1 << 7 - (offset & 7);
132
+ let bytes2 = current ?? new Uint8Array(0);
133
+ if (bytes2.length <= byte) {
134
+ const grown = new Uint8Array(byte + 1);
135
+ grown.set(bytes2);
136
+ bytes2 = grown;
137
+ } else bytes2 = Uint8Array.from(bytes2);
138
+ const previous = (bytes2[byte] ?? 0) & mask ? 1 : 0;
139
+ bytes2[byte] = bitText === "1" ? (bytes2[byte] ?? 0) | mask : (bytes2[byte] ?? 0) & ~mask;
140
+ database.put(key, { kind: "string", bytes: bytes2 });
141
+ return int(previous);
142
+ }
143
+ function cmdGetbit(database, args) {
144
+ if (args.length !== 2) return arityError("getbit");
145
+ const offset = bitOffset(args[1]);
146
+ if (offset === null) return offsetError();
147
+ const current = stringAt(database, text(args[0]));
148
+ if (isReply(current)) return current;
149
+ const byte = current?.[offset >> 3] ?? 0;
150
+ return int(byte & 1 << 7 - (offset & 7) ? 1 : 0);
151
+ }
152
+ var popcount = (byte) => {
153
+ let count = 0;
154
+ for (let value = byte; value; value &= value - 1) count++;
155
+ return count;
156
+ };
157
+ function cmdBitcount(database, args) {
158
+ if (args.length < 1) return arityError("bitcount");
159
+ if (args.length === 2 || args.length > 4) return syntaxError();
160
+ let bitMode = false;
161
+ if (args.length === 4) {
162
+ const unit = text(args[3]).toUpperCase();
163
+ if (unit === "BIT") bitMode = true;
164
+ else if (unit !== "BYTE") return syntaxError();
165
+ }
166
+ const start = args.length >= 3 ? parseI64(args[1] ?? utf8("")) : 0n;
167
+ const end = args.length >= 3 ? parseI64(args[2] ?? utf8("")) : -1n;
168
+ if (start === null || end === null) return notInteger();
169
+ const current = stringAt(database, text(args[0]));
170
+ if (isReply(current)) return current;
171
+ if (!current) return int(0);
172
+ const length2 = BigInt(bitMode ? current.length * 8 : current.length);
173
+ let from = start < 0n ? length2 + start : start;
174
+ let to = end < 0n ? length2 + end : end;
175
+ if (from < 0n) from = 0n;
176
+ if (to < 0n) to = 0n;
177
+ if (to >= length2) to = length2 - 1n;
178
+ if (from > to) return int(0);
179
+ let count = 0;
180
+ if (!bitMode) {
181
+ for (let i = Number(from); i <= Number(to); i++) count += popcount(current[i] ?? 0);
182
+ return int(count);
183
+ }
184
+ for (let bit = Number(from); bit <= Number(to); bit++)
185
+ if ((current[bit >> 3] ?? 0) & 1 << 7 - (bit & 7)) count++;
186
+ return int(count);
187
+ }
188
+ var HEADER = Uint8Array.from([72, 89, 76, 76, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
189
+ var notHll = () => err("WRONGTYPE Key is not a valid HyperLogLog string value.");
190
+ function decodeHll(bytes2) {
191
+ if (bytes2.length < HEADER.length) return null;
192
+ for (let i = 0; i < HEADER.length; i++) if (bytes2[i] !== HEADER[i]) return null;
193
+ const members = /* @__PURE__ */ new Set();
194
+ const view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength);
195
+ let at = HEADER.length;
196
+ while (at < bytes2.length) {
197
+ if (at + 4 > bytes2.length) return null;
198
+ const size2 = view.getUint32(at);
199
+ at += 4;
200
+ if (at + size2 > bytes2.length) return null;
201
+ members.add(latin1(bytes2.subarray(at, at + size2)));
202
+ at += size2;
203
+ }
204
+ return members;
205
+ }
206
+ function encodeHll(members) {
207
+ const parts = [...members].sort();
208
+ let size2 = HEADER.length;
209
+ for (const member of parts) size2 += 4 + member.length;
210
+ const out = new Uint8Array(size2);
211
+ out.set(HEADER);
212
+ const view = new DataView(out.buffer);
213
+ let at = HEADER.length;
214
+ for (const member of parts) {
215
+ view.setUint32(at, member.length);
216
+ at += 4;
217
+ for (let i = 0; i < member.length; i++) out[at++] = member.charCodeAt(i);
218
+ }
219
+ return out;
220
+ }
221
+ function hllAt(database, key) {
222
+ const value = database.get(key);
223
+ if (!value) return null;
224
+ if (value.kind !== "string") return wrongType();
225
+ return decodeHll(value.bytes) ?? notHll();
226
+ }
227
+ var isSet = (value) => value instanceof Set;
228
+ function writeHll(database, key, members) {
229
+ database.put(key, { kind: "string", bytes: encodeHll(members) });
230
+ }
231
+ function cmdPfadd(database, args, apply) {
232
+ if (args.length < 1) return arityError("pfadd");
233
+ const key = text(args[0]);
234
+ const current = hllAt(database, key);
235
+ if (current !== null && !isSet(current)) return current;
236
+ if (!apply) return queued();
237
+ const members = current ?? /* @__PURE__ */ new Set();
238
+ let changed = current === null;
239
+ for (const arg of args.slice(1)) {
240
+ const member = latin1(arg);
241
+ if (members.has(member)) continue;
242
+ members.add(member);
243
+ changed = true;
244
+ }
245
+ if (changed) writeHll(database, key, members);
246
+ return int(changed ? 1 : 0);
247
+ }
248
+ function cmdPfcount(database, args) {
249
+ if (args.length < 1) return arityError("pfcount");
250
+ const union = /* @__PURE__ */ new Set();
251
+ for (const arg of args) {
252
+ const members = hllAt(database, text(arg));
253
+ if (members === null) continue;
254
+ if (!isSet(members)) return members;
255
+ for (const member of members) union.add(member);
256
+ }
257
+ return int(union.size);
258
+ }
259
+ function cmdPfmerge(database, args, apply) {
260
+ if (args.length < 1) return arityError("pfmerge");
261
+ const union = /* @__PURE__ */ new Set();
262
+ for (const arg of args) {
263
+ const members = hllAt(database, text(arg));
264
+ if (members === null) continue;
265
+ if (!isSet(members)) return members;
266
+ for (const member of members) union.add(member);
267
+ }
268
+ if (!apply) return queued();
269
+ writeHll(database, text(args[0]), union);
270
+ return ok();
271
+ }
272
+
103
273
  // src/command-table.ts
104
274
  var ROWS = [
105
275
  "acl -2 0 0 0 @slow A container for Access List Control commands. 6.0.0 server Depends on subcommand.",
106
276
  "append 3 write denyoom fast 1 1 1 @write @string @fast Appends a string to the value of a key. Creates the key if it doesn't exist. 2.0.0 string O(1). The amortized time complexity is O(1) assuming the appended value is small and the already present value is of any size, since the dynamic string library used by Redis will double the free space available on every reallocation.",
107
277
  "asking 1 fast 0 0 0 @fast @connection Signals that a cluster client is following an -ASK redirect. 3.0.0 cluster O(1)",
108
278
  "auth -2 noscript loading stale fast no_auth allow_busy 0 0 0 @fast @connection Authenticates the connection. 1.0.0 connection O(N) where N is the number of passwords defined for the user",
279
+ "bitcount -2 readonly 1 1 1 @read @bitmap @slow Counts the number of set bits (population counting) in a string. 2.6.0 bitmap O(N)",
109
280
  "blmove 6 write denyoom blocking 1 2 1 @write @list @slow @blocking Pops an element from a list, pushes it to another list and returns it. Blocks until an element is available otherwise. Deletes the list if the last element was moved. 6.2.0 list O(1)",
110
281
  "blpop -3 write blocking 1 -2 1 @write @list @slow @blocking Removes and returns the first element in a list. Blocks until an element is available otherwise. Deletes the list if the last element was popped. 2.0.0 list O(N) where N is the number of provided keys.",
111
282
  "brpop -3 write blocking 1 -2 1 @write @list @slow @blocking Removes and returns the last element in a list. Blocks until an element is available otherwise. Deletes the list if the last element was popped. 2.0.0 list O(N) where N is the number of provided keys.",
@@ -124,15 +295,21 @@ var ROWS = [
124
295
  "discard 1 noscript loading stale fast allow_busy 0 0 0 @fast @transaction Discards a transaction. 2.0.0 transactions O(N), when N is the number of queued commands",
125
296
  "echo 2 loading stale fast 0 0 0 @fast @connection Returns the given string. 1.0.0 connection O(1)",
126
297
  "eval -3 noscript stale skip_monitor no_mandatory_keys movablekeys 0 0 0 @slow @scripting Executes a server-side Lua script. 2.6.0 scripting Depends on the script that is executed.",
298
+ "eval_ro -3 readonly noscript stale skip_monitor no_mandatory_keys movablekeys 0 0 0 @slow @scripting Executes a read-only server-side Lua script. 7.0.0 scripting Depends on the script that is executed.",
127
299
  "evalsha -3 noscript stale skip_monitor no_mandatory_keys movablekeys 0 0 0 @slow @scripting Executes a server-side Lua script by SHA1 digest. 2.6.0 scripting Depends on the script that is executed.",
300
+ "evalsha_ro -3 readonly noscript stale skip_monitor no_mandatory_keys movablekeys 0 0 0 @slow @scripting Executes a read-only server-side Lua script by SHA1 digest. 7.0.0 scripting Depends on the script that is executed.",
128
301
  "exec 1 noscript loading stale skip_slowlog 0 0 0 @slow @transaction Executes all commands in a transaction. 1.2.0 transactions Depends on commands in the transaction",
129
302
  "exists -2 readonly fast 1 -1 1 @keyspace @read @fast Determines whether one or more keys exist. 1.0.0 generic O(N) where N is the number of keys to check.",
130
303
  "expire -3 write fast 1 1 1 @keyspace @write @fast Sets the expiration time of a key in seconds. 1.0.0 generic O(1)",
131
304
  "expireat -3 write fast 1 1 1 @keyspace @write @fast Sets the expiration time of a key to a Unix timestamp. 1.2.0 generic O(1)",
132
305
  "expiretime 2 readonly fast 1 1 1 @keyspace @read @fast Returns the expiration time of a key as a Unix timestamp. 7.0.0 generic O(1)",
306
+ "fcall -3 noscript stale skip_monitor no_mandatory_keys movablekeys 0 0 0 @slow @scripting Invokes a function. 7.0.0 scripting Depends on the function that is executed.",
307
+ "fcall_ro -3 readonly noscript stale skip_monitor no_mandatory_keys movablekeys 0 0 0 @slow @scripting Invokes a read-only function. 7.0.0 scripting Depends on the function that is executed.",
133
308
  "flushall -1 write 0 0 0 @keyspace @write @slow @dangerous Removes all keys from all databases. 1.0.0 server O(N) where N is the total number of keys in all databases",
134
309
  "flushdb -1 write 0 0 0 @keyspace @write @slow @dangerous Remove all keys from the current database. 1.0.0 server O(N) where N is the number of keys in the selected database",
310
+ "function -2 0 0 0 @slow A container for function commands. 7.0.0 scripting Depends on subcommand.",
135
311
  "get 2 readonly fast 1 1 1 @read @string @fast Returns the string value of a key. 1.0.0 string O(1)",
312
+ "getbit 3 readonly fast 1 1 1 @read @bitmap @fast Returns a bit value by offset. 2.2.0 bitmap O(1)",
136
313
  "getdel 2 write fast 1 1 1 @write @string @fast Returns the string value of a key after deleting the key. 6.2.0 string O(1)",
137
314
  "getex -2 write fast 1 1 1 @write @string @fast Returns the string value of a key after setting its expiration time. 6.2.0 string O(1)",
138
315
  "getrange 4 readonly 1 1 1 @read @string @slow Returns a substring of the string stored at a key. 2.4.0 string O(N) where N is the length of the returned string. The complexity is ultimately determined by the returned length, but because creating a substring from an existing string is very cheap, it can be considered O(1) for small strings.",
@@ -175,6 +352,7 @@ var ROWS = [
175
352
  "lpop -2 write fast 1 1 1 @write @list @fast Returns the first elements in a list after removing it. Deletes the list if the last element was popped. 1.0.0 list O(N) where N is the number of elements returned",
176
353
  "lpos -3 readonly 1 1 1 @read @list @slow Returns the index of matching elements in a list. 6.0.6 list O(N) where N is the number of elements in the list, for the average case. When searching for elements near the head or the tail of the list, or when the MAXLEN option is provided, the command may run in constant time.",
177
354
  "lpush -3 write denyoom fast 1 1 1 @write @list @fast Prepends one or more elements to a list. Creates the key if it doesn't exist. 1.0.0 list O(1) for each element added, so O(N) to add N elements when the command is called with multiple arguments.",
355
+ "lpushx -3 write denyoom fast 1 1 1 @write @list @fast Prepends one or more elements to a list only when the list exists. 2.2.0 list O(1) for each element added, so O(N) to add N elements when the command is called with multiple arguments.",
178
356
  "lrange 4 readonly 1 1 1 @read @list @slow Returns a range of elements from a list. 1.0.0 list O(S+N) where S is the distance of start offset from HEAD for small lists, from nearest end (HEAD or TAIL) for large lists; and N is the number of elements in the specified range.",
179
357
  "lrem 4 write 1 1 1 @write @list @slow Removes elements from a list. Deletes the list if the last element was removed. 1.0.0 list O(N+M) where N is the length of the list and M is the number of elements removed.",
180
358
  "lset 4 write denyoom 1 1 1 @write @list @slow Sets the value of an element in a list by its index. 1.0.0 list O(N) where N is the length of the list. Setting either the first or the last element of the list is O(1).",
@@ -191,6 +369,9 @@ var ROWS = [
191
369
  "pexpire -3 write fast 1 1 1 @keyspace @write @fast Sets the expiration time of a key in milliseconds. 2.6.0 generic O(1)",
192
370
  "pexpireat -3 write fast 1 1 1 @keyspace @write @fast Sets the expiration time of a key to a Unix milliseconds timestamp. 2.6.0 generic O(1)",
193
371
  "pexpiretime 2 readonly fast 1 1 1 @keyspace @read @fast Returns the expiration time of a key as a Unix milliseconds timestamp. 7.0.0 generic O(1)",
372
+ "pfadd -2 write denyoom fast 1 1 1 @write @hyperloglog @fast Adds elements to a HyperLogLog key. Creates the key if it doesn't exist. 2.8.9 hyperloglog O(1) to add every element.",
373
+ "pfcount -2 readonly 1 -1 1 @read @hyperloglog @slow Returns the approximated cardinality of the set(s) observed by the HyperLogLog key(s). 2.8.9 hyperloglog O(1) with a very small average constant time when called with a single key. O(N) with N being the number of keys, and much bigger constant times, when called with multiple keys.",
374
+ "pfmerge -2 write denyoom 1 -1 1 @write @hyperloglog @slow Merges one or more HyperLogLog values into a single key. 2.8.9 hyperloglog O(N) to merge N HyperLogLogs, but with high constant times.",
194
375
  "ping -1 fast 0 0 0 @fast @connection Returns the server's liveliness response. 1.0.0 connection O(1)",
195
376
  "psetex 4 write denyoom 1 1 1 @write @string @slow Sets both string value and expiration time in milliseconds of a key. The key is created if it doesn't exist. 2.6.0 string O(1)",
196
377
  "psubscribe -2 pubsub noscript loading stale 0 0 0 @pubsub @slow Listens for messages published to channels that match one or more patterns. 2.0.0 pubsub O(N) where N is the number of patterns to subscribe to.",
@@ -208,36 +389,47 @@ var ROWS = [
208
389
  "rpop -2 write fast 1 1 1 @write @list @fast Returns and removes the last elements of a list. Deletes the list if the last element was popped. 1.0.0 list O(N) where N is the number of elements returned",
209
390
  "rpoplpush 3 write denyoom 1 2 1 @write @list @slow Returns the last element of a list after removing and pushing it to another list. Deletes the list if the last element was popped. 1.2.0 list O(1)",
210
391
  "rpush -3 write denyoom fast 1 1 1 @write @list @fast Appends one or more elements to a list. Creates the key if it doesn't exist. 1.0.0 list O(1) for each element added, so O(N) to add N elements when the command is called with multiple arguments.",
392
+ "rpushx -3 write denyoom fast 1 1 1 @write @list @fast Appends an element to a list only when the list exists. 2.2.0 list O(1) for each element added, so O(N) to add N elements when the command is called with multiple arguments.",
211
393
  "sadd -3 write denyoom fast 1 1 1 @write @set @fast Adds one or more members to a set. Creates the key if it doesn't exist. 1.0.0 set O(1) for each element added, so O(N) to add N elements when the command is called with multiple arguments.",
212
394
  "scan -2 readonly 0 0 0 @keyspace @read @slow Iterates over the key names in the database. 2.8.0 generic O(1) for every call. O(N) for a complete iteration, including enough command calls for the cursor to return back to 0. N is the number of elements inside the collection.",
213
395
  "scard 2 readonly fast 1 1 1 @read @set @fast Returns the number of members in a set. 1.0.0 set O(1)",
214
396
  "script -2 0 0 0 @slow A container for Lua scripts management commands. 2.6.0 scripting Depends on subcommand.",
215
397
  "sdiff -2 readonly 1 -1 1 @read @set @slow Returns the difference of multiple sets. 1.0.0 set O(N) where N is the total number of elements in all given sets.",
398
+ "sdiffstore -3 write denyoom 1 -1 1 @write @set @slow Stores the difference of multiple sets in a key. 1.0.0 set O(N) where N is the total number of elements in all given sets.",
216
399
  "select 2 loading stale fast 0 0 0 @fast @connection Changes the selected database. 1.0.0 connection O(1)",
217
400
  "set -3 write denyoom 1 1 1 @write @string @slow Sets the string value of a key, ignoring its type. The key is created if it doesn't exist. 1.0.0 string O(1)",
401
+ "setbit 4 write denyoom 1 1 1 @write @bitmap @slow Sets or clears the bit at offset of the string value. Creates the key if it doesn't exist. 2.2.0 bitmap O(1)",
218
402
  "setex 4 write denyoom 1 1 1 @write @string @slow Sets the string value and expiration time of a key. Creates the key if it doesn't exist. 2.0.0 string O(1)",
219
403
  "setnx 3 write denyoom fast 1 1 1 @write @string @fast Set the string value of a key only when the key doesn't exist. 1.0.0 string O(1)",
220
404
  "setrange 4 write denyoom 1 1 1 @write @string @slow Overwrites a part of a string value with another by an offset. Creates the key if it doesn't exist. 2.2.0 string O(1), not counting the time taken to copy the new string in place. Usually, this string is very small so the amortized complexity is O(1). Otherwise, complexity is O(M) with M being the length of the value argument.",
221
405
  "shutdown -1 admin noscript loading stale no_multi allow_busy 0 0 0 @admin @slow @dangerous Synchronously saves the database(s) to disk and shuts down the Redis server. 1.0.0 server O(N) when saving, where N is the total number of keys in all databases when saving data, otherwise O(1)",
222
406
  "sinter -2 readonly 1 -1 1 @read @set @slow Returns the intersect of multiple sets. 1.0.0 set O(N*M) worst case where N is the cardinality of the smallest set and M is the number of sets.",
407
+ "sintercard -3 readonly movablekeys 0 0 0 @read @set @slow Returns the number of members of the intersect of multiple sets. 7.0.0 set O(N*M) worst case where N is the cardinality of the smallest set and M is the number of sets.",
408
+ "sinterstore -3 write denyoom 1 -1 1 @write @set @slow Stores the intersect of multiple sets in a key. 1.0.0 set O(N*M) worst case where N is the cardinality of the smallest set and M is the number of sets.",
223
409
  "sismember 3 readonly fast 1 1 1 @read @set @fast Determines whether a member belongs to a set. 1.0.0 set O(1)",
224
410
  "slowlog -2 0 0 0 @slow A container for slow log commands. 2.2.12 server Depends on subcommand.",
225
411
  "smembers 2 readonly 1 1 1 @read @set @slow Returns all members of a set. 1.0.0 set O(N) where N is the set cardinality.",
226
412
  "smismember -3 readonly fast 1 1 1 @read @set @fast Determines whether multiple members belong to a set. 6.2.0 set O(N) where N is the number of elements being checked for membership",
227
413
  "smove 4 write fast 1 2 1 @write @set @fast Moves a member from one set to another. 1.0.0 set O(1)",
228
414
  "spop -2 write fast 1 1 1 @write @set @fast Returns one or more random members from a set after removing them. Deletes the set if the last member was popped. 1.0.0 set Without the count argument O(1), otherwise O(N) where N is the value of the passed count.",
415
+ "spublish 3 pubsub loading stale fast 1 1 1 @pubsub @fast Post a message to a shard channel 7.0.0 pubsub O(N) where N is the number of clients subscribed to the receiving shard channel.",
229
416
  "srandmember -2 readonly 1 1 1 @read @set @slow Get one or multiple random members from a set 1.0.0 set Without the count argument O(1), otherwise O(N) where N is the absolute value of the passed count.",
230
417
  "srem -3 write fast 1 1 1 @write @set @fast Removes one or more members from a set. Deletes the set if the last member was removed. 1.0.0 set O(N) where N is the number of members to be removed.",
231
418
  "sscan -3 readonly 1 1 1 @read @set @slow Iterates over members of a set. 2.8.0 set O(1) for every call. O(N) for a complete iteration, including enough command calls for the cursor to return back to 0. N is the number of elements inside the collection.",
419
+ "ssubscribe -2 pubsub noscript loading stale 1 -1 1 @pubsub @slow Listens for messages published to shard channels. 7.0.0 pubsub O(N) where N is the number of shard channels to subscribe to.",
232
420
  "strlen 2 readonly fast 1 1 1 @read @string @fast Returns the length of a string value. 2.2.0 string O(1)",
233
421
  "subscribe -2 pubsub noscript loading stale 0 0 0 @pubsub @slow Listens for messages published to channels. 2.0.0 pubsub O(N) where N is the number of channels to subscribe to.",
234
422
  "sunion -2 readonly 1 -1 1 @read @set @slow Returns the union of multiple sets. 1.0.0 set O(N) where N is the total number of elements in all given sets.",
423
+ "sunionstore -3 write denyoom 1 -1 1 @write @set @slow Stores the union of multiple sets in a key. 1.0.0 set O(N) where N is the total number of elements in all given sets.",
424
+ "sunsubscribe -1 pubsub noscript loading stale 1 -1 1 @pubsub @slow Stops listening to messages posted to shard channels. 7.0.0 pubsub O(N) where N is the number of shard channels to unsubscribe.",
235
425
  "time 1 loading stale fast 0 0 0 @fast Returns the server time. 2.6.0 server O(1)",
426
+ "touch -2 readonly fast 1 -1 1 @keyspace @read @fast Returns the number of existing keys out of those specified after updating the time they were last accessed. 3.2.1 generic O(N) where N is the number of keys that will be touched.",
236
427
  "ttl 2 readonly fast 1 1 1 @keyspace @read @fast Returns the expiration time in seconds of a key. 1.0.0 generic O(1)",
237
428
  "type 2 readonly fast 1 1 1 @keyspace @read @fast Determines the type of value stored at a key. 1.0.0 generic O(1)",
238
429
  "unlink -2 write fast 1 -1 1 @keyspace @write @fast Asynchronously deletes one or more keys. 4.0.0 generic O(1) for each key removed regardless of its size. Then the command does O(N) work in a different thread in order to reclaim memory, where N is the number of allocations the deleted objects where composed of.",
239
430
  "unsubscribe -1 pubsub noscript loading stale 0 0 0 @pubsub @slow Stops listening to messages posted to channels. 2.0.0 pubsub O(N) where N is the number of channels to unsubscribe.",
240
431
  "unwatch 1 noscript loading stale fast allow_busy 0 0 0 @fast @transaction Forgets about watched keys of a transaction. 2.2.0 transactions O(1)",
432
+ "wait 3 blocking 0 0 0 @slow @blocking @connection Blocks until the asynchronous replication of all preceding write commands sent by the connection is completed. 3.0.0 generic O(1)",
241
433
  "watch -2 noscript loading stale fast allow_busy 1 -1 1 @fast @transaction Monitors changes to keys to determine the execution of a transaction. 2.2.0 transactions O(1) for every key.",
242
434
  "xack -4 write fast 1 1 1 @write @stream @fast Returns the number of messages that were successfully acknowledged by the consumer group member of a stream. 5.0.0 stream O(1) for each message ID processed.",
243
435
  "xadd -5 write denyoom fast 1 1 1 @write @stream @fast Appends a new message to a stream. Creates the key if it doesn't exist. 5.0.0 stream O(1) when adding a new entry, O(N) when trimming where N being the number of entries evicted.",
@@ -256,21 +448,33 @@ var ROWS = [
256
448
  "zadd -4 write denyoom fast 1 1 1 @write @sortedset @fast Adds one or more members to a sorted set, or updates their scores. Creates the key if it doesn't exist. 1.2.0 sorted-set O(log(N)) for each item added, where N is the number of elements in the sorted set.",
257
449
  "zcard 2 readonly fast 1 1 1 @read @sortedset @fast Returns the number of members in a sorted set. 1.2.0 sorted-set O(1)",
258
450
  "zcount 4 readonly fast 1 1 1 @read @sortedset @fast Returns the count of members in a sorted set that have scores within a range. 2.0.0 sorted-set O(log(N)) with N being the number of elements in the sorted set.",
451
+ "zdiff -3 readonly movablekeys 0 0 0 @read @sortedset @slow Returns the difference between multiple sorted sets. 6.2.0 sorted-set O(L + (N-K)log(N)) worst case where L is the total number of elements in all the sets, N is the size of the first set, and K is the size of the result set.",
452
+ "zdiffstore -4 write denyoom movablekeys 1 1 1 @write @sortedset @slow Stores the difference of multiple sorted sets in a key. 6.2.0 sorted-set O(L + (N-K)log(N)) worst case where L is the total number of elements in all the sets, N is the size of the first set, and K is the size of the result set.",
259
453
  "zincrby 4 write denyoom fast 1 1 1 @write @sortedset @fast Increments the score of a member in a sorted set. 1.2.0 sorted-set O(log(N)) where N is the number of elements in the sorted set.",
454
+ "zinter -3 readonly movablekeys 0 0 0 @read @sortedset @slow Returns the intersect of multiple sorted sets. 6.2.0 sorted-set O(N*K)+O(M*log(M)) worst case with N being the smallest input sorted set, K being the number of input sorted sets and M being the number of elements in the resulting sorted set.",
455
+ "zintercard -3 readonly movablekeys 0 0 0 @read @sortedset @slow Returns the number of members of the intersect of multiple sorted sets. 7.0.0 sorted-set O(N*K) worst case with N being the smallest input sorted set, K being the number of input sorted sets.",
456
+ "zinterstore -4 write denyoom movablekeys 1 1 1 @write @sortedset @slow Stores the intersect of multiple sorted sets in a key. 2.0.0 sorted-set O(N*K)+O(M*log(M)) worst case with N being the smallest input sorted set, K being the number of input sorted sets and M being the number of elements in the resulting sorted set.",
457
+ "zlexcount 4 readonly fast 1 1 1 @read @sortedset @fast Returns the number of members in a sorted set within a lexicographical range. 2.8.9 sorted-set O(log(N)) with N being the number of elements in the sorted set.",
260
458
  "zmscore -3 readonly fast 1 1 1 @read @sortedset @fast Returns the score of one or more members in a sorted set. 6.2.0 sorted-set O(N) where N is the number of members being requested.",
261
459
  "zpopmax -2 write fast 1 1 1 @write @sortedset @fast Returns the highest-scoring members from a sorted set after removing them. Deletes the sorted set if the last member was popped. 5.0.0 sorted-set O(log(N)*M) with N being the number of elements in the sorted set, and M being the number of elements popped.",
262
460
  "zpopmin -2 write fast 1 1 1 @write @sortedset @fast Returns the lowest-scoring members from a sorted set after removing them. Deletes the sorted set if the last member was popped. 5.0.0 sorted-set O(log(N)*M) with N being the number of elements in the sorted set, and M being the number of elements popped.",
461
+ "zrandmember -2 readonly 1 1 1 @read @sortedset @slow Returns one or more random members from a sorted set. 6.2.0 sorted-set O(N) where N is the number of members returned",
263
462
  "zrange -4 readonly 1 1 1 @read @sortedset @slow Returns members in a sorted set within a range of indexes. 1.2.0 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements returned.",
463
+ "zrangebylex -4 readonly 1 1 1 @read @sortedset @slow Returns members in a sorted set within a lexicographical range. 2.8.9 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with LIMIT), you can consider it O(log(N)).",
264
464
  "zrangebyscore -4 readonly 1 1 1 @read @sortedset @slow Returns members in a sorted set within a range of scores. 1.0.5 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with LIMIT), you can consider it O(log(N)).",
465
+ "zrangestore -5 write denyoom 1 2 1 @write @sortedset @slow Stores a range of members from sorted set in a key. 6.2.0 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements stored into the destination key.",
265
466
  "zrank -3 readonly fast 1 1 1 @read @sortedset @fast Returns the index of a member in a sorted set ordered by ascending scores. 2.0.0 sorted-set O(log(N))",
266
467
  "zrem -3 write fast 1 1 1 @write @sortedset @fast Removes one or more members from a sorted set. Deletes the sorted set if all members were removed. 1.2.0 sorted-set O(M*log(N)) with N being the number of elements in the sorted set and M the number of elements to be removed.",
468
+ "zremrangebylex 4 write 1 1 1 @write @sortedset @slow Removes members in a sorted set within a lexicographical range. Deletes the sorted set if all members were removed. 2.8.9 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements removed by the operation.",
267
469
  "zremrangebyrank 4 write 1 1 1 @write @sortedset @slow Removes members in a sorted set within a range of indexes. Deletes the sorted set if all members were removed. 2.0.0 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements removed by the operation.",
268
470
  "zremrangebyscore 4 write 1 1 1 @write @sortedset @slow Removes members in a sorted set within a range of scores. Deletes the sorted set if all members were removed. 1.2.0 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements removed by the operation.",
269
471
  "zrevrange -4 readonly 1 1 1 @read @sortedset @slow Returns members in a sorted set within a range of indexes in reverse order. 1.2.0 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements returned.",
472
+ "zrevrangebylex -4 readonly 1 1 1 @read @sortedset @slow Returns members in a sorted set within a lexicographical range in reverse order. 2.8.9 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with LIMIT), you can consider it O(log(N)).",
270
473
  "zrevrangebyscore -4 readonly 1 1 1 @read @sortedset @slow Returns members in a sorted set within a range of scores in reverse order. 2.2.0 sorted-set O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with LIMIT), you can consider it O(log(N)).",
271
474
  "zrevrank -3 readonly fast 1 1 1 @read @sortedset @fast Returns the index of a member in a sorted set ordered by descending scores. 2.0.0 sorted-set O(log(N))",
272
475
  "zscan -3 readonly 1 1 1 @read @sortedset @slow Iterates over members and scores of a sorted set. 2.8.0 sorted-set O(1) for every call. O(N) for a complete iteration, including enough command calls for the cursor to return back to 0. N is the number of elements inside the collection.",
273
476
  "zscore 3 readonly fast 1 1 1 @read @sortedset @fast Returns the score of a member in a sorted set. 1.2.0 sorted-set O(1)",
477
+ "zunion -3 readonly movablekeys 0 0 0 @read @sortedset @slow Returns the union of multiple sorted sets. 6.2.0 sorted-set O(N)+O(M*log(M)) with N being the sum of the sizes of the input sorted sets, and M being the number of elements in the resulting sorted set.",
274
478
  "zunionstore -4 write denyoom movablekeys 1 1 1 @write @sortedset @slow Stores the union of multiple sorted sets in a key. 2.0.0 sorted-set O(N)+O(M log(M)) with N being the sum of the sizes of the input sorted sets, and M being the number of elements in the resulting sorted set."
275
479
  ];
276
480
  var COMMAND_TABLE = ROWS.map((row) => {
@@ -413,8 +617,8 @@ function sha256Hex(input) {
413
617
 
414
618
  // src/introspect.ts
415
619
  var upper = (bytes2) => bytes2 ? latin1(bytes2).toUpperCase() : "";
416
- var text = (bytes2) => bytes2 ? latin1(bytes2) : "";
417
- var unknownSubcommand = (name, sub) => err(`ERR unknown subcommand '${text(sub)}'. Try ${name.toUpperCase()} HELP.`);
620
+ var text2 = (bytes2) => bytes2 ? latin1(bytes2) : "";
621
+ var unknownSubcommand = (name, sub) => err(`ERR unknown subcommand '${text2(sub)}'. Try ${name.toUpperCase()} HELP.`);
418
622
  var unsupported = (what) => err(`ERR ${what} is not supported by the Mockingbird Redis emulator`);
419
623
  var isInt64Text = (bytes2) => {
420
624
  if (bytes2.length === 0 || bytes2.length > 20) return false;
@@ -522,7 +726,7 @@ function cmdObject(database, args) {
522
726
  if (!["ENCODING", "FREQ", "IDLETIME", "REFCOUNT"].includes(sub))
523
727
  return unknownSubcommand("object", args[0]);
524
728
  if (args.length !== 2) return arityError(`object|${sub.toLowerCase()}`);
525
- const key = text(args[1]);
729
+ const key = text2(args[1]);
526
730
  const value = database.peek(key);
527
731
  if (!value) return nil();
528
732
  if (sub === "ENCODING") return bulk(encodingOf(value));
@@ -542,7 +746,7 @@ function cmdMemory(database, args) {
542
746
  if (samples === null) return notInteger();
543
747
  if (samples < 0n) return syntaxError();
544
748
  }
545
- const key = text(args[1]);
749
+ const key = text2(args[1]);
546
750
  const value = database.peek(key);
547
751
  return value ? int(memoryUsage(key, value)) : nil();
548
752
  }
@@ -626,14 +830,14 @@ function docsEntry(row) {
626
830
  }
627
831
  function keyPositions(row, args) {
628
832
  const name = row[0];
629
- const numkeysAt = (at, first3, store = false) => {
833
+ const numkeysAt = (at, first3, store2 = false) => {
630
834
  const declared = parseI64(args[at] ?? utf8(""));
631
835
  if (declared === null || declared < 1n || declared > BigInt(args.length - first3))
632
836
  return err("ERR Invalid arguments specified for command");
633
837
  const positions2 = Array.from({ length: Number(declared) }, (_, i) => first3 + i);
634
- return store ? [0, ...positions2] : positions2;
838
+ return store2 ? [0, ...positions2] : positions2;
635
839
  };
636
- if (name === "eval" || name === "evalsha") {
840
+ if (["eval", "evalsha", "eval_ro", "evalsha_ro", "fcall", "fcall_ro"].includes(name)) {
637
841
  const declared = parseI64(args[1] ?? utf8(""));
638
842
  if (declared === null || declared < 1n || declared > BigInt(args.length - 2)) return [];
639
843
  return Array.from({ length: Number(declared) }, (_, i) => 2 + i);
@@ -667,20 +871,20 @@ function cmdCommand(args) {
667
871
  if (args.length === 1) return arr(COMMAND_TABLE.map(infoEntry));
668
872
  return arr(
669
873
  args.slice(1).map((arg) => {
670
- const row = BY_NAME.get(text(arg).toLowerCase());
874
+ const row = BY_NAME.get(text2(arg).toLowerCase());
671
875
  return row ? infoEntry(row) : nil();
672
876
  })
673
877
  );
674
878
  }
675
879
  if (sub === "DOCS") {
676
- const rows = args.length === 1 ? COMMAND_TABLE : args.slice(1).map((arg) => BY_NAME.get(text(arg).toLowerCase())).filter((row) => row !== void 0);
880
+ const rows = args.length === 1 ? COMMAND_TABLE : args.slice(1).map((arg) => BY_NAME.get(text2(arg).toLowerCase())).filter((row) => row !== void 0);
677
881
  return map(rows.map((row) => [bulk(row[0]), docsEntry(row)]));
678
882
  }
679
883
  if (sub === "LIST") {
680
884
  if (args.length === 1) return arr(commandNames().map((name) => bulk(name)));
681
885
  if (args.length !== 4 || upper(args[1]) !== "FILTERBY") return syntaxError();
682
886
  const kind = upper(args[2]);
683
- const operand = text(args[3]);
887
+ const operand = text2(args[3]);
684
888
  if (kind === "MODULE") return arr([]);
685
889
  if (kind === "ACLCAT")
686
890
  return arr(
@@ -698,7 +902,7 @@ function cmdCommand(args) {
698
902
  }
699
903
  if (sub === "GETKEYS") {
700
904
  if (args.length < 2) return arityError("command|getkeys");
701
- const row = BY_NAME.get(text(args[1]).toLowerCase());
905
+ const row = BY_NAME.get(text2(args[1]).toLowerCase());
702
906
  if (!row) return err("ERR Invalid command specified");
703
907
  const rest = args.slice(2);
704
908
  const given = rest.length + 1;
@@ -790,6 +994,8 @@ var Database = class {
790
994
  touched = /* @__PURE__ */ new Map();
791
995
  order = [];
792
996
  tick = 0;
997
+ /** Called with each key removed because its TTL passed (keyspace `expired` events). */
998
+ onExpired;
793
999
  now() {
794
1000
  return this.clock.now();
795
1001
  }
@@ -827,6 +1033,7 @@ var Database = class {
827
1033
  this.order = this.order.filter((item) => item !== key);
828
1034
  this.lru.delete(key);
829
1035
  this.touched.delete(key);
1036
+ this.onExpired?.(key);
830
1037
  }
831
1038
  }
832
1039
  /** Drop hash fields whose own TTL (`HEXPIRE`) has passed; a hash left empty goes away. */
@@ -1002,7 +1209,6 @@ function memberKey(bytes2) {
1002
1209
 
1003
1210
  // src/extra.ts
1004
1211
  var EXTRA_WRITES = [
1005
- "zunionstore",
1006
1212
  "lmpop",
1007
1213
  "blmove",
1008
1214
  "brpoplpush",
@@ -1014,15 +1220,13 @@ var EXTRA_WRITES = [
1014
1220
  "hpersist"
1015
1221
  ];
1016
1222
  var upper2 = (bytes2) => bytes2 ? latin1(bytes2).toUpperCase() : "";
1017
- var text2 = (bytes2) => bytes2 ? latin1(bytes2) : "";
1223
+ var text3 = (bytes2) => bytes2 ? latin1(bytes2) : "";
1018
1224
  function extraCommand(host, session, command, args, apply) {
1019
1225
  switch (command) {
1020
1226
  case "hscan":
1021
1227
  case "sscan":
1022
1228
  case "zscan":
1023
1229
  return cmdCollectionScan(host, session, command, args);
1024
- case "zunionstore":
1025
- return cmdZunionstore(host, session, args, apply);
1026
1230
  case "lmpop":
1027
1231
  return cmdLmpop(host, session, args, apply);
1028
1232
  case "blmove":
@@ -1053,9 +1257,9 @@ function extraCommand(host, session, command, args, apply) {
1053
1257
  var MAX_CURSOR = 18446744073709551615n;
1054
1258
  function cmdCollectionScan(host, session, command, args) {
1055
1259
  if (args.length < 2) return arityError(command);
1056
- const cursorText = text2(args[1]);
1260
+ const cursorText = text3(args[1]);
1057
1261
  if (!/^\d+$/.test(cursorText) || BigInt(cursorText) > MAX_CURSOR) return err("ERR invalid cursor");
1058
- const value = host.database(session.db).get(text2(args[0]));
1262
+ const value = host.database(session.db).get(text3(args[0]));
1059
1263
  if (!value) return arr([bulk("0"), arr([])]);
1060
1264
  const kind = command === "hscan" ? "hash" : command === "sscan" ? "set" : "zset";
1061
1265
  if (value.kind !== kind) return wrongType();
@@ -1067,11 +1271,11 @@ function cmdCollectionScan(host, session, command, args) {
1067
1271
  if (option === "MATCH") {
1068
1272
  const pattern_ = args[++i];
1069
1273
  if (!pattern_) return syntaxError();
1070
- pattern = text2(pattern_);
1274
+ pattern = text3(pattern_);
1071
1275
  } else if (option === "COUNT") {
1072
- const raw = args[++i];
1073
- if (!raw) return syntaxError();
1074
- const parsed = parseI64(raw);
1276
+ const raw2 = args[++i];
1277
+ if (!raw2) return syntaxError();
1278
+ const parsed = parseI64(raw2);
1075
1279
  if (parsed === null) return notInteger();
1076
1280
  if (parsed < 1n) return syntaxError();
1077
1281
  count = Number(parsed);
@@ -1108,86 +1312,13 @@ function scanEntries(database, value, noValues) {
1108
1312
  }
1109
1313
  return [];
1110
1314
  }
1111
- function formatScore(score) {
1112
- if (Number.isNaN(score)) return "nan";
1113
- if (score === Infinity) return "inf";
1114
- if (score === -Infinity) return "-inf";
1115
- return String(score);
1116
- }
1117
- function parseFloatArg(bytes2) {
1118
- const value = text2(bytes2).trim().toLowerCase();
1119
- if (value === "inf" || value === "+inf") return Infinity;
1120
- if (value === "-inf") return -Infinity;
1121
- if (!/^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/.test(value)) return null;
1122
- const parsed = Number(value);
1123
- return Number.isFinite(parsed) ? parsed : null;
1124
- }
1125
- function cmdZunionstore(host, session, args, apply) {
1126
- if (args.length < 3) return arityError("zunionstore");
1127
- const numkeys = parseI64(args[1] ?? utf8(""));
1128
- if (numkeys === null) return notInteger();
1129
- if (numkeys < 1n) return err("ERR at least 1 input key is needed for 'zunionstore' command");
1130
- if (numkeys > BigInt(args.length - 2)) return syntaxError();
1131
- const count = Number(numkeys);
1132
- const keys = args.slice(2, 2 + count).map(text2);
1133
- const weights = keys.map(() => 1);
1134
- let aggregate = "SUM";
1135
- for (let i = 2 + count; i < args.length; i++) {
1136
- const option = upper2(args[i]);
1137
- if (option === "WEIGHTS") {
1138
- if (i + count >= args.length) return syntaxError();
1139
- for (let j = 0; j < count; j++) {
1140
- const weight = parseFloatArg(args[i + 1 + j]);
1141
- if (weight === null) return err("ERR weight value is not a float");
1142
- weights[j] = weight;
1143
- }
1144
- i += count;
1145
- } else if (option === "AGGREGATE") {
1146
- const kind = upper2(args[++i]);
1147
- if (kind !== "SUM" && kind !== "MIN" && kind !== "MAX") return syntaxError();
1148
- aggregate = kind;
1149
- } else return syntaxError();
1150
- }
1151
- const database = host.database(session.db);
1152
- const scores = /* @__PURE__ */ new Map();
1153
- keys.forEach((key, index) => {
1154
- const value = database.get(key);
1155
- if (!value) return;
1156
- if (value.kind !== "zset" && value.kind !== "set") return;
1157
- const weight = weights[index] ?? 1;
1158
- const members2 = value.kind === "zset" ? [...value.members.values()] : [...value.members.values()].map((member) => ({ member, score: 1 }));
1159
- for (const { member, score } of members2) {
1160
- const scaled = Number.isNaN(score * weight) ? 0 : score * weight;
1161
- const id = memberKey(member);
1162
- const current = scores.get(id);
1163
- if (!current) scores.set(id, { member, score: scaled });
1164
- else if (aggregate === "SUM") current.score = nanToZero(current.score + scaled);
1165
- else if (aggregate === "MIN") current.score = Math.min(current.score, scaled);
1166
- else current.score = Math.max(current.score, scaled);
1167
- }
1168
- });
1169
- for (const key of keys) {
1170
- const value = database.get(key);
1171
- if (value && value.kind !== "zset" && value.kind !== "set") return wrongType();
1172
- }
1173
- if (!apply) return queued();
1174
- const dest = text2(args[0]);
1175
- database.delete(dest);
1176
- if (scores.size === 0) return int(0);
1177
- const members = /* @__PURE__ */ new Map();
1178
- for (const [id, item] of scores) members.set(id, item);
1179
- database.put(dest, { kind: "zset", members });
1180
- host.wake(session.db, dest);
1181
- return int(members.size);
1182
- }
1183
- var nanToZero = (value) => Number.isNaN(value) ? 0 : value;
1184
1315
  function cmdLmpop(host, session, args, apply) {
1185
1316
  if (args.length < 3) return arityError("lmpop");
1186
1317
  const numkeys = parseI64(args[0] ?? utf8(""));
1187
1318
  if (numkeys === null || numkeys < 1n) return err("ERR numkeys should be greater than 0");
1188
1319
  const count = Number(numkeys);
1189
1320
  if (count > args.length - 2) return syntaxError();
1190
- const keys = args.slice(1, 1 + count).map(text2);
1321
+ const keys = args.slice(1, 1 + count).map(text3);
1191
1322
  const where = upper2(args[1 + count]);
1192
1323
  if (where !== "LEFT" && where !== "RIGHT") return syntaxError();
1193
1324
  let take = 1;
@@ -1216,10 +1347,10 @@ function cmdLmpop(host, session, args, apply) {
1216
1347
  return apply ? nilArray() : queued();
1217
1348
  }
1218
1349
  function parseTimeoutSeconds(bytes2) {
1219
- const raw = text2(bytes2);
1220
- if (!/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/.test(raw))
1350
+ const raw2 = text3(bytes2);
1351
+ if (!/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/.test(raw2))
1221
1352
  return err("ERR timeout is not a float or out of range");
1222
- const value = Number(raw);
1353
+ const value = Number(raw2);
1223
1354
  if (!Number.isFinite(value) || value * 1e3 > Number.MAX_SAFE_INTEGER)
1224
1355
  return err("ERR timeout is out of range");
1225
1356
  if (value < 0) return err("ERR timeout is negative");
@@ -1257,8 +1388,8 @@ function cmdBlockingMove(host, session, command, args, apply) {
1257
1388
  }
1258
1389
  const timeout = parseTimeoutSeconds(args[args.length - 1]);
1259
1390
  if (typeof timeout !== "number") return timeout;
1260
- const src = text2(args[0]);
1261
- const dst = text2(args[1]);
1391
+ const src = text3(args[0]);
1392
+ const dst = text3(args[1]);
1262
1393
  const database = host.database(session.db);
1263
1394
  const source = database.get(src);
1264
1395
  if (source && source.kind !== "list") return wrongType();
@@ -1283,10 +1414,10 @@ function cmdBlockingMove(host, session, command, args, apply) {
1283
1414
  function cmdMsetnx(host, session, args, apply) {
1284
1415
  if (args.length < 2 || args.length % 2 !== 0) return arityError("msetnx");
1285
1416
  const database = host.database(session.db);
1286
- for (let i = 0; i < args.length; i += 2) if (database.has(text2(args[i]))) return int(0);
1417
+ for (let i = 0; i < args.length; i += 2) if (database.has(text3(args[i]))) return int(0);
1287
1418
  if (!apply) return queued();
1288
1419
  for (let i = 0; i < args.length; i += 2) {
1289
- database.put(text2(args[i]), { kind: "string", bytes: args[i + 1] ?? utf8("") });
1420
+ database.put(text3(args[i]), { kind: "string", bytes: args[i + 1] ?? utf8("") });
1290
1421
  }
1291
1422
  return int(1);
1292
1423
  }
@@ -1305,8 +1436,8 @@ function cmdCopy(host, session, args, apply) {
1305
1436
  destDb = Number(parsed);
1306
1437
  } else return syntaxError();
1307
1438
  }
1308
- const sourceKey = text2(args[0]);
1309
- const destKey = text2(args[1]);
1439
+ const sourceKey = text3(args[0]);
1440
+ const destKey = text3(args[1]);
1310
1441
  if (destDb === session.db && sourceKey === destKey)
1311
1442
  return err("ERR source and destination objects are the same");
1312
1443
  const source = host.database(session.db);
@@ -1325,7 +1456,7 @@ function cmdCopy(host, session, args, apply) {
1325
1456
  function cmdExpireTime(host, session, command, args) {
1326
1457
  if (args.length !== 1) return arityError(command);
1327
1458
  const database = host.database(session.db);
1328
- const key = text2(args[0]);
1459
+ const key = text3(args[0]);
1329
1460
  if (!database.has(key)) return int(-2);
1330
1461
  const at = database.expiry(key);
1331
1462
  if (at === null) return int(-1);
@@ -1362,7 +1493,7 @@ function cmdHashExpire(host, session, command, args, apply) {
1362
1493
  const absolute = command === "hexpire" || command === "hpexpire" ? BigInt(now) + millis : millis;
1363
1494
  if (absolute > BigInt(HASH_EXPIRE_MAX_MS) || millis > BigInt(HASH_EXPIRE_MAX_MS))
1364
1495
  return err(`ERR invalid expire time in '${command}' command`);
1365
- const key = text2(args[0]);
1496
+ const key = text3(args[0]);
1366
1497
  const hash = hashAt(database, key);
1367
1498
  if (hash !== null && !("fields" in hash)) return hash;
1368
1499
  if (hash === null) return apply ? arr(clause.fields.map(() => int(-2))) : queued();
@@ -1399,7 +1530,7 @@ function cmdHashTtl(host, session, command, args, apply) {
1399
1530
  const clause = fieldsClause(args, 1);
1400
1531
  if ("error" in clause) return clause.error;
1401
1532
  const database = host.database(session.db);
1402
- const key = text2(args[0]);
1533
+ const key = text3(args[0]);
1403
1534
  const hash = hashAt(database, key);
1404
1535
  if (hash !== null && !("fields" in hash)) return hash;
1405
1536
  if (command === "hpersist" && !apply) return queued();
@@ -1450,10 +1581,10 @@ function roundDrop(digits, drop) {
1450
1581
  if (head > 5 || head === 5 && (rest || value % 2n === 1n)) value += 1n;
1451
1582
  return value.toString();
1452
1583
  }
1453
- function nonFinite(x, upper4) {
1454
- if (Number.isNaN(x)) return upper4 ? "NAN" : "nan";
1455
- if (x === Infinity) return upper4 ? "INF" : "inf";
1456
- if (x === -Infinity) return upper4 ? "-INF" : "-inf";
1584
+ function nonFinite(x, upper6) {
1585
+ if (Number.isNaN(x)) return upper6 ? "NAN" : "nan";
1586
+ if (x === Infinity) return upper6 ? "INF" : "inf";
1587
+ if (x === -Infinity) return upper6 ? "-INF" : "-inf";
1457
1588
  return null;
1458
1589
  }
1459
1590
  var isNegative = (x) => x < 0 || Object.is(x, -0);
@@ -1481,8 +1612,8 @@ function expText(exp) {
1481
1612
  const magnitude = Math.abs(exp);
1482
1613
  return `${exp < 0 ? "-" : "+"}${magnitude < 10 ? "0" : ""}${magnitude}`;
1483
1614
  }
1484
- function trimZeros(text4) {
1485
- return text4.includes(".") ? text4.replace(/\.?0+$/, "") : text4;
1615
+ function trimZeros(text8) {
1616
+ return text8.includes(".") ? text8.replace(/\.?0+$/, "") : text8;
1486
1617
  }
1487
1618
  function pad(body, sign, spec, zeroOk) {
1488
1619
  const length2 = sign.length + body.length;
@@ -1492,8 +1623,8 @@ function pad(body, sign, spec, zeroOk) {
1492
1623
  return " ".repeat(spec.width - length2) + sign + body;
1493
1624
  }
1494
1625
  function formatFloat(x, spec) {
1495
- const upper4 = spec.conv === "E" || spec.conv === "G";
1496
- const special = nonFinite(x, upper4);
1626
+ const upper6 = spec.conv === "E" || spec.conv === "G";
1627
+ const special = nonFinite(x, upper6);
1497
1628
  const negative = isNegative(x);
1498
1629
  const sign = negative ? "-" : spec.flags.includes("+") ? "+" : spec.flags.includes(" ") ? " " : "";
1499
1630
  if (special !== null) {
@@ -1511,7 +1642,7 @@ function formatFloat(x, spec) {
1511
1642
  const { digits, exp } = expDigits(magnitude, precision);
1512
1643
  const mantissa = precision === 0 ? digits : `${digits[0]}.${digits.slice(1)}`;
1513
1644
  body = `${mantissa}${alt && precision === 0 ? "." : ""}e${expText(exp)}`;
1514
- if (upper4) body = body.toUpperCase();
1645
+ if (upper6) body = body.toUpperCase();
1515
1646
  } else {
1516
1647
  const precision = spec.precision === null ? 6 : spec.precision === 0 ? 1 : spec.precision;
1517
1648
  const { digits, exp } = expDigits(magnitude, precision - 1);
@@ -1523,7 +1654,7 @@ function formatFloat(x, spec) {
1523
1654
  body = fixedDigits(magnitude, Math.max(0, precision - 1 - exp));
1524
1655
  if (!alt) body = trimZeros(body);
1525
1656
  }
1526
- if (upper4) body = body.toUpperCase();
1657
+ if (upper6) body = body.toUpperCase();
1527
1658
  }
1528
1659
  return pad(body, sign, spec, true);
1529
1660
  }
@@ -1580,7 +1711,7 @@ var LuaUserdata = class {
1580
1711
  }
1581
1712
  label;
1582
1713
  };
1583
- var pos = { line: 0 };
1714
+ var pos = { line: 0, chunk: "user_script" };
1584
1715
  var LuaError = class {
1585
1716
  constructor(value, line = pos.line) {
1586
1717
  this.value = value;
@@ -1590,7 +1721,7 @@ var LuaError = class {
1590
1721
  line;
1591
1722
  };
1592
1723
  function rtError(message) {
1593
- throw new LuaError(pos.line < 0 ? message : `user_script:${pos.line}: ${message}`);
1724
+ throw new LuaError(pos.line < 0 ? message : `${pos.chunk}:${pos.line}: ${message}`);
1594
1725
  }
1595
1726
  var EMPTY = [];
1596
1727
  var LuaTable = class {
@@ -1713,8 +1844,8 @@ function typeName(value) {
1713
1844
  }
1714
1845
  }
1715
1846
  var truthy = (value) => value !== void 0 && value !== false;
1716
- function parseNumber(text4) {
1717
- const s = text4.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
1847
+ function parseNumber(text8) {
1848
+ const s = text8.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
1718
1849
  if (s === "") return void 0;
1719
1850
  if (/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(s)) return Number(s);
1720
1851
  const hex = /^([+-]?)0[xX]([0-9a-fA-F]+)$/.exec(s);
@@ -1729,8 +1860,8 @@ function parseNumber(text4) {
1729
1860
  }
1730
1861
  return void 0;
1731
1862
  }
1732
- function parseNumberBase(text4, base) {
1733
- const s = text4.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
1863
+ function parseNumberBase(text8, base) {
1864
+ const s = text8.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
1734
1865
  const match = /^(-?)([0-9a-zA-Z]+)$/.exec(s);
1735
1866
  if (!match) return void 0;
1736
1867
  let value = 0;
@@ -3160,12 +3291,12 @@ function caught(error) {
3160
3291
  if (error instanceof LuaError) {
3161
3292
  const value = error.value;
3162
3293
  if (value instanceof LuaTable) {
3163
- const text4 = value.getStr("err");
3164
- if (typeof text4 === "string") return text4;
3294
+ const text8 = value.getStr("err");
3295
+ if (typeof text8 === "string") return text8;
3165
3296
  }
3166
3297
  return value;
3167
3298
  }
3168
- if (error instanceof RangeError) return `user_script:${pos.line}: stack overflow`;
3299
+ if (error instanceof RangeError) return `${pos.chunk}:${pos.line}: stack overflow`;
3169
3300
  throw error;
3170
3301
  }
3171
3302
  function pcall(...args) {
@@ -3218,8 +3349,8 @@ function toNumberBuiltin(...args) {
3218
3349
  }
3219
3350
  const base = checkInt(args, 1, "tonumber");
3220
3351
  if (base < 2 || base > 36) argError(1, "tonumber", "base out of range");
3221
- const text4 = checkString(args, 0, "tonumber");
3222
- return parseNumberBase(text4, base);
3352
+ const text8 = checkString(args, 0, "tonumber");
3353
+ return parseNumberBase(text8, base);
3223
3354
  }
3224
3355
  function unpack(...args) {
3225
3356
  const table = checkTable(args, 0, "unpack");
@@ -3244,7 +3375,7 @@ function errorBuiltin(...args) {
3244
3375
  let value = args[0];
3245
3376
  const level = optInt(args, 1, "error", 1);
3246
3377
  if ((typeof value === "string" || typeof value === "number") && level > 0 && pos.line >= 0) {
3247
- value = `user_script:${pos.line}: ${tostr(value)}`;
3378
+ value = `${pos.chunk}:${pos.line}: ${tostr(value)}`;
3248
3379
  }
3249
3380
  throw new LuaError(value);
3250
3381
  }
@@ -3332,9 +3463,9 @@ function strRep(...args) {
3332
3463
  }
3333
3464
  var FORMAT_FLAGS = "-+ #0";
3334
3465
  var isDigit = (c) => c !== void 0 && c >= "0" && c <= "9";
3335
- function padText(text4, width, left) {
3336
- if (text4.length >= width) return text4;
3337
- return left ? text4 + " ".repeat(width - text4.length) : " ".repeat(width - text4.length) + text4;
3466
+ function padText(text8, width, left) {
3467
+ if (text8.length >= width) return text8;
3468
+ return left ? text8 + " ".repeat(width - text8.length) : " ".repeat(width - text8.length) + text8;
3338
3469
  }
3339
3470
  function quote(s) {
3340
3471
  let out = '"';
@@ -3469,16 +3600,16 @@ function addReplacement(ms, s, e, repl, kind) {
3469
3600
  const whole = ms.src.slice(s, e);
3470
3601
  let value;
3471
3602
  if (kind === "string") {
3472
- const text5 = repl;
3603
+ const text9 = repl;
3473
3604
  let out = "";
3474
- for (let i = 0; i < text5.length; i++) {
3475
- const c = text5[i];
3605
+ for (let i = 0; i < text9.length; i++) {
3606
+ const c = text9[i];
3476
3607
  if (c !== "%") {
3477
3608
  out += c;
3478
3609
  continue;
3479
3610
  }
3480
3611
  i++;
3481
- const next = text5[i];
3612
+ const next = text9[i];
3482
3613
  if (next === void 0 || next < "0" || next > "9") {
3483
3614
  if (next !== "%") rtError("invalid use of '%' in replacement string");
3484
3615
  out += "%";
@@ -3495,9 +3626,9 @@ function addReplacement(ms, s, e, repl, kind) {
3495
3626
  value = first(callValue(repl, captures));
3496
3627
  }
3497
3628
  if (value === void 0 || value === false) return whole;
3498
- const text4 = tostr(value);
3499
- if (text4 === void 0) return rtError(`invalid replacement value (a ${typeName(value)})`);
3500
- return text4;
3629
+ const text8 = tostr(value);
3630
+ if (text8 === void 0) return rtError(`invalid replacement value (a ${typeName(value)})`);
3631
+ return text8;
3501
3632
  }
3502
3633
  function strGsub(...args) {
3503
3634
  const src = checkString(args, 0, "gsub");
@@ -3579,11 +3710,11 @@ function tableConcat(...args) {
3579
3710
  const to = args[3] === void 0 ? table.length() : checkInt(args, 3, "concat");
3580
3711
  const parts = [];
3581
3712
  for (let i = from; i <= to; i++) {
3582
- const text4 = tostr(table.get(i));
3583
- if (text4 === void 0) {
3713
+ const text8 = tostr(table.get(i));
3714
+ if (text8 === void 0) {
3584
3715
  rtError(`invalid value (${typeName(table.get(i))}) at index ${i} in table for 'concat'`);
3585
3716
  }
3586
- parts.push(text4);
3717
+ parts.push(text8);
3587
3718
  }
3588
3719
  return parts.join(separator);
3589
3720
  }
@@ -3607,7 +3738,7 @@ function withoutPosition(less) {
3607
3738
  return less(a, b);
3608
3739
  } catch (error) {
3609
3740
  if (error instanceof LuaError && typeof error.value === "string") {
3610
- const prefix = `user_script:${error.line}: `;
3741
+ const prefix = `${pos.chunk}:${error.line}: `;
3611
3742
  if (error.value.startsWith(prefix))
3612
3743
  throw new LuaError(error.value.slice(prefix.length), error.line);
3613
3744
  }
@@ -3812,13 +3943,13 @@ function bitLib() {
3812
3943
  );
3813
3944
  }
3814
3945
  function coroutineLib() {
3815
- const unsupported2 = (name) => () => rtError(`coroutine.${name} is not supported by this emulator's Lua runtime`);
3946
+ const unsupported3 = (name) => () => rtError(`coroutine.${name} is not supported by this emulator's Lua runtime`);
3816
3947
  return freeze(
3817
3948
  makeLib(
3818
3949
  Object.fromEntries(
3819
3950
  ["create", "resume", "running", "status", "wrap", "yield"].map((name) => [
3820
3951
  name,
3821
- unsupported2(name)
3952
+ unsupported3(name)
3822
3953
  ])
3823
3954
  )
3824
3955
  )
@@ -3970,8 +4101,8 @@ var SIMPLE_ESCAPES = {
3970
4101
  t: " "
3971
4102
  };
3972
4103
  var Decoder = class {
3973
- constructor(text4) {
3974
- this.text = text4;
4104
+ constructor(text8) {
4105
+ this.text = text8;
3975
4106
  }
3976
4107
  text;
3977
4108
  at = 0;
@@ -3980,14 +4111,14 @@ var Decoder = class {
3980
4111
  return rtError(`Expected ${expected} but found ${found} at character ${token.index + 1}`);
3981
4112
  }
3982
4113
  skipSpace() {
3983
- const text4 = this.text;
3984
- while (" \n\r".includes(text4[this.at] ?? "x")) this.at++;
4114
+ const text8 = this.text;
4115
+ while (" \n\r".includes(text8[this.at] ?? "x")) this.at++;
3985
4116
  }
3986
4117
  token() {
3987
4118
  this.skipSpace();
3988
- const text4 = this.text;
4119
+ const text8 = this.text;
3989
4120
  const index = this.at;
3990
- const c = text4[index];
4121
+ const c = text8[index];
3991
4122
  if (c === void 0) return { type: "T_END", index };
3992
4123
  const punctuation = PUNCTUATION[c];
3993
4124
  if (punctuation !== void 0) {
@@ -3996,7 +4127,7 @@ var Decoder = class {
3996
4127
  }
3997
4128
  if (c === '"') return this.stringToken(index);
3998
4129
  if (c === "-" || c >= "0" && c <= "9") {
3999
- const match = /^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(text4.slice(index, index + 400));
4130
+ const match = /^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(text8.slice(index, index + 400));
4000
4131
  if (match === null) return { type: "T_ERROR", index, value: "invalid token" };
4001
4132
  this.at += match[0].length;
4002
4133
  return { type: "T_NUMBER", index, value: Number(match[0]) };
@@ -4006,7 +4137,7 @@ var Decoder = class {
4006
4137
  ["false", false],
4007
4138
  ["null", null]
4008
4139
  ]) {
4009
- if (text4.startsWith(word, index)) {
4140
+ if (text8.startsWith(word, index)) {
4010
4141
  this.at += word.length;
4011
4142
  return value === null ? { type: "T_NULL", index } : { type: "T_BOOLEAN", index, value };
4012
4143
  }
@@ -4014,29 +4145,29 @@ var Decoder = class {
4014
4145
  return { type: "T_ERROR", index, value: "invalid token" };
4015
4146
  }
4016
4147
  stringToken(index) {
4017
- const text4 = this.text;
4148
+ const text8 = this.text;
4018
4149
  let i = index + 1;
4019
4150
  let out = "";
4020
4151
  for (; ; ) {
4021
- const c = text4[i];
4152
+ const c = text8[i];
4022
4153
  if (c === void 0)
4023
- return { type: "T_ERROR", index: text4.length, value: "unexpected end of string" };
4154
+ return { type: "T_ERROR", index: text8.length, value: "unexpected end of string" };
4024
4155
  if (c === '"') break;
4025
4156
  if (c !== "\\") {
4026
4157
  out += c;
4027
4158
  i++;
4028
4159
  continue;
4029
4160
  }
4030
- const esc = text4[i + 1];
4161
+ const esc = text8[i + 1];
4031
4162
  if (esc === "u") {
4032
- const hex = text4.slice(i + 2, i + 6);
4163
+ const hex = text8.slice(i + 2, i + 6);
4033
4164
  if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
4034
4165
  return { type: "T_ERROR", index: i, value: "invalid unicode escape code" };
4035
4166
  }
4036
4167
  let code = Number.parseInt(hex, 16);
4037
4168
  i += 6;
4038
4169
  if (code >= 55296 && code <= 56319) {
4039
- const low = /^\\u([dD][c-fC-F][0-9a-fA-F]{2})/.exec(text4.slice(i, i + 6));
4170
+ const low = /^\\u([dD][c-fC-F][0-9a-fA-F]{2})/.exec(text8.slice(i, i + 6));
4040
4171
  if (low === null)
4041
4172
  return { type: "T_ERROR", index: i, value: "invalid unicode escape code" };
4042
4173
  code = 65536 + (code - 55296 << 10) + (Number.parseInt(low[1], 16) - 56320);
@@ -4116,8 +4247,8 @@ var Decoder = class {
4116
4247
  return result;
4117
4248
  }
4118
4249
  };
4119
- function decodeJson(text4) {
4120
- return new Decoder(text4).decode();
4250
+ function decodeJson(text8) {
4251
+ return new Decoder(text8).decode();
4121
4252
  }
4122
4253
  function setter(apply, read) {
4123
4254
  return (...args) => {
@@ -4486,12 +4617,12 @@ function tokenize(src) {
4486
4617
  const close = `]${"=".repeat(level)}]`;
4487
4618
  const end = src.indexOf(close, start);
4488
4619
  if (end < 0) fail(line, `unfinished long ${what}`, "<eof>");
4489
- let text4 = src.slice(start, end);
4490
- line += text4.split("\n").length - 1;
4620
+ let text8 = src.slice(start, end);
4621
+ line += text8.split("\n").length - 1;
4491
4622
  i = end + close.length;
4492
- if (text4.startsWith("\r\n")) text4 = text4.slice(2);
4493
- else if (text4.startsWith("\n")) text4 = text4.slice(1);
4494
- return text4;
4623
+ if (text8.startsWith("\r\n")) text8 = text8.slice(2);
4624
+ else if (text8.startsWith("\n")) text8 = text8.slice(1);
4625
+ return text8;
4495
4626
  };
4496
4627
  if (src.startsWith("#")) {
4497
4628
  while (i < src.length && src[i] !== "\n") i++;
@@ -4572,11 +4703,11 @@ function tokenize(src) {
4572
4703
  if (src[i] === "+" || src[i] === "-") i++;
4573
4704
  }
4574
4705
  while (isAlpha(src[i]) || isDigit2(src[i])) i++;
4575
- const text4 = src.slice(start, i);
4576
- if (!/^(0[xX][0-9a-fA-F]+|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?)$/.test(text4)) {
4577
- fail(line, "malformed number", text4);
4706
+ const text8 = src.slice(start, i);
4707
+ if (!/^(0[xX][0-9a-fA-F]+|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?)$/.test(text8)) {
4708
+ fail(line, "malformed number", text8);
4578
4709
  }
4579
- tokens.push({ t: "num", v: Number(text4), line, text: text4 });
4710
+ tokens.push({ t: "num", v: Number(text8), line, text: text8 });
4580
4711
  continue;
4581
4712
  }
4582
4713
  if (isAlpha(c)) {
@@ -5499,6 +5630,10 @@ function loadstring(globals2) {
5499
5630
  var shared = null;
5500
5631
  function globals() {
5501
5632
  if (shared !== null) return shared;
5633
+ shared = buildGlobals(redisLib());
5634
+ return shared;
5635
+ }
5636
+ function buildGlobals(redis) {
5502
5637
  const g = new LuaTable();
5503
5638
  baseLib(g);
5504
5639
  g.set("string", stringLib());
@@ -5510,7 +5645,7 @@ function globals() {
5510
5645
  g.set("struct", structLib());
5511
5646
  g.set("cjson", cjsonLib());
5512
5647
  g.set("cmsgpack", cmsgpackLib());
5513
- g.set("redis", redisLib());
5648
+ g.set("redis", redis);
5514
5649
  g.set("loadstring", loadstring(g));
5515
5650
  g.set("_G", g);
5516
5651
  const meta = new LuaTable();
@@ -5520,7 +5655,6 @@ function globals() {
5520
5655
  );
5521
5656
  g.meta = meta;
5522
5657
  g.readonly = true;
5523
- shared = g;
5524
5658
  return g;
5525
5659
  }
5526
5660
  var CACHE_LIMIT = 1024;
@@ -5546,19 +5680,20 @@ function compileScript(source, sha) {
5546
5680
  }
5547
5681
  function failure(error, sha) {
5548
5682
  if (error instanceof ScriptFailure) throw error;
5683
+ const chunk = pos.chunk;
5549
5684
  let line = pos.line;
5550
- let text4;
5685
+ let text8;
5551
5686
  if (error instanceof LuaError) {
5552
5687
  line = error.line;
5553
5688
  const value = error.value;
5554
5689
  if (value instanceof LuaTable) {
5555
5690
  const message = value.getStr("err");
5556
- text4 = typeof message === "string" ? message : "ERR unknown error";
5557
- } else text4 = `ERR ${tostringValue(value)}`;
5691
+ text8 = typeof message === "string" ? message : "ERR unknown error";
5692
+ } else text8 = `ERR ${tostringValue(value)}`;
5558
5693
  } else if (error instanceof RangeError) {
5559
- text4 = `ERR user_script:${line}: stack overflow`;
5694
+ text8 = `ERR ${chunk}:${line}: stack overflow`;
5560
5695
  } else throw error;
5561
- throw new ScriptFailure(`${text4} script: ${sha}, on @user_script:${line}.`);
5696
+ throw new ScriptFailure(`${text8} script: ${sha}, on @${chunk}:${line}.`);
5562
5697
  }
5563
5698
  function runScript(source, sha, keys, argv, host, version) {
5564
5699
  const chunk = compile(source, sha);
@@ -5583,6 +5718,713 @@ function runScript(source, sha, keys, argv, host, version) {
5583
5718
  g.set("ARGV", previous.argv);
5584
5719
  }
5585
5720
  }
5721
+ var FUNCTION_FLAGS = /* @__PURE__ */ new Set([
5722
+ "no-writes",
5723
+ "allow-oom",
5724
+ "allow-stale",
5725
+ "no-cluster",
5726
+ "allow-cross-slot-keys"
5727
+ ]);
5728
+ var NAME_PATTERN = /^[A-Za-z0-9_]+$/;
5729
+ var NAME_ERROR = "Library names can only contain letters, numbers, or underscores(_) and must be at least one character long";
5730
+ function registerError(message) {
5731
+ throw new LuaError(message);
5732
+ }
5733
+ var functionGlobals = null;
5734
+ var runtimeRedis = null;
5735
+ var registering = null;
5736
+ function registerFunction(...args) {
5737
+ const target = registering;
5738
+ if (target === null)
5739
+ return registerError("redis.register_function can only be called on FUNCTION LOAD command");
5740
+ let name;
5741
+ let callback;
5742
+ let flags = [];
5743
+ let description = null;
5744
+ if (args.length === 1 && args[0] instanceof LuaTable) {
5745
+ const spec = args[0];
5746
+ name = spec.getStr("function_name");
5747
+ callback = spec.getStr("callback");
5748
+ const given = spec.getStr("flags");
5749
+ if (given !== void 0) {
5750
+ if (!(given instanceof LuaTable))
5751
+ registerError(
5752
+ "flags argument to redis.register_function must be a table representing function flags"
5753
+ );
5754
+ flags = given.arr.map((flag) => {
5755
+ if (typeof flag !== "string" || !FUNCTION_FLAGS.has(flag))
5756
+ return registerError("unknown flag given");
5757
+ return flag;
5758
+ });
5759
+ }
5760
+ const text8 = spec.getStr("description");
5761
+ if (text8 !== void 0) {
5762
+ if (typeof text8 !== "string")
5763
+ registerError("description argument given to redis.register_function must be a string");
5764
+ description = text8;
5765
+ }
5766
+ } else if (args.length === 2) {
5767
+ ;
5768
+ [name, callback] = args;
5769
+ } else registerError("wrong number of arguments to redis.register_function");
5770
+ if (typeof name !== "string")
5771
+ return registerError("function_name argument given to redis.register_function must be a string");
5772
+ if (typeof callback !== "function")
5773
+ return registerError("callback argument given to redis.register_function must be a function");
5774
+ if (!NAME_PATTERN.test(name)) registerError(NAME_ERROR);
5775
+ if (target.has(name)) registerError("Function already exists in the library");
5776
+ target.set(name, { name, callback, flags, description });
5777
+ return [];
5778
+ }
5779
+ function loadRedisLib() {
5780
+ const lib = makeLib({
5781
+ register_function: registerFunction,
5782
+ log: () => [],
5783
+ setresp: () => [],
5784
+ LOG_DEBUG: 0,
5785
+ LOG_VERBOSE: 1,
5786
+ LOG_NOTICE: 2,
5787
+ LOG_WARNING: 3
5788
+ });
5789
+ const meta = new LuaTable();
5790
+ meta.set(
5791
+ "__index",
5792
+ (_table, key) => rtError(`Script attempted to access nonexistent global variable '${tostringValue(key)}'`)
5793
+ );
5794
+ lib.meta = meta;
5795
+ return freeze(lib);
5796
+ }
5797
+ function libraryGlobals() {
5798
+ if (functionGlobals === null) {
5799
+ runtimeRedis = redisLib();
5800
+ functionGlobals = buildGlobals(runtimeRedis);
5801
+ }
5802
+ return functionGlobals;
5803
+ }
5804
+ function loadFunctionLibrary(body) {
5805
+ let chunk;
5806
+ try {
5807
+ chunk = compileChunk(parseChunk(body, "user_function"));
5808
+ } catch (error) {
5809
+ if (error instanceof LuaSyntaxError)
5810
+ throw new ScriptFailure(`ERR Error compiling function: ${error.message}`);
5811
+ throw error;
5812
+ }
5813
+ const g = libraryGlobals();
5814
+ const registered = /* @__PURE__ */ new Map();
5815
+ const previous = { chunk: pos.chunk, line: pos.line, registering };
5816
+ registering = registered;
5817
+ pos.chunk = "user_function";
5818
+ pos.line = 0;
5819
+ g.set("redis", loadRedisLib());
5820
+ try {
5821
+ chunk.run(g)();
5822
+ } catch (error) {
5823
+ let text8;
5824
+ if (error instanceof LuaError) {
5825
+ const value = error.value;
5826
+ const message = value instanceof LuaTable ? value.getStr("err") : void 0;
5827
+ text8 = typeof message === "string" ? message : `ERR ${tostringValue(value)}`;
5828
+ } else if (error instanceof RangeError) text8 = "ERR user_function: stack overflow";
5829
+ else throw error;
5830
+ throw new ScriptFailure(`ERR Error registering functions: ${text8}`);
5831
+ } finally {
5832
+ if (runtimeRedis !== null) g.set("redis", runtimeRedis);
5833
+ registering = previous.registering;
5834
+ pos.chunk = previous.chunk;
5835
+ pos.line = previous.line;
5836
+ }
5837
+ if (registered.size === 0) throw new ScriptFailure("ERR No functions registered");
5838
+ return registered;
5839
+ }
5840
+ function runFunction(fn, keys, argv, host, version) {
5841
+ libraryGlobals();
5842
+ const keysTable = new LuaTable();
5843
+ keysTable.arr = keys;
5844
+ const argvTable = new LuaTable();
5845
+ argvTable.arr = argv;
5846
+ const previous = { host: state.host, chunk: pos.chunk };
5847
+ state.host = host;
5848
+ if (version !== void 0) state.version = version;
5849
+ pos.chunk = "user_function";
5850
+ pos.line = 0;
5851
+ try {
5852
+ return firstValue(fn.callback(keysTable, argvTable));
5853
+ } catch (error) {
5854
+ return failure(error, fn.name);
5855
+ } finally {
5856
+ state.host = previous.host;
5857
+ pos.chunk = previous.chunk;
5858
+ }
5859
+ }
5860
+ function firstValue(result) {
5861
+ return Array.isArray(result) ? result[0] : result;
5862
+ }
5863
+
5864
+ // src/functions.ts
5865
+ var text4 = (bytes2) => bytes2 ? latin1(bytes2) : "";
5866
+ var upper3 = (bytes2) => text4(bytes2).toUpperCase();
5867
+ var raw = (value) => bulk(fromLatin1(value));
5868
+ var unsupported2 = (sub) => err(`ERR FUNCTION ${sub} is not supported by the Mockingbird Redis emulator`);
5869
+ function metadata(code) {
5870
+ if (!code.startsWith("#!")) return "ERR Missing library metadata";
5871
+ const newline = code.indexOf("\n");
5872
+ const line = code.slice(2, newline < 0 ? code.length : newline);
5873
+ const [engine = "", ...parts] = line.split(" ").filter(Boolean);
5874
+ if (engine.toLowerCase() !== "lua") return `ERR Engine '${engine}' not found`;
5875
+ let name;
5876
+ for (const part of parts) {
5877
+ if (!part.startsWith("name=")) return `ERR Invalid metadata value given: ${part}`;
5878
+ name = part.slice(5);
5879
+ }
5880
+ if (name === void 0) return "ERR Library name was not given";
5881
+ if (!/^[A-Za-z0-9_]+$/.test(name))
5882
+ return "ERR Library names can only contain letters, numbers, or underscores(_) and must be at least one character long";
5883
+ return { name };
5884
+ }
5885
+ var FunctionRegistry = class {
5886
+ libraries = /* @__PURE__ */ new Map();
5887
+ find(name) {
5888
+ for (const library of this.libraries.values()) {
5889
+ const fn = library.functions.get(name);
5890
+ if (fn) return fn;
5891
+ }
5892
+ return void 0;
5893
+ }
5894
+ clear() {
5895
+ this.libraries.clear();
5896
+ }
5897
+ command(args, apply) {
5898
+ const sub = upper3(args[0]);
5899
+ if (sub === "LOAD") return this.load(args.slice(1), apply);
5900
+ if (sub === "LIST") return this.list(args.slice(1));
5901
+ if (sub === "DELETE") {
5902
+ if (args.length !== 2) return arityError("function|delete");
5903
+ if (!this.libraries.has(text4(args[1]))) return err("ERR Library not found");
5904
+ if (!apply) return queued();
5905
+ this.libraries.delete(text4(args[1]));
5906
+ return ok();
5907
+ }
5908
+ if (sub === "FLUSH") {
5909
+ if (args.length > 2) return arityError("function|flush");
5910
+ const mode = upper3(args[1]);
5911
+ if (args.length === 2 && mode !== "ASYNC" && mode !== "SYNC")
5912
+ return err("ERR FUNCTION FLUSH only supports SYNC|ASYNC option");
5913
+ if (!apply) return queued();
5914
+ this.libraries.clear();
5915
+ return ok();
5916
+ }
5917
+ if (sub === "STATS") {
5918
+ let functions = 0;
5919
+ for (const library of this.libraries.values()) functions += library.functions.size;
5920
+ return map([
5921
+ [bulk("running_script"), nil()],
5922
+ [
5923
+ bulk("engines"),
5924
+ map([
5925
+ [
5926
+ bulk("LUA"),
5927
+ map([
5928
+ [bulk("libraries_count"), int(this.libraries.size)],
5929
+ [bulk("functions_count"), int(functions)]
5930
+ ])
5931
+ ]
5932
+ ])
5933
+ ]
5934
+ ]);
5935
+ }
5936
+ if (sub === "KILL") return err("NOTBUSY No scripts in execution right now.");
5937
+ if (sub === "DUMP" || sub === "RESTORE" || sub === "HELP") return unsupported2(sub);
5938
+ if (args.length === 0) return arityError("function");
5939
+ return err(`ERR unknown subcommand '${text4(args[0])}'. Try FUNCTION HELP.`);
5940
+ }
5941
+ load(args, apply) {
5942
+ const replace = args.length === 2 && upper3(args[0]) === "REPLACE";
5943
+ if (args.length !== 1 && !replace)
5944
+ return args.length === 0 ? arityError("function|load") : syntaxError();
5945
+ const code = text4(args[args.length - 1]);
5946
+ const meta = metadata(code);
5947
+ if (typeof meta === "string") return err(meta);
5948
+ if (this.libraries.has(meta.name) && !replace)
5949
+ return err(`ERR Library '${meta.name}' already exists`);
5950
+ if (!apply) return queued();
5951
+ const newline = code.indexOf("\n");
5952
+ const body = newline < 0 ? "" : code.slice(newline);
5953
+ let functions;
5954
+ try {
5955
+ functions = loadFunctionLibrary(body);
5956
+ } catch (error) {
5957
+ if (error instanceof ScriptFailure) return err(error.message);
5958
+ throw error;
5959
+ }
5960
+ for (const [name] of functions) {
5961
+ for (const library of this.libraries.values()) {
5962
+ if (library.name === meta.name) continue;
5963
+ if (library.functions.has(name)) return err(`ERR Function ${name} already exists`);
5964
+ }
5965
+ }
5966
+ this.libraries.set(meta.name, { name: meta.name, code, functions });
5967
+ return bulk(meta.name);
5968
+ }
5969
+ list(args) {
5970
+ let withCode = false;
5971
+ let pattern = null;
5972
+ for (let i = 0; i < args.length; i++) {
5973
+ const option = upper3(args[i]);
5974
+ if (option === "WITHCODE" && !withCode) withCode = true;
5975
+ else if (option === "LIBRARYNAME" && pattern === null && i + 1 < args.length)
5976
+ pattern = text4(args[++i]);
5977
+ else return err(`ERR Unknown argument ${text4(args[i])}`);
5978
+ }
5979
+ const rows = [];
5980
+ for (const library of this.libraries.values()) {
5981
+ if (pattern !== null && !globMatch(pattern, library.name)) continue;
5982
+ const functions = [...library.functions.values()].map(
5983
+ (fn) => map([
5984
+ [bulk("name"), raw(fn.name)],
5985
+ [bulk("description"), fn.description === null ? nil() : raw(fn.description)],
5986
+ [bulk("flags"), arr(fn.flags.map((flag) => bulk(flag)))]
5987
+ ])
5988
+ );
5989
+ const fields = [
5990
+ [bulk("library_name"), bulk(library.name)],
5991
+ [bulk("engine"), bulk("LUA")],
5992
+ [bulk("functions"), arr(functions)]
5993
+ ];
5994
+ if (withCode) fields.push([bulk("library_code"), raw(library.code)]);
5995
+ rows.push(map(fields));
5996
+ }
5997
+ return arr(rows);
5998
+ }
5999
+ };
6000
+
6001
+ // src/notify.ts
6002
+ var NOTIFY_KEYSPACE = 1 << 0;
6003
+ var NOTIFY_KEYEVENT = 1 << 1;
6004
+ var NOTIFY_GENERIC = 1 << 2;
6005
+ var NOTIFY_STRING = 1 << 3;
6006
+ var NOTIFY_LIST = 1 << 4;
6007
+ var NOTIFY_SET = 1 << 5;
6008
+ var NOTIFY_HASH = 1 << 6;
6009
+ var NOTIFY_ZSET = 1 << 7;
6010
+ var NOTIFY_EXPIRED = 1 << 8;
6011
+ var NOTIFY_EVICTED = 1 << 9;
6012
+ var NOTIFY_STREAM = 1 << 10;
6013
+ var NOTIFY_KEY_MISS = 1 << 11;
6014
+ var NOTIFY_MODULE = 1 << 13;
6015
+ var NOTIFY_NEW = 1 << 14;
6016
+ var NOTIFY_ALL = NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED | NOTIFY_STREAM | NOTIFY_MODULE;
6017
+ var CLASSES = {
6018
+ A: NOTIFY_ALL,
6019
+ g: NOTIFY_GENERIC,
6020
+ $: NOTIFY_STRING,
6021
+ l: NOTIFY_LIST,
6022
+ s: NOTIFY_SET,
6023
+ h: NOTIFY_HASH,
6024
+ z: NOTIFY_ZSET,
6025
+ x: NOTIFY_EXPIRED,
6026
+ e: NOTIFY_EVICTED,
6027
+ K: NOTIFY_KEYSPACE,
6028
+ E: NOTIFY_KEYEVENT,
6029
+ t: NOTIFY_STREAM,
6030
+ m: NOTIFY_KEY_MISS,
6031
+ d: NOTIFY_MODULE,
6032
+ n: NOTIFY_NEW
6033
+ };
6034
+ function parseNotifyFlags(value) {
6035
+ let flags = 0;
6036
+ for (const char of value) {
6037
+ const flag = CLASSES[char];
6038
+ if (flag === void 0) return null;
6039
+ flags |= flag;
6040
+ }
6041
+ return flags;
6042
+ }
6043
+ function formatNotifyFlags(flags) {
6044
+ let out = "";
6045
+ if ((flags & NOTIFY_ALL) === NOTIFY_ALL) out += "A";
6046
+ else {
6047
+ const order = [
6048
+ ["g", NOTIFY_GENERIC],
6049
+ ["$", NOTIFY_STRING],
6050
+ ["l", NOTIFY_LIST],
6051
+ ["s", NOTIFY_SET],
6052
+ ["h", NOTIFY_HASH],
6053
+ ["z", NOTIFY_ZSET],
6054
+ ["x", NOTIFY_EXPIRED],
6055
+ ["e", NOTIFY_EVICTED],
6056
+ ["t", NOTIFY_STREAM],
6057
+ ["d", NOTIFY_MODULE],
6058
+ ["n", NOTIFY_NEW]
6059
+ ];
6060
+ for (const [char, flag] of order) if (flags & flag) out += char;
6061
+ }
6062
+ if (flags & NOTIFY_KEYSPACE) out += "K";
6063
+ if (flags & NOTIFY_KEYEVENT) out += "E";
6064
+ if (flags & NOTIFY_KEY_MISS) out += "m";
6065
+ return out;
6066
+ }
6067
+ var text5 = (bytes2) => bytes2 ? latin1(bytes2) : "";
6068
+ var hasOption = (args, ...names) => args.some((arg) => names.includes(text5(arg).toUpperCase()));
6069
+ var intOf = (reply) => reply.t === "int" ? Number(reply.v) : reply.t === "bool" ? Number(reply.v) : 0;
6070
+ var NOTIFIED = /* @__PURE__ */ new Set([
6071
+ "set",
6072
+ "setnx",
6073
+ "setex",
6074
+ "psetex",
6075
+ "getset",
6076
+ "mset",
6077
+ "msetnx",
6078
+ "getex",
6079
+ "getdel",
6080
+ "incr",
6081
+ "incrby",
6082
+ "decr",
6083
+ "decrby",
6084
+ "incrbyfloat",
6085
+ "append",
6086
+ "setrange",
6087
+ "setbit",
6088
+ "del",
6089
+ "unlink",
6090
+ "expire",
6091
+ "pexpire",
6092
+ "expireat",
6093
+ "pexpireat",
6094
+ "persist",
6095
+ "rename",
6096
+ "renamenx",
6097
+ "lpush",
6098
+ "rpush",
6099
+ "lpushx",
6100
+ "rpushx",
6101
+ "lpop",
6102
+ "rpop",
6103
+ "lset",
6104
+ "linsert",
6105
+ "lrem",
6106
+ "ltrim",
6107
+ "lmove",
6108
+ "rpoplpush",
6109
+ "blmove",
6110
+ "brpoplpush",
6111
+ "lmpop",
6112
+ "blpop",
6113
+ "brpop",
6114
+ "sadd",
6115
+ "srem",
6116
+ "spop",
6117
+ "smove",
6118
+ "sinterstore",
6119
+ "sunionstore",
6120
+ "sdiffstore",
6121
+ "hset",
6122
+ "hmset",
6123
+ "hsetnx",
6124
+ "hdel",
6125
+ "hincrby",
6126
+ "hincrbyfloat",
6127
+ "zadd",
6128
+ "zincrby",
6129
+ "zrem",
6130
+ "zpopmin",
6131
+ "zpopmax",
6132
+ "bzpopmin",
6133
+ "bzpopmax",
6134
+ "zremrangebyscore",
6135
+ "zremrangebyrank",
6136
+ "zremrangebylex",
6137
+ "zunionstore",
6138
+ "zinterstore",
6139
+ "zdiffstore",
6140
+ "zrangestore",
6141
+ "xadd",
6142
+ "xdel",
6143
+ "xtrim",
6144
+ "xgroup",
6145
+ "pfadd",
6146
+ "pfmerge"
6147
+ ]);
6148
+ function notifiedKeys(command, args) {
6149
+ switch (command) {
6150
+ case "mset":
6151
+ case "msetnx":
6152
+ return args.filter((_, index) => index % 2 === 0).map(text5);
6153
+ case "del":
6154
+ case "unlink":
6155
+ return args.map(text5);
6156
+ case "rename":
6157
+ case "renamenx":
6158
+ case "lmove":
6159
+ case "rpoplpush":
6160
+ case "blmove":
6161
+ case "brpoplpush":
6162
+ case "smove":
6163
+ return [text5(args[0]), text5(args[1])];
6164
+ case "lmpop": {
6165
+ const count = Number(text5(args[0]));
6166
+ return Number.isInteger(count) && count > 0 ? args.slice(1, 1 + count).map(text5) : [];
6167
+ }
6168
+ case "blpop":
6169
+ case "brpop":
6170
+ case "bzpopmin":
6171
+ case "bzpopmax":
6172
+ return args.slice(0, -1).map(text5);
6173
+ case "xgroup":
6174
+ return [text5(args[1])];
6175
+ default:
6176
+ return [text5(args[0])];
6177
+ }
6178
+ }
6179
+ var POP = { left: "lpop", right: "rpop" };
6180
+ var PUSH = { left: "lpush", right: "rpush" };
6181
+ function moveEvents(src, dst, from, to, srcGone) {
6182
+ const events = [
6183
+ { cls: NOTIFY_LIST, event: PUSH[to] ?? "lpush", key: dst },
6184
+ { cls: NOTIFY_LIST, event: POP[from] ?? "lpop", key: src }
6185
+ ];
6186
+ if (srcGone) events.push({ cls: NOTIFY_GENERIC, event: "del", key: src });
6187
+ return events;
6188
+ }
6189
+ function commandEvents(command, args, reply, before, after) {
6190
+ const events = [];
6191
+ const emit = (cls, event, key2) => events.push({ cls, event, key: key2 });
6192
+ const changed = (key2) => before(key2).gen !== after(key2).gen;
6193
+ const gone = (key2) => before(key2).exists && !after(key2).exists;
6194
+ const key = text5(args[0]);
6195
+ const delIfGone = (target = key) => {
6196
+ if (gone(target)) emit(NOTIFY_GENERIC, "del", target);
6197
+ };
6198
+ const simple2 = (cls, event) => {
6199
+ if (changed(key)) emit(cls, event, key);
6200
+ };
6201
+ for (const name of notifiedKeys(command, args))
6202
+ if (!before(name).exists && after(name).exists) emit(NOTIFY_NEW, "new", name);
6203
+ switch (command) {
6204
+ case "set":
6205
+ if (!changed(key)) break;
6206
+ emit(NOTIFY_STRING, "set", key);
6207
+ if (hasOption(args.slice(2), "EX", "PX", "EXAT", "PXAT")) emit(NOTIFY_GENERIC, "expire", key);
6208
+ break;
6209
+ case "setex":
6210
+ case "psetex":
6211
+ emit(NOTIFY_STRING, "set", key);
6212
+ emit(NOTIFY_GENERIC, "expire", key);
6213
+ break;
6214
+ case "setnx":
6215
+ case "getset":
6216
+ simple2(NOTIFY_STRING, "set");
6217
+ break;
6218
+ case "mset":
6219
+ case "msetnx":
6220
+ for (const name of notifiedKeys(command, args))
6221
+ if (changed(name)) emit(NOTIFY_STRING, "set", name);
6222
+ break;
6223
+ case "getex":
6224
+ if (!changed(key)) break;
6225
+ if (gone(key)) emit(NOTIFY_GENERIC, "del", key);
6226
+ else if (hasOption(args.slice(1), "PERSIST")) emit(NOTIFY_GENERIC, "persist", key);
6227
+ else emit(NOTIFY_GENERIC, "expire", key);
6228
+ break;
6229
+ case "getdel":
6230
+ delIfGone();
6231
+ break;
6232
+ case "incr":
6233
+ case "incrby":
6234
+ case "decr":
6235
+ case "decrby":
6236
+ simple2(NOTIFY_STRING, "incrby");
6237
+ break;
6238
+ case "incrbyfloat":
6239
+ case "append":
6240
+ case "setrange":
6241
+ case "setbit":
6242
+ simple2(NOTIFY_STRING, command);
6243
+ break;
6244
+ case "del":
6245
+ case "unlink":
6246
+ for (const name of notifiedKeys(command, args)) delIfGone(name);
6247
+ break;
6248
+ case "expire":
6249
+ case "pexpire":
6250
+ case "expireat":
6251
+ case "pexpireat":
6252
+ if (!changed(key)) break;
6253
+ if (gone(key)) emit(NOTIFY_GENERIC, "del", key);
6254
+ else emit(NOTIFY_GENERIC, "expire", key);
6255
+ break;
6256
+ case "persist":
6257
+ if (intOf(reply) === 1) emit(NOTIFY_GENERIC, "persist", key);
6258
+ break;
6259
+ case "rename":
6260
+ case "renamenx":
6261
+ if (reply.t === "simple" || intOf(reply) === 1) {
6262
+ emit(NOTIFY_GENERIC, "rename_from", key);
6263
+ emit(NOTIFY_GENERIC, "rename_to", text5(args[1]));
6264
+ }
6265
+ break;
6266
+ case "lpush":
6267
+ case "lpushx":
6268
+ simple2(NOTIFY_LIST, "lpush");
6269
+ break;
6270
+ case "rpush":
6271
+ case "rpushx":
6272
+ simple2(NOTIFY_LIST, "rpush");
6273
+ break;
6274
+ case "lpop":
6275
+ case "rpop":
6276
+ case "ltrim":
6277
+ if (!changed(key)) break;
6278
+ emit(NOTIFY_LIST, command, key);
6279
+ delIfGone();
6280
+ break;
6281
+ case "lset":
6282
+ case "linsert":
6283
+ simple2(NOTIFY_LIST, command);
6284
+ break;
6285
+ case "lrem":
6286
+ if (intOf(reply) === 0) break;
6287
+ emit(NOTIFY_LIST, "lrem", key);
6288
+ delIfGone();
6289
+ break;
6290
+ case "lmove":
6291
+ case "blmove":
6292
+ case "rpoplpush":
6293
+ case "brpoplpush": {
6294
+ if (reply.t !== "bulk" || reply.v === null) break;
6295
+ const rpoplpush = command.endsWith("rpoplpush");
6296
+ const from = rpoplpush ? "right" : text5(args[2]).toLowerCase();
6297
+ const to = rpoplpush ? "left" : text5(args[3]).toLowerCase();
6298
+ const dst = text5(args[1]);
6299
+ events.push(
6300
+ ...moveEvents(
6301
+ key,
6302
+ dst,
6303
+ from === "left" ? "left" : "right",
6304
+ to === "left" ? "left" : "right",
6305
+ gone(key)
6306
+ )
6307
+ );
6308
+ break;
6309
+ }
6310
+ case "lmpop":
6311
+ case "blpop":
6312
+ case "brpop": {
6313
+ if (reply.t !== "array" || !reply.v) break;
6314
+ const [popped] = reply.v;
6315
+ const name = popped?.t === "bulk" && popped.v ? latin1(popped.v) : "";
6316
+ const left = command === "blpop" || command === "lmpop" && args.some((arg) => text5(arg).toUpperCase() === "LEFT");
6317
+ emit(NOTIFY_LIST, left ? "lpop" : "rpop", name);
6318
+ delIfGone(name);
6319
+ break;
6320
+ }
6321
+ case "sadd":
6322
+ if (intOf(reply) > 0) emit(NOTIFY_SET, "sadd", key);
6323
+ break;
6324
+ case "srem":
6325
+ if (intOf(reply) === 0) break;
6326
+ emit(NOTIFY_SET, "srem", key);
6327
+ delIfGone();
6328
+ break;
6329
+ case "spop":
6330
+ if (!changed(key)) break;
6331
+ emit(NOTIFY_SET, "spop", key);
6332
+ delIfGone();
6333
+ break;
6334
+ case "smove": {
6335
+ if (intOf(reply) !== 1) break;
6336
+ const dst = text5(args[1]);
6337
+ emit(NOTIFY_SET, "srem", key);
6338
+ delIfGone();
6339
+ if (changed(dst)) emit(NOTIFY_SET, "sadd", dst);
6340
+ break;
6341
+ }
6342
+ case "sinterstore":
6343
+ case "sunionstore":
6344
+ case "sdiffstore":
6345
+ if (after(key).exists) emit(NOTIFY_SET, command, key);
6346
+ else if (before(key).exists) emit(NOTIFY_GENERIC, "del", key);
6347
+ break;
6348
+ case "hset":
6349
+ case "hmset":
6350
+ simple2(NOTIFY_HASH, "hset");
6351
+ break;
6352
+ case "hsetnx":
6353
+ if (intOf(reply) === 1) emit(NOTIFY_HASH, "hset", key);
6354
+ break;
6355
+ case "hincrby":
6356
+ case "hincrbyfloat":
6357
+ simple2(NOTIFY_HASH, command);
6358
+ break;
6359
+ case "hdel":
6360
+ if (intOf(reply) === 0) break;
6361
+ emit(NOTIFY_HASH, "hdel", key);
6362
+ delIfGone();
6363
+ break;
6364
+ case "zadd":
6365
+ simple2(NOTIFY_ZSET, hasOption(args.slice(1), "INCR") ? "zincr" : "zadd");
6366
+ break;
6367
+ case "zincrby":
6368
+ simple2(NOTIFY_ZSET, "zincr");
6369
+ break;
6370
+ case "zrem":
6371
+ case "zremrangebyscore":
6372
+ case "zremrangebyrank":
6373
+ case "zremrangebylex":
6374
+ if (intOf(reply) === 0) break;
6375
+ emit(NOTIFY_ZSET, command, key);
6376
+ delIfGone();
6377
+ break;
6378
+ case "zpopmin":
6379
+ case "zpopmax":
6380
+ if (!changed(key)) break;
6381
+ emit(NOTIFY_ZSET, command, key);
6382
+ delIfGone();
6383
+ break;
6384
+ case "bzpopmin":
6385
+ case "bzpopmax": {
6386
+ if (reply.t !== "array" || !reply.v) break;
6387
+ const [popped] = reply.v;
6388
+ const name = popped?.t === "bulk" && popped.v ? latin1(popped.v) : "";
6389
+ emit(NOTIFY_ZSET, command.slice(1), name);
6390
+ delIfGone(name);
6391
+ break;
6392
+ }
6393
+ case "zunionstore":
6394
+ case "zinterstore":
6395
+ case "zdiffstore":
6396
+ case "zrangestore":
6397
+ if (after(key).exists) emit(NOTIFY_ZSET, command, key);
6398
+ else if (before(key).exists) emit(NOTIFY_GENERIC, "del", key);
6399
+ break;
6400
+ case "xadd":
6401
+ if (reply.t !== "bulk" || reply.v === null) break;
6402
+ emit(NOTIFY_STREAM, "xadd", key);
6403
+ if (after(key).size < before(key).size + 1) emit(NOTIFY_STREAM, "xtrim", key);
6404
+ break;
6405
+ case "xdel":
6406
+ case "xtrim":
6407
+ if (intOf(reply) > 0) emit(NOTIFY_STREAM, command, key);
6408
+ break;
6409
+ case "xgroup": {
6410
+ const sub = text5(args[0]).toLowerCase();
6411
+ const known = ["create", "setid", "destroy", "createconsumer", "delconsumer"];
6412
+ if (!known.includes(sub)) break;
6413
+ if ((sub === "destroy" || sub === "createconsumer") && intOf(reply) !== 1) break;
6414
+ emit(NOTIFY_STREAM, `xgroup-${sub}`, text5(args[1]));
6415
+ break;
6416
+ }
6417
+ case "pfadd":
6418
+ if (intOf(reply) === 1) emit(NOTIFY_STRING, "pfadd", key);
6419
+ break;
6420
+ case "pfmerge":
6421
+ emit(NOTIFY_STRING, "pfadd", key);
6422
+ break;
6423
+ default:
6424
+ break;
6425
+ }
6426
+ return events;
6427
+ }
5586
6428
 
5587
6429
  // src/portable.ts
5588
6430
  var encodePortable = (value) => {
@@ -5653,6 +6495,325 @@ function assertPortableDatabase(value) {
5653
6495
  }
5654
6496
  }
5655
6497
 
6498
+ // src/zset.ts
6499
+ var ZSET_WRITES = [
6500
+ "zunionstore",
6501
+ "zinterstore",
6502
+ "zdiffstore",
6503
+ "zrangestore",
6504
+ "zremrangebylex"
6505
+ ];
6506
+ var text6 = (bytes2) => bytes2 ? latin1(bytes2) : "";
6507
+ var upper4 = (bytes2) => text6(bytes2).toUpperCase();
6508
+ function scoreReply(score, proto) {
6509
+ return proto === 3 ? { t: "double", v: score } : bulk(formatScore(score));
6510
+ }
6511
+ function scoredReply(items, withScores, proto) {
6512
+ if (!withScores) return arr(items.map((item) => ({ t: "bulk", v: item.member })));
6513
+ if (proto === 3)
6514
+ return arr(items.map((item) => arr([{ t: "bulk", v: item.member }, scoreReply(item.score, 3)])));
6515
+ return arr(items.flatMap((item) => [{ t: "bulk", v: item.member }, scoreReply(item.score, 2)]));
6516
+ }
6517
+ function ordered(zset) {
6518
+ return [...zset.members.values()].sort(
6519
+ (a, b) => a.score !== b.score ? a.score - b.score : cmpBytes(a.member, b.member)
6520
+ );
6521
+ }
6522
+ function zsetAt(database, key) {
6523
+ const value = database.get(key);
6524
+ if (!value) return null;
6525
+ return value.kind === "zset" ? value : wrongType();
6526
+ }
6527
+ var isReply2 = (value) => typeof value === "object" && value !== null && "t" in value;
6528
+ function store(ctx, dest, items) {
6529
+ ctx.database.delete(dest);
6530
+ if (items.length === 0) return int(0);
6531
+ const members = /* @__PURE__ */ new Map();
6532
+ for (const item of items) members.set(memberKey(item.member), { ...item });
6533
+ ctx.database.put(dest, { kind: "zset", members });
6534
+ ctx.wake(dest);
6535
+ return int(members.size);
6536
+ }
6537
+ function parseFloatText(raw2) {
6538
+ const value = raw2.trim().toLowerCase();
6539
+ if (value === "inf" || value === "+inf") return Infinity;
6540
+ if (value === "-inf") return -Infinity;
6541
+ if (!/^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?$/.test(value)) return null;
6542
+ const parsed = Number(value);
6543
+ return Number.isNaN(parsed) ? null : parsed;
6544
+ }
6545
+ function parseScoreBound(raw2) {
6546
+ const exclusive = raw2.startsWith("(");
6547
+ const value = parseFloatText(exclusive ? raw2.slice(1) : raw2);
6548
+ return value === null ? null : { value, exclusive };
6549
+ }
6550
+ function parseLexBound(raw2) {
6551
+ if (!raw2 || raw2.length === 0) return null;
6552
+ const head = raw2[0];
6553
+ if (raw2.length === 1 && head === 45) return { kind: "min" };
6554
+ if (raw2.length === 1 && head === 43) return { kind: "max" };
6555
+ if (head === 91 || head === 40)
6556
+ return { kind: "at", value: raw2.slice(1), exclusive: head === 40 };
6557
+ return null;
6558
+ }
6559
+ function aboveMin(member, min) {
6560
+ if (min.kind === "min") return true;
6561
+ if (min.kind === "max") return false;
6562
+ const order = cmpBytes(member, min.value);
6563
+ return min.exclusive ? order > 0 : order >= 0;
6564
+ }
6565
+ function belowMax(member, max) {
6566
+ if (max.kind === "max") return true;
6567
+ if (max.kind === "min") return false;
6568
+ const order = cmpBytes(member, max.value);
6569
+ return max.exclusive ? order < 0 : order <= 0;
6570
+ }
6571
+ var inScore = (score, min, max) => (min.exclusive ? score > min.value : score >= min.value) && (max.exclusive ? score < max.value : score <= max.value);
6572
+ function selectRange(ctx, command, args) {
6573
+ let by = command.includes("byscore") ? "score" : command.includes("bylex") ? "lex" : "rank";
6574
+ let rev = command.startsWith("zrev");
6575
+ const modern = command === "zrange" || command === "zrangestore";
6576
+ let withScores = false;
6577
+ let offset = 0n;
6578
+ let limit = -1n;
6579
+ for (let i = 3; i < args.length; i++) {
6580
+ const option = upper4(args[i]);
6581
+ if (option === "WITHSCORES" && command !== "zrangestore") withScores = true;
6582
+ else if (option === "LIMIT" && i + 2 < args.length) {
6583
+ const o = parseI64(args[i + 1] ?? utf8(""));
6584
+ const c = parseI64(args[i + 2] ?? utf8(""));
6585
+ if (o === null || c === null) return notInteger();
6586
+ offset = o;
6587
+ limit = c;
6588
+ i += 2;
6589
+ } else if (modern && option === "BYSCORE" && by === "rank") by = "score";
6590
+ else if (modern && option === "BYLEX" && by === "rank") by = "lex";
6591
+ else if (modern && option === "REV") rev = true;
6592
+ else return syntaxError();
6593
+ }
6594
+ if (withScores && by === "lex")
6595
+ return err("ERR syntax error, WITHSCORES not supported in combination with BYLEX");
6596
+ if ((offset !== 0n || limit !== -1n) && by === "rank")
6597
+ return err(
6598
+ "ERR syntax error, LIMIT is only supported in combination with either BYSCORE or BYLEX"
6599
+ );
6600
+ const swap = rev && by !== "rank";
6601
+ const minArg = swap ? args[2] : args[1];
6602
+ const maxArg = swap ? args[1] : args[2];
6603
+ let pick;
6604
+ if (by === "rank") {
6605
+ const start = parseI64(minArg ?? utf8(""));
6606
+ const end = parseI64(maxArg ?? utf8(""));
6607
+ if (start === null || end === null) return notInteger();
6608
+ pick = (members) => {
6609
+ const length2 = BigInt(members.length);
6610
+ let from = start < 0n ? length2 + start : start;
6611
+ let to = end < 0n ? length2 + end : end;
6612
+ if (from < 0n) from = 0n;
6613
+ if (from > to || from >= length2) return [];
6614
+ if (to >= length2) to = length2 - 1n;
6615
+ const source = rev ? members.slice().reverse() : members;
6616
+ return source.slice(Number(from), Number(to) + 1);
6617
+ };
6618
+ } else {
6619
+ let test;
6620
+ if (by === "score") {
6621
+ const min = parseScoreBound(text6(minArg));
6622
+ const max = parseScoreBound(text6(maxArg));
6623
+ if (!min || !max) return err("ERR min or max is not a float");
6624
+ test = (item) => inScore(item.score, min, max);
6625
+ } else {
6626
+ const min = parseLexBound(minArg);
6627
+ const max = parseLexBound(maxArg);
6628
+ if (!min || !max) return err("ERR min or max not valid string range item");
6629
+ test = (item) => aboveMin(item.member, min) && belowMax(item.member, max);
6630
+ }
6631
+ pick = (members) => {
6632
+ if (offset < 0n) return [];
6633
+ const source = (rev ? members.slice().reverse() : members).filter(test);
6634
+ const from = Number(offset);
6635
+ return limit < 0n ? source.slice(from) : source.slice(from, from + Number(limit));
6636
+ };
6637
+ }
6638
+ const zset = zsetAt(ctx.database, text6(args[0]));
6639
+ if (isReply2(zset)) return zset;
6640
+ return { items: zset ? pick(ordered(zset)) : [], withScores };
6641
+ }
6642
+ function cmdZrange(ctx, command, args) {
6643
+ if (command === "zrangestore") {
6644
+ if (args.length < 4) return arityError(command);
6645
+ const selected2 = selectRange(ctx, command, args.slice(1));
6646
+ if (isReply2(selected2)) return selected2;
6647
+ if (!ctx.apply) return queued();
6648
+ return store(ctx, text6(args[0]), selected2.items);
6649
+ }
6650
+ if (args.length < 3) return arityError(command);
6651
+ const selected = selectRange(ctx, command, args);
6652
+ if (isReply2(selected)) return selected;
6653
+ return scoredReply(selected.items, selected.withScores, ctx.proto);
6654
+ }
6655
+ function cmdZlex(ctx, command, args) {
6656
+ if (args.length !== 3) return arityError(command);
6657
+ const min = parseLexBound(args[1]);
6658
+ const max = parseLexBound(args[2]);
6659
+ if (!min || !max) return err("ERR min or max not valid string range item");
6660
+ const key = text6(args[0]);
6661
+ const zset = zsetAt(ctx.database, key);
6662
+ if (isReply2(zset)) return zset;
6663
+ if (!zset) return int(0);
6664
+ const matched = ordered(zset).filter(
6665
+ (item) => aboveMin(item.member, min) && belowMax(item.member, max)
6666
+ );
6667
+ if (command === "zlexcount") return int(matched.length);
6668
+ if (!ctx.apply) return queued();
6669
+ for (const item of matched) zset.members.delete(memberKey(item.member));
6670
+ if (matched.length > 0) {
6671
+ if (zset.members.size === 0) ctx.database.delete(key);
6672
+ else ctx.database.put(key, zset);
6673
+ }
6674
+ return int(matched.length);
6675
+ }
6676
+ function inputs(database, keys) {
6677
+ const out = [];
6678
+ for (const key of keys) {
6679
+ const value = database.get(key);
6680
+ if (!value) out.push(null);
6681
+ else if (value.kind === "zset") out.push(value.members);
6682
+ else if (value.kind === "set") {
6683
+ const members = /* @__PURE__ */ new Map();
6684
+ for (const [id, member] of value.members) members.set(id, { member, score: 1 });
6685
+ out.push(members);
6686
+ } else return wrongType();
6687
+ }
6688
+ return out;
6689
+ }
6690
+ var nanToZero = (value) => Number.isNaN(value) ? 0 : value;
6691
+ function cmdZalgebra(ctx, command, args) {
6692
+ const stored = command.endsWith("store");
6693
+ const base = stored ? 1 : 0;
6694
+ if (args.length < base + 2) return arityError(command);
6695
+ const numkeys = parseI64(args[base] ?? utf8(""));
6696
+ if (numkeys === null) return notInteger();
6697
+ if (numkeys < 1n) return err(`ERR at least 1 input key is needed for '${command}' command`);
6698
+ if (numkeys > BigInt(args.length - base - 1)) return syntaxError();
6699
+ const count = Number(numkeys);
6700
+ const keys = args.slice(base + 1, base + 1 + count).map(text6);
6701
+ const diff = command.startsWith("zdiff");
6702
+ const weights = keys.map(() => 1);
6703
+ let aggregate = "SUM";
6704
+ let withScores = false;
6705
+ for (let i = base + 1 + count; i < args.length; i++) {
6706
+ const option = upper4(args[i]);
6707
+ if (option === "WEIGHTS" && !diff && i + count < args.length) {
6708
+ for (let j = 0; j < count; j++) {
6709
+ const weight = parseFloatText(text6(args[i + 1 + j]));
6710
+ if (weight === null) return err("ERR weight value is not a float");
6711
+ weights[j] = weight;
6712
+ }
6713
+ i += count;
6714
+ } else if (option === "AGGREGATE" && !diff && i + 1 < args.length) {
6715
+ const kind = upper4(args[++i]);
6716
+ if (kind !== "SUM" && kind !== "MIN" && kind !== "MAX") return syntaxError();
6717
+ aggregate = kind;
6718
+ } else if (option === "WITHSCORES" && !stored) withScores = true;
6719
+ else return syntaxError();
6720
+ }
6721
+ const sets = inputs(ctx.database, keys);
6722
+ if (isReply2(sets)) return sets;
6723
+ const combine = (left, right) => aggregate === "SUM" ? nanToZero(left + right) : aggregate === "MIN" ? Math.min(left, right) : Math.max(left, right);
6724
+ const weighted = (score, index) => nanToZero(score * (weights[index] ?? 1));
6725
+ const result = /* @__PURE__ */ new Map();
6726
+ if (command.startsWith("zunion")) {
6727
+ sets.forEach((members, index) => {
6728
+ for (const [id, item] of members ?? []) {
6729
+ const score = weighted(item.score, index);
6730
+ const current = result.get(id);
6731
+ result.set(id, {
6732
+ member: item.member,
6733
+ score: current ? combine(current.score, score) : score
6734
+ });
6735
+ }
6736
+ });
6737
+ } else if (command.startsWith("zinter")) {
6738
+ const [first2, ...rest] = sets;
6739
+ for (const [id, item] of first2 ?? []) {
6740
+ let score = weighted(item.score, 0);
6741
+ let everywhere = true;
6742
+ rest.forEach((members, offset) => {
6743
+ const other = members?.get(id);
6744
+ if (!other) everywhere = false;
6745
+ else score = combine(score, weighted(other.score, offset + 1));
6746
+ });
6747
+ if (everywhere) result.set(id, { member: item.member, score });
6748
+ }
6749
+ } else {
6750
+ const [first2, ...rest] = sets;
6751
+ for (const [id, item] of first2 ?? [])
6752
+ if (!rest.some((members) => members?.has(id))) result.set(id, { ...item });
6753
+ }
6754
+ const items = [...result.values()].sort(
6755
+ (a, b) => a.score !== b.score ? a.score - b.score : cmpBytes(a.member, b.member)
6756
+ );
6757
+ if (!stored) return scoredReply(items, withScores, ctx.proto);
6758
+ if (!ctx.apply) return queued();
6759
+ return store(ctx, text6(args[0]), items);
6760
+ }
6761
+ function cmdZintercard(ctx, args) {
6762
+ if (args.length < 2) return arityError("zintercard");
6763
+ const numkeys = parseI64(args[0] ?? utf8(""));
6764
+ if (numkeys === null) return notInteger();
6765
+ if (numkeys < 1n) return err("ERR at least 1 input key is needed for 'zintercard' command");
6766
+ if (numkeys > BigInt(args.length - 1)) return syntaxError();
6767
+ const count = Number(numkeys);
6768
+ let limit = 0n;
6769
+ for (let i = 1 + count; i < args.length; i++) {
6770
+ if (upper4(args[i]) !== "LIMIT" || i + 1 >= args.length) return syntaxError();
6771
+ const parsed = parseI64(args[++i] ?? utf8(""));
6772
+ if (parsed === null || parsed < 0n) return err("ERR LIMIT can't be negative");
6773
+ limit = parsed;
6774
+ }
6775
+ const sets = inputs(ctx.database, args.slice(1, 1 + count).map(text6));
6776
+ if (isReply2(sets)) return sets;
6777
+ const [first2, ...rest] = sets;
6778
+ let found = 0;
6779
+ for (const id of first2?.keys() ?? []) {
6780
+ if (!rest.every((members) => members?.has(id))) continue;
6781
+ found++;
6782
+ if (limit > 0n && BigInt(found) >= limit) break;
6783
+ }
6784
+ return int(found);
6785
+ }
6786
+ function cmdZrandmember(ctx, args) {
6787
+ if (args.length < 1 || args.length > 3) return arityError("zrandmember");
6788
+ if (args.length === 3 && upper4(args[2]) !== "WITHSCORES") return syntaxError();
6789
+ const count = args.length >= 2 ? parseI64(args[1] ?? utf8("")) : null;
6790
+ if (args.length >= 2 && count === null) return notInteger();
6791
+ const zset = zsetAt(ctx.database, text6(args[0]));
6792
+ if (isReply2(zset)) return zset;
6793
+ if (count === null) {
6794
+ if (!zset) return nil();
6795
+ const items = ordered(zset);
6796
+ const item = items[Math.floor(ctx.random() * items.length)];
6797
+ return item ? { t: "bulk", v: item.member } : nil();
6798
+ }
6799
+ if (!zset || count === 0n) return arr([]);
6800
+ const pool = ordered(zset);
6801
+ const picked = [];
6802
+ if (count < 0n) {
6803
+ for (let i = 0n; i < -count; i++) {
6804
+ const item = pool[Math.floor(ctx.random() * pool.length)];
6805
+ if (item) picked.push(item);
6806
+ }
6807
+ } else {
6808
+ const take = Math.min(pool.length, Number(count));
6809
+ for (let i = 0; i < take; i++) {
6810
+ const [item] = pool.splice(Math.floor(ctx.random() * pool.length), 1);
6811
+ if (item) picked.push(item);
6812
+ }
6813
+ }
6814
+ return scoredReply(picked, args.length === 3, ctx.proto);
6815
+ }
6816
+
5656
6817
  // src/engine.ts
5657
6818
  var RedisConnectionError = class extends Error {
5658
6819
  constructor(message) {
@@ -5689,7 +6850,9 @@ var IMMEDIATE = /* @__PURE__ */ new Set([
5689
6850
  "subscribe",
5690
6851
  "unsubscribe",
5691
6852
  "psubscribe",
5692
- "punsubscribe"
6853
+ "punsubscribe",
6854
+ "ssubscribe",
6855
+ "sunsubscribe"
5693
6856
  ]);
5694
6857
  var WRITES = /* @__PURE__ */ new Set([
5695
6858
  "set",
@@ -5727,6 +6890,8 @@ var WRITES = /* @__PURE__ */ new Set([
5727
6890
  "hsetnx",
5728
6891
  "lpush",
5729
6892
  "rpush",
6893
+ "lpushx",
6894
+ "rpushx",
5730
6895
  "lpop",
5731
6896
  "rpop",
5732
6897
  "lset",
@@ -5741,6 +6906,9 @@ var WRITES = /* @__PURE__ */ new Set([
5741
6906
  "srem",
5742
6907
  "spop",
5743
6908
  "smove",
6909
+ "sinterstore",
6910
+ "sunionstore",
6911
+ "sdiffstore",
5744
6912
  "zadd",
5745
6913
  "zrem",
5746
6914
  "zincrby",
@@ -5760,7 +6928,10 @@ var WRITES = /* @__PURE__ */ new Set([
5760
6928
  "xautoclaim",
5761
6929
  "eval",
5762
6930
  "evalsha",
5763
- ...EXTRA_WRITES
6931
+ "fcall",
6932
+ ...EXTRA_WRITES,
6933
+ ...ZSET_WRITES,
6934
+ ...BITS_WRITES
5764
6935
  ]);
5765
6936
  var SCRIPT_DENIED_TEXT = scriptDenied().v;
5766
6937
  var SCRIPT_NESTED = /* @__PURE__ */ new Set(["eval", "evalsha", "eval_ro", "evalsha_ro", "fcall", "fcall_ro"]);
@@ -5779,10 +6950,21 @@ var SCRIPT_BLOCKED = /* @__PURE__ */ new Set([
5779
6950
  "unsubscribe",
5780
6951
  "psubscribe",
5781
6952
  "punsubscribe",
6953
+ "ssubscribe",
6954
+ "sunsubscribe",
5782
6955
  "shutdown",
5783
- "monitor"
6956
+ "monitor",
6957
+ "wait",
6958
+ "function"
5784
6959
  ]);
5785
6960
  var VERSION = "7.2.4";
6961
+ var CONFIG_PARAMETERS = [
6962
+ "maxmemory",
6963
+ "maxmemory-policy",
6964
+ "notify-keyspace-events",
6965
+ "timeout",
6966
+ "databases"
6967
+ ];
5786
6968
  var I64_MAX = 9223372036854775807n;
5787
6969
  var BASE_MEMORY = 1048576;
5788
6970
  var SYSTEM_MEMORY = 17179869184;
@@ -5792,11 +6974,11 @@ function humanBytes(value) {
5792
6974
  if (value < 1024 ** 3) return `${(value / 1024 ** 2).toFixed(2)}M`;
5793
6975
  return `${(value / 1024 ** 3).toFixed(2)}G`;
5794
6976
  }
5795
- function text3(bytes2) {
6977
+ function text7(bytes2) {
5796
6978
  return bytes2 ? latin1(bytes2) : "";
5797
6979
  }
5798
- function upper3(bytes2) {
5799
- return text3(bytes2).toUpperCase();
6980
+ function upper5(bytes2) {
6981
+ return text7(bytes2).toUpperCase();
5800
6982
  }
5801
6983
  function scoreText(score) {
5802
6984
  if (Number.isNaN(score)) return "nan";
@@ -5807,7 +6989,7 @@ function scoreText(score) {
5807
6989
  }
5808
6990
  function parseScore(bytes2) {
5809
6991
  if (!bytes2) return null;
5810
- const value = text3(bytes2).trim().toLowerCase();
6992
+ const value = text7(bytes2).trim().toLowerCase();
5811
6993
  if (value === "+inf" || value === "inf") return Infinity;
5812
6994
  if (value === "-inf") return -Infinity;
5813
6995
  if (!/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/.test(value)) return null;
@@ -5816,7 +6998,7 @@ function parseScore(bytes2) {
5816
6998
  }
5817
6999
  function parseTimeout(bytes2) {
5818
7000
  if (!bytes2) return null;
5819
- const value = Number(text3(bytes2));
7001
+ const value = Number(text7(bytes2));
5820
7002
  if (!Number.isFinite(value) || value < 0) return null;
5821
7003
  return value;
5822
7004
  }
@@ -5932,8 +7114,18 @@ var Redis = class {
5932
7114
  nextClientId = 1;
5933
7115
  waiters = [];
5934
7116
  channelSubs = /* @__PURE__ */ new Map();
7117
+ shardSubs = /* @__PURE__ */ new Map();
5935
7118
  patternSubs = /* @__PURE__ */ new Map();
5936
7119
  scripts = /* @__PURE__ */ new Map();
7120
+ functions = new FunctionRegistry();
7121
+ /** `notify-keyspace-events` as Redis's flag bits; 0 publishes nothing. */
7122
+ notifyFlags = 0;
7123
+ expiryTimer;
7124
+ notifyDepth = 0;
7125
+ deferredEvents = [];
7126
+ unsubscribeClock;
7127
+ /** Set while an `EVAL_RO` / `EVALSHA_RO` script or a `no-writes` function runs. */
7128
+ scriptReadOnly = false;
5937
7129
  invoked = "";
5938
7130
  scriptDepth = 0;
5939
7131
  commandCount = 0;
@@ -5950,7 +7142,12 @@ var Redis = class {
5950
7142
  constructor(options = {}) {
5951
7143
  this.clock = options.clock ?? wallClock();
5952
7144
  const count = options.databases ?? 16;
5953
- this.dbs = Array.from({ length: count }, () => new Database(this.clock));
7145
+ this.dbs = Array.from({ length: count }, (_, index) => {
7146
+ const database = new Database(this.clock);
7147
+ database.onExpired = (key) => this.notify(index, NOTIFY_EXPIRED, "expired", key);
7148
+ return database;
7149
+ });
7150
+ this.unsubscribeClock = this.clock.subscribe(() => this.activeExpire());
5954
7151
  this.password = options.password;
5955
7152
  this.users = options.users ?? [];
5956
7153
  this.authRequired = options.password !== void 0 || this.users.length > 0;
@@ -6093,6 +7290,9 @@ var Redis = class {
6093
7290
  this.rngState = this.initialRngState;
6094
7291
  for (const database of this.dbs) database.clear();
6095
7292
  this.scripts.clear();
7293
+ this.functions.clear();
7294
+ this.notifyFlags = 0;
7295
+ this.syncExpiryTimer();
6096
7296
  this.faultValue = null;
6097
7297
  this.clock.reset();
6098
7298
  this.startedAt = this.clock.now();
@@ -6110,6 +7310,9 @@ var Redis = class {
6110
7310
  }
6111
7311
  close() {
6112
7312
  this.closed = true;
7313
+ this.unsubscribeClock();
7314
+ this.notifyFlags = 0;
7315
+ this.syncExpiryTimer();
6113
7316
  for (const cancel of [...this.pendingLatency]) cancel();
6114
7317
  for (const waiter of [...this.waiters]) {
6115
7318
  this.failWaiter(waiter, new RedisConnectionError("Connection is closed"));
@@ -6136,6 +7339,7 @@ var Redis = class {
6136
7339
  watching: [],
6137
7340
  channels: /* @__PURE__ */ new Set(),
6138
7341
  patterns: /* @__PURE__ */ new Set(),
7342
+ shards: /* @__PURE__ */ new Set(),
6139
7343
  dead: false,
6140
7344
  quit: false,
6141
7345
  inExec: false,
@@ -6250,7 +7454,7 @@ var Redis = class {
6250
7454
  this.commandCount++;
6251
7455
  this.commandStats.set(command, (this.commandStats.get(command) ?? 0) + 1);
6252
7456
  if (this.authRequired && !session.authenticated && !PREAUTH.has(command)) return noAuth();
6253
- if (session.channels.size + session.patterns.size > 0 && !PUBSUB_OK.has(command)) {
7457
+ if (this.subscriptions(session) > 0 && !PUBSUB_OK.has(command)) {
6254
7458
  return pubsubOnly(command);
6255
7459
  }
6256
7460
  if (this.faultValue === "busy" && command !== "script" && command !== "shutdown")
@@ -6285,35 +7489,125 @@ var Redis = class {
6285
7489
  * everything else after it ran, so SELECT shows the new database. Commands Redis refuses
6286
7490
  * before running them (unknown, wrong arity, NOAUTH, queued in MULTI) are not shown.
6287
7491
  */
6288
- execCmd(session, command, args, apply, raw = command) {
6289
- if (!apply || !this.monitoring()) return this.execCommand(session, command, args, apply);
6290
- const early = this.scriptDepth === 0 && (command === "eval" || command === "evalsha");
6291
- if (early) this.feedMonitors(session, command, args, raw);
6292
- const reply = this.execCommand(session, command, args, apply);
7492
+ execCmd(session, command, args, apply, raw2 = command) {
7493
+ if (!apply || !this.monitoring()) return this.execNotified(session, command, args, apply);
7494
+ const early = this.scriptDepth === 0 && SCRIPT_NESTED.has(command);
7495
+ if (early) this.feedMonitors(session, command, args, raw2);
7496
+ const reply = this.execNotified(session, command, args, apply);
6293
7497
  if (early) return reply;
6294
- if (reply instanceof Promise) this.feedMonitors(session, command, args, raw);
6295
- else if (!monitorSkips(reply)) this.feedMonitors(session, command, args, raw);
7498
+ if (reply instanceof Promise) this.feedMonitors(session, command, args, raw2);
7499
+ else if (!monitorSkips(reply)) this.feedMonitors(session, command, args, raw2);
6296
7500
  return reply;
6297
7501
  }
6298
7502
  monitoring() {
6299
7503
  for (const session of this.sessions) if (session.monitor) return true;
6300
7504
  return false;
6301
7505
  }
6302
- feedMonitors(session, command, args, raw) {
7506
+ feedMonitors(session, command, args, raw2) {
6303
7507
  const flags = commandFlags(command);
6304
- const scripted = command === "eval" || command === "evalsha";
7508
+ const scripted = SCRIPT_NESTED.has(command);
6305
7509
  if (command === "monitor" || flags.includes("admin")) return;
6306
7510
  if (flags.includes("skip_monitor") && !scripted) return;
6307
7511
  const origin = this.scriptDepth > 0 ? "lua" : session.remoteAddr ?? `127.0.0.1:${session.id}`;
6308
- const line = monitorLine(this.clock.now(), session.db, origin, raw, monitorArgs(command, args));
7512
+ const line = monitorLine(this.clock.now(), session.db, origin, raw2, monitorArgs(command, args));
6309
7513
  for (const other of this.sessions) if (other.monitor && !other.dead) other.onPush(simple(line));
6310
7514
  }
7515
+ /** Runs a command and publishes the keyspace events its effects call for. */
7516
+ execNotified(session, command, args, apply) {
7517
+ const tracked = apply && this.notifyFlags !== 0 && (NOTIFIED.has(command) || command === "copy");
7518
+ if (!tracked) return this.execCommand(session, command, args, apply);
7519
+ this.notifyDepth++;
7520
+ try {
7521
+ return this.execTracked(session, command, args);
7522
+ } finally {
7523
+ this.notifyDepth--;
7524
+ if (this.notifyDepth === 0) {
7525
+ const deferred = this.deferredEvents.splice(0);
7526
+ for (const batch of deferred) this.publishEvents(batch.db, batch.events);
7527
+ }
7528
+ }
7529
+ }
7530
+ execTracked(session, command, args) {
7531
+ const apply = true;
7532
+ const db = session.db;
7533
+ if (command === "copy") return this.execCopy(session, args);
7534
+ const keys = notifiedKeys(command, args);
7535
+ const before = /* @__PURE__ */ new Map();
7536
+ for (const key of keys) before.set(key, this.keyState(db, key));
7537
+ const reply = this.execCommand(session, command, args, apply);
7538
+ if (reply instanceof Promise || reply.t === "error") return reply;
7539
+ const after = /* @__PURE__ */ new Map();
7540
+ const state2 = (map2, key) => map2.get(key) ?? { exists: false, gen: 0, size: 0 };
7541
+ for (const key of keys) after.set(key, this.keyState(db, key));
7542
+ const events = commandEvents(
7543
+ command,
7544
+ args,
7545
+ reply,
7546
+ (key) => state2(before, key),
7547
+ (key) => state2(after, key)
7548
+ );
7549
+ this.publishEvents(db, events);
7550
+ return reply;
7551
+ }
7552
+ keyState(db, key) {
7553
+ const database = this.database(db);
7554
+ const gen = database.generation(key);
7555
+ const value = database.peek(key);
7556
+ return {
7557
+ exists: value !== void 0,
7558
+ gen,
7559
+ size: value?.kind === "stream" ? value.stream.entries.length : 0
7560
+ };
7561
+ }
7562
+ /** `COPY` publishes `copy_to` (and `new`) in the destination database. */
7563
+ execCopy(session, args) {
7564
+ let destDb = session.db;
7565
+ for (let i = 2; i < args.length - 1; i++) {
7566
+ const index = Number(text7(args[i + 1]));
7567
+ if (upper5(args[i]) === "DB" && Number.isInteger(index) && index >= 0 && index < this.dbs.length)
7568
+ destDb = index;
7569
+ }
7570
+ const dest = text7(args[1]);
7571
+ const existed = this.keyState(destDb, dest).exists;
7572
+ const reply = this.execCommand(session, "copy", args, true);
7573
+ if (reply instanceof Promise || reply.t !== "int" || Number(reply.v) !== 1) return reply;
7574
+ if (!existed) this.notify(destDb, NOTIFY_NEW, "new", dest);
7575
+ this.notify(destDb, NOTIFY_GENERIC, "copy_to", dest);
7576
+ return reply;
7577
+ }
7578
+ publishEvents(db, events) {
7579
+ for (const event of events) this.notify(db, event.cls, event.event, event.key);
7580
+ }
7581
+ /** Publish one keyspace event on `__keyspace@<db>__:<key>` and `__keyevent@<db>__:<event>`. */
7582
+ notify(db, cls, event, key) {
7583
+ const flags = this.notifyFlags;
7584
+ if (!(flags & cls) || !(flags & (NOTIFY_KEYSPACE | NOTIFY_KEYEVENT))) return;
7585
+ if (flags & NOTIFY_KEYSPACE) this.deliver(`__keyspace@${db}__:${key}`, fromLatin1(event));
7586
+ if (flags & NOTIFY_KEYEVENT) this.deliver(`__keyevent@${db}__:${event}`, fromLatin1(key));
7587
+ }
7588
+ /** Expire every key whose time has passed, so `expired` events need no further command. */
7589
+ activeExpire() {
7590
+ if (this.closed || !(this.notifyFlags & NOTIFY_EXPIRED)) return;
7591
+ for (const database of this.dbs) database.keys();
7592
+ }
7593
+ /** With a wall clock, nothing moves the clock: poll for expired keys like Redis's `hz` cycle. */
7594
+ syncExpiryTimer() {
7595
+ const wanted = !this.closed && !this.clock.manual && (this.notifyFlags & NOTIFY_EXPIRED) !== 0 && (this.notifyFlags & (NOTIFY_KEYSPACE | NOTIFY_KEYEVENT)) !== 0;
7596
+ if (wanted && this.expiryTimer === void 0) {
7597
+ this.expiryTimer = setInterval(() => this.activeExpire(), 100);
7598
+ const timer = this.expiryTimer;
7599
+ timer.unref?.();
7600
+ } else if (!wanted && this.expiryTimer !== void 0) {
7601
+ clearInterval(this.expiryTimer);
7602
+ this.expiryTimer = void 0;
7603
+ }
7604
+ }
6311
7605
  execCommand(session, command, args, apply) {
6312
7606
  if (apply && this.scriptDepth > 0 && SCRIPT_BLOCKED.has(command)) return scriptDenied();
6313
- if (apply && command === "xread" && args.some((arg) => text3(arg).toUpperCase() === "BLOCK") && this.scriptDepth > 0) {
7607
+ if (apply && command === "xread" && args.some((arg) => text7(arg).toUpperCase() === "BLOCK") && this.scriptDepth > 0) {
6314
7608
  return scriptDenied();
6315
7609
  }
6316
- if (apply && command === "xreadgroup" && args.some((arg) => text3(arg).toUpperCase() === "BLOCK") && this.scriptDepth > 0) {
7610
+ if (apply && command === "xreadgroup" && args.some((arg) => text7(arg).toUpperCase() === "BLOCK") && this.scriptDepth > 0) {
6317
7611
  return scriptDenied();
6318
7612
  }
6319
7613
  const denied = this.guardWrite(session, command, apply);
@@ -6340,7 +7634,7 @@ var Redis = class {
6340
7634
  return bulk(
6341
7635
  this.info(
6342
7636
  session,
6343
- args.map((arg) => text3(arg))
7637
+ args.map((arg) => text7(arg))
6344
7638
  )
6345
7639
  );
6346
7640
  case "time":
@@ -6353,7 +7647,7 @@ var Redis = class {
6353
7647
  case "cluster":
6354
7648
  return clusterDisabled();
6355
7649
  case "module":
6356
- return args.length >= 1 && upper3(args[0]) === "LIST" ? arr([]) : arityError("module");
7650
+ return args.length >= 1 && upper5(args[0]) === "LIST" ? arr([]) : arityError("module");
6357
7651
  case "command":
6358
7652
  return cmdCommand(args);
6359
7653
  case "monitor":
@@ -6370,7 +7664,7 @@ var Redis = class {
6370
7664
  case "acl":
6371
7665
  return cmdAcl(this.aclUsers(), session.username, args);
6372
7666
  case "config":
6373
- return this.cmdConfig(args, apply);
7667
+ return this.cmdConfig(session, args, apply);
6374
7668
  case "dbsize":
6375
7669
  return int(this.database(session.db).keys().length);
6376
7670
  case "flushdb":
@@ -6391,6 +7685,22 @@ var Redis = class {
6391
7685
  return this.cmdType(session, args);
6392
7686
  case "exists":
6393
7687
  return this.cmdExists(session, args);
7688
+ case "setbit":
7689
+ return cmdSetbit(this.database(session.db), args, apply);
7690
+ case "getbit":
7691
+ return cmdGetbit(this.database(session.db), args);
7692
+ case "bitcount":
7693
+ return cmdBitcount(this.database(session.db), args);
7694
+ case "pfadd":
7695
+ return cmdPfadd(this.database(session.db), args, apply);
7696
+ case "pfcount":
7697
+ return cmdPfcount(this.database(session.db), args);
7698
+ case "pfmerge":
7699
+ return cmdPfmerge(this.database(session.db), args, apply);
7700
+ case "touch":
7701
+ return this.cmdTouch(session, args);
7702
+ case "wait":
7703
+ return this.cmdWait(args);
6394
7704
  case "del":
6395
7705
  case "unlink":
6396
7706
  return this.cmdDel(session, args, apply);
@@ -6472,6 +7782,8 @@ var Redis = class {
6472
7782
  return this.cmdHash(session, command, args, apply);
6473
7783
  case "lpush":
6474
7784
  case "rpush":
7785
+ case "lpushx":
7786
+ case "rpushx":
6475
7787
  case "lpop":
6476
7788
  case "rpop":
6477
7789
  case "llen":
@@ -6500,6 +7812,10 @@ var Redis = class {
6500
7812
  case "sinter":
6501
7813
  case "sunion":
6502
7814
  case "sdiff":
7815
+ case "sinterstore":
7816
+ case "sunionstore":
7817
+ case "sdiffstore":
7818
+ case "sintercard":
6503
7819
  case "smove":
6504
7820
  return this.cmdSetFamily(session, command, args, apply);
6505
7821
  case "zadd":
@@ -6509,10 +7825,6 @@ var Redis = class {
6509
7825
  case "zmscore":
6510
7826
  case "zrank":
6511
7827
  case "zrevrank":
6512
- case "zrange":
6513
- case "zrevrange":
6514
- case "zrangebyscore":
6515
- case "zrevrangebyscore":
6516
7828
  case "zcount":
6517
7829
  case "zpopmin":
6518
7830
  case "zpopmax":
@@ -6520,6 +7832,28 @@ var Redis = class {
6520
7832
  case "zremrangebyscore":
6521
7833
  case "zremrangebyrank":
6522
7834
  return this.cmdZset(session, command, args, apply);
7835
+ case "zrange":
7836
+ case "zrevrange":
7837
+ case "zrangebyscore":
7838
+ case "zrevrangebyscore":
7839
+ case "zrangebylex":
7840
+ case "zrevrangebylex":
7841
+ case "zrangestore":
7842
+ return cmdZrange(this.zsetContext(session, apply), command, args);
7843
+ case "zlexcount":
7844
+ case "zremrangebylex":
7845
+ return cmdZlex(this.zsetContext(session, apply), command, args);
7846
+ case "zunionstore":
7847
+ case "zinterstore":
7848
+ case "zdiffstore":
7849
+ case "zunion":
7850
+ case "zinter":
7851
+ case "zdiff":
7852
+ return cmdZalgebra(this.zsetContext(session, apply), command, args);
7853
+ case "zintercard":
7854
+ return cmdZintercard(this.zsetContext(session, apply), args);
7855
+ case "zrandmember":
7856
+ return cmdZrandmember(this.zsetContext(session, apply), args);
6523
7857
  case "bzpopmin":
6524
7858
  return this.cmdBlockingZset(session, args, apply, false);
6525
7859
  case "bzpopmax":
@@ -6544,8 +7878,13 @@ var Redis = class {
6544
7878
  case "psubscribe":
6545
7879
  case "punsubscribe":
6546
7880
  return this.cmdSub(session, command, args);
7881
+ case "ssubscribe":
7882
+ case "sunsubscribe":
7883
+ return this.cmdShardSub(session, command, args);
6547
7884
  case "publish":
6548
7885
  return this.cmdPublish(args);
7886
+ case "spublish":
7887
+ return this.cmdSpublish(args);
6549
7888
  case "pubsub":
6550
7889
  return this.cmdPubsub(args);
6551
7890
  case "multi":
@@ -6564,7 +7903,14 @@ var Redis = class {
6564
7903
  return ok();
6565
7904
  case "eval":
6566
7905
  case "evalsha":
7906
+ case "eval_ro":
7907
+ case "evalsha_ro":
6567
7908
  return this.cmdEval(session, command, args, apply);
7909
+ case "fcall":
7910
+ case "fcall_ro":
7911
+ return this.cmdFcall(session, command, args, apply);
7912
+ case "function":
7913
+ return this.functions.command(args, apply);
6568
7914
  case "script":
6569
7915
  return this.cmdScript(args, apply);
6570
7916
  case "shutdown":
@@ -6617,8 +7963,10 @@ var Redis = class {
6617
7963
  if (this.maxmemory > 0 && this.policy === "allkeys-lru") {
6618
7964
  while (this.memory() > this.maxmemory) {
6619
7965
  let evicted = false;
6620
- for (const database of this.dbs) {
6621
- if (database.evictLru()) {
7966
+ for (const [index, database] of this.dbs.entries()) {
7967
+ const key = database.evictLru();
7968
+ if (key !== null) {
7969
+ this.notify(index, NOTIFY_EVICTED, "evicted", key);
6622
7970
  evicted = true;
6623
7971
  break;
6624
7972
  }
@@ -6630,7 +7978,7 @@ var Redis = class {
6630
7978
  }
6631
7979
  cmdPing(session, args) {
6632
7980
  if (args.length > 1) return arityError("ping");
6633
- if (session.channels.size + session.patterns.size > 0) {
7981
+ if (this.subscriptions(session) > 0) {
6634
7982
  return push([bulk("pong"), args[0] ? { t: "bulk", v: args[0] } : bulk("")]);
6635
7983
  }
6636
7984
  if (args.length === 1) return { t: "bulk", v: args[0] ?? null };
@@ -6638,8 +7986,8 @@ var Redis = class {
6638
7986
  }
6639
7987
  cmdAuth(session, args) {
6640
7988
  if (args.length !== 1 && args.length !== 2) return arityError("auth");
6641
- const user = args.length === 2 ? text3(args[0]) : "default";
6642
- const password = text3(args.length === 2 ? args[1] : args[0]);
7989
+ const user = args.length === 2 ? text7(args[0]) : "default";
7990
+ const password = text7(args.length === 2 ? args[1] : args[0]);
6643
7991
  if (!this.authRequired) return authWithoutPassword(password);
6644
7992
  const account = user === "default" ? {
6645
7993
  password: this.users.find((item) => item.name === "default")?.password ?? this.password,
@@ -6656,13 +8004,13 @@ var Redis = class {
6656
8004
  let protocol = session.protocol;
6657
8005
  let index = 0;
6658
8006
  if (args.length > 0) {
6659
- const requested = Number(text3(args[0]));
8007
+ const requested = Number(text7(args[0]));
6660
8008
  if (requested !== 2 && requested !== 3) return err("NOPROTO unsupported protocol version");
6661
8009
  protocol = requested;
6662
8010
  index = 1;
6663
8011
  }
6664
8012
  while (index < args.length) {
6665
- const option = upper3(args[index]);
8013
+ const option = upper5(args[index]);
6666
8014
  if (option === "AUTH") {
6667
8015
  const user = args[index + 1];
6668
8016
  const pass = args[index + 2];
@@ -6675,7 +8023,7 @@ var Redis = class {
6675
8023
  if (option === "SETNAME") {
6676
8024
  const name = args[index + 1];
6677
8025
  if (!name) return syntaxError();
6678
- session.name = text3(name);
8026
+ session.name = text7(name);
6679
8027
  index += 2;
6680
8028
  continue;
6681
8029
  }
@@ -6714,21 +8062,21 @@ var Redis = class {
6714
8062
  return simple("RESET");
6715
8063
  }
6716
8064
  cmdClient(session, args, apply) {
6717
- const sub = upper3(args[0]);
8065
+ const sub = upper5(args[0]);
6718
8066
  if (sub === "SETNAME") {
6719
8067
  if (args.length !== 2) return arityError("client|setname");
6720
8068
  if (!apply) return queued();
6721
- session.name = text3(args[1]);
8069
+ session.name = text7(args[1]);
6722
8070
  return ok();
6723
8071
  }
6724
8072
  if (sub === "GETNAME") return session.name ? bulk(session.name) : nil();
6725
8073
  if (sub === "SETINFO") {
6726
8074
  if (args.length !== 3) return arityError("client|setinfo");
6727
- const kind = upper3(args[1]);
8075
+ const kind = upper5(args[1]);
6728
8076
  if (kind !== "LIB-NAME" && kind !== "LIB-VER") return syntaxError();
6729
8077
  if (!apply) return queued();
6730
- if (kind === "LIB-NAME") session.libName = text3(args[2]);
6731
- else session.libVer = text3(args[2]);
8078
+ if (kind === "LIB-NAME") session.libName = text7(args[2]);
8079
+ else session.libVer = text7(args[2]);
6732
8080
  return ok();
6733
8081
  }
6734
8082
  if (sub === "ID") return int(session.id);
@@ -6738,7 +8086,7 @@ var Redis = class {
6738
8086
  }
6739
8087
  if (sub === "PAUSE" || sub === "UNPAUSE") return ok();
6740
8088
  if (!sub) return arityError("client");
6741
- return err(`ERR unknown subcommand '${text3(args[0]).toLowerCase()}'. Try CLIENT HELP.`);
8089
+ return err(`ERR unknown subcommand '${text7(args[0]).toLowerCase()}'. Try CLIENT HELP.`);
6742
8090
  }
6743
8091
  clientInfo(session) {
6744
8092
  return `id=${session.id} addr=127.0.0.1:${session.id} laddr=127.0.0.1:${session.localPort ?? 6379} name=${session.name} db=${session.db} sub=${session.channels.size} psub=${session.patterns.size} multi=${session.multi ? session.multi.length : -1} lib-name=${session.libName} lib-ver=${session.libVer}`;
@@ -6855,31 +8203,62 @@ var Redis = class {
6855
8203
  const micros = now % 1e3 * 1e3;
6856
8204
  return arr([bulk(String(seconds)), bulk(String(micros))]);
6857
8205
  }
6858
- cmdConfig(args, apply) {
6859
- const sub = upper3(args[0]);
8206
+ configValue(name) {
8207
+ switch (name) {
8208
+ case "maxmemory":
8209
+ return String(this.maxmemory);
8210
+ case "maxmemory-policy":
8211
+ return this.policy;
8212
+ case "notify-keyspace-events":
8213
+ return formatNotifyFlags(this.notifyFlags);
8214
+ case "timeout":
8215
+ return "0";
8216
+ default:
8217
+ return String(this.dbs.length);
8218
+ }
8219
+ }
8220
+ cmdConfig(session, args, apply) {
8221
+ const sub = upper5(args[0]);
6860
8222
  if (sub === "GET") {
6861
- if (args.length !== 2) return arityError("config|get");
6862
- const key = text3(args[1]).toLowerCase();
6863
- const value = key === "maxmemory" ? String(this.maxmemory) : key === "maxmemory-policy" ? this.policy : key === "timeout" ? "0" : key === "databases" ? String(this.dbs.length) : null;
6864
- if (value === null) return arr([]);
6865
- return arr([bulk(key), bulk(value)]);
8223
+ if (args.length < 2) return arityError("config|get");
8224
+ const rows = [];
8225
+ for (const name of CONFIG_PARAMETERS) {
8226
+ if (!args.slice(1).some((arg) => globMatch(text7(arg).toLowerCase(), name))) continue;
8227
+ rows.push([bulk(name), bulk(this.configValue(name))]);
8228
+ }
8229
+ return this.proto(session) === 3 ? map(rows) : arr(rows.flat());
6866
8230
  }
6867
8231
  if (sub === "SET") {
6868
- if (args.length !== 3) return arityError("config|set");
6869
- if (!apply) return queued();
6870
- const key = text3(args[1]).toLowerCase();
6871
- const value = text3(args[2]);
6872
- if (key === "maxmemory") {
6873
- const parsed = Number(value);
6874
- if (!Number.isFinite(parsed) || parsed < 0) return err("ERR Invalid argument");
6875
- return ok();
6876
- }
6877
- if (key === "maxmemory-policy") {
6878
- if (value !== "noeviction" && value !== "allkeys-lru") return err("ERR Invalid argument");
6879
- this.policy = value;
6880
- return ok();
8232
+ if (args.length < 3 || args.length % 2 === 0) return arityError("config|set");
8233
+ const failed = (name, reason) => err(`ERR CONFIG SET failed (possibly related to argument '${name}') - ${reason}`);
8234
+ const changes = [];
8235
+ const seen = /* @__PURE__ */ new Set();
8236
+ for (let i = 1; i < args.length; i += 2) {
8237
+ const key = text7(args[i]).toLowerCase();
8238
+ const value = text7(args[i + 1]);
8239
+ if (seen.has(key)) return failed(key, "duplicate parameter");
8240
+ seen.add(key);
8241
+ if (key === "maxmemory") {
8242
+ const parsed = Number(value);
8243
+ if (!Number.isFinite(parsed) || parsed < 0) return err("ERR Invalid argument");
8244
+ } else if (key === "maxmemory-policy") {
8245
+ if (value !== "noeviction" && value !== "allkeys-lru") return err("ERR Invalid argument");
8246
+ changes.push(() => {
8247
+ this.policy = value;
8248
+ });
8249
+ } else if (key === "notify-keyspace-events") {
8250
+ const flags = parseNotifyFlags(value);
8251
+ if (flags === null)
8252
+ return failed(key, "Invalid event class character. Use 'Ag$lshzxeKEtmdn'.");
8253
+ changes.push(() => {
8254
+ this.notifyFlags = flags;
8255
+ this.syncExpiryTimer();
8256
+ });
8257
+ } else return err("ERR Unsupported CONFIG parameter");
6881
8258
  }
6882
- return err("ERR Unsupported CONFIG parameter");
8259
+ if (!apply) return queued();
8260
+ for (const change of changes) change();
8261
+ return ok();
6883
8262
  }
6884
8263
  return arityError("config");
6885
8264
  }
@@ -6891,21 +8270,21 @@ var Redis = class {
6891
8270
  }
6892
8271
  cmdScan(session, args) {
6893
8272
  if (args.length < 1) return arityError("scan");
6894
- const cursor = Number(text3(args[0]));
8273
+ const cursor = Number(text7(args[0]));
6895
8274
  if (!Number.isInteger(cursor) || cursor < 0) return err("ERR invalid cursor");
6896
8275
  let pattern = "*";
6897
8276
  let count = 10;
6898
8277
  let type = null;
6899
8278
  for (let i = 1; i < args.length; i++) {
6900
- const option = upper3(args[i]);
8279
+ const option = upper5(args[i]);
6901
8280
  if (option === "TYPE") {
6902
8281
  const value = args[++i];
6903
8282
  if (!value) return syntaxError();
6904
- type = text3(value).toLowerCase();
8283
+ type = text7(value).toLowerCase();
6905
8284
  } else if (option === "MATCH") {
6906
8285
  const value = args[++i];
6907
8286
  if (!value) return syntaxError();
6908
- pattern = text3(value);
8287
+ pattern = text7(value);
6909
8288
  } else if (option === "COUNT") {
6910
8289
  const value = args[++i];
6911
8290
  const parsed = value ? parseI64(value) : null;
@@ -6924,31 +8303,46 @@ var Redis = class {
6924
8303
  }
6925
8304
  cmdKeys(session, args) {
6926
8305
  if (args.length !== 1) return arityError("keys");
6927
- const keys = this.database(session.db).matching(text3(args[0]));
8306
+ const keys = this.database(session.db).matching(text7(args[0]));
6928
8307
  return arr(keys.map((key) => ({ t: "bulk", v: fromLatin1(key) })));
6929
8308
  }
6930
8309
  cmdType(session, args) {
6931
8310
  if (args.length !== 1) return arityError("type");
6932
- const value = this.database(session.db).get(text3(args[0]));
8311
+ const value = this.database(session.db).get(text7(args[0]));
6933
8312
  return simple(value?.kind ?? "none");
6934
8313
  }
8314
+ /** `TOUCH`: the number of the given keys that exist; each counts as an access. */
8315
+ cmdTouch(session, args) {
8316
+ if (args.length < 1) return arityError("touch");
8317
+ const database = this.database(session.db);
8318
+ return int(args.filter((arg) => database.has(text7(arg))).length);
8319
+ }
8320
+ /** `WAIT`: a standalone node has no replicas to wait for, so it answers 0 at once. */
8321
+ cmdWait(args) {
8322
+ if (args.length !== 2) return arityError("wait");
8323
+ const replicas = parseI64(args[0] ?? utf8(""));
8324
+ const timeout = parseI64(args[1] ?? utf8(""));
8325
+ if (replicas === null || timeout === null) return notInteger();
8326
+ if (timeout < 0n) return err("ERR timeout is negative");
8327
+ return int(0);
8328
+ }
6935
8329
  cmdExists(session, args) {
6936
8330
  if (args.length < 1) return arityError("exists");
6937
8331
  const database = this.database(session.db);
6938
- return int(args.filter((arg) => database.has(text3(arg))).length);
8332
+ return int(args.filter((arg) => database.has(text7(arg))).length);
6939
8333
  }
6940
8334
  cmdDel(session, args, apply) {
6941
8335
  if (args.length < 1) return arityError("del");
6942
8336
  if (!apply) return queued();
6943
8337
  const database = this.database(session.db);
6944
8338
  let removed = 0;
6945
- for (const arg of args) if (database.delete(text3(arg))) removed++;
8339
+ for (const arg of args) if (database.delete(text7(arg))) removed++;
6946
8340
  return int(removed);
6947
8341
  }
6948
8342
  cmdRename(session, args, apply, nx) {
6949
8343
  if (args.length !== 2) return arityError(nx ? "renamenx" : "rename");
6950
- const source = text3(args[0]);
6951
- const dest = text3(args[1]);
8344
+ const source = text7(args[0]);
8345
+ const dest = text7(args[1]);
6952
8346
  if (source === dest) return err("ERR source and destination objects are the same");
6953
8347
  const database = this.database(session.db);
6954
8348
  if (!database.has(source)) return noSuchKey();
@@ -6959,11 +8353,11 @@ var Redis = class {
6959
8353
  }
6960
8354
  cmdExpire(session, command, args, apply) {
6961
8355
  if (args.length < 2) return arityError(command);
6962
- const key = text3(args[0]);
8356
+ const key = text7(args[0]);
6963
8357
  const amount = parseI64(args[1] ?? utf8(""));
6964
8358
  if (amount === null) return notInteger();
6965
8359
  let flag = "";
6966
- if (args.length === 3) flag = upper3(args[2]);
8360
+ if (args.length === 3) flag = upper5(args[2]);
6967
8361
  else if (args.length > 3) return syntaxError();
6968
8362
  if (flag && !["NX", "XX", "GT", "LT"].includes(flag)) return syntaxError();
6969
8363
  const database = this.database(session.db);
@@ -6986,14 +8380,14 @@ var Redis = class {
6986
8380
  }
6987
8381
  cmdTtl(session, command, args) {
6988
8382
  if (args.length !== 1) return arityError(command);
6989
- const pttl = this.database(session.db).pttl(text3(args[0]));
8383
+ const pttl = this.database(session.db).pttl(text7(args[0]));
6990
8384
  if (pttl < 0) return int(pttl);
6991
8385
  return int(command === "pttl" ? pttl : Math.floor((pttl + 500) / 1e3));
6992
8386
  }
6993
8387
  cmdPersist(session, args, apply) {
6994
8388
  if (args.length !== 1) return arityError("persist");
6995
8389
  const database = this.database(session.db);
6996
- const key = text3(args[0]);
8390
+ const key = text7(args[0]);
6997
8391
  if (database.pttl(key) < 0) return int(0);
6998
8392
  if (!apply) return queued();
6999
8393
  database.setExpiry(key, null);
@@ -7007,7 +8401,7 @@ var Redis = class {
7007
8401
  }
7008
8402
  cmdGet(session, args) {
7009
8403
  if (args.length !== 1) return arityError("get");
7010
- const value = this.stringAt(this.database(session.db), text3(args[0]));
8404
+ const value = this.stringAt(this.database(session.db), text7(args[0]));
7011
8405
  if (value instanceof Uint8Array) return { t: "bulk", v: value };
7012
8406
  if (value === null) return nil();
7013
8407
  return value;
@@ -7019,7 +8413,7 @@ var Redis = class {
7019
8413
  */
7020
8414
  cmdSet(session, args, apply, command = "set") {
7021
8415
  if (args.length < 2) return arityError(command);
7022
- const key = text3(args[0]);
8416
+ const key = text7(args[0]);
7023
8417
  const value = args[1];
7024
8418
  if (!value) return arityError(command);
7025
8419
  let nx = false;
@@ -7028,7 +8422,7 @@ var Redis = class {
7028
8422
  let mode = null;
7029
8423
  let rawAmount;
7030
8424
  for (let i = 2; i < args.length; i++) {
7031
- const option = upper3(args[i]);
8425
+ const option = upper5(args[i]);
7032
8426
  if (option === "NX") {
7033
8427
  if (xx) return syntaxError();
7034
8428
  nx = true;
@@ -7071,7 +8465,7 @@ var Redis = class {
7071
8465
  if (args.length !== 2) return arityError("setnx");
7072
8466
  if (!apply) return queued();
7073
8467
  const database = this.database(session.db);
7074
- const key = text3(args[0]);
8468
+ const key = text7(args[0]);
7075
8469
  if (database.has(key)) return int(0);
7076
8470
  database.put(key, { kind: "string", bytes: args[1] ?? utf8("") });
7077
8471
  database.setExpiry(key, null);
@@ -7093,7 +8487,7 @@ var Redis = class {
7093
8487
  cmdAppend(session, args, apply) {
7094
8488
  if (args.length !== 2) return arityError("append");
7095
8489
  const database = this.database(session.db);
7096
- const key = text3(args[0]);
8490
+ const key = text7(args[0]);
7097
8491
  const extra = args[1] ?? utf8("");
7098
8492
  const current = this.stringAt(database, key);
7099
8493
  if (current && !(current instanceof Uint8Array)) return current;
@@ -7104,14 +8498,14 @@ var Redis = class {
7104
8498
  }
7105
8499
  cmdStrlen(session, args) {
7106
8500
  if (args.length !== 1) return arityError("strlen");
7107
- const value = this.stringAt(this.database(session.db), text3(args[0]));
8501
+ const value = this.stringAt(this.database(session.db), text7(args[0]));
7108
8502
  if (value instanceof Uint8Array) return int(value.length);
7109
8503
  if (value === null) return int(0);
7110
8504
  return value;
7111
8505
  }
7112
8506
  cmdGetRange(session, args) {
7113
8507
  if (args.length !== 3) return arityError("getrange");
7114
- const value = this.stringAt(this.database(session.db), text3(args[0]));
8508
+ const value = this.stringAt(this.database(session.db), text7(args[0]));
7115
8509
  if (value && !(value instanceof Uint8Array)) return value;
7116
8510
  const bytes2 = value instanceof Uint8Array ? value : utf8("");
7117
8511
  const [start, end] = indexes(bytes2.length, args[1], args[2]);
@@ -7123,7 +8517,7 @@ var Redis = class {
7123
8517
  const offset = parseI64(args[1] ?? utf8(""));
7124
8518
  if (offset === null || offset < 0n) return err("ERR offset is out of range");
7125
8519
  const database = this.database(session.db);
7126
- const key = text3(args[0]);
8520
+ const key = text7(args[0]);
7127
8521
  const current = this.stringAt(database, key);
7128
8522
  if (current && !(current instanceof Uint8Array)) return current;
7129
8523
  if (!apply) return queued();
@@ -7137,13 +8531,13 @@ var Redis = class {
7137
8531
  }
7138
8532
  cmdIncr(session, args, delta, apply) {
7139
8533
  if (args.length !== 1) return arityError(delta < 0n ? "decr" : "incr");
7140
- return this.addInteger(session, text3(args[0]), delta, apply);
8534
+ return this.addInteger(session, text7(args[0]), delta, apply);
7141
8535
  }
7142
8536
  cmdIncrBy(session, command, args, apply) {
7143
8537
  if (args.length !== 2) return arityError(command);
7144
8538
  const delta = parseI64(args[1] ?? utf8(""));
7145
8539
  if (delta === null) return notInteger();
7146
- return this.addInteger(session, text3(args[0]), command === "decrby" ? -delta : delta, apply);
8540
+ return this.addInteger(session, text7(args[0]), command === "decrby" ? -delta : delta, apply);
7147
8541
  }
7148
8542
  addInteger(session, key, delta, apply) {
7149
8543
  const database = this.database(session.db);
@@ -7167,7 +8561,7 @@ var Redis = class {
7167
8561
  const delta = parseScore(args[1]);
7168
8562
  if (delta === null) return notFloat();
7169
8563
  const database = this.database(session.db);
7170
- const key = text3(args[0]);
8564
+ const key = text7(args[0]);
7171
8565
  const current = this.stringAt(database, key);
7172
8566
  if (current && !(current instanceof Uint8Array)) return current;
7173
8567
  const base = current instanceof Uint8Array ? parseScore(current) : 0;
@@ -7182,7 +8576,7 @@ var Redis = class {
7182
8576
  const got = this.cmdGet(session, args);
7183
8577
  if (got.t === "error" || got.t !== "bulk" || got.v === null) return got;
7184
8578
  if (!apply) return queued();
7185
- this.database(session.db).delete(text3(args[0]));
8579
+ this.database(session.db).delete(text7(args[0]));
7186
8580
  return got;
7187
8581
  }
7188
8582
  cmdGetEx(session, args, apply) {
@@ -7191,9 +8585,9 @@ var Redis = class {
7191
8585
  if (got.t === "error") return got;
7192
8586
  if (args.length === 1) return got;
7193
8587
  if (!apply) return queued();
7194
- const option = upper3(args[1]);
8588
+ const option = upper5(args[1]);
7195
8589
  if (option === "PERSIST") {
7196
- this.database(session.db).setExpiry(text3(args[0]), null);
8590
+ this.database(session.db).setExpiry(text7(args[0]), null);
7197
8591
  return got;
7198
8592
  }
7199
8593
  const result = this.cmdExpire(
@@ -7218,7 +8612,7 @@ var Redis = class {
7218
8612
  }
7219
8613
  cmdHash(session, command, args, apply) {
7220
8614
  const database = this.database(session.db);
7221
- const key = text3(args[0]);
8615
+ const key = text7(args[0]);
7222
8616
  if (command === "hset" || command === "hmset" || command === "hsetnx") {
7223
8617
  if (args.length < 3 || (args.length - 1) % 2 !== 0) return arityError(command);
7224
8618
  const hash = this.requireHash(database, key, false);
@@ -7287,8 +8681,16 @@ var Redis = class {
7287
8681
  if (command === "hkeys" || command === "hvals" || command === "hgetall") {
7288
8682
  if (args.length !== 1) return arityError(command);
7289
8683
  const hash = this.requireHash(database, key, false);
7290
- if (hash === null) return arr([]);
8684
+ const asMap = command === "hgetall" && this.proto(session) === 3;
8685
+ if (hash === null) return asMap ? map([]) : arr([]);
7291
8686
  if (!("fields" in hash)) return hash;
8687
+ if (asMap)
8688
+ return map(
8689
+ [...hash.fields].map(([field, value]) => [
8690
+ { t: "bulk", v: fromLatin1(field) },
8691
+ { t: "bulk", v: value }
8692
+ ])
8693
+ );
7292
8694
  const items = [];
7293
8695
  for (const [field, value] of hash.fields) {
7294
8696
  if (command !== "hvals") items.push({ t: "bulk", v: fromLatin1(field) });
@@ -7353,14 +8755,14 @@ var Redis = class {
7353
8755
  }
7354
8756
  cmdList(session, command, args, apply) {
7355
8757
  const database = this.database(session.db);
7356
- const key = text3(args[0]);
8758
+ const key = text7(args[0]);
7357
8759
  if (command === "lpos") {
7358
8760
  if (args.length < 2) return arityError(command);
7359
8761
  let rank = 1;
7360
8762
  let count;
7361
8763
  let maxlen = 0;
7362
8764
  for (let i = 2; i < args.length; i += 2) {
7363
- const option = upper3(args[i]);
8765
+ const option = upper5(args[i]);
7364
8766
  const value = parseI64(args[i + 1] ?? utf8(""));
7365
8767
  if (value === null) return notInteger();
7366
8768
  if (option === "RANK") {
@@ -7394,15 +8796,16 @@ var Redis = class {
7394
8796
  }
7395
8797
  return count === void 0 ? positions[0] === void 0 ? nil() : int(positions[0]) : arr(positions.map(int));
7396
8798
  }
7397
- if (command === "lpush" || command === "rpush") {
8799
+ if (command === "lpush" || command === "rpush" || command === "lpushx" || command === "rpushx") {
7398
8800
  if (args.length < 2) return arityError(command);
7399
8801
  const existing = this.requireList(database, key, false);
7400
8802
  if (existing && !("items" in existing)) return existing;
7401
8803
  if (!apply) return queued();
8804
+ if (command.endsWith("x") && existing === null) return int(0);
7402
8805
  const list = this.requireList(database, key, true);
7403
8806
  if (!list || !("items" in list)) return list ?? wrongType();
7404
8807
  const items = args.slice(1);
7405
- if (command === "lpush") for (const item of items) list.items.unshift(item);
8808
+ if (command.startsWith("l")) for (const item of items) list.items.unshift(item);
7406
8809
  else for (const item of items) list.items.push(item);
7407
8810
  database.put(key, list);
7408
8811
  const length2 = list.items.length;
@@ -7501,7 +8904,7 @@ var Redis = class {
7501
8904
  const list = this.requireList(database, key, false);
7502
8905
  if (list === null) return int(0);
7503
8906
  if (!("items" in list)) return list;
7504
- const where = upper3(args[1]);
8907
+ const where = upper5(args[1]);
7505
8908
  if (where !== "BEFORE" && where !== "AFTER") return syntaxError();
7506
8909
  const pivot = args[2] ?? utf8("");
7507
8910
  const at = list.items.findIndex(
@@ -7516,9 +8919,9 @@ var Redis = class {
7516
8919
  }
7517
8920
  if (command === "lmove" || command === "rpoplpush") {
7518
8921
  const source = key;
7519
- const dest = command === "rpoplpush" ? text3(args[1]) : text3(args[1]);
7520
- const from = command === "rpoplpush" ? "right" : upper3(args[2]);
7521
- const to = command === "rpoplpush" ? "left" : upper3(args[3]);
8922
+ const dest = command === "rpoplpush" ? text7(args[1]) : text7(args[1]);
8923
+ const from = command === "rpoplpush" ? "right" : upper5(args[2]);
8924
+ const to = command === "rpoplpush" ? "left" : upper5(args[3]);
7522
8925
  if (command === "lmove" && args.length !== 4) return arityError("lmove");
7523
8926
  if (command === "rpoplpush" && args.length !== 2) return arityError("rpoplpush");
7524
8927
  if (from !== "LEFT" && from !== "RIGHT" && command === "lmove") return syntaxError();
@@ -7548,7 +8951,7 @@ var Redis = class {
7548
8951
  if (args.length < 2) return arityError(name);
7549
8952
  const timeout = parseTimeout(args[args.length - 1]);
7550
8953
  if (timeout === null) return err("ERR timeout is not a float or out of range");
7551
- const keys = args.slice(0, -1).map((arg) => text3(arg));
8954
+ const keys = args.slice(0, -1).map((arg) => text7(arg));
7552
8955
  for (const key of keys) {
7553
8956
  const value = this.database(session.db).get(key);
7554
8957
  if (value && value.kind !== "list") return wrongType();
@@ -7595,7 +8998,7 @@ var Redis = class {
7595
8998
  }
7596
8999
  cmdSetFamily(session, command, args, apply) {
7597
9000
  const database = this.database(session.db);
7598
- const key = text3(args[0]);
9001
+ const key = text7(args[0]);
7599
9002
  if (command === "sadd" || command === "srem") {
7600
9003
  if (args.length < 2) return arityError(command);
7601
9004
  const existing = this.requireSet(database, key, false);
@@ -7673,35 +9076,44 @@ var Redis = class {
7673
9076
  if (count === null) return picked[0] ? { t: "bulk", v: picked[0] } : nil();
7674
9077
  return arr(picked.map((member) => ({ t: "bulk", v: member })));
7675
9078
  }
7676
- if (command === "sinter" || command === "sunion" || command === "sdiff") {
7677
- if (args.length < 1) return arityError(command);
9079
+ if (command === "sintercard") return this.cmdSintercard(database, args);
9080
+ if (command === "sinter" || command === "sunion" || command === "sdiff" || command === "sinterstore" || command === "sunionstore" || command === "sdiffstore") {
9081
+ const stored = command.endsWith("store");
9082
+ if (args.length < (stored ? 2 : 1)) return arityError(command);
7678
9083
  const sets = [];
7679
- for (const arg of args) {
7680
- const set = this.requireSet(database, text3(arg), false);
9084
+ for (const arg of stored ? args.slice(1) : args) {
9085
+ const set = this.requireSet(database, text7(arg), false);
7681
9086
  if (set && !("members" in set)) return set;
7682
9087
  sets.push(set && "members" in set ? set : null);
7683
9088
  }
7684
9089
  const [first2, ...rest] = sets;
7685
9090
  let members = new Map(first2?.members ?? []);
7686
- if (command === "sinter") {
9091
+ if (command.startsWith("sinter")) {
7687
9092
  for (const set of rest) {
7688
9093
  members = new Map([...members].filter(([member]) => set?.members.has(member)));
7689
9094
  }
7690
- } else if (command === "sunion") {
9095
+ } else if (command.startsWith("sunion")) {
7691
9096
  for (const set of rest)
7692
9097
  for (const [member, bytes2] of set?.members ?? []) members.set(member, bytes2);
7693
9098
  } else {
7694
9099
  for (const set of rest)
7695
9100
  for (const member of set?.members.keys() ?? []) members.delete(member);
7696
9101
  }
7697
- const ordered = [...members.values()].sort((a, b) => compareBytes(a, b));
7698
- return arr(ordered.map((member) => ({ t: "bulk", v: member })));
9102
+ if (stored) {
9103
+ if (!apply) return queued();
9104
+ database.delete(key);
9105
+ if (members.size === 0) return int(0);
9106
+ database.put(key, { kind: "set", members });
9107
+ return int(members.size);
9108
+ }
9109
+ const ordered2 = [...members.values()].sort((a, b) => compareBytes(a, b));
9110
+ return arr(ordered2.map((member) => ({ t: "bulk", v: member })));
7699
9111
  }
7700
9112
  if (command === "smove") {
7701
9113
  if (args.length !== 3) return arityError("smove");
7702
9114
  const source = this.requireSet(database, key, false);
7703
9115
  if (source && !("members" in source)) return source;
7704
- const destKey = text3(args[1]);
9116
+ const destKey = text7(args[1]);
7705
9117
  const dest = this.requireSet(database, destKey, false);
7706
9118
  if (dest && !("members" in dest)) return dest;
7707
9119
  const member = memberKey(args[2] ?? utf8(""));
@@ -7719,6 +9131,35 @@ var Redis = class {
7719
9131
  }
7720
9132
  return unknownCommand(command, args);
7721
9133
  }
9134
+ cmdSintercard(database, args) {
9135
+ if (args.length < 2) return arityError("sintercard");
9136
+ const numkeys = parseI64(args[0] ?? utf8(""));
9137
+ if (numkeys === null || numkeys < 1n) return err("ERR numkeys should be greater than 0");
9138
+ if (numkeys > BigInt(args.length - 1))
9139
+ return err("ERR Number of keys can't be greater than number of args");
9140
+ const count = Number(numkeys);
9141
+ let limit = 0n;
9142
+ for (let i = 1 + count; i < args.length; i++) {
9143
+ if (upper5(args[i]) !== "LIMIT" || i + 1 >= args.length) return syntaxError();
9144
+ const parsed = parseI64(args[++i] ?? utf8(""));
9145
+ if (parsed === null || parsed < 0n) return err("ERR LIMIT can't be negative");
9146
+ limit = parsed;
9147
+ }
9148
+ const sets = [];
9149
+ for (const arg of args.slice(1, 1 + count)) {
9150
+ const set = this.requireSet(database, text7(arg), false);
9151
+ if (set && !("members" in set)) return set;
9152
+ sets.push(set && "members" in set ? set : null);
9153
+ }
9154
+ const [first2, ...rest] = sets;
9155
+ let found = 0;
9156
+ for (const member of first2?.members.keys() ?? []) {
9157
+ if (!rest.every((set) => set?.members.has(member))) continue;
9158
+ found++;
9159
+ if (limit > 0n && BigInt(found) >= limit) break;
9160
+ }
9161
+ return int(found);
9162
+ }
7722
9163
  requireZset(database, key, create) {
7723
9164
  const value = database.get(key);
7724
9165
  if (!value) {
@@ -7732,7 +9173,7 @@ var Redis = class {
7732
9173
  }
7733
9174
  cmdZset(session, command, args, apply) {
7734
9175
  const database = this.database(session.db);
7735
- const key = text3(args[0]);
9176
+ const key = text7(args[0]);
7736
9177
  if (command === "zadd") return this.cmdZadd(session, args, apply);
7737
9178
  if (command === "zrem") {
7738
9179
  if (args.length < 2) return arityError("zrem");
@@ -7760,7 +9201,7 @@ var Redis = class {
7760
9201
  if (zset && !("members" in zset)) return zset;
7761
9202
  const scores = args.slice(1).map((arg) => {
7762
9203
  const member = zset && "members" in zset ? zset.members.get(memberKey(arg)) : void 0;
7763
- return member ? bulk(scoreText(member.score)) : nil();
9204
+ return member ? scoreReply(member.score, this.proto(session)) : nil();
7764
9205
  });
7765
9206
  return command === "zscore" ? scores[0] ?? nil() : arr(scores);
7766
9207
  }
@@ -7777,30 +9218,31 @@ var Redis = class {
7777
9218
  zset.members.set(memberKey(member), { member, score });
7778
9219
  database.put(key, zset);
7779
9220
  this.wake(session.db, key);
7780
- return bulk(scoreText(score));
9221
+ return scoreReply(score, this.proto(session));
7781
9222
  }
7782
9223
  if (command === "zrank" || command === "zrevrank") {
7783
- if (args.length !== 2) return arityError(command);
9224
+ if (args.length !== 2 && args.length !== 3) return arityError(command);
9225
+ const withScore = args.length === 3;
9226
+ if (withScore && upper5(args[2]) !== "WITHSCORE") return syntaxError();
7784
9227
  const zset = this.requireZset(database, key, false);
7785
- if (zset === null) return nil();
9228
+ if (zset === null) return withScore ? nilArray() : nil();
7786
9229
  if (!("members" in zset)) return zset;
7787
- const ordered = database.zsetOrdered(zset);
7788
- const at = ordered.findIndex(
9230
+ const sorted = ordered(zset);
9231
+ const at = sorted.findIndex(
7789
9232
  (item) => memberKey(item.member) === memberKey(args[1] ?? utf8(""))
7790
9233
  );
7791
- if (at < 0) return nil();
7792
- return int(command === "zrevrank" ? ordered.length - 1 - at : at);
7793
- }
7794
- if (command === "zrange" || command === "zrevrange" || command === "zrangebyscore" || command === "zrevrangebyscore") {
7795
- return this.cmdZrange(database, command, args);
9234
+ if (at < 0) return withScore ? nilArray() : nil();
9235
+ const rank = int(command === "zrevrank" ? sorted.length - 1 - at : at);
9236
+ const score = sorted[at]?.score ?? 0;
9237
+ return withScore ? arr([rank, scoreReply(score, this.proto(session))]) : rank;
7796
9238
  }
7797
9239
  if (command === "zcount") {
7798
9240
  if (args.length !== 3) return arityError("zcount");
7799
9241
  const zset = this.requireZset(database, key, false);
7800
9242
  if (zset === null) return int(0);
7801
9243
  if (!("members" in zset)) return zset;
7802
- const min = parseBound(text3(args[1]));
7803
- const max = parseBound(text3(args[2]));
9244
+ const min = parseBound(text7(args[1]));
9245
+ const max = parseBound(text7(args[2]));
7804
9246
  if (!min || !max) return notFloat();
7805
9247
  return int(database.zsetOrdered(zset).filter((item) => inBound(item.score, min, max)).length);
7806
9248
  }
@@ -7810,19 +9252,19 @@ var Redis = class {
7810
9252
  if (zset === null) return arr([]);
7811
9253
  if (!("members" in zset)) return zset;
7812
9254
  const count = args.length === 2 ? parseI64(args[1] ?? utf8("")) : 1n;
7813
- if (count === null || count < 0n) return notInteger();
9255
+ if (count === null || count < 0n) return err("ERR value is out of range, must be positive");
7814
9256
  if (!apply) return queued();
7815
- const ordered = database.zsetOrdered(zset);
7816
- const picked = command === "zpopmax" ? ordered.slice(-Number(count)).reverse() : ordered.slice(0, Number(count));
9257
+ const ordered2 = database.zsetOrdered(zset);
9258
+ const picked = command === "zpopmax" ? ordered2.slice(-Number(count)).reverse() : ordered2.slice(0, Number(count));
7817
9259
  for (const item of picked) zset.members.delete(memberKey(item.member));
7818
9260
  database.dropIfEmpty(key);
7819
9261
  if (database.has(key)) database.put(key, zset);
7820
- return arr(
7821
- picked.flatMap((item) => [
7822
- { t: "bulk", v: item.member },
7823
- bulk(scoreText(item.score))
7824
- ])
7825
- );
9262
+ const proto = this.proto(session);
9263
+ if (args.length === 1) {
9264
+ const item = picked[0];
9265
+ return item ? arr([{ t: "bulk", v: item.member }, scoreReply(item.score, proto)]) : arr([]);
9266
+ }
9267
+ return scoredReply(picked, true, proto);
7826
9268
  }
7827
9269
  if (command === "zremrangebyscore" || command === "zremrangebyrank") {
7828
9270
  if (args.length !== 3) return arityError(command);
@@ -7830,21 +9272,21 @@ var Redis = class {
7830
9272
  if (zset === null) return int(0);
7831
9273
  if (!("members" in zset)) return zset;
7832
9274
  if (!apply) return queued();
7833
- const ordered = database.zsetOrdered(zset);
9275
+ const ordered2 = database.zsetOrdered(zset);
7834
9276
  let removed = 0;
7835
9277
  if (command === "zremrangebyrank") {
7836
- const [start, end] = indexes(ordered.length, args[1], args[2]);
7837
- ordered.forEach((item, index) => {
9278
+ const [start, end] = indexes(ordered2.length, args[1], args[2]);
9279
+ ordered2.forEach((item, index) => {
7838
9280
  if (index >= start && index <= end) {
7839
9281
  zset.members.delete(memberKey(item.member));
7840
9282
  removed++;
7841
9283
  }
7842
9284
  });
7843
9285
  } else {
7844
- const min = parseBound(text3(args[1]));
7845
- const max = parseBound(text3(args[2]));
9286
+ const min = parseBound(text7(args[1]));
9287
+ const max = parseBound(text7(args[2]));
7846
9288
  if (!min || !max) return notFloat();
7847
- for (const item of ordered) {
9289
+ for (const item of ordered2) {
7848
9290
  if (!inBound(item.score, min, max)) continue;
7849
9291
  zset.members.delete(memberKey(item.member));
7850
9292
  removed++;
@@ -7866,7 +9308,7 @@ var Redis = class {
7866
9308
  let ch = false;
7867
9309
  let incr = false;
7868
9310
  while (index < args.length) {
7869
- const option = upper3(args[index]);
9311
+ const option = upper5(args[index]);
7870
9312
  if (!["NX", "XX", "GT", "LT", "CH", "INCR"].includes(option)) break;
7871
9313
  if (option === "NX") nx = true;
7872
9314
  if (option === "XX") xx = true;
@@ -7882,94 +9324,63 @@ var Redis = class {
7882
9324
  if (incr && args.length - index !== 2)
7883
9325
  return err("ERR INCR option supports a single increment-element pair");
7884
9326
  const database = this.database(session.db);
7885
- const key = text3(args[0]);
9327
+ const key = text7(args[0]);
7886
9328
  const existing = this.requireZset(database, key, false);
7887
9329
  if (existing && !("members" in existing)) return existing;
9330
+ for (let i = index; i < args.length; i += 2) if (parseScore(args[i]) === null) return notFloat();
7888
9331
  if (!apply) return queued();
7889
- const zset = this.requireZset(database, key, true);
7890
- if (!zset || !("members" in zset)) return zset ?? wrongType();
7891
- let changed = 0;
9332
+ const zset = existing ?? { kind: "zset", members: /* @__PURE__ */ new Map() };
7892
9333
  let added = 0;
7893
9334
  let updatedScore = 0;
9335
+ let incremented = null;
7894
9336
  for (let i = index; i < args.length; i += 2) {
7895
- const score = parseScore(args[i]);
7896
- if (score === null) return notFloat();
9337
+ const score = parseScore(args[i]) ?? 0;
7897
9338
  const member = args[i + 1] ?? utf8("");
7898
9339
  const current = zset.members.get(memberKey(member));
7899
9340
  if (nx && current) continue;
7900
9341
  if ((xx || gt || lt) && !current) continue;
7901
- if (gt && current && score <= current.score) continue;
7902
- if (lt && current && score >= current.score) continue;
7903
9342
  const next = incr ? (current?.score ?? 0) + score : score;
9343
+ if (Number.isNaN(next)) return err("ERR resulting score is not a number (NaN)");
9344
+ if (gt && current && next <= current.score) continue;
9345
+ if (lt && current && next >= current.score) continue;
9346
+ if (incr) incremented = next;
7904
9347
  if (!current) added++;
7905
9348
  else if (current.score !== next) updatedScore++;
9349
+ else continue;
7906
9350
  zset.members.set(memberKey(member), { member, score: next });
7907
- if (incr) {
7908
- database.put(key, zset);
7909
- this.wake(session.db, key);
7910
- return bulk(scoreText(next));
7911
- }
7912
- }
7913
- changed = ch ? added + updatedScore : added;
7914
- database.put(key, zset);
7915
- this.wake(session.db, key);
7916
- return int(changed);
7917
- }
7918
- cmdZrange(database, command, args) {
7919
- if (args.length < 3) return arityError(command);
7920
- const zset = this.requireZset(database, text3(args[0]), false);
7921
- if (zset === null) return arr([]);
7922
- if (!("members" in zset)) return zset;
7923
- let byScore = command === "zrangebyscore" || command === "zrevrangebyscore";
7924
- let rev = command === "zrevrange" || command === "zrevrangebyscore";
7925
- let withScores = false;
7926
- let limit = null;
7927
- const rest = args.slice(3);
7928
- for (let i = 0; i < rest.length; i++) {
7929
- const option = upper3(rest[i]);
7930
- if (option === "BYSCORE") byScore = true;
7931
- else if (option === "REV") rev = true;
7932
- else if (option === "WITHSCORES") withScores = true;
7933
- else if (option === "LIMIT") {
7934
- const offset = parseI64(rest[++i] ?? utf8(""));
7935
- const count = parseI64(rest[++i] ?? utf8(""));
7936
- if (offset === null || count === null) return notInteger();
7937
- limit = { offset: Number(offset), count: Number(count) };
7938
- } else return syntaxError();
7939
9351
  }
7940
- let ordered = database.zsetOrdered(zset);
7941
- if (byScore) {
7942
- const left = parseBound(text3(args[1]));
7943
- const right = parseBound(text3(args[2]));
7944
- if (!left || !right) return notFloat();
7945
- const min = rev ? right : left;
7946
- const max = rev ? left : right;
7947
- ordered = ordered.filter((item) => inBound(item.score, min, max));
7948
- } else {
7949
- const [start, end] = indexes(ordered.length, args[1], args[2]);
7950
- ordered = start > end ? [] : ordered.slice(start, end + 1);
9352
+ if (added + updatedScore > 0) {
9353
+ database.put(key, zset);
9354
+ this.wake(session.db, key);
7951
9355
  }
7952
- if (rev) ordered.reverse();
7953
- if (limit) ordered = ordered.slice(limit.offset, limit.offset + limit.count);
7954
- return arr(
7955
- ordered.flatMap((item) => {
7956
- const member = { t: "bulk", v: item.member };
7957
- return withScores ? [member, bulk(scoreText(item.score))] : [member];
7958
- })
7959
- );
9356
+ if (incr) return incremented === null ? nil() : scoreReply(incremented, this.proto(session));
9357
+ return int(ch ? added + updatedScore : added);
9358
+ }
9359
+ /** Replies are RESP2 inside a script (Redis's default `redis.setresp(2)`), else the connection's. */
9360
+ proto(session) {
9361
+ return this.scriptDepth > 0 ? 2 : session.protocol;
9362
+ }
9363
+ zsetContext(session, apply) {
9364
+ return {
9365
+ database: this.database(session.db),
9366
+ proto: this.proto(session),
9367
+ apply,
9368
+ random: () => this.random(),
9369
+ wake: (key) => this.wake(session.db, key)
9370
+ };
7960
9371
  }
7961
9372
  cmdBlockingZset(session, args, apply, max) {
7962
9373
  const name = max ? "bzpopmax" : "bzpopmin";
7963
9374
  if (args.length < 2) return arityError(name);
7964
9375
  const timeout = parseTimeout(args[args.length - 1]);
7965
9376
  if (timeout === null) return err("ERR timeout is not a float or out of range");
7966
- const keys = args.slice(0, -1).map((arg) => text3(arg));
9377
+ const keys = args.slice(0, -1).map((arg) => text7(arg));
7967
9378
  for (const key of keys) {
7968
9379
  const value = this.database(session.db).get(key);
7969
9380
  if (value && value.kind !== "zset") return wrongType();
7970
9381
  }
7971
9382
  if (!apply) return queued();
7972
- const immediate = this.takeZset(session.db, keys, max);
9383
+ const immediate = this.takeZset(session.db, keys, max, this.proto(session));
7973
9384
  if (immediate) return immediate;
7974
9385
  if (session.inExec || this.scriptDepth > 0) return nilArray();
7975
9386
  return this.block({
@@ -7983,20 +9394,20 @@ var Redis = class {
7983
9394
  session
7984
9395
  });
7985
9396
  }
7986
- takeZset(dbIndex, keys, max) {
9397
+ takeZset(dbIndex, keys, max, proto) {
7987
9398
  if (this.consumersPaused) return null;
7988
9399
  const database = this.database(dbIndex);
7989
9400
  for (const key of keys) {
7990
9401
  const value = database.get(key);
7991
9402
  if (!value) continue;
7992
9403
  if (value.kind !== "zset") return wrongType();
7993
- const ordered = database.zsetOrdered(value);
7994
- const member = max ? ordered[ordered.length - 1] : ordered[0];
9404
+ const ordered2 = database.zsetOrdered(value);
9405
+ const member = max ? ordered2[ordered2.length - 1] : ordered2[0];
7995
9406
  if (!member) continue;
7996
9407
  value.members.delete(memberKey(member.member));
7997
9408
  database.dropIfEmpty(key);
7998
9409
  if (database.has(key)) database.put(key, value);
7999
- return arr([bulk(key), { t: "bulk", v: member.member }, bulk(scoreText(member.score))]);
9410
+ return arr([bulk(key), { t: "bulk", v: member.member }, scoreReply(member.score, proto)]);
8000
9411
  }
8001
9412
  return null;
8002
9413
  }
@@ -8004,7 +9415,7 @@ var Redis = class {
8004
9415
  if (command === "xadd") return this.cmdXadd(session, args, apply);
8005
9416
  if (command === "xlen") {
8006
9417
  if (args.length !== 1) return arityError("xlen");
8007
- const stream = this.stream(session, text3(args[0]), false);
9418
+ const stream = this.stream(session, text7(args[0]), false);
8008
9419
  if (stream === null) return int(0);
8009
9420
  if (!(stream instanceof Object) || !("entries" in stream)) return stream;
8010
9421
  return int(stream.entries.length);
@@ -8040,9 +9451,9 @@ var Redis = class {
8040
9451
  let index = 1;
8041
9452
  let nomk = false;
8042
9453
  let maxlen = null;
8043
- const key = text3(args[0]);
9454
+ const key = text7(args[0]);
8044
9455
  while (index < args.length) {
8045
- const option = upper3(args[index]);
9456
+ const option = upper5(args[index]);
8046
9457
  if (option === "NOMKSTREAM") {
8047
9458
  nomk = true;
8048
9459
  index++;
@@ -8050,7 +9461,7 @@ var Redis = class {
8050
9461
  }
8051
9462
  if (option === "MAXLEN" || option === "MINID") {
8052
9463
  index++;
8053
- if (upper3(args[index]) === "~" || upper3(args[index]) === "=") index++;
9464
+ if (upper5(args[index]) === "~" || upper5(args[index]) === "=") index++;
8054
9465
  const parsed = parseI64(args[index] ?? utf8(""));
8055
9466
  if (parsed === null || parsed < 0n) return syntaxError();
8056
9467
  if (option === "MAXLEN") maxlen = Number(parsed);
@@ -8059,7 +9470,7 @@ var Redis = class {
8059
9470
  }
8060
9471
  break;
8061
9472
  }
8062
- const idArg = text3(args[index]);
9473
+ const idArg = text7(args[index]);
8063
9474
  const fields = args.slice(index + 1);
8064
9475
  if (fields.length < 2 || fields.length % 2 !== 0) return syntaxError();
8065
9476
  const database = this.database(session.db);
@@ -8106,48 +9517,54 @@ var Redis = class {
8106
9517
  }
8107
9518
  return `${parsed.ms}-${parsed.seq}`;
8108
9519
  }
9520
+ /** `XRANGE key start end` and `XREVRANGE key end start`, with `(` exclusive and incomplete IDs. */
8109
9521
  cmdXrange(session, command, args) {
8110
9522
  if (args.length < 3) return arityError(command);
8111
- const stream = this.stream(session, text3(args[0]), false);
9523
+ const rev = command === "xrevrange";
9524
+ const startRaw = text7(rev ? args[2] : args[1]);
9525
+ const endRaw = text7(rev ? args[1] : args[2]);
9526
+ let count = null;
9527
+ for (let i = 3; i < args.length; i++) {
9528
+ if (upper5(args[i]) !== "COUNT" || i + 1 >= args.length) return syntaxError();
9529
+ const parsed = parseI64(args[++i] ?? utf8(""));
9530
+ if (parsed === null) return notInteger();
9531
+ count = parsed < 0n ? 0n : parsed;
9532
+ }
9533
+ const start = parseRangeId(startRaw, "start");
9534
+ if (typeof start === "string") return err(start);
9535
+ const end = parseRangeId(endRaw, "end");
9536
+ if (typeof end === "string") return err(end);
9537
+ if (count === 0n) return nilArray();
9538
+ const stream = this.stream(session, text7(args[0]), false);
8112
9539
  if (stream === null) return arr([]);
8113
9540
  if (!("entries" in stream)) return stream;
8114
- const start = text3(args[1]);
8115
- const end = text3(args[2]);
8116
- let count = Infinity;
8117
- if (upper3(args[3]) === "COUNT") {
8118
- const parsed = parseI64(args[4] ?? utf8(""));
8119
- if (parsed === null) return syntaxError();
8120
- count = Number(parsed);
8121
- }
8122
- let entries = stream.entries.filter((entry) => {
8123
- const afterStart = start === "-" || cmpId(entry.id, start) >= 0;
8124
- const beforeEnd = end === "+" || cmpId(entry.id, end) <= 0;
8125
- return afterStart && beforeEnd;
8126
- });
8127
- if (command === "xrevrange") entries = entries.slice().reverse();
8128
- return arr(entries.slice(0, count).map((entry) => entryFields(entry)));
9541
+ const within = (entry) => compareId(entry, start) >= 0 && compareId(entry, end) <= 0;
9542
+ let entries = stream.entries.filter(within);
9543
+ if (rev) entries = entries.slice().reverse();
9544
+ if (count !== null) entries = entries.slice(0, Number(count));
9545
+ return arr(entries.map((entry) => entryFields(entry)));
8129
9546
  }
8130
9547
  cmdXdel(session, args, apply) {
8131
9548
  if (args.length < 2) return arityError("xdel");
8132
- const stream = this.stream(session, text3(args[0]), false);
9549
+ const stream = this.stream(session, text7(args[0]), false);
8133
9550
  if (stream === null) return int(0);
8134
9551
  if (!("entries" in stream)) return stream;
8135
9552
  if (!apply) return queued();
8136
- const ids = new Set(args.slice(1).map((arg) => text3(arg)));
9553
+ const ids = new Set(args.slice(1).map((arg) => text7(arg)));
8137
9554
  const before = stream.entries.length;
8138
9555
  stream.entries = stream.entries.filter((entry) => !ids.has(entry.id));
8139
9556
  return int(before - stream.entries.length);
8140
9557
  }
8141
9558
  cmdXtrim(session, args, apply) {
8142
9559
  if (args.length < 3) return arityError("xtrim");
8143
- const stream = this.stream(session, text3(args[0]), false);
9560
+ const stream = this.stream(session, text7(args[0]), false);
8144
9561
  if (stream === null) return int(0);
8145
9562
  if (!("entries" in stream)) return stream;
8146
9563
  let index = 1;
8147
- const strategy = upper3(args[index]);
9564
+ const strategy = upper5(args[index]);
8148
9565
  if (strategy !== "MAXLEN" && strategy !== "MINID") return syntaxError();
8149
9566
  index++;
8150
- if (upper3(args[index]) === "~" || upper3(args[index]) === "=") index++;
9567
+ if (upper5(args[index]) === "~" || upper5(args[index]) === "=") index++;
8151
9568
  if (!apply) return queued();
8152
9569
  const before = stream.entries.length;
8153
9570
  if (strategy === "MAXLEN") {
@@ -8160,13 +9577,13 @@ var Redis = class {
8160
9577
  return int(before - stream.entries.length);
8161
9578
  }
8162
9579
  cmdXgroup(session, args, apply) {
8163
- const sub = upper3(args[0]);
9580
+ const sub = upper5(args[0]);
8164
9581
  if (sub === "CREATE") {
8165
9582
  if (args.length < 4) return arityError("xgroup");
8166
- const key = text3(args[1]);
8167
- const group = text3(args[2]);
8168
- const id = text3(args[3]);
8169
- const mk = args.some((arg) => upper3(arg) === "MKSTREAM");
9583
+ const key = text7(args[1]);
9584
+ const group = text7(args[2]);
9585
+ const id = text7(args[3]);
9586
+ const mk = args.some((arg) => upper5(arg) === "MKSTREAM");
8170
9587
  let stream = this.stream(session, key, false);
8171
9588
  if (stream === null) {
8172
9589
  if (!mk) {
@@ -8190,32 +9607,32 @@ var Redis = class {
8190
9607
  }
8191
9608
  if (sub === "DESTROY") {
8192
9609
  if (args.length !== 3) return arityError("xgroup");
8193
- const stream = this.stream(session, text3(args[1]), false);
9610
+ const stream = this.stream(session, text7(args[1]), false);
8194
9611
  if (!stream || !("groups" in stream)) return int(0);
8195
9612
  if (!apply) return queued();
8196
- return int(stream.groups.delete(text3(args[2])) ? 1 : 0);
9613
+ return int(stream.groups.delete(text7(args[2])) ? 1 : 0);
8197
9614
  }
8198
9615
  if (sub === "CREATECONSUMER") {
8199
9616
  if (args.length !== 4) return arityError("xgroup");
8200
- const stream = this.stream(session, text3(args[1]), false);
9617
+ const stream = this.stream(session, text7(args[1]), false);
8201
9618
  if (!stream || !("groups" in stream))
8202
9619
  return err("ERR The XGROUP subcommand requires the key to exist");
8203
- const group = stream.groups.get(text3(args[2]));
9620
+ const group = stream.groups.get(text7(args[2]));
8204
9621
  if (!group) return err("NOGROUP No such consumer group");
8205
9622
  if (!apply) return queued();
8206
- const name = text3(args[3]);
9623
+ const name = text7(args[3]);
8207
9624
  const created = !group.consumers.has(name);
8208
9625
  group.consumers.set(name, { seenAt: this.clock.now() });
8209
9626
  return int(created ? 1 : 0);
8210
9627
  }
8211
9628
  if (sub === "DELCONSUMER") {
8212
9629
  if (args.length !== 4) return arityError("xgroup");
8213
- const stream = this.stream(session, text3(args[1]), false);
9630
+ const stream = this.stream(session, text7(args[1]), false);
8214
9631
  if (!stream || !("groups" in stream)) return int(0);
8215
- const group = stream.groups.get(text3(args[2]));
9632
+ const group = stream.groups.get(text7(args[2]));
8216
9633
  if (!group) return int(0);
8217
9634
  if (!apply) return queued();
8218
- const name = text3(args[3]);
9635
+ const name = text7(args[3]);
8219
9636
  let pending = 0;
8220
9637
  for (const [id, item] of group.pel) {
8221
9638
  if (item.consumer !== name) continue;
@@ -8227,17 +9644,17 @@ var Redis = class {
8227
9644
  }
8228
9645
  if (sub === "SETID") {
8229
9646
  if (args.length < 4) return arityError("xgroup");
8230
- const stream = this.stream(session, text3(args[1]), false);
9647
+ const stream = this.stream(session, text7(args[1]), false);
8231
9648
  if (!stream || !("groups" in stream))
8232
9649
  return err("ERR The XGROUP subcommand requires the key to exist");
8233
- const group = stream.groups.get(text3(args[2]));
9650
+ const group = stream.groups.get(text7(args[2]));
8234
9651
  if (!group) return err("NOGROUP No such consumer group");
8235
9652
  if (!apply) return queued();
8236
- const id = text3(args[3]);
9653
+ const id = text7(args[3]);
8237
9654
  group.lastId = id === "$" ? stream.entries[stream.entries.length - 1]?.id ?? "0-0" : id;
8238
9655
  return ok();
8239
9656
  }
8240
- return err(`ERR unknown subcommand '${text3(args[0]).toLowerCase()}'. Try XGROUP HELP.`);
9657
+ return err(`ERR unknown subcommand '${text7(args[0]).toLowerCase()}'. Try XGROUP HELP.`);
8241
9658
  }
8242
9659
  cmdXread(session, args, apply, group) {
8243
9660
  let index = 0;
@@ -8247,13 +9664,13 @@ var Redis = class {
8247
9664
  let block = null;
8248
9665
  let noack = false;
8249
9666
  if (group) {
8250
- if (upper3(args[0]) !== "GROUP") return syntaxError();
8251
- groupName = text3(args[1]);
8252
- consumer = text3(args[2]);
9667
+ if (upper5(args[0]) !== "GROUP") return syntaxError();
9668
+ groupName = text7(args[1]);
9669
+ consumer = text7(args[2]);
8253
9670
  index = 3;
8254
9671
  }
8255
- while (index < args.length && upper3(args[index]) !== "STREAMS") {
8256
- const option = upper3(args[index]);
9672
+ while (index < args.length && upper5(args[index]) !== "STREAMS") {
9673
+ const option = upper5(args[index]);
8257
9674
  if (option === "COUNT") {
8258
9675
  const parsed = parseI64(args[++index] ?? utf8(""));
8259
9676
  if (parsed === null || parsed < 0n) return syntaxError();
@@ -8266,12 +9683,12 @@ var Redis = class {
8266
9683
  else return syntaxError();
8267
9684
  index++;
8268
9685
  }
8269
- if (upper3(args[index]) !== "STREAMS") return syntaxError();
9686
+ if (upper5(args[index]) !== "STREAMS") return syntaxError();
8270
9687
  const rest = args.slice(index + 1);
8271
9688
  if (rest.length < 2 || rest.length % 2 !== 0) return syntaxError();
8272
9689
  const half = rest.length / 2;
8273
- const keys = rest.slice(0, half).map((arg) => text3(arg));
8274
- const ids = rest.slice(half).map((arg) => text3(arg));
9690
+ const keys = rest.slice(0, half).map((arg) => text7(arg));
9691
+ const ids = rest.slice(half).map((arg) => text7(arg));
8275
9692
  if (!apply) return queued();
8276
9693
  for (const key of keys) {
8277
9694
  const value = this.database(session.db).get(key);
@@ -8342,24 +9759,24 @@ var Redis = class {
8342
9759
  }
8343
9760
  cmdXack(session, args, apply) {
8344
9761
  if (args.length < 3) return arityError("xack");
8345
- const stream = this.stream(session, text3(args[0]), false);
9762
+ const stream = this.stream(session, text7(args[0]), false);
8346
9763
  if (stream === null) return int(0);
8347
9764
  if (!("groups" in stream)) return stream;
8348
- const group = stream.groups.get(text3(args[1]));
9765
+ const group = stream.groups.get(text7(args[1]));
8349
9766
  if (!group) return int(0);
8350
9767
  if (!apply) return queued();
8351
9768
  let acked = 0;
8352
- for (const id of args.slice(2).map((arg) => text3(arg))) {
9769
+ for (const id of args.slice(2).map((arg) => text7(arg))) {
8353
9770
  if (group.pel.delete(id)) acked++;
8354
9771
  }
8355
9772
  return int(acked);
8356
9773
  }
8357
9774
  cmdXpending(session, args) {
8358
9775
  if (args.length < 2) return arityError("xpending");
8359
- const stream = this.stream(session, text3(args[0]), false);
9776
+ const stream = this.stream(session, text7(args[0]), false);
8360
9777
  if (stream === null) return err("ERR no such key");
8361
9778
  if (!("groups" in stream)) return stream;
8362
- const group = stream.groups.get(text3(args[1]));
9779
+ const group = stream.groups.get(text7(args[1]));
8363
9780
  if (!group) return err("NOGROUP No such consumer group");
8364
9781
  if (args.length === 2) {
8365
9782
  if (group.pel.size === 0) return arr([int(0), nil(), nil(), arr([])]);
@@ -8374,11 +9791,11 @@ var Redis = class {
8374
9791
  arr([...counts].map(([name, count2]) => arr([bulk(name), bulk(String(count2))])))
8375
9792
  ]);
8376
9793
  }
8377
- const start = text3(args[2]);
8378
- const end = text3(args[3]);
9794
+ const start = text7(args[2]);
9795
+ const end = text7(args[3]);
8379
9796
  const count = parseI64(args[4] ?? utf8(""));
8380
9797
  if (count === null) return syntaxError();
8381
- const consumer = args[5] ? text3(args[5]) : null;
9798
+ const consumer = args[5] ? text7(args[5]) : null;
8382
9799
  const rows = [...group.pel.values()].filter(
8383
9800
  (item) => (start === "-" || cmpId(item.id, start) >= 0) && (end === "+" || cmpId(item.id, end) <= 0)
8384
9801
  ).filter((item) => consumer === null || item.consumer === consumer).sort((a, b) => cmpId(a.id, b.id)).slice(0, Number(count));
@@ -8396,25 +9813,25 @@ var Redis = class {
8396
9813
  cmdXclaim(session, args, apply, auto) {
8397
9814
  const minIdleIndex = auto ? 3 : 3;
8398
9815
  if (args.length < (auto ? 5 : 5)) return arityError(auto ? "xautoclaim" : "xclaim");
8399
- const stream = this.stream(session, text3(args[0]), false);
9816
+ const stream = this.stream(session, text7(args[0]), false);
8400
9817
  if (!stream || !("groups" in stream)) return auto ? nilArray() : arr([]);
8401
- const group = stream.groups.get(text3(args[1]));
9818
+ const group = stream.groups.get(text7(args[1]));
8402
9819
  if (!group) return err("NOGROUP No such consumer group");
8403
- const consumer = text3(args[2]);
8404
- const minIdle = Number(text3(args[minIdleIndex]));
9820
+ const consumer = text7(args[2]);
9821
+ const minIdle = Number(text7(args[minIdleIndex]));
8405
9822
  if (!Number.isFinite(minIdle) || minIdle < 0) return syntaxError();
8406
9823
  if (!apply) return queued();
8407
9824
  let count = auto ? 100 : Infinity;
8408
9825
  let justId = false;
8409
9826
  const ids = [];
8410
9827
  if (auto) {
8411
- const start = text3(args[4]);
9828
+ const start = text7(args[4]);
8412
9829
  for (let i = 5; i < args.length; i++) {
8413
- if (upper3(args[i]) === "COUNT") {
9830
+ if (upper5(args[i]) === "COUNT") {
8414
9831
  const parsed = parseI64(args[++i] ?? utf8(""));
8415
9832
  if (parsed === null) return syntaxError();
8416
9833
  count = Number(parsed);
8417
- } else if (upper3(args[i]) === "JUSTID") justId = true;
9834
+ } else if (upper5(args[i]) === "JUSTID") justId = true;
8418
9835
  }
8419
9836
  const claimed2 = [];
8420
9837
  const deleted = [];
@@ -8447,11 +9864,11 @@ var Redis = class {
8447
9864
  ]);
8448
9865
  }
8449
9866
  for (let i = 4; i < args.length; i++) {
8450
- const option = upper3(args[i]);
9867
+ const option = upper5(args[i]);
8451
9868
  if (option === "IDLE" || option === "TIME" || option === "RETRYCOUNT") i++;
8452
9869
  else if (option === "FORCE" || option === "JUSTID") {
8453
9870
  if (option === "JUSTID") justId = true;
8454
- } else ids.push(text3(args[i]));
9871
+ } else ids.push(text7(args[i]));
8455
9872
  }
8456
9873
  const claimed = [];
8457
9874
  for (const id of ids) {
@@ -8468,9 +9885,9 @@ var Redis = class {
8468
9885
  return arr(claimed.map((entry) => justId ? bulk(entry.id) : entryFields(entry)));
8469
9886
  }
8470
9887
  cmdXinfo(session, args) {
8471
- const sub = upper3(args[0]);
9888
+ const sub = upper5(args[0]);
8472
9889
  if (sub === "STREAM") {
8473
- const stream = this.stream(session, text3(args[1]), false);
9890
+ const stream = this.stream(session, text7(args[1]), false);
8474
9891
  if (!stream || !("entries" in stream)) return err("ERR no such key");
8475
9892
  const first2 = stream.entries[0];
8476
9893
  const last = stream.entries[stream.entries.length - 1];
@@ -8492,7 +9909,7 @@ var Redis = class {
8492
9909
  ]);
8493
9910
  }
8494
9911
  if (sub === "GROUPS") {
8495
- const stream = this.stream(session, text3(args[1]), false);
9912
+ const stream = this.stream(session, text7(args[1]), false);
8496
9913
  if (!stream || !("groups" in stream)) return err("ERR no such key");
8497
9914
  return arr(
8498
9915
  [...stream.groups.values()].map(
@@ -8510,9 +9927,9 @@ var Redis = class {
8510
9927
  );
8511
9928
  }
8512
9929
  if (sub === "CONSUMERS") {
8513
- const stream = this.stream(session, text3(args[1]), false);
9930
+ const stream = this.stream(session, text7(args[1]), false);
8514
9931
  if (!stream || !("groups" in stream)) return err("ERR no such key");
8515
- const group = stream.groups.get(text3(args[2]));
9932
+ const group = stream.groups.get(text7(args[2]));
8516
9933
  if (!group) return err("NOGROUP No such consumer group");
8517
9934
  return arr(
8518
9935
  [...group.consumers].map(([name, info]) => {
@@ -8534,7 +9951,7 @@ var Redis = class {
8534
9951
  cmdSub(session, command, args) {
8535
9952
  const pattern = command.startsWith("p");
8536
9953
  const leaving = command.includes("unsubscribe");
8537
- const names = args.map((arg) => text3(arg));
9954
+ const names = args.map((arg) => text7(arg));
8538
9955
  if (!leaving && names.length === 0) return arityError(command);
8539
9956
  const targets = names.length > 0 ? names : [...pattern ? session.patterns : session.channels];
8540
9957
  if (targets.length === 0) {
@@ -8571,10 +9988,51 @@ var Redis = class {
8571
9988
  });
8572
9989
  return last;
8573
9990
  }
9991
+ subscriptions(session) {
9992
+ return session.channels.size + session.patterns.size + session.shards.size;
9993
+ }
9994
+ /** `SSUBSCRIBE` / `SUNSUBSCRIBE`. The count in each reply is the shard channels only, as Redis. */
9995
+ cmdShardSub(session, command, args) {
9996
+ const leaving = command === "sunsubscribe";
9997
+ const names = args.map((arg) => text7(arg));
9998
+ if (!leaving && names.length === 0) return arityError(command);
9999
+ const targets = names.length > 0 ? names : [...session.shards];
10000
+ if (targets.length === 0) return push([bulk(command), nil(), int(0)]);
10001
+ let last = ok();
10002
+ targets.forEach((name, index) => {
10003
+ if (leaving) {
10004
+ session.shards.delete(name);
10005
+ this.shardSubs.get(name)?.delete(session);
10006
+ if (this.shardSubs.get(name)?.size === 0) this.shardSubs.delete(name);
10007
+ } else {
10008
+ session.shards.add(name);
10009
+ const set = this.shardSubs.get(name) ?? /* @__PURE__ */ new Set();
10010
+ set.add(session);
10011
+ this.shardSubs.set(name, set);
10012
+ }
10013
+ const reply = push([bulk(command), bulk(name), int(session.shards.size)]);
10014
+ if (index < targets.length - 1) session.onPush(reply);
10015
+ else last = reply;
10016
+ });
10017
+ return last;
10018
+ }
10019
+ cmdSpublish(args) {
10020
+ if (args.length !== 2) return arityError("spublish");
10021
+ const channel = text7(args[0]);
10022
+ const message = args[1] ?? utf8("");
10023
+ let delivered = 0;
10024
+ for (const session of this.shardSubs.get(channel) ?? []) {
10025
+ session.onPush(push([bulk("smessage"), bulk(channel), { t: "bulk", v: message }]));
10026
+ delivered++;
10027
+ }
10028
+ return int(delivered);
10029
+ }
8574
10030
  cmdPublish(args) {
8575
10031
  if (args.length !== 2) return arityError("publish");
8576
- const channel = text3(args[0]);
8577
- const message = args[1] ?? utf8("");
10032
+ return int(this.deliver(text7(args[0]), args[1] ?? utf8("")));
10033
+ }
10034
+ /** Deliver `message` to `channel`'s subscribers and matching patterns; returns the receivers. */
10035
+ deliver(channel, message) {
8578
10036
  let delivered = 0;
8579
10037
  for (const session of this.channelSubs.get(channel) ?? []) {
8580
10038
  session.onPush(push([bulk("message"), bulk(channel), { t: "bulk", v: message }]));
@@ -8589,24 +10047,36 @@ var Redis = class {
8589
10047
  delivered++;
8590
10048
  }
8591
10049
  }
8592
- return int(delivered);
10050
+ return delivered;
8593
10051
  }
8594
10052
  cmdPubsub(args) {
8595
- const sub = upper3(args[0]);
10053
+ const sub = upper5(args[0]);
8596
10054
  if (sub === "NUMSUB") {
8597
10055
  const rows = [];
8598
10056
  for (const arg of args.slice(1)) {
8599
- rows.push(bulk(text3(arg)), int(this.channelSubs.get(text3(arg))?.size ?? 0));
10057
+ rows.push(bulk(text7(arg)), int(this.channelSubs.get(text7(arg))?.size ?? 0));
8600
10058
  }
8601
10059
  return arr(rows);
8602
10060
  }
8603
10061
  if (sub === "CHANNELS") {
8604
- const pattern = args[1] ? text3(args[1]) : "*";
10062
+ const pattern = args[1] ? text7(args[1]) : "*";
8605
10063
  return arr(
8606
10064
  [...this.channelSubs.keys()].filter((channel) => globMatch(pattern, channel)).map((channel) => bulk(channel))
8607
10065
  );
8608
10066
  }
8609
10067
  if (sub === "NUMPAT") return int(this.patternSubs.size);
10068
+ if (sub === "SHARDCHANNELS") {
10069
+ const pattern = args[1] ? text7(args[1]) : "*";
10070
+ return arr(
10071
+ [...this.shardSubs.keys()].filter((channel) => globMatch(pattern, channel)).map((channel) => bulk(channel))
10072
+ );
10073
+ }
10074
+ if (sub === "SHARDNUMSUB") {
10075
+ const rows = [];
10076
+ for (const arg of args.slice(1))
10077
+ rows.push(bulk(text7(arg)), int(this.shardSubs.get(text7(arg))?.size ?? 0));
10078
+ return arr(rows);
10079
+ }
8610
10080
  return arityError("pubsub");
8611
10081
  }
8612
10082
  cmdExec(session) {
@@ -8644,20 +10114,21 @@ var Redis = class {
8644
10114
  if (args.length < 1) return arityError("watch");
8645
10115
  if (session.multi) return err("ERR WATCH inside MULTI is not allowed");
8646
10116
  for (const arg of args) {
8647
- const key = text3(arg);
10117
+ const key = text7(arg);
8648
10118
  session.watching.push({ db: session.db, key, gen: this.database(session.db).generation(key) });
8649
10119
  }
8650
10120
  return ok();
8651
10121
  }
8652
10122
  cmdEval(session, command, args, apply) {
8653
- if (command === "evalsha" && this.faultValue === "noscript") {
10123
+ const bySha = command.startsWith("evalsha");
10124
+ if (bySha && this.faultValue === "noscript") {
8654
10125
  this.faultValue = null;
8655
10126
  return err("NOSCRIPT No matching script. Please use EVAL.");
8656
10127
  }
8657
10128
  if (args.length < 2) return arityError(command);
8658
- const digest = command === "eval" ? sha1Hex(args[0] ?? utf8("")) : text3(args[0]).toLowerCase();
8659
- const source = command === "eval" ? latin1(args[0] ?? utf8("")) : this.scripts.get(digest);
8660
- if (command === "evalsha" && source === void 0) return noScript();
10129
+ const digest = bySha ? text7(args[0]).toLowerCase() : sha1Hex(args[0] ?? utf8(""));
10130
+ const source = bySha ? this.scripts.get(digest) : latin1(args[0] ?? utf8(""));
10131
+ if (bySha && source === void 0) return noScript();
8661
10132
  const numkeys = parseI64(args[1] ?? utf8(""));
8662
10133
  if (numkeys === null) return notInteger();
8663
10134
  if (numkeys < 0n) return err("ERR Number of keys can't be negative");
@@ -8667,13 +10138,46 @@ var Redis = class {
8667
10138
  if (!apply || source === void 0) return queued();
8668
10139
  const keys = args.slice(2, 2 + Number(numkeys));
8669
10140
  const argv = args.slice(2 + Number(numkeys));
8670
- const result = this.runScript(session, source, digest, keys, argv);
10141
+ const result = this.runScript(session, source, digest, keys, argv, command.endsWith("_ro"));
8671
10142
  if (!(result.t === "error" && result.v.includes("Error compiling script")))
8672
10143
  this.scripts.set(digest, source);
8673
10144
  return result;
8674
10145
  }
10146
+ /** `FCALL` / `FCALL_RO`: run a function a library registered with `FUNCTION LOAD`. */
10147
+ cmdFcall(session, command, args, apply) {
10148
+ if (args.length < 2) return arityError(command);
10149
+ const fn = this.functions.find(latin1(args[0] ?? utf8("")));
10150
+ if (!fn) return err("ERR Function not found");
10151
+ const numkeys = parseI64(args[1] ?? utf8(""));
10152
+ if (numkeys === null) return err("ERR Bad number of keys provided");
10153
+ if (numkeys < 0n) return err("ERR Number of keys can't be negative");
10154
+ if (numkeys > BigInt(args.length - 2))
10155
+ return err("ERR Number of keys can't be greater than number of args");
10156
+ const readOnly = fn.flags.includes("no-writes");
10157
+ if (command === "fcall_ro" && !readOnly)
10158
+ return err("ERR Can not execute a script with write flag using *_ro command.");
10159
+ if (!apply) return queued();
10160
+ const keys = args.slice(2, 2 + Number(numkeys)).map(latin1);
10161
+ const argv = args.slice(2 + Number(numkeys)).map(latin1);
10162
+ const host = {
10163
+ call: (callArgs, raise) => this.luaDispatch(session, callArgs, raise)
10164
+ };
10165
+ const wasReadOnly = this.scriptReadOnly;
10166
+ this.scriptDepth++;
10167
+ this.scriptReadOnly = readOnly;
10168
+ try {
10169
+ return luaToReply(runFunction(fn, keys, argv, host, VERSION));
10170
+ } catch (error) {
10171
+ if (error instanceof ScriptFailure) return err(error.message);
10172
+ const message = error instanceof Error ? error.message : String(error);
10173
+ return err(`ERR Error running script: ${message}`);
10174
+ } finally {
10175
+ this.scriptDepth--;
10176
+ this.scriptReadOnly = wasReadOnly;
10177
+ }
10178
+ }
8675
10179
  cmdScript(args, apply) {
8676
- const sub = upper3(args[0]);
10180
+ const sub = upper5(args[0]);
8677
10181
  if (sub === "LOAD") {
8678
10182
  if (args.length !== 2) return arityError("script|load");
8679
10183
  if (!apply) return queued();
@@ -8689,7 +10193,7 @@ var Redis = class {
8689
10193
  return bulk(digest);
8690
10194
  }
8691
10195
  if (sub === "EXISTS") {
8692
- return arr(args.slice(1).map((arg) => int(this.scripts.has(text3(arg).toLowerCase()) ? 1 : 0)));
10196
+ return arr(args.slice(1).map((arg) => int(this.scripts.has(text7(arg).toLowerCase()) ? 1 : 0)));
8693
10197
  }
8694
10198
  if (sub === "FLUSH") {
8695
10199
  if (!apply) return queued();
@@ -8703,11 +10207,13 @@ var Redis = class {
8703
10207
  }
8704
10208
  return arityError("script");
8705
10209
  }
8706
- runScript(session, source, digest, keys, argv) {
10210
+ runScript(session, source, digest, keys, argv, readOnly = false) {
8707
10211
  const host = {
8708
10212
  call: (callArgs, raise) => this.luaDispatch(session, callArgs, raise)
8709
10213
  };
10214
+ const wasReadOnly = this.scriptReadOnly;
8710
10215
  this.scriptDepth++;
10216
+ this.scriptReadOnly = readOnly;
8711
10217
  try {
8712
10218
  const value = runScript(source, digest, keys.map(latin1), argv.map(latin1), host, VERSION);
8713
10219
  return luaToReply(value);
@@ -8717,6 +10223,7 @@ var Redis = class {
8717
10223
  return err(`ERR Error running script: ${message}`);
8718
10224
  } finally {
8719
10225
  this.scriptDepth--;
10226
+ this.scriptReadOnly = wasReadOnly;
8720
10227
  }
8721
10228
  }
8722
10229
  /** `redis.call` (`raise`) and `redis.pcall`: run one command for the script and convert its reply. */
@@ -8737,6 +10244,8 @@ var Redis = class {
8737
10244
  throw error;
8738
10245
  }
8739
10246
  if (SCRIPT_NESTED.has(name)) return fail2("ERR This Redis command is not allowed from script");
10247
+ if (this.scriptReadOnly && commandFlags(name).includes("write"))
10248
+ return fail2("ERR Write commands are not allowed from read-only scripts.");
8740
10249
  const reply = this.execCmd(session, name, bytes2, true, head);
8741
10250
  if (reply instanceof Promise) return fail2("ERR This Redis command is not allowed from script");
8742
10251
  if (reply.t === "error") {
@@ -8793,13 +10302,19 @@ var Redis = class {
8793
10302
  for (const waiter of [...this.waiters]) {
8794
10303
  if (waiter.settled || waiter.db !== dbIndex || !waiter.keys.includes(key)) continue;
8795
10304
  const reply = this.satisfy(waiter);
8796
- if (reply) this.finishWaiter(waiter, reply);
10305
+ if (reply) {
10306
+ this.waiterEvents(waiter, reply);
10307
+ this.finishWaiter(waiter, reply);
10308
+ }
8797
10309
  }
8798
10310
  }
8799
10311
  wakeAll() {
8800
10312
  for (const waiter of [...this.waiters]) {
8801
10313
  const reply = this.satisfy(waiter);
8802
- if (reply) this.finishWaiter(waiter, reply);
10314
+ if (reply) {
10315
+ this.waiterEvents(waiter, reply);
10316
+ this.finishWaiter(waiter, reply);
10317
+ }
8803
10318
  }
8804
10319
  }
8805
10320
  satisfy(waiter) {
@@ -8816,7 +10331,8 @@ var Redis = class {
8816
10331
  waiter.destSide ?? "left"
8817
10332
  );
8818
10333
  if (waiter.kind === "list") return this.takeList(waiter.db, waiter.keys, waiter.side);
8819
- if (waiter.kind === "zset") return this.takeZset(waiter.db, waiter.keys, waiter.max === true);
10334
+ if (waiter.kind === "zset")
10335
+ return this.takeZset(waiter.db, waiter.keys, waiter.max === true, session.protocol);
8820
10336
  const reply = this.readStreams(
8821
10337
  session,
8822
10338
  waiter.keys,
@@ -8831,6 +10347,35 @@ var Redis = class {
8831
10347
  if (reply.t === "error") return reply;
8832
10348
  return null;
8833
10349
  }
10350
+ /** Keyspace events of a blocked pop or move that an arriving element completed. */
10351
+ waiterEvents(waiter, reply) {
10352
+ if (this.notifyFlags === 0 || reply.t === "error") return;
10353
+ const gone = (key2) => this.database(waiter.db).peek(key2) === void 0;
10354
+ if (waiter.kind === "list" && waiter.destKey !== void 0) {
10355
+ const src = waiter.keys[0] ?? "";
10356
+ if (reply.t !== "bulk" || reply.v === null) return;
10357
+ const events2 = moveEvents(
10358
+ src,
10359
+ waiter.destKey,
10360
+ waiter.side,
10361
+ waiter.destSide ?? "left",
10362
+ gone(src)
10363
+ );
10364
+ this.publishWaiterEvents(waiter.db, events2);
10365
+ return;
10366
+ }
10367
+ if (waiter.kind === "stream" || reply.t !== "array" || !reply.v) return;
10368
+ const head = reply.v[0];
10369
+ const key = head?.t === "bulk" && head.v ? latin1(head.v) : "";
10370
+ const event = waiter.kind === "list" ? { cls: NOTIFY_LIST, event: waiter.side === "left" ? "lpop" : "rpop", key } : { cls: NOTIFY_ZSET, event: waiter.max ? "zpopmax" : "zpopmin", key };
10371
+ const events = [event];
10372
+ if (gone(key)) events.push({ cls: NOTIFY_GENERIC, event: "del", key });
10373
+ this.publishWaiterEvents(waiter.db, events);
10374
+ }
10375
+ publishWaiterEvents(db, events) {
10376
+ if (this.notifyDepth > 0) this.deferredEvents.push({ db, events });
10377
+ else this.publishEvents(db, events);
10378
+ }
8834
10379
  finishWaiter(waiter, reply) {
8835
10380
  if (waiter.settled) return;
8836
10381
  waiter.settled = true;
@@ -8852,8 +10397,13 @@ var Redis = class {
8852
10397
  leavePubsub(session) {
8853
10398
  for (const channel of session.channels) this.channelSubs.get(channel)?.delete(session);
8854
10399
  for (const pattern of session.patterns) this.patternSubs.get(pattern)?.delete(session);
10400
+ for (const shard of session.shards) {
10401
+ this.shardSubs.get(shard)?.delete(session);
10402
+ if (this.shardSubs.get(shard)?.size === 0) this.shardSubs.delete(shard);
10403
+ }
8855
10404
  session.channels.clear();
8856
10405
  session.patterns.clear();
10406
+ session.shards.clear();
8857
10407
  }
8858
10408
  };
8859
10409
  var waiterSession = /* @__PURE__ */ new WeakMap();
@@ -8872,8 +10422,8 @@ function compareBytes(left, right) {
8872
10422
  return left.length - right.length;
8873
10423
  }
8874
10424
  function indexes(length2, startRaw, endRaw) {
8875
- let start = Number(text3(startRaw));
8876
- let end = Number(text3(endRaw));
10425
+ let start = Number(text7(startRaw));
10426
+ let end = Number(text7(endRaw));
8877
10427
  if (!Number.isInteger(start)) start = 0;
8878
10428
  if (!Number.isInteger(end)) end = -1;
8879
10429
  if (start < 0) start = length2 + start;
@@ -8882,14 +10432,42 @@ function indexes(length2, startRaw, endRaw) {
8882
10432
  if (end >= length2) end = length2 - 1;
8883
10433
  return [start, end];
8884
10434
  }
8885
- function listIndex(length2, raw) {
8886
- const parsed = parseI64(raw ?? utf8(""));
10435
+ function listIndex(length2, raw2) {
10436
+ const parsed = parseI64(raw2 ?? utf8(""));
8887
10437
  if (parsed === null) return null;
8888
10438
  let index = Number(parsed);
8889
10439
  if (index < 0) index = length2 + index;
8890
10440
  if (index < 0 || index >= length2) return null;
8891
10441
  return index;
8892
10442
  }
10443
+ var ID_MAX = 18446744073709551615n;
10444
+ var INVALID_ID = "ERR Invalid stream ID specified as stream command argument";
10445
+ function parseRangeId(raw2, side) {
10446
+ const exclusive = raw2.startsWith("(");
10447
+ const body = exclusive ? raw2.slice(1) : raw2;
10448
+ let id;
10449
+ if (body === "-" || body === "+") {
10450
+ if (exclusive) return INVALID_ID;
10451
+ id = body === "-" ? { ms: 0n, seq: 0n } : { ms: ID_MAX, seq: ID_MAX };
10452
+ } else if (/^\d+$/.test(body)) {
10453
+ id = { ms: BigInt(body), seq: side === "start" ? 0n : ID_MAX };
10454
+ } else id = parseStreamId(body);
10455
+ if (!id || id.ms > ID_MAX || id.seq > ID_MAX) return INVALID_ID;
10456
+ if (!exclusive) return id;
10457
+ if (side === "start") {
10458
+ if (id.seq < ID_MAX) return { ms: id.ms, seq: id.seq + 1n };
10459
+ if (id.ms < ID_MAX) return { ms: id.ms + 1n, seq: 0n };
10460
+ return "ERR invalid start ID for the interval";
10461
+ }
10462
+ if (id.seq > 0n) return { ms: id.ms, seq: id.seq - 1n };
10463
+ if (id.ms > 0n) return { ms: id.ms - 1n, seq: ID_MAX };
10464
+ return "ERR invalid end ID for the interval";
10465
+ }
10466
+ function compareId(entry, id) {
10467
+ if (entry.ms !== id.ms) return entry.ms < id.ms ? -1 : 1;
10468
+ if (entry.seq !== id.seq) return entry.seq < id.seq ? -1 : 1;
10469
+ return 0;
10470
+ }
8893
10471
  function parseBound(value) {
8894
10472
  if (value === "+inf" || value === "inf") return { value: Infinity, exclusive: false };
8895
10473
  if (value === "-inf") return { value: -Infinity, exclusive: false };
@@ -8985,4 +10563,4 @@ export {
8985
10563
  RedisPipeline,
8986
10564
  createRedis
8987
10565
  };
8988
- //# sourceMappingURL=chunk-AMGKTUAB.js.map
10566
+ //# sourceMappingURL=chunk-FDTSPQXG.js.map