@marianmeres/kv 2.1.0 → 2.3.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.
@@ -26,6 +26,12 @@ export interface AdapterAbstractOptions extends Record<string, any> {
26
26
  defaultTtl: number;
27
27
  /** Optional logger instance for debugging and error logging. */
28
28
  logger?: Logger;
29
+ /**
30
+ * When `true` (default), keys are validated on every operation: must be
31
+ * non-empty strings, no `\0` characters, and the total stored length
32
+ * (namespace + key) must be ≤ 512. Set to `false` to skip validation.
33
+ */
34
+ validateKeys?: boolean;
29
35
  }
30
36
  /**
31
37
  * Represents a single operation within a transaction.
@@ -40,6 +46,40 @@ export interface Operation {
40
46
  /** Optional settings for the operation (only used for "set" operations). */
41
47
  options?: Partial<SetOptions>;
42
48
  }
49
+ /**
50
+ * Extended shape accepted by {@link AdapterAbstract.setMultiple}.
51
+ *
52
+ * The tuple form `[key, value]` is preserved for backward compatibility;
53
+ * the object form allows per-pair TTL that overrides `options.ttl`.
54
+ */
55
+ export type SetMultipleEntry = [string, any] | {
56
+ key: string;
57
+ value: any;
58
+ ttl?: number;
59
+ };
60
+ /**
61
+ * Result of a {@link AdapterAbstract.ttl} call.
62
+ *
63
+ * Discriminated union — switch on `.state`:
64
+ * - `"missing"` — key does not exist (or has expired)
65
+ * - `"no-ttl"` — key exists with no expiration
66
+ * - `"expires"` — key exists and will expire at `at`
67
+ */
68
+ export type TtlResult = {
69
+ state: "missing";
70
+ } | {
71
+ state: "no-ttl";
72
+ } | {
73
+ state: "expires";
74
+ at: Date;
75
+ };
76
+ /**
77
+ * Thrown when a CAS-based atomic primitive (e.g. Deno KV `incr`/`cas`)
78
+ * exhausts its retry budget due to contention on the key.
79
+ */
80
+ export declare class KvRaceError extends Error {
81
+ constructor(message: string);
82
+ }
43
83
  /**
44
84
  * Abstract base class for all KV storage adapters.
45
85
  *
@@ -92,6 +132,14 @@ export declare abstract class AdapterAbstract {
92
132
  * matched literally.
93
133
  */
94
134
  protected _globToRegex(pattern: string): RegExp;
135
+ /**
136
+ * Normalizes the polymorphic `setMultiple` input to a single shape.
137
+ */
138
+ protected _normalizePairs(entries: readonly SetMultipleEntry[]): Array<{
139
+ key: string;
140
+ value: any;
141
+ ttl?: number;
142
+ }>;
95
143
  /**
96
144
  * Initializes the adapter and connects to the underlying storage.
97
145
  *
@@ -129,6 +177,45 @@ export declare abstract class AdapterAbstract {
129
177
  * ```
130
178
  */
131
179
  set(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
180
+ /**
181
+ * Stores a key-value pair only when the key does not already exist.
182
+ *
183
+ * @returns `true` if the value was stored, `false` if the key existed.
184
+ */
185
+ setIfAbsent(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
186
+ /**
187
+ * Atomically sets a new value and returns the previous one.
188
+ *
189
+ * @returns The previous value, or `null` if the key did not exist.
190
+ */
191
+ getSet(key: string, value: any, options?: Partial<SetOptions>): Promise<any>;
192
+ /**
193
+ * Atomically increments a numeric value.
194
+ *
195
+ * If the key does not exist, it is created with the value `by`.
196
+ * If the key exists but is not a JSON number, throws `TypeError`.
197
+ *
198
+ * TTL semantics: `options.ttl` (or `defaultTtl`) is applied only when the
199
+ * key is newly created by this call. Existing TTLs are preserved.
200
+ *
201
+ * @returns The new numeric value after the increment.
202
+ * @throws {TypeError} If the stored value is not a number.
203
+ */
204
+ incr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
205
+ /**
206
+ * Atomically decrements a numeric value. See {@link incr} for details.
207
+ */
208
+ decr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
209
+ /**
210
+ * Atomic compare-and-set. Replaces the stored value with `next` only when
211
+ * the currently-stored value deep-equals `expected`.
212
+ *
213
+ * Missing keys never match, even when `expected` is `null`.
214
+ *
215
+ * @returns `true` if the swap happened, `false` if the current value did
216
+ * not match.
217
+ */
218
+ cas(key: string, expected: any, next: any, options?: Partial<SetOptions>): Promise<boolean>;
132
219
  /**
133
220
  * Retrieves a value by its key.
134
221
  *
@@ -149,7 +236,8 @@ export declare abstract class AdapterAbstract {
149
236
  *
150
237
  * @param key - The key to delete.
151
238
  * @returns A promise that resolves to `true` if the key existed and was deleted,
152
- * `false` if the key didn't exist. Note: Deno KV always returns `true`.
239
+ * `false` if the key didn't exist. Note: Deno KV always returns `true` unless
240
+ * the adapter was created with `strictDeleteResult: true`.
153
241
  *
154
242
  * @example
155
243
  * ```typescript
@@ -190,6 +278,20 @@ export declare abstract class AdapterAbstract {
190
278
  * @throws {Error} In Redis cluster mode.
191
279
  */
192
280
  keys(pattern: string): Promise<string[]>;
281
+ /**
282
+ * Iterates matching keys without materializing the full list.
283
+ *
284
+ * Prefer this over {@link keys} for unbounded or unknown-sized scans.
285
+ * Ordering is not guaranteed across adapters.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * for await (const k of client.keysIter("user:*")) {
290
+ * console.log(k);
291
+ * }
292
+ * ```
293
+ */
294
+ keysIter(pattern: string): AsyncIterable<string>;
193
295
  /**
194
296
  * Deletes all keys matching a pattern.
195
297
  *
@@ -210,21 +312,22 @@ export declare abstract class AdapterAbstract {
210
312
  /**
211
313
  * Stores multiple key-value pairs in a single batch operation.
212
314
  *
213
- * More efficient than multiple individual `set` calls, especially for Redis and PostgreSQL.
315
+ * Accepts either tuples `[key, value]` (legacy) or objects
316
+ * `{ key, value, ttl? }`. Per-pair `ttl` overrides `options.ttl`.
214
317
  *
215
- * @param keyValuePairs - An array of `[key, value]` tuples to store.
216
- * @param options - Optional settings applied to all pairs (e.g., TTL).
217
- * @returns A promise that resolves to an array of boolean results for each operation.
318
+ * @param entries - Pairs to store.
319
+ * @param options - Optional batch-wide settings (TTL fallback).
320
+ * @returns Array of boolean results (one per entry).
218
321
  *
219
322
  * @example
220
323
  * ```typescript
221
324
  * await client.setMultiple([
222
325
  * ["user:1", { name: "Alice" }],
223
- * ["user:2", { name: "Bob" }],
326
+ * { key: "user:2", value: { name: "Bob" }, ttl: 30 },
224
327
  * ], { ttl: 3600 });
225
328
  * ```
226
329
  */
227
- setMultiple(keyValuePairs: [string, any][], options?: Partial<SetOptions>): Promise<any[]>;
330
+ setMultiple(entries: readonly SetMultipleEntry[], options?: Partial<SetOptions>): Promise<boolean[]>;
228
331
  /**
229
332
  * Retrieves multiple values in a single batch operation.
230
333
  *
@@ -277,28 +380,22 @@ export declare abstract class AdapterAbstract {
277
380
  */
278
381
  expire(key: string, ttl: number): Promise<boolean>;
279
382
  /**
280
- * Gets the expiration time of a key.
281
- *
282
- * @param key - The key to check.
283
- * @returns A promise that resolves to:
284
- * - `Date` - The expiration date if TTL is set
285
- * - `null` - If the key exists but has no expiration
286
- * - `false` - If the key doesn't exist or has expired
287
- * Note: Deno KV always returns `null` (TTL query not supported).
383
+ * Gets the expiration time of a key as a discriminated union.
288
384
  *
289
385
  * @example
290
386
  * ```typescript
291
- * const expiry = await client.ttl("session:abc");
292
- * if (expiry instanceof Date) {
293
- * console.log(`Expires at: ${expiry.toISOString()}`);
294
- * } else if (expiry === null) {
295
- * console.log("No expiration set");
296
- * } else {
297
- * console.log("Key does not exist");
387
+ * const t = await client.ttl("session:abc");
388
+ * switch (t.state) {
389
+ * case "expires": console.log(`expires at ${t.at.toISOString()}`); break;
390
+ * case "no-ttl": console.log("no expiration"); break;
391
+ * case "missing": console.log("key not found"); break;
298
392
  * }
299
393
  * ```
394
+ *
395
+ * Note: Deno KV cannot report TTL state — always returns `{ state: "no-ttl" }`
396
+ * for existing keys and `{ state: "missing" }` for absent ones.
300
397
  */
301
- ttl(key: string): Promise<Date | null | false>;
398
+ ttl(key: string): Promise<TtlResult>;
302
399
  /**
303
400
  * Returns information about the current adapter instance.
304
401
  *
@@ -322,6 +419,6 @@ export declare abstract class AdapterAbstract {
322
419
  */
323
420
  __debug_dump(): Promise<Record<string, {
324
421
  value: any;
325
- ttl: Date | null | false;
422
+ ttl: Date | null;
326
423
  }>>;
327
424
  }
@@ -3,6 +3,16 @@
3
3
  *
4
4
  * Abstract base class and shared types for all KV adapters.
5
5
  */
6
+ /**
7
+ * Thrown when a CAS-based atomic primitive (e.g. Deno KV `incr`/`cas`)
8
+ * exhausts its retry budget due to contention on the key.
9
+ */
10
+ export class KvRaceError extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "KvRaceError";
14
+ }
15
+ }
6
16
  function notImplemented() {
7
17
  throw new Error("Not implemented");
8
18
  }
@@ -26,6 +36,7 @@ export class AdapterAbstract {
26
36
  _type = "abstract";
27
37
  options = {
28
38
  defaultTtl: 0,
39
+ validateKeys: true,
29
40
  };
30
41
  _initialized = false;
31
42
  /**
@@ -55,6 +66,17 @@ export class AdapterAbstract {
55
66
  }
56
67
  }
57
68
  _withNs(key) {
69
+ if (this.options.validateKeys !== false) {
70
+ if (typeof key !== "string" || key.length === 0) {
71
+ throw new TypeError("KV key must be a non-empty string");
72
+ }
73
+ if (key.includes("\0")) {
74
+ throw new TypeError("KV key must not contain null characters (\\0)");
75
+ }
76
+ if (this.namespace.length + key.length > 512) {
77
+ throw new RangeError(`KV key exceeds 512-char limit (namespace + key = ${this.namespace.length + key.length})`);
78
+ }
79
+ }
58
80
  return this.namespace + key;
59
81
  }
60
82
  _withoutNs(key) {
@@ -88,6 +110,12 @@ export class AdapterAbstract {
88
110
  const body = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
89
111
  return new RegExp(`^${body}$`);
90
112
  }
113
+ /**
114
+ * Normalizes the polymorphic `setMultiple` input to a single shape.
115
+ */
116
+ _normalizePairs(entries) {
117
+ return entries.map((e) => Array.isArray(e) ? { key: e[0], value: e[1] } : e);
118
+ }
91
119
  /**
92
120
  * Stores a key-value pair in the storage.
93
121
  *
@@ -107,6 +135,55 @@ export class AdapterAbstract {
107
135
  set(key, value, options) {
108
136
  return notImplemented();
109
137
  }
138
+ /**
139
+ * Stores a key-value pair only when the key does not already exist.
140
+ *
141
+ * @returns `true` if the value was stored, `false` if the key existed.
142
+ */
143
+ setIfAbsent(key, value, options) {
144
+ return notImplemented();
145
+ }
146
+ /**
147
+ * Atomically sets a new value and returns the previous one.
148
+ *
149
+ * @returns The previous value, or `null` if the key did not exist.
150
+ */
151
+ getSet(key, value, options) {
152
+ return notImplemented();
153
+ }
154
+ /**
155
+ * Atomically increments a numeric value.
156
+ *
157
+ * If the key does not exist, it is created with the value `by`.
158
+ * If the key exists but is not a JSON number, throws `TypeError`.
159
+ *
160
+ * TTL semantics: `options.ttl` (or `defaultTtl`) is applied only when the
161
+ * key is newly created by this call. Existing TTLs are preserved.
162
+ *
163
+ * @returns The new numeric value after the increment.
164
+ * @throws {TypeError} If the stored value is not a number.
165
+ */
166
+ incr(key, by, options) {
167
+ return notImplemented();
168
+ }
169
+ /**
170
+ * Atomically decrements a numeric value. See {@link incr} for details.
171
+ */
172
+ decr(key, by, options) {
173
+ return notImplemented();
174
+ }
175
+ /**
176
+ * Atomic compare-and-set. Replaces the stored value with `next` only when
177
+ * the currently-stored value deep-equals `expected`.
178
+ *
179
+ * Missing keys never match, even when `expected` is `null`.
180
+ *
181
+ * @returns `true` if the swap happened, `false` if the current value did
182
+ * not match.
183
+ */
184
+ cas(key, expected, next, options) {
185
+ return notImplemented();
186
+ }
110
187
  /**
111
188
  * Retrieves a value by its key.
112
189
  *
@@ -129,7 +206,8 @@ export class AdapterAbstract {
129
206
  *
130
207
  * @param key - The key to delete.
131
208
  * @returns A promise that resolves to `true` if the key existed and was deleted,
132
- * `false` if the key didn't exist. Note: Deno KV always returns `true`.
209
+ * `false` if the key didn't exist. Note: Deno KV always returns `true` unless
210
+ * the adapter was created with `strictDeleteResult: true`.
133
211
  *
134
212
  * @example
135
213
  * ```typescript
@@ -176,6 +254,22 @@ export class AdapterAbstract {
176
254
  keys(pattern) {
177
255
  return notImplemented();
178
256
  }
257
+ /**
258
+ * Iterates matching keys without materializing the full list.
259
+ *
260
+ * Prefer this over {@link keys} for unbounded or unknown-sized scans.
261
+ * Ordering is not guaranteed across adapters.
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * for await (const k of client.keysIter("user:*")) {
266
+ * console.log(k);
267
+ * }
268
+ * ```
269
+ */
270
+ keysIter(pattern) {
271
+ return notImplemented();
272
+ }
179
273
  /**
180
274
  * Deletes all keys matching a pattern.
181
275
  *
@@ -198,21 +292,22 @@ export class AdapterAbstract {
198
292
  /**
199
293
  * Stores multiple key-value pairs in a single batch operation.
200
294
  *
201
- * More efficient than multiple individual `set` calls, especially for Redis and PostgreSQL.
295
+ * Accepts either tuples `[key, value]` (legacy) or objects
296
+ * `{ key, value, ttl? }`. Per-pair `ttl` overrides `options.ttl`.
202
297
  *
203
- * @param keyValuePairs - An array of `[key, value]` tuples to store.
204
- * @param options - Optional settings applied to all pairs (e.g., TTL).
205
- * @returns A promise that resolves to an array of boolean results for each operation.
298
+ * @param entries - Pairs to store.
299
+ * @param options - Optional batch-wide settings (TTL fallback).
300
+ * @returns Array of boolean results (one per entry).
206
301
  *
207
302
  * @example
208
303
  * ```typescript
209
304
  * await client.setMultiple([
210
305
  * ["user:1", { name: "Alice" }],
211
- * ["user:2", { name: "Bob" }],
306
+ * { key: "user:2", value: { name: "Bob" }, ttl: 30 },
212
307
  * ], { ttl: 3600 });
213
308
  * ```
214
309
  */
215
- setMultiple(keyValuePairs, options) {
310
+ setMultiple(entries, options) {
216
311
  return notImplemented();
217
312
  }
218
313
  /**
@@ -273,26 +368,20 @@ export class AdapterAbstract {
273
368
  return notImplemented();
274
369
  }
275
370
  /**
276
- * Gets the expiration time of a key.
277
- *
278
- * @param key - The key to check.
279
- * @returns A promise that resolves to:
280
- * - `Date` - The expiration date if TTL is set
281
- * - `null` - If the key exists but has no expiration
282
- * - `false` - If the key doesn't exist or has expired
283
- * Note: Deno KV always returns `null` (TTL query not supported).
371
+ * Gets the expiration time of a key as a discriminated union.
284
372
  *
285
373
  * @example
286
374
  * ```typescript
287
- * const expiry = await client.ttl("session:abc");
288
- * if (expiry instanceof Date) {
289
- * console.log(`Expires at: ${expiry.toISOString()}`);
290
- * } else if (expiry === null) {
291
- * console.log("No expiration set");
292
- * } else {
293
- * console.log("Key does not exist");
375
+ * const t = await client.ttl("session:abc");
376
+ * switch (t.state) {
377
+ * case "expires": console.log(`expires at ${t.at.toISOString()}`); break;
378
+ * case "no-ttl": console.log("no expiration"); break;
379
+ * case "missing": console.log("key not found"); break;
294
380
  * }
295
381
  * ```
382
+ *
383
+ * Note: Deno KV cannot report TTL state — always returns `{ state: "no-ttl" }`
384
+ * for existing keys and `{ state: "missing" }` for absent ones.
296
385
  */
297
386
  ttl(key) {
298
387
  return notImplemented();
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Deno KV key-value storage adapter implementation.
5
5
  */
6
- import { AdapterAbstract, type Operation, type SetOptions, type AdapterAbstractOptions } from "./abstract.js";
6
+ import { AdapterAbstract, type Operation, type SetMultipleEntry, type SetOptions, type TtlResult, type AdapterAbstractOptions } from "./abstract.js";
7
7
  /**
8
8
  * Configuration options for the Deno KV adapter.
9
9
  */
@@ -13,6 +13,20 @@ export interface AdapterDenoKvOptions extends AdapterAbstractOptions {
13
13
  * @see https://docs.deno.com/deploy/kv/#testing
14
14
  */
15
15
  db: any;
16
+ /**
17
+ * When `true`, `delete()` pre-checks the key's existence and returns
18
+ * the real "did it exist?" flag — at the cost of one extra round-trip.
19
+ * Default `false` preserves the Deno.Kv native "always true" behavior.
20
+ */
21
+ strictDeleteResult?: boolean;
22
+ /**
23
+ * Max retry attempts for CAS-based primitives (`incr`, `decr`, `getSet`,
24
+ * `cas`) before throwing `KvRaceError`. Each attempt waits a small
25
+ * exponential-backoff delay, so 20 retries covers substantial contention
26
+ * without blocking callers for long.
27
+ * @default 20
28
+ */
29
+ atomicRetryAttempts?: number;
16
30
  }
17
31
  /**
18
32
  * Deno KV key-value storage adapter.
@@ -22,11 +36,14 @@ export interface AdapterDenoKvOptions extends AdapterAbstractOptions {
22
36
  *
23
37
  * @remarks
24
38
  * - Only works in Deno runtime (will throw error in Node.js)
25
- * - `delete()` always returns `true` (Deno.Kv limitation)
26
- * - `expire()` is not supported - always returns `false`
27
- * - `ttl()` is not supported - always returns `null`
28
- * - TTL can be set during `set()` but cannot be queried afterward
39
+ * - `delete()` returns `true` by default even for missing keys (Deno.Kv
40
+ * limitation); opt in to strict behavior via `strictDeleteResult: true`
41
+ * - `expire()` is not supported — always returns `false`
42
+ * - `ttl()` returns `{ state: "no-ttl" }` for present keys (TTL cannot be
43
+ * queried) and `{ state: "missing" }` for absent ones
29
44
  * - Uses `getMany()` for efficient batch reads
45
+ * - Atomic primitives (`incr`, `decr`, `getSet`, `cas`) use a CAS retry loop
46
+ * backed by Deno.Kv's native `atomic().check()`
30
47
  *
31
48
  * @example
32
49
  * ```typescript
@@ -49,6 +66,16 @@ export declare class AdapterDenoKv extends AdapterAbstract {
49
66
  /** @inheritdoc */
50
67
  set(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
51
68
  /** @inheritdoc */
69
+ setIfAbsent(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>;
70
+ /** @inheritdoc */
71
+ getSet(key: string, value: any, options?: Partial<SetOptions>): Promise<any>;
72
+ /** @inheritdoc */
73
+ incr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
74
+ /** @inheritdoc */
75
+ decr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>;
76
+ /** @inheritdoc */
77
+ cas(key: string, expected: any, next: any, options?: Partial<SetOptions>): Promise<boolean>;
78
+ /** @inheritdoc */
52
79
  get(key: string): Promise<any>;
53
80
  /** @inheritdoc */
54
81
  exists(key: string): Promise<boolean>;
@@ -57,21 +84,24 @@ export declare class AdapterDenoKv extends AdapterAbstract {
57
84
  /** @inheritdoc */
58
85
  keys(pattern: string): Promise<string[]>;
59
86
  /** @inheritdoc */
87
+ keysIter(pattern: string): AsyncIterable<string>;
88
+ /** @inheritdoc */
60
89
  clear(pattern: string): Promise<number>;
61
90
  /** @inheritdoc */
62
- setMultiple(keyValuePairs: [string, any][], options?: Partial<SetOptions>): Promise<boolean[]>;
91
+ setMultiple(entries: readonly SetMultipleEntry[], options?: Partial<SetOptions>): Promise<boolean[]>;
63
92
  /** @inheritdoc */
64
93
  getMultiple(keys: string[]): Promise<Record<string, any>>;
65
94
  /** @inheritdoc */
66
95
  transaction(operations: Operation[]): Promise<any[]>;
67
96
  /**
68
- * Not supported in Deno.Kv - always returns `false`.
97
+ * Not supported in Deno.Kv — always returns `false`.
69
98
  * @inheritdoc
70
99
  */
71
- expire(key: string, ttl: number): Promise<boolean>;
100
+ expire(_key: string, _ttl: number): Promise<boolean>;
72
101
  /**
73
- * Not supported in Deno.Kv - always returns `null`.
74
- * @inheritdoc
102
+ * Deno.Kv cannot report TTL state. Returns `{ state: "no-ttl" }` for
103
+ * existing keys (whether or not they actually have an expireIn set)
104
+ * and `{ state: "missing" }` for absent keys.
75
105
  */
76
- ttl(key: string): Promise<Date | null | false>;
106
+ ttl(key: string): Promise<TtlResult>;
77
107
  }