@valkey/valkey-glide 1.3.4 → 1.3.5-rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +36 -14
  3. package/build-ts/{src/BaseClient.d.ts → BaseClient.d.ts} +62 -118
  4. package/build-ts/BaseClient.js +6049 -0
  5. package/build-ts/{src/Transaction.d.ts → Batch.d.ts} +124 -67
  6. package/build-ts/Batch.js +3457 -0
  7. package/build-ts/{src/Commands.d.ts → Commands.d.ts} +171 -791
  8. package/build-ts/Commands.js +2708 -0
  9. package/build-ts/Errors.js +42 -0
  10. package/build-ts/{src/GlideClient.d.ts → GlideClient.d.ts} +55 -19
  11. package/build-ts/GlideClient.js +899 -0
  12. package/build-ts/{src/GlideClusterClient.d.ts → GlideClusterClient.d.ts} +78 -42
  13. package/build-ts/GlideClusterClient.js +1251 -0
  14. package/build-ts/Logger.js +67 -0
  15. package/build-ts/{src/ProtobufMessage.d.ts → ProtobufMessage.d.ts} +171 -634
  16. package/build-ts/ProtobufMessage.js +5265 -0
  17. package/build-ts/index.d.ts +16 -11
  18. package/build-ts/index.js +53 -216
  19. package/build-ts/native.d.ts +14 -0
  20. package/build-ts/native.js +342 -0
  21. package/build-ts/server-modules/GlideFt.js +628 -0
  22. package/build-ts/{src/server-modules → server-modules}/GlideFtOptions.d.ts +1 -1
  23. package/build-ts/server-modules/GlideFtOptions.js +5 -0
  24. package/build-ts/{src/server-modules → server-modules}/GlideJson.d.ts +65 -65
  25. package/build-ts/server-modules/GlideJson.js +1572 -0
  26. package/package.json +141 -64
  27. /package/build-ts/{src/Errors.d.ts → Errors.d.ts} +0 -0
  28. /package/build-ts/{src/Logger.d.ts → Logger.d.ts} +0 -0
  29. /package/build-ts/{src/server-modules → server-modules}/GlideFt.d.ts +0 -0
@@ -0,0 +1,899 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.GlideClient = exports.GlideClientConfiguration = void 0;
7
+ const BaseClient_1 = require("./BaseClient");
8
+ const Commands_1 = require("./Commands");
9
+ /* eslint-disable-next-line @typescript-eslint/no-namespace */
10
+ var GlideClientConfiguration;
11
+ (function (GlideClientConfiguration) {
12
+ /**
13
+ * Enum representing pubsub subscription modes.
14
+ * @see {@link https://valkey.io/docs/topics/pubsub/|Valkey PubSub Documentation} for more details.
15
+ */
16
+ let PubSubChannelModes;
17
+ (function (PubSubChannelModes) {
18
+ /**
19
+ * Use exact channel names.
20
+ */
21
+ PubSubChannelModes[PubSubChannelModes["Exact"] = 0] = "Exact";
22
+ /**
23
+ * Use channel name patterns.
24
+ */
25
+ PubSubChannelModes[PubSubChannelModes["Pattern"] = 1] = "Pattern";
26
+ })(PubSubChannelModes = GlideClientConfiguration.PubSubChannelModes || (GlideClientConfiguration.PubSubChannelModes = {}));
27
+ })(GlideClientConfiguration || (exports.GlideClientConfiguration = GlideClientConfiguration = {}));
28
+ /**
29
+ * Client used for connection to standalone servers.
30
+ * Use {@link createClient} to request a client.
31
+ *
32
+ * @see For full documentation refer to {@link https://github.com/valkey-io/valkey-glide/wiki/NodeJS-wrapper#standalone | Valkey Glide Wiki}.
33
+ */
34
+ class GlideClient extends BaseClient_1.BaseClient {
35
+ /**
36
+ * @internal
37
+ */
38
+ createClientRequest(options) {
39
+ const configuration = super.createClientRequest(options);
40
+ configuration.databaseId = options.databaseId;
41
+ configuration.connectionRetryStrategy = options.connectionBackoff;
42
+ this.configurePubsub(options, configuration);
43
+ if (options.advancedConfiguration) {
44
+ this.configureAdvancedConfigurationBase(options.advancedConfiguration, configuration);
45
+ }
46
+ return configuration;
47
+ }
48
+ /**
49
+ * Creates a new `GlideClient` instance and establishes a connection to a standalone Valkey server.
50
+ *
51
+ * @param options - The configuration options for the client, including server addresses, authentication credentials, TLS settings, database selection, reconnection strategy, and Pub/Sub subscriptions.
52
+ * @returns A promise that resolves to a connected `GlideClient` instance.
53
+ *
54
+ * @remarks
55
+ * Use this static method to create and connect a `GlideClient` to a standalone Valkey server.
56
+ * The client will automatically handle connection establishment, including any authentication and TLS configurations.
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // Connecting to a Standalone Server
61
+ * import { GlideClient, GlideClientConfiguration } from '@valkey/valkey-glide';
62
+ *
63
+ * const client = await GlideClient.createClient({
64
+ * addresses: [
65
+ * { host: 'primary.example.com', port: 6379 },
66
+ * { host: 'replica1.example.com', port: 6379 },
67
+ * ],
68
+ * databaseId: 1,
69
+ * credentials: {
70
+ * username: 'user1',
71
+ * password: 'passwordA',
72
+ * },
73
+ * useTLS: true,
74
+ * connectionBackoff: {
75
+ * numberOfRetries: 5,
76
+ * factor: 1000,
77
+ * exponentBase: 2,
78
+ * },
79
+ * pubsubSubscriptions: {
80
+ * channelsAndPatterns: {
81
+ * [GlideClientConfiguration.PubSubChannelModes.Exact]: new Set(['updates']),
82
+ * },
83
+ * callback: (msg) => {
84
+ * console.log(`Received message: ${msg.payload}`);
85
+ * },
86
+ * },
87
+ * });
88
+ * ```
89
+ *
90
+ * @remarks
91
+ * - **Authentication**: If `credentials` are provided, the client will attempt to authenticate using the specified username and password.
92
+ * - **TLS**: If `useTLS` is set to `true`, the client will establish a secure connection using TLS.
93
+ * - **Reconnection Strategy**: The `connectionBackoff` settings define how the client will attempt to reconnect in case of disconnections.
94
+ * - **Pub/Sub Subscriptions**: Any channels or patterns specified in `pubsubSubscriptions` will be subscribed to upon connection.
95
+ */
96
+ static async createClient(options) {
97
+ return super.createClientInternal(options, (socket, options) => new GlideClient(socket, options));
98
+ }
99
+ /**
100
+ * @internal
101
+ */
102
+ static async __createClient(options, connectedSocket) {
103
+ return this.__createClientInternal(options, connectedSocket, (socket, options) => new GlideClient(socket, options));
104
+ }
105
+ /**
106
+ * Execute a batch by processing the queued commands.
107
+ *
108
+ * **Notes:**
109
+ * - **Atomic Batches - Transactions:** If the transaction fails due to a `WATCH` command, `EXEC` will return `null`.
110
+ *
111
+ * @see {@link https://github.com/valkey-io/valkey-glide/wiki/NodeJS-wrapper#transaction|Valkey Glide Wiki} for details on Valkey Transactions.
112
+ *
113
+ * @param batch - A {@link Batch} object containing a list of commands to be executed.
114
+ * @param raiseOnError - Determines how errors are handled within the batch response.
115
+ * - If `true`, the first the first encountered error in the batch will be raised as an exception of type {@link RequestError}
116
+ * after all retries and reconnections have been exhausted.
117
+ * - If `false`, errors will be included as part of the batch response, allowing the caller to process both successful and failed commands together.
118
+ * In this case, error details will be provided as instances of {@link RequestError} in the response list.
119
+ * @param options - (Optional) See {@link BatchOptions} and {@link DecoderOption}.
120
+ * @returns A list of results corresponding to the execution of each command in the transaction.
121
+ * If a command returns a value, it will be included in the list. If a command doesn't return a value,
122
+ * the list entry will be `null`.
123
+ * If the transaction failed due to a `WATCH` command, `exec` will return `null`.
124
+ *
125
+ * @see {@link https://valkey.io/docs/topics/transactions/|Valkey Transactions (Atomic Batches)} for details.
126
+ * @see {@link https://valkey.io/docs/topics/pipelining/|Valkey Pipelines (Non-Atomic Batches)} for details.
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * // Example 1: Atomic Batch (Transaction) with Options
131
+ * const transaction = new Batch(true) // Atomic (Transactional)
132
+ * .set("key", "value")
133
+ * .get("key");
134
+ *
135
+ * const result = await client.exec(transaction, false, {timeout: 1000}); // Execute the transaction with raiseOnError = false and a timeout of 1000ms
136
+ * console.log(result); // Output: ['OK', 'value']
137
+ * ```
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * // Example 2: Non-Atomic Batch (Pipelining) with Options
142
+ * const pipeline = new Batch(false) // Non-Atomic (Pipelining)
143
+ * .set("key1", "value1")
144
+ * .set("key2", "value2")
145
+ * .get("key1")
146
+ * .get("key2");
147
+ *
148
+ * const result = await client.exec(pipeline, false, {timeout: 1000}); // Execute the pipeline with raiseOnError = false and a timeout of 1000ms
149
+ * console.log(result); // Output: ['OK', 'OK', 'value1', 'value2']
150
+ * ```
151
+ */
152
+ async exec(batch, raiseOnError, options) {
153
+ return this.createWritePromise(batch.commands, options, batch.isAtomic, raiseOnError).then((result) => this.processResultWithSetCommands(result, batch.setCommandsIndexes));
154
+ }
155
+ /** Executes a single command, without checking inputs. Every part of the command, including subcommands,
156
+ * should be added as a separate value in args.
157
+ *
158
+ * Note: An error will occur if the string decoder is used with commands that return only bytes as a response.
159
+ *
160
+ * @see {@link https://github.com/valkey-io/valkey-glide/wiki/General-Concepts#custom-command|Valkey Glide Wiki} for details on the restrictions and limitations of the custom command API.
161
+ *
162
+ * @param args - A list including the command name and arguments for the custom command.
163
+ * @param options - (Optional) See {@link DecoderOption}.
164
+ * @returns The executed custom command return value.
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * // Example usage of customCommand method to retrieve pub/sub clients
169
+ * const result = await client.customCommand(["CLIENT", "LIST", "TYPE", "PUBSUB"]);
170
+ * console.log(result); // Output: Returns a list of all pub/sub clients
171
+ * ```
172
+ */
173
+ async customCommand(args, options) {
174
+ return this.createWritePromise((0, Commands_1.createCustomCommand)(args), options);
175
+ }
176
+ /**
177
+ * Pings the server.
178
+ *
179
+ * @see {@link https://valkey.io/commands/ping/|valkey.io} for details.
180
+ *
181
+ * @param options - (Optional) Additional parameters:
182
+ * - (Optional) `message` : a message to include in the `PING` command.
183
+ * + If not provided, the server will respond with `"PONG"`.
184
+ * + If provided, the server will respond with a copy of the message.
185
+ * - (Optional) `decoder`: see {@link DecoderOption}.
186
+ * @returns `"PONG"` if `message` is not provided, otherwise return a copy of `message`.
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * // Example usage of ping method without any message
191
+ * const result = await client.ping();
192
+ * console.log(result); // Output: 'PONG'
193
+ * ```
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * // Example usage of ping method with a message
198
+ * const result = await client.ping("Hello");
199
+ * console.log(result); // Output: 'Hello'
200
+ * ```
201
+ */
202
+ async ping(options) {
203
+ return this.createWritePromise((0, Commands_1.createPing)(options?.message), options);
204
+ }
205
+ /**
206
+ * Gets information and statistics about the server.
207
+ *
208
+ * Starting from server version 7, command supports multiple section arguments.
209
+ *
210
+ * @see {@link https://valkey.io/commands/info/|valkey.io} for details.
211
+ *
212
+ * @param sections - (Optional) A list of {@link InfoOptions} values specifying which sections of information to retrieve.
213
+ * When no parameter is provided, {@link InfoOptions.Default|Default} is assumed.
214
+ * @returns A string containing the information for the sections requested.
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * // Example usage of the info method with retrieving total_net_input_bytes from the result
219
+ * const result = await client.info(new Section[] { Section.STATS });
220
+ * console.log(someParsingFunction(result, "total_net_input_bytes")); // Output: 1
221
+ * ```
222
+ */
223
+ async info(sections) {
224
+ return this.createWritePromise((0, Commands_1.createInfo)(sections), {
225
+ decoder: BaseClient_1.Decoder.String,
226
+ });
227
+ }
228
+ /**
229
+ * Changes the currently selected database.
230
+ *
231
+ * @see {@link https://valkey.io/commands/select/|valkey.io} for details.
232
+ *
233
+ * @param index - The index of the database to select.
234
+ * @returns A simple `"OK"` response.
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * // Example usage of select method
239
+ * const result = await client.select(2);
240
+ * console.log(result); // Output: 'OK'
241
+ * ```
242
+ */
243
+ async select(index) {
244
+ return this.createWritePromise((0, Commands_1.createSelect)(index), {
245
+ decoder: BaseClient_1.Decoder.String,
246
+ });
247
+ }
248
+ /**
249
+ * Gets the name of the primary's connection.
250
+ *
251
+ * @see {@link https://valkey.io/commands/client-getname/|valkey.io} for more details.
252
+ *
253
+ * @param options - (Optional) See {@link DecoderOption}.
254
+ * @returns The name of the client connection as a string if a name is set, or `null` if no name is assigned.
255
+ *
256
+ * @example
257
+ * ```typescript
258
+ * // Example usage of client_getname method
259
+ * const result = await client.client_getname();
260
+ * console.log(result); // Output: 'Client Name'
261
+ * ```
262
+ */
263
+ async clientGetName(options) {
264
+ return this.createWritePromise((0, Commands_1.createClientGetName)(), options);
265
+ }
266
+ /**
267
+ * Rewrites the configuration file with the current configuration.
268
+ *
269
+ * @see {@link https://valkey.io/commands/config-rewrite/|valkey.io} for details.
270
+ *
271
+ * @returns "OK" when the configuration was rewritten properly. Otherwise, an error is thrown.
272
+ *
273
+ * @example
274
+ * ```typescript
275
+ * // Example usage of configRewrite command
276
+ * const result = await client.configRewrite();
277
+ * console.log(result); // Output: 'OK'
278
+ * ```
279
+ */
280
+ async configRewrite() {
281
+ return this.createWritePromise((0, Commands_1.createConfigRewrite)(), {
282
+ decoder: BaseClient_1.Decoder.String,
283
+ });
284
+ }
285
+ /**
286
+ * Resets the statistics reported by the server using the `INFO` and `LATENCY HISTOGRAM` commands.
287
+ *
288
+ * @see {@link https://valkey.io/commands/config-resetstat/|valkey.io} for details.
289
+ *
290
+ * @returns always "OK".
291
+ *
292
+ * @example
293
+ * ```typescript
294
+ * // Example usage of configResetStat command
295
+ * const result = await client.configResetStat();
296
+ * console.log(result); // Output: 'OK'
297
+ * ```
298
+ */
299
+ async configResetStat() {
300
+ return this.createWritePromise((0, Commands_1.createConfigResetStat)(), {
301
+ decoder: BaseClient_1.Decoder.String,
302
+ });
303
+ }
304
+ /**
305
+ * Returns the current connection ID.
306
+ *
307
+ * @see {@link https://valkey.io/commands/client-id/|valkey.io} for details.
308
+ *
309
+ * @returns The ID of the connection.
310
+ *
311
+ * @example
312
+ * ```typescript
313
+ * const result = await client.clientId();
314
+ * console.log("Connection id: " + result);
315
+ * ```
316
+ */
317
+ async clientId() {
318
+ return this.createWritePromise((0, Commands_1.createClientId)());
319
+ }
320
+ /**
321
+ * Reads the configuration parameters of the running server.
322
+ * Starting from server version 7, command supports multiple parameters.
323
+ *
324
+ * @see {@link https://valkey.io/commands/config-get/|valkey.io} for details.
325
+ *
326
+ * @param parameters - A list of configuration parameter names to retrieve values for.
327
+ * @param options - (Optional) See {@link DecoderOption}.
328
+ *
329
+ * @returns A map of values corresponding to the configuration parameters.
330
+ *
331
+ * @example
332
+ * ```typescript
333
+ * // Example usage of configGet method with multiple configuration parameters
334
+ * const result = await client.configGet(["timeout", "maxmemory"]);
335
+ * console.log(result); // Output: {'timeout': '1000', 'maxmemory': '1GB'}
336
+ * ```
337
+ */
338
+ async configGet(parameters, options) {
339
+ return this.createWritePromise((0, Commands_1.createConfigGet)(parameters), options).then(BaseClient_1.convertGlideRecordToRecord);
340
+ }
341
+ /**
342
+ * Sets configuration parameters to the specified values.
343
+ * Starting from server version 7, command supports multiple parameters.
344
+ *
345
+ * @see {@link https://valkey.io/commands/config-set/|valkey.io} for details.
346
+ * @param parameters - A map consisting of configuration parameters and their respective values to set.
347
+ * @returns `"OK"` when the configuration was set properly. Otherwise an error is thrown.
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * // Example usage of configSet method to set multiple configuration parameters
352
+ * const result = await client.configSet({ timeout: "1000", maxmemory, "1GB" });
353
+ * console.log(result); // Output: 'OK'
354
+ * ```
355
+ */
356
+ async configSet(parameters) {
357
+ return this.createWritePromise((0, Commands_1.createConfigSet)(parameters), {
358
+ decoder: BaseClient_1.Decoder.String,
359
+ });
360
+ }
361
+ /**
362
+ * Echoes the provided `message` back.
363
+ *
364
+ * @see {@link https://valkey.io/commands/echo|valkey.io} for more details.
365
+ *
366
+ * @param message - The message to be echoed back.
367
+ * @param options - (Optional) See {@link DecoderOption}.
368
+ * @returns The provided `message`.
369
+ *
370
+ * @example
371
+ * ```typescript
372
+ * // Example usage of the echo command
373
+ * const echoedMessage = await client.echo("valkey-glide");
374
+ * console.log(echoedMessage); // Output: 'valkey-glide'
375
+ * ```
376
+ */
377
+ async echo(message, options) {
378
+ return this.createWritePromise((0, Commands_1.createEcho)(message), options);
379
+ }
380
+ /**
381
+ * Returns the server time.
382
+ *
383
+ * @see {@link https://valkey.io/commands/time/|valkey.io} for details.
384
+ *
385
+ * @returns The current server time as an `array` with two items:
386
+ * - A Unix timestamp,
387
+ * - The amount of microseconds already elapsed in the current second.
388
+ *
389
+ * @example
390
+ * ```typescript
391
+ * console.log(await client.time()); // Output: ['1710925775', '913580']
392
+ * ```
393
+ */
394
+ async time() {
395
+ return this.createWritePromise((0, Commands_1.createTime)(), {
396
+ decoder: BaseClient_1.Decoder.String,
397
+ });
398
+ }
399
+ /**
400
+ * Copies the value stored at the `source` to the `destination` key. If `destinationDB` is specified,
401
+ * the value will be copied to the database specified, otherwise the current database will be used.
402
+ * When `replace` is true, removes the `destination` key first if it already exists, otherwise performs
403
+ * no action.
404
+ *
405
+ * @see {@link https://valkey.io/commands/copy/|valkey.io} for more details.
406
+ * @remarks Since Valkey version 6.2.0.
407
+ *
408
+ * @param source - The key to the source value.
409
+ * @param destination - The key where the value should be copied to.
410
+ * @param options - (Optional) Additional parameters:
411
+ * - (Optional) `destinationDB`: the alternative logical database index for the destination key.
412
+ * If not provided, the current database will be used.
413
+ * - (Optional) `replace`: if `true`, the `destination` key should be removed before copying the
414
+ * value to it. If not provided, no action will be performed if the key already exists.
415
+ * @returns `true` if `source` was copied, `false` if the `source` was not copied.
416
+ *
417
+ * @example
418
+ * ```typescript
419
+ * const result = await client.copy("set1", "set2");
420
+ * console.log(result); // Output: true - "set1" was copied to "set2".
421
+ * ```
422
+ * ```typescript
423
+ * const result = await client.copy("set1", "set2", { replace: true });
424
+ * console.log(result); // Output: true - "set1" was copied to "set2".
425
+ * ```
426
+ * ```typescript
427
+ * const result = await client.copy("set1", "set2", { destinationDB: 1, replace: false });
428
+ * console.log(result); // Output: true - "set1" was copied to "set2".
429
+ * ```
430
+ */
431
+ async copy(source, destination, options) {
432
+ return this.createWritePromise((0, Commands_1.createCopy)(source, destination, options));
433
+ }
434
+ /**
435
+ * Move `key` from the currently selected database to the database specified by `dbIndex`.
436
+ *
437
+ * @see {@link https://valkey.io/commands/move/|valkey.io} for more details.
438
+ *
439
+ * @param key - The key to move.
440
+ * @param dbIndex - The index of the database to move `key` to.
441
+ * @returns `true` if `key` was moved, or `false` if the `key` already exists in the destination
442
+ * database or does not exist in the source database.
443
+ *
444
+ * @example
445
+ * ```typescript
446
+ * const result = await client.move("key", 1);
447
+ * console.log(result); // Output: true
448
+ * ```
449
+ */
450
+ async move(key, dbIndex) {
451
+ return this.createWritePromise((0, Commands_1.createMove)(key, dbIndex));
452
+ }
453
+ /**
454
+ * Displays a piece of generative computer art and the server version.
455
+ *
456
+ * @see {@link https://valkey.io/commands/lolwut/|valkey.io} for more details.
457
+ *
458
+ * @param options - (Optional) The LOLWUT options - see {@link LolwutOptions}.
459
+ * @returns A piece of generative computer art along with the current server version.
460
+ *
461
+ * @example
462
+ * ```typescript
463
+ * const response = await client.lolwut({ version: 6, parameters: [40, 20] });
464
+ * console.log(response); // Output: "Valkey ver. 7.2.3" - Indicates the current server version.
465
+ * ```
466
+ */
467
+ async lolwut(options) {
468
+ return this.createWritePromise((0, Commands_1.createLolwut)(options), {
469
+ decoder: BaseClient_1.Decoder.String,
470
+ });
471
+ }
472
+ /**
473
+ * Deletes a library and all its functions.
474
+ *
475
+ * @see {@link https://valkey.io/commands/function-delete/|valkey.io} for details.
476
+ * @remarks Since Valkey version 7.0.0.
477
+ *
478
+ * @param libraryCode - The library name to delete.
479
+ * @returns A simple `"OK"` response.
480
+ *
481
+ * @example
482
+ * ```typescript
483
+ * const result = await client.functionDelete("libName");
484
+ * console.log(result); // Output: 'OK'
485
+ * ```
486
+ */
487
+ async functionDelete(libraryCode) {
488
+ return this.createWritePromise((0, Commands_1.createFunctionDelete)(libraryCode), {
489
+ decoder: BaseClient_1.Decoder.String,
490
+ });
491
+ }
492
+ /**
493
+ * Loads a library to Valkey.
494
+ *
495
+ * @see {@link https://valkey.io/commands/function-load/|valkey.io} for details.
496
+ * @remarks Since Valkey version 7.0.0.
497
+ *
498
+ * @param libraryCode - The source code that implements the library.
499
+ * @param options - (Optional) Additional parameters:
500
+ * - (Optional) `replace`: Whether the given library should overwrite a library with the same name if it
501
+ * already exists.
502
+ * - (Optional) `decoder`: see {@link DecoderOption}.
503
+ * @returns The library name that was loaded.
504
+ *
505
+ * @example
506
+ * ```typescript
507
+ * const code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return args[1] end)";
508
+ * const result = await client.functionLoad(code, { replace: true });
509
+ * console.log(result); // Output: 'mylib'
510
+ * ```
511
+ */
512
+ async functionLoad(libraryCode, options) {
513
+ return this.createWritePromise((0, Commands_1.createFunctionLoad)(libraryCode, options?.replace), options);
514
+ }
515
+ /**
516
+ * Deletes all function libraries.
517
+ *
518
+ * @see {@link https://valkey.io/commands/function-flush/|valkey.io} for details.
519
+ * @remarks Since Valkey version 7.0.0.
520
+ *
521
+ * @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
522
+ * @returns A simple `"OK"` response.
523
+ *
524
+ * @example
525
+ * ```typescript
526
+ * const result = await client.functionFlush(FlushMode.SYNC);
527
+ * console.log(result); // Output: 'OK'
528
+ * ```
529
+ */
530
+ async functionFlush(mode) {
531
+ return this.createWritePromise((0, Commands_1.createFunctionFlush)(mode), {
532
+ decoder: BaseClient_1.Decoder.String,
533
+ });
534
+ }
535
+ /**
536
+ * Returns information about the functions and libraries.
537
+ *
538
+ * @see {@link https://valkey.io/commands/function-list/|valkey.io} for details.
539
+ * @remarks Since Valkey version 7.0.0.
540
+ *
541
+ * @param options - (Optional) See {@link FunctionListOptions} and {@link DecoderOption}.
542
+ * @returns Info about all or selected libraries and their functions in {@link FunctionListResponse} format.
543
+ *
544
+ * @example
545
+ * ```typescript
546
+ * // Request info for specific library including the source code
547
+ * const result1 = await client.functionList({ libNamePattern: "myLib*", withCode: true });
548
+ * // Request info for all libraries
549
+ * const result2 = await client.functionList();
550
+ * console.log(result2); // Output:
551
+ * // [{
552
+ * // "library_name": "myLib5_backup",
553
+ * // "engine": "LUA",
554
+ * // "functions": [{
555
+ * // "name": "myfunc",
556
+ * // "description": null,
557
+ * // "flags": [ "no-writes" ],
558
+ * // }],
559
+ * // "library_code": "#!lua name=myLib5_backup \n redis.register_function('myfunc', function(keys, args) return args[1] end)"
560
+ * // }]
561
+ * ```
562
+ */
563
+ async functionList(options) {
564
+ return this.createWritePromise((0, Commands_1.createFunctionList)(options), options).then((res) => res.map(BaseClient_1.convertGlideRecordToRecord));
565
+ }
566
+ /**
567
+ * Returns information about the function that's currently running and information about the
568
+ * available execution engines.
569
+ *
570
+ * FUNCTION STATS runs on all nodes of the server, including primary and replicas.
571
+ * The response includes a mapping from node address to the command response for that node.
572
+ *
573
+ * @see {@link https://valkey.io/commands/function-stats/|valkey.io} for details.
574
+ * @remarks Since Valkey version 7.0.0.
575
+ *
576
+ * @param options - (Optional) See {@link DecoderOption}.
577
+ * @returns A Record where the key is the node address and the value is a Record with two keys:
578
+ * - `"running_script"`: Information about the running script, or `null` if no script is running.
579
+ * - `"engines"`: Information about available engines and their stats.
580
+ * - see example for more details.
581
+ * @example
582
+ * ```typescript
583
+ * const response = await client.functionStats();
584
+ * console.log(response); // Example output:
585
+ * // {
586
+ * // "127.0.0.1:6379": { // Response from the primary node
587
+ * // "running_script": {
588
+ * // "name": "foo",
589
+ * // "command": ["FCALL", "foo", "0", "hello"],
590
+ * // "duration_ms": 7758
591
+ * // },
592
+ * // "engines": {
593
+ * // "LUA": {
594
+ * // "libraries_count": 1,
595
+ * // "functions_count": 1
596
+ * // }
597
+ * // }
598
+ * // },
599
+ * // "127.0.0.1:6380": { // Response from a replica node
600
+ * // "running_script": null,
601
+ * // "engines": {
602
+ * // "LUA": {
603
+ * // "libraries_count": 1,
604
+ * // "functions_count": 1
605
+ * // }
606
+ * // }
607
+ * // }
608
+ * // }
609
+ * ```
610
+ */
611
+ async functionStats(options) {
612
+ return this.createWritePromise((0, Commands_1.createFunctionStats)(), options).then((res) => (0, BaseClient_1.convertGlideRecordToRecord)(res));
613
+ }
614
+ /**
615
+ * Kills a function that is currently executing.
616
+ * `FUNCTION KILL` terminates read-only functions only.
617
+ * `FUNCTION KILL` runs on all nodes of the server, including primary and replicas.
618
+ *
619
+ * @see {@link https://valkey.io/commands/function-kill/|valkey.io} for details.
620
+ * @remarks Since Valkey version 7.0.0.
621
+ *
622
+ * @returns `"OK"` if function is terminated. Otherwise, throws an error.
623
+ * @example
624
+ * ```typescript
625
+ * await client.functionKill();
626
+ * ```
627
+ */
628
+ async functionKill() {
629
+ return this.createWritePromise((0, Commands_1.createFunctionKill)(), {
630
+ decoder: BaseClient_1.Decoder.String,
631
+ });
632
+ }
633
+ /**
634
+ * Returns the serialized payload of all loaded libraries.
635
+ *
636
+ * @see {@link https://valkey.io/commands/function-dump/|valkey.io} for details.
637
+ * @remarks Since Valkey version 7.0.0.
638
+ *
639
+ * @returns The serialized payload of all loaded libraries.
640
+ *
641
+ * @example
642
+ * ```typescript
643
+ * const data = await client.functionDump();
644
+ * // data can be used to restore loaded functions on any Valkey instance
645
+ * ```
646
+ */
647
+ async functionDump() {
648
+ return this.createWritePromise((0, Commands_1.createFunctionDump)(), {
649
+ decoder: BaseClient_1.Decoder.Bytes,
650
+ });
651
+ }
652
+ /**
653
+ * Restores libraries from the serialized payload returned by {@link functionDump}.
654
+ *
655
+ * @see {@link https://valkey.io/commands/function-restore/|valkey.io} for details.
656
+ * @remarks Since Valkey version 7.0.0.
657
+ *
658
+ * @param payload - The serialized data from {@link functionDump}.
659
+ * @param policy - (Optional) A policy for handling existing libraries, see {@link FunctionRestorePolicy}.
660
+ * {@link FunctionRestorePolicy.APPEND} is used by default.
661
+ * @returns `"OK"`.
662
+ *
663
+ * @example
664
+ * ```typescript
665
+ * await client.functionRestore(data, FunctionRestorePolicy.FLUSH);
666
+ * ```
667
+ */
668
+ async functionRestore(payload, policy) {
669
+ return this.createWritePromise((0, Commands_1.createFunctionRestore)(payload, policy), {
670
+ decoder: BaseClient_1.Decoder.String,
671
+ });
672
+ }
673
+ /**
674
+ * Deletes all the keys of all the existing databases. This command never fails.
675
+ *
676
+ * @see {@link https://valkey.io/commands/flushall/|valkey.io} for more details.
677
+ *
678
+ * @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
679
+ * @returns `"OK"`.
680
+ *
681
+ * @example
682
+ * ```typescript
683
+ * const result = await client.flushall(FlushMode.SYNC);
684
+ * console.log(result); // Output: 'OK'
685
+ * ```
686
+ */
687
+ async flushall(mode) {
688
+ return this.createWritePromise((0, Commands_1.createFlushAll)(mode), {
689
+ decoder: BaseClient_1.Decoder.String,
690
+ });
691
+ }
692
+ /**
693
+ * Deletes all the keys of the currently selected database. This command never fails.
694
+ *
695
+ * @see {@link https://valkey.io/commands/flushdb/|valkey.io} for more details.
696
+ *
697
+ * @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
698
+ * @returns `"OK"`.
699
+ *
700
+ * @example
701
+ * ```typescript
702
+ * const result = await client.flushdb(FlushMode.SYNC);
703
+ * console.log(result); // Output: 'OK'
704
+ * ```
705
+ */
706
+ async flushdb(mode) {
707
+ return this.createWritePromise((0, Commands_1.createFlushDB)(mode), {
708
+ decoder: BaseClient_1.Decoder.String,
709
+ });
710
+ }
711
+ /**
712
+ * Returns the number of keys in the currently selected database.
713
+ *
714
+ * @see {@link https://valkey.io/commands/dbsize/|valkey.io} for more details.
715
+ *
716
+ * @returns The number of keys in the currently selected database.
717
+ *
718
+ * @example
719
+ * ```typescript
720
+ * const numKeys = await client.dbsize();
721
+ * console.log("Number of keys in the current database: ", numKeys);
722
+ * ```
723
+ */
724
+ async dbsize() {
725
+ return this.createWritePromise((0, Commands_1.createDBSize)());
726
+ }
727
+ /** Publish a message on pubsub channel.
728
+ *
729
+ * @see {@link https://valkey.io/commands/publish/|valkey.io} for more details.
730
+ *
731
+ * @param message - Message to publish.
732
+ * @param channel - Channel to publish the message on.
733
+ * @returns - Number of subscriptions in primary node that received the message.
734
+ * Note that this value does not include subscriptions that configured on replicas.
735
+ *
736
+ * @example
737
+ * ```typescript
738
+ * // Example usage of publish command
739
+ * const result = await client.publish("Hi all!", "global-channel");
740
+ * console.log(result); // Output: 1 - This message was posted to 1 subscription which is configured on primary node
741
+ * ```
742
+ */
743
+ async publish(message, channel) {
744
+ return this.createWritePromise((0, Commands_1.createPublish)(message, channel));
745
+ }
746
+ /**
747
+ * Returns `UNIX TIME` of the last DB save timestamp or startup timestamp if no save
748
+ * was made since then.
749
+ *
750
+ * @see {@link https://valkey.io/commands/lastsave/|valkey.io} for more details.
751
+ *
752
+ * @returns `UNIX TIME` of the last DB save executed with success.
753
+ *
754
+ * @example
755
+ * ```typescript
756
+ * const timestamp = await client.lastsave();
757
+ * console.log("Last DB save was done at " + timestamp);
758
+ * ```
759
+ */
760
+ async lastsave() {
761
+ return this.createWritePromise((0, Commands_1.createLastSave)());
762
+ }
763
+ /**
764
+ * Returns a random existing key name from the currently selected database.
765
+ *
766
+ * @see {@link https://valkey.io/commands/randomkey/|valkey.io} for more details.
767
+ * @param options - (Optional) See {@link DecoderOption}.
768
+ * @returns A random existing key name from the currently selected database.
769
+ *
770
+ * @example
771
+ * ```typescript
772
+ * const result = await client.randomKey();
773
+ * console.log(result); // Output: "key12" - "key12" is a random existing key name from the currently selected database.
774
+ * ```
775
+ */
776
+ async randomKey(options) {
777
+ return this.createWritePromise((0, Commands_1.createRandomKey)(), options);
778
+ }
779
+ /**
780
+ * Flushes all the previously watched keys for a transaction. Executing a transaction will
781
+ * automatically flush all previously watched keys.
782
+ *
783
+ * @see {@link https://valkey.io/commands/unwatch/|valkey.io} and {@link https://valkey.io/topics/transactions/#cas|Valkey Glide Wiki} for more details.
784
+ *
785
+ * @returns A simple `"OK"` response.
786
+ *
787
+ * @example
788
+ * ```typescript
789
+ * let response = await client.watch(["sampleKey"]);
790
+ * console.log(response); // Output: "OK"
791
+ * response = await client.unwatch();
792
+ * console.log(response); // Output: "OK"
793
+ * ```
794
+ */
795
+ async unwatch() {
796
+ return this.createWritePromise((0, Commands_1.createUnWatch)(), {
797
+ decoder: BaseClient_1.Decoder.String,
798
+ });
799
+ }
800
+ /**
801
+ * Checks existence of scripts in the script cache by their SHA1 digest.
802
+ *
803
+ * @see {@link https://valkey.io/commands/script-exists/|valkey.io} for more details.
804
+ *
805
+ * @param sha1s - List of SHA1 digests of the scripts to check.
806
+ * @returns A list of boolean values indicating the existence of each script.
807
+ *
808
+ * @example
809
+ * ```typescript
810
+ * console result = await client.scriptExists(["sha1_digest1", "sha1_digest2"]);
811
+ * console.log(result); // Output: [true, false]
812
+ * ```
813
+ */
814
+ async scriptExists(sha1s) {
815
+ return this.createWritePromise((0, Commands_1.createScriptExists)(sha1s));
816
+ }
817
+ /**
818
+ * Flushes the Lua scripts cache.
819
+ *
820
+ * @see {@link https://valkey.io/commands/script-flush/|valkey.io} for more details.
821
+ *
822
+ * @param mode - (Optional) The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
823
+ * @returns A simple `"OK"` response.
824
+ *
825
+ * @example
826
+ * ```typescript
827
+ * console result = await client.scriptFlush(FlushMode.SYNC);
828
+ * console.log(result); // Output: "OK"
829
+ * ```
830
+ */
831
+ async scriptFlush(mode) {
832
+ return this.createWritePromise((0, Commands_1.createScriptFlush)(mode), {
833
+ decoder: BaseClient_1.Decoder.String,
834
+ });
835
+ }
836
+ /**
837
+ * Kills the currently executing Lua script, assuming no write operation was yet performed by the script.
838
+ *
839
+ * @see {@link https://valkey.io/commands/script-kill/|valkey.io} for more details.
840
+ *
841
+ * @returns A simple `"OK"` response.
842
+ *
843
+ * @example
844
+ * ```typescript
845
+ * console result = await client.scriptKill();
846
+ * console.log(result); // Output: "OK"
847
+ * ```
848
+ */
849
+ async scriptKill() {
850
+ return this.createWritePromise((0, Commands_1.createScriptKill)(), {
851
+ decoder: BaseClient_1.Decoder.String,
852
+ });
853
+ }
854
+ /**
855
+ * Incrementally iterate over a collection of keys.
856
+ * `SCAN` is a cursor based iterator. This means that at every call of the method,
857
+ * the server returns an updated cursor that the user needs to use as the cursor argument in the next call.
858
+ * An iteration starts when the cursor is set to "0", and terminates when the cursor returned by the server is "0".
859
+ *
860
+ * A full iteration always retrieves all the elements that were present
861
+ * in the collection from the start to the end of a full iteration.
862
+ * Elements that were not constantly present in the collection during a full iteration, may be returned or not.
863
+ *
864
+ * @see {@link https://valkey.io/commands/scan|valkey.io} for more details.
865
+ *
866
+ * @param cursor - The `cursor` used for iteration. For the first iteration, the cursor should be set to "0".
867
+ * Using a non-zero cursor in the first iteration,
868
+ * or an invalid cursor at any iteration, will lead to undefined results.
869
+ * Using the same cursor in multiple iterations will, in case nothing changed between the iterations,
870
+ * return the same elements multiple times.
871
+ * If the the db has changed, it may result in undefined behavior.
872
+ * @param options - (Optional) The options to use for the scan operation, see {@link ScanOptions} and {@link DecoderOption}.
873
+ * @returns A List containing the next cursor value and a list of keys,
874
+ * formatted as [cursor, [key1, key2, ...]]
875
+ *
876
+ * @example
877
+ * ```typescript
878
+ * // Example usage of scan method
879
+ * let result = await client.scan('0');
880
+ * console.log(result); // Output: ['17', ['key1', 'key2', 'key3', 'key4', 'key5', 'set1', 'set2', 'set3']]
881
+ * let firstCursorResult = result[0];
882
+ * result = await client.scan(firstCursorResult);
883
+ * console.log(result); // Output: ['349', ['key4', 'key5', 'set1', 'hash1', 'zset1', 'list1', 'list2',
884
+ * // 'list3', 'zset2', 'zset3', 'zset4', 'zset5', 'zset6']]
885
+ * result = await client.scan(result[0]);
886
+ * console.log(result); // Output: ['0', ['key6', 'key7']]
887
+ *
888
+ * result = await client.scan(firstCursorResult, {match: 'key*', count: 2});
889
+ * console.log(result); // Output: ['6', ['key4', 'key5']]
890
+ *
891
+ * result = await client.scan("0", {type: ObjectType.Set});
892
+ * console.log(result); // Output: ['362', ['set1', 'set2', 'set3']]
893
+ * ```
894
+ */
895
+ async scan(cursor, options) {
896
+ return this.createWritePromise((0, Commands_1.createScan)(cursor, options), options);
897
+ }
898
+ }
899
+ exports.GlideClient = GlideClient;