@ooneex/rate-limit 1.1.3 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15,13 +15,23 @@ var __legacyMetadataTS = (k, v) => {
15
15
  return Reflect.metadata(k, v);
16
16
  };
17
17
 
18
+ // src/decorators.ts
19
+ import { container, EContainerScope } from "@ooneex/container";
20
+ var decorator = {
21
+ rateLimit: (scope = EContainerScope.Singleton) => {
22
+ return (target) => {
23
+ container.add(target, scope);
24
+ };
25
+ }
26
+ };
18
27
  // src/RateLimitException.ts
19
28
  import { Exception } from "@ooneex/exception";
20
29
  import { HttpStatus } from "@ooneex/http-status";
21
30
 
22
31
  class RateLimitException extends Exception {
23
- constructor(message, data = {}) {
32
+ constructor(message, key, data = {}) {
24
33
  super(message, {
34
+ key,
25
35
  status: HttpStatus.Code.TooManyRequests,
26
36
  data
27
37
  });
@@ -30,7 +40,7 @@ class RateLimitException extends Exception {
30
40
  }
31
41
  // src/RedisRateLimiter.ts
32
42
  import { AppEnv } from "@ooneex/app-env";
33
- import { inject, injectable } from "@ooneex/container";
43
+ import { inject } from "@ooneex/container";
34
44
  class RedisRateLimiter {
35
45
  env;
36
46
  client;
@@ -38,7 +48,7 @@ class RedisRateLimiter {
38
48
  this.env = env;
39
49
  const connectionString = options.connectionString || this.env.RATE_LIMIT_REDIS_URL;
40
50
  if (!connectionString) {
41
- throw new RateLimitException("Redis connection string is required. Please provide a connection string either through the constructor options or set the RATE_LIMIT_REDIS_URL environment variable.");
51
+ throw new RateLimitException("Redis connection string is required. Please provide a connection string either through the constructor options or set the RATE_LIMIT_REDIS_URL environment variable.", "RATE_LIMIT_CONNECTION_FAILED");
42
52
  }
43
53
  const { connectionString: _, ...userOptions } = options;
44
54
  const defaultOptions = {
@@ -60,7 +70,9 @@ class RedisRateLimiter {
60
70
  getKey(key) {
61
71
  return `ratelimit:${key}`;
62
72
  }
63
- async check(key, limit, windowSeconds) {
73
+ async check(key) {
74
+ const limit = 120;
75
+ const windowSeconds = 60;
64
76
  try {
65
77
  await this.connect();
66
78
  const rateLimitKey = this.getKey(key);
@@ -77,9 +89,13 @@ class RedisRateLimiter {
77
89
  resetAt
78
90
  };
79
91
  } catch (error) {
80
- throw new RateLimitException(`Failed to check rate limit for key "${key}": ${error}`);
92
+ throw new RateLimitException(`Failed to check rate limit for key "${key}": ${error}`, "RATE_LIMIT_CHECK_FAILED");
81
93
  }
82
94
  }
95
+ async isLimited(key) {
96
+ const result = await this.check(key);
97
+ return result.limited;
98
+ }
83
99
  async reset(key) {
84
100
  try {
85
101
  await this.connect();
@@ -87,7 +103,7 @@ class RedisRateLimiter {
87
103
  const result = await this.client.del(rateLimitKey);
88
104
  return result > 0;
89
105
  } catch (error) {
90
- throw new RateLimitException(`Failed to reset rate limit for key "${key}": ${error}`);
106
+ throw new RateLimitException(`Failed to reset rate limit for key "${key}": ${error}`, "RATE_LIMIT_RESET_FAILED");
91
107
  }
92
108
  }
93
109
  async getCount(key) {
@@ -100,21 +116,3618 @@ class RedisRateLimiter {
100
116
  }
101
117
  return Number.parseInt(value, 10);
102
118
  } catch (error) {
103
- throw new RateLimitException(`Failed to get count for key "${key}": ${error}`);
119
+ throw new RateLimitException(`Failed to get count for key "${key}": ${error}`, "RATE_LIMIT_COUNT_FAILED");
104
120
  }
105
121
  }
106
122
  }
107
123
  RedisRateLimiter = __legacyDecorateClassTS([
108
- injectable(),
124
+ decorator.rateLimit(),
109
125
  __legacyDecorateParamTS(0, inject(AppEnv)),
110
126
  __legacyMetadataTS("design:paramtypes", [
111
127
  typeof AppEnv === "undefined" ? Object : AppEnv,
112
128
  typeof RedisRateLimiterOptionsType === "undefined" ? Object : RedisRateLimiterOptionsType
113
129
  ])
114
130
  ], RedisRateLimiter);
131
+ // src/UpstashRedisRateLimiter.ts
132
+ import { AppEnv as AppEnv2 } from "@ooneex/app-env";
133
+ import { inject as inject2 } from "@ooneex/container";
134
+ import { Ratelimit } from "@upstash/ratelimit";
135
+
136
+ // ../../node_modules/.bun/uncrypto@0.1.3/node_modules/uncrypto/dist/crypto.web.mjs
137
+ var webCrypto = globalThis.crypto;
138
+ var subtle = webCrypto.subtle;
139
+
140
+ // ../../node_modules/.bun/@upstash+redis@1.37.0/node_modules/@upstash/redis/chunk-IH7W44G6.mjs
141
+ var __defProp = Object.defineProperty;
142
+ var __export = (target, all) => {
143
+ for (var name in all)
144
+ __defProp(target, name, { get: all[name], enumerable: true });
145
+ };
146
+ var error_exports = {};
147
+ __export(error_exports, {
148
+ UpstashError: () => UpstashError,
149
+ UpstashJSONParseError: () => UpstashJSONParseError,
150
+ UrlError: () => UrlError
151
+ });
152
+ var UpstashError = class extends Error {
153
+ constructor(message, options) {
154
+ super(message, options);
155
+ this.name = "UpstashError";
156
+ }
157
+ };
158
+ var UrlError = class extends Error {
159
+ constructor(url) {
160
+ super(`Upstash Redis client was passed an invalid URL. You should pass a URL starting with https. Received: "${url}". `);
161
+ this.name = "UrlError";
162
+ }
163
+ };
164
+ var UpstashJSONParseError = class extends UpstashError {
165
+ constructor(body, options) {
166
+ const truncatedBody = body.length > 200 ? body.slice(0, 200) + "..." : body;
167
+ super(`Unable to parse response body: ${truncatedBody}`, options);
168
+ this.name = "UpstashJSONParseError";
169
+ }
170
+ };
171
+ function parseRecursive(obj) {
172
+ const parsed = Array.isArray(obj) ? obj.map((o) => {
173
+ try {
174
+ return parseRecursive(o);
175
+ } catch {
176
+ return o;
177
+ }
178
+ }) : JSON.parse(obj);
179
+ if (typeof parsed === "number" && parsed.toString() !== obj) {
180
+ return obj;
181
+ }
182
+ return parsed;
183
+ }
184
+ function parseResponse(result) {
185
+ try {
186
+ return parseRecursive(result);
187
+ } catch {
188
+ return result;
189
+ }
190
+ }
191
+ function deserializeScanResponse(result) {
192
+ return [result[0], ...parseResponse(result.slice(1))];
193
+ }
194
+ function deserializeScanWithTypesResponse(result) {
195
+ const [cursor, keys] = result;
196
+ const parsedKeys = [];
197
+ for (let i = 0;i < keys.length; i += 2) {
198
+ parsedKeys.push({ key: keys[i], type: keys[i + 1] });
199
+ }
200
+ return [cursor, parsedKeys];
201
+ }
202
+ function mergeHeaders(...headers) {
203
+ const merged = {};
204
+ for (const header of headers) {
205
+ if (!header)
206
+ continue;
207
+ for (const [key, value] of Object.entries(header)) {
208
+ if (value !== undefined && value !== null) {
209
+ merged[key] = value;
210
+ }
211
+ }
212
+ }
213
+ return merged;
214
+ }
215
+ function kvArrayToObject(v) {
216
+ if (typeof v === "object" && v !== null && !Array.isArray(v))
217
+ return v;
218
+ if (!Array.isArray(v))
219
+ return {};
220
+ const obj = {};
221
+ for (let i = 0;i < v.length; i += 2) {
222
+ if (typeof v[i] === "string")
223
+ obj[v[i]] = v[i + 1];
224
+ }
225
+ return obj;
226
+ }
227
+ var MAX_BUFFER_SIZE = 1024 * 1024;
228
+ var HttpClient = class {
229
+ baseUrl;
230
+ headers;
231
+ options;
232
+ readYourWrites;
233
+ upstashSyncToken = "";
234
+ hasCredentials;
235
+ retry;
236
+ constructor(config) {
237
+ this.options = {
238
+ backend: config.options?.backend,
239
+ agent: config.agent,
240
+ responseEncoding: config.responseEncoding ?? "base64",
241
+ cache: config.cache,
242
+ signal: config.signal,
243
+ keepAlive: config.keepAlive ?? true
244
+ };
245
+ this.upstashSyncToken = "";
246
+ this.readYourWrites = config.readYourWrites ?? true;
247
+ this.baseUrl = (config.baseUrl || "").replace(/\/$/, "");
248
+ const urlRegex = /^https?:\/\/[^\s#$./?].\S*$/;
249
+ if (this.baseUrl && !urlRegex.test(this.baseUrl)) {
250
+ throw new UrlError(this.baseUrl);
251
+ }
252
+ this.headers = {
253
+ "Content-Type": "application/json",
254
+ ...config.headers
255
+ };
256
+ this.hasCredentials = Boolean(this.baseUrl && this.headers.authorization.split(" ")[1]);
257
+ if (this.options.responseEncoding === "base64") {
258
+ this.headers["Upstash-Encoding"] = "base64";
259
+ }
260
+ this.retry = typeof config.retry === "boolean" && !config.retry ? {
261
+ attempts: 1,
262
+ backoff: () => 0
263
+ } : {
264
+ attempts: config.retry?.retries ?? 5,
265
+ backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50)
266
+ };
267
+ }
268
+ mergeTelemetry(telemetry) {
269
+ this.headers = merge(this.headers, "Upstash-Telemetry-Runtime", telemetry.runtime);
270
+ this.headers = merge(this.headers, "Upstash-Telemetry-Platform", telemetry.platform);
271
+ this.headers = merge(this.headers, "Upstash-Telemetry-Sdk", telemetry.sdk);
272
+ }
273
+ async request(req) {
274
+ const requestHeaders = mergeHeaders(this.headers, req.headers ?? {});
275
+ const requestUrl = [this.baseUrl, ...req.path ?? []].join("/");
276
+ const isEventStream = requestHeaders.Accept === "text/event-stream";
277
+ const signal = req.signal ?? this.options.signal;
278
+ const isSignalFunction = typeof signal === "function";
279
+ const requestOptions = {
280
+ cache: this.options.cache,
281
+ method: "POST",
282
+ headers: requestHeaders,
283
+ body: JSON.stringify(req.body),
284
+ keepalive: this.options.keepAlive,
285
+ agent: this.options.agent,
286
+ signal: isSignalFunction ? signal() : signal,
287
+ backend: this.options.backend
288
+ };
289
+ if (!this.hasCredentials) {}
290
+ if (this.readYourWrites) {
291
+ const newHeader = this.upstashSyncToken;
292
+ this.headers["upstash-sync-token"] = newHeader;
293
+ }
294
+ let res = null;
295
+ let error = null;
296
+ for (let i = 0;i <= this.retry.attempts; i++) {
297
+ try {
298
+ res = await fetch(requestUrl, requestOptions);
299
+ break;
300
+ } catch (error_) {
301
+ if (requestOptions.signal?.aborted && isSignalFunction) {
302
+ throw error_;
303
+ } else if (requestOptions.signal?.aborted) {
304
+ const myBlob = new Blob([
305
+ JSON.stringify({ result: requestOptions.signal.reason ?? "Aborted" })
306
+ ]);
307
+ const myOptions = {
308
+ status: 200,
309
+ statusText: requestOptions.signal.reason ?? "Aborted"
310
+ };
311
+ res = new Response(myBlob, myOptions);
312
+ break;
313
+ }
314
+ error = error_;
315
+ if (i < this.retry.attempts) {
316
+ await new Promise((r) => setTimeout(r, this.retry.backoff(i)));
317
+ }
318
+ }
319
+ }
320
+ if (!res) {
321
+ throw error ?? new Error("Exhausted all retries");
322
+ }
323
+ if (!res.ok) {
324
+ let body2;
325
+ const rawBody2 = await res.text();
326
+ try {
327
+ body2 = JSON.parse(rawBody2);
328
+ } catch (error2) {
329
+ throw new UpstashJSONParseError(rawBody2, { cause: error2 });
330
+ }
331
+ throw new UpstashError(`${body2.error}, command was: ${JSON.stringify(req.body)}`);
332
+ }
333
+ if (this.readYourWrites) {
334
+ const headers = res.headers;
335
+ this.upstashSyncToken = headers.get("upstash-sync-token") ?? "";
336
+ }
337
+ if (isEventStream && req && req.onMessage && res.body) {
338
+ const reader = res.body.getReader();
339
+ const decoder = new TextDecoder;
340
+ (async () => {
341
+ try {
342
+ let buffer = "";
343
+ while (true) {
344
+ const { value, done } = await reader.read();
345
+ if (done)
346
+ break;
347
+ buffer += decoder.decode(value, { stream: true });
348
+ const lines = buffer.split(`
349
+ `);
350
+ buffer = lines.pop() || "";
351
+ if (buffer.length > MAX_BUFFER_SIZE) {
352
+ throw new Error("Buffer size exceeded (1MB)");
353
+ }
354
+ for (const line of lines) {
355
+ if (line.startsWith("data: ")) {
356
+ const data = line.slice(6);
357
+ req.onMessage?.(data);
358
+ }
359
+ }
360
+ }
361
+ } catch (error2) {
362
+ if (error2 instanceof Error && error2.name === "AbortError") {} else {}
363
+ } finally {
364
+ try {
365
+ await reader.cancel();
366
+ } catch {}
367
+ }
368
+ })();
369
+ return { result: 1 };
370
+ }
371
+ let body;
372
+ const rawBody = await res.text();
373
+ try {
374
+ body = JSON.parse(rawBody);
375
+ } catch (error2) {
376
+ throw new UpstashJSONParseError(rawBody, { cause: error2 });
377
+ }
378
+ if (this.readYourWrites) {
379
+ const headers = res.headers;
380
+ this.upstashSyncToken = headers.get("upstash-sync-token") ?? "";
381
+ }
382
+ if (this.options.responseEncoding === "base64") {
383
+ if (Array.isArray(body)) {
384
+ return body.map(({ result: result2, error: error2 }) => ({
385
+ result: decode(result2),
386
+ error: error2
387
+ }));
388
+ }
389
+ const result = decode(body.result);
390
+ return { result, error: body.error };
391
+ }
392
+ return body;
393
+ }
394
+ };
395
+ function base64decode(b64) {
396
+ let dec = "";
397
+ try {
398
+ const binString = atob(b64);
399
+ const size = binString.length;
400
+ const bytes = new Uint8Array(size);
401
+ for (let i = 0;i < size; i++) {
402
+ bytes[i] = binString.charCodeAt(i);
403
+ }
404
+ dec = new TextDecoder().decode(bytes);
405
+ } catch {
406
+ dec = b64;
407
+ }
408
+ return dec;
409
+ }
410
+ function decode(raw) {
411
+ let result = undefined;
412
+ switch (typeof raw) {
413
+ case "undefined": {
414
+ return raw;
415
+ }
416
+ case "number": {
417
+ result = raw;
418
+ break;
419
+ }
420
+ case "object": {
421
+ if (Array.isArray(raw)) {
422
+ result = raw.map((v) => typeof v === "string" ? base64decode(v) : Array.isArray(v) ? v.map((element) => decode(element)) : v);
423
+ } else {
424
+ result = null;
425
+ }
426
+ break;
427
+ }
428
+ case "string": {
429
+ result = raw === "OK" ? "OK" : base64decode(raw);
430
+ break;
431
+ }
432
+ default: {
433
+ break;
434
+ }
435
+ }
436
+ return result;
437
+ }
438
+ function merge(obj, key, value) {
439
+ if (!value) {
440
+ return obj;
441
+ }
442
+ obj[key] = obj[key] ? [obj[key], value].join(",") : value;
443
+ return obj;
444
+ }
445
+ var defaultSerializer = (c) => {
446
+ switch (typeof c) {
447
+ case "string":
448
+ case "number":
449
+ case "boolean": {
450
+ return c;
451
+ }
452
+ default: {
453
+ return JSON.stringify(c);
454
+ }
455
+ }
456
+ };
457
+ var Command = class {
458
+ command;
459
+ serialize;
460
+ deserialize;
461
+ headers;
462
+ path;
463
+ onMessage;
464
+ isStreaming;
465
+ signal;
466
+ constructor(command, opts) {
467
+ this.serialize = defaultSerializer;
468
+ this.deserialize = opts?.automaticDeserialization === undefined || opts.automaticDeserialization ? opts?.deserialize ?? parseResponse : (x) => x;
469
+ this.command = command.map((c) => this.serialize(c));
470
+ this.headers = opts?.headers;
471
+ this.path = opts?.path;
472
+ this.onMessage = opts?.streamOptions?.onMessage;
473
+ this.isStreaming = opts?.streamOptions?.isStreaming ?? false;
474
+ this.signal = opts?.streamOptions?.signal;
475
+ if (opts?.latencyLogging) {
476
+ const originalExec = this.exec.bind(this);
477
+ this.exec = async (client) => {
478
+ const start = performance.now();
479
+ const result = await originalExec(client);
480
+ const end = performance.now();
481
+ const loggerResult = (end - start).toFixed(2);
482
+ return result;
483
+ };
484
+ }
485
+ }
486
+ async exec(client) {
487
+ const { result, error } = await client.request({
488
+ body: this.command,
489
+ path: this.path,
490
+ upstashSyncToken: client.upstashSyncToken,
491
+ headers: this.headers,
492
+ onMessage: this.onMessage,
493
+ isStreaming: this.isStreaming,
494
+ signal: this.signal
495
+ });
496
+ if (error) {
497
+ throw new UpstashError(error);
498
+ }
499
+ if (result === undefined) {
500
+ throw new TypeError("Request did not return a result");
501
+ }
502
+ return this.deserialize(result);
503
+ }
504
+ };
505
+ var ExecCommand = class extends Command {
506
+ constructor(cmd, opts) {
507
+ const normalizedCmd = cmd.map((arg) => typeof arg === "string" ? arg : String(arg));
508
+ super(normalizedCmd, opts);
509
+ }
510
+ };
511
+ var FIELD_TYPES = [
512
+ "TEXT",
513
+ "U64",
514
+ "I64",
515
+ "F64",
516
+ "BOOL",
517
+ "DATE",
518
+ "KEYWORD",
519
+ "FACET"
520
+ ];
521
+ function isFieldType(value) {
522
+ return typeof value === "string" && FIELD_TYPES.includes(value);
523
+ }
524
+ function isDetailedField(value) {
525
+ return typeof value === "object" && value !== null && "type" in value && isFieldType(value.type);
526
+ }
527
+ function isNestedSchema(value) {
528
+ return typeof value === "object" && value !== null && !isDetailedField(value);
529
+ }
530
+ function flattenSchema(schema, pathPrefix = []) {
531
+ const fields = [];
532
+ for (const [key, value] of Object.entries(schema)) {
533
+ const currentPath = [...pathPrefix, key];
534
+ const pathString = currentPath.join(".");
535
+ if (isFieldType(value)) {
536
+ fields.push({
537
+ path: pathString,
538
+ type: value
539
+ });
540
+ } else if (isDetailedField(value)) {
541
+ fields.push({
542
+ path: pathString,
543
+ type: value.type,
544
+ fast: "fast" in value ? value.fast : undefined,
545
+ noTokenize: "noTokenize" in value ? value.noTokenize : undefined,
546
+ noStem: "noStem" in value ? value.noStem : undefined,
547
+ from: "from" in value ? value.from : undefined
548
+ });
549
+ } else if (isNestedSchema(value)) {
550
+ const nestedFields = flattenSchema(value, currentPath);
551
+ fields.push(...nestedFields);
552
+ }
553
+ }
554
+ return fields;
555
+ }
556
+ function deserializeQueryResponse(rawResponse) {
557
+ return rawResponse.map((itemRaw) => {
558
+ const raw = itemRaw;
559
+ const key = raw[0];
560
+ const score = Number(raw[1]);
561
+ const rawFields = raw[2];
562
+ if (rawFields === undefined) {
563
+ return { key, score };
564
+ }
565
+ if (!Array.isArray(rawFields) || rawFields.length === 0) {
566
+ return { key, score, data: {} };
567
+ }
568
+ let data = {};
569
+ for (const fieldRaw of rawFields) {
570
+ const key2 = fieldRaw[0];
571
+ const value = fieldRaw[1];
572
+ const pathParts = key2.split(".");
573
+ if (pathParts.length === 1) {
574
+ data[key2] = value;
575
+ } else {
576
+ let currentObj = data;
577
+ for (let i = 0;i < pathParts.length - 1; i++) {
578
+ const pathPart = pathParts[i];
579
+ if (!(pathPart in currentObj)) {
580
+ currentObj[pathPart] = {};
581
+ }
582
+ currentObj = currentObj[pathPart];
583
+ }
584
+ currentObj[pathParts.at(-1)] = value;
585
+ }
586
+ }
587
+ if ("$" in data) {
588
+ data = data["$"];
589
+ }
590
+ return { key, score, data };
591
+ });
592
+ }
593
+ function deserializeDescribeResponse(rawResponse) {
594
+ const description = {};
595
+ for (let i = 0;i < rawResponse.length; i += 2) {
596
+ const descriptor = rawResponse[i];
597
+ switch (descriptor) {
598
+ case "name": {
599
+ description["name"] = rawResponse[i + 1];
600
+ break;
601
+ }
602
+ case "type": {
603
+ description["dataType"] = rawResponse[i + 1].toLowerCase();
604
+ break;
605
+ }
606
+ case "prefixes": {
607
+ description["prefixes"] = rawResponse[i + 1];
608
+ break;
609
+ }
610
+ case "language": {
611
+ description["language"] = rawResponse[i + 1];
612
+ break;
613
+ }
614
+ case "schema": {
615
+ const schema = {};
616
+ for (const fieldDescription of rawResponse[i + 1]) {
617
+ const fieldName = fieldDescription[0];
618
+ const fieldInfo = { type: fieldDescription[1] };
619
+ if (fieldDescription.length > 2) {
620
+ for (let j = 2;j < fieldDescription.length; j++) {
621
+ const fieldOption = fieldDescription[j];
622
+ switch (fieldOption) {
623
+ case "NOSTEM": {
624
+ fieldInfo.noStem = true;
625
+ break;
626
+ }
627
+ case "NOTOKENIZE": {
628
+ fieldInfo.noTokenize = true;
629
+ break;
630
+ }
631
+ case "FAST": {
632
+ fieldInfo.fast = true;
633
+ break;
634
+ }
635
+ case "FROM": {
636
+ fieldInfo.from = fieldDescription[++j];
637
+ break;
638
+ }
639
+ }
640
+ }
641
+ }
642
+ schema[fieldName] = fieldInfo;
643
+ }
644
+ description["schema"] = schema;
645
+ break;
646
+ }
647
+ }
648
+ }
649
+ return description;
650
+ }
651
+ function parseCountResponse(rawResponse) {
652
+ return typeof rawResponse === "number" ? rawResponse : Number.parseInt(rawResponse, 10);
653
+ }
654
+ function deserializeAggregateResponse(rawResponse) {
655
+ return parseAggregationArray(rawResponse);
656
+ }
657
+ function parseAggregationArray(arr) {
658
+ const result = {};
659
+ for (let i = 0;i < arr.length; i += 2) {
660
+ const key = arr[i];
661
+ const value = arr[i + 1];
662
+ if (Array.isArray(value)) {
663
+ if (value.length > 0 && typeof value[0] === "string") {
664
+ result[key] = value[0] === "buckets" ? parseBucketsValue(value) : parseStatsValue(value);
665
+ } else {
666
+ result[key] = parseAggregationArray(value);
667
+ }
668
+ } else {
669
+ result[key] = value;
670
+ }
671
+ }
672
+ return result;
673
+ }
674
+ function coerceNumericString(value) {
675
+ if (typeof value === "string" && value !== "" && !Number.isNaN(Number(value))) {
676
+ return Number(value);
677
+ }
678
+ return value;
679
+ }
680
+ function parseStatsValue(arr) {
681
+ const result = {};
682
+ for (let i = 0;i < arr.length; i += 2) {
683
+ const key = arr[i];
684
+ const value = arr[i + 1];
685
+ if (Array.isArray(value) && value.length > 0) {
686
+ if (typeof value[0] === "string") {
687
+ result[key] = parseStatsValue(value);
688
+ } else if (Array.isArray(value[0]) && typeof value[0][0] === "string") {
689
+ result[key] = value.map((item) => parseStatsValue(item));
690
+ } else {
691
+ result[key] = value;
692
+ }
693
+ } else {
694
+ result[key] = coerceNumericString(value);
695
+ }
696
+ }
697
+ return result;
698
+ }
699
+ function parseBucketsValue(arr) {
700
+ if (arr[0] === "buckets" && Array.isArray(arr[1])) {
701
+ const result = {
702
+ buckets: arr[1].map((bucket) => {
703
+ const bucketObj = {};
704
+ for (let i = 0;i < bucket.length; i += 2) {
705
+ const key = bucket[i];
706
+ const value = bucket[i + 1];
707
+ bucketObj[key] = Array.isArray(value) && value.length > 0 && typeof value[0] === "string" ? parseStatsValue(value) : value;
708
+ }
709
+ return bucketObj;
710
+ })
711
+ };
712
+ for (let i = 2;i < arr.length; i += 2) {
713
+ result[arr[i]] = arr[i + 1];
714
+ }
715
+ return result;
716
+ }
717
+ return arr;
718
+ }
719
+ function buildQueryCommand(redisCommand, name, options) {
720
+ const query = JSON.stringify(options?.filter ?? {});
721
+ const command = [redisCommand, name, query];
722
+ if (options?.limit !== undefined) {
723
+ command.push("LIMIT", options.limit.toString());
724
+ }
725
+ if (options?.offset !== undefined) {
726
+ command.push("OFFSET", options.offset.toString());
727
+ }
728
+ if (options?.select && Object.keys(options.select).length === 0) {
729
+ command.push("NOCONTENT");
730
+ }
731
+ if (options) {
732
+ if ("orderBy" in options && options.orderBy) {
733
+ command.push("ORDERBY");
734
+ for (const [field, direction] of Object.entries(options.orderBy)) {
735
+ command.push(field, direction);
736
+ }
737
+ } else if ("scoreFunc" in options && options.scoreFunc) {
738
+ command.push("SCOREFUNC", ...buildScoreFunc(options.scoreFunc));
739
+ }
740
+ }
741
+ if (options?.highlight) {
742
+ command.push("HIGHLIGHT", "FIELDS", options.highlight.fields.length.toString(), ...options.highlight.fields);
743
+ if (options.highlight.preTag && options.highlight.postTag) {
744
+ command.push("TAGS", options.highlight.preTag, options.highlight.postTag);
745
+ }
746
+ }
747
+ if (options?.select && Object.keys(options.select).length > 0) {
748
+ command.push("SELECT", Object.keys(options.select).length.toString(), ...Object.keys(options.select));
749
+ }
750
+ return command;
751
+ }
752
+ function buildScoreFunc(scoreBy) {
753
+ const result = [];
754
+ if (typeof scoreBy === "string") {
755
+ result.push("FIELDVALUE", scoreBy);
756
+ } else if ("fields" in scoreBy) {
757
+ if (scoreBy.combineMode) {
758
+ result.push("COMBINEMODE", scoreBy.combineMode.toUpperCase());
759
+ }
760
+ if (scoreBy.scoreMode) {
761
+ result.push("SCOREMODE", scoreBy.scoreMode.toUpperCase());
762
+ }
763
+ for (const field of scoreBy.fields) {
764
+ result.push(...buildScoreFuncField(field));
765
+ }
766
+ } else {
767
+ result.push(...buildScoreFuncField(scoreBy));
768
+ }
769
+ return result;
770
+ }
771
+ function buildScoreFuncField(field) {
772
+ const result = [];
773
+ if (typeof field === "string") {
774
+ result.push("FIELDVALUE", field);
775
+ } else {
776
+ if (field.scoreMode) {
777
+ result.push("SCOREMODE", field.scoreMode.toUpperCase());
778
+ }
779
+ result.push("FIELDVALUE", field.field);
780
+ if (field.modifier) {
781
+ result.push("MODIFIER", field.modifier.toUpperCase());
782
+ }
783
+ if (field.factor !== undefined) {
784
+ result.push("FACTOR", field.factor.toString());
785
+ }
786
+ if (field.missing !== undefined) {
787
+ result.push("MISSING", field.missing.toString());
788
+ }
789
+ }
790
+ return result;
791
+ }
792
+ function buildCreateIndexCommand(params) {
793
+ const { name, schema, dataType, prefix, language, skipInitialScan, existsOk } = params;
794
+ const prefixArray = Array.isArray(prefix) ? prefix : [prefix];
795
+ const payload = [
796
+ name,
797
+ ...skipInitialScan ? ["SKIPINITIALSCAN"] : [],
798
+ ...existsOk ? ["EXISTSOK"] : [],
799
+ "ON",
800
+ dataType.toUpperCase(),
801
+ "PREFIX",
802
+ prefixArray.length.toString(),
803
+ ...prefixArray,
804
+ ...language ? ["LANGUAGE", language] : [],
805
+ "SCHEMA"
806
+ ];
807
+ const fields = flattenSchema(schema);
808
+ for (const field of fields) {
809
+ payload.push(field.path, field.type);
810
+ if (field.fast) {
811
+ payload.push("FAST");
812
+ }
813
+ if (field.noTokenize) {
814
+ payload.push("NOTOKENIZE");
815
+ }
816
+ if (field.noStem) {
817
+ payload.push("NOSTEM");
818
+ }
819
+ if (field.from) {
820
+ payload.push("FROM", field.from);
821
+ }
822
+ }
823
+ return ["SEARCH.CREATE", ...payload];
824
+ }
825
+ function buildAggregateCommand(name, options) {
826
+ const query = JSON.stringify(options?.filter ?? {});
827
+ const aggregations = JSON.stringify(options.aggregations);
828
+ return ["SEARCH.AGGREGATE", name, query, aggregations];
829
+ }
830
+ var SearchIndex = class {
831
+ name;
832
+ schema;
833
+ client;
834
+ constructor({ name, schema, client }) {
835
+ this.name = name;
836
+ this.schema = schema;
837
+ this.client = client;
838
+ }
839
+ async waitIndexing() {
840
+ const command = ["SEARCH.WAITINDEXING", this.name];
841
+ return await new ExecCommand(command).exec(this.client);
842
+ }
843
+ async describe() {
844
+ const command = ["SEARCH.DESCRIBE", this.name];
845
+ const rawResult = await new ExecCommand(command).exec(this.client);
846
+ if (!rawResult)
847
+ return null;
848
+ return deserializeDescribeResponse(rawResult);
849
+ }
850
+ async query(options) {
851
+ const command = buildQueryCommand("SEARCH.QUERY", this.name, options);
852
+ const rawResult = await new ExecCommand(command).exec(this.client);
853
+ if (!rawResult)
854
+ return rawResult;
855
+ return deserializeQueryResponse(rawResult);
856
+ }
857
+ async aggregate(options) {
858
+ const command = buildAggregateCommand(this.name, options);
859
+ const rawResult = await new ExecCommand(command).exec(this.client);
860
+ return deserializeAggregateResponse(rawResult);
861
+ }
862
+ async count({ filter }) {
863
+ const command = buildQueryCommand("SEARCH.COUNT", this.name, { filter });
864
+ const rawResult = await new ExecCommand(command).exec(this.client);
865
+ return { count: parseCountResponse(rawResult) };
866
+ }
867
+ async drop() {
868
+ const command = ["SEARCH.DROP", this.name];
869
+ const result = await new ExecCommand(command).exec(this.client);
870
+ return result;
871
+ }
872
+ async addAlias({ alias }) {
873
+ const command = ["SEARCH.ALIASADD", alias, this.name];
874
+ const result = await new ExecCommand(command).exec(this.client);
875
+ return result;
876
+ }
877
+ };
878
+ async function createIndex(client, params) {
879
+ const { name, schema } = params;
880
+ const createIndexCommand = buildCreateIndexCommand(params);
881
+ await new ExecCommand(createIndexCommand).exec(client);
882
+ return initIndex(client, { name, schema });
883
+ }
884
+ function initIndex(client, params) {
885
+ const { name, schema } = params;
886
+ return new SearchIndex({ name, schema, client });
887
+ }
888
+ async function listAliases(client) {
889
+ const command = ["SEARCH.LISTALIASES"];
890
+ const rawResult = await new ExecCommand(command).exec(client);
891
+ if (rawResult === 0 || Array.isArray(rawResult) && rawResult.length === 0) {
892
+ return {};
893
+ }
894
+ if (!Array.isArray(rawResult)) {
895
+ return {};
896
+ }
897
+ const aliases = {};
898
+ for (const pair of rawResult) {
899
+ if (Array.isArray(pair) && pair.length === 2) {
900
+ const [alias, index] = pair;
901
+ aliases[alias] = index;
902
+ }
903
+ }
904
+ return aliases;
905
+ }
906
+ async function addAlias(client, { indexName, alias }) {
907
+ const command = ["SEARCH.ALIASADD", alias, indexName];
908
+ const result = await new ExecCommand(command).exec(client);
909
+ return result;
910
+ }
911
+ async function delAlias(client, { alias }) {
912
+ const command = ["SEARCH.ALIASDEL", alias];
913
+ const result = await new ExecCommand(command).exec(client);
914
+ return result;
915
+ }
916
+ function deserialize(result) {
917
+ if (result.length === 0) {
918
+ return null;
919
+ }
920
+ const obj = {};
921
+ for (let i = 0;i < result.length; i += 2) {
922
+ const key = result[i];
923
+ const value = result[i + 1];
924
+ try {
925
+ obj[key] = JSON.parse(value);
926
+ } catch {
927
+ obj[key] = value;
928
+ }
929
+ }
930
+ return obj;
931
+ }
932
+ var HRandFieldCommand = class extends Command {
933
+ constructor(cmd, opts) {
934
+ const command = ["hrandfield", cmd[0]];
935
+ if (typeof cmd[1] === "number") {
936
+ command.push(cmd[1]);
937
+ }
938
+ if (cmd[2]) {
939
+ command.push("WITHVALUES");
940
+ }
941
+ super(command, {
942
+ deserialize: cmd[2] ? (result) => deserialize(result) : opts?.deserialize,
943
+ ...opts
944
+ });
945
+ }
946
+ };
947
+ var AppendCommand = class extends Command {
948
+ constructor(cmd, opts) {
949
+ super(["append", ...cmd], opts);
950
+ }
951
+ };
952
+ var BitCountCommand = class extends Command {
953
+ constructor([key, start, end], opts) {
954
+ const command = ["bitcount", key];
955
+ if (typeof start === "number") {
956
+ command.push(start);
957
+ }
958
+ if (typeof end === "number") {
959
+ command.push(end);
960
+ }
961
+ super(command, opts);
962
+ }
963
+ };
964
+ var BitFieldCommand = class {
965
+ constructor(args, client, opts, execOperation = (command) => command.exec(this.client)) {
966
+ this.client = client;
967
+ this.opts = opts;
968
+ this.execOperation = execOperation;
969
+ this.command = ["bitfield", ...args];
970
+ }
971
+ command;
972
+ chain(...args) {
973
+ this.command.push(...args);
974
+ return this;
975
+ }
976
+ get(...args) {
977
+ return this.chain("get", ...args);
978
+ }
979
+ set(...args) {
980
+ return this.chain("set", ...args);
981
+ }
982
+ incrby(...args) {
983
+ return this.chain("incrby", ...args);
984
+ }
985
+ overflow(overflow) {
986
+ return this.chain("overflow", overflow);
987
+ }
988
+ exec() {
989
+ const command = new Command(this.command, this.opts);
990
+ return this.execOperation(command);
991
+ }
992
+ };
993
+ var BitOpCommand = class extends Command {
994
+ constructor(cmd, opts) {
995
+ super(["bitop", ...cmd], opts);
996
+ }
997
+ };
998
+ var BitPosCommand = class extends Command {
999
+ constructor(cmd, opts) {
1000
+ super(["bitpos", ...cmd], opts);
1001
+ }
1002
+ };
1003
+ var ClientSetInfoCommand = class extends Command {
1004
+ constructor([attribute, value], opts) {
1005
+ super(["CLIENT", "SETINFO", attribute.toUpperCase(), value], opts);
1006
+ }
1007
+ };
1008
+ var CopyCommand = class extends Command {
1009
+ constructor([key, destinationKey, opts], commandOptions) {
1010
+ super(["COPY", key, destinationKey, ...opts?.replace ? ["REPLACE"] : []], {
1011
+ ...commandOptions,
1012
+ deserialize(result) {
1013
+ if (result > 0) {
1014
+ return "COPIED";
1015
+ }
1016
+ return "NOT_COPIED";
1017
+ }
1018
+ });
1019
+ }
1020
+ };
1021
+ var DBSizeCommand = class extends Command {
1022
+ constructor(opts) {
1023
+ super(["dbsize"], opts);
1024
+ }
1025
+ };
1026
+ var DecrCommand = class extends Command {
1027
+ constructor(cmd, opts) {
1028
+ super(["decr", ...cmd], opts);
1029
+ }
1030
+ };
1031
+ var DecrByCommand = class extends Command {
1032
+ constructor(cmd, opts) {
1033
+ super(["decrby", ...cmd], opts);
1034
+ }
1035
+ };
1036
+ var DelCommand = class extends Command {
1037
+ constructor(cmd, opts) {
1038
+ super(["del", ...cmd], opts);
1039
+ }
1040
+ };
1041
+ var EchoCommand = class extends Command {
1042
+ constructor(cmd, opts) {
1043
+ super(["echo", ...cmd], opts);
1044
+ }
1045
+ };
1046
+ var EvalROCommand = class extends Command {
1047
+ constructor([script, keys, args], opts) {
1048
+ super(["eval_ro", script, keys.length, ...keys, ...args ?? []], opts);
1049
+ }
1050
+ };
1051
+ var EvalCommand = class extends Command {
1052
+ constructor([script, keys, args], opts) {
1053
+ super(["eval", script, keys.length, ...keys, ...args ?? []], opts);
1054
+ }
1055
+ };
1056
+ var EvalshaROCommand = class extends Command {
1057
+ constructor([sha, keys, args], opts) {
1058
+ super(["evalsha_ro", sha, keys.length, ...keys, ...args ?? []], opts);
1059
+ }
1060
+ };
1061
+ var EvalshaCommand = class extends Command {
1062
+ constructor([sha, keys, args], opts) {
1063
+ super(["evalsha", sha, keys.length, ...keys, ...args ?? []], opts);
1064
+ }
1065
+ };
1066
+ var ExistsCommand = class extends Command {
1067
+ constructor(cmd, opts) {
1068
+ super(["exists", ...cmd], opts);
1069
+ }
1070
+ };
1071
+ var ExpireCommand = class extends Command {
1072
+ constructor(cmd, opts) {
1073
+ super(["expire", ...cmd.filter(Boolean)], opts);
1074
+ }
1075
+ };
1076
+ var ExpireAtCommand = class extends Command {
1077
+ constructor(cmd, opts) {
1078
+ super(["expireat", ...cmd], opts);
1079
+ }
1080
+ };
1081
+ var FCallCommand = class extends Command {
1082
+ constructor([functionName, keys, args], opts) {
1083
+ super(["fcall", functionName, ...keys ? [keys.length, ...keys] : [0], ...args ?? []], opts);
1084
+ }
1085
+ };
1086
+ var FCallRoCommand = class extends Command {
1087
+ constructor([functionName, keys, args], opts) {
1088
+ super(["fcall_ro", functionName, ...keys ? [keys.length, ...keys] : [0], ...args ?? []], opts);
1089
+ }
1090
+ };
1091
+ var FlushAllCommand = class extends Command {
1092
+ constructor(args, opts) {
1093
+ const command = ["flushall"];
1094
+ if (args && args.length > 0 && args[0].async) {
1095
+ command.push("async");
1096
+ }
1097
+ super(command, opts);
1098
+ }
1099
+ };
1100
+ var FlushDBCommand = class extends Command {
1101
+ constructor([opts], cmdOpts) {
1102
+ const command = ["flushdb"];
1103
+ if (opts?.async) {
1104
+ command.push("async");
1105
+ }
1106
+ super(command, cmdOpts);
1107
+ }
1108
+ };
1109
+ var FunctionDeleteCommand = class extends Command {
1110
+ constructor([libraryName], opts) {
1111
+ super(["function", "delete", libraryName], opts);
1112
+ }
1113
+ };
1114
+ var FunctionFlushCommand = class extends Command {
1115
+ constructor(opts) {
1116
+ super(["function", "flush"], opts);
1117
+ }
1118
+ };
1119
+ var FunctionListCommand = class extends Command {
1120
+ constructor([args], opts) {
1121
+ const command = ["function", "list"];
1122
+ if (args?.libraryName) {
1123
+ command.push("libraryname", args.libraryName);
1124
+ }
1125
+ if (args?.withCode) {
1126
+ command.push("withcode");
1127
+ }
1128
+ super(command, { deserialize: deserialize2, ...opts });
1129
+ }
1130
+ };
1131
+ function deserialize2(result) {
1132
+ if (!Array.isArray(result))
1133
+ return [];
1134
+ return result.map((libRaw) => {
1135
+ const lib = kvArrayToObject(libRaw);
1136
+ const functionsParsed = lib.functions.map((fnRaw) => kvArrayToObject(fnRaw));
1137
+ return {
1138
+ libraryName: lib.library_name,
1139
+ engine: lib.engine,
1140
+ functions: functionsParsed.map((fn) => ({
1141
+ name: fn.name,
1142
+ description: fn.description ?? undefined,
1143
+ flags: fn.flags
1144
+ })),
1145
+ libraryCode: lib.library_code
1146
+ };
1147
+ });
1148
+ }
1149
+ var FunctionLoadCommand = class extends Command {
1150
+ constructor([args], opts) {
1151
+ super(["function", "load", ...args.replace ? ["replace"] : [], args.code], opts);
1152
+ }
1153
+ };
1154
+ var FunctionStatsCommand = class extends Command {
1155
+ constructor(opts) {
1156
+ super(["function", "stats"], { deserialize: deserialize3, ...opts });
1157
+ }
1158
+ };
1159
+ function deserialize3(result) {
1160
+ const rawEngines = kvArrayToObject(kvArrayToObject(result).engines);
1161
+ const parsedEngines = Object.fromEntries(Object.entries(rawEngines).map(([key, value]) => [key, kvArrayToObject(value)]));
1162
+ const final = {
1163
+ engines: Object.fromEntries(Object.entries(parsedEngines).map(([key, value]) => [
1164
+ key,
1165
+ {
1166
+ librariesCount: value.libraries_count,
1167
+ functionsCount: value.functions_count
1168
+ }
1169
+ ]))
1170
+ };
1171
+ return final;
1172
+ }
1173
+ var GeoAddCommand = class extends Command {
1174
+ constructor([key, arg1, ...arg2], opts) {
1175
+ const command = ["geoadd", key];
1176
+ if ("nx" in arg1 && arg1.nx) {
1177
+ command.push("nx");
1178
+ } else if ("xx" in arg1 && arg1.xx) {
1179
+ command.push("xx");
1180
+ }
1181
+ if ("ch" in arg1 && arg1.ch) {
1182
+ command.push("ch");
1183
+ }
1184
+ if ("latitude" in arg1 && arg1.latitude) {
1185
+ command.push(arg1.longitude, arg1.latitude, arg1.member);
1186
+ }
1187
+ command.push(...arg2.flatMap(({ latitude, longitude, member }) => [longitude, latitude, member]));
1188
+ super(command, opts);
1189
+ }
1190
+ };
1191
+ var GeoDistCommand = class extends Command {
1192
+ constructor([key, member1, member2, unit = "M"], opts) {
1193
+ super(["GEODIST", key, member1, member2, unit], opts);
1194
+ }
1195
+ };
1196
+ var GeoHashCommand = class extends Command {
1197
+ constructor(cmd, opts) {
1198
+ const [key] = cmd;
1199
+ const members = Array.isArray(cmd[1]) ? cmd[1] : cmd.slice(1);
1200
+ super(["GEOHASH", key, ...members], opts);
1201
+ }
1202
+ };
1203
+ var GeoPosCommand = class extends Command {
1204
+ constructor(cmd, opts) {
1205
+ const [key] = cmd;
1206
+ const members = Array.isArray(cmd[1]) ? cmd[1] : cmd.slice(1);
1207
+ super(["GEOPOS", key, ...members], {
1208
+ deserialize: (result) => transform(result),
1209
+ ...opts
1210
+ });
1211
+ }
1212
+ };
1213
+ function transform(result) {
1214
+ const final = [];
1215
+ for (const pos of result) {
1216
+ if (!pos?.[0] || !pos?.[1]) {
1217
+ continue;
1218
+ }
1219
+ final.push({ lng: Number.parseFloat(pos[0]), lat: Number.parseFloat(pos[1]) });
1220
+ }
1221
+ return final;
1222
+ }
1223
+ var GeoSearchCommand = class extends Command {
1224
+ constructor([key, centerPoint, shape, order, opts], commandOptions) {
1225
+ const command = ["GEOSEARCH", key];
1226
+ if (centerPoint.type === "FROMMEMBER" || centerPoint.type === "frommember") {
1227
+ command.push(centerPoint.type, centerPoint.member);
1228
+ }
1229
+ if (centerPoint.type === "FROMLONLAT" || centerPoint.type === "fromlonlat") {
1230
+ command.push(centerPoint.type, centerPoint.coordinate.lon, centerPoint.coordinate.lat);
1231
+ }
1232
+ if (shape.type === "BYRADIUS" || shape.type === "byradius") {
1233
+ command.push(shape.type, shape.radius, shape.radiusType);
1234
+ }
1235
+ if (shape.type === "BYBOX" || shape.type === "bybox") {
1236
+ command.push(shape.type, shape.rect.width, shape.rect.height, shape.rectType);
1237
+ }
1238
+ command.push(order);
1239
+ if (opts?.count) {
1240
+ command.push("COUNT", opts.count.limit, ...opts.count.any ? ["ANY"] : []);
1241
+ }
1242
+ const transform2 = (result) => {
1243
+ if (!opts?.withCoord && !opts?.withDist && !opts?.withHash) {
1244
+ return result.map((member) => {
1245
+ try {
1246
+ return { member: JSON.parse(member) };
1247
+ } catch {
1248
+ return { member };
1249
+ }
1250
+ });
1251
+ }
1252
+ return result.map((members) => {
1253
+ let counter = 1;
1254
+ const obj = {};
1255
+ try {
1256
+ obj.member = JSON.parse(members[0]);
1257
+ } catch {
1258
+ obj.member = members[0];
1259
+ }
1260
+ if (opts.withDist) {
1261
+ obj.dist = Number.parseFloat(members[counter++]);
1262
+ }
1263
+ if (opts.withHash) {
1264
+ obj.hash = members[counter++].toString();
1265
+ }
1266
+ if (opts.withCoord) {
1267
+ obj.coord = {
1268
+ long: Number.parseFloat(members[counter][0]),
1269
+ lat: Number.parseFloat(members[counter][1])
1270
+ };
1271
+ }
1272
+ return obj;
1273
+ });
1274
+ };
1275
+ super([
1276
+ ...command,
1277
+ ...opts?.withCoord ? ["WITHCOORD"] : [],
1278
+ ...opts?.withDist ? ["WITHDIST"] : [],
1279
+ ...opts?.withHash ? ["WITHHASH"] : []
1280
+ ], {
1281
+ deserialize: transform2,
1282
+ ...commandOptions
1283
+ });
1284
+ }
1285
+ };
1286
+ var GeoSearchStoreCommand = class extends Command {
1287
+ constructor([destination, key, centerPoint, shape, order, opts], commandOptions) {
1288
+ const command = ["GEOSEARCHSTORE", destination, key];
1289
+ if (centerPoint.type === "FROMMEMBER" || centerPoint.type === "frommember") {
1290
+ command.push(centerPoint.type, centerPoint.member);
1291
+ }
1292
+ if (centerPoint.type === "FROMLONLAT" || centerPoint.type === "fromlonlat") {
1293
+ command.push(centerPoint.type, centerPoint.coordinate.lon, centerPoint.coordinate.lat);
1294
+ }
1295
+ if (shape.type === "BYRADIUS" || shape.type === "byradius") {
1296
+ command.push(shape.type, shape.radius, shape.radiusType);
1297
+ }
1298
+ if (shape.type === "BYBOX" || shape.type === "bybox") {
1299
+ command.push(shape.type, shape.rect.width, shape.rect.height, shape.rectType);
1300
+ }
1301
+ command.push(order);
1302
+ if (opts?.count) {
1303
+ command.push("COUNT", opts.count.limit, ...opts.count.any ? ["ANY"] : []);
1304
+ }
1305
+ super([...command, ...opts?.storeDist ? ["STOREDIST"] : []], commandOptions);
1306
+ }
1307
+ };
1308
+ var GetCommand = class extends Command {
1309
+ constructor(cmd, opts) {
1310
+ super(["get", ...cmd], opts);
1311
+ }
1312
+ };
1313
+ var GetBitCommand = class extends Command {
1314
+ constructor(cmd, opts) {
1315
+ super(["getbit", ...cmd], opts);
1316
+ }
1317
+ };
1318
+ var GetDelCommand = class extends Command {
1319
+ constructor(cmd, opts) {
1320
+ super(["getdel", ...cmd], opts);
1321
+ }
1322
+ };
1323
+ var GetExCommand = class extends Command {
1324
+ constructor([key, opts], cmdOpts) {
1325
+ const command = ["getex", key];
1326
+ if (opts) {
1327
+ if ("ex" in opts && typeof opts.ex === "number") {
1328
+ command.push("ex", opts.ex);
1329
+ } else if ("px" in opts && typeof opts.px === "number") {
1330
+ command.push("px", opts.px);
1331
+ } else if ("exat" in opts && typeof opts.exat === "number") {
1332
+ command.push("exat", opts.exat);
1333
+ } else if ("pxat" in opts && typeof opts.pxat === "number") {
1334
+ command.push("pxat", opts.pxat);
1335
+ } else if ("persist" in opts && opts.persist) {
1336
+ command.push("persist");
1337
+ }
1338
+ }
1339
+ super(command, cmdOpts);
1340
+ }
1341
+ };
1342
+ var GetRangeCommand = class extends Command {
1343
+ constructor(cmd, opts) {
1344
+ super(["getrange", ...cmd], opts);
1345
+ }
1346
+ };
1347
+ var GetSetCommand = class extends Command {
1348
+ constructor(cmd, opts) {
1349
+ super(["getset", ...cmd], opts);
1350
+ }
1351
+ };
1352
+ var HDelCommand = class extends Command {
1353
+ constructor(cmd, opts) {
1354
+ super(["hdel", ...cmd], opts);
1355
+ }
1356
+ };
1357
+ var HExistsCommand = class extends Command {
1358
+ constructor(cmd, opts) {
1359
+ super(["hexists", ...cmd], opts);
1360
+ }
1361
+ };
1362
+ var HExpireCommand = class extends Command {
1363
+ constructor(cmd, opts) {
1364
+ const [key, fields, seconds, option] = cmd;
1365
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1366
+ super([
1367
+ "hexpire",
1368
+ key,
1369
+ seconds,
1370
+ ...option ? [option] : [],
1371
+ "FIELDS",
1372
+ fieldArray.length,
1373
+ ...fieldArray
1374
+ ], opts);
1375
+ }
1376
+ };
1377
+ var HExpireAtCommand = class extends Command {
1378
+ constructor(cmd, opts) {
1379
+ const [key, fields, timestamp, option] = cmd;
1380
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1381
+ super([
1382
+ "hexpireat",
1383
+ key,
1384
+ timestamp,
1385
+ ...option ? [option] : [],
1386
+ "FIELDS",
1387
+ fieldArray.length,
1388
+ ...fieldArray
1389
+ ], opts);
1390
+ }
1391
+ };
1392
+ var HExpireTimeCommand = class extends Command {
1393
+ constructor(cmd, opts) {
1394
+ const [key, fields] = cmd;
1395
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1396
+ super(["hexpiretime", key, "FIELDS", fieldArray.length, ...fieldArray], opts);
1397
+ }
1398
+ };
1399
+ var HPersistCommand = class extends Command {
1400
+ constructor(cmd, opts) {
1401
+ const [key, fields] = cmd;
1402
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1403
+ super(["hpersist", key, "FIELDS", fieldArray.length, ...fieldArray], opts);
1404
+ }
1405
+ };
1406
+ var HPExpireCommand = class extends Command {
1407
+ constructor(cmd, opts) {
1408
+ const [key, fields, milliseconds, option] = cmd;
1409
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1410
+ super([
1411
+ "hpexpire",
1412
+ key,
1413
+ milliseconds,
1414
+ ...option ? [option] : [],
1415
+ "FIELDS",
1416
+ fieldArray.length,
1417
+ ...fieldArray
1418
+ ], opts);
1419
+ }
1420
+ };
1421
+ var HPExpireAtCommand = class extends Command {
1422
+ constructor(cmd, opts) {
1423
+ const [key, fields, timestamp, option] = cmd;
1424
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1425
+ super([
1426
+ "hpexpireat",
1427
+ key,
1428
+ timestamp,
1429
+ ...option ? [option] : [],
1430
+ "FIELDS",
1431
+ fieldArray.length,
1432
+ ...fieldArray
1433
+ ], opts);
1434
+ }
1435
+ };
1436
+ var HPExpireTimeCommand = class extends Command {
1437
+ constructor(cmd, opts) {
1438
+ const [key, fields] = cmd;
1439
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1440
+ super(["hpexpiretime", key, "FIELDS", fieldArray.length, ...fieldArray], opts);
1441
+ }
1442
+ };
1443
+ var HPTtlCommand = class extends Command {
1444
+ constructor(cmd, opts) {
1445
+ const [key, fields] = cmd;
1446
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1447
+ super(["hpttl", key, "FIELDS", fieldArray.length, ...fieldArray], opts);
1448
+ }
1449
+ };
1450
+ var HGetCommand = class extends Command {
1451
+ constructor(cmd, opts) {
1452
+ super(["hget", ...cmd], opts);
1453
+ }
1454
+ };
1455
+ function deserialize4(result) {
1456
+ if (result.length === 0) {
1457
+ return null;
1458
+ }
1459
+ const obj = {};
1460
+ for (let i = 0;i < result.length; i += 2) {
1461
+ const key = result[i];
1462
+ const value = result[i + 1];
1463
+ try {
1464
+ const valueIsNumberAndNotSafeInteger = !Number.isNaN(Number(value)) && !Number.isSafeInteger(Number(value));
1465
+ obj[key] = valueIsNumberAndNotSafeInteger ? value : JSON.parse(value);
1466
+ } catch {
1467
+ obj[key] = value;
1468
+ }
1469
+ }
1470
+ return obj;
1471
+ }
1472
+ var HGetAllCommand = class extends Command {
1473
+ constructor(cmd, opts) {
1474
+ super(["hgetall", ...cmd], {
1475
+ deserialize: (result) => deserialize4(result),
1476
+ ...opts
1477
+ });
1478
+ }
1479
+ };
1480
+ function deserialize5(fields, result) {
1481
+ if (result.every((field) => field === null)) {
1482
+ return null;
1483
+ }
1484
+ const obj = {};
1485
+ for (const [i, field] of fields.entries()) {
1486
+ try {
1487
+ obj[field] = JSON.parse(result[i]);
1488
+ } catch {
1489
+ obj[field] = result[i];
1490
+ }
1491
+ }
1492
+ return obj;
1493
+ }
1494
+ var HMGetCommand = class extends Command {
1495
+ constructor([key, ...fields], opts) {
1496
+ super(["hmget", key, ...fields], {
1497
+ deserialize: (result) => deserialize5(fields, result),
1498
+ ...opts
1499
+ });
1500
+ }
1501
+ };
1502
+ var HGetDelCommand = class extends Command {
1503
+ constructor([key, ...fields], opts) {
1504
+ super(["hgetdel", key, "FIELDS", fields.length, ...fields], {
1505
+ deserialize: (result) => deserialize5(fields.map(String), result),
1506
+ ...opts
1507
+ });
1508
+ }
1509
+ };
1510
+ var HGetExCommand = class extends Command {
1511
+ constructor([key, opts, ...fields], cmdOpts) {
1512
+ const command = ["hgetex", key];
1513
+ if ("ex" in opts && typeof opts.ex === "number") {
1514
+ command.push("EX", opts.ex);
1515
+ } else if ("px" in opts && typeof opts.px === "number") {
1516
+ command.push("PX", opts.px);
1517
+ } else if ("exat" in opts && typeof opts.exat === "number") {
1518
+ command.push("EXAT", opts.exat);
1519
+ } else if ("pxat" in opts && typeof opts.pxat === "number") {
1520
+ command.push("PXAT", opts.pxat);
1521
+ } else if ("persist" in opts && opts.persist) {
1522
+ command.push("PERSIST");
1523
+ }
1524
+ command.push("FIELDS", fields.length, ...fields);
1525
+ super(command, {
1526
+ deserialize: (result) => deserialize5(fields.map(String), result),
1527
+ ...cmdOpts
1528
+ });
1529
+ }
1530
+ };
1531
+ var HIncrByCommand = class extends Command {
1532
+ constructor(cmd, opts) {
1533
+ super(["hincrby", ...cmd], opts);
1534
+ }
1535
+ };
1536
+ var HIncrByFloatCommand = class extends Command {
1537
+ constructor(cmd, opts) {
1538
+ super(["hincrbyfloat", ...cmd], opts);
1539
+ }
1540
+ };
1541
+ var HKeysCommand = class extends Command {
1542
+ constructor([key], opts) {
1543
+ super(["hkeys", key], opts);
1544
+ }
1545
+ };
1546
+ var HLenCommand = class extends Command {
1547
+ constructor(cmd, opts) {
1548
+ super(["hlen", ...cmd], opts);
1549
+ }
1550
+ };
1551
+ var HMSetCommand = class extends Command {
1552
+ constructor([key, kv], opts) {
1553
+ super(["hmset", key, ...Object.entries(kv).flatMap(([field, value]) => [field, value])], opts);
1554
+ }
1555
+ };
1556
+ var HScanCommand = class extends Command {
1557
+ constructor([key, cursor, cmdOpts], opts) {
1558
+ const command = ["hscan", key, cursor];
1559
+ if (cmdOpts?.match) {
1560
+ command.push("match", cmdOpts.match);
1561
+ }
1562
+ if (typeof cmdOpts?.count === "number") {
1563
+ command.push("count", cmdOpts.count);
1564
+ }
1565
+ super(command, {
1566
+ deserialize: deserializeScanResponse,
1567
+ ...opts
1568
+ });
1569
+ }
1570
+ };
1571
+ var HSetCommand = class extends Command {
1572
+ constructor([key, kv], opts) {
1573
+ super(["hset", key, ...Object.entries(kv).flatMap(([field, value]) => [field, value])], opts);
1574
+ }
1575
+ };
1576
+ var HSetExCommand = class extends Command {
1577
+ constructor([key, opts, kv], cmdOpts) {
1578
+ const command = ["hsetex", key];
1579
+ if (opts.conditional) {
1580
+ command.push(opts.conditional.toUpperCase());
1581
+ }
1582
+ if (opts.expiration) {
1583
+ if ("ex" in opts.expiration && typeof opts.expiration.ex === "number") {
1584
+ command.push("EX", opts.expiration.ex);
1585
+ } else if ("px" in opts.expiration && typeof opts.expiration.px === "number") {
1586
+ command.push("PX", opts.expiration.px);
1587
+ } else if ("exat" in opts.expiration && typeof opts.expiration.exat === "number") {
1588
+ command.push("EXAT", opts.expiration.exat);
1589
+ } else if ("pxat" in opts.expiration && typeof opts.expiration.pxat === "number") {
1590
+ command.push("PXAT", opts.expiration.pxat);
1591
+ } else if ("keepttl" in opts.expiration && opts.expiration.keepttl) {
1592
+ command.push("KEEPTTL");
1593
+ }
1594
+ }
1595
+ const entries = Object.entries(kv);
1596
+ command.push("FIELDS", entries.length);
1597
+ for (const [field, value] of entries) {
1598
+ command.push(field, value);
1599
+ }
1600
+ super(command, cmdOpts);
1601
+ }
1602
+ };
1603
+ var HSetNXCommand = class extends Command {
1604
+ constructor(cmd, opts) {
1605
+ super(["hsetnx", ...cmd], opts);
1606
+ }
1607
+ };
1608
+ var HStrLenCommand = class extends Command {
1609
+ constructor(cmd, opts) {
1610
+ super(["hstrlen", ...cmd], opts);
1611
+ }
1612
+ };
1613
+ var HTtlCommand = class extends Command {
1614
+ constructor(cmd, opts) {
1615
+ const [key, fields] = cmd;
1616
+ const fieldArray = Array.isArray(fields) ? fields : [fields];
1617
+ super(["httl", key, "FIELDS", fieldArray.length, ...fieldArray], opts);
1618
+ }
1619
+ };
1620
+ var HValsCommand = class extends Command {
1621
+ constructor(cmd, opts) {
1622
+ super(["hvals", ...cmd], opts);
1623
+ }
1624
+ };
1625
+ var IncrCommand = class extends Command {
1626
+ constructor(cmd, opts) {
1627
+ super(["incr", ...cmd], opts);
1628
+ }
1629
+ };
1630
+ var IncrByCommand = class extends Command {
1631
+ constructor(cmd, opts) {
1632
+ super(["incrby", ...cmd], opts);
1633
+ }
1634
+ };
1635
+ var IncrByFloatCommand = class extends Command {
1636
+ constructor(cmd, opts) {
1637
+ super(["incrbyfloat", ...cmd], opts);
1638
+ }
1639
+ };
1640
+ var JsonArrAppendCommand = class extends Command {
1641
+ constructor(cmd, opts) {
1642
+ super(["JSON.ARRAPPEND", ...cmd], opts);
1643
+ }
1644
+ };
1645
+ var JsonArrIndexCommand = class extends Command {
1646
+ constructor(cmd, opts) {
1647
+ super(["JSON.ARRINDEX", ...cmd], opts);
1648
+ }
1649
+ };
1650
+ var JsonArrInsertCommand = class extends Command {
1651
+ constructor(cmd, opts) {
1652
+ super(["JSON.ARRINSERT", ...cmd], opts);
1653
+ }
1654
+ };
1655
+ var JsonArrLenCommand = class extends Command {
1656
+ constructor(cmd, opts) {
1657
+ super(["JSON.ARRLEN", cmd[0], cmd[1] ?? "$"], opts);
1658
+ }
1659
+ };
1660
+ var JsonArrPopCommand = class extends Command {
1661
+ constructor(cmd, opts) {
1662
+ super(["JSON.ARRPOP", ...cmd], opts);
1663
+ }
1664
+ };
1665
+ var JsonArrTrimCommand = class extends Command {
1666
+ constructor(cmd, opts) {
1667
+ const path = cmd[1] ?? "$";
1668
+ const start = cmd[2] ?? 0;
1669
+ const stop = cmd[3] ?? 0;
1670
+ super(["JSON.ARRTRIM", cmd[0], path, start, stop], opts);
1671
+ }
1672
+ };
1673
+ var JsonClearCommand = class extends Command {
1674
+ constructor(cmd, opts) {
1675
+ super(["JSON.CLEAR", ...cmd], opts);
1676
+ }
1677
+ };
1678
+ var JsonDelCommand = class extends Command {
1679
+ constructor(cmd, opts) {
1680
+ super(["JSON.DEL", ...cmd], opts);
1681
+ }
1682
+ };
1683
+ var JsonForgetCommand = class extends Command {
1684
+ constructor(cmd, opts) {
1685
+ super(["JSON.FORGET", ...cmd], opts);
1686
+ }
1687
+ };
1688
+ var JsonGetCommand = class extends Command {
1689
+ constructor(cmd, opts) {
1690
+ const command = ["JSON.GET"];
1691
+ if (typeof cmd[1] === "string") {
1692
+ command.push(...cmd);
1693
+ } else {
1694
+ command.push(cmd[0]);
1695
+ if (cmd[1]) {
1696
+ if (cmd[1].indent) {
1697
+ command.push("INDENT", cmd[1].indent);
1698
+ }
1699
+ if (cmd[1].newline) {
1700
+ command.push("NEWLINE", cmd[1].newline);
1701
+ }
1702
+ if (cmd[1].space) {
1703
+ command.push("SPACE", cmd[1].space);
1704
+ }
1705
+ }
1706
+ command.push(...cmd.slice(2));
1707
+ }
1708
+ super(command, opts);
1709
+ }
1710
+ };
1711
+ var JsonMergeCommand = class extends Command {
1712
+ constructor(cmd, opts) {
1713
+ const command = ["JSON.MERGE", ...cmd];
1714
+ super(command, opts);
1715
+ }
1716
+ };
1717
+ var JsonMGetCommand = class extends Command {
1718
+ constructor(cmd, opts) {
1719
+ super(["JSON.MGET", ...cmd[0], cmd[1]], opts);
1720
+ }
1721
+ };
1722
+ var JsonMSetCommand = class extends Command {
1723
+ constructor(cmd, opts) {
1724
+ const command = ["JSON.MSET"];
1725
+ for (const c of cmd) {
1726
+ command.push(c.key, c.path, c.value);
1727
+ }
1728
+ super(command, opts);
1729
+ }
1730
+ };
1731
+ var JsonNumIncrByCommand = class extends Command {
1732
+ constructor(cmd, opts) {
1733
+ super(["JSON.NUMINCRBY", ...cmd], opts);
1734
+ }
1735
+ };
1736
+ var JsonNumMultByCommand = class extends Command {
1737
+ constructor(cmd, opts) {
1738
+ super(["JSON.NUMMULTBY", ...cmd], opts);
1739
+ }
1740
+ };
1741
+ var JsonObjKeysCommand = class extends Command {
1742
+ constructor(cmd, opts) {
1743
+ super(["JSON.OBJKEYS", ...cmd], opts);
1744
+ }
1745
+ };
1746
+ var JsonObjLenCommand = class extends Command {
1747
+ constructor(cmd, opts) {
1748
+ super(["JSON.OBJLEN", ...cmd], opts);
1749
+ }
1750
+ };
1751
+ var JsonRespCommand = class extends Command {
1752
+ constructor(cmd, opts) {
1753
+ super(["JSON.RESP", ...cmd], opts);
1754
+ }
1755
+ };
1756
+ var JsonSetCommand = class extends Command {
1757
+ constructor(cmd, opts) {
1758
+ const command = ["JSON.SET", cmd[0], cmd[1], cmd[2]];
1759
+ if (cmd[3]) {
1760
+ if (cmd[3].nx) {
1761
+ command.push("NX");
1762
+ } else if (cmd[3].xx) {
1763
+ command.push("XX");
1764
+ }
1765
+ }
1766
+ super(command, opts);
1767
+ }
1768
+ };
1769
+ var JsonStrAppendCommand = class extends Command {
1770
+ constructor(cmd, opts) {
1771
+ super(["JSON.STRAPPEND", ...cmd], opts);
1772
+ }
1773
+ };
1774
+ var JsonStrLenCommand = class extends Command {
1775
+ constructor(cmd, opts) {
1776
+ super(["JSON.STRLEN", ...cmd], opts);
1777
+ }
1778
+ };
1779
+ var JsonToggleCommand = class extends Command {
1780
+ constructor(cmd, opts) {
1781
+ super(["JSON.TOGGLE", ...cmd], opts);
1782
+ }
1783
+ };
1784
+ var JsonTypeCommand = class extends Command {
1785
+ constructor(cmd, opts) {
1786
+ super(["JSON.TYPE", ...cmd], opts);
1787
+ }
1788
+ };
1789
+ var KeysCommand = class extends Command {
1790
+ constructor(cmd, opts) {
1791
+ super(["keys", ...cmd], opts);
1792
+ }
1793
+ };
1794
+ var LIndexCommand = class extends Command {
1795
+ constructor(cmd, opts) {
1796
+ super(["lindex", ...cmd], opts);
1797
+ }
1798
+ };
1799
+ var LInsertCommand = class extends Command {
1800
+ constructor(cmd, opts) {
1801
+ super(["linsert", ...cmd], opts);
1802
+ }
1803
+ };
1804
+ var LLenCommand = class extends Command {
1805
+ constructor(cmd, opts) {
1806
+ super(["llen", ...cmd], opts);
1807
+ }
1808
+ };
1809
+ var LMoveCommand = class extends Command {
1810
+ constructor(cmd, opts) {
1811
+ super(["lmove", ...cmd], opts);
1812
+ }
1813
+ };
1814
+ var LmPopCommand = class extends Command {
1815
+ constructor(cmd, opts) {
1816
+ const [numkeys, keys, direction, count] = cmd;
1817
+ super(["LMPOP", numkeys, ...keys, direction, ...count ? ["COUNT", count] : []], opts);
1818
+ }
1819
+ };
1820
+ var LPopCommand = class extends Command {
1821
+ constructor(cmd, opts) {
1822
+ super(["lpop", ...cmd], opts);
1823
+ }
1824
+ };
1825
+ var LPosCommand = class extends Command {
1826
+ constructor(cmd, opts) {
1827
+ const args = ["lpos", cmd[0], cmd[1]];
1828
+ if (typeof cmd[2]?.rank === "number") {
1829
+ args.push("rank", cmd[2].rank);
1830
+ }
1831
+ if (typeof cmd[2]?.count === "number") {
1832
+ args.push("count", cmd[2].count);
1833
+ }
1834
+ if (typeof cmd[2]?.maxLen === "number") {
1835
+ args.push("maxLen", cmd[2].maxLen);
1836
+ }
1837
+ super(args, opts);
1838
+ }
1839
+ };
1840
+ var LPushCommand = class extends Command {
1841
+ constructor(cmd, opts) {
1842
+ super(["lpush", ...cmd], opts);
1843
+ }
1844
+ };
1845
+ var LPushXCommand = class extends Command {
1846
+ constructor(cmd, opts) {
1847
+ super(["lpushx", ...cmd], opts);
1848
+ }
1849
+ };
1850
+ var LRangeCommand = class extends Command {
1851
+ constructor(cmd, opts) {
1852
+ super(["lrange", ...cmd], opts);
1853
+ }
1854
+ };
1855
+ var LRemCommand = class extends Command {
1856
+ constructor(cmd, opts) {
1857
+ super(["lrem", ...cmd], opts);
1858
+ }
1859
+ };
1860
+ var LSetCommand = class extends Command {
1861
+ constructor(cmd, opts) {
1862
+ super(["lset", ...cmd], opts);
1863
+ }
1864
+ };
1865
+ var LTrimCommand = class extends Command {
1866
+ constructor(cmd, opts) {
1867
+ super(["ltrim", ...cmd], opts);
1868
+ }
1869
+ };
1870
+ var MGetCommand = class extends Command {
1871
+ constructor(cmd, opts) {
1872
+ const keys = Array.isArray(cmd[0]) ? cmd[0] : cmd;
1873
+ super(["mget", ...keys], opts);
1874
+ }
1875
+ };
1876
+ var MSetCommand = class extends Command {
1877
+ constructor([kv], opts) {
1878
+ super(["mset", ...Object.entries(kv).flatMap(([key, value]) => [key, value])], opts);
1879
+ }
1880
+ };
1881
+ var MSetNXCommand = class extends Command {
1882
+ constructor([kv], opts) {
1883
+ super(["msetnx", ...Object.entries(kv).flat()], opts);
1884
+ }
1885
+ };
1886
+ var PersistCommand = class extends Command {
1887
+ constructor(cmd, opts) {
1888
+ super(["persist", ...cmd], opts);
1889
+ }
1890
+ };
1891
+ var PExpireCommand = class extends Command {
1892
+ constructor(cmd, opts) {
1893
+ super(["pexpire", ...cmd], opts);
1894
+ }
1895
+ };
1896
+ var PExpireAtCommand = class extends Command {
1897
+ constructor(cmd, opts) {
1898
+ super(["pexpireat", ...cmd], opts);
1899
+ }
1900
+ };
1901
+ var PfAddCommand = class extends Command {
1902
+ constructor(cmd, opts) {
1903
+ super(["pfadd", ...cmd], opts);
1904
+ }
1905
+ };
1906
+ var PfCountCommand = class extends Command {
1907
+ constructor(cmd, opts) {
1908
+ super(["pfcount", ...cmd], opts);
1909
+ }
1910
+ };
1911
+ var PfMergeCommand = class extends Command {
1912
+ constructor(cmd, opts) {
1913
+ super(["pfmerge", ...cmd], opts);
1914
+ }
1915
+ };
1916
+ var PingCommand = class extends Command {
1917
+ constructor(cmd, opts) {
1918
+ const command = ["ping"];
1919
+ if (cmd?.[0] !== undefined) {
1920
+ command.push(cmd[0]);
1921
+ }
1922
+ super(command, opts);
1923
+ }
1924
+ };
1925
+ var PSetEXCommand = class extends Command {
1926
+ constructor(cmd, opts) {
1927
+ super(["psetex", ...cmd], opts);
1928
+ }
1929
+ };
1930
+ var PTtlCommand = class extends Command {
1931
+ constructor(cmd, opts) {
1932
+ super(["pttl", ...cmd], opts);
1933
+ }
1934
+ };
1935
+ var PublishCommand = class extends Command {
1936
+ constructor(cmd, opts) {
1937
+ super(["publish", ...cmd], opts);
1938
+ }
1939
+ };
1940
+ var RandomKeyCommand = class extends Command {
1941
+ constructor(opts) {
1942
+ super(["randomkey"], opts);
1943
+ }
1944
+ };
1945
+ var RenameCommand = class extends Command {
1946
+ constructor(cmd, opts) {
1947
+ super(["rename", ...cmd], opts);
1948
+ }
1949
+ };
1950
+ var RenameNXCommand = class extends Command {
1951
+ constructor(cmd, opts) {
1952
+ super(["renamenx", ...cmd], opts);
1953
+ }
1954
+ };
1955
+ var RPopCommand = class extends Command {
1956
+ constructor(cmd, opts) {
1957
+ super(["rpop", ...cmd], opts);
1958
+ }
1959
+ };
1960
+ var RPushCommand = class extends Command {
1961
+ constructor(cmd, opts) {
1962
+ super(["rpush", ...cmd], opts);
1963
+ }
1964
+ };
1965
+ var RPushXCommand = class extends Command {
1966
+ constructor(cmd, opts) {
1967
+ super(["rpushx", ...cmd], opts);
1968
+ }
1969
+ };
1970
+ var SAddCommand = class extends Command {
1971
+ constructor(cmd, opts) {
1972
+ super(["sadd", ...cmd], opts);
1973
+ }
1974
+ };
1975
+ var ScanCommand = class extends Command {
1976
+ constructor([cursor, opts], cmdOpts) {
1977
+ const command = ["scan", cursor];
1978
+ if (opts?.match) {
1979
+ command.push("match", opts.match);
1980
+ }
1981
+ if (typeof opts?.count === "number") {
1982
+ command.push("count", opts.count);
1983
+ }
1984
+ if (opts && "withType" in opts && opts.withType === true) {
1985
+ command.push("withtype");
1986
+ } else if (opts && "type" in opts && opts.type && opts.type.length > 0) {
1987
+ command.push("type", opts.type);
1988
+ }
1989
+ super(command, {
1990
+ deserialize: opts?.withType ? deserializeScanWithTypesResponse : deserializeScanResponse,
1991
+ ...cmdOpts
1992
+ });
1993
+ }
1994
+ };
1995
+ var SCardCommand = class extends Command {
1996
+ constructor(cmd, opts) {
1997
+ super(["scard", ...cmd], opts);
1998
+ }
1999
+ };
2000
+ var ScriptExistsCommand = class extends Command {
2001
+ constructor(hashes, opts) {
2002
+ super(["script", "exists", ...hashes], {
2003
+ deserialize: (result) => result,
2004
+ ...opts
2005
+ });
2006
+ }
2007
+ };
2008
+ var ScriptFlushCommand = class extends Command {
2009
+ constructor([opts], cmdOpts) {
2010
+ const cmd = ["script", "flush"];
2011
+ if (opts?.sync) {
2012
+ cmd.push("sync");
2013
+ } else if (opts?.async) {
2014
+ cmd.push("async");
2015
+ }
2016
+ super(cmd, cmdOpts);
2017
+ }
2018
+ };
2019
+ var ScriptLoadCommand = class extends Command {
2020
+ constructor(args, opts) {
2021
+ super(["script", "load", ...args], opts);
2022
+ }
2023
+ };
2024
+ var SDiffCommand = class extends Command {
2025
+ constructor(cmd, opts) {
2026
+ super(["sdiff", ...cmd], opts);
2027
+ }
2028
+ };
2029
+ var SDiffStoreCommand = class extends Command {
2030
+ constructor(cmd, opts) {
2031
+ super(["sdiffstore", ...cmd], opts);
2032
+ }
2033
+ };
2034
+ var SetCommand = class extends Command {
2035
+ constructor([key, value, opts], cmdOpts) {
2036
+ const command = ["set", key, value];
2037
+ if (opts) {
2038
+ if ("nx" in opts && opts.nx) {
2039
+ command.push("nx");
2040
+ } else if ("xx" in opts && opts.xx) {
2041
+ command.push("xx");
2042
+ }
2043
+ if ("get" in opts && opts.get) {
2044
+ command.push("get");
2045
+ }
2046
+ if ("ex" in opts && typeof opts.ex === "number") {
2047
+ command.push("ex", opts.ex);
2048
+ } else if ("px" in opts && typeof opts.px === "number") {
2049
+ command.push("px", opts.px);
2050
+ } else if ("exat" in opts && typeof opts.exat === "number") {
2051
+ command.push("exat", opts.exat);
2052
+ } else if ("pxat" in opts && typeof opts.pxat === "number") {
2053
+ command.push("pxat", opts.pxat);
2054
+ } else if ("keepTtl" in opts && opts.keepTtl) {
2055
+ command.push("keepTtl");
2056
+ }
2057
+ }
2058
+ super(command, cmdOpts);
2059
+ }
2060
+ };
2061
+ var SetBitCommand = class extends Command {
2062
+ constructor(cmd, opts) {
2063
+ super(["setbit", ...cmd], opts);
2064
+ }
2065
+ };
2066
+ var SetExCommand = class extends Command {
2067
+ constructor(cmd, opts) {
2068
+ super(["setex", ...cmd], opts);
2069
+ }
2070
+ };
2071
+ var SetNxCommand = class extends Command {
2072
+ constructor(cmd, opts) {
2073
+ super(["setnx", ...cmd], opts);
2074
+ }
2075
+ };
2076
+ var SetRangeCommand = class extends Command {
2077
+ constructor(cmd, opts) {
2078
+ super(["setrange", ...cmd], opts);
2079
+ }
2080
+ };
2081
+ var SInterCommand = class extends Command {
2082
+ constructor(cmd, opts) {
2083
+ super(["sinter", ...cmd], opts);
2084
+ }
2085
+ };
2086
+ var SInterCardCommand = class extends Command {
2087
+ constructor(cmd, cmdOpts) {
2088
+ const [keys, opts] = cmd;
2089
+ const command = ["sintercard", keys.length, ...keys];
2090
+ if (opts?.limit !== undefined) {
2091
+ command.push("LIMIT", opts.limit);
2092
+ }
2093
+ super(command, cmdOpts);
2094
+ }
2095
+ };
2096
+ var SInterStoreCommand = class extends Command {
2097
+ constructor(cmd, opts) {
2098
+ super(["sinterstore", ...cmd], opts);
2099
+ }
2100
+ };
2101
+ var SIsMemberCommand = class extends Command {
2102
+ constructor(cmd, opts) {
2103
+ super(["sismember", ...cmd], opts);
2104
+ }
2105
+ };
2106
+ var SMembersCommand = class extends Command {
2107
+ constructor(cmd, opts) {
2108
+ super(["smembers", ...cmd], opts);
2109
+ }
2110
+ };
2111
+ var SMIsMemberCommand = class extends Command {
2112
+ constructor(cmd, opts) {
2113
+ super(["smismember", cmd[0], ...cmd[1]], opts);
2114
+ }
2115
+ };
2116
+ var SMoveCommand = class extends Command {
2117
+ constructor(cmd, opts) {
2118
+ super(["smove", ...cmd], opts);
2119
+ }
2120
+ };
2121
+ var SPopCommand = class extends Command {
2122
+ constructor([key, count], opts) {
2123
+ const command = ["spop", key];
2124
+ if (typeof count === "number") {
2125
+ command.push(count);
2126
+ }
2127
+ super(command, opts);
2128
+ }
2129
+ };
2130
+ var SRandMemberCommand = class extends Command {
2131
+ constructor([key, count], opts) {
2132
+ const command = ["srandmember", key];
2133
+ if (typeof count === "number") {
2134
+ command.push(count);
2135
+ }
2136
+ super(command, opts);
2137
+ }
2138
+ };
2139
+ var SRemCommand = class extends Command {
2140
+ constructor(cmd, opts) {
2141
+ super(["srem", ...cmd], opts);
2142
+ }
2143
+ };
2144
+ var SScanCommand = class extends Command {
2145
+ constructor([key, cursor, opts], cmdOpts) {
2146
+ const command = ["sscan", key, cursor];
2147
+ if (opts?.match) {
2148
+ command.push("match", opts.match);
2149
+ }
2150
+ if (typeof opts?.count === "number") {
2151
+ command.push("count", opts.count);
2152
+ }
2153
+ super(command, {
2154
+ deserialize: deserializeScanResponse,
2155
+ ...cmdOpts
2156
+ });
2157
+ }
2158
+ };
2159
+ var StrLenCommand = class extends Command {
2160
+ constructor(cmd, opts) {
2161
+ super(["strlen", ...cmd], opts);
2162
+ }
2163
+ };
2164
+ var SUnionCommand = class extends Command {
2165
+ constructor(cmd, opts) {
2166
+ super(["sunion", ...cmd], opts);
2167
+ }
2168
+ };
2169
+ var SUnionStoreCommand = class extends Command {
2170
+ constructor(cmd, opts) {
2171
+ super(["sunionstore", ...cmd], opts);
2172
+ }
2173
+ };
2174
+ var TimeCommand = class extends Command {
2175
+ constructor(opts) {
2176
+ super(["time"], opts);
2177
+ }
2178
+ };
2179
+ var TouchCommand = class extends Command {
2180
+ constructor(cmd, opts) {
2181
+ super(["touch", ...cmd], opts);
2182
+ }
2183
+ };
2184
+ var TtlCommand = class extends Command {
2185
+ constructor(cmd, opts) {
2186
+ super(["ttl", ...cmd], opts);
2187
+ }
2188
+ };
2189
+ var TypeCommand = class extends Command {
2190
+ constructor(cmd, opts) {
2191
+ super(["type", ...cmd], opts);
2192
+ }
2193
+ };
2194
+ var UnlinkCommand = class extends Command {
2195
+ constructor(cmd, opts) {
2196
+ super(["unlink", ...cmd], opts);
2197
+ }
2198
+ };
2199
+ var XAckCommand = class extends Command {
2200
+ constructor([key, group, id], opts) {
2201
+ const ids = Array.isArray(id) ? [...id] : [id];
2202
+ super(["XACK", key, group, ...ids], opts);
2203
+ }
2204
+ };
2205
+ var XAckDelCommand = class extends Command {
2206
+ constructor([key, group, opts, ...ids], cmdOpts) {
2207
+ const command = ["XACKDEL", key, group];
2208
+ command.push(opts.toUpperCase(), "IDS", ids.length, ...ids);
2209
+ super(command, cmdOpts);
2210
+ }
2211
+ };
2212
+ var XAddCommand = class extends Command {
2213
+ constructor([key, id, entries, opts], commandOptions) {
2214
+ const command = ["XADD", key];
2215
+ if (opts) {
2216
+ if (opts.nomkStream) {
2217
+ command.push("NOMKSTREAM");
2218
+ }
2219
+ if (opts.trim) {
2220
+ command.push(opts.trim.type, opts.trim.comparison, opts.trim.threshold);
2221
+ if (opts.trim.limit !== undefined) {
2222
+ command.push("LIMIT", opts.trim.limit);
2223
+ }
2224
+ }
2225
+ }
2226
+ command.push(id);
2227
+ for (const [k, v] of Object.entries(entries)) {
2228
+ command.push(k, v);
2229
+ }
2230
+ super(command, commandOptions);
2231
+ }
2232
+ };
2233
+ var XAutoClaim = class extends Command {
2234
+ constructor([key, group, consumer, minIdleTime, start, options], opts) {
2235
+ const commands = [];
2236
+ if (options?.count) {
2237
+ commands.push("COUNT", options.count);
2238
+ }
2239
+ if (options?.justId) {
2240
+ commands.push("JUSTID");
2241
+ }
2242
+ super(["XAUTOCLAIM", key, group, consumer, minIdleTime, start, ...commands], opts);
2243
+ }
2244
+ };
2245
+ var XClaimCommand = class extends Command {
2246
+ constructor([key, group, consumer, minIdleTime, id, options], opts) {
2247
+ const ids = Array.isArray(id) ? [...id] : [id];
2248
+ const commands = [];
2249
+ if (options?.idleMS) {
2250
+ commands.push("IDLE", options.idleMS);
2251
+ }
2252
+ if (options?.idleMS) {
2253
+ commands.push("TIME", options.timeMS);
2254
+ }
2255
+ if (options?.retryCount) {
2256
+ commands.push("RETRYCOUNT", options.retryCount);
2257
+ }
2258
+ if (options?.force) {
2259
+ commands.push("FORCE");
2260
+ }
2261
+ if (options?.justId) {
2262
+ commands.push("JUSTID");
2263
+ }
2264
+ if (options?.lastId) {
2265
+ commands.push("LASTID", options.lastId);
2266
+ }
2267
+ super(["XCLAIM", key, group, consumer, minIdleTime, ...ids, ...commands], opts);
2268
+ }
2269
+ };
2270
+ var XDelCommand = class extends Command {
2271
+ constructor([key, ids], opts) {
2272
+ const cmds = Array.isArray(ids) ? [...ids] : [ids];
2273
+ super(["XDEL", key, ...cmds], opts);
2274
+ }
2275
+ };
2276
+ var XDelExCommand = class extends Command {
2277
+ constructor([key, opts, ...ids], cmdOpts) {
2278
+ const command = ["XDELEX", key];
2279
+ if (opts) {
2280
+ command.push(opts.toUpperCase());
2281
+ }
2282
+ command.push("IDS", ids.length, ...ids);
2283
+ super(command, cmdOpts);
2284
+ }
2285
+ };
2286
+ var XGroupCommand = class extends Command {
2287
+ constructor([key, opts], commandOptions) {
2288
+ const command = ["XGROUP"];
2289
+ switch (opts.type) {
2290
+ case "CREATE": {
2291
+ command.push("CREATE", key, opts.group, opts.id);
2292
+ if (opts.options) {
2293
+ if (opts.options.MKSTREAM) {
2294
+ command.push("MKSTREAM");
2295
+ }
2296
+ if (opts.options.ENTRIESREAD !== undefined) {
2297
+ command.push("ENTRIESREAD", opts.options.ENTRIESREAD.toString());
2298
+ }
2299
+ }
2300
+ break;
2301
+ }
2302
+ case "CREATECONSUMER": {
2303
+ command.push("CREATECONSUMER", key, opts.group, opts.consumer);
2304
+ break;
2305
+ }
2306
+ case "DELCONSUMER": {
2307
+ command.push("DELCONSUMER", key, opts.group, opts.consumer);
2308
+ break;
2309
+ }
2310
+ case "DESTROY": {
2311
+ command.push("DESTROY", key, opts.group);
2312
+ break;
2313
+ }
2314
+ case "SETID": {
2315
+ command.push("SETID", key, opts.group, opts.id);
2316
+ if (opts.options?.ENTRIESREAD !== undefined) {
2317
+ command.push("ENTRIESREAD", opts.options.ENTRIESREAD.toString());
2318
+ }
2319
+ break;
2320
+ }
2321
+ default: {
2322
+ throw new Error("Invalid XGROUP");
2323
+ }
2324
+ }
2325
+ super(command, commandOptions);
2326
+ }
2327
+ };
2328
+ var XInfoCommand = class extends Command {
2329
+ constructor([key, options], opts) {
2330
+ const cmds = [];
2331
+ if (options.type === "CONSUMERS") {
2332
+ cmds.push("CONSUMERS", key, options.group);
2333
+ } else {
2334
+ cmds.push("GROUPS", key);
2335
+ }
2336
+ super(["XINFO", ...cmds], opts);
2337
+ }
2338
+ };
2339
+ var XLenCommand = class extends Command {
2340
+ constructor(cmd, opts) {
2341
+ super(["XLEN", ...cmd], opts);
2342
+ }
2343
+ };
2344
+ var XPendingCommand = class extends Command {
2345
+ constructor([key, group, start, end, count, options], opts) {
2346
+ const consumers = options?.consumer === undefined ? [] : Array.isArray(options.consumer) ? [...options.consumer] : [options.consumer];
2347
+ super([
2348
+ "XPENDING",
2349
+ key,
2350
+ group,
2351
+ ...options?.idleTime ? ["IDLE", options.idleTime] : [],
2352
+ start,
2353
+ end,
2354
+ count,
2355
+ ...consumers
2356
+ ], opts);
2357
+ }
2358
+ };
2359
+ function deserialize6(result) {
2360
+ const obj = {};
2361
+ for (const e of result) {
2362
+ for (let i = 0;i < e.length; i += 2) {
2363
+ const streamId = e[i];
2364
+ const entries = e[i + 1];
2365
+ if (!(streamId in obj)) {
2366
+ obj[streamId] = {};
2367
+ }
2368
+ for (let j = 0;j < entries.length; j += 2) {
2369
+ const field = entries[j];
2370
+ const value = entries[j + 1];
2371
+ try {
2372
+ obj[streamId][field] = JSON.parse(value);
2373
+ } catch {
2374
+ obj[streamId][field] = value;
2375
+ }
2376
+ }
2377
+ }
2378
+ }
2379
+ return obj;
2380
+ }
2381
+ var XRangeCommand = class extends Command {
2382
+ constructor([key, start, end, count], opts) {
2383
+ const command = ["XRANGE", key, start, end];
2384
+ if (typeof count === "number") {
2385
+ command.push("COUNT", count);
2386
+ }
2387
+ super(command, {
2388
+ deserialize: (result) => deserialize6(result),
2389
+ ...opts
2390
+ });
2391
+ }
2392
+ };
2393
+ var UNBALANCED_XREAD_ERR = "ERR Unbalanced XREAD list of streams: for each stream key an ID or '$' must be specified";
2394
+ var XReadCommand = class extends Command {
2395
+ constructor([key, id, options], opts) {
2396
+ if (Array.isArray(key) && Array.isArray(id) && key.length !== id.length) {
2397
+ throw new Error(UNBALANCED_XREAD_ERR);
2398
+ }
2399
+ const commands = [];
2400
+ if (typeof options?.count === "number") {
2401
+ commands.push("COUNT", options.count);
2402
+ }
2403
+ if (typeof options?.blockMS === "number") {
2404
+ commands.push("BLOCK", options.blockMS);
2405
+ }
2406
+ commands.push("STREAMS", ...Array.isArray(key) ? [...key] : [key], ...Array.isArray(id) ? [...id] : [id]);
2407
+ super(["XREAD", ...commands], opts);
2408
+ }
2409
+ };
2410
+ var UNBALANCED_XREADGROUP_ERR = "ERR Unbalanced XREADGROUP list of streams: for each stream key an ID or '$' must be specified";
2411
+ var XReadGroupCommand = class extends Command {
2412
+ constructor([group, consumer, key, id, options], opts) {
2413
+ if (Array.isArray(key) && Array.isArray(id) && key.length !== id.length) {
2414
+ throw new Error(UNBALANCED_XREADGROUP_ERR);
2415
+ }
2416
+ const commands = [];
2417
+ if (typeof options?.count === "number") {
2418
+ commands.push("COUNT", options.count);
2419
+ }
2420
+ if (typeof options?.blockMS === "number") {
2421
+ commands.push("BLOCK", options.blockMS);
2422
+ }
2423
+ if (typeof options?.NOACK === "boolean" && options.NOACK) {
2424
+ commands.push("NOACK");
2425
+ }
2426
+ commands.push("STREAMS", ...Array.isArray(key) ? [...key] : [key], ...Array.isArray(id) ? [...id] : [id]);
2427
+ super(["XREADGROUP", "GROUP", group, consumer, ...commands], opts);
2428
+ }
2429
+ };
2430
+ var XRevRangeCommand = class extends Command {
2431
+ constructor([key, end, start, count], opts) {
2432
+ const command = ["XREVRANGE", key, end, start];
2433
+ if (typeof count === "number") {
2434
+ command.push("COUNT", count);
2435
+ }
2436
+ super(command, {
2437
+ deserialize: (result) => deserialize7(result),
2438
+ ...opts
2439
+ });
2440
+ }
2441
+ };
2442
+ function deserialize7(result) {
2443
+ const obj = {};
2444
+ for (const e of result) {
2445
+ for (let i = 0;i < e.length; i += 2) {
2446
+ const streamId = e[i];
2447
+ const entries = e[i + 1];
2448
+ if (!(streamId in obj)) {
2449
+ obj[streamId] = {};
2450
+ }
2451
+ for (let j = 0;j < entries.length; j += 2) {
2452
+ const field = entries[j];
2453
+ const value = entries[j + 1];
2454
+ try {
2455
+ obj[streamId][field] = JSON.parse(value);
2456
+ } catch {
2457
+ obj[streamId][field] = value;
2458
+ }
2459
+ }
2460
+ }
2461
+ }
2462
+ return obj;
2463
+ }
2464
+ var XTrimCommand = class extends Command {
2465
+ constructor([key, options], opts) {
2466
+ const { limit, strategy, threshold, exactness = "~" } = options;
2467
+ super(["XTRIM", key, strategy, exactness, threshold, ...limit ? ["LIMIT", limit] : []], opts);
2468
+ }
2469
+ };
2470
+ var ZAddCommand = class extends Command {
2471
+ constructor([key, arg1, ...arg2], opts) {
2472
+ const command = ["zadd", key];
2473
+ if ("nx" in arg1 && arg1.nx) {
2474
+ command.push("nx");
2475
+ } else if ("xx" in arg1 && arg1.xx) {
2476
+ command.push("xx");
2477
+ }
2478
+ if ("ch" in arg1 && arg1.ch) {
2479
+ command.push("ch");
2480
+ }
2481
+ if ("incr" in arg1 && arg1.incr) {
2482
+ command.push("incr");
2483
+ }
2484
+ if ("lt" in arg1 && arg1.lt) {
2485
+ command.push("lt");
2486
+ } else if ("gt" in arg1 && arg1.gt) {
2487
+ command.push("gt");
2488
+ }
2489
+ if ("score" in arg1 && "member" in arg1) {
2490
+ command.push(arg1.score, arg1.member);
2491
+ }
2492
+ command.push(...arg2.flatMap(({ score, member }) => [score, member]));
2493
+ super(command, opts);
2494
+ }
2495
+ };
2496
+ var ZCardCommand = class extends Command {
2497
+ constructor(cmd, opts) {
2498
+ super(["zcard", ...cmd], opts);
2499
+ }
2500
+ };
2501
+ var ZCountCommand = class extends Command {
2502
+ constructor(cmd, opts) {
2503
+ super(["zcount", ...cmd], opts);
2504
+ }
2505
+ };
2506
+ var ZIncrByCommand = class extends Command {
2507
+ constructor(cmd, opts) {
2508
+ super(["zincrby", ...cmd], opts);
2509
+ }
2510
+ };
2511
+ var ZInterStoreCommand = class extends Command {
2512
+ constructor([destination, numKeys, keyOrKeys, opts], cmdOpts) {
2513
+ const command = ["zinterstore", destination, numKeys];
2514
+ if (Array.isArray(keyOrKeys)) {
2515
+ command.push(...keyOrKeys);
2516
+ } else {
2517
+ command.push(keyOrKeys);
2518
+ }
2519
+ if (opts) {
2520
+ if ("weights" in opts && opts.weights) {
2521
+ command.push("weights", ...opts.weights);
2522
+ } else if ("weight" in opts && typeof opts.weight === "number") {
2523
+ command.push("weights", opts.weight);
2524
+ }
2525
+ if ("aggregate" in opts) {
2526
+ command.push("aggregate", opts.aggregate);
2527
+ }
2528
+ }
2529
+ super(command, cmdOpts);
2530
+ }
2531
+ };
2532
+ var ZLexCountCommand = class extends Command {
2533
+ constructor(cmd, opts) {
2534
+ super(["zlexcount", ...cmd], opts);
2535
+ }
2536
+ };
2537
+ var ZPopMaxCommand = class extends Command {
2538
+ constructor([key, count], opts) {
2539
+ const command = ["zpopmax", key];
2540
+ if (typeof count === "number") {
2541
+ command.push(count);
2542
+ }
2543
+ super(command, opts);
2544
+ }
2545
+ };
2546
+ var ZPopMinCommand = class extends Command {
2547
+ constructor([key, count], opts) {
2548
+ const command = ["zpopmin", key];
2549
+ if (typeof count === "number") {
2550
+ command.push(count);
2551
+ }
2552
+ super(command, opts);
2553
+ }
2554
+ };
2555
+ var ZRangeCommand = class extends Command {
2556
+ constructor([key, min, max, opts], cmdOpts) {
2557
+ const command = ["zrange", key, min, max];
2558
+ if (opts?.byScore) {
2559
+ command.push("byscore");
2560
+ }
2561
+ if (opts?.byLex) {
2562
+ command.push("bylex");
2563
+ }
2564
+ if (opts?.rev) {
2565
+ command.push("rev");
2566
+ }
2567
+ if (opts?.count !== undefined && opts.offset !== undefined) {
2568
+ command.push("limit", opts.offset, opts.count);
2569
+ }
2570
+ if (opts?.withScores) {
2571
+ command.push("withscores");
2572
+ }
2573
+ super(command, cmdOpts);
2574
+ }
2575
+ };
2576
+ var ZRankCommand = class extends Command {
2577
+ constructor(cmd, opts) {
2578
+ super(["zrank", ...cmd], opts);
2579
+ }
2580
+ };
2581
+ var ZRemCommand = class extends Command {
2582
+ constructor(cmd, opts) {
2583
+ super(["zrem", ...cmd], opts);
2584
+ }
2585
+ };
2586
+ var ZRemRangeByLexCommand = class extends Command {
2587
+ constructor(cmd, opts) {
2588
+ super(["zremrangebylex", ...cmd], opts);
2589
+ }
2590
+ };
2591
+ var ZRemRangeByRankCommand = class extends Command {
2592
+ constructor(cmd, opts) {
2593
+ super(["zremrangebyrank", ...cmd], opts);
2594
+ }
2595
+ };
2596
+ var ZRemRangeByScoreCommand = class extends Command {
2597
+ constructor(cmd, opts) {
2598
+ super(["zremrangebyscore", ...cmd], opts);
2599
+ }
2600
+ };
2601
+ var ZRevRankCommand = class extends Command {
2602
+ constructor(cmd, opts) {
2603
+ super(["zrevrank", ...cmd], opts);
2604
+ }
2605
+ };
2606
+ var ZScanCommand = class extends Command {
2607
+ constructor([key, cursor, opts], cmdOpts) {
2608
+ const command = ["zscan", key, cursor];
2609
+ if (opts?.match) {
2610
+ command.push("match", opts.match);
2611
+ }
2612
+ if (typeof opts?.count === "number") {
2613
+ command.push("count", opts.count);
2614
+ }
2615
+ super(command, {
2616
+ deserialize: deserializeScanResponse,
2617
+ ...cmdOpts
2618
+ });
2619
+ }
2620
+ };
2621
+ var ZScoreCommand = class extends Command {
2622
+ constructor(cmd, opts) {
2623
+ super(["zscore", ...cmd], opts);
2624
+ }
2625
+ };
2626
+ var ZUnionCommand = class extends Command {
2627
+ constructor([numKeys, keyOrKeys, opts], cmdOpts) {
2628
+ const command = ["zunion", numKeys];
2629
+ if (Array.isArray(keyOrKeys)) {
2630
+ command.push(...keyOrKeys);
2631
+ } else {
2632
+ command.push(keyOrKeys);
2633
+ }
2634
+ if (opts) {
2635
+ if ("weights" in opts && opts.weights) {
2636
+ command.push("weights", ...opts.weights);
2637
+ } else if ("weight" in opts && typeof opts.weight === "number") {
2638
+ command.push("weights", opts.weight);
2639
+ }
2640
+ if ("aggregate" in opts) {
2641
+ command.push("aggregate", opts.aggregate);
2642
+ }
2643
+ if (opts.withScores) {
2644
+ command.push("withscores");
2645
+ }
2646
+ }
2647
+ super(command, cmdOpts);
2648
+ }
2649
+ };
2650
+ var ZUnionStoreCommand = class extends Command {
2651
+ constructor([destination, numKeys, keyOrKeys, opts], cmdOpts) {
2652
+ const command = ["zunionstore", destination, numKeys];
2653
+ if (Array.isArray(keyOrKeys)) {
2654
+ command.push(...keyOrKeys);
2655
+ } else {
2656
+ command.push(keyOrKeys);
2657
+ }
2658
+ if (opts) {
2659
+ if ("weights" in opts && opts.weights) {
2660
+ command.push("weights", ...opts.weights);
2661
+ } else if ("weight" in opts && typeof opts.weight === "number") {
2662
+ command.push("weights", opts.weight);
2663
+ }
2664
+ if ("aggregate" in opts) {
2665
+ command.push("aggregate", opts.aggregate);
2666
+ }
2667
+ }
2668
+ super(command, cmdOpts);
2669
+ }
2670
+ };
2671
+ var ZDiffStoreCommand = class extends Command {
2672
+ constructor(cmd, opts) {
2673
+ super(["zdiffstore", ...cmd], opts);
2674
+ }
2675
+ };
2676
+ var ZMScoreCommand = class extends Command {
2677
+ constructor(cmd, opts) {
2678
+ const [key, members] = cmd;
2679
+ super(["zmscore", key, ...members], opts);
2680
+ }
2681
+ };
2682
+ var Pipeline = class {
2683
+ client;
2684
+ commands;
2685
+ commandOptions;
2686
+ multiExec;
2687
+ constructor(opts) {
2688
+ this.client = opts.client;
2689
+ this.commands = [];
2690
+ this.commandOptions = opts.commandOptions;
2691
+ this.multiExec = opts.multiExec ?? false;
2692
+ if (this.commandOptions?.latencyLogging) {
2693
+ const originalExec = this.exec.bind(this);
2694
+ this.exec = async (options) => {
2695
+ const start = performance.now();
2696
+ const result = await (options ? originalExec(options) : originalExec());
2697
+ const end = performance.now();
2698
+ const loggerResult = (end - start).toFixed(2);
2699
+ return result;
2700
+ };
2701
+ }
2702
+ }
2703
+ exec = async (options) => {
2704
+ if (this.commands.length === 0) {
2705
+ throw new Error("Pipeline is empty");
2706
+ }
2707
+ const path = this.multiExec ? ["multi-exec"] : ["pipeline"];
2708
+ const res = await this.client.request({
2709
+ path,
2710
+ body: Object.values(this.commands).map((c) => c.command)
2711
+ });
2712
+ return options?.keepErrors ? res.map(({ error, result }, i) => {
2713
+ return {
2714
+ error,
2715
+ result: this.commands[i].deserialize(result)
2716
+ };
2717
+ }) : res.map(({ error, result }, i) => {
2718
+ if (error) {
2719
+ throw new UpstashError(`Command ${i + 1} [ ${this.commands[i].command[0]} ] failed: ${error}`);
2720
+ }
2721
+ return this.commands[i].deserialize(result);
2722
+ });
2723
+ };
2724
+ length() {
2725
+ return this.commands.length;
2726
+ }
2727
+ chain(command) {
2728
+ this.commands.push(command);
2729
+ return this;
2730
+ }
2731
+ append = (...args) => this.chain(new AppendCommand(args, this.commandOptions));
2732
+ bitcount = (...args) => this.chain(new BitCountCommand(args, this.commandOptions));
2733
+ bitfield = (...args) => new BitFieldCommand(args, this.client, this.commandOptions, this.chain.bind(this));
2734
+ bitop = (op, destinationKey, sourceKey, ...sourceKeys) => this.chain(new BitOpCommand([op, destinationKey, sourceKey, ...sourceKeys], this.commandOptions));
2735
+ bitpos = (...args) => this.chain(new BitPosCommand(args, this.commandOptions));
2736
+ clientSetinfo = (...args) => this.chain(new ClientSetInfoCommand(args, this.commandOptions));
2737
+ copy = (...args) => this.chain(new CopyCommand(args, this.commandOptions));
2738
+ zdiffstore = (...args) => this.chain(new ZDiffStoreCommand(args, this.commandOptions));
2739
+ dbsize = () => this.chain(new DBSizeCommand(this.commandOptions));
2740
+ decr = (...args) => this.chain(new DecrCommand(args, this.commandOptions));
2741
+ decrby = (...args) => this.chain(new DecrByCommand(args, this.commandOptions));
2742
+ del = (...args) => this.chain(new DelCommand(args, this.commandOptions));
2743
+ echo = (...args) => this.chain(new EchoCommand(args, this.commandOptions));
2744
+ evalRo = (...args) => this.chain(new EvalROCommand(args, this.commandOptions));
2745
+ eval = (...args) => this.chain(new EvalCommand(args, this.commandOptions));
2746
+ evalshaRo = (...args) => this.chain(new EvalshaROCommand(args, this.commandOptions));
2747
+ evalsha = (...args) => this.chain(new EvalshaCommand(args, this.commandOptions));
2748
+ exists = (...args) => this.chain(new ExistsCommand(args, this.commandOptions));
2749
+ expire = (...args) => this.chain(new ExpireCommand(args, this.commandOptions));
2750
+ expireat = (...args) => this.chain(new ExpireAtCommand(args, this.commandOptions));
2751
+ flushall = (args) => this.chain(new FlushAllCommand(args, this.commandOptions));
2752
+ flushdb = (...args) => this.chain(new FlushDBCommand(args, this.commandOptions));
2753
+ geoadd = (...args) => this.chain(new GeoAddCommand(args, this.commandOptions));
2754
+ geodist = (...args) => this.chain(new GeoDistCommand(args, this.commandOptions));
2755
+ geopos = (...args) => this.chain(new GeoPosCommand(args, this.commandOptions));
2756
+ geohash = (...args) => this.chain(new GeoHashCommand(args, this.commandOptions));
2757
+ geosearch = (...args) => this.chain(new GeoSearchCommand(args, this.commandOptions));
2758
+ geosearchstore = (...args) => this.chain(new GeoSearchStoreCommand(args, this.commandOptions));
2759
+ get = (...args) => this.chain(new GetCommand(args, this.commandOptions));
2760
+ getbit = (...args) => this.chain(new GetBitCommand(args, this.commandOptions));
2761
+ getdel = (...args) => this.chain(new GetDelCommand(args, this.commandOptions));
2762
+ getex = (...args) => this.chain(new GetExCommand(args, this.commandOptions));
2763
+ getrange = (...args) => this.chain(new GetRangeCommand(args, this.commandOptions));
2764
+ getset = (key, value) => this.chain(new GetSetCommand([key, value], this.commandOptions));
2765
+ hdel = (...args) => this.chain(new HDelCommand(args, this.commandOptions));
2766
+ hexists = (...args) => this.chain(new HExistsCommand(args, this.commandOptions));
2767
+ hexpire = (...args) => this.chain(new HExpireCommand(args, this.commandOptions));
2768
+ hexpireat = (...args) => this.chain(new HExpireAtCommand(args, this.commandOptions));
2769
+ hexpiretime = (...args) => this.chain(new HExpireTimeCommand(args, this.commandOptions));
2770
+ httl = (...args) => this.chain(new HTtlCommand(args, this.commandOptions));
2771
+ hpexpire = (...args) => this.chain(new HPExpireCommand(args, this.commandOptions));
2772
+ hpexpireat = (...args) => this.chain(new HPExpireAtCommand(args, this.commandOptions));
2773
+ hpexpiretime = (...args) => this.chain(new HPExpireTimeCommand(args, this.commandOptions));
2774
+ hpttl = (...args) => this.chain(new HPTtlCommand(args, this.commandOptions));
2775
+ hpersist = (...args) => this.chain(new HPersistCommand(args, this.commandOptions));
2776
+ hget = (...args) => this.chain(new HGetCommand(args, this.commandOptions));
2777
+ hgetall = (...args) => this.chain(new HGetAllCommand(args, this.commandOptions));
2778
+ hgetdel = (...args) => this.chain(new HGetDelCommand(args, this.commandOptions));
2779
+ hgetex = (...args) => this.chain(new HGetExCommand(args, this.commandOptions));
2780
+ hincrby = (...args) => this.chain(new HIncrByCommand(args, this.commandOptions));
2781
+ hincrbyfloat = (...args) => this.chain(new HIncrByFloatCommand(args, this.commandOptions));
2782
+ hkeys = (...args) => this.chain(new HKeysCommand(args, this.commandOptions));
2783
+ hlen = (...args) => this.chain(new HLenCommand(args, this.commandOptions));
2784
+ hmget = (...args) => this.chain(new HMGetCommand(args, this.commandOptions));
2785
+ hmset = (key, kv) => this.chain(new HMSetCommand([key, kv], this.commandOptions));
2786
+ hrandfield = (key, count, withValues) => this.chain(new HRandFieldCommand([key, count, withValues], this.commandOptions));
2787
+ hscan = (...args) => this.chain(new HScanCommand(args, this.commandOptions));
2788
+ hset = (key, kv) => this.chain(new HSetCommand([key, kv], this.commandOptions));
2789
+ hsetex = (...args) => this.chain(new HSetExCommand(args, this.commandOptions));
2790
+ hsetnx = (key, field, value) => this.chain(new HSetNXCommand([key, field, value], this.commandOptions));
2791
+ hstrlen = (...args) => this.chain(new HStrLenCommand(args, this.commandOptions));
2792
+ hvals = (...args) => this.chain(new HValsCommand(args, this.commandOptions));
2793
+ incr = (...args) => this.chain(new IncrCommand(args, this.commandOptions));
2794
+ incrby = (...args) => this.chain(new IncrByCommand(args, this.commandOptions));
2795
+ incrbyfloat = (...args) => this.chain(new IncrByFloatCommand(args, this.commandOptions));
2796
+ keys = (...args) => this.chain(new KeysCommand(args, this.commandOptions));
2797
+ lindex = (...args) => this.chain(new LIndexCommand(args, this.commandOptions));
2798
+ linsert = (key, direction, pivot, value) => this.chain(new LInsertCommand([key, direction, pivot, value], this.commandOptions));
2799
+ llen = (...args) => this.chain(new LLenCommand(args, this.commandOptions));
2800
+ lmove = (...args) => this.chain(new LMoveCommand(args, this.commandOptions));
2801
+ lpop = (...args) => this.chain(new LPopCommand(args, this.commandOptions));
2802
+ lmpop = (...args) => this.chain(new LmPopCommand(args, this.commandOptions));
2803
+ lpos = (...args) => this.chain(new LPosCommand(args, this.commandOptions));
2804
+ lpush = (key, ...elements) => this.chain(new LPushCommand([key, ...elements], this.commandOptions));
2805
+ lpushx = (key, ...elements) => this.chain(new LPushXCommand([key, ...elements], this.commandOptions));
2806
+ lrange = (...args) => this.chain(new LRangeCommand(args, this.commandOptions));
2807
+ lrem = (key, count, value) => this.chain(new LRemCommand([key, count, value], this.commandOptions));
2808
+ lset = (key, index, value) => this.chain(new LSetCommand([key, index, value], this.commandOptions));
2809
+ ltrim = (...args) => this.chain(new LTrimCommand(args, this.commandOptions));
2810
+ mget = (...args) => this.chain(new MGetCommand(args, this.commandOptions));
2811
+ mset = (kv) => this.chain(new MSetCommand([kv], this.commandOptions));
2812
+ msetnx = (kv) => this.chain(new MSetNXCommand([kv], this.commandOptions));
2813
+ persist = (...args) => this.chain(new PersistCommand(args, this.commandOptions));
2814
+ pexpire = (...args) => this.chain(new PExpireCommand(args, this.commandOptions));
2815
+ pexpireat = (...args) => this.chain(new PExpireAtCommand(args, this.commandOptions));
2816
+ pfadd = (...args) => this.chain(new PfAddCommand(args, this.commandOptions));
2817
+ pfcount = (...args) => this.chain(new PfCountCommand(args, this.commandOptions));
2818
+ pfmerge = (...args) => this.chain(new PfMergeCommand(args, this.commandOptions));
2819
+ ping = (args) => this.chain(new PingCommand(args, this.commandOptions));
2820
+ psetex = (key, ttl, value) => this.chain(new PSetEXCommand([key, ttl, value], this.commandOptions));
2821
+ pttl = (...args) => this.chain(new PTtlCommand(args, this.commandOptions));
2822
+ publish = (...args) => this.chain(new PublishCommand(args, this.commandOptions));
2823
+ randomkey = () => this.chain(new RandomKeyCommand(this.commandOptions));
2824
+ rename = (...args) => this.chain(new RenameCommand(args, this.commandOptions));
2825
+ renamenx = (...args) => this.chain(new RenameNXCommand(args, this.commandOptions));
2826
+ rpop = (...args) => this.chain(new RPopCommand(args, this.commandOptions));
2827
+ rpush = (key, ...elements) => this.chain(new RPushCommand([key, ...elements], this.commandOptions));
2828
+ rpushx = (key, ...elements) => this.chain(new RPushXCommand([key, ...elements], this.commandOptions));
2829
+ sadd = (key, member, ...members) => this.chain(new SAddCommand([key, member, ...members], this.commandOptions));
2830
+ scan = (...args) => this.chain(new ScanCommand(args, this.commandOptions));
2831
+ scard = (...args) => this.chain(new SCardCommand(args, this.commandOptions));
2832
+ scriptExists = (...args) => this.chain(new ScriptExistsCommand(args, this.commandOptions));
2833
+ scriptFlush = (...args) => this.chain(new ScriptFlushCommand(args, this.commandOptions));
2834
+ scriptLoad = (...args) => this.chain(new ScriptLoadCommand(args, this.commandOptions));
2835
+ sdiff = (...args) => this.chain(new SDiffCommand(args, this.commandOptions));
2836
+ sdiffstore = (...args) => this.chain(new SDiffStoreCommand(args, this.commandOptions));
2837
+ set = (key, value, opts) => this.chain(new SetCommand([key, value, opts], this.commandOptions));
2838
+ setbit = (...args) => this.chain(new SetBitCommand(args, this.commandOptions));
2839
+ setex = (key, ttl, value) => this.chain(new SetExCommand([key, ttl, value], this.commandOptions));
2840
+ setnx = (key, value) => this.chain(new SetNxCommand([key, value], this.commandOptions));
2841
+ setrange = (...args) => this.chain(new SetRangeCommand(args, this.commandOptions));
2842
+ sinter = (...args) => this.chain(new SInterCommand(args, this.commandOptions));
2843
+ sintercard = (...args) => this.chain(new SInterCardCommand(args, this.commandOptions));
2844
+ sinterstore = (...args) => this.chain(new SInterStoreCommand(args, this.commandOptions));
2845
+ sismember = (key, member) => this.chain(new SIsMemberCommand([key, member], this.commandOptions));
2846
+ smembers = (...args) => this.chain(new SMembersCommand(args, this.commandOptions));
2847
+ smismember = (key, members) => this.chain(new SMIsMemberCommand([key, members], this.commandOptions));
2848
+ smove = (source, destination, member) => this.chain(new SMoveCommand([source, destination, member], this.commandOptions));
2849
+ spop = (...args) => this.chain(new SPopCommand(args, this.commandOptions));
2850
+ srandmember = (...args) => this.chain(new SRandMemberCommand(args, this.commandOptions));
2851
+ srem = (key, ...members) => this.chain(new SRemCommand([key, ...members], this.commandOptions));
2852
+ sscan = (...args) => this.chain(new SScanCommand(args, this.commandOptions));
2853
+ strlen = (...args) => this.chain(new StrLenCommand(args, this.commandOptions));
2854
+ sunion = (...args) => this.chain(new SUnionCommand(args, this.commandOptions));
2855
+ sunionstore = (...args) => this.chain(new SUnionStoreCommand(args, this.commandOptions));
2856
+ time = () => this.chain(new TimeCommand(this.commandOptions));
2857
+ touch = (...args) => this.chain(new TouchCommand(args, this.commandOptions));
2858
+ ttl = (...args) => this.chain(new TtlCommand(args, this.commandOptions));
2859
+ type = (...args) => this.chain(new TypeCommand(args, this.commandOptions));
2860
+ unlink = (...args) => this.chain(new UnlinkCommand(args, this.commandOptions));
2861
+ zadd = (...args) => {
2862
+ if ("score" in args[1]) {
2863
+ return this.chain(new ZAddCommand([args[0], args[1], ...args.slice(2)], this.commandOptions));
2864
+ }
2865
+ return this.chain(new ZAddCommand([args[0], args[1], ...args.slice(2)], this.commandOptions));
2866
+ };
2867
+ xadd = (...args) => this.chain(new XAddCommand(args, this.commandOptions));
2868
+ xack = (...args) => this.chain(new XAckCommand(args, this.commandOptions));
2869
+ xackdel = (...args) => this.chain(new XAckDelCommand(args, this.commandOptions));
2870
+ xdel = (...args) => this.chain(new XDelCommand(args, this.commandOptions));
2871
+ xdelex = (...args) => this.chain(new XDelExCommand(args, this.commandOptions));
2872
+ xgroup = (...args) => this.chain(new XGroupCommand(args, this.commandOptions));
2873
+ xread = (...args) => this.chain(new XReadCommand(args, this.commandOptions));
2874
+ xreadgroup = (...args) => this.chain(new XReadGroupCommand(args, this.commandOptions));
2875
+ xinfo = (...args) => this.chain(new XInfoCommand(args, this.commandOptions));
2876
+ xlen = (...args) => this.chain(new XLenCommand(args, this.commandOptions));
2877
+ xpending = (...args) => this.chain(new XPendingCommand(args, this.commandOptions));
2878
+ xclaim = (...args) => this.chain(new XClaimCommand(args, this.commandOptions));
2879
+ xautoclaim = (...args) => this.chain(new XAutoClaim(args, this.commandOptions));
2880
+ xtrim = (...args) => this.chain(new XTrimCommand(args, this.commandOptions));
2881
+ xrange = (...args) => this.chain(new XRangeCommand(args, this.commandOptions));
2882
+ xrevrange = (...args) => this.chain(new XRevRangeCommand(args, this.commandOptions));
2883
+ zcard = (...args) => this.chain(new ZCardCommand(args, this.commandOptions));
2884
+ zcount = (...args) => this.chain(new ZCountCommand(args, this.commandOptions));
2885
+ zincrby = (key, increment, member) => this.chain(new ZIncrByCommand([key, increment, member], this.commandOptions));
2886
+ zinterstore = (...args) => this.chain(new ZInterStoreCommand(args, this.commandOptions));
2887
+ zlexcount = (...args) => this.chain(new ZLexCountCommand(args, this.commandOptions));
2888
+ zmscore = (...args) => this.chain(new ZMScoreCommand(args, this.commandOptions));
2889
+ zpopmax = (...args) => this.chain(new ZPopMaxCommand(args, this.commandOptions));
2890
+ zpopmin = (...args) => this.chain(new ZPopMinCommand(args, this.commandOptions));
2891
+ zrange = (...args) => this.chain(new ZRangeCommand(args, this.commandOptions));
2892
+ zrank = (key, member) => this.chain(new ZRankCommand([key, member], this.commandOptions));
2893
+ zrem = (key, ...members) => this.chain(new ZRemCommand([key, ...members], this.commandOptions));
2894
+ zremrangebylex = (...args) => this.chain(new ZRemRangeByLexCommand(args, this.commandOptions));
2895
+ zremrangebyrank = (...args) => this.chain(new ZRemRangeByRankCommand(args, this.commandOptions));
2896
+ zremrangebyscore = (...args) => this.chain(new ZRemRangeByScoreCommand(args, this.commandOptions));
2897
+ zrevrank = (key, member) => this.chain(new ZRevRankCommand([key, member], this.commandOptions));
2898
+ zscan = (...args) => this.chain(new ZScanCommand(args, this.commandOptions));
2899
+ zscore = (key, member) => this.chain(new ZScoreCommand([key, member], this.commandOptions));
2900
+ zunionstore = (...args) => this.chain(new ZUnionStoreCommand(args, this.commandOptions));
2901
+ zunion = (...args) => this.chain(new ZUnionCommand(args, this.commandOptions));
2902
+ get json() {
2903
+ return {
2904
+ arrappend: (...args) => this.chain(new JsonArrAppendCommand(args, this.commandOptions)),
2905
+ arrindex: (...args) => this.chain(new JsonArrIndexCommand(args, this.commandOptions)),
2906
+ arrinsert: (...args) => this.chain(new JsonArrInsertCommand(args, this.commandOptions)),
2907
+ arrlen: (...args) => this.chain(new JsonArrLenCommand(args, this.commandOptions)),
2908
+ arrpop: (...args) => this.chain(new JsonArrPopCommand(args, this.commandOptions)),
2909
+ arrtrim: (...args) => this.chain(new JsonArrTrimCommand(args, this.commandOptions)),
2910
+ clear: (...args) => this.chain(new JsonClearCommand(args, this.commandOptions)),
2911
+ del: (...args) => this.chain(new JsonDelCommand(args, this.commandOptions)),
2912
+ forget: (...args) => this.chain(new JsonForgetCommand(args, this.commandOptions)),
2913
+ get: (...args) => this.chain(new JsonGetCommand(args, this.commandOptions)),
2914
+ merge: (...args) => this.chain(new JsonMergeCommand(args, this.commandOptions)),
2915
+ mget: (...args) => this.chain(new JsonMGetCommand(args, this.commandOptions)),
2916
+ mset: (...args) => this.chain(new JsonMSetCommand(args, this.commandOptions)),
2917
+ numincrby: (...args) => this.chain(new JsonNumIncrByCommand(args, this.commandOptions)),
2918
+ nummultby: (...args) => this.chain(new JsonNumMultByCommand(args, this.commandOptions)),
2919
+ objkeys: (...args) => this.chain(new JsonObjKeysCommand(args, this.commandOptions)),
2920
+ objlen: (...args) => this.chain(new JsonObjLenCommand(args, this.commandOptions)),
2921
+ resp: (...args) => this.chain(new JsonRespCommand(args, this.commandOptions)),
2922
+ set: (...args) => this.chain(new JsonSetCommand(args, this.commandOptions)),
2923
+ strappend: (...args) => this.chain(new JsonStrAppendCommand(args, this.commandOptions)),
2924
+ strlen: (...args) => this.chain(new JsonStrLenCommand(args, this.commandOptions)),
2925
+ toggle: (...args) => this.chain(new JsonToggleCommand(args, this.commandOptions)),
2926
+ type: (...args) => this.chain(new JsonTypeCommand(args, this.commandOptions))
2927
+ };
2928
+ }
2929
+ get functions() {
2930
+ return {
2931
+ load: (...args) => this.chain(new FunctionLoadCommand(args, this.commandOptions)),
2932
+ list: (...args) => this.chain(new FunctionListCommand(args, this.commandOptions)),
2933
+ delete: (...args) => this.chain(new FunctionDeleteCommand(args, this.commandOptions)),
2934
+ flush: () => this.chain(new FunctionFlushCommand(this.commandOptions)),
2935
+ stats: () => this.chain(new FunctionStatsCommand(this.commandOptions)),
2936
+ call: (...args) => this.chain(new FCallCommand(args, this.commandOptions)),
2937
+ callRo: (...args) => this.chain(new FCallRoCommand(args, this.commandOptions))
2938
+ };
2939
+ }
2940
+ };
2941
+ var EXCLUDE_COMMANDS = /* @__PURE__ */ new Set([
2942
+ "scan",
2943
+ "keys",
2944
+ "flushdb",
2945
+ "flushall",
2946
+ "dbsize",
2947
+ "hscan",
2948
+ "hgetall",
2949
+ "hkeys",
2950
+ "lrange",
2951
+ "sscan",
2952
+ "smembers",
2953
+ "xrange",
2954
+ "xrevrange",
2955
+ "zscan",
2956
+ "zrange",
2957
+ "exec"
2958
+ ]);
2959
+ function createAutoPipelineProxy(_redis, namespace = "root") {
2960
+ const redis = _redis;
2961
+ if (!redis.autoPipelineExecutor) {
2962
+ redis.autoPipelineExecutor = new AutoPipelineExecutor(redis);
2963
+ }
2964
+ return new Proxy(redis, {
2965
+ get: (redis2, command) => {
2966
+ if (command === "pipelineCounter") {
2967
+ return redis2.autoPipelineExecutor.pipelineCounter;
2968
+ }
2969
+ if (namespace === "root" && command === "json") {
2970
+ return createAutoPipelineProxy(redis2, "json");
2971
+ }
2972
+ if (namespace === "root" && command === "functions") {
2973
+ return createAutoPipelineProxy(redis2, "functions");
2974
+ }
2975
+ if (namespace === "root") {
2976
+ const commandInRedisButNotPipeline = command in redis2 && !(command in redis2.autoPipelineExecutor.pipeline);
2977
+ const isCommandExcluded = EXCLUDE_COMMANDS.has(command);
2978
+ if (commandInRedisButNotPipeline || isCommandExcluded) {
2979
+ return redis2[command];
2980
+ }
2981
+ }
2982
+ const pipeline = redis2.autoPipelineExecutor.pipeline;
2983
+ const targetFunction = namespace === "json" ? pipeline.json[command] : namespace === "functions" ? pipeline.functions[command] : pipeline[command];
2984
+ const isFunction = typeof targetFunction === "function";
2985
+ if (isFunction) {
2986
+ return (...args) => {
2987
+ return redis2.autoPipelineExecutor.withAutoPipeline((pipeline2) => {
2988
+ const targetFunction2 = namespace === "json" ? pipeline2.json[command] : namespace === "functions" ? pipeline2.functions[command] : pipeline2[command];
2989
+ targetFunction2(...args);
2990
+ });
2991
+ };
2992
+ }
2993
+ return targetFunction;
2994
+ }
2995
+ });
2996
+ }
2997
+ var AutoPipelineExecutor = class {
2998
+ pipelinePromises = /* @__PURE__ */ new WeakMap;
2999
+ activePipeline = null;
3000
+ indexInCurrentPipeline = 0;
3001
+ redis;
3002
+ pipeline;
3003
+ pipelineCounter = 0;
3004
+ constructor(redis) {
3005
+ this.redis = redis;
3006
+ this.pipeline = redis.pipeline();
3007
+ }
3008
+ async withAutoPipeline(executeWithPipeline) {
3009
+ const pipeline = this.activePipeline ?? this.redis.pipeline();
3010
+ if (!this.activePipeline) {
3011
+ this.activePipeline = pipeline;
3012
+ this.indexInCurrentPipeline = 0;
3013
+ }
3014
+ const index = this.indexInCurrentPipeline++;
3015
+ executeWithPipeline(pipeline);
3016
+ const pipelineDone = this.deferExecution().then(() => {
3017
+ if (!this.pipelinePromises.has(pipeline)) {
3018
+ const pipelinePromise = pipeline.exec({ keepErrors: true });
3019
+ this.pipelineCounter += 1;
3020
+ this.pipelinePromises.set(pipeline, pipelinePromise);
3021
+ this.activePipeline = null;
3022
+ }
3023
+ return this.pipelinePromises.get(pipeline);
3024
+ });
3025
+ const results = await pipelineDone;
3026
+ const commandResult = results[index];
3027
+ if (commandResult.error) {
3028
+ throw new UpstashError(`Command failed: ${commandResult.error}`);
3029
+ }
3030
+ return commandResult.result;
3031
+ }
3032
+ async deferExecution() {
3033
+ await Promise.resolve();
3034
+ await Promise.resolve();
3035
+ }
3036
+ };
3037
+ var PSubscribeCommand = class extends Command {
3038
+ constructor(cmd, opts) {
3039
+ const sseHeaders = {
3040
+ Accept: "text/event-stream",
3041
+ "Cache-Control": "no-cache",
3042
+ Connection: "keep-alive"
3043
+ };
3044
+ super([], {
3045
+ ...opts,
3046
+ headers: sseHeaders,
3047
+ path: ["psubscribe", ...cmd],
3048
+ streamOptions: {
3049
+ isStreaming: true,
3050
+ onMessage: opts?.streamOptions?.onMessage,
3051
+ signal: opts?.streamOptions?.signal
3052
+ }
3053
+ });
3054
+ }
3055
+ };
3056
+ var Subscriber = class extends EventTarget {
3057
+ subscriptions;
3058
+ client;
3059
+ listeners;
3060
+ opts;
3061
+ constructor(client, channels, isPattern = false, opts) {
3062
+ super();
3063
+ this.client = client;
3064
+ this.subscriptions = /* @__PURE__ */ new Map;
3065
+ this.listeners = /* @__PURE__ */ new Map;
3066
+ this.opts = opts;
3067
+ for (const channel of channels) {
3068
+ if (isPattern) {
3069
+ this.subscribeToPattern(channel);
3070
+ } else {
3071
+ this.subscribeToChannel(channel);
3072
+ }
3073
+ }
3074
+ }
3075
+ subscribeToChannel(channel) {
3076
+ const controller = new AbortController;
3077
+ const command = new SubscribeCommand([channel], {
3078
+ streamOptions: {
3079
+ signal: controller.signal,
3080
+ onMessage: (data) => this.handleMessage(data, false)
3081
+ }
3082
+ });
3083
+ command.exec(this.client).catch((error) => {
3084
+ if (error.name !== "AbortError") {
3085
+ this.dispatchToListeners("error", error);
3086
+ }
3087
+ });
3088
+ this.subscriptions.set(channel, {
3089
+ command,
3090
+ controller,
3091
+ isPattern: false
3092
+ });
3093
+ }
3094
+ subscribeToPattern(pattern) {
3095
+ const controller = new AbortController;
3096
+ const command = new PSubscribeCommand([pattern], {
3097
+ streamOptions: {
3098
+ signal: controller.signal,
3099
+ onMessage: (data) => this.handleMessage(data, true)
3100
+ }
3101
+ });
3102
+ command.exec(this.client).catch((error) => {
3103
+ if (error.name !== "AbortError") {
3104
+ this.dispatchToListeners("error", error);
3105
+ }
3106
+ });
3107
+ this.subscriptions.set(pattern, {
3108
+ command,
3109
+ controller,
3110
+ isPattern: true
3111
+ });
3112
+ }
3113
+ handleMessage(data, isPattern) {
3114
+ const messageData = data.replace(/^data:\s*/, "");
3115
+ const firstCommaIndex = messageData.indexOf(",");
3116
+ const secondCommaIndex = messageData.indexOf(",", firstCommaIndex + 1);
3117
+ const thirdCommaIndex = isPattern ? messageData.indexOf(",", secondCommaIndex + 1) : -1;
3118
+ if (firstCommaIndex !== -1 && secondCommaIndex !== -1) {
3119
+ const type = messageData.slice(0, firstCommaIndex);
3120
+ if (isPattern && type === "pmessage" && thirdCommaIndex !== -1) {
3121
+ const pattern = messageData.slice(firstCommaIndex + 1, secondCommaIndex);
3122
+ const channel = messageData.slice(secondCommaIndex + 1, thirdCommaIndex);
3123
+ const messageStr = messageData.slice(thirdCommaIndex + 1);
3124
+ try {
3125
+ const message = this.opts?.automaticDeserialization === false ? messageStr : JSON.parse(messageStr);
3126
+ this.dispatchToListeners("pmessage", { pattern, channel, message });
3127
+ this.dispatchToListeners(`pmessage:${pattern}`, { pattern, channel, message });
3128
+ } catch (error) {
3129
+ this.dispatchToListeners("error", new Error(`Failed to parse message: ${error}`));
3130
+ }
3131
+ } else {
3132
+ const channel = messageData.slice(firstCommaIndex + 1, secondCommaIndex);
3133
+ const messageStr = messageData.slice(secondCommaIndex + 1);
3134
+ try {
3135
+ if (type === "subscribe" || type === "psubscribe" || type === "unsubscribe" || type === "punsubscribe") {
3136
+ const count = Number.parseInt(messageStr);
3137
+ this.dispatchToListeners(type, count);
3138
+ } else {
3139
+ const message = this.opts?.automaticDeserialization === false ? messageStr : parseWithTryCatch(messageStr);
3140
+ this.dispatchToListeners(type, { channel, message });
3141
+ this.dispatchToListeners(`${type}:${channel}`, { channel, message });
3142
+ }
3143
+ } catch (error) {
3144
+ this.dispatchToListeners("error", new Error(`Failed to parse message: ${error}`));
3145
+ }
3146
+ }
3147
+ }
3148
+ }
3149
+ dispatchToListeners(type, data) {
3150
+ const listeners = this.listeners.get(type);
3151
+ if (listeners) {
3152
+ for (const listener of listeners) {
3153
+ listener(data);
3154
+ }
3155
+ }
3156
+ }
3157
+ on(type, listener) {
3158
+ if (!this.listeners.has(type)) {
3159
+ this.listeners.set(type, /* @__PURE__ */ new Set);
3160
+ }
3161
+ this.listeners.get(type)?.add(listener);
3162
+ }
3163
+ removeAllListeners() {
3164
+ this.listeners.clear();
3165
+ }
3166
+ async unsubscribe(channels) {
3167
+ if (channels) {
3168
+ for (const channel of channels) {
3169
+ const subscription = this.subscriptions.get(channel);
3170
+ if (subscription) {
3171
+ try {
3172
+ subscription.controller.abort();
3173
+ } catch {}
3174
+ this.subscriptions.delete(channel);
3175
+ }
3176
+ }
3177
+ } else {
3178
+ for (const subscription of this.subscriptions.values()) {
3179
+ try {
3180
+ subscription.controller.abort();
3181
+ } catch {}
3182
+ }
3183
+ this.subscriptions.clear();
3184
+ this.removeAllListeners();
3185
+ }
3186
+ }
3187
+ getSubscribedChannels() {
3188
+ return [...this.subscriptions.keys()];
3189
+ }
3190
+ };
3191
+ var SubscribeCommand = class extends Command {
3192
+ constructor(cmd, opts) {
3193
+ const sseHeaders = {
3194
+ Accept: "text/event-stream",
3195
+ "Cache-Control": "no-cache",
3196
+ Connection: "keep-alive"
3197
+ };
3198
+ super([], {
3199
+ ...opts,
3200
+ headers: sseHeaders,
3201
+ path: ["subscribe", ...cmd],
3202
+ streamOptions: {
3203
+ isStreaming: true,
3204
+ onMessage: opts?.streamOptions?.onMessage,
3205
+ signal: opts?.streamOptions?.signal
3206
+ }
3207
+ });
3208
+ }
3209
+ };
3210
+ var parseWithTryCatch = (str) => {
3211
+ try {
3212
+ return JSON.parse(str);
3213
+ } catch {
3214
+ return str;
3215
+ }
3216
+ };
3217
+ var Script = class {
3218
+ script;
3219
+ sha1;
3220
+ initPromise;
3221
+ redis;
3222
+ constructor(redis, script) {
3223
+ this.redis = redis;
3224
+ this.script = script;
3225
+ this.sha1 = "";
3226
+ this.init(script);
3227
+ }
3228
+ init(script) {
3229
+ if (!this.initPromise) {
3230
+ this.initPromise = this.digest(script).then((sha1) => {
3231
+ this.sha1 = sha1;
3232
+ });
3233
+ }
3234
+ return this.initPromise;
3235
+ }
3236
+ async eval(keys, args) {
3237
+ await this.init(this.script);
3238
+ return await this.redis.eval(this.script, keys, args);
3239
+ }
3240
+ async evalsha(keys, args) {
3241
+ await this.init(this.script);
3242
+ return await this.redis.evalsha(this.sha1, keys, args);
3243
+ }
3244
+ async exec(keys, args) {
3245
+ await this.init(this.script);
3246
+ const res = await this.redis.evalsha(this.sha1, keys, args).catch(async (error) => {
3247
+ if (error instanceof Error && error.message.toLowerCase().includes("noscript")) {
3248
+ return await this.redis.eval(this.script, keys, args);
3249
+ }
3250
+ throw error;
3251
+ });
3252
+ return res;
3253
+ }
3254
+ async digest(s) {
3255
+ const data = new TextEncoder().encode(s);
3256
+ const hashBuffer = await subtle.digest("SHA-1", data);
3257
+ const hashArray = [...new Uint8Array(hashBuffer)];
3258
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
3259
+ }
3260
+ };
3261
+ var ScriptRO = class {
3262
+ script;
3263
+ sha1;
3264
+ initPromise;
3265
+ redis;
3266
+ constructor(redis, script) {
3267
+ this.redis = redis;
3268
+ this.sha1 = "";
3269
+ this.script = script;
3270
+ this.init(script);
3271
+ }
3272
+ init(script) {
3273
+ if (!this.initPromise) {
3274
+ this.initPromise = this.digest(script).then((sha1) => {
3275
+ this.sha1 = sha1;
3276
+ });
3277
+ }
3278
+ return this.initPromise;
3279
+ }
3280
+ async evalRo(keys, args) {
3281
+ await this.init(this.script);
3282
+ return await this.redis.evalRo(this.script, keys, args);
3283
+ }
3284
+ async evalshaRo(keys, args) {
3285
+ await this.init(this.script);
3286
+ return await this.redis.evalshaRo(this.sha1, keys, args);
3287
+ }
3288
+ async exec(keys, args) {
3289
+ await this.init(this.script);
3290
+ const res = await this.redis.evalshaRo(this.sha1, keys, args).catch(async (error) => {
3291
+ if (error instanceof Error && error.message.toLowerCase().includes("noscript")) {
3292
+ return await this.redis.evalRo(this.script, keys, args);
3293
+ }
3294
+ throw error;
3295
+ });
3296
+ return res;
3297
+ }
3298
+ async digest(s) {
3299
+ const data = new TextEncoder().encode(s);
3300
+ const hashBuffer = await subtle.digest("SHA-1", data);
3301
+ const hashArray = [...new Uint8Array(hashBuffer)];
3302
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
3303
+ }
3304
+ };
3305
+ var Redis = class {
3306
+ client;
3307
+ opts;
3308
+ enableTelemetry;
3309
+ enableAutoPipelining;
3310
+ constructor(client, opts) {
3311
+ this.client = client;
3312
+ this.opts = opts;
3313
+ this.enableTelemetry = opts?.enableTelemetry ?? true;
3314
+ if (opts?.readYourWrites === false) {
3315
+ this.client.readYourWrites = false;
3316
+ }
3317
+ this.enableAutoPipelining = opts?.enableAutoPipelining ?? true;
3318
+ }
3319
+ get readYourWritesSyncToken() {
3320
+ return this.client.upstashSyncToken;
3321
+ }
3322
+ set readYourWritesSyncToken(session) {
3323
+ this.client.upstashSyncToken = session;
3324
+ }
3325
+ get json() {
3326
+ return {
3327
+ arrappend: (...args) => new JsonArrAppendCommand(args, this.opts).exec(this.client),
3328
+ arrindex: (...args) => new JsonArrIndexCommand(args, this.opts).exec(this.client),
3329
+ arrinsert: (...args) => new JsonArrInsertCommand(args, this.opts).exec(this.client),
3330
+ arrlen: (...args) => new JsonArrLenCommand(args, this.opts).exec(this.client),
3331
+ arrpop: (...args) => new JsonArrPopCommand(args, this.opts).exec(this.client),
3332
+ arrtrim: (...args) => new JsonArrTrimCommand(args, this.opts).exec(this.client),
3333
+ clear: (...args) => new JsonClearCommand(args, this.opts).exec(this.client),
3334
+ del: (...args) => new JsonDelCommand(args, this.opts).exec(this.client),
3335
+ forget: (...args) => new JsonForgetCommand(args, this.opts).exec(this.client),
3336
+ get: (...args) => new JsonGetCommand(args, this.opts).exec(this.client),
3337
+ merge: (...args) => new JsonMergeCommand(args, this.opts).exec(this.client),
3338
+ mget: (...args) => new JsonMGetCommand(args, this.opts).exec(this.client),
3339
+ mset: (...args) => new JsonMSetCommand(args, this.opts).exec(this.client),
3340
+ numincrby: (...args) => new JsonNumIncrByCommand(args, this.opts).exec(this.client),
3341
+ nummultby: (...args) => new JsonNumMultByCommand(args, this.opts).exec(this.client),
3342
+ objkeys: (...args) => new JsonObjKeysCommand(args, this.opts).exec(this.client),
3343
+ objlen: (...args) => new JsonObjLenCommand(args, this.opts).exec(this.client),
3344
+ resp: (...args) => new JsonRespCommand(args, this.opts).exec(this.client),
3345
+ set: (...args) => new JsonSetCommand(args, this.opts).exec(this.client),
3346
+ strappend: (...args) => new JsonStrAppendCommand(args, this.opts).exec(this.client),
3347
+ strlen: (...args) => new JsonStrLenCommand(args, this.opts).exec(this.client),
3348
+ toggle: (...args) => new JsonToggleCommand(args, this.opts).exec(this.client),
3349
+ type: (...args) => new JsonTypeCommand(args, this.opts).exec(this.client)
3350
+ };
3351
+ }
3352
+ get functions() {
3353
+ return {
3354
+ load: (...args) => new FunctionLoadCommand(args, this.opts).exec(this.client),
3355
+ list: (...args) => new FunctionListCommand(args, this.opts).exec(this.client),
3356
+ delete: (...args) => new FunctionDeleteCommand(args, this.opts).exec(this.client),
3357
+ flush: () => new FunctionFlushCommand(this.opts).exec(this.client),
3358
+ stats: () => new FunctionStatsCommand(this.opts).exec(this.client),
3359
+ call: (...args) => new FCallCommand(args, this.opts).exec(this.client),
3360
+ callRo: (...args) => new FCallRoCommand(args, this.opts).exec(this.client)
3361
+ };
3362
+ }
3363
+ use = (middleware) => {
3364
+ const makeRequest = this.client.request.bind(this.client);
3365
+ this.client.request = (req) => middleware(req, makeRequest);
3366
+ };
3367
+ addTelemetry = (telemetry) => {
3368
+ if (!this.enableTelemetry) {
3369
+ return;
3370
+ }
3371
+ try {
3372
+ this.client.mergeTelemetry(telemetry);
3373
+ } catch {}
3374
+ };
3375
+ createScript(script, opts) {
3376
+ return opts?.readonly ? new ScriptRO(this, script) : new Script(this, script);
3377
+ }
3378
+ get search() {
3379
+ return {
3380
+ createIndex: (params) => {
3381
+ return createIndex(this.client, params);
3382
+ },
3383
+ index: (params) => {
3384
+ return initIndex(this.client, params);
3385
+ },
3386
+ alias: {
3387
+ list: () => {
3388
+ return listAliases(this.client);
3389
+ },
3390
+ add: ({ indexName, alias }) => {
3391
+ return addAlias(this.client, { indexName, alias });
3392
+ },
3393
+ delete: ({ alias }) => {
3394
+ return delAlias(this.client, { alias });
3395
+ }
3396
+ }
3397
+ };
3398
+ }
3399
+ pipeline = () => new Pipeline({
3400
+ client: this.client,
3401
+ commandOptions: this.opts,
3402
+ multiExec: false
3403
+ });
3404
+ autoPipeline = () => {
3405
+ return createAutoPipelineProxy(this);
3406
+ };
3407
+ multi = () => new Pipeline({
3408
+ client: this.client,
3409
+ commandOptions: this.opts,
3410
+ multiExec: true
3411
+ });
3412
+ bitfield = (...args) => new BitFieldCommand(args, this.client, this.opts);
3413
+ append = (...args) => new AppendCommand(args, this.opts).exec(this.client);
3414
+ bitcount = (...args) => new BitCountCommand(args, this.opts).exec(this.client);
3415
+ bitop = (op, destinationKey, sourceKey, ...sourceKeys) => new BitOpCommand([op, destinationKey, sourceKey, ...sourceKeys], this.opts).exec(this.client);
3416
+ bitpos = (...args) => new BitPosCommand(args, this.opts).exec(this.client);
3417
+ clientSetinfo = (...args) => new ClientSetInfoCommand(args, this.opts).exec(this.client);
3418
+ copy = (...args) => new CopyCommand(args, this.opts).exec(this.client);
3419
+ dbsize = () => new DBSizeCommand(this.opts).exec(this.client);
3420
+ decr = (...args) => new DecrCommand(args, this.opts).exec(this.client);
3421
+ decrby = (...args) => new DecrByCommand(args, this.opts).exec(this.client);
3422
+ del = (...args) => new DelCommand(args, this.opts).exec(this.client);
3423
+ echo = (...args) => new EchoCommand(args, this.opts).exec(this.client);
3424
+ evalRo = (...args) => new EvalROCommand(args, this.opts).exec(this.client);
3425
+ eval = (...args) => new EvalCommand(args, this.opts).exec(this.client);
3426
+ evalshaRo = (...args) => new EvalshaROCommand(args, this.opts).exec(this.client);
3427
+ evalsha = (...args) => new EvalshaCommand(args, this.opts).exec(this.client);
3428
+ exec = (args) => new ExecCommand(args, this.opts).exec(this.client);
3429
+ exists = (...args) => new ExistsCommand(args, this.opts).exec(this.client);
3430
+ expire = (...args) => new ExpireCommand(args, this.opts).exec(this.client);
3431
+ expireat = (...args) => new ExpireAtCommand(args, this.opts).exec(this.client);
3432
+ flushall = (args) => new FlushAllCommand(args, this.opts).exec(this.client);
3433
+ flushdb = (...args) => new FlushDBCommand(args, this.opts).exec(this.client);
3434
+ geoadd = (...args) => new GeoAddCommand(args, this.opts).exec(this.client);
3435
+ geopos = (...args) => new GeoPosCommand(args, this.opts).exec(this.client);
3436
+ geodist = (...args) => new GeoDistCommand(args, this.opts).exec(this.client);
3437
+ geohash = (...args) => new GeoHashCommand(args, this.opts).exec(this.client);
3438
+ geosearch = (...args) => new GeoSearchCommand(args, this.opts).exec(this.client);
3439
+ geosearchstore = (...args) => new GeoSearchStoreCommand(args, this.opts).exec(this.client);
3440
+ get = (...args) => new GetCommand(args, this.opts).exec(this.client);
3441
+ getbit = (...args) => new GetBitCommand(args, this.opts).exec(this.client);
3442
+ getdel = (...args) => new GetDelCommand(args, this.opts).exec(this.client);
3443
+ getex = (...args) => new GetExCommand(args, this.opts).exec(this.client);
3444
+ getrange = (...args) => new GetRangeCommand(args, this.opts).exec(this.client);
3445
+ getset = (key, value) => new GetSetCommand([key, value], this.opts).exec(this.client);
3446
+ hdel = (...args) => new HDelCommand(args, this.opts).exec(this.client);
3447
+ hexists = (...args) => new HExistsCommand(args, this.opts).exec(this.client);
3448
+ hexpire = (...args) => new HExpireCommand(args, this.opts).exec(this.client);
3449
+ hexpireat = (...args) => new HExpireAtCommand(args, this.opts).exec(this.client);
3450
+ hexpiretime = (...args) => new HExpireTimeCommand(args, this.opts).exec(this.client);
3451
+ httl = (...args) => new HTtlCommand(args, this.opts).exec(this.client);
3452
+ hpexpire = (...args) => new HPExpireCommand(args, this.opts).exec(this.client);
3453
+ hpexpireat = (...args) => new HPExpireAtCommand(args, this.opts).exec(this.client);
3454
+ hpexpiretime = (...args) => new HPExpireTimeCommand(args, this.opts).exec(this.client);
3455
+ hpttl = (...args) => new HPTtlCommand(args, this.opts).exec(this.client);
3456
+ hpersist = (...args) => new HPersistCommand(args, this.opts).exec(this.client);
3457
+ hget = (...args) => new HGetCommand(args, this.opts).exec(this.client);
3458
+ hgetall = (...args) => new HGetAllCommand(args, this.opts).exec(this.client);
3459
+ hgetdel = (...args) => new HGetDelCommand(args, this.opts).exec(this.client);
3460
+ hgetex = (...args) => new HGetExCommand(args, this.opts).exec(this.client);
3461
+ hincrby = (...args) => new HIncrByCommand(args, this.opts).exec(this.client);
3462
+ hincrbyfloat = (...args) => new HIncrByFloatCommand(args, this.opts).exec(this.client);
3463
+ hkeys = (...args) => new HKeysCommand(args, this.opts).exec(this.client);
3464
+ hlen = (...args) => new HLenCommand(args, this.opts).exec(this.client);
3465
+ hmget = (...args) => new HMGetCommand(args, this.opts).exec(this.client);
3466
+ hmset = (key, kv) => new HMSetCommand([key, kv], this.opts).exec(this.client);
3467
+ hrandfield = (key, count, withValues) => new HRandFieldCommand([key, count, withValues], this.opts).exec(this.client);
3468
+ hscan = (...args) => new HScanCommand(args, this.opts).exec(this.client);
3469
+ hset = (key, kv) => new HSetCommand([key, kv], this.opts).exec(this.client);
3470
+ hsetex = (...args) => new HSetExCommand(args, this.opts).exec(this.client);
3471
+ hsetnx = (key, field, value) => new HSetNXCommand([key, field, value], this.opts).exec(this.client);
3472
+ hstrlen = (...args) => new HStrLenCommand(args, this.opts).exec(this.client);
3473
+ hvals = (...args) => new HValsCommand(args, this.opts).exec(this.client);
3474
+ incr = (...args) => new IncrCommand(args, this.opts).exec(this.client);
3475
+ incrby = (...args) => new IncrByCommand(args, this.opts).exec(this.client);
3476
+ incrbyfloat = (...args) => new IncrByFloatCommand(args, this.opts).exec(this.client);
3477
+ keys = (...args) => new KeysCommand(args, this.opts).exec(this.client);
3478
+ lindex = (...args) => new LIndexCommand(args, this.opts).exec(this.client);
3479
+ linsert = (key, direction, pivot, value) => new LInsertCommand([key, direction, pivot, value], this.opts).exec(this.client);
3480
+ llen = (...args) => new LLenCommand(args, this.opts).exec(this.client);
3481
+ lmove = (...args) => new LMoveCommand(args, this.opts).exec(this.client);
3482
+ lpop = (...args) => new LPopCommand(args, this.opts).exec(this.client);
3483
+ lmpop = (...args) => new LmPopCommand(args, this.opts).exec(this.client);
3484
+ lpos = (...args) => new LPosCommand(args, this.opts).exec(this.client);
3485
+ lpush = (key, ...elements) => new LPushCommand([key, ...elements], this.opts).exec(this.client);
3486
+ lpushx = (key, ...elements) => new LPushXCommand([key, ...elements], this.opts).exec(this.client);
3487
+ lrange = (...args) => new LRangeCommand(args, this.opts).exec(this.client);
3488
+ lrem = (key, count, value) => new LRemCommand([key, count, value], this.opts).exec(this.client);
3489
+ lset = (key, index, value) => new LSetCommand([key, index, value], this.opts).exec(this.client);
3490
+ ltrim = (...args) => new LTrimCommand(args, this.opts).exec(this.client);
3491
+ mget = (...args) => new MGetCommand(args, this.opts).exec(this.client);
3492
+ mset = (kv) => new MSetCommand([kv], this.opts).exec(this.client);
3493
+ msetnx = (kv) => new MSetNXCommand([kv], this.opts).exec(this.client);
3494
+ persist = (...args) => new PersistCommand(args, this.opts).exec(this.client);
3495
+ pexpire = (...args) => new PExpireCommand(args, this.opts).exec(this.client);
3496
+ pexpireat = (...args) => new PExpireAtCommand(args, this.opts).exec(this.client);
3497
+ pfadd = (...args) => new PfAddCommand(args, this.opts).exec(this.client);
3498
+ pfcount = (...args) => new PfCountCommand(args, this.opts).exec(this.client);
3499
+ pfmerge = (...args) => new PfMergeCommand(args, this.opts).exec(this.client);
3500
+ ping = (args) => new PingCommand(args, this.opts).exec(this.client);
3501
+ psetex = (key, ttl, value) => new PSetEXCommand([key, ttl, value], this.opts).exec(this.client);
3502
+ psubscribe = (patterns) => {
3503
+ const patternArray = Array.isArray(patterns) ? patterns : [patterns];
3504
+ return new Subscriber(this.client, patternArray, true, this.opts);
3505
+ };
3506
+ pttl = (...args) => new PTtlCommand(args, this.opts).exec(this.client);
3507
+ publish = (...args) => new PublishCommand(args, this.opts).exec(this.client);
3508
+ randomkey = () => new RandomKeyCommand().exec(this.client);
3509
+ rename = (...args) => new RenameCommand(args, this.opts).exec(this.client);
3510
+ renamenx = (...args) => new RenameNXCommand(args, this.opts).exec(this.client);
3511
+ rpop = (...args) => new RPopCommand(args, this.opts).exec(this.client);
3512
+ rpush = (key, ...elements) => new RPushCommand([key, ...elements], this.opts).exec(this.client);
3513
+ rpushx = (key, ...elements) => new RPushXCommand([key, ...elements], this.opts).exec(this.client);
3514
+ sadd = (key, member, ...members) => new SAddCommand([key, member, ...members], this.opts).exec(this.client);
3515
+ scan(cursor, opts) {
3516
+ return new ScanCommand([cursor, opts], this.opts).exec(this.client);
3517
+ }
3518
+ scard = (...args) => new SCardCommand(args, this.opts).exec(this.client);
3519
+ scriptExists = (...args) => new ScriptExistsCommand(args, this.opts).exec(this.client);
3520
+ scriptFlush = (...args) => new ScriptFlushCommand(args, this.opts).exec(this.client);
3521
+ scriptLoad = (...args) => new ScriptLoadCommand(args, this.opts).exec(this.client);
3522
+ sdiff = (...args) => new SDiffCommand(args, this.opts).exec(this.client);
3523
+ sdiffstore = (...args) => new SDiffStoreCommand(args, this.opts).exec(this.client);
3524
+ set = (key, value, opts) => new SetCommand([key, value, opts], this.opts).exec(this.client);
3525
+ setbit = (...args) => new SetBitCommand(args, this.opts).exec(this.client);
3526
+ setex = (key, ttl, value) => new SetExCommand([key, ttl, value], this.opts).exec(this.client);
3527
+ setnx = (key, value) => new SetNxCommand([key, value], this.opts).exec(this.client);
3528
+ setrange = (...args) => new SetRangeCommand(args, this.opts).exec(this.client);
3529
+ sinter = (...args) => new SInterCommand(args, this.opts).exec(this.client);
3530
+ sintercard = (...args) => new SInterCardCommand(args, this.opts).exec(this.client);
3531
+ sinterstore = (...args) => new SInterStoreCommand(args, this.opts).exec(this.client);
3532
+ sismember = (key, member) => new SIsMemberCommand([key, member], this.opts).exec(this.client);
3533
+ smismember = (key, members) => new SMIsMemberCommand([key, members], this.opts).exec(this.client);
3534
+ smembers = (...args) => new SMembersCommand(args, this.opts).exec(this.client);
3535
+ smove = (source, destination, member) => new SMoveCommand([source, destination, member], this.opts).exec(this.client);
3536
+ spop = (...args) => new SPopCommand(args, this.opts).exec(this.client);
3537
+ srandmember = (...args) => new SRandMemberCommand(args, this.opts).exec(this.client);
3538
+ srem = (key, ...members) => new SRemCommand([key, ...members], this.opts).exec(this.client);
3539
+ sscan = (...args) => new SScanCommand(args, this.opts).exec(this.client);
3540
+ strlen = (...args) => new StrLenCommand(args, this.opts).exec(this.client);
3541
+ subscribe = (channels) => {
3542
+ const channelArray = Array.isArray(channels) ? channels : [channels];
3543
+ return new Subscriber(this.client, channelArray, false, this.opts);
3544
+ };
3545
+ sunion = (...args) => new SUnionCommand(args, this.opts).exec(this.client);
3546
+ sunionstore = (...args) => new SUnionStoreCommand(args, this.opts).exec(this.client);
3547
+ time = () => new TimeCommand().exec(this.client);
3548
+ touch = (...args) => new TouchCommand(args, this.opts).exec(this.client);
3549
+ ttl = (...args) => new TtlCommand(args, this.opts).exec(this.client);
3550
+ type = (...args) => new TypeCommand(args, this.opts).exec(this.client);
3551
+ unlink = (...args) => new UnlinkCommand(args, this.opts).exec(this.client);
3552
+ xadd = (...args) => new XAddCommand(args, this.opts).exec(this.client);
3553
+ xack = (...args) => new XAckCommand(args, this.opts).exec(this.client);
3554
+ xackdel = (...args) => new XAckDelCommand(args, this.opts).exec(this.client);
3555
+ xdel = (...args) => new XDelCommand(args, this.opts).exec(this.client);
3556
+ xdelex = (...args) => new XDelExCommand(args, this.opts).exec(this.client);
3557
+ xgroup = (...args) => new XGroupCommand(args, this.opts).exec(this.client);
3558
+ xread = (...args) => new XReadCommand(args, this.opts).exec(this.client);
3559
+ xreadgroup = (...args) => new XReadGroupCommand(args, this.opts).exec(this.client);
3560
+ xinfo = (...args) => new XInfoCommand(args, this.opts).exec(this.client);
3561
+ xlen = (...args) => new XLenCommand(args, this.opts).exec(this.client);
3562
+ xpending = (...args) => new XPendingCommand(args, this.opts).exec(this.client);
3563
+ xclaim = (...args) => new XClaimCommand(args, this.opts).exec(this.client);
3564
+ xautoclaim = (...args) => new XAutoClaim(args, this.opts).exec(this.client);
3565
+ xtrim = (...args) => new XTrimCommand(args, this.opts).exec(this.client);
3566
+ xrange = (...args) => new XRangeCommand(args, this.opts).exec(this.client);
3567
+ xrevrange = (...args) => new XRevRangeCommand(args, this.opts).exec(this.client);
3568
+ zadd = (...args) => {
3569
+ if ("score" in args[1]) {
3570
+ return new ZAddCommand([args[0], args[1], ...args.slice(2)], this.opts).exec(this.client);
3571
+ }
3572
+ return new ZAddCommand([args[0], args[1], ...args.slice(2)], this.opts).exec(this.client);
3573
+ };
3574
+ zcard = (...args) => new ZCardCommand(args, this.opts).exec(this.client);
3575
+ zcount = (...args) => new ZCountCommand(args, this.opts).exec(this.client);
3576
+ zdiffstore = (...args) => new ZDiffStoreCommand(args, this.opts).exec(this.client);
3577
+ zincrby = (key, increment, member) => new ZIncrByCommand([key, increment, member], this.opts).exec(this.client);
3578
+ zinterstore = (...args) => new ZInterStoreCommand(args, this.opts).exec(this.client);
3579
+ zlexcount = (...args) => new ZLexCountCommand(args, this.opts).exec(this.client);
3580
+ zmscore = (...args) => new ZMScoreCommand(args, this.opts).exec(this.client);
3581
+ zpopmax = (...args) => new ZPopMaxCommand(args, this.opts).exec(this.client);
3582
+ zpopmin = (...args) => new ZPopMinCommand(args, this.opts).exec(this.client);
3583
+ zrange = (...args) => new ZRangeCommand(args, this.opts).exec(this.client);
3584
+ zrank = (key, member) => new ZRankCommand([key, member], this.opts).exec(this.client);
3585
+ zrem = (key, ...members) => new ZRemCommand([key, ...members], this.opts).exec(this.client);
3586
+ zremrangebylex = (...args) => new ZRemRangeByLexCommand(args, this.opts).exec(this.client);
3587
+ zremrangebyrank = (...args) => new ZRemRangeByRankCommand(args, this.opts).exec(this.client);
3588
+ zremrangebyscore = (...args) => new ZRemRangeByScoreCommand(args, this.opts).exec(this.client);
3589
+ zrevrank = (key, member) => new ZRevRankCommand([key, member], this.opts).exec(this.client);
3590
+ zscan = (...args) => new ZScanCommand(args, this.opts).exec(this.client);
3591
+ zscore = (key, member) => new ZScoreCommand([key, member], this.opts).exec(this.client);
3592
+ zunion = (...args) => new ZUnionCommand(args, this.opts).exec(this.client);
3593
+ zunionstore = (...args) => new ZUnionStoreCommand(args, this.opts).exec(this.client);
3594
+ };
3595
+ var VERSION = "v1.30.2";
3596
+
3597
+ // ../../node_modules/.bun/@upstash+redis@1.37.0/node_modules/@upstash/redis/nodejs.mjs
3598
+ if (typeof atob === "undefined") {
3599
+ global.atob = (b64) => Buffer.from(b64, "base64").toString("utf8");
3600
+ }
3601
+ var Redis2 = class _Redis extends Redis {
3602
+ constructor(configOrRequester) {
3603
+ if ("request" in configOrRequester) {
3604
+ super(configOrRequester);
3605
+ return;
3606
+ }
3607
+ if (!configOrRequester.url) {} else if (configOrRequester.url.startsWith(" ") || configOrRequester.url.endsWith(" ") || /\r|\n/.test(configOrRequester.url)) {}
3608
+ if (!configOrRequester.token) {} else if (configOrRequester.token.startsWith(" ") || configOrRequester.token.endsWith(" ") || /\r|\n/.test(configOrRequester.token)) {}
3609
+ const client = new HttpClient({
3610
+ baseUrl: configOrRequester.url,
3611
+ retry: configOrRequester.retry,
3612
+ headers: { authorization: `Bearer ${configOrRequester.token}` },
3613
+ agent: configOrRequester.agent,
3614
+ responseEncoding: configOrRequester.responseEncoding,
3615
+ cache: configOrRequester.cache ?? "no-store",
3616
+ signal: configOrRequester.signal,
3617
+ keepAlive: configOrRequester.keepAlive,
3618
+ readYourWrites: configOrRequester.readYourWrites
3619
+ });
3620
+ const safeEnv = typeof process === "object" && process && typeof process.env === "object" && process.env ? process.env : {};
3621
+ super(client, {
3622
+ automaticDeserialization: configOrRequester.automaticDeserialization,
3623
+ enableTelemetry: configOrRequester.enableTelemetry ?? !safeEnv.UPSTASH_DISABLE_TELEMETRY,
3624
+ latencyLogging: configOrRequester.latencyLogging,
3625
+ enableAutoPipelining: configOrRequester.enableAutoPipelining
3626
+ });
3627
+ const nodeVersion = typeof process === "object" && process ? process.version : undefined;
3628
+ this.addTelemetry({
3629
+ runtime: typeof EdgeRuntime === "string" ? "edge-light" : nodeVersion ? `node@${nodeVersion}` : "unknown",
3630
+ platform: safeEnv.UPSTASH_CONSOLE ? "console" : safeEnv.VERCEL ? "vercel" : safeEnv.AWS_REGION ? "aws" : "unknown",
3631
+ sdk: `@upstash/redis@${VERSION}`
3632
+ });
3633
+ if (this.enableAutoPipelining) {
3634
+ return this.autoPipeline();
3635
+ }
3636
+ }
3637
+ static fromEnv(config) {
3638
+ if (typeof process !== "object" || !process || typeof process.env !== "object" || !process.env) {
3639
+ throw new TypeError('[Upstash Redis] Unable to get environment variables, `process.env` is undefined. If you are deploying to cloudflare, please import from "@upstash/redis/cloudflare" instead');
3640
+ }
3641
+ const url = process.env.UPSTASH_REDIS_REST_URL || process.env.KV_REST_API_URL;
3642
+ if (!url) {}
3643
+ const token = process.env.UPSTASH_REDIS_REST_TOKEN || process.env.KV_REST_API_TOKEN;
3644
+ if (!token) {}
3645
+ return new _Redis({ ...config, url, token });
3646
+ }
3647
+ };
3648
+
3649
+ // src/UpstashRedisRateLimiter.ts
3650
+ class UpstashRedisRateLimiter {
3651
+ env;
3652
+ ratelimit;
3653
+ static DEFAULT_ALGORITHM = {
3654
+ type: "slidingWindow",
3655
+ limit: 120,
3656
+ window: "60 s"
3657
+ };
3658
+ constructor(env, options = {}) {
3659
+ this.env = env;
3660
+ const url = options.url || this.env.RATE_LIMIT_UPSTASH_REDIS_URL;
3661
+ const token = options.token || this.env.RATE_LIMIT_UPSTASH_REDIS_TOKEN;
3662
+ if (!url || !token) {
3663
+ throw new RateLimitException("Upstash Redis URL and token are required. Please provide them through the constructor options or set the RATE_LIMIT_UPSTASH_REDIS_URL and RATE_LIMIT_UPSTASH_REDIS_TOKEN environment variables.", "RATE_LIMIT_CONNECTION_FAILED");
3664
+ }
3665
+ const redis = new Redis2({ url, token });
3666
+ const limiter = this.buildLimiter(options.algorithm);
3667
+ this.ratelimit = new Ratelimit({
3668
+ redis,
3669
+ limiter,
3670
+ prefix: options.prefix ?? "@ooneex/ratelimit",
3671
+ analytics: options.analytics ?? true
3672
+ });
3673
+ }
3674
+ buildLimiter(algorithm = UpstashRedisRateLimiter.DEFAULT_ALGORITHM) {
3675
+ switch (algorithm.type) {
3676
+ case "fixedWindow":
3677
+ return Ratelimit.fixedWindow(algorithm.limit, algorithm.window);
3678
+ case "slidingWindow":
3679
+ return Ratelimit.slidingWindow(algorithm.limit, algorithm.window);
3680
+ case "tokenBucket":
3681
+ return Ratelimit.tokenBucket(algorithm.refillRate, algorithm.interval, algorithm.maxTokens);
3682
+ }
3683
+ }
3684
+ async check(key) {
3685
+ try {
3686
+ const result = await this.ratelimit.limit(key);
3687
+ return {
3688
+ limited: !result.success,
3689
+ remaining: result.remaining,
3690
+ total: result.limit,
3691
+ resetAt: new Date(result.reset)
3692
+ };
3693
+ } catch (error) {
3694
+ throw new RateLimitException(`Failed to check rate limit for key "${key}": ${error}`, "RATE_LIMIT_CHECK_FAILED");
3695
+ }
3696
+ }
3697
+ async isLimited(key) {
3698
+ const result = await this.check(key);
3699
+ return result.limited;
3700
+ }
3701
+ async reset(key) {
3702
+ try {
3703
+ await this.ratelimit.resetUsedTokens(key);
3704
+ return true;
3705
+ } catch (error) {
3706
+ throw new RateLimitException(`Failed to reset rate limit for key "${key}": ${error}`, "RATE_LIMIT_RESET_FAILED");
3707
+ }
3708
+ }
3709
+ async getCount(key) {
3710
+ try {
3711
+ const { remaining } = await this.ratelimit.getRemaining(key);
3712
+ return remaining;
3713
+ } catch (error) {
3714
+ throw new RateLimitException(`Failed to get count for key "${key}": ${error}`, "RATE_LIMIT_COUNT_FAILED");
3715
+ }
3716
+ }
3717
+ }
3718
+ UpstashRedisRateLimiter = __legacyDecorateClassTS([
3719
+ decorator.rateLimit(),
3720
+ __legacyDecorateParamTS(0, inject2(AppEnv2)),
3721
+ __legacyMetadataTS("design:paramtypes", [
3722
+ typeof AppEnv2 === "undefined" ? Object : AppEnv2,
3723
+ typeof UpstashRedisRateLimiterOptionsType === "undefined" ? Object : UpstashRedisRateLimiterOptionsType
3724
+ ])
3725
+ ], UpstashRedisRateLimiter);
115
3726
  export {
3727
+ decorator,
3728
+ UpstashRedisRateLimiter,
116
3729
  RedisRateLimiter,
117
3730
  RateLimitException
118
3731
  };
119
3732
 
120
- //# debugId=66919C914CDF5FD864756E2164756E21
3733
+ //# debugId=6B308BC01FD0CA0B64756E2164756E21