require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 722: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // platforms/nodejs.ts var nodejs_exports = {}; __export(nodejs_exports, { Redis: () => Redis2, errors: () => error_exports }); module.exports = __toCommonJS(nodejs_exports); // pkg/error.ts var error_exports = {}; __export(error_exports, { UpstashError: () => UpstashError, UrlError: () => UrlError }); var UpstashError = class extends Error { constructor(message) { super(message); this.name = "UpstashError"; } }; var UrlError = class extends Error { constructor(url) { super( `Upstash Redis client was passed an invalid URL. You should pass a URL starting with https. Received: "${url}". ` ); this.name = "UrlError"; } }; // pkg/http.ts var HttpClient = class { baseUrl; headers; options; readYourWrites; upstashSyncToken = ""; hasCredentials; retry; constructor(config) { this.options = { backend: config.options?.backend, agent: config.agent, responseEncoding: config.responseEncoding ?? "base64", // default to base64 cache: config.cache, signal: config.signal, keepAlive: config.keepAlive ?? true }; this.upstashSyncToken = ""; this.readYourWrites = config.readYourWrites ?? true; this.baseUrl = (config.baseUrl || "").replace(/\/$/, ""); const urlRegex = /^https?:\/\/[^\s#$./?].\S*$/; if (this.baseUrl && !urlRegex.test(this.baseUrl)) { throw new UrlError(this.baseUrl); } this.headers = { "Content-Type": "application/json", ...config.headers }; this.hasCredentials = Boolean(this.baseUrl && this.headers.authorization.split(" ")[1]); if (this.options.responseEncoding === "base64") { this.headers["Upstash-Encoding"] = "base64"; } this.retry = typeof config.retry === "boolean" && !config.retry ? { attempts: 1, backoff: () => 0 } : { attempts: config.retry?.retries ?? 5, backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50) }; } mergeTelemetry(telemetry) { this.headers = merge(this.headers, "Upstash-Telemetry-Runtime", telemetry.runtime); this.headers = merge(this.headers, "Upstash-Telemetry-Platform", telemetry.platform); this.headers = merge(this.headers, "Upstash-Telemetry-Sdk", telemetry.sdk); } async request(req) { const requestOptions = { //@ts-expect-error this should throw due to bun regression cache: this.options.cache, method: "POST", headers: this.headers, body: JSON.stringify(req.body), keepalive: this.options.keepAlive, agent: this.options.agent, signal: this.options.signal, /** * Fastly specific */ backend: this.options.backend }; if (!this.hasCredentials) { console.warn( "[Upstash Redis] Redis client was initialized without url or token. Failed to execute command." ); } if (this.readYourWrites) { const newHeader = this.upstashSyncToken; this.headers["upstash-sync-token"] = newHeader; } let res = null; let error = null; for (let i = 0; i <= this.retry.attempts; i++) { try { res = await fetch([this.baseUrl, ...req.path ?? []].join("/"), requestOptions); break; } catch (error_) { if (this.options.signal?.aborted) { const myBlob = new Blob([ JSON.stringify({ result: this.options.signal.reason ?? "Aborted" }) ]); const myOptions = { status: 200, statusText: this.options.signal.reason ?? "Aborted" }; res = new Response(myBlob, myOptions); break; } error = error_; await new Promise((r) => setTimeout(r, this.retry.backoff(i))); } } if (!res) { throw error ?? new Error("Exhausted all retries"); } const body = await res.json(); if (!res.ok) { throw new UpstashError(`${body.error}, command was: ${JSON.stringify(req.body)}`); } if (this.readYourWrites) { const headers = res.headers; this.upstashSyncToken = headers.get("upstash-sync-token") ?? ""; } if (this.readYourWrites) { const headers = res.headers; this.upstashSyncToken = headers.get("upstash-sync-token") ?? ""; } if (this.options.responseEncoding === "base64") { if (Array.isArray(body)) { return body.map(({ result: result2, error: error2 }) => ({ result: decode(result2), error: error2 })); } const result = decode(body.result); return { result, error: body.error }; } return body; } }; function base64decode(b64) { let dec = ""; try { const binString = atob(b64); const size = binString.length; const bytes = new Uint8Array(size); for (let i = 0; i < size; i++) { bytes[i] = binString.charCodeAt(i); } dec = new TextDecoder().decode(bytes); } catch { dec = b64; } return dec; } function decode(raw) { let result = void 0; switch (typeof raw) { case "undefined": { return raw; } case "number": { result = raw; break; } case "object": { if (Array.isArray(raw)) { result = raw.map( (v) => typeof v === "string" ? base64decode(v) : Array.isArray(v) ? v.map((element) => decode(element)) : v ); } else { result = null; } break; } case "string": { result = raw === "OK" ? "OK" : base64decode(raw); break; } default: { break; } } return result; } function merge(obj, key, value) { if (!value) { return obj; } obj[key] = obj[key] ? [obj[key], value].join(",") : value; return obj; } // pkg/auto-pipeline.ts function createAutoPipelineProxy(_redis, json) { const redis = _redis; if (!redis.autoPipelineExecutor) { redis.autoPipelineExecutor = new AutoPipelineExecutor(redis); } return new Proxy(redis, { get: (redis2, command) => { if (command === "pipelineCounter") { return redis2.autoPipelineExecutor.pipelineCounter; } if (command === "json") { return createAutoPipelineProxy(redis2, true); } const commandInRedisButNotPipeline = command in redis2 && !(command in redis2.autoPipelineExecutor.pipeline); if (commandInRedisButNotPipeline) { return redis2[command]; } const isFunction = json ? typeof redis2.autoPipelineExecutor.pipeline.json[command] === "function" : typeof redis2.autoPipelineExecutor.pipeline[command] === "function"; if (isFunction) { return (...args) => { return redis2.autoPipelineExecutor.withAutoPipeline((pipeline) => { if (json) { pipeline.json[command]( ...args ); } else { pipeline[command](...args); } }); }; } return redis2.autoPipelineExecutor.pipeline[command]; } }); } var AutoPipelineExecutor = class { pipelinePromises = /* @__PURE__ */ new WeakMap(); activePipeline = null; indexInCurrentPipeline = 0; redis; pipeline; // only to make sure that proxy can work pipelineCounter = 0; // to keep track of how many times a pipeline was executed constructor(redis) { this.redis = redis; this.pipeline = redis.pipeline(); } async withAutoPipeline(executeWithPipeline) { const pipeline = this.activePipeline ?? this.redis.pipeline(); if (!this.activePipeline) { this.activePipeline = pipeline; this.indexInCurrentPipeline = 0; } const index = this.indexInCurrentPipeline++; executeWithPipeline(pipeline); const pipelineDone = this.deferExecution().then(() => { if (!this.pipelinePromises.has(pipeline)) { const pipelinePromise = pipeline.exec({ keepErrors: true }); this.pipelineCounter += 1; this.pipelinePromises.set(pipeline, pipelinePromise); this.activePipeline = null; } return this.pipelinePromises.get(pipeline); }); const results = await pipelineDone; const commandResult = results[index]; if (commandResult.error) { throw new UpstashError(`Command failed: ${commandResult.error}`); } return commandResult.result; } async deferExecution() { await Promise.resolve(); await Promise.resolve(); } }; // pkg/util.ts function parseRecursive(obj) { const parsed = Array.isArray(obj) ? obj.map((o) => { try { return parseRecursive(o); } catch { return o; } }) : JSON.parse(obj); if (typeof parsed === "number" && parsed.toString() !== obj) { return obj; } return parsed; } function parseResponse(result) { try { return parseRecursive(result); } catch { return result; } } function deserializeScanResponse(result) { return [result[0], ...parseResponse(result.slice(1))]; } // pkg/commands/command.ts var defaultSerializer = (c) => { switch (typeof c) { case "string": case "number": case "boolean": { return c; } default: { return JSON.stringify(c); } } }; var Command = class { command; serialize; deserialize; /** * Create a new command instance. * * You can define a custom `deserialize` function. By default we try to deserialize as json. */ constructor(command, opts) { this.serialize = defaultSerializer; this.deserialize = opts?.automaticDeserialization === void 0 || opts.automaticDeserialization ? opts?.deserialize ?? parseResponse : (x) => x; this.command = command.map((c) => this.serialize(c)); if (opts?.latencyLogging) { const originalExec = this.exec.bind(this); this.exec = async (client) => { const start = performance.now(); const result = await originalExec(client); const end = performance.now(); const loggerResult = (end - start).toFixed(2); console.log( `Latency for \x1B[38;2;19;185;39m${this.command[0].toString().toUpperCase()}\x1B[0m: \x1B[38;2;0;255;255m${loggerResult} ms\x1B[0m` ); return result; }; } } /** * Execute the command using a client. */ async exec(client) { const { result, error } = await client.request({ body: this.command, upstashSyncToken: client.upstashSyncToken }); if (error) { throw new UpstashError(error); } if (result === void 0) { throw new TypeError("Request did not return a result"); } return this.deserialize(result); } }; // pkg/commands/append.ts var AppendCommand = class extends Command { constructor(cmd, opts) { super(["append", ...cmd], opts); } }; // pkg/commands/bitcount.ts var BitCountCommand = class extends Command { constructor([key, start, end], opts) { const command = ["bitcount", key]; if (typeof start === "number") { command.push(start); } if (typeof end === "number") { command.push(end); } super(command, opts); } }; // pkg/commands/bitfield.ts var BitFieldCommand = class { constructor(args, client, opts, execOperation = (command) => command.exec(this.client)) { this.client = client; this.opts = opts; this.execOperation = execOperation; this.command = ["bitfield", ...args]; } command; chain(...args) { this.command.push(...args); return this; } get(...args) { return this.chain("get", ...args); } set(...args) { return this.chain("set", ...args); } incrby(...args) { return this.chain("incrby", ...args); } overflow(overflow) { return this.chain("overflow", overflow); } exec() { const command = new Command(this.command, this.opts); return this.execOperation(command); } }; // pkg/commands/bitop.ts var BitOpCommand = class extends Command { constructor(cmd, opts) { super(["bitop", ...cmd], opts); } }; // pkg/commands/bitpos.ts var BitPosCommand = class extends Command { constructor(cmd, opts) { super(["bitpos", ...cmd], opts); } }; // pkg/commands/copy.ts var CopyCommand = class extends Command { constructor([key, destinationKey, opts], commandOptions) { super(["COPY", key, destinationKey, ...opts?.replace ? ["REPLACE"] : []], { ...commandOptions, deserialize(result) { if (result > 0) { return "COPIED"; } return "NOT_COPIED"; } }); } }; // pkg/commands/dbsize.ts var DBSizeCommand = class extends Command { constructor(opts) { super(["dbsize"], opts); } }; // pkg/commands/decr.ts var DecrCommand = class extends Command { constructor(cmd, opts) { super(["decr", ...cmd], opts); } }; // pkg/commands/decrby.ts var DecrByCommand = class extends Command { constructor(cmd, opts) { super(["decrby", ...cmd], opts); } }; // pkg/commands/del.ts var DelCommand = class extends Command { constructor(cmd, opts) { super(["del", ...cmd], opts); } }; // pkg/commands/echo.ts var EchoCommand = class extends Command { constructor(cmd, opts) { super(["echo", ...cmd], opts); } }; // pkg/commands/eval.ts var EvalCommand = class extends Command { constructor([script, keys, args], opts) { super(["eval", script, keys.length, ...keys, ...args ?? []], opts); } }; // pkg/commands/evalsha.ts var EvalshaCommand = class extends Command { constructor([sha, keys, args], opts) { super(["evalsha", sha, keys.length, ...keys, ...args ?? []], opts); } }; // pkg/commands/exists.ts var ExistsCommand = class extends Command { constructor(cmd, opts) { super(["exists", ...cmd], opts); } }; // pkg/commands/expire.ts var ExpireCommand = class extends Command { constructor(cmd, opts) { super(["expire", ...cmd.filter(Boolean)], opts); } }; // pkg/commands/expireat.ts var ExpireAtCommand = class extends Command { constructor(cmd, opts) { super(["expireat", ...cmd], opts); } }; // pkg/commands/flushall.ts var FlushAllCommand = class extends Command { constructor(args, opts) { const command = ["flushall"]; if (args && args.length > 0 && args[0].async) { command.push("async"); } super(command, opts); } }; // pkg/commands/flushdb.ts var FlushDBCommand = class extends Command { constructor([opts], cmdOpts) { const command = ["flushdb"]; if (opts?.async) { command.push("async"); } super(command, cmdOpts); } }; // pkg/commands/geo_add.ts var GeoAddCommand = class extends Command { constructor([key, arg1, ...arg2], opts) { const command = ["geoadd", key]; if ("nx" in arg1 && arg1.nx) { command.push("nx"); } else if ("xx" in arg1 && arg1.xx) { command.push("xx"); } if ("ch" in arg1 && arg1.ch) { command.push("ch"); } if ("latitude" in arg1 && arg1.latitude) { command.push(arg1.longitude, arg1.latitude, arg1.member); } command.push( ...arg2.flatMap(({ latitude, longitude, member }) => [longitude, latitude, member]) ); super(command, opts); } }; // pkg/commands/geo_dist.ts var GeoDistCommand = class extends Command { constructor([key, member1, member2, unit = "M"], opts) { super(["GEODIST", key, member1, member2, unit], opts); } }; // pkg/commands/geo_hash.ts var GeoHashCommand = class extends Command { constructor(cmd, opts) { const [key] = cmd; const members = Array.isArray(cmd[1]) ? cmd[1] : cmd.slice(1); super(["GEOHASH", key, ...members], opts); } }; // pkg/commands/geo_pos.ts var GeoPosCommand = class extends Command { constructor(cmd, opts) { const [key] = cmd; const members = Array.isArray(cmd[1]) ? cmd[1] : cmd.slice(1); super(["GEOPOS", key, ...members], { deserialize: (result) => transform(result), ...opts }); } }; function transform(result) { const final = []; for (const pos of result) { if (!pos?.[0] || !pos?.[1]) { continue; } final.push({ lng: Number.parseFloat(pos[0]), lat: Number.parseFloat(pos[1]) }); } return final; } // pkg/commands/geo_search.ts var GeoSearchCommand = class extends Command { constructor([key, centerPoint, shape, order, opts], commandOptions) { const command = ["GEOSEARCH", key]; if (centerPoint.type === "FROMMEMBER" || centerPoint.type === "frommember") { command.push(centerPoint.type, centerPoint.member); } if (centerPoint.type === "FROMLONLAT" || centerPoint.type === "fromlonlat") { command.push(centerPoint.type, centerPoint.coordinate.lon, centerPoint.coordinate.lat); } if (shape.type === "BYRADIUS" || shape.type === "byradius") { command.push(shape.type, shape.radius, shape.radiusType); } if (shape.type === "BYBOX" || shape.type === "bybox") { command.push(shape.type, shape.rect.width, shape.rect.height, shape.rectType); } command.push(order); if (opts?.count) { command.push("COUNT", opts.count.limit, ...opts.count.any ? ["ANY"] : []); } const transform2 = (result) => { if (!opts?.withCoord && !opts?.withDist && !opts?.withHash) { return result.map((member) => { try { return { member: JSON.parse(member) }; } catch { return { member }; } }); } return result.map((members) => { let counter = 1; const obj = {}; try { obj.member = JSON.parse(members[0]); } catch { obj.member = members[0]; } if (opts.withDist) { obj.dist = Number.parseFloat(members[counter++]); } if (opts.withHash) { obj.hash = members[counter++].toString(); } if (opts.withCoord) { obj.coord = { long: Number.parseFloat(members[counter][0]), lat: Number.parseFloat(members[counter][1]) }; } return obj; }); }; super( [ ...command, ...opts?.withCoord ? ["WITHCOORD"] : [], ...opts?.withDist ? ["WITHDIST"] : [], ...opts?.withHash ? ["WITHHASH"] : [] ], { deserialize: transform2, ...commandOptions } ); } }; // pkg/commands/geo_search_store.ts var GeoSearchStoreCommand = class extends Command { constructor([destination, key, centerPoint, shape, order, opts], commandOptions) { const command = ["GEOSEARCHSTORE", destination, key]; if (centerPoint.type === "FROMMEMBER" || centerPoint.type === "frommember") { command.push(centerPoint.type, centerPoint.member); } if (centerPoint.type === "FROMLONLAT" || centerPoint.type === "fromlonlat") { command.push(centerPoint.type, centerPoint.coordinate.lon, centerPoint.coordinate.lat); } if (shape.type === "BYRADIUS" || shape.type === "byradius") { command.push(shape.type, shape.radius, shape.radiusType); } if (shape.type === "BYBOX" || shape.type === "bybox") { command.push(shape.type, shape.rect.width, shape.rect.height, shape.rectType); } command.push(order); if (opts?.count) { command.push("COUNT", opts.count.limit, ...opts.count.any ? ["ANY"] : []); } super([...command, ...opts?.storeDist ? ["STOREDIST"] : []], commandOptions); } }; // pkg/commands/get.ts var GetCommand = class extends Command { constructor(cmd, opts) { super(["get", ...cmd], opts); } }; // pkg/commands/getbit.ts var GetBitCommand = class extends Command { constructor(cmd, opts) { super(["getbit", ...cmd], opts); } }; // pkg/commands/getdel.ts var GetDelCommand = class extends Command { constructor(cmd, opts) { super(["getdel", ...cmd], opts); } }; // pkg/commands/getrange.ts var GetRangeCommand = class extends Command { constructor(cmd, opts) { super(["getrange", ...cmd], opts); } }; // pkg/commands/getset.ts var GetSetCommand = class extends Command { constructor(cmd, opts) { super(["getset", ...cmd], opts); } }; // pkg/commands/hdel.ts var HDelCommand = class extends Command { constructor(cmd, opts) { super(["hdel", ...cmd], opts); } }; // pkg/commands/hexists.ts var HExistsCommand = class extends Command { constructor(cmd, opts) { super(["hexists", ...cmd], opts); } }; // pkg/commands/hget.ts var HGetCommand = class extends Command { constructor(cmd, opts) { super(["hget", ...cmd], opts); } }; // pkg/commands/hgetall.ts function deserialize(result) { if (result.length === 0) { return null; } const obj = {}; while (result.length >= 2) { const key = result.shift(); const value = result.shift(); try { const valueIsNumberAndNotSafeInteger = !Number.isNaN(Number(value)) && !Number.isSafeInteger(Number(value)); obj[key] = valueIsNumberAndNotSafeInteger ? value : JSON.parse(value); } catch { obj[key] = value; } } return obj; } var HGetAllCommand = class extends Command { constructor(cmd, opts) { super(["hgetall", ...cmd], { deserialize: (result) => deserialize(result), ...opts }); } }; // pkg/commands/hincrby.ts var HIncrByCommand = class extends Command { constructor(cmd, opts) { super(["hincrby", ...cmd], opts); } }; // pkg/commands/hincrbyfloat.ts var HIncrByFloatCommand = class extends Command { constructor(cmd, opts) { super(["hincrbyfloat", ...cmd], opts); } }; // pkg/commands/hkeys.ts var HKeysCommand = class extends Command { constructor([key], opts) { super(["hkeys", key], opts); } }; // pkg/commands/hlen.ts var HLenCommand = class extends Command { constructor(cmd, opts) { super(["hlen", ...cmd], opts); } }; // pkg/commands/hmget.ts function deserialize2(fields, result) { if (result.every((field) => field === null)) { return null; } const obj = {}; for (const [i, field] of fields.entries()) { try { obj[field] = JSON.parse(result[i]); } catch { obj[field] = result[i]; } } return obj; } var HMGetCommand = class extends Command { constructor([key, ...fields], opts) { super(["hmget", key, ...fields], { deserialize: (result) => deserialize2(fields, result), ...opts }); } }; // pkg/commands/hmset.ts var HMSetCommand = class extends Command { constructor([key, kv], opts) { super(["hmset", key, ...Object.entries(kv).flatMap(([field, value]) => [field, value])], opts); } }; // pkg/commands/hrandfield.ts function deserialize3(result) { if (result.length === 0) { return null; } const obj = {}; while (result.length >= 2) { const key = result.shift(); const value = result.shift(); try { obj[key] = JSON.parse(value); } catch { obj[key] = value; } } return obj; } var HRandFieldCommand = class extends Command { constructor(cmd, opts) { const command = ["hrandfield", cmd[0]]; if (typeof cmd[1] === "number") { command.push(cmd[1]); } if (cmd[2]) { command.push("WITHVALUES"); } super(command, { // @ts-expect-error to silence compiler deserialize: cmd[2] ? (result) => deserialize3(result) : opts?.deserialize, ...opts }); } }; // pkg/commands/hscan.ts var HScanCommand = class extends Command { constructor([key, cursor, cmdOpts], opts) { const command = ["hscan", key, cursor]; if (cmdOpts?.match) { command.push("match", cmdOpts.match); } if (typeof cmdOpts?.count === "number") { command.push("count", cmdOpts.count); } super(command, { deserialize: deserializeScanResponse, ...opts }); } }; // pkg/commands/hset.ts var HSetCommand = class extends Command { constructor([key, kv], opts) { super(["hset", key, ...Object.entries(kv).flatMap(([field, value]) => [field, value])], opts); } }; // pkg/commands/hsetnx.ts var HSetNXCommand = class extends Command { constructor(cmd, opts) { super(["hsetnx", ...cmd], opts); } }; // pkg/commands/hstrlen.ts var HStrLenCommand = class extends Command { constructor(cmd, opts) { super(["hstrlen", ...cmd], opts); } }; // pkg/commands/hvals.ts var HValsCommand = class extends Command { constructor(cmd, opts) { super(["hvals", ...cmd], opts); } }; // pkg/commands/incr.ts var IncrCommand = class extends Command { constructor(cmd, opts) { super(["incr", ...cmd], opts); } }; // pkg/commands/incrby.ts var IncrByCommand = class extends Command { constructor(cmd, opts) { super(["incrby", ...cmd], opts); } }; // pkg/commands/incrbyfloat.ts var IncrByFloatCommand = class extends Command { constructor(cmd, opts) { super(["incrbyfloat", ...cmd], opts); } }; // pkg/commands/json_arrappend.ts var JsonArrAppendCommand = class extends Command { constructor(cmd, opts) { super(["JSON.ARRAPPEND", ...cmd], opts); } }; // pkg/commands/json_arrindex.ts var JsonArrIndexCommand = class extends Command { constructor(cmd, opts) { super(["JSON.ARRINDEX", ...cmd], opts); } }; // pkg/commands/json_arrinsert.ts var JsonArrInsertCommand = class extends Command { constructor(cmd, opts) { super(["JSON.ARRINSERT", ...cmd], opts); } }; // pkg/commands/json_arrlen.ts var JsonArrLenCommand = class extends Command { constructor(cmd, opts) { super(["JSON.ARRLEN", cmd[0], cmd[1] ?? "$"], opts); } }; // pkg/commands/json_arrpop.ts var JsonArrPopCommand = class extends Command { constructor(cmd, opts) { super(["JSON.ARRPOP", ...cmd], opts); } }; // pkg/commands/json_arrtrim.ts var JsonArrTrimCommand = class extends Command { constructor(cmd, opts) { const path = cmd[1] ?? "$"; const start = cmd[2] ?? 0; const stop = cmd[3] ?? 0; super(["JSON.ARRTRIM", cmd[0], path, start, stop], opts); } }; // pkg/commands/json_clear.ts var JsonClearCommand = class extends Command { constructor(cmd, opts) { super(["JSON.CLEAR", ...cmd], opts); } }; // pkg/commands/json_del.ts var JsonDelCommand = class extends Command { constructor(cmd, opts) { super(["JSON.DEL", ...cmd], opts); } }; // pkg/commands/json_forget.ts var JsonForgetCommand = class extends Command { constructor(cmd, opts) { super(["JSON.FORGET", ...cmd], opts); } }; // pkg/commands/json_get.ts var JsonGetCommand = class extends Command { constructor(cmd, opts) { const command = ["JSON.GET"]; if (typeof cmd[1] === "string") { command.push(...cmd); } else { command.push(cmd[0]); if (cmd[1]) { if (cmd[1].indent) { command.push("INDENT", cmd[1].indent); } if (cmd[1].newline) { command.push("NEWLINE", cmd[1].newline); } if (cmd[1].space) { command.push("SPACE", cmd[1].space); } } command.push(...cmd.slice(2)); } super(command, opts); } }; // pkg/commands/json_mget.ts var JsonMGetCommand = class extends Command { constructor(cmd, opts) { super(["JSON.MGET", ...cmd[0], cmd[1]], opts); } }; // pkg/commands/json_mset.ts var JsonMSetCommand = class extends Command { constructor(cmd, opts) { const command = ["JSON.MSET"]; for (const c of cmd) { command.push(c.key, c.path, c.value); } super(command, opts); } }; // pkg/commands/json_numincrby.ts var JsonNumIncrByCommand = class extends Command { constructor(cmd, opts) { super(["JSON.NUMINCRBY", ...cmd], opts); } }; // pkg/commands/json_nummultby.ts var JsonNumMultByCommand = class extends Command { constructor(cmd, opts) { super(["JSON.NUMMULTBY", ...cmd], opts); } }; // pkg/commands/json_objkeys.ts var JsonObjKeysCommand = class extends Command { constructor(cmd, opts) { super(["JSON.OBJKEYS", ...cmd], opts); } }; // pkg/commands/json_objlen.ts var JsonObjLenCommand = class extends Command { constructor(cmd, opts) { super(["JSON.OBJLEN", ...cmd], opts); } }; // pkg/commands/json_resp.ts var JsonRespCommand = class extends Command { constructor(cmd, opts) { super(["JSON.RESP", ...cmd], opts); } }; // pkg/commands/json_set.ts var JsonSetCommand = class extends Command { constructor(cmd, opts) { const command = ["JSON.SET", cmd[0], cmd[1], cmd[2]]; if (cmd[3]) { if (cmd[3].nx) { command.push("NX"); } else if (cmd[3].xx) { command.push("XX"); } } super(command, opts); } }; // pkg/commands/json_strappend.ts var JsonStrAppendCommand = class extends Command { constructor(cmd, opts) { super(["JSON.STRAPPEND", ...cmd], opts); } }; // pkg/commands/json_strlen.ts var JsonStrLenCommand = class extends Command { constructor(cmd, opts) { super(["JSON.STRLEN", ...cmd], opts); } }; // pkg/commands/json_toggle.ts var JsonToggleCommand = class extends Command { constructor(cmd, opts) { super(["JSON.TOGGLE", ...cmd], opts); } }; // pkg/commands/json_type.ts var JsonTypeCommand = class extends Command { constructor(cmd, opts) { super(["JSON.TYPE", ...cmd], opts); } }; // pkg/commands/keys.ts var KeysCommand = class extends Command { constructor(cmd, opts) { super(["keys", ...cmd], opts); } }; // pkg/commands/lindex.ts var LIndexCommand = class extends Command { constructor(cmd, opts) { super(["lindex", ...cmd], opts); } }; // pkg/commands/linsert.ts var LInsertCommand = class extends Command { constructor(cmd, opts) { super(["linsert", ...cmd], opts); } }; // pkg/commands/llen.ts var LLenCommand = class extends Command { constructor(cmd, opts) { super(["llen", ...cmd], opts); } }; // pkg/commands/lmove.ts var LMoveCommand = class extends Command { constructor(cmd, opts) { super(["lmove", ...cmd], opts); } }; // pkg/commands/lmpop.ts var LmPopCommand = class extends Command { constructor(cmd, opts) { const [numkeys, keys, direction, count] = cmd; super(["LMPOP", numkeys, ...keys, direction, ...count ? ["COUNT", count] : []], opts); } }; // pkg/commands/lpop.ts var LPopCommand = class extends Command { constructor(cmd, opts) { super(["lpop", ...cmd], opts); } }; // pkg/commands/lpos.ts var LPosCommand = class extends Command { constructor(cmd, opts) { const args = ["lpos", cmd[0], cmd[1]]; if (typeof cmd[2]?.rank === "number") { args.push("rank", cmd[2].rank); } if (typeof cmd[2]?.count === "number") { args.push("count", cmd[2].count); } if (typeof cmd[2]?.maxLen === "number") { args.push("maxLen", cmd[2].maxLen); } super(args, opts); } }; // pkg/commands/lpush.ts var LPushCommand = class extends Command { constructor(cmd, opts) { super(["lpush", ...cmd], opts); } }; // pkg/commands/lpushx.ts var LPushXCommand = class extends Command { constructor(cmd, opts) { super(["lpushx", ...cmd], opts); } }; // pkg/commands/lrange.ts var LRangeCommand = class extends Command { constructor(cmd, opts) { super(["lrange", ...cmd], opts); } }; // pkg/commands/lrem.ts var LRemCommand = class extends Command { constructor(cmd, opts) { super(["lrem", ...cmd], opts); } }; // pkg/commands/lset.ts var LSetCommand = class extends Command { constructor(cmd, opts) { super(["lset", ...cmd], opts); } }; // pkg/commands/ltrim.ts var LTrimCommand = class extends Command { constructor(cmd, opts) { super(["ltrim", ...cmd], opts); } }; // pkg/commands/mget.ts var MGetCommand = class extends Command { constructor(cmd, opts) { const keys = Array.isArray(cmd[0]) ? cmd[0] : cmd; super(["mget", ...keys], opts); } }; // pkg/commands/mset.ts var MSetCommand = class extends Command { constructor([kv], opts) { super(["mset", ...Object.entries(kv).flatMap(([key, value]) => [key, value])], opts); } }; // pkg/commands/msetnx.ts var MSetNXCommand = class extends Command { constructor([kv], opts) { super(["msetnx", ...Object.entries(kv).flat()], opts); } }; // pkg/commands/persist.ts var PersistCommand = class extends Command { constructor(cmd, opts) { super(["persist", ...cmd], opts); } }; // pkg/commands/pexpire.ts var PExpireCommand = class extends Command { constructor(cmd, opts) { super(["pexpire", ...cmd], opts); } }; // pkg/commands/pexpireat.ts var PExpireAtCommand = class extends Command { constructor(cmd, opts) { super(["pexpireat", ...cmd], opts); } }; // pkg/commands/pfadd.ts var PfAddCommand = class extends Command { constructor(cmd, opts) { super(["pfadd", ...cmd], opts); } }; // pkg/commands/pfcount.ts var PfCountCommand = class extends Command { constructor(cmd, opts) { super(["pfcount", ...cmd], opts); } }; // pkg/commands/pfmerge.ts var PfMergeCommand = class extends Command { constructor(cmd, opts) { super(["pfmerge", ...cmd], opts); } }; // pkg/commands/ping.ts var PingCommand = class extends Command { constructor(cmd, opts) { const command = ["ping"]; if (cmd?.[0] !== void 0) { command.push(cmd[0]); } super(command, opts); } }; // pkg/commands/psetex.ts var PSetEXCommand = class extends Command { constructor(cmd, opts) { super(["psetex", ...cmd], opts); } }; // pkg/commands/pttl.ts var PTtlCommand = class extends Command { constructor(cmd, opts) { super(["pttl", ...cmd], opts); } }; // pkg/commands/publish.ts var PublishCommand = class extends Command { constructor(cmd, opts) { super(["publish", ...cmd], opts); } }; // pkg/commands/randomkey.ts var RandomKeyCommand = class extends Command { constructor(opts) { super(["randomkey"], opts); } }; // pkg/commands/rename.ts var RenameCommand = class extends Command { constructor(cmd, opts) { super(["rename", ...cmd], opts); } }; // pkg/commands/renamenx.ts var RenameNXCommand = class extends Command { constructor(cmd, opts) { super(["renamenx", ...cmd], opts); } }; // pkg/commands/rpop.ts var RPopCommand = class extends Command { constructor(cmd, opts) { super(["rpop", ...cmd], opts); } }; // pkg/commands/rpush.ts var RPushCommand = class extends Command { constructor(cmd, opts) { super(["rpush", ...cmd], opts); } }; // pkg/commands/rpushx.ts var RPushXCommand = class extends Command { constructor(cmd, opts) { super(["rpushx", ...cmd], opts); } }; // pkg/commands/sadd.ts var SAddCommand = class extends Command { constructor(cmd, opts) { super(["sadd", ...cmd], opts); } }; // pkg/commands/scan.ts var ScanCommand = class extends Command { constructor([cursor, opts], cmdOpts) { const command = ["scan", cursor]; if (opts?.match) { command.push("match", opts.match); } if (typeof opts?.count === "number") { command.push("count", opts.count); } if (opts?.type && opts.type.length > 0) { command.push("type", opts.type); } super(command, { deserialize: deserializeScanResponse, ...cmdOpts }); } }; // pkg/commands/scard.ts var SCardCommand = class extends Command { constructor(cmd, opts) { super(["scard", ...cmd], opts); } }; // pkg/commands/script_exists.ts var ScriptExistsCommand = class extends Command { constructor(hashes, opts) { super(["script", "exists", ...hashes], { deserialize: (result) => result, ...opts }); } }; // pkg/commands/script_flush.ts var ScriptFlushCommand = class extends Command { constructor([opts], cmdOpts) { const cmd = ["script", "flush"]; if (opts?.sync) { cmd.push("sync"); } else if (opts?.async) { cmd.push("async"); } super(cmd, cmdOpts); } }; // pkg/commands/script_load.ts var ScriptLoadCommand = class extends Command { constructor(args, opts) { super(["script", "load", ...args], opts); } }; // pkg/commands/sdiff.ts var SDiffCommand = class extends Command { constructor(cmd, opts) { super(["sdiff", ...cmd], opts); } }; // pkg/commands/sdiffstore.ts var SDiffStoreCommand = class extends Command { constructor(cmd, opts) { super(["sdiffstore", ...cmd], opts); } }; // pkg/commands/set.ts var SetCommand = class extends Command { constructor([key, value, opts], cmdOpts) { const command = ["set", key, value]; if (opts) { if ("nx" in opts && opts.nx) { command.push("nx"); } else if ("xx" in opts && opts.xx) { command.push("xx"); } if ("get" in opts && opts.get) { command.push("get"); } if ("ex" in opts && typeof opts.ex === "number") { command.push("ex", opts.ex); } else if ("px" in opts && typeof opts.px === "number") { command.push("px", opts.px); } else if ("exat" in opts && typeof opts.exat === "number") { command.push("exat", opts.exat); } else if ("pxat" in opts && typeof opts.pxat === "number") { command.push("pxat", opts.pxat); } else if ("keepTtl" in opts && opts.keepTtl) { command.push("keepTtl"); } } super(command, cmdOpts); } }; // pkg/commands/setbit.ts var SetBitCommand = class extends Command { constructor(cmd, opts) { super(["setbit", ...cmd], opts); } }; // pkg/commands/setex.ts var SetExCommand = class extends Command { constructor(cmd, opts) { super(["setex", ...cmd], opts); } }; // pkg/commands/setnx.ts var SetNxCommand = class extends Command { constructor(cmd, opts) { super(["setnx", ...cmd], opts); } }; // pkg/commands/setrange.ts var SetRangeCommand = class extends Command { constructor(cmd, opts) { super(["setrange", ...cmd], opts); } }; // pkg/commands/sinter.ts var SInterCommand = class extends Command { constructor(cmd, opts) { super(["sinter", ...cmd], opts); } }; // pkg/commands/sinterstore.ts var SInterStoreCommand = class extends Command { constructor(cmd, opts) { super(["sinterstore", ...cmd], opts); } }; // pkg/commands/sismember.ts var SIsMemberCommand = class extends Command { constructor(cmd, opts) { super(["sismember", ...cmd], opts); } }; // pkg/commands/smembers.ts var SMembersCommand = class extends Command { constructor(cmd, opts) { super(["smembers", ...cmd], opts); } }; // pkg/commands/smismember.ts var SMIsMemberCommand = class extends Command { constructor(cmd, opts) { super(["smismember", cmd[0], ...cmd[1]], opts); } }; // pkg/commands/smove.ts var SMoveCommand = class extends Command { constructor(cmd, opts) { super(["smove", ...cmd], opts); } }; // pkg/commands/spop.ts var SPopCommand = class extends Command { constructor([key, count], opts) { const command = ["spop", key]; if (typeof count === "number") { command.push(count); } super(command, opts); } }; // pkg/commands/srandmember.ts var SRandMemberCommand = class extends Command { constructor([key, count], opts) { const command = ["srandmember", key]; if (typeof count === "number") { command.push(count); } super(command, opts); } }; // pkg/commands/srem.ts var SRemCommand = class extends Command { constructor(cmd, opts) { super(["srem", ...cmd], opts); } }; // pkg/commands/sscan.ts var SScanCommand = class extends Command { constructor([key, cursor, opts], cmdOpts) { const command = ["sscan", key, cursor]; if (opts?.match) { command.push("match", opts.match); } if (typeof opts?.count === "number") { command.push("count", opts.count); } super(command, { deserialize: deserializeScanResponse, ...cmdOpts }); } }; // pkg/commands/strlen.ts var StrLenCommand = class extends Command { constructor(cmd, opts) { super(["strlen", ...cmd], opts); } }; // pkg/commands/sunion.ts var SUnionCommand = class extends Command { constructor(cmd, opts) { super(["sunion", ...cmd], opts); } }; // pkg/commands/sunionstore.ts var SUnionStoreCommand = class extends Command { constructor(cmd, opts) { super(["sunionstore", ...cmd], opts); } }; // pkg/commands/time.ts var TimeCommand = class extends Command { constructor(opts) { super(["time"], opts); } }; // pkg/commands/touch.ts var TouchCommand = class extends Command { constructor(cmd, opts) { super(["touch", ...cmd], opts); } }; // pkg/commands/ttl.ts var TtlCommand = class extends Command { constructor(cmd, opts) { super(["ttl", ...cmd], opts); } }; // pkg/commands/type.ts var TypeCommand = class extends Command { constructor(cmd, opts) { super(["type", ...cmd], opts); } }; // pkg/commands/unlink.ts var UnlinkCommand = class extends Command { constructor(cmd, opts) { super(["unlink", ...cmd], opts); } }; // pkg/commands/xack.ts var XAckCommand = class extends Command { constructor([key, group, id], opts) { const ids = Array.isArray(id) ? [...id] : [id]; super(["XACK", key, group, ...ids], opts); } }; // pkg/commands/xadd.ts var XAddCommand = class extends Command { constructor([key, id, entries, opts], commandOptions) { const command = ["XADD", key]; if (opts) { if (opts.nomkStream) { command.push("NOMKSTREAM"); } if (opts.trim) { command.push(opts.trim.type, opts.trim.comparison, opts.trim.threshold); if (opts.trim.limit !== void 0) { command.push("LIMIT", opts.trim.limit); } } } command.push(id); for (const [k, v] of Object.entries(entries)) { command.push(k, v); } super(command, commandOptions); } }; // pkg/commands/xautoclaim.ts var XAutoClaim = class extends Command { constructor([key, group, consumer, minIdleTime, start, options], opts) { const commands = []; if (options?.count) { commands.push("COUNT", options.count); } if (options?.justId) { commands.push("JUSTID"); } super(["XAUTOCLAIM", key, group, consumer, minIdleTime, start, ...commands], opts); } }; // pkg/commands/xclaim.ts var XClaimCommand = class extends Command { constructor([key, group, consumer, minIdleTime, id, options], opts) { const ids = Array.isArray(id) ? [...id] : [id]; const commands = []; if (options?.idleMS) { commands.push("IDLE", options.idleMS); } if (options?.idleMS) { commands.push("TIME", options.timeMS); } if (options?.retryCount) { commands.push("RETRYCOUNT", options.retryCount); } if (options?.force) { commands.push("FORCE"); } if (options?.justId) { commands.push("JUSTID"); } if (options?.lastId) { commands.push("LASTID", options.lastId); } super(["XCLAIM", key, group, consumer, minIdleTime, ...ids, ...commands], opts); } }; // pkg/commands/xdel.ts var XDelCommand = class extends Command { constructor([key, ids], opts) { const cmds = Array.isArray(ids) ? [...ids] : [ids]; super(["XDEL", key, ...cmds], opts); } }; // pkg/commands/xgroup.ts var XGroupCommand = class extends Command { constructor([key, opts], commandOptions) { const command = ["XGROUP"]; switch (opts.type) { case "CREATE": { command.push("CREATE", key, opts.group, opts.id); if (opts.options) { if (opts.options.MKSTREAM) { command.push("MKSTREAM"); } if (opts.options.ENTRIESREAD !== void 0) { command.push("ENTRIESREAD", opts.options.ENTRIESREAD.toString()); } } break; } case "CREATECONSUMER": { command.push("CREATECONSUMER", key, opts.group, opts.consumer); break; } case "DELCONSUMER": { command.push("DELCONSUMER", key, opts.group, opts.consumer); break; } case "DESTROY": { command.push("DESTROY", key, opts.group); break; } case "SETID": { command.push("SETID", key, opts.group, opts.id); if (opts.options?.ENTRIESREAD !== void 0) { command.push("ENTRIESREAD", opts.options.ENTRIESREAD.toString()); } break; } default: { throw new Error("Invalid XGROUP"); } } super(command, commandOptions); } }; // pkg/commands/xinfo.ts var XInfoCommand = class extends Command { constructor([key, options], opts) { const cmds = []; if (options.type === "CONSUMERS") { cmds.push("CONSUMERS", key, options.group); } else { cmds.push("GROUPS", key); } super(["XINFO", ...cmds], opts); } }; // pkg/commands/xlen.ts var XLenCommand = class extends Command { constructor(cmd, opts) { super(["XLEN", ...cmd], opts); } }; // pkg/commands/xpending.ts var XPendingCommand = class extends Command { constructor([key, group, start, end, count, options], opts) { const consumers = options?.consumer === void 0 ? [] : Array.isArray(options.consumer) ? [...options.consumer] : [options.consumer]; super( [ "XPENDING", key, group, ...options?.idleTime ? ["IDLE", options.idleTime] : [], start, end, count, ...consumers ], opts ); } }; // pkg/commands/xrange.ts function deserialize4(result) { const obj = {}; for (const e of result) { while (e.length >= 2) { const streamId = e.shift(); const entries = e.shift(); if (!(streamId in obj)) { obj[streamId] = {}; } while (entries.length >= 2) { const field = entries.shift(); const value = entries.shift(); try { obj[streamId][field] = JSON.parse(value); } catch { obj[streamId][field] = value; } } } } return obj; } var XRangeCommand = class extends Command { constructor([key, start, end, count], opts) { const command = ["XRANGE", key, start, end]; if (typeof count === "number") { command.push("COUNT", count); } super(command, { deserialize: (result) => deserialize4(result), ...opts }); } }; // pkg/commands/xread.ts var UNBALANCED_XREAD_ERR = "ERR Unbalanced XREAD list of streams: for each stream key an ID or '$' must be specified"; var XReadCommand = class extends Command { constructor([key, id, options], opts) { if (Array.isArray(key) && Array.isArray(id) && key.length !== id.length) { throw new Error(UNBALANCED_XREAD_ERR); } const commands = []; if (typeof options?.count === "number") { commands.push("COUNT", options.count); } if (typeof options?.blockMS === "number") { commands.push("BLOCK", options.blockMS); } commands.push( "STREAMS", ...Array.isArray(key) ? [...key] : [key], ...Array.isArray(id) ? [...id] : [id] ); super(["XREAD", ...commands], opts); } }; // pkg/commands/xreadgroup.ts var UNBALANCED_XREADGROUP_ERR = "ERR Unbalanced XREADGROUP list of streams: for each stream key an ID or '$' must be specified"; var XReadGroupCommand = class extends Command { constructor([group, consumer, key, id, options], opts) { if (Array.isArray(key) && Array.isArray(id) && key.length !== id.length) { throw new Error(UNBALANCED_XREADGROUP_ERR); } const commands = []; if (typeof options?.count === "number") { commands.push("COUNT", options.count); } if (typeof options?.blockMS === "number") { commands.push("BLOCK", options.blockMS); } if (typeof options?.NOACK === "boolean" && options.NOACK) { commands.push("NOACK"); } commands.push( "STREAMS", ...Array.isArray(key) ? [...key] : [key], ...Array.isArray(id) ? [...id] : [id] ); super(["XREADGROUP", "GROUP", group, consumer, ...commands], opts); } }; // pkg/commands/xrevrange.ts var XRevRangeCommand = class extends Command { constructor([key, end, start, count], opts) { const command = ["XREVRANGE", key, end, start]; if (typeof count === "number") { command.push("COUNT", count); } super(command, { deserialize: (result) => deserialize5(result), ...opts }); } }; function deserialize5(result) { const obj = {}; for (const e of result) { while (e.length >= 2) { const streamId = e.shift(); const entries = e.shift(); if (!(streamId in obj)) { obj[streamId] = {}; } while (entries.length >= 2) { const field = entries.shift(); const value = entries.shift(); try { obj[streamId][field] = JSON.parse(value); } catch { obj[streamId][field] = value; } } } } return obj; } // pkg/commands/xtrim.ts var XTrimCommand = class extends Command { constructor([key, options], opts) { const { limit, strategy, threshold, exactness = "~" } = options; super(["XTRIM", key, strategy, exactness, threshold, ...limit ? ["LIMIT", limit] : []], opts); } }; // pkg/commands/zadd.ts var ZAddCommand = class extends Command { constructor([key, arg1, ...arg2], opts) { const command = ["zadd", key]; if ("nx" in arg1 && arg1.nx) { command.push("nx"); } else if ("xx" in arg1 && arg1.xx) { command.push("xx"); } if ("ch" in arg1 && arg1.ch) { command.push("ch"); } if ("incr" in arg1 && arg1.incr) { command.push("incr"); } if ("lt" in arg1 && arg1.lt) { command.push("lt"); } else if ("gt" in arg1 && arg1.gt) { command.push("gt"); } if ("score" in arg1 && "member" in arg1) { command.push(arg1.score, arg1.member); } command.push(...arg2.flatMap(({ score, member }) => [score, member])); super(command, opts); } }; // pkg/commands/zcard.ts var ZCardCommand = class extends Command { constructor(cmd, opts) { super(["zcard", ...cmd], opts); } }; // pkg/commands/zcount.ts var ZCountCommand = class extends Command { constructor(cmd, opts) { super(["zcount", ...cmd], opts); } }; // pkg/commands/zincrby.ts var ZIncrByCommand = class extends Command { constructor(cmd, opts) { super(["zincrby", ...cmd], opts); } }; // pkg/commands/zinterstore.ts var ZInterStoreCommand = class extends Command { constructor([destination, numKeys, keyOrKeys, opts], cmdOpts) { const command = ["zinterstore", destination, numKeys]; if (Array.isArray(keyOrKeys)) { command.push(...keyOrKeys); } else { command.push(keyOrKeys); } if (opts) { if ("weights" in opts && opts.weights) { command.push("weights", ...opts.weights); } else if ("weight" in opts && typeof opts.weight === "number") { command.push("weights", opts.weight); } if ("aggregate" in opts) { command.push("aggregate", opts.aggregate); } } super(command, cmdOpts); } }; // pkg/commands/zlexcount.ts var ZLexCountCommand = class extends Command { constructor(cmd, opts) { super(["zlexcount", ...cmd], opts); } }; // pkg/commands/zpopmax.ts var ZPopMaxCommand = class extends Command { constructor([key, count], opts) { const command = ["zpopmax", key]; if (typeof count === "number") { command.push(count); } super(command, opts); } }; // pkg/commands/zpopmin.ts var ZPopMinCommand = class extends Command { constructor([key, count], opts) { const command = ["zpopmin", key]; if (typeof count === "number") { command.push(count); } super(command, opts); } }; // pkg/commands/zrange.ts var ZRangeCommand = class extends Command { constructor([key, min, max, opts], cmdOpts) { const command = ["zrange", key, min, max]; if (opts?.byScore) { command.push("byscore"); } if (opts?.byLex) { command.push("bylex"); } if (opts?.rev) { command.push("rev"); } if (opts?.count !== void 0 && opts.offset !== void 0) { command.push("limit", opts.offset, opts.count); } if (opts?.withScores) { command.push("withscores"); } super(command, cmdOpts); } }; // pkg/commands/zrank.ts var ZRankCommand = class extends Command { constructor(cmd, opts) { super(["zrank", ...cmd], opts); } }; // pkg/commands/zrem.ts var ZRemCommand = class extends Command { constructor(cmd, opts) { super(["zrem", ...cmd], opts); } }; // pkg/commands/zremrangebylex.ts var ZRemRangeByLexCommand = class extends Command { constructor(cmd, opts) { super(["zremrangebylex", ...cmd], opts); } }; // pkg/commands/zremrangebyrank.ts var ZRemRangeByRankCommand = class extends Command { constructor(cmd, opts) { super(["zremrangebyrank", ...cmd], opts); } }; // pkg/commands/zremrangebyscore.ts var ZRemRangeByScoreCommand = class extends Command { constructor(cmd, opts) { super(["zremrangebyscore", ...cmd], opts); } }; // pkg/commands/zrevrank.ts var ZRevRankCommand = class extends Command { constructor(cmd, opts) { super(["zrevrank", ...cmd], opts); } }; // pkg/commands/zscan.ts var ZScanCommand = class extends Command { constructor([key, cursor, opts], cmdOpts) { const command = ["zscan", key, cursor]; if (opts?.match) { command.push("match", opts.match); } if (typeof opts?.count === "number") { command.push("count", opts.count); } super(command, { deserialize: deserializeScanResponse, ...cmdOpts }); } }; // pkg/commands/zscore.ts var ZScoreCommand = class extends Command { constructor(cmd, opts) { super(["zscore", ...cmd], opts); } }; // pkg/commands/zunion.ts var ZUnionCommand = class extends Command { constructor([numKeys, keyOrKeys, opts], cmdOpts) { const command = ["zunion", numKeys]; if (Array.isArray(keyOrKeys)) { command.push(...keyOrKeys); } else { command.push(keyOrKeys); } if (opts) { if ("weights" in opts && opts.weights) { command.push("weights", ...opts.weights); } else if ("weight" in opts && typeof opts.weight === "number") { command.push("weights", opts.weight); } if ("aggregate" in opts) { command.push("aggregate", opts.aggregate); } if (opts.withScores) { command.push("withscores"); } } super(command, cmdOpts); } }; // pkg/commands/zunionstore.ts var ZUnionStoreCommand = class extends Command { constructor([destination, numKeys, keyOrKeys, opts], cmdOpts) { const command = ["zunionstore", destination, numKeys]; if (Array.isArray(keyOrKeys)) { command.push(...keyOrKeys); } else { command.push(keyOrKeys); } if (opts) { if ("weights" in opts && opts.weights) { command.push("weights", ...opts.weights); } else if ("weight" in opts && typeof opts.weight === "number") { command.push("weights", opts.weight); } if ("aggregate" in opts) { command.push("aggregate", opts.aggregate); } } super(command, cmdOpts); } }; // pkg/commands/zdiffstore.ts var ZDiffStoreCommand = class extends Command { constructor(cmd, opts) { super(["zdiffstore", ...cmd], opts); } }; // pkg/commands/zmscore.ts var ZMScoreCommand = class extends Command { constructor(cmd, opts) { const [key, members] = cmd; super(["zmscore", key, ...members], opts); } }; // pkg/pipeline.ts var Pipeline = class { client; commands; commandOptions; multiExec; constructor(opts) { this.client = opts.client; this.commands = []; this.commandOptions = opts.commandOptions; this.multiExec = opts.multiExec ?? false; if (this.commandOptions?.latencyLogging) { const originalExec = this.exec.bind(this); this.exec = async (options) => { const start = performance.now(); const result = await (options ? originalExec(options) : originalExec()); const end = performance.now(); const loggerResult = (end - start).toFixed(2); console.log( `Latency for \x1B[38;2;19;185;39m${this.multiExec ? ["MULTI-EXEC"] : ["PIPELINE"].toString().toUpperCase()}\x1B[0m: \x1B[38;2;0;255;255m${loggerResult} ms\x1B[0m` ); return result; }; } } exec = async (options) => { if (this.commands.length === 0) { throw new Error("Pipeline is empty"); } const path = this.multiExec ? ["multi-exec"] : ["pipeline"]; const res = await this.client.request({ path, body: Object.values(this.commands).map((c) => c.command) }); return options?.keepErrors ? res.map(({ error, result }, i) => { return { error, result: this.commands[i].deserialize(result) }; }) : res.map(({ error, result }, i) => { if (error) { throw new UpstashError( `Command ${i + 1} [ ${this.commands[i].command[0]} ] failed: ${error}` ); } return this.commands[i].deserialize(result); }); }; /** * Returns the length of pipeline before the execution */ length() { return this.commands.length; } /** * Pushes a command into the pipeline and returns a chainable instance of the * pipeline */ chain(command) { this.commands.push(command); return this; } /** * @see https://redis.io/commands/append */ append = (...args) => this.chain(new AppendCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/bitcount */ bitcount = (...args) => this.chain(new BitCountCommand(args, this.commandOptions)); /** * Returns an instance that can be used to execute `BITFIELD` commands on one key. * * @example * ```typescript * redis.set("mykey", 0); * const result = await redis.pipeline() * .bitfield("mykey") * .set("u4", 0, 16) * .incr("u4", "#1", 1) * .exec(); * console.log(result); // [[0, 1]] * ``` * * @see https://redis.io/commands/bitfield */ bitfield = (...args) => new BitFieldCommand(args, this.client, this.commandOptions, this.chain.bind(this)); /** * @see https://redis.io/commands/bitop */ bitop = (op, destinationKey, sourceKey, ...sourceKeys) => this.chain( new BitOpCommand([op, destinationKey, sourceKey, ...sourceKeys], this.commandOptions) ); /** * @see https://redis.io/commands/bitpos */ bitpos = (...args) => this.chain(new BitPosCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/copy */ copy = (...args) => this.chain(new CopyCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zdiffstore */ zdiffstore = (...args) => this.chain(new ZDiffStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/dbsize */ dbsize = () => this.chain(new DBSizeCommand(this.commandOptions)); /** * @see https://redis.io/commands/decr */ decr = (...args) => this.chain(new DecrCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/decrby */ decrby = (...args) => this.chain(new DecrByCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/del */ del = (...args) => this.chain(new DelCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/echo */ echo = (...args) => this.chain(new EchoCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/eval */ eval = (...args) => this.chain(new EvalCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/evalsha */ evalsha = (...args) => this.chain(new EvalshaCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/exists */ exists = (...args) => this.chain(new ExistsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/expire */ expire = (...args) => this.chain(new ExpireCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/expireat */ expireat = (...args) => this.chain(new ExpireAtCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/flushall */ flushall = (args) => this.chain(new FlushAllCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/flushdb */ flushdb = (...args) => this.chain(new FlushDBCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/geoadd */ geoadd = (...args) => this.chain(new GeoAddCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/geodist */ geodist = (...args) => this.chain(new GeoDistCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/geopos */ geopos = (...args) => this.chain(new GeoPosCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/geohash */ geohash = (...args) => this.chain(new GeoHashCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/geosearch */ geosearch = (...args) => this.chain(new GeoSearchCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/geosearchstore */ geosearchstore = (...args) => this.chain(new GeoSearchStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/get */ get = (...args) => this.chain(new GetCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/getbit */ getbit = (...args) => this.chain(new GetBitCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/getdel */ getdel = (...args) => this.chain(new GetDelCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/getrange */ getrange = (...args) => this.chain(new GetRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/getset */ getset = (key, value) => this.chain(new GetSetCommand([key, value], this.commandOptions)); /** * @see https://redis.io/commands/hdel */ hdel = (...args) => this.chain(new HDelCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hexists */ hexists = (...args) => this.chain(new HExistsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hget */ hget = (...args) => this.chain(new HGetCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hgetall */ hgetall = (...args) => this.chain(new HGetAllCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hincrby */ hincrby = (...args) => this.chain(new HIncrByCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hincrbyfloat */ hincrbyfloat = (...args) => this.chain(new HIncrByFloatCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hkeys */ hkeys = (...args) => this.chain(new HKeysCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hlen */ hlen = (...args) => this.chain(new HLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hmget */ hmget = (...args) => this.chain(new HMGetCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hmset */ hmset = (key, kv) => this.chain(new HMSetCommand([key, kv], this.commandOptions)); /** * @see https://redis.io/commands/hrandfield */ hrandfield = (key, count, withValues) => this.chain(new HRandFieldCommand([key, count, withValues], this.commandOptions)); /** * @see https://redis.io/commands/hscan */ hscan = (...args) => this.chain(new HScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hset */ hset = (key, kv) => this.chain(new HSetCommand([key, kv], this.commandOptions)); /** * @see https://redis.io/commands/hsetnx */ hsetnx = (key, field, value) => this.chain(new HSetNXCommand([key, field, value], this.commandOptions)); /** * @see https://redis.io/commands/hstrlen */ hstrlen = (...args) => this.chain(new HStrLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/hvals */ hvals = (...args) => this.chain(new HValsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/incr */ incr = (...args) => this.chain(new IncrCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/incrby */ incrby = (...args) => this.chain(new IncrByCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/incrbyfloat */ incrbyfloat = (...args) => this.chain(new IncrByFloatCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/keys */ keys = (...args) => this.chain(new KeysCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lindex */ lindex = (...args) => this.chain(new LIndexCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/linsert */ linsert = (key, direction, pivot, value) => this.chain(new LInsertCommand([key, direction, pivot, value], this.commandOptions)); /** * @see https://redis.io/commands/llen */ llen = (...args) => this.chain(new LLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lmove */ lmove = (...args) => this.chain(new LMoveCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lpop */ lpop = (...args) => this.chain(new LPopCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lmpop */ lmpop = (...args) => this.chain(new LmPopCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lpos */ lpos = (...args) => this.chain(new LPosCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lpush */ lpush = (key, ...elements) => this.chain(new LPushCommand([key, ...elements], this.commandOptions)); /** * @see https://redis.io/commands/lpushx */ lpushx = (key, ...elements) => this.chain(new LPushXCommand([key, ...elements], this.commandOptions)); /** * @see https://redis.io/commands/lrange */ lrange = (...args) => this.chain(new LRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/lrem */ lrem = (key, count, value) => this.chain(new LRemCommand([key, count, value], this.commandOptions)); /** * @see https://redis.io/commands/lset */ lset = (key, index, value) => this.chain(new LSetCommand([key, index, value], this.commandOptions)); /** * @see https://redis.io/commands/ltrim */ ltrim = (...args) => this.chain(new LTrimCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/mget */ mget = (...args) => this.chain(new MGetCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/mset */ mset = (kv) => this.chain(new MSetCommand([kv], this.commandOptions)); /** * @see https://redis.io/commands/msetnx */ msetnx = (kv) => this.chain(new MSetNXCommand([kv], this.commandOptions)); /** * @see https://redis.io/commands/persist */ persist = (...args) => this.chain(new PersistCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pexpire */ pexpire = (...args) => this.chain(new PExpireCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pexpireat */ pexpireat = (...args) => this.chain(new PExpireAtCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pfadd */ pfadd = (...args) => this.chain(new PfAddCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pfcount */ pfcount = (...args) => this.chain(new PfCountCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/pfmerge */ pfmerge = (...args) => this.chain(new PfMergeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/ping */ ping = (args) => this.chain(new PingCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/psetex */ psetex = (key, ttl, value) => this.chain(new PSetEXCommand([key, ttl, value], this.commandOptions)); /** * @see https://redis.io/commands/pttl */ pttl = (...args) => this.chain(new PTtlCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/publish */ publish = (...args) => this.chain(new PublishCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/randomkey */ randomkey = () => this.chain(new RandomKeyCommand(this.commandOptions)); /** * @see https://redis.io/commands/rename */ rename = (...args) => this.chain(new RenameCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/renamenx */ renamenx = (...args) => this.chain(new RenameNXCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/rpop */ rpop = (...args) => this.chain(new RPopCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/rpush */ rpush = (key, ...elements) => this.chain(new RPushCommand([key, ...elements], this.commandOptions)); /** * @see https://redis.io/commands/rpushx */ rpushx = (key, ...elements) => this.chain(new RPushXCommand([key, ...elements], this.commandOptions)); /** * @see https://redis.io/commands/sadd */ sadd = (key, member, ...members) => this.chain(new SAddCommand([key, member, ...members], this.commandOptions)); /** * @see https://redis.io/commands/scan */ scan = (...args) => this.chain(new ScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/scard */ scard = (...args) => this.chain(new SCardCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/script-exists */ scriptExists = (...args) => this.chain(new ScriptExistsCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/script-flush */ scriptFlush = (...args) => this.chain(new ScriptFlushCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/script-load */ scriptLoad = (...args) => this.chain(new ScriptLoadCommand(args, this.commandOptions)); /*)* * @see https://redis.io/commands/sdiff */ sdiff = (...args) => this.chain(new SDiffCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sdiffstore */ sdiffstore = (...args) => this.chain(new SDiffStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/set */ set = (key, value, opts) => this.chain(new SetCommand([key, value, opts], this.commandOptions)); /** * @see https://redis.io/commands/setbit */ setbit = (...args) => this.chain(new SetBitCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/setex */ setex = (key, ttl, value) => this.chain(new SetExCommand([key, ttl, value], this.commandOptions)); /** * @see https://redis.io/commands/setnx */ setnx = (key, value) => this.chain(new SetNxCommand([key, value], this.commandOptions)); /** * @see https://redis.io/commands/setrange */ setrange = (...args) => this.chain(new SetRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sinter */ sinter = (...args) => this.chain(new SInterCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sinterstore */ sinterstore = (...args) => this.chain(new SInterStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sismember */ sismember = (key, member) => this.chain(new SIsMemberCommand([key, member], this.commandOptions)); /** * @see https://redis.io/commands/smembers */ smembers = (...args) => this.chain(new SMembersCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/smismember */ smismember = (key, members) => this.chain(new SMIsMemberCommand([key, members], this.commandOptions)); /** * @see https://redis.io/commands/smove */ smove = (source, destination, member) => this.chain(new SMoveCommand([source, destination, member], this.commandOptions)); /** * @see https://redis.io/commands/spop */ spop = (...args) => this.chain(new SPopCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/srandmember */ srandmember = (...args) => this.chain(new SRandMemberCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/srem */ srem = (key, ...members) => this.chain(new SRemCommand([key, ...members], this.commandOptions)); /** * @see https://redis.io/commands/sscan */ sscan = (...args) => this.chain(new SScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/strlen */ strlen = (...args) => this.chain(new StrLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sunion */ sunion = (...args) => this.chain(new SUnionCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/sunionstore */ sunionstore = (...args) => this.chain(new SUnionStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/time */ time = () => this.chain(new TimeCommand(this.commandOptions)); /** * @see https://redis.io/commands/touch */ touch = (...args) => this.chain(new TouchCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/ttl */ ttl = (...args) => this.chain(new TtlCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/type */ type = (...args) => this.chain(new TypeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/unlink */ unlink = (...args) => this.chain(new UnlinkCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zadd */ zadd = (...args) => { if ("score" in args[1]) { return this.chain( new ZAddCommand([args[0], args[1], ...args.slice(2)], this.commandOptions) ); } return this.chain( new ZAddCommand( [args[0], args[1], ...args.slice(2)], this.commandOptions ) ); }; /** * @see https://redis.io/commands/xadd */ xadd = (...args) => this.chain(new XAddCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xack */ xack = (...args) => this.chain(new XAckCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xdel */ xdel = (...args) => this.chain(new XDelCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xgroup */ xgroup = (...args) => this.chain(new XGroupCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xread */ xread = (...args) => this.chain(new XReadCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xreadgroup */ xreadgroup = (...args) => this.chain(new XReadGroupCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xinfo */ xinfo = (...args) => this.chain(new XInfoCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xlen */ xlen = (...args) => this.chain(new XLenCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xpending */ xpending = (...args) => this.chain(new XPendingCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xclaim */ xclaim = (...args) => this.chain(new XClaimCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xautoclaim */ xautoclaim = (...args) => this.chain(new XAutoClaim(args, this.commandOptions)); /** * @see https://redis.io/commands/xtrim */ xtrim = (...args) => this.chain(new XTrimCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xrange */ xrange = (...args) => this.chain(new XRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/xrevrange */ xrevrange = (...args) => this.chain(new XRevRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zcard */ zcard = (...args) => this.chain(new ZCardCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zcount */ zcount = (...args) => this.chain(new ZCountCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zincrby */ zincrby = (key, increment, member) => this.chain(new ZIncrByCommand([key, increment, member], this.commandOptions)); /** * @see https://redis.io/commands/zinterstore */ zinterstore = (...args) => this.chain(new ZInterStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zlexcount */ zlexcount = (...args) => this.chain(new ZLexCountCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zmscore */ zmscore = (...args) => this.chain(new ZMScoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zpopmax */ zpopmax = (...args) => this.chain(new ZPopMaxCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zpopmin */ zpopmin = (...args) => this.chain(new ZPopMinCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zrange */ zrange = (...args) => this.chain(new ZRangeCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zrank */ zrank = (key, member) => this.chain(new ZRankCommand([key, member], this.commandOptions)); /** * @see https://redis.io/commands/zrem */ zrem = (key, ...members) => this.chain(new ZRemCommand([key, ...members], this.commandOptions)); /** * @see https://redis.io/commands/zremrangebylex */ zremrangebylex = (...args) => this.chain(new ZRemRangeByLexCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zremrangebyrank */ zremrangebyrank = (...args) => this.chain(new ZRemRangeByRankCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zremrangebyscore */ zremrangebyscore = (...args) => this.chain(new ZRemRangeByScoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zrevrank */ zrevrank = (key, member) => this.chain(new ZRevRankCommand([key, member], this.commandOptions)); /** * @see https://redis.io/commands/zscan */ zscan = (...args) => this.chain(new ZScanCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zscore */ zscore = (key, member) => this.chain(new ZScoreCommand([key, member], this.commandOptions)); /** * @see https://redis.io/commands/zunionstore */ zunionstore = (...args) => this.chain(new ZUnionStoreCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/zunion */ zunion = (...args) => this.chain(new ZUnionCommand(args, this.commandOptions)); /** * @see https://redis.io/commands/?group=json */ get json() { return { /** * @see https://redis.io/commands/json.arrappend */ arrappend: (...args) => this.chain(new JsonArrAppendCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrindex */ arrindex: (...args) => this.chain(new JsonArrIndexCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrinsert */ arrinsert: (...args) => this.chain(new JsonArrInsertCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrlen */ arrlen: (...args) => this.chain(new JsonArrLenCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrpop */ arrpop: (...args) => this.chain(new JsonArrPopCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.arrtrim */ arrtrim: (...args) => this.chain(new JsonArrTrimCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.clear */ clear: (...args) => this.chain(new JsonClearCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.del */ del: (...args) => this.chain(new JsonDelCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.forget */ forget: (...args) => this.chain(new JsonForgetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.get */ get: (...args) => this.chain(new JsonGetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.mget */ mget: (...args) => this.chain(new JsonMGetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.mset */ mset: (...args) => this.chain(new JsonMSetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.numincrby */ numincrby: (...args) => this.chain(new JsonNumIncrByCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.nummultby */ nummultby: (...args) => this.chain(new JsonNumMultByCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.objkeys */ objkeys: (...args) => this.chain(new JsonObjKeysCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.objlen */ objlen: (...args) => this.chain(new JsonObjLenCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.resp */ resp: (...args) => this.chain(new JsonRespCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.set */ set: (...args) => this.chain(new JsonSetCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.strappend */ strappend: (...args) => this.chain(new JsonStrAppendCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.strlen */ strlen: (...args) => this.chain(new JsonStrLenCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.toggle */ toggle: (...args) => this.chain(new JsonToggleCommand(args, this.commandOptions)), /** * @see https://redis.io/commands/json.type */ type: (...args) => this.chain(new JsonTypeCommand(args, this.commandOptions)) }; } }; // pkg/script.ts var import_enc_hex = __toESM(__nccwpck_require__(606)); var import_sha1 = __toESM(__nccwpck_require__(377)); var Script = class { script; sha1; redis; constructor(redis, script) { this.redis = redis; this.sha1 = this.digest(script); this.script = script; } /** * Send an `EVAL` command to redis. */ async eval(keys, args) { return await this.redis.eval(this.script, keys, args); } /** * Calculates the sha1 hash of the script and then calls `EVALSHA`. */ async evalsha(keys, args) { return await this.redis.evalsha(this.sha1, keys, args); } /** * Optimistically try to run `EVALSHA` first. * If the script is not loaded in redis, it will fall back and try again with `EVAL`. * * Following calls will be able to use the cached script */ async exec(keys, args) { const res = await this.redis.evalsha(this.sha1, keys, args).catch(async (error) => { if (error instanceof Error && error.message.toLowerCase().includes("noscript")) { return await this.redis.eval(this.script, keys, args); } throw error; }); return res; } /** * Compute the sha1 hash of the script and return its hex representation. */ digest(s) { return import_enc_hex.default.stringify((0, import_sha1.default)(s)); } }; // pkg/redis.ts var Redis = class { client; opts; enableTelemetry; enableAutoPipelining; /** * Create a new redis client * * @example * ```typescript * const redis = new Redis({ * url: "", * token: "", * }); * ``` */ constructor(client, opts) { this.client = client; this.opts = opts; this.enableTelemetry = opts?.enableTelemetry ?? true; if (opts?.readYourWrites === false) { this.client.readYourWrites = false; } this.enableAutoPipelining = opts?.enableAutoPipelining ?? true; } get readYourWritesSyncToken() { return this.client.upstashSyncToken; } set readYourWritesSyncToken(session) { this.client.upstashSyncToken = session; } get json() { return { /** * @see https://redis.io/commands/json.arrappend */ arrappend: (...args) => new JsonArrAppendCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.arrindex */ arrindex: (...args) => new JsonArrIndexCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.arrinsert */ arrinsert: (...args) => new JsonArrInsertCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.arrlen */ arrlen: (...args) => new JsonArrLenCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.arrpop */ arrpop: (...args) => new JsonArrPopCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.arrtrim */ arrtrim: (...args) => new JsonArrTrimCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.clear */ clear: (...args) => new JsonClearCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.del */ del: (...args) => new JsonDelCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.forget */ forget: (...args) => new JsonForgetCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.get */ get: (...args) => new JsonGetCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.mget */ mget: (...args) => new JsonMGetCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.mset */ mset: (...args) => new JsonMSetCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.numincrby */ numincrby: (...args) => new JsonNumIncrByCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.nummultby */ nummultby: (...args) => new JsonNumMultByCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.objkeys */ objkeys: (...args) => new JsonObjKeysCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.objlen */ objlen: (...args) => new JsonObjLenCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.resp */ resp: (...args) => new JsonRespCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.set */ set: (...args) => new JsonSetCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.strappend */ strappend: (...args) => new JsonStrAppendCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.strlen */ strlen: (...args) => new JsonStrLenCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.toggle */ toggle: (...args) => new JsonToggleCommand(args, this.opts).exec(this.client), /** * @see https://redis.io/commands/json.type */ type: (...args) => new JsonTypeCommand(args, this.opts).exec(this.client) }; } /** * Wrap a new middleware around the HTTP client. */ use = (middleware) => { const makeRequest = this.client.request.bind(this.client); this.client.request = (req) => middleware(req, makeRequest); }; /** * Technically this is not private, we can hide it from intellisense by doing this */ addTelemetry = (telemetry) => { if (!this.enableTelemetry) { return; } try { this.client.mergeTelemetry(telemetry); } catch { } }; createScript(script) { return new Script(this, script); } /** * Create a new pipeline that allows you to send requests in bulk. * * @see {@link Pipeline} */ pipeline = () => new Pipeline({ client: this.client, commandOptions: this.opts, multiExec: false }); autoPipeline = () => { return createAutoPipelineProxy(this); }; /** * Create a new transaction to allow executing multiple steps atomically. * * All the commands in a transaction are serialized and executed sequentially. A request sent by * another client will never be served in the middle of the execution of a Redis Transaction. This * guarantees that the commands are executed as a single isolated operation. * * @see {@link Pipeline} */ multi = () => new Pipeline({ client: this.client, commandOptions: this.opts, multiExec: true }); /** * Returns an instance that can be used to execute `BITFIELD` commands on one key. * * @example * ```typescript * redis.set("mykey", 0); * const result = await redis.bitfield("mykey") * .set("u4", 0, 16) * .incr("u4", "#1", 1) * .exec(); * console.log(result); // [0, 1] * ``` * * @see https://redis.io/commands/bitfield */ bitfield = (...args) => new BitFieldCommand(args, this.client, this.opts); /** * @see https://redis.io/commands/append */ append = (...args) => new AppendCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/bitcount */ bitcount = (...args) => new BitCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/bitop */ bitop = (op, destinationKey, sourceKey, ...sourceKeys) => new BitOpCommand([op, destinationKey, sourceKey, ...sourceKeys], this.opts).exec( this.client ); /** * @see https://redis.io/commands/bitpos */ bitpos = (...args) => new BitPosCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/copy */ copy = (...args) => new CopyCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/dbsize */ dbsize = () => new DBSizeCommand(this.opts).exec(this.client); /** * @see https://redis.io/commands/decr */ decr = (...args) => new DecrCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/decrby */ decrby = (...args) => new DecrByCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/del */ del = (...args) => new DelCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/echo */ echo = (...args) => new EchoCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/eval */ eval = (...args) => new EvalCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/evalsha */ evalsha = (...args) => new EvalshaCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/exists */ exists = (...args) => new ExistsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/expire */ expire = (...args) => new ExpireCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/expireat */ expireat = (...args) => new ExpireAtCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/flushall */ flushall = (args) => new FlushAllCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/flushdb */ flushdb = (...args) => new FlushDBCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/geoadd */ geoadd = (...args) => new GeoAddCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/geopos */ geopos = (...args) => new GeoPosCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/geodist */ geodist = (...args) => new GeoDistCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/geohash */ geohash = (...args) => new GeoHashCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/geosearch */ geosearch = (...args) => new GeoSearchCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/geosearchstore */ geosearchstore = (...args) => new GeoSearchStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/get */ get = (...args) => new GetCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getbit */ getbit = (...args) => new GetBitCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getdel */ getdel = (...args) => new GetDelCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getrange */ getrange = (...args) => new GetRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/getset */ getset = (key, value) => new GetSetCommand([key, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/hdel */ hdel = (...args) => new HDelCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hexists */ hexists = (...args) => new HExistsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hget */ hget = (...args) => new HGetCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hgetall */ hgetall = (...args) => new HGetAllCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hincrby */ hincrby = (...args) => new HIncrByCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hincrbyfloat */ hincrbyfloat = (...args) => new HIncrByFloatCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hkeys */ hkeys = (...args) => new HKeysCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hlen */ hlen = (...args) => new HLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hmget */ hmget = (...args) => new HMGetCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hmset */ hmset = (key, kv) => new HMSetCommand([key, kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/hrandfield */ hrandfield = (key, count, withValues) => new HRandFieldCommand([key, count, withValues], this.opts).exec(this.client); /** * @see https://redis.io/commands/hscan */ hscan = (...args) => new HScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hset */ hset = (key, kv) => new HSetCommand([key, kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/hsetnx */ hsetnx = (key, field, value) => new HSetNXCommand([key, field, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/hstrlen */ hstrlen = (...args) => new HStrLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/hvals */ hvals = (...args) => new HValsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/incr */ incr = (...args) => new IncrCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/incrby */ incrby = (...args) => new IncrByCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/incrbyfloat */ incrbyfloat = (...args) => new IncrByFloatCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/keys */ keys = (...args) => new KeysCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lindex */ lindex = (...args) => new LIndexCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/linsert */ linsert = (key, direction, pivot, value) => new LInsertCommand([key, direction, pivot, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/llen */ llen = (...args) => new LLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lmove */ lmove = (...args) => new LMoveCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lpop */ lpop = (...args) => new LPopCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lmpop */ lmpop = (...args) => new LmPopCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lpos */ lpos = (...args) => new LPosCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lpush */ lpush = (key, ...elements) => new LPushCommand([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/lpushx */ lpushx = (key, ...elements) => new LPushXCommand([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/lrange */ lrange = (...args) => new LRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/lrem */ lrem = (key, count, value) => new LRemCommand([key, count, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/lset */ lset = (key, index, value) => new LSetCommand([key, index, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/ltrim */ ltrim = (...args) => new LTrimCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/mget */ mget = (...args) => new MGetCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/mset */ mset = (kv) => new MSetCommand([kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/msetnx */ msetnx = (kv) => new MSetNXCommand([kv], this.opts).exec(this.client); /** * @see https://redis.io/commands/persist */ persist = (...args) => new PersistCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pexpire */ pexpire = (...args) => new PExpireCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pexpireat */ pexpireat = (...args) => new PExpireAtCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pfadd */ pfadd = (...args) => new PfAddCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pfcount */ pfcount = (...args) => new PfCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/pfmerge */ pfmerge = (...args) => new PfMergeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/ping */ ping = (args) => new PingCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/psetex */ psetex = (key, ttl, value) => new PSetEXCommand([key, ttl, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/pttl */ pttl = (...args) => new PTtlCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/publish */ publish = (...args) => new PublishCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/randomkey */ randomkey = () => new RandomKeyCommand().exec(this.client); /** * @see https://redis.io/commands/rename */ rename = (...args) => new RenameCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/renamenx */ renamenx = (...args) => new RenameNXCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/rpop */ rpop = (...args) => new RPopCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/rpush */ rpush = (key, ...elements) => new RPushCommand([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/rpushx */ rpushx = (key, ...elements) => new RPushXCommand([key, ...elements], this.opts).exec(this.client); /** * @see https://redis.io/commands/sadd */ sadd = (key, member, ...members) => new SAddCommand([key, member, ...members], this.opts).exec(this.client); /** * @see https://redis.io/commands/scan */ scan = (...args) => new ScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/scard */ scard = (...args) => new SCardCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/script-exists */ scriptExists = (...args) => new ScriptExistsCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/script-flush */ scriptFlush = (...args) => new ScriptFlushCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/script-load */ scriptLoad = (...args) => new ScriptLoadCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sdiff */ sdiff = (...args) => new SDiffCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sdiffstore */ sdiffstore = (...args) => new SDiffStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/set */ set = (key, value, opts) => new SetCommand([key, value, opts], this.opts).exec(this.client); /** * @see https://redis.io/commands/setbit */ setbit = (...args) => new SetBitCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/setex */ setex = (key, ttl, value) => new SetExCommand([key, ttl, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/setnx */ setnx = (key, value) => new SetNxCommand([key, value], this.opts).exec(this.client); /** * @see https://redis.io/commands/setrange */ setrange = (...args) => new SetRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sinter */ sinter = (...args) => new SInterCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sinterstore */ sinterstore = (...args) => new SInterStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sismember */ sismember = (key, member) => new SIsMemberCommand([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/smismember */ smismember = (key, members) => new SMIsMemberCommand([key, members], this.opts).exec(this.client); /** * @see https://redis.io/commands/smembers */ smembers = (...args) => new SMembersCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/smove */ smove = (source, destination, member) => new SMoveCommand([source, destination, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/spop */ spop = (...args) => new SPopCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/srandmember */ srandmember = (...args) => new SRandMemberCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/srem */ srem = (key, ...members) => new SRemCommand([key, ...members], this.opts).exec(this.client); /** * @see https://redis.io/commands/sscan */ sscan = (...args) => new SScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/strlen */ strlen = (...args) => new StrLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sunion */ sunion = (...args) => new SUnionCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/sunionstore */ sunionstore = (...args) => new SUnionStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/time */ time = () => new TimeCommand().exec(this.client); /** * @see https://redis.io/commands/touch */ touch = (...args) => new TouchCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/ttl */ ttl = (...args) => new TtlCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/type */ type = (...args) => new TypeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/unlink */ unlink = (...args) => new UnlinkCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xadd */ xadd = (...args) => new XAddCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xack */ xack = (...args) => new XAckCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xdel */ xdel = (...args) => new XDelCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xgroup */ xgroup = (...args) => new XGroupCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xread */ xread = (...args) => new XReadCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xreadgroup */ xreadgroup = (...args) => new XReadGroupCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xinfo */ xinfo = (...args) => new XInfoCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xlen */ xlen = (...args) => new XLenCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xpending */ xpending = (...args) => new XPendingCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xclaim */ xclaim = (...args) => new XClaimCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xautoclaim */ xautoclaim = (...args) => new XAutoClaim(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xtrim */ xtrim = (...args) => new XTrimCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xrange */ xrange = (...args) => new XRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/xrevrange */ xrevrange = (...args) => new XRevRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zadd */ zadd = (...args) => { if ("score" in args[1]) { return new ZAddCommand([args[0], args[1], ...args.slice(2)], this.opts).exec( this.client ); } return new ZAddCommand( [args[0], args[1], ...args.slice(2)], this.opts ).exec(this.client); }; /** * @see https://redis.io/commands/zcard */ zcard = (...args) => new ZCardCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zcount */ zcount = (...args) => new ZCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zdiffstore */ zdiffstore = (...args) => new ZDiffStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zincrby */ zincrby = (key, increment, member) => new ZIncrByCommand([key, increment, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zinterstore */ zinterstore = (...args) => new ZInterStoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zlexcount */ zlexcount = (...args) => new ZLexCountCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zmscore */ zmscore = (...args) => new ZMScoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zpopmax */ zpopmax = (...args) => new ZPopMaxCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zpopmin */ zpopmin = (...args) => new ZPopMinCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zrange */ zrange = (...args) => new ZRangeCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zrank */ zrank = (key, member) => new ZRankCommand([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zrem */ zrem = (key, ...members) => new ZRemCommand([key, ...members], this.opts).exec(this.client); /** * @see https://redis.io/commands/zremrangebylex */ zremrangebylex = (...args) => new ZRemRangeByLexCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zremrangebyrank */ zremrangebyrank = (...args) => new ZRemRangeByRankCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zremrangebyscore */ zremrangebyscore = (...args) => new ZRemRangeByScoreCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zrevrank */ zrevrank = (key, member) => new ZRevRankCommand([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zscan */ zscan = (...args) => new ZScanCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zscore */ zscore = (key, member) => new ZScoreCommand([key, member], this.opts).exec(this.client); /** * @see https://redis.io/commands/zunion */ zunion = (...args) => new ZUnionCommand(args, this.opts).exec(this.client); /** * @see https://redis.io/commands/zunionstore */ zunionstore = (...args) => new ZUnionStoreCommand(args, this.opts).exec(this.client); }; // version.ts var VERSION = "v1.34.3"; // platforms/nodejs.ts if (typeof atob === "undefined") { global.atob = (b64) => Buffer.from(b64, "base64").toString("utf8"); } var Redis2 = class _Redis extends Redis { /** * Create a new redis client by providing a custom `Requester` implementation * * @example * ```ts * * import { UpstashRequest, Requester, UpstashResponse, Redis } from "@upstash/redis" * * const requester: Requester = { * request: (req: UpstashRequest): Promise> => { * // ... * } * } * * const redis = new Redis(requester) * ``` */ constructor(configOrRequester) { if ("request" in configOrRequester) { super(configOrRequester); return; } if (!configOrRequester.url) { console.warn( `[Upstash Redis] The 'url' property is missing or undefined in your Redis config.` ); } else if (configOrRequester.url.startsWith(" ") || configOrRequester.url.endsWith(" ") || /\r|\n/.test(configOrRequester.url)) { console.warn( "[Upstash Redis] The redis url contains whitespace or newline, which can cause errors!" ); } if (!configOrRequester.token) { console.warn( `[Upstash Redis] The 'token' property is missing or undefined in your Redis config.` ); } else if (configOrRequester.token.startsWith(" ") || configOrRequester.token.endsWith(" ") || /\r|\n/.test(configOrRequester.token)) { console.warn( "[Upstash Redis] The redis token contains whitespace or newline, which can cause errors!" ); } const client = new HttpClient({ baseUrl: configOrRequester.url, retry: configOrRequester.retry, headers: { authorization: `Bearer ${configOrRequester.token}` }, agent: configOrRequester.agent, responseEncoding: configOrRequester.responseEncoding, cache: configOrRequester.cache ?? "no-store", signal: configOrRequester.signal, keepAlive: configOrRequester.keepAlive, readYourWrites: configOrRequester.readYourWrites }); super(client, { automaticDeserialization: configOrRequester.automaticDeserialization, enableTelemetry: !process.env.UPSTASH_DISABLE_TELEMETRY, latencyLogging: configOrRequester.latencyLogging, enableAutoPipelining: configOrRequester.enableAutoPipelining }); this.addTelemetry({ runtime: ( // @ts-expect-error to silence compiler typeof EdgeRuntime === "string" ? "edge-light" : `node@${process.version}` ), platform: process.env.VERCEL ? "vercel" : process.env.AWS_REGION ? "aws" : "unknown", sdk: `@upstash/redis@${VERSION}` }); if (this.enableAutoPipelining) { return this.autoPipeline(); } } /** * Create a new Upstash Redis instance from environment variables. * * Use this to automatically load connection secrets from your environment * variables. For instance when using the Vercel integration. * * This tries to load `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from * your environment using `process.env`. */ static fromEnv(config) { if (process.env === void 0) { 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' ); } const url = process.env.UPSTASH_REDIS_REST_URL || process.env.KV_REST_API_URL; if (!url) { console.warn("[Upstash Redis] Unable to find environment variable: `UPSTASH_REDIS_REST_URL`"); } const token = process.env.UPSTASH_REDIS_REST_TOKEN || process.env.KV_REST_API_TOKEN; if (!token) { console.warn( "[Upstash Redis] Unable to find environment variable: `UPSTASH_REDIS_REST_TOKEN`" ); } return new _Redis({ ...config, url, token }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 255: /***/ (function(module, exports, __nccwpck_require__) { ;(function (root, factory) { if (true) { // CommonJS module.exports = exports = factory(); } else {} }(this, function () { /*globals window, global, require*/ /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { var crypto; // Native crypto from window (Browser) if (typeof window !== 'undefined' && window.crypto) { crypto = window.crypto; } // Native crypto in web worker (Browser) if (typeof self !== 'undefined' && self.crypto) { crypto = self.crypto; } // Native crypto from worker if (typeof globalThis !== 'undefined' && globalThis.crypto) { crypto = globalThis.crypto; } // Native (experimental IE 11) crypto from window (Browser) if (!crypto && typeof window !== 'undefined' && window.msCrypto) { crypto = window.msCrypto; } // Native crypto from global (NodeJS) if (!crypto && typeof global !== 'undefined' && global.crypto) { crypto = global.crypto; } // Native crypto import via require (NodeJS) if (!crypto && "function" === 'function') { try { crypto = __nccwpck_require__(982); } catch (err) {} } /* * Cryptographically secure pseudorandom number generator * * As Math.random() is cryptographically not safe to use */ var cryptoSecureRandomInt = function () { if (crypto) { // Use getRandomValues method (Browser) if (typeof crypto.getRandomValues === 'function') { try { return crypto.getRandomValues(new Uint32Array(1))[0]; } catch (err) {} } // Use randomBytes method (NodeJS) if (typeof crypto.randomBytes === 'function') { try { return crypto.randomBytes(4).readInt32LE(); } catch (err) {} } } throw new Error('Native crypto module could not be used to get secure random number.'); }; /* * Local polyfill of Object.create */ var create = Object.create || (function () { function F() {} return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()); /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var j = 0; j < thatSigBytes; j += 4) { thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; for (var i = 0; i < nBytes; i += 4) { words.push(cryptoSecureRandomInt()); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { var processedWords; // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); /***/ }), /***/ 606: /***/ (function(module, exports, __nccwpck_require__) { ;(function (root, factory) { if (true) { // CommonJS module.exports = exports = factory(__nccwpck_require__(255)); } else {} }(this, function (CryptoJS) { return CryptoJS.enc.Hex; })); /***/ }), /***/ 377: /***/ (function(module, exports, __nccwpck_require__) { ;(function (root, factory) { if (true) { // CommonJS module.exports = exports = factory(__nccwpck_require__(255)); } else {} }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); /***/ }), /***/ 982: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 943: /***/ ((module) => { "use strict"; module.exports = require("fs/promises"); /***/ }), /***/ 928: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 287: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({value: true}));// src/index.ts var _redis = __nccwpck_require__(722); var _kv = null; process.env.UPSTASH_DISABLE_TELEMETRY = "1"; var VercelKV = class extends _redis.Redis { // This API is based on https://github.com/redis/node-redis#scan-iterator which is not supported in @upstash/redis /** * Same as `scan` but returns an AsyncIterator to allow iteration via `for await`. */ async *scanIterator(options) { let cursor = "0"; let keys; do { [cursor, keys] = await this.scan(cursor, options); for (const key of keys) { yield key; } } while (cursor !== "0"); } /** * Same as `hscan` but returns an AsyncIterator to allow iteration via `for await`. */ async *hscanIterator(key, options) { let cursor = "0"; let items; do { [cursor, items] = await this.hscan(key, cursor, options); for (const item of items) { yield item; } } while (cursor !== "0"); } /** * Same as `sscan` but returns an AsyncIterator to allow iteration via `for await`. */ async *sscanIterator(key, options) { let cursor = "0"; let items; do { [cursor, items] = await this.sscan(key, cursor, options); for (const item of items) { yield item; } } while (cursor !== "0"); } /** * Same as `zscan` but returns an AsyncIterator to allow iteration via `for await`. */ async *zscanIterator(key, options) { let cursor = "0"; let items; do { [cursor, items] = await this.zscan(key, cursor, options); for (const item of items) { yield item; } } while (cursor !== "0"); } }; function createClient(config) { return new VercelKV({ // The Next.js team recommends no value or `default` for fetch requests's `cache` option // upstash/redis defaults to `no-store`, so we enforce `default` cache: "default", enableAutoPipelining: true, ...config }); } var src_default = new Proxy( {}, { get(target, prop, receiver) { if (prop === "then" || prop === "parse") { return Reflect.get(target, prop, receiver); } if (!_kv) { if (!process.env.KV_REST_API_URL || !process.env.KV_REST_API_TOKEN) { throw new Error( "@vercel/kv: Missing required environment variables KV_REST_API_URL and KV_REST_API_TOKEN" ); } console.warn( '\x1B[33m"The default export has been moved to a named export and it will be removed in version 1, change to import { kv }\x1B[0m"' ); _kv = createClient({ url: process.env.KV_REST_API_URL, token: process.env.KV_REST_API_TOKEN }); } return Reflect.get(_kv, prop); } } ); var kv = new Proxy( {}, { get(target, prop) { if (!_kv) { if (!process.env.KV_REST_API_URL || !process.env.KV_REST_API_TOKEN) { throw new Error( "@vercel/kv: Missing required environment variables KV_REST_API_URL and KV_REST_API_TOKEN" ); } _kv = createClient({ url: process.env.KV_REST_API_URL, token: process.env.KV_REST_API_TOKEN }); } return Reflect.get(_kv, prop); } } ); exports.VercelKV = VercelKV; exports.createClient = createClient; exports["default"] = src_default; exports.kv = kv; //# sourceMappingURL=index.cjs.map /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ /************************************************************************/ var __webpack_exports__ = {}; const fs = __nccwpck_require__(943) const path = __nccwpck_require__(928) const { createClient } = __nccwpck_require__(287) async function collectExamplesResult(manifestFile) { const file = path.join(process.cwd(), manifestFile) const contents = await fs.readFile(file, 'utf-8') const results = JSON.parse(contents) let failingCount = 0 let passingCount = 0 const currentDate = new Date() const isoString = currentDate.toISOString() const timestamp = isoString.slice(0, 19).replace('T', ' ') for (const isPassing of Object.values(results)) { if (isPassing) { passingCount += 1 } else { failingCount += 1 } } const status = `${process.env.GITHUB_SHA}\t${timestamp}\t${passingCount}/${ passingCount + failingCount }` return { status, // Uses JSON.stringify to create minified JSON, otherwise whitespace is preserved. data: JSON.stringify(results), } } async function collectResults(manifestFile) { const file = path.join(process.cwd(), manifestFile) const contents = await fs.readFile(file, 'utf-8') const results = JSON.parse(contents) let passingTests = '' let failingTests = '' let passCount = 0 let failCount = 0 const currentDate = new Date() const isoString = currentDate.toISOString() const timestamp = isoString.slice(0, 19).replace('T', ' ') if (results.version === 2) { for (const [testFileName, result] of Object.entries(results.suites)) { let suitePassCount = 0 let suiteFailCount = 0 suitePassCount += result.passed.length suiteFailCount += result.failed.length if (suitePassCount > 0) { passingTests += `${testFileName}\n` } if (suiteFailCount > 0) { failingTests += `${testFileName}\n` } for (const passed of result.passed) { const passedName = passed.replaceAll('`', '\\`') passingTests += `* ${passedName}\n` } for (const passed of result.failed) { const failedName = passed.replaceAll('`', '\\`') failingTests += `* ${failedName}\n` } passCount += suitePassCount failCount += suiteFailCount if (suitePassCount > 0) { passingTests += `\n` } if (suiteFailCount > 0) { failingTests += `\n` } } const testRun = `${process.env.GITHUB_SHA}\t${timestamp}\t${passCount}/${ passCount + failCount }` return { testRun, passingTests, failingTests } } else { for (const [testFileName, result] of Object.entries(results)) { let suitePassCount = 0 let suiteFailCount = 0 suitePassCount += result.passed.length suiteFailCount += result.failed.length if (suitePassCount > 0) { passingTests += `${testFileName}\n` } if (suiteFailCount > 0) { failingTests += `${testFileName}\n` } for (const passed of result.passed) { const passedName = passed.replaceAll('`', '\\`') passingTests += `* ${passedName}\n` } for (const passed of result.failed) { const failedName = passed.replaceAll('`', '\\`') failingTests += `* ${failedName}\n` } passCount += suitePassCount failCount += suiteFailCount if (suitePassCount > 0) { passingTests += `\n` } if (suiteFailCount > 0) { failingTests += `\n` } } const testRun = `${process.env.GITHUB_SHA}\t${timestamp}\t${passCount}/${ passCount + failCount }` return { testRun, passingTests, failingTests } } } async function collectAndUpload( kv, { jsonPrefix, kvPrefix, deploymentDomain } ) { const developmentResult = await collectResults( `test/${jsonPrefix}dev-tests-manifest.json` ) const productionResult = await collectResults( `test/${jsonPrefix}build-tests-manifest.json` ) const developmentExamplesResult = await collectExamplesResult( `test/${jsonPrefix}dev-examples-manifest.json` ) console.log('TEST RESULT DEVELOPMENT') console.log(developmentResult.testRun) console.log('TEST RESULT PRODUCTION') console.log(productionResult.testRun) console.log('EXAMPLES RESULT') console.log(developmentExamplesResult.status) await kv.rpush(`${kvPrefix}test-runs`, developmentResult.testRun) await kv.rpush(`${kvPrefix}test-runs-production`, productionResult.testRun) await kv.rpush(`${kvPrefix}examples-runs`, developmentExamplesResult.status) console.log('SUCCESSFULLY SAVED RUNS') await kv.set(`${kvPrefix}passing-tests`, developmentResult.passingTests) await kv.set( `${kvPrefix}passing-tests-production`, productionResult.passingTests ) console.log('SUCCESSFULLY SAVED PASSING') await kv.set(`${kvPrefix}failing-tests`, developmentResult.failingTests) await kv.set( `${kvPrefix}failing-tests-production`, productionResult.failingTests ) console.log('SUCCESSFULLY SAVED FAILING') await kv.set(`${kvPrefix}examples-data`, developmentExamplesResult.data) console.log('SUCCESSFULLY SAVED EXAMPLES') if (deploymentDomain != null) { // Upstash does not provide strong consistency, so just wait a couple // seconds before invalidating the cache in case of replication lag. // // https://upstash.com/docs/redis/features/consistency await new Promise((resolve) => setTimeout(resolve, 2000)) try { const response = await fetch( `https://${deploymentDomain}/api/revalidate`, { method: 'POST', headers: { 'X-Auth-Token': process.env.TURBOYET_TOKEN, 'Content-Type': 'application/json', }, } ) const responseJson = await response.json() if (!responseJson.revalidated) { throw new Error(responseJson.error) } console.log('SUCCESSFULLY REVALIDATED VERCEL DATA CACHE') } catch (error) { // non-fatal: the cache will eventually expire anyways console.error('FAILED TO REVALIDATE VERCEL DATA CACHE', error) } } } async function main() { try { const kv = createClient({ url: process.env.TURBOYET_KV_REST_API_URL, token: process.env.TURBOYET_KV_REST_API_TOKEN, }) console.log('### UPLOADING TURBOPACK DATA') await collectAndUpload(kv, { jsonPrefix: 'turbopack-', kvPrefix: '', deploymentDomain: 'areweturboyet.com', }) console.log('### UPLOADING RSPACK DATA') await collectAndUpload(kv, { jsonPrefix: 'rspack-', kvPrefix: 'rspack-', deploymentDomain: 'arewerspackyet.com', }) } catch (error) { console.log(error) } } main() module.exports = __webpack_exports__; /******/ })() ; //# sourceMappingURL=index.js.map