UNPKG

@valkey/valkey-glide

Version:

General Language Independent Driver for the Enterprise (GLIDE) for Valkey

1,663 lines 87.7 kB
"use strict"; /** * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0 */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimeUnit = exports.ScoreFilter = exports.SortOrder = exports.GeoUnit = exports.HashExpirationCondition = exports.HashFieldConditionalChange = exports.ConditionalChange = exports.FlushMode = exports.BitmapIndexType = exports.FunctionRestorePolicy = exports.InsertPosition = exports.InfBoundary = exports.UpdateByScore = exports.ExpireOptions = exports.ListDirection = exports.BitFieldOverflow = exports.BitOverflowControl = exports.BitFieldIncrBy = exports.BitFieldSet = exports.BitFieldGet = exports.BitOffsetMultiplier = exports.BitOffset = exports.UnsignedEncoding = exports.SignedEncoding = exports.BitwiseOperation = exports.InfoOptions = void 0; exports.parseInfoResponse = parseInfoResponse; exports.createGet = createGet; exports.createGetDel = createGetDel; exports.createGetRange = createGetRange; exports.createSet = createSet; exports.createPing = createPing; exports.createInfo = createInfo; exports.createDel = createDel; exports.createSelect = createSelect; exports.createClientGetName = createClientGetName; exports.createConfigRewrite = createConfigRewrite; exports.createConfigResetStat = createConfigResetStat; exports.createMGet = createMGet; exports.createMSet = createMSet; exports.createMSetNX = createMSetNX; exports.createIncr = createIncr; exports.createIncrBy = createIncrBy; exports.createIncrByFloat = createIncrByFloat; exports.createClientId = createClientId; exports.createConfigGet = createConfigGet; exports.createConfigSet = createConfigSet; exports.createHGet = createHGet; exports.convertFieldsAndValuesToHashDataType = convertFieldsAndValuesToHashDataType; exports.createHSet = createHSet; exports.createHKeys = createHKeys; exports.createHSetNX = createHSetNX; exports.createHSetEx = createHSetEx; exports.createHGetEx = createHGetEx; exports.createHExpire = createHExpire; exports.createHPersist = createHPersist; exports.createHPExpire = createHPExpire; exports.createHExpireAt = createHExpireAt; exports.createHPExpireAt = createHPExpireAt; exports.createHTtl = createHTtl; exports.createHPTtl = createHPTtl; exports.createHExpireTime = createHExpireTime; exports.createHPExpireTime = createHPExpireTime; exports.createDecr = createDecr; exports.createDecrBy = createDecrBy; exports.createBitOp = createBitOp; exports.createGetBit = createGetBit; exports.createSetBit = createSetBit; exports.createBitField = createBitField; exports.createHDel = createHDel; exports.createHMGet = createHMGet; exports.createHExists = createHExists; exports.createHGetAll = createHGetAll; exports.createLPush = createLPush; exports.createLPushX = createLPushX; exports.createLPop = createLPop; exports.createLRange = createLRange; exports.createLLen = createLLen; exports.createLMove = createLMove; exports.createBLMove = createBLMove; exports.createLSet = createLSet; exports.createLTrim = createLTrim; exports.createLRem = createLRem; exports.createRPush = createRPush; exports.createRPushX = createRPushX; exports.createRPop = createRPop; exports.createSAdd = createSAdd; exports.createSRem = createSRem; exports.createSScan = createSScan; exports.createSMembers = createSMembers; exports.createSMove = createSMove; exports.createSCard = createSCard; exports.createSInter = createSInter; exports.createSInterCard = createSInterCard; exports.createSInterStore = createSInterStore; exports.createSDiff = createSDiff; exports.createSDiffStore = createSDiffStore; exports.createSUnion = createSUnion; exports.createSUnionStore = createSUnionStore; exports.createSIsMember = createSIsMember; exports.createSMIsMember = createSMIsMember; exports.createSPop = createSPop; exports.createSRandMember = createSRandMember; exports.createCustomCommand = createCustomCommand; exports.createHIncrBy = createHIncrBy; exports.createHIncrByFloat = createHIncrByFloat; exports.createHLen = createHLen; exports.createHVals = createHVals; exports.createExists = createExists; exports.createUnlink = createUnlink; exports.createExpire = createExpire; exports.createExpireAt = createExpireAt; exports.createExpireTime = createExpireTime; exports.createPExpire = createPExpire; exports.createPExpireAt = createPExpireAt; exports.createPExpireTime = createPExpireTime; exports.createTTL = createTTL; exports.convertElementsAndScores = convertElementsAndScores; exports.createZAdd = createZAdd; exports.createZInterstore = createZInterstore; exports.createZInter = createZInter; exports.createZUnion = createZUnion; exports.createZRem = createZRem; exports.createZCard = createZCard; exports.createZInterCard = createZInterCard; exports.createZDiff = createZDiff; exports.createZDiffWithScores = createZDiffWithScores; exports.createZDiffStore = createZDiffStore; exports.createZScore = createZScore; exports.createZUnionStore = createZUnionStore; exports.createZMScore = createZMScore; exports.createScan = createScan; exports.createZCount = createZCount; exports.createZRange = createZRange; exports.createZRangeWithScores = createZRangeWithScores; exports.createZRangeStore = createZRangeStore; exports.createType = createType; exports.createStrlen = createStrlen; exports.createLIndex = createLIndex; exports.createLInsert = createLInsert; exports.createZPopMin = createZPopMin; exports.createZPopMax = createZPopMax; exports.createEcho = createEcho; exports.createPTTL = createPTTL; exports.createZRemRangeByRank = createZRemRangeByRank; exports.createZRemRangeByLex = createZRemRangeByLex; exports.createZRemRangeByScore = createZRemRangeByScore; exports.createPersist = createPersist; exports.createZLexCount = createZLexCount; exports.createZRank = createZRank; exports.createXAdd = createXAdd; exports.createXDel = createXDel; exports.createXTrim = createXTrim; exports.createXRange = createXRange; exports.createXRevRange = createXRevRange; exports.createXGroupCreateConsumer = createXGroupCreateConsumer; exports.createXGroupDelConsumer = createXGroupDelConsumer; exports.createTime = createTime; exports.createPublish = createPublish; exports.createBRPop = createBRPop; exports.createBLPop = createBLPop; exports.createFCall = createFCall; exports.createFCallReadOnly = createFCallReadOnly; exports.createFunctionDelete = createFunctionDelete; exports.createFunctionFlush = createFunctionFlush; exports.createFunctionLoad = createFunctionLoad; exports.createFunctionList = createFunctionList; exports.createFunctionStats = createFunctionStats; exports.createFunctionKill = createFunctionKill; exports.createFunctionDump = createFunctionDump; exports.createFunctionRestore = createFunctionRestore; exports.createBitCount = createBitCount; exports.createBitPos = createBitPos; exports.convertKeysAndEntries = convertKeysAndEntries; exports.createXRead = createXRead; exports.createXReadGroup = createXReadGroup; exports.createXInfoStream = createXInfoStream; exports.createXInfoGroups = createXInfoGroups; exports.createXLen = createXLen; exports.createXPending = createXPending; exports.createXInfoConsumers = createXInfoConsumers; exports.createXClaim = createXClaim; exports.createXAutoClaim = createXAutoClaim; exports.createXGroupCreate = createXGroupCreate; exports.createXGroupDestroy = createXGroupDestroy; exports.createRename = createRename; exports.createRenameNX = createRenameNX; exports.createPfAdd = createPfAdd; exports.createPfCount = createPfCount; exports.createPfMerge = createPfMerge; exports.createObjectEncoding = createObjectEncoding; exports.createObjectFreq = createObjectFreq; exports.createObjectIdletime = createObjectIdletime; exports.createObjectRefcount = createObjectRefcount; exports.createLolwut = createLolwut; exports.createFlushAll = createFlushAll; exports.createFlushDB = createFlushDB; exports.createCopy = createCopy; exports.createMove = createMove; exports.createDump = createDump; exports.createRestore = createRestore; exports.createLPos = createLPos; exports.createDBSize = createDBSize; exports.createGeoAdd = createGeoAdd; exports.createGeoPos = createGeoPos; exports.createGeoDist = createGeoDist; exports.createGeoHash = createGeoHash; exports.createGeoSearch = createGeoSearch; exports.createGeoSearchStore = createGeoSearchStore; exports.createZRevRank = createZRevRank; exports.createZRevRankWithScore = createZRevRankWithScore; exports.createZMPop = createZMPop; exports.createBZMPop = createBZMPop; exports.createZIncrBy = createZIncrBy; exports.createSort = createSort; exports.createSortReadOnly = createSortReadOnly; exports.createHStrlen = createHStrlen; exports.createHRandField = createHRandField; exports.createHScan = createHScan; exports.createZRandMember = createZRandMember; exports.createLastSave = createLastSave; exports.createLCS = createLCS; exports.createTouch = createTouch; exports.createRandomKey = createRandomKey; exports.createWatch = createWatch; exports.createUnWatch = createUnWatch; exports.createWait = createWait; exports.createZScan = createZScan; exports.createSetRange = createSetRange; exports.createAppend = createAppend; exports.createLMPop = createLMPop; exports.createBLMPop = createBLMPop; exports.createPubSubChannels = createPubSubChannels; exports.createPubSubNumPat = createPubSubNumPat; exports.createPubSubNumSub = createPubSubNumSub; exports.createPubsubShardChannels = createPubsubShardChannels; exports.createPubSubShardNumSub = createPubSubShardNumSub; exports.createSubscribeLazy = createSubscribeLazy; exports.createSubscribe = createSubscribe; exports.createPSubscribeLazy = createPSubscribeLazy; exports.createPSubscribe = createPSubscribe; exports.createUnsubscribeLazy = createUnsubscribeLazy; exports.createUnsubscribe = createUnsubscribe; exports.createPUnsubscribeLazy = createPUnsubscribeLazy; exports.createPUnsubscribe = createPUnsubscribe; exports.createSSubscribeLazy = createSSubscribeLazy; exports.createSSubscribe = createSSubscribe; exports.createSUnsubscribeLazy = createSUnsubscribeLazy; exports.createSUnsubscribe = createSUnsubscribe; exports.createGetSubscriptions = createGetSubscriptions; exports.createBZPopMax = createBZPopMax; exports.createBZPopMin = createBZPopMin; exports.createScriptShow = createScriptShow; exports.createGetEx = createGetEx; exports.createXAck = createXAck; exports.createXGroupSetid = createXGroupSetid; exports.createScriptExists = createScriptExists; exports.createScriptFlush = createScriptFlush; exports.createScriptKill = createScriptKill; /** * Note: 'eslint-disable-line @typescript-eslint/no-unused-vars' is used intentionally * to suppress unused import errors for types referenced only in JSDoc. */ const long_1 = __importDefault(require("long")); const BaseClient_1 = require("./BaseClient"); const native_1 = require("../build-ts/native"); const ProtobufMessage_1 = require("../build-ts/ProtobufMessage"); var RequestType = ProtobufMessage_1.command_request.RequestType; function isLargeCommand(args) { let lenSum = 0; for (const arg of args) { lenSum += arg.length; if (lenSum >= native_1.MAX_REQUEST_ARGS_LEN) { return true; } } return false; } /** * Convert a string array into Uint8Array[] */ function toBuffersArray(args) { const argsBytes = []; for (const arg of args) { if (Buffer.isBuffer(arg)) { argsBytes.push(arg); } else if (typeof arg === "string") { argsBytes.push(Buffer.from(arg)); } else { // Fallback for unexpected types (number, boolean, etc.) argsBytes.push(Buffer.from(String(arg))); } } return argsBytes; } /** * @test */ function parseInfoResponse(response) { const lines = response.split("\n"); const parsedResponse = {}; for (const line of lines) { // Ignore lines that start with '#' if (!line.startsWith("#")) { const [key, value] = line.trim().split(":"); parsedResponse[key] = value; } } return parsedResponse; } function createCommand(requestType, args) { const singleCommand = ProtobufMessage_1.command_request.Command.create({ requestType, }); const argsBytes = toBuffersArray(args); if (isLargeCommand(args)) { // pass as a pointer const pointerArr = (0, native_1.createLeakedStringVec)(argsBytes); const pointer = new long_1.default(pointerArr[0], pointerArr[1]); singleCommand.argsVecPointer = pointer; } else { singleCommand.argsArray = ProtobufMessage_1.command_request.Command.ArgsArray.create({ args: argsBytes, }); } return singleCommand; } /** * @internal */ function createGet(key) { return createCommand(RequestType.Get, [key]); } /** * @internal */ function createGetDel(key) { return createCommand(RequestType.GetDel, [key]); } /** * @internal */ function createGetRange(key, start, end) { return createCommand(RequestType.GetRange, [ key, start.toString(), end.toString(), ]); } /** * @internal */ function createSet(key, value, options) { const args = [key, value]; if (options) { if (options.conditionalSet === "onlyIfExists") { args.push("XX"); } else if (options.conditionalSet === "onlyIfDoesNotExist") { args.push("NX"); } else if (options.conditionalSet === "onlyIfEqual") { args.push("IFEQ", options.comparisonValue); } if (options.returnOldValue) { args.push("GET"); } if (options.expiry) { if (options.expiry !== "keepExisting" && !Number.isInteger(options.expiry.count)) { throw new Error(`Received expiry '${JSON.stringify(options.expiry)}'. Count must be an integer`); } if (options.expiry === "keepExisting") { args.push("KEEPTTL"); } else { args.push(options.expiry.type, options.expiry.count.toString()); } } } return createCommand(RequestType.Set, args); } /** * INFO option: a specific section of information: * When no parameter is provided, the default option is assumed. */ var InfoOptions; (function (InfoOptions) { /** * SERVER: General information about the server */ InfoOptions["Server"] = "server"; /** * CLIENTS: Client connections section */ InfoOptions["Clients"] = "clients"; /** * MEMORY: Memory consumption related information */ InfoOptions["Memory"] = "memory"; /** * PERSISTENCE: RDB and AOF related information */ InfoOptions["Persistence"] = "persistence"; /** * STATS: General statistics */ InfoOptions["Stats"] = "stats"; /** * REPLICATION: Master/replica replication information */ InfoOptions["Replication"] = "replication"; /** * CPU: CPU consumption statistics */ InfoOptions["Cpu"] = "cpu"; /** * COMMANDSTATS: Valkey command statistics */ InfoOptions["Commandstats"] = "commandstats"; /** * LATENCYSTATS: Valkey command latency percentile distribution statistics */ InfoOptions["Latencystats"] = "latencystats"; /** * SENTINEL: Valkey Sentinel section (only applicable to Sentinel instances) */ InfoOptions["Sentinel"] = "sentinel"; /** * CLUSTER: Valkey Cluster section */ InfoOptions["Cluster"] = "cluster"; /** * MODULES: Modules section */ InfoOptions["Modules"] = "modules"; /** * KEYSPACE: Database related statistics */ InfoOptions["Keyspace"] = "keyspace"; /** * ERRORSTATS: Valkey error statistics */ InfoOptions["Errorstats"] = "errorstats"; /** * ALL: Return all sections (excluding module generated ones) */ InfoOptions["All"] = "all"; /** * DEFAULT: Return only the default set of sections */ InfoOptions["Default"] = "default"; /** * EVERYTHING: Includes all and modules */ InfoOptions["Everything"] = "everything"; })(InfoOptions || (exports.InfoOptions = InfoOptions = {})); /** * @internal */ function createPing(str) { const args = str == undefined ? [] : [str]; return createCommand(RequestType.Ping, args); } /** * @internal */ function createInfo(options) { const args = options == undefined ? [] : options; return createCommand(RequestType.Info, args); } /** * @internal */ function createDel(keys) { return createCommand(RequestType.Del, keys); } /** * @internal */ function createSelect(index) { return createCommand(RequestType.Select, [index.toString()]); } /** * @internal */ function createClientGetName() { return createCommand(RequestType.ClientGetName, []); } /** * @internal */ function createConfigRewrite() { return createCommand(RequestType.ConfigRewrite, []); } /** * @internal */ function createConfigResetStat() { return createCommand(RequestType.ConfigResetStat, []); } /** * @internal */ function createMGet(keys) { return createCommand(RequestType.MGet, keys); } /** * @internal */ function createMSet(keysAndValues) { return createCommand(RequestType.MSet, keysAndValues.flatMap((e) => [e.key, e.value])); } /** * @internal */ function createMSetNX(keysAndValues) { return createCommand(RequestType.MSetNX, keysAndValues.flatMap((e) => [e.key, e.value])); } /** * @internal */ function createIncr(key) { return createCommand(RequestType.Incr, [key]); } /** * @internal */ function createIncrBy(key, amount) { return createCommand(RequestType.IncrBy, [key, amount.toString()]); } /** * @internal */ function createIncrByFloat(key, amount) { return createCommand(RequestType.IncrByFloat, [key, amount.toString()]); } /** * @internal */ function createClientId() { return createCommand(RequestType.ClientId, []); } /** * @internal */ function createConfigGet(parameters) { return createCommand(RequestType.ConfigGet, parameters); } /** * @internal */ function createConfigSet(parameters) { return createCommand(RequestType.ConfigSet, Object.entries(parameters).flat()); } /** * @internal */ function createHGet(key, field) { return createCommand(RequestType.HGet, [key, field]); } /** * This function converts an input from {@link HashDataType} or `Record` types to `HashDataType`. * * @param fieldsAndValues - field names and their values. * @returns HashDataType array containing field names and their values. */ function convertFieldsAndValuesToHashDataType(fieldsAndValues) { if (!Array.isArray(fieldsAndValues)) { return Object.entries(fieldsAndValues).map(([field, value]) => { return { field, value }; }); } return fieldsAndValues; } /** * @internal */ function createHSet(key, fieldValueList) { return createCommand(RequestType.HSet, [key].concat(fieldValueList .map((fieldValueObject) => [ fieldValueObject.field, fieldValueObject.value, ]) .flat())); } /** * @internal */ function createHKeys(key) { return createCommand(RequestType.HKeys, [key]); } /** * @internal */ function createHSetNX(key, field, value) { return createCommand(RequestType.HSetNX, [key, field, value]); } /** * @internal */ function createHSetEx(key, fieldValueMap, options) { const args = [key]; // Add field conditional change options (FNX | FXX) if (options?.fieldConditionalChange) { args.push(options.fieldConditionalChange); } // Add expiry options (EX | PX | EXAT | PXAT | KEEPTTL) // Note: PERSIST is not supported by HSETEX if (options?.expiry) { if (options.expiry === "KEEPTTL") { args.push("KEEPTTL"); } else { // Validate that count is an integer if (!Number.isInteger(options.expiry.count)) { throw new Error(`HSETEX received expiry '${JSON.stringify(options.expiry)}'. Count must be an integer`); } args.push(options.expiry.type, options.expiry.count.toString()); } } // Only add FIELDS keyword and field count if fieldValueMap is not empty if (fieldValueMap.length > 0) { args.push("FIELDS", fieldValueMap.length.toString()); // Add field-value pairs fieldValueMap.forEach((fieldValueObject) => { args.push(fieldValueObject.field, fieldValueObject.value); }); } return createCommand(RequestType.HSetEx, args); } /** * @internal */ function createHGetEx(key, fields, options) { const args = [key]; // Add expiry options (EX | PX | EXAT | PXAT | PERSIST) // Note: HGETEX does not support KEEPTTL if (options?.expiry) { if (options.expiry === "PERSIST") { args.push("PERSIST"); } else { // Validate that count is an integer if (!Number.isInteger(options.expiry.count)) { throw new Error(`HGETEX received expiry '${JSON.stringify(options.expiry)}'. Count must be an integer`); } args.push(options.expiry.type, options.expiry.count.toString()); } } // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HGetEx, args); } /** * @internal */ function createHExpire(key, seconds, fields, options) { const args = [key, seconds.toString()]; // Add condition options (NX | XX | GT | LT) if (options?.condition) { args.push(options.condition); } // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HExpire, args); } /** * @internal */ function createHPersist(key, fields) { const args = [key]; // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HPersist, args); } /** * @internal */ function createHPExpire(key, milliseconds, fields, options) { const args = [key, milliseconds.toString()]; // Add condition options (NX | XX | GT | LT) if (options?.condition) { args.push(options.condition); } // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HPExpire, args); } /** * @internal */ function createHExpireAt(key, unixTimestampSeconds, fields, options) { const args = [key, unixTimestampSeconds.toString()]; // Add condition options (NX | XX | GT | LT) if (options?.condition) { args.push(options.condition); } // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HExpireAt, args); } /** * @internal */ function createHPExpireAt(key, unixTimestampMilliseconds, fields, options) { const args = [key, unixTimestampMilliseconds.toString()]; // Add condition options (NX | XX | GT | LT) if (options?.condition) { args.push(options.condition); } // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HPExpireAt, args); } /** * @internal */ function createHTtl(key, fields) { const args = [key]; // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HTtl, args); } /** * @internal */ function createHPTtl(key, fields) { const args = [key]; // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HPTtl, args); } /** * @internal */ function createHExpireTime(key, fields) { const args = [key]; // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HExpireTime, args); } /** * @internal */ function createHPExpireTime(key, fields) { const args = [key]; // Add FIELDS keyword and field count - always required when fields parameter exists args.push("FIELDS", fields.length.toString()); // Add field names args.push(...fields); return createCommand(RequestType.HPExpireTime, args); } /** * @internal */ function createDecr(key) { return createCommand(RequestType.Decr, [key]); } /** * @internal */ function createDecrBy(key, amount) { return createCommand(RequestType.DecrBy, [key, amount.toString()]); } /** * Enumeration defining the bitwise operation to use in the {@link BaseClient.bitop|bitop} command. Specifies the * bitwise operation to perform between the passed in keys. */ var BitwiseOperation; (function (BitwiseOperation) { BitwiseOperation["AND"] = "AND"; BitwiseOperation["OR"] = "OR"; BitwiseOperation["XOR"] = "XOR"; BitwiseOperation["NOT"] = "NOT"; })(BitwiseOperation || (exports.BitwiseOperation = BitwiseOperation = {})); /** * @internal */ function createBitOp(operation, destination, keys) { return createCommand(RequestType.BitOp, [operation, destination, ...keys]); } /** * @internal */ function createGetBit(key, offset) { return createCommand(RequestType.GetBit, [key, offset.toString()]); } /** * @internal */ function createSetBit(key, offset, value) { return createCommand(RequestType.SetBit, [ key, offset.toString(), value.toString(), ]); } /** * Represents a signed argument encoding. */ class SignedEncoding { static SIGNED_ENCODING_PREFIX = "i"; encoding; /** * Creates an instance of SignedEncoding. * * @param encodingLength - The bit size of the encoding. Must be less than 65 bits long. */ constructor(encodingLength) { this.encoding = `${SignedEncoding.SIGNED_ENCODING_PREFIX}${encodingLength.toString()}`; } toArg() { return this.encoding; } } exports.SignedEncoding = SignedEncoding; /** * Represents an unsigned argument encoding. */ class UnsignedEncoding { static UNSIGNED_ENCODING_PREFIX = "u"; encoding; /** * Creates an instance of UnsignedEncoding. * * @param encodingLength - The bit size of the encoding. Must be less than 64 bits long. */ constructor(encodingLength) { this.encoding = `${UnsignedEncoding.UNSIGNED_ENCODING_PREFIX}${encodingLength.toString()}`; } toArg() { return this.encoding; } } exports.UnsignedEncoding = UnsignedEncoding; /** * Represents an offset in an array of bits for the {@link BaseClient.bitfield|bitfield} or * {@link BaseClient.bitfieldReadOnly|bitfieldReadOnly} commands. * * For example, if we have the binary `01101001` with offset of 1 for an unsigned encoding of size 4, then the value * is 13 from `0(1101)001`. */ class BitOffset { offset; /** * Creates an instance of BitOffset. * * @param offset - The bit index offset in the array of bits. Must be greater than or equal to 0. */ constructor(offset) { this.offset = offset.toString(); } toArg() { return this.offset; } } exports.BitOffset = BitOffset; /** * Represents an offset in an array of bits for the {@link BaseClient.bitfield|bitfield} or * {@link BaseClient.bitfieldReadOnly|bitfieldReadOnly} commands. The bit offset index is calculated as the numerical * value of the offset multiplied by the encoding value. * * For example, if we have the binary 01101001 with offset multiplier of 1 for an unsigned encoding of size 4, then the * value is 9 from `0110(1001)`. */ class BitOffsetMultiplier { static OFFSET_MULTIPLIER_PREFIX = "#"; offset; /** * Creates an instance of BitOffsetMultiplier. * * @param offset - The offset in the array of bits, which will be multiplied by the encoding value to get the final * bit index offset. */ constructor(offset) { this.offset = `${BitOffsetMultiplier.OFFSET_MULTIPLIER_PREFIX}${offset.toString()}`; } toArg() { return this.offset; } } exports.BitOffsetMultiplier = BitOffsetMultiplier; /** * Represents the "GET" subcommand for getting a value in the binary representation of the string stored in `key`. */ class BitFieldGet { static GET_COMMAND_STRING = "GET"; encoding; offset; /** * Creates an instance of BitFieldGet. * * @param encoding - The bit encoding for the subcommand. * @param offset - The offset in the array of bits from which to get the value. */ constructor(encoding, offset) { this.encoding = encoding; this.offset = offset; } toArgs() { return [ BitFieldGet.GET_COMMAND_STRING, this.encoding.toArg(), this.offset.toArg(), ]; } } exports.BitFieldGet = BitFieldGet; /** * Represents the "SET" subcommand for setting bits in the binary representation of the string stored in `key`. */ class BitFieldSet { static SET_COMMAND_STRING = "SET"; encoding; offset; value; /** * Creates an instance of BitFieldSet * * @param encoding - The bit encoding for the subcommand. * @param offset - The offset in the array of bits where the value will be set. * @param value - The value to set the bits in the binary value to. */ constructor(encoding, offset, value) { this.encoding = encoding; this.offset = offset; this.value = value; } toArgs() { return [ BitFieldSet.SET_COMMAND_STRING, this.encoding.toArg(), this.offset.toArg(), this.value.toString(), ]; } } exports.BitFieldSet = BitFieldSet; /** * Represents the "INCRBY" subcommand for increasing or decreasing bits in the binary representation of the string * stored in `key`. */ class BitFieldIncrBy { static INCRBY_COMMAND_STRING = "INCRBY"; encoding; offset; increment; /** * Creates an instance of BitFieldIncrBy * * @param encoding - The bit encoding for the subcommand. * @param offset - The offset in the array of bits where the value will be incremented. * @param increment - The value to increment the bits in the binary value by. */ constructor(encoding, offset, increment) { this.encoding = encoding; this.offset = offset; this.increment = increment; } toArgs() { return [ BitFieldIncrBy.INCRBY_COMMAND_STRING, this.encoding.toArg(), this.offset.toArg(), this.increment.toString(), ]; } } exports.BitFieldIncrBy = BitFieldIncrBy; /** * Enumeration specifying bit overflow controls for the {@link BaseClient.bitfield|bitfield} command. */ var BitOverflowControl; (function (BitOverflowControl) { /** * Performs modulo when overflows occur with unsigned encoding. When overflows occur with signed encoding, the value * restarts at the most negative value. When underflows occur with signed encoding, the value restarts at the most * positive value. */ BitOverflowControl["WRAP"] = "WRAP"; /** * Underflows remain set to the minimum value, and overflows remain set to the maximum value. */ BitOverflowControl["SAT"] = "SAT"; /** * Returns `None` when overflows occur. */ BitOverflowControl["FAIL"] = "FAIL"; })(BitOverflowControl || (exports.BitOverflowControl = BitOverflowControl = {})); /** * Represents the "OVERFLOW" subcommand that determines the result of the "SET" or "INCRBY" * {@link BaseClient.bitfield|bitfield} subcommands when an underflow or overflow occurs. */ class BitFieldOverflow { static OVERFLOW_COMMAND_STRING = "OVERFLOW"; overflowControl; /** * Creates an instance of BitFieldOverflow. * * @param overflowControl - The desired overflow behavior. */ constructor(overflowControl) { this.overflowControl = overflowControl; } toArgs() { return [BitFieldOverflow.OVERFLOW_COMMAND_STRING, this.overflowControl]; } } exports.BitFieldOverflow = BitFieldOverflow; /** * @internal */ function createBitField(key, subcommands, readOnly = false) { const requestType = readOnly ? RequestType.BitFieldReadOnly : RequestType.BitField; let args = [key]; for (const subcommand of subcommands) { args = args.concat(subcommand.toArgs()); } return createCommand(requestType, args); } /** * @internal */ function createHDel(key, fields) { return createCommand(RequestType.HDel, [key].concat(fields)); } /** * @internal */ function createHMGet(key, fields) { return createCommand(RequestType.HMGet, [key].concat(fields)); } /** * @internal */ function createHExists(key, field) { return createCommand(RequestType.HExists, [key, field]); } /** * @internal */ function createHGetAll(key) { return createCommand(RequestType.HGetAll, [key]); } /** * @internal */ function createLPush(key, elements) { return createCommand(RequestType.LPush, [key].concat(elements)); } /** * @internal */ function createLPushX(key, elements) { return createCommand(RequestType.LPushX, [key].concat(elements)); } /** * @internal */ function createLPop(key, count) { const args = count == undefined ? [key] : [key, count.toString()]; return createCommand(RequestType.LPop, args); } /** * @internal */ function createLRange(key, start, end) { return createCommand(RequestType.LRange, [ key, start.toString(), end.toString(), ]); } /** * @internal */ function createLLen(key) { return createCommand(RequestType.LLen, [key]); } /** * Enumeration representing element popping or adding direction for the List Based Commands. */ var ListDirection; (function (ListDirection) { /** * Represents the option that elements should be popped from or added to the left side of a list. */ ListDirection["LEFT"] = "LEFT"; /** * Represents the option that elements should be popped from or added to the right side of a list. */ ListDirection["RIGHT"] = "RIGHT"; })(ListDirection || (exports.ListDirection = ListDirection = {})); /** * @internal */ function createLMove(source, destination, whereFrom, whereTo) { return createCommand(RequestType.LMove, [ source, destination, whereFrom, whereTo, ]); } /** * @internal */ function createBLMove(source, destination, whereFrom, whereTo, timeout) { return createCommand(RequestType.BLMove, [ source, destination, whereFrom, whereTo, timeout.toString(), ]); } /** * @internal */ function createLSet(key, index, element) { return createCommand(RequestType.LSet, [key, index.toString(), element]); } /** * @internal */ function createLTrim(key, start, end) { return createCommand(RequestType.LTrim, [ key, start.toString(), end.toString(), ]); } /** * @internal */ function createLRem(key, count, element) { return createCommand(RequestType.LRem, [key, count.toString(), element]); } /** * @internal */ function createRPush(key, elements) { return createCommand(RequestType.RPush, [key].concat(elements)); } /** * @internal */ function createRPushX(key, elements) { return createCommand(RequestType.RPushX, [key].concat(elements)); } /** * @internal */ function createRPop(key, count) { const args = count == undefined ? [key] : [key, count.toString()]; return createCommand(RequestType.RPop, args); } /** * @internal */ function createSAdd(key, members) { return createCommand(RequestType.SAdd, [key].concat(members)); } /** * @internal */ function createSRem(key, members) { return createCommand(RequestType.SRem, [key].concat(members)); } /** * @internal */ function createSScan(key, cursor, options) { let args = [key, cursor]; if (options) { args = args.concat(convertBaseScanOptionsToArgsArray(options)); } return createCommand(RequestType.SScan, args); } /** * @internal */ function createSMembers(key) { return createCommand(RequestType.SMembers, [key]); } /** * * @internal */ function createSMove(source, destination, member) { return createCommand(RequestType.SMove, [source, destination, member]); } /** * @internal */ function createSCard(key) { return createCommand(RequestType.SCard, [key]); } /** * @internal */ function createSInter(keys) { return createCommand(RequestType.SInter, keys); } /** * @internal */ function createSInterCard(keys, limit) { let args = keys; args.unshift(keys.length.toString()); if (limit != undefined) { args = args.concat(["LIMIT", limit.toString()]); } return createCommand(RequestType.SInterCard, args); } /** * @internal */ function createSInterStore(destination, keys) { return createCommand(RequestType.SInterStore, [destination].concat(keys)); } /** * @internal */ function createSDiff(keys) { return createCommand(RequestType.SDiff, keys); } /** * @internal */ function createSDiffStore(destination, keys) { return createCommand(RequestType.SDiffStore, [destination].concat(keys)); } /** * @internal */ function createSUnion(keys) { return createCommand(RequestType.SUnion, keys); } /** * @internal */ function createSUnionStore(destination, keys) { return createCommand(RequestType.SUnionStore, [destination].concat(keys)); } /** * @internal */ function createSIsMember(key, member) { return createCommand(RequestType.SIsMember, [key, member]); } /** * @internal */ function createSMIsMember(key, members) { return createCommand(RequestType.SMIsMember, [key].concat(members)); } /** * @internal */ function createSPop(key, count) { const args = count == undefined ? [key] : [key, count.toString()]; return createCommand(RequestType.SPop, args); } /** * @internal */ function createSRandMember(key, count) { const args = count == undefined ? [key] : [key, count.toString()]; return createCommand(RequestType.SRandMember, args); } /** * @internal */ function createCustomCommand(args) { return createCommand(RequestType.CustomCommand, args); } /** * @internal */ function createHIncrBy(key, field, amount) { return createCommand(RequestType.HIncrBy, [key, field, amount.toString()]); } /** * @internal */ function createHIncrByFloat(key, field, amount) { return createCommand(RequestType.HIncrByFloat, [ key, field, amount.toString(), ]); } /** * @internal */ function createHLen(key) { return createCommand(RequestType.HLen, [key]); } /** * @internal */ function createHVals(key) { return createCommand(RequestType.HVals, [key]); } /** * @internal */ function createExists(keys) { return createCommand(RequestType.Exists, keys); } /** * @internal */ function createUnlink(keys) { return createCommand(RequestType.Unlink, keys); } var ExpireOptions; (function (ExpireOptions) { /** * `HasNoExpiry` - Sets expiry only when the key has no expiry. */ ExpireOptions["HasNoExpiry"] = "NX"; /** * `HasExistingExpiry` - Sets expiry only when the key has an existing expiry. */ ExpireOptions["HasExistingExpiry"] = "XX"; /** * `NewExpiryGreaterThanCurrent` - Sets expiry only when the new expiry is * greater than current one. */ ExpireOptions["NewExpiryGreaterThanCurrent"] = "GT"; /** * `NewExpiryLessThanCurrent` - Sets expiry only when the new expiry is less * than current one. */ ExpireOptions["NewExpiryLessThanCurrent"] = "LT"; })(ExpireOptions || (exports.ExpireOptions = ExpireOptions = {})); /** * @internal */ function createExpire(key, seconds, option) { const args = option == undefined ? [key, seconds.toString()] : [key, seconds.toString(), option]; return createCommand(RequestType.Expire, args); } /** * @internal */ function createExpireAt(key, unixSeconds, option) { const args = option == undefined ? [key, unixSeconds.toString()] : [key, unixSeconds.toString(), option]; return createCommand(RequestType.ExpireAt, args); } /** * @internal */ function createExpireTime(key) { return createCommand(RequestType.ExpireTime, [key]); } /** * @internal */ function createPExpire(key, milliseconds, option) { const args = option == undefined ? [key, milliseconds.toString()] : [key, milliseconds.toString(), option]; return createCommand(RequestType.PExpire, args); } /** * @internal */ function createPExpireAt(key, unixMilliseconds, option) { const args = option == undefined ? [key, unixMilliseconds.toString()] : [key, unixMilliseconds.toString(), option]; return createCommand(RequestType.PExpireAt, args); } /** * @internal */ function createPExpireTime(key) { return createCommand(RequestType.PExpireTime, [key]); } /** * @internal */ function createTTL(key) { return createCommand(RequestType.TTL, [key]); } /** * Options for updating elements of a sorted set key. */ var UpdateByScore; (function (UpdateByScore) { /** Only update existing elements if the new score is less than the current score. */ UpdateByScore["LESS_THAN"] = "LT"; /** Only update existing elements if the new score is greater than the current score. */ UpdateByScore["GREATER_THAN"] = "GT"; })(UpdateByScore || (exports.UpdateByScore = UpdateByScore = {})); /** * @internal * Convert input from `Record` to `SortedSetDataType` to ensure the only one type. */ function convertElementsAndScores(membersAndScores) { if (!Array.isArray(membersAndScores)) { // convert Record<string, number> to SortedSetDataType return Object.entries(membersAndScores).map((element) => { return { element: element[0], score: element[1] }; }); } return membersAndScores; } /** * @internal */ function createZAdd(key, membersAndScores, options, incr = false) { const args = [key]; if (options) { if (options.conditionalChange) { if (options.conditionalChange === ConditionalChange.ONLY_IF_DOES_NOT_EXIST && options.updateOptions) { throw new Error(`The GT, LT, and NX options are mutually exclusive. Cannot choose both ${options.updateOptions} and NX.`); } args.push(options.conditionalChange); } if (options.updateOptions) { args.push(options.updateOptions); } if (options.changed) { args.push("CH"); } } if (incr) { args.push("INCR"); } if (Array.isArray(membersAndScores)) { for (let i = 0, len = membersAndScores.length; i < len; i++) { const item = membersAndScores[i]; args.push(item.score.toString(), item.element); } } else { const members = Object.keys(membersAndScores); for (let i = 0, len = members.length; i < len; i++) { const member = members[i]; args.push(membersAndScores[member].toString(), member); } } return createCommand(RequestType.ZAdd, args); } /** * @internal */ function createZInterstore(destination, keys, aggregationType) { const args = createZCmdArgs(keys, { aggregationType, withScores: false, destination, }); return createCommand(RequestType.ZInterStore, args); } /** * @internal */ function createZInter(keys, aggregationType, withScores) { const args = createZCmdArgs(keys, { aggregationType, withScores }); return createCommand(RequestType.ZInter, args); } /** * @internal */ function createZUnion(keys, aggregationType, withScores) { const args = createZCmdArgs(keys, { aggregationType, withScores }); return createCommand(RequestType.ZUnion, args); } /** * @internal * Helper function for Zcommands (ZInter, ZinterStore, ZUnion..) that arranges arguments in the server's required order. */ function createZCmdArgs(keys, options) { const args = []; const destination = options.destination; if (destination) { args.push(destination); } args.push(keys.length.toString()); if (!Array.isArray(keys[0])) { // KeyWeight is an array args.push(...keys); } else { const weightsKeys = keys.map(([key]) => key); args.push(...weightsKeys); const weights = keys.map(([, weight]) => weight.toString()); args.push("WEIGHTS", ...weights); } const aggregationType = options.aggregationType; if (aggregationType) { args.push("AGGREGATE", aggregationType); } if (options.withScores) { args.push("WITHSCORES"); } return args; } /** * @internal */ function createZRem(key, members) { return createCommand(RequestType.ZRem, [key].concat(members)); } /** * @internal */ function createZCard(key) { return createCommand(RequestType.ZCard, [key]); } /** * @internal */ function createZInterCard(keys, limit) { const args = keys; args.unshift(keys.length.toString()); if (limit != undefined) { args.push("LIMIT", limit.toString()); } return createCommand(RequestType.ZInterCard, args); } /** * @internal */ function createZDiff(keys) { const args = keys; args.unshift(keys.length.toString()); return createCommand(RequestType.ZDiff, args); } /** * @internal */ function createZDiffWithScores(keys) { const args = keys; args.unshift(keys.length.toString()); args.push("WITHSCORES"); return createCommand(RequestType.ZDiff, args); } /** * @internal */ function createZDiffStore(destination, keys) { const args = [destination, keys.length.toString(), ...keys]; return createCommand(RequestType.ZDiffStore, args); } /** * @internal */ function createZScore(key, member) { return createCommand(RequestType.ZScore, [key, member]); } /** * @internal */ function createZUnionStore(destination, keys, aggregationType) { const args = createZCmdArgs(keys, { destination, aggregationType }); return createCommand(RequestType.ZUnionStore, args); } /** * @internal */ function createZMScore(key, members) { return createCommand(RequestType.ZMScore, [key, ...members]); } /** * @internal */ function createScan(cursor, options) { let args = [cursor]; if (options) { args = args.concat(convertBaseScanOptionsToArgsArray(options)); } if (options?.type) { args.push("TYPE", options.type); } return createCommand(RequestType.Scan, args); } var InfBoundary; (function (InfBoundary) { /** * Positive infinity bound. */ InfBoundary["PositiveInfinity"] = "+"; /** * Negative infinity bound. */ InfBoundary["NegativeInfinity"] = "-"; })(InfBoundary || (exports.InfBoundary = InfBoundary = {})); /** Returns a string representation of a score boundary as a command argument. */ function getScoreBoundaryArg(score) { if (typeof score === "string") { // InfBoundary return score + "inf"; } if (score.isInclusive == false) { return "(" + score.value.toString(); } return score.value.toString(); } /** Returns a string representation of a lex boundary as a command argument. */ function getLexBoundaryArg(score) { if (typeof score === "string") { // InfBoundary return score; } if (score.isInclusive == false) { return typeof score.value === "string" ? "(" + score.value : Buffer.concat([Buffer.from("("), score.value]); } return typeof score.value === "string" ? "[" + score.value : Buffer.concat([Buffer.from("["), score.value]); } /** Returns a string representation of a stream boundary as a command argument. */ function getStreamBoundaryArg(boundary) { if (typeof boundary === "string") { // InfBoundary return boundary; } if (boundary.isInclusive == false) { return "(" + boundary.value.toString(); } return boundary.value.toString(); } function createZRangeArgs(key, rangeQuery, reverse, withScores) { const args = [key]; if (typeof rangeQuery.start != "number") { rangeQuery = rangeQuery; if (rangeQuery.type == "byLex") { args.push(getLexBoundaryArg(rangeQuery.start), getLexBoundaryArg(rangeQuery.end), "BYLEX"); } else { args.push(getScoreBoundaryArg(rangeQuery.start), getScoreBoundaryArg(rangeQuery.end), "BYSCORE"); } } else { args.push(rangeQuery.start.toString()); args.push(rangeQuery.end.toString()); } if (reverse) { args.push("REV"); } if ("limit" in rangeQuery && rangeQuery.limit !== undefined) { args.push("LIMIT", String(rangeQuery.limit.offset), String(rang