speedkey 0.1.0

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