@marianmeres/kv 1.3.2 → 2.2.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.
package/README.md CHANGED
@@ -48,38 +48,155 @@ await client.keys('my:*'); // ['my:foo:key']
48
48
  ## API
49
49
 
50
50
  ```typescript
51
+ // single-key ops
51
52
  client.set(key: string, value: any, options?): Promise<boolean>
53
+ client.setIfAbsent(key: string, value: any, options?): Promise<boolean>
52
54
  client.get(key: string): Promise<any>
55
+ client.getSet(key: string, value: any, options?): Promise<any> // returns previous value
53
56
  client.delete(key: string): Promise<boolean>
54
57
  client.exists(key: string): Promise<boolean>
58
+
59
+ // atomic primitives
60
+ client.incr(key: string, by?: number, options?): Promise<number>
61
+ client.decr(key: string, by?: number, options?): Promise<number>
62
+ client.cas(key: string, expected: any, next: any, options?): Promise<boolean>
63
+
64
+ // patterns & iteration
55
65
  client.keys(pattern: string): Promise<string[]>
66
+ client.keysIter(pattern: string): AsyncIterable<string>
56
67
  client.clear(pattern: string): Promise<number>
57
- client.setMultiple(keyValuePairs: [string, any][], options?): Promise<any[]>
68
+
69
+ // batch
70
+ client.setMultiple(
71
+ entries: [string, any][] | { key: string; value: any; ttl?: number }[],
72
+ options?
73
+ ): Promise<boolean[]>
58
74
  client.getMultiple(keys: string[]): Promise<Record<string, any>>
59
75
  client.transaction(operations: Operation[]): Promise<any[]>
76
+
77
+ // TTL
60
78
  client.expire(key: string, ttl: number): Promise<boolean>
61
- client.ttl(key: string): Promise<Date | null | false>
79
+ client.ttl(key: string): Promise<TtlResult>
62
80
  ```
63
81
 
82
+ ### `TtlResult`
83
+
84
+ ```typescript
85
+ type TtlResult =
86
+ | { state: "missing" }
87
+ | { state: "no-ttl" }
88
+ | { state: "expires"; at: Date };
89
+ ```
90
+
91
+ ## Pattern Syntax
92
+
93
+ `keys()` and `clear()` use Redis-style glob patterns:
94
+
95
+ - `*` — match any number of characters
96
+ - `?` — match exactly one character
97
+ - all other characters (including `.`, `%`, `_`, `(`, `)`, `[`, `]`) are treated **literally**
98
+
99
+ ## Adapter Feature Matrix
100
+
101
+ | Feature | Memory | Redis | PostgreSQL | Deno KV |
102
+ |---|:-:|:-:|:-:|:-:|
103
+ | Persistent | ✗ | ✓ | ✓ | ✓ |
104
+ | TTL on `set()` | ✓ | ✓ | ✓ | ✓ |
105
+ | `ttl()` → `expires`/`no-ttl`/`missing` | ✓ | ✓ | ✓ | `no-ttl`/`missing` only |
106
+ | `expire()` | ✓ | ✓ | ✓ | always `false` |
107
+ | Atomic `setIfAbsent` / `incr` / `decr` / `cas` / `getSet` | ✓ | ✓ (Lua) | ✓ (UPSERT) | ✓ (CAS retry loop) |
108
+ | Sorted `keys()` | ✓ | ✓ | ✓ | ✓ |
109
+ | Streaming `keysIter()` | ✓ | ✓ (SCAN) | ✓ (cursor) | ✓ (native) |
110
+ | Per-pair TTL in `setMultiple` | ✓ | ✓ | ✓ | ✓ |
111
+ | Atomic `transaction()` | ✓ (single-threaded) | ✓ (MULTI) | ✓ (BEGIN/COMMIT) | ✓ when no `get` ops |
112
+ | `delete()` returns real existed-flag | ✓ | ✓ | ✓ | opt-in via `strictDeleteResult` |
113
+ | Background TTL cleanup | optional | native (Redis does it) | optional | native (Deno.Kv does it) |
114
+ | `keys()` / `clear()` | ✓ | ✓ (non-cluster only) | ✓ | ✓ |
115
+
64
116
  ## Adapter-Specific Limitations
65
117
 
66
118
  ### Deno KV
67
119
  - **`delete()`**: Always returns `true`, even for non-existent keys (Deno.Kv limitation)
68
- - **`expire()`**: Not supported - always returns `false`
69
- - **`ttl()`**: Not supported - always returns `null`
70
- - **Note**: TTL can be set during `set()` operation, but cannot be queried or modified after
120
+ - **`expire()`**: Not supported — always returns `false`
121
+ - **`ttl()`**: Not supported — always returns `null`
122
+ - **`transaction()`**: Atomic via `Deno.Kv.atomic()` **only** when the transaction contains no `get` operations. A transaction that mixes `get` with `set`/`delete` falls back to sequential (non-atomic) execution.
123
+ - **Note**: TTL can be set during `set()`, but cannot be queried or modified after.
71
124
 
72
125
  ### Redis
73
126
  - **`keys()` and `clear()`**: Not supported in cluster mode (throws error)
74
127
  - **Namespace**: Required (cannot be empty string)
128
+ - **Connection ownership**: If you pass a not-yet-open client to the adapter, `initialize()` opens it and `destroy()` closes it. If you pass an already-open client, the adapter leaves the connection lifecycle to you — safe to share a single client across adapters with different namespaces.
75
129
 
76
130
  ### PostgreSQL
77
- - Creates a table (default: `__kv`) in your database
78
- - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option
131
+ - Creates a table (default: `__kv`) in your database.
132
+ - `tableName` must match `^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$` (word chars plus an optional `schema.` prefix).
133
+ - `transaction()` pins a single connection from the Pool for the whole BEGIN/…/COMMIT block — safe to call against a `pg.Pool`.
134
+ - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option.
79
135
 
80
136
  ### Memory
81
- - Data is not persisted (in-memory only)
82
- - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option
137
+ - Data is not persisted (in-memory only).
138
+ - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option.
139
+
140
+ ## Breaking Changes (2.1 / 3.0 candidate)
141
+
142
+ Since 2.0, the following changes are in this tree:
143
+
144
+ **v3.0 (breaking — bump major if you ship these as-is):**
145
+ - **`ttl(key)` now returns a discriminated `TtlResult`** — `{ state: "missing" | "no-ttl" | "expires", at? }` — instead of `Date | null | false`. Migration:
146
+ ```ts
147
+ // before
148
+ const t = await client.ttl(k);
149
+ if (t instanceof Date) use(t);
150
+ else if (t === null) /* no ttl */
151
+ else /* missing */
152
+
153
+ // after
154
+ const t = await client.ttl(k);
155
+ switch (t.state) {
156
+ case "expires": use(t.at); break;
157
+ case "no-ttl": /* … */; break;
158
+ case "missing": /* … */; break;
159
+ }
160
+ ```
161
+ - **Key validation is on by default.** Non-empty strings, no `\0`, total `namespace + key` length ≤ 512. Set `validateKeys: false` on the adapter options to opt out. Previous behavior silently accepted empty/overlong keys and let the backend error cryptically.
162
+
163
+ **v2.1 / v2.2 (additive):**
164
+ - New methods `setIfAbsent`, `incr`, `decr`, `getSet`, `cas`, `keysIter` on every adapter.
165
+ - `setMultiple` accepts `{ key, value, ttl? }[]` entries in addition to the legacy `[key, value][]` tuples. Per-pair `ttl` overrides batch `options.ttl`.
166
+ - Deno KV: new `strictDeleteResult: true` option pre-checks existence so `delete()` returns the real did-it-exist flag (default stays `true` for BC).
167
+ - Deno KV: new `atomicRetryAttempts` option (default 20) for CAS-based primitives under contention.
168
+ - Default `clear()` in Deno KV now batches into atomic commits (500 at a time).
169
+
170
+ ## Breaking Changes (2.0.0)
171
+
172
+ This release fixes several correctness bugs. Most fixes are behavior-preserving,
173
+ but a few change semantics in ways that could affect existing code:
174
+
175
+ - **`set(key, value, { ttl: 0 })` now explicitly disables expiration for the
176
+ call, overriding any non-zero `defaultTtl`.** Before: `ttl: 0` was silently
177
+ ignored and `defaultTtl` was used. If you relied on the old behavior, omit
178
+ the `ttl` option instead of passing `0`.
179
+ - **Redis adapter: `destroy()` now closes connections that `initialize()` opened.**
180
+ Connections that were already open when you passed them to the adapter remain
181
+ under your control (unchanged). If your test harness used to close the
182
+ underlying client twice, remove the redundant close.
183
+ - **Redis adapter: `__debug_dump()` is scoped to the adapter's namespace.**
184
+ Before: it dumped every key in the selected DB (across tenants). After:
185
+ only keys under this adapter's namespace.
186
+ - **`getMultiple()` preserves stored falsy values (`false`, `0`, `""`, `null`).**
187
+ Before: all of these were coerced to `null`, indistinguishable from "key
188
+ missing". After: stored falsy values round-trip; only missing keys map to
189
+ `null`.
190
+ - **Deno KV: `exists(key)` returns `true` when the stored value is `null`.**
191
+ Before: `null` values were reported as non-existent.
192
+ - **Deno KV: `keys()` is sorted.**
193
+ - **`keys()` and `clear()` now treat non-wildcard regex/LIKE metacharacters
194
+ as literals.** Before: Memory/Deno KV adapters leaked `.`/`(`/`[` through to
195
+ regex, and the PostgreSQL adapter leaked `%`/`_` through to LIKE. After:
196
+ only `*` and `?` are wildcards; everything else matches literally.
197
+ - **PostgreSQL: `tableName` is validated.** Invalid names (anything outside
198
+ `[A-Za-z0-9_.]`) now throw in the constructor instead of producing confusing
199
+ SQL errors at runtime.
83
200
 
84
201
  ## Full API Reference
85
202
 
@@ -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
  *
@@ -73,6 +113,33 @@ export declare abstract class AdapterAbstract {
73
113
  protected _assertValidNamespace(): void;
74
114
  protected _withNs(key: string): string;
75
115
  protected _withoutNs(key: string): string;
116
+ /**
117
+ * Resolves the effective TTL (in seconds) for a set operation.
118
+ *
119
+ * Uses `options.ttl` when provided, otherwise falls back to `defaultTtl`.
120
+ * Non-positive values (0 or less) mean "no expiration" and return `undefined`.
121
+ *
122
+ * Note: `{ ttl: 0 }` explicitly overrides a non-zero `defaultTtl` to mean
123
+ * "no expiration for this call".
124
+ */
125
+ protected _resolveTtl(opts?: Partial<SetOptions>): number | undefined;
126
+ /**
127
+ * Converts a Redis-style glob pattern to a regular expression.
128
+ * Escapes regex metacharacters before translating `*`/`?`.
129
+ *
130
+ * Glob syntax: `*` matches any chars, `?` matches a single char.
131
+ * All other characters — including `.`, `(`, `)`, `[`, `]`, `+` — are
132
+ * matched literally.
133
+ */
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
+ }>;
76
143
  /**
77
144
  * Initializes the adapter and connects to the underlying storage.
78
145
  *
@@ -110,6 +177,45 @@ export declare abstract class AdapterAbstract {
110
177
  * ```
111
178
  */
112
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>;
113
219
  /**
114
220
  * Retrieves a value by its key.
115
221
  *
@@ -130,7 +236,8 @@ export declare abstract class AdapterAbstract {
130
236
  *
131
237
  * @param key - The key to delete.
132
238
  * @returns A promise that resolves to `true` if the key existed and was deleted,
133
- * `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`.
134
241
  *
135
242
  * @example
136
243
  * ```typescript
@@ -171,6 +278,20 @@ export declare abstract class AdapterAbstract {
171
278
  * @throws {Error} In Redis cluster mode.
172
279
  */
173
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>;
174
295
  /**
175
296
  * Deletes all keys matching a pattern.
176
297
  *
@@ -191,21 +312,22 @@ export declare abstract class AdapterAbstract {
191
312
  /**
192
313
  * Stores multiple key-value pairs in a single batch operation.
193
314
  *
194
- * 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`.
195
317
  *
196
- * @param keyValuePairs - An array of `[key, value]` tuples to store.
197
- * @param options - Optional settings applied to all pairs (e.g., TTL).
198
- * @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).
199
321
  *
200
322
  * @example
201
323
  * ```typescript
202
324
  * await client.setMultiple([
203
325
  * ["user:1", { name: "Alice" }],
204
- * ["user:2", { name: "Bob" }],
326
+ * { key: "user:2", value: { name: "Bob" }, ttl: 30 },
205
327
  * ], { ttl: 3600 });
206
328
  * ```
207
329
  */
208
- setMultiple(keyValuePairs: [string, any][], options?: Partial<SetOptions>): Promise<any[]>;
330
+ setMultiple(entries: readonly SetMultipleEntry[], options?: Partial<SetOptions>): Promise<boolean[]>;
209
331
  /**
210
332
  * Retrieves multiple values in a single batch operation.
211
333
  *
@@ -258,28 +380,22 @@ export declare abstract class AdapterAbstract {
258
380
  */
259
381
  expire(key: string, ttl: number): Promise<boolean>;
260
382
  /**
261
- * Gets the expiration time of a key.
262
- *
263
- * @param key - The key to check.
264
- * @returns A promise that resolves to:
265
- * - `Date` - The expiration date if TTL is set
266
- * - `null` - If the key exists but has no expiration
267
- * - `false` - If the key doesn't exist or has expired
268
- * Note: Deno KV always returns `null` (TTL query not supported).
383
+ * Gets the expiration time of a key as a discriminated union.
269
384
  *
270
385
  * @example
271
386
  * ```typescript
272
- * const expiry = await client.ttl("session:abc");
273
- * if (expiry instanceof Date) {
274
- * console.log(`Expires at: ${expiry.toISOString()}`);
275
- * } else if (expiry === null) {
276
- * console.log("No expiration set");
277
- * } else {
278
- * 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;
279
392
  * }
280
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.
281
397
  */
282
- ttl(key: string): Promise<Date | null | false>;
398
+ ttl(key: string): Promise<TtlResult>;
283
399
  /**
284
400
  * Returns information about the current adapter instance.
285
401
  *
@@ -303,6 +419,6 @@ export declare abstract class AdapterAbstract {
303
419
  */
304
420
  __debug_dump(): Promise<Record<string, {
305
421
  value: any;
306
- ttl: Date | null | false;
422
+ ttl: Date | null;
307
423
  }>>;
308
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
  /**
@@ -39,7 +50,10 @@ export class AdapterAbstract {
39
50
  constructor(namespace = "", options = {}) {
40
51
  this.namespace = namespace;
41
52
  this.options = { ...this.options, ...(options || {}) };
42
- this._assertValidNamespace();
53
+ // NOTE: subclasses re-declare `namespace` with a field initializer, so
54
+ // validation runs in each subclass constructor AFTER `super()` completes.
55
+ // Calling `_assertValidNamespace()` here would see the base default (empty)
56
+ // and provide no safety.
43
57
  }
44
58
  _assertInitialized() {
45
59
  if (!this._initialized) {
@@ -52,6 +66,17 @@ export class AdapterAbstract {
52
66
  }
53
67
  }
54
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
+ }
55
80
  return this.namespace + key;
56
81
  }
57
82
  _withoutNs(key) {
@@ -59,6 +84,38 @@ export class AdapterAbstract {
59
84
  key = key.slice(this.namespace.length);
60
85
  return key;
61
86
  }
87
+ /**
88
+ * Resolves the effective TTL (in seconds) for a set operation.
89
+ *
90
+ * Uses `options.ttl` when provided, otherwise falls back to `defaultTtl`.
91
+ * Non-positive values (0 or less) mean "no expiration" and return `undefined`.
92
+ *
93
+ * Note: `{ ttl: 0 }` explicitly overrides a non-zero `defaultTtl` to mean
94
+ * "no expiration for this call".
95
+ */
96
+ _resolveTtl(opts) {
97
+ const raw = opts?.ttl ?? this.options.defaultTtl;
98
+ return raw && raw > 0 ? raw : undefined;
99
+ }
100
+ /**
101
+ * Converts a Redis-style glob pattern to a regular expression.
102
+ * Escapes regex metacharacters before translating `*`/`?`.
103
+ *
104
+ * Glob syntax: `*` matches any chars, `?` matches a single char.
105
+ * All other characters — including `.`, `(`, `)`, `[`, `]`, `+` — are
106
+ * matched literally.
107
+ */
108
+ _globToRegex(pattern) {
109
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
110
+ const body = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
111
+ return new RegExp(`^${body}$`);
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
+ }
62
119
  /**
63
120
  * Stores a key-value pair in the storage.
64
121
  *
@@ -78,6 +135,55 @@ export class AdapterAbstract {
78
135
  set(key, value, options) {
79
136
  return notImplemented();
80
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
+ }
81
187
  /**
82
188
  * Retrieves a value by its key.
83
189
  *
@@ -100,7 +206,8 @@ export class AdapterAbstract {
100
206
  *
101
207
  * @param key - The key to delete.
102
208
  * @returns A promise that resolves to `true` if the key existed and was deleted,
103
- * `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`.
104
211
  *
105
212
  * @example
106
213
  * ```typescript
@@ -147,6 +254,22 @@ export class AdapterAbstract {
147
254
  keys(pattern) {
148
255
  return notImplemented();
149
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
+ }
150
273
  /**
151
274
  * Deletes all keys matching a pattern.
152
275
  *
@@ -169,21 +292,22 @@ export class AdapterAbstract {
169
292
  /**
170
293
  * Stores multiple key-value pairs in a single batch operation.
171
294
  *
172
- * 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`.
173
297
  *
174
- * @param keyValuePairs - An array of `[key, value]` tuples to store.
175
- * @param options - Optional settings applied to all pairs (e.g., TTL).
176
- * @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).
177
301
  *
178
302
  * @example
179
303
  * ```typescript
180
304
  * await client.setMultiple([
181
305
  * ["user:1", { name: "Alice" }],
182
- * ["user:2", { name: "Bob" }],
306
+ * { key: "user:2", value: { name: "Bob" }, ttl: 30 },
183
307
  * ], { ttl: 3600 });
184
308
  * ```
185
309
  */
186
- setMultiple(keyValuePairs, options) {
310
+ setMultiple(entries, options) {
187
311
  return notImplemented();
188
312
  }
189
313
  /**
@@ -244,26 +368,20 @@ export class AdapterAbstract {
244
368
  return notImplemented();
245
369
  }
246
370
  /**
247
- * Gets the expiration time of a key.
248
- *
249
- * @param key - The key to check.
250
- * @returns A promise that resolves to:
251
- * - `Date` - The expiration date if TTL is set
252
- * - `null` - If the key exists but has no expiration
253
- * - `false` - If the key doesn't exist or has expired
254
- * Note: Deno KV always returns `null` (TTL query not supported).
371
+ * Gets the expiration time of a key as a discriminated union.
255
372
  *
256
373
  * @example
257
374
  * ```typescript
258
- * const expiry = await client.ttl("session:abc");
259
- * if (expiry instanceof Date) {
260
- * console.log(`Expires at: ${expiry.toISOString()}`);
261
- * } else if (expiry === null) {
262
- * console.log("No expiration set");
263
- * } else {
264
- * 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;
265
380
  * }
266
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.
267
385
  */
268
386
  ttl(key) {
269
387
  return notImplemented();