@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/AGENTS.md CHANGED
@@ -6,7 +6,7 @@ Machine-friendly reference for AI agents working with this codebase.
6
6
 
7
7
  - **Stack**: TypeScript, Deno (primary), Node.js (via npm build)
8
8
  - **Run**: `deno task test` | **Build**: `deno task npm:build`
9
- - **Version**: 1.3.1
9
+ - **Version**: 2.1.0
10
10
 
11
11
  ## Purpose
12
12
 
@@ -36,10 +36,20 @@ tests/
36
36
 
37
37
  ## Critical Conventions
38
38
 
39
- 1. Namespace must end with `:` or be empty string
40
- 2. Values are JSON-stringified internally
41
- 3. TTL is in seconds; stored as absolute Date internally
42
- 4. Pattern matching: Redis-style (`*` = any chars, `?` = single char)
39
+ 1. Namespace must end with `:` or be empty string.
40
+ 2. Values are JSON-stringified internally.
41
+ 3. TTL is in seconds; stored as absolute `Date` internally.
42
+ 4. Pattern matching: Redis-style (`*` = any chars, `?` = single char). All other characters — including `.`, `(`, `[`, `%`, `_` — are matched **literally**.
43
+ 5. TTL resolution: `options.ttl ?? defaultTtl`; `0` or negative disables expiration for that call (explicitly overrides `defaultTtl`).
44
+ 6. All pattern-to-regex / pattern-to-LIKE conversion lives in `abstract.ts` — use `_globToRegex()`, `_resolveTtl()`, `_normalizePairs()`; do not re-implement per-adapter.
45
+ 7. Postgres `transaction()` must pin a single connection via `pool.connect()`; every nested query uses that client, not `this.options.db`.
46
+ 8. Redis adapter owns the connection iff `initialize()` opened it (`#weOpened` flag).
47
+ 9. Key validation lives in `_withNs()` — enforced when `options.validateKeys !== false`. Reject empty strings, keys with `\0`, and total `namespace + key` length > 512.
48
+ 10. `ttl()` returns `TtlResult = { state: "missing" | "no-ttl" | "expires"; at? }` — discriminated union, not `Date | null | false`.
49
+ 11. `incr`/`decr`/`getSet`/`cas`/`setIfAbsent` must be atomic: Redis = Lua or NX; Postgres = UPSERT/UPDATE with RETURNING; Deno KV = `#atomicUpdate` CAS retry loop; Memory = plain read-modify-write (single-threaded).
50
+ 12. Non-numeric `incr`/`decr` target throws `TypeError("KV value is not a number")`. In Postgres, detect via error code `22P02`.
51
+ 13. Deno KV atomic retries exhausted → throw `KvRaceError` (imported from `abstract.ts`).
52
+ 14. `keysIter` must clean up on early consumer break — PG releases its server-side cursor in the generator's `finally`.
43
53
 
44
54
  ## Before Making Changes
45
55
 
@@ -53,8 +63,8 @@ tests/
53
63
  |---------|-------------|------------------|-------------|
54
64
  | Memory | `"memory"` | None | Not persisted |
55
65
  | Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
56
- | PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | None |
57
- | Deno KV | `"deno-kv"` | `db` (Deno.Kv) | Deno runtime only; `delete()` always true; `expire()`/`ttl()` not supported |
66
+ | PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | `tableName` limited to `[A-Za-z0-9_]` + optional `schema.` prefix |
67
+ | Deno KV | `"deno-kv"` | `db` (Deno.Kv) | Deno runtime only; `delete()` always `true`; `expire()`/`ttl()` unsupported; `transaction()` atomic only when no `get` ops |
58
68
 
59
69
  ## Core API
60
70
 
@@ -67,20 +77,35 @@ createKVClient(namespace?: string, type?: AdapterType, options?: AdapterOptions)
67
77
  ### Client Methods
68
78
 
69
79
  ```
80
+ // lifecycle
70
81
  initialize(): Promise<void>
71
82
  destroy(hard?: boolean): Promise<void>
72
83
  info(): AdapterInfo
73
- set(key: string, value: any, options?: SetOptions): Promise<boolean>
74
- get(key: string): Promise<any>
75
- delete(key: string): Promise<boolean>
76
- exists(key: string): Promise<boolean>
77
- keys(pattern: string): Promise<string[]>
78
- clear(pattern: string): Promise<number>
79
- setMultiple(pairs: [string, any][], options?: SetOptions): Promise<boolean[]>
80
- getMultiple(keys: string[]): Promise<Record<string, any>>
84
+
85
+ // single-key
86
+ set(key, value, options?): Promise<boolean>
87
+ setIfAbsent(key, value, options?): Promise<boolean> // atomic
88
+ getSet(key, value, options?): Promise<any> // returns previous
89
+ incr(key, by?=1, options?): Promise<number> // atomic
90
+ decr(key, by?=1, options?): Promise<number> // atomic
91
+ cas(key, expected, next, options?): Promise<boolean> // atomic
92
+ get(key): Promise<any>
93
+ delete(key): Promise<boolean>
94
+ exists(key): Promise<boolean>
95
+
96
+ // patterns
97
+ keys(pattern): Promise<string[]> // sorted
98
+ keysIter(pattern): AsyncIterable<string> // streaming
99
+ clear(pattern): Promise<number>
100
+
101
+ // batch
102
+ setMultiple(entries: SetMultipleEntry[], options?): Promise<boolean[]>
103
+ getMultiple(keys): Promise<Record<string, any>>
81
104
  transaction(operations: Operation[]): Promise<any[]>
82
- expire(key: string, ttl: number): Promise<boolean>
83
- ttl(key: string): Promise<Date | null | false>
105
+
106
+ // TTL
107
+ expire(key, ttl): Promise<boolean>
108
+ ttl(key): Promise<TtlResult>
84
109
  ```
85
110
 
86
111
  ## Key Types
@@ -88,8 +113,19 @@ ttl(key: string): Promise<Date | null | false>
88
113
  ```typescript
89
114
  interface SetOptions { ttl: number }
90
115
  interface AdapterInfo { type: string }
91
- interface AdapterAbstractOptions { defaultTtl: number; logger?: Logger }
116
+ interface AdapterAbstractOptions { defaultTtl: number; logger?: Logger; validateKeys?: boolean }
92
117
  interface Operation { type: "set" | "get" | "delete"; key: string; value?: any; options?: SetOptions }
118
+
119
+ type SetMultipleEntry =
120
+ | [string, any]
121
+ | { key: string; value: any; ttl?: number };
122
+
123
+ type TtlResult =
124
+ | { state: "missing" }
125
+ | { state: "no-ttl" }
126
+ | { state: "expires"; at: Date };
127
+
128
+ class KvRaceError extends Error {} // Deno KV CAS retry-exhaustion
93
129
  ```
94
130
 
95
131
  ## Commands
package/API.md CHANGED
@@ -149,11 +149,110 @@ Values are automatically serialized to JSON. If the key already exists, it will
149
149
 
150
150
  **Returns:** `Promise<boolean>` - `true` if the operation was successful.
151
151
 
152
+ **TTL resolution:**
153
+
154
+ - If `options.ttl` is omitted, the adapter's `defaultTtl` is used.
155
+ - If `options.ttl` is a positive number, it overrides `defaultTtl` for this call.
156
+ - If `options.ttl` is `0` or negative, **no expiration** is applied — this explicitly overrides a non-zero `defaultTtl`.
157
+
152
158
  **Example:**
153
159
 
154
160
  ```typescript
155
161
  await client.set("user:123", { name: "John" });
156
162
  await client.set("session:abc", { token: "xyz" }, { ttl: 3600 }); // expires in 1 hour
163
+ await client.set("pinned", 1, { ttl: 0 }); // never expires, even if defaultTtl > 0
164
+ ```
165
+
166
+ ---
167
+
168
+ #### `setIfAbsent(key, value, options?)`
169
+
170
+ Stores a value only if the key does not already exist. Atomic.
171
+
172
+ ```typescript
173
+ setIfAbsent(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>
174
+ ```
175
+
176
+ **Returns:** `true` if the value was stored, `false` if the key existed. Expired keys are treated as missing — `setIfAbsent` succeeds on them.
177
+
178
+ **Example** (lock pattern):
179
+
180
+ ```typescript
181
+ if (await client.setIfAbsent("lock:job:42", { by: "worker-1" }, { ttl: 30 })) {
182
+ // we got the lock
183
+ }
184
+ ```
185
+
186
+ ---
187
+
188
+ #### `getSet(key, value, options?)`
189
+
190
+ Atomically replaces the stored value and returns the previous one.
191
+
192
+ ```typescript
193
+ getSet(key: string, value: any, options?: Partial<SetOptions>): Promise<any>
194
+ ```
195
+
196
+ **Returns:** the previous value, or `null` if the key did not exist.
197
+
198
+ Stored falsy values (`false`, `0`, `""`, `null`) round-trip correctly.
199
+
200
+ ---
201
+
202
+ #### `incr(key, by?, options?)` / `decr(key, by?, options?)`
203
+
204
+ Atomically increments (or decrements) a numeric value.
205
+
206
+ ```typescript
207
+ incr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>
208
+ decr(key: string, by?: number, options?: Partial<SetOptions>): Promise<number>
209
+ ```
210
+
211
+ **Parameters:**
212
+
213
+ | Parameter | Type | Default | Description |
214
+ |---|---|---|---|
215
+ | `key` | `string` | — | The key to increment |
216
+ | `by` | `number` | `1` | Amount to add (or subtract for `decr`) |
217
+ | `options` | `Partial<SetOptions>` | — | TTL only applies on key creation — existing keys keep their TTL |
218
+
219
+ **Returns:** the new value after the operation.
220
+
221
+ **Errors:** throws `TypeError("KV value is not a number")` when the stored value is not a JSON number. On Deno KV under heavy contention, may throw `KvRaceError` after `atomicRetryAttempts` (default 20) failed CAS attempts.
222
+
223
+ **Example:**
224
+
225
+ ```typescript
226
+ await client.incr("views"); // creates "views" = 1
227
+ await client.incr("views", 10); // now 11
228
+ await client.decr("views", 3); // now 8
229
+
230
+ // Sliding window: TTL only applied on first hit
231
+ await client.incr("rate:user:1", 1, { ttl: 60 });
232
+ ```
233
+
234
+ ---
235
+
236
+ #### `cas(key, expected, next, options?)`
237
+
238
+ Atomic compare-and-set — replaces the stored value only when the current value deep-equals `expected`.
239
+
240
+ ```typescript
241
+ cas(key: string, expected: any, next: any, options?: Partial<SetOptions>): Promise<boolean>
242
+ ```
243
+
244
+ **Returns:** `true` if the swap happened, `false` otherwise (mismatch or missing key).
245
+
246
+ > Missing keys never match, even when `expected` is `null`.
247
+
248
+ When `options.ttl` is supplied, the stored expiration is updated on success. When it is omitted, the existing TTL is preserved (Deno KV: best-effort — see the Deno KV section).
249
+
250
+ **Example** (optimistic update):
251
+
252
+ ```typescript
253
+ const current = await client.get("counter");
254
+ const swapped = await client.cas("counter", current, current + 1);
255
+ if (!swapped) { /* retry or reconcile */ }
157
256
  ```
158
257
 
159
258
  ---
@@ -221,6 +320,8 @@ exists(key: string): Promise<boolean>
221
320
 
222
321
  **Returns:** `Promise<boolean>` - `true` if the key exists and hasn't expired.
223
322
 
323
+ > A key with a stored value of `null` is considered to exist. `exists()` only returns `false` when the key is missing or has expired.
324
+
224
325
  ---
225
326
 
226
327
  #### `expire(key, ttl)`
@@ -253,10 +354,15 @@ await client.expire("session:abc", 1800); // Expire in 30 minutes
253
354
 
254
355
  #### `ttl(key)`
255
356
 
256
- Gets the expiration time of a key.
357
+ Gets the expiration state of a key as a discriminated union.
257
358
 
258
359
  ```typescript
259
- ttl(key: string): Promise<Date | null | false>
360
+ ttl(key: string): Promise<TtlResult>
361
+
362
+ type TtlResult =
363
+ | { state: "missing" }
364
+ | { state: "no-ttl" }
365
+ | { state: "expires"; at: Date };
260
366
  ```
261
367
 
262
368
  **Parameters:**
@@ -265,26 +371,40 @@ ttl(key: string): Promise<Date | null | false>
265
371
  |-----------|------|-------------|
266
372
  | `key` | `string` | The key to check. |
267
373
 
268
- **Returns:**
269
- - `Date` - The expiration date if TTL is set
270
- - `null` - If the key exists but has no expiration
271
- - `false` - If the key doesn't exist or has expired
374
+ **Returns:** A `TtlResult`. Switch on `.state`:
375
+ - `"missing"` — key doesn't exist (or has expired)
376
+ - `"no-ttl"` — key exists with no expiration
377
+ - `"expires"` — key exists and will expire at `.at`
272
378
 
273
- > **Note:** Deno KV always returns `null` (TTL query not supported).
379
+ > **Note:** Deno KV cannot query TTL — existing keys always return `{ state: "no-ttl" }`; absent keys return `{ state: "missing" }`.
274
380
 
275
381
  **Example:**
276
382
 
277
383
  ```typescript
278
- const expiry = await client.ttl("session:abc");
279
- if (expiry instanceof Date) {
280
- console.log(`Expires at: ${expiry.toISOString()}`);
281
- } else if (expiry === null) {
282
- console.log("No expiration set");
283
- } else {
284
- console.log("Key does not exist");
384
+ const t = await client.ttl("session:abc");
385
+ switch (t.state) {
386
+ case "expires": console.log(`Expires at ${t.at.toISOString()}`); break;
387
+ case "no-ttl": console.log("No expiration set"); break;
388
+ case "missing": console.log("Key does not exist"); break;
285
389
  }
286
390
  ```
287
391
 
392
+ **Migrating from pre-3.0** (`Date | null | false`):
393
+
394
+ ```typescript
395
+ // old
396
+ const t = await client.ttl(k);
397
+ if (t instanceof Date) use(t);
398
+ else if (t === null) // no ttl
399
+ else // missing
400
+
401
+ // new (equivalent)
402
+ const t = await client.ttl(k);
403
+ if (t.state === "expires") use(t.at);
404
+ else if (t.state === "no-ttl") // no ttl
405
+ else // missing
406
+ ```
407
+
288
408
  ---
289
409
 
290
410
  ### Pattern-Based Operations
@@ -300,6 +420,7 @@ keys(pattern: string): Promise<string[]>
300
420
  Uses Redis-style wildcard patterns:
301
421
  - `*` matches any number of characters
302
422
  - `?` matches exactly one character
423
+ - **Every other character is a literal match**, including regex metacharacters (`.`, `(`, `[`, `+`, `^`, `$`, `|`) and SQL LIKE metacharacters (`%`, `_`, `\`).
303
424
 
304
425
  **Parameters:**
305
426
 
@@ -316,6 +437,35 @@ Uses Redis-style wildcard patterns:
316
437
  ```typescript
317
438
  const userKeys = await client.keys("user:*");
318
439
  const allKeys = await client.keys("*");
440
+
441
+ // literal dot, not "any char"
442
+ const dotted = await client.keys("config.yaml"); // matches ONLY "config.yaml"
443
+ ```
444
+
445
+ ---
446
+
447
+ #### `keysIter(pattern)`
448
+
449
+ Iterates matching keys without materializing the full list. Prefer this over `keys()` for unbounded or unknown-sized scans.
450
+
451
+ ```typescript
452
+ keysIter(pattern: string): AsyncIterable<string>
453
+ ```
454
+
455
+ Ordering is not guaranteed across adapters — use `keys()` if you need sorted output.
456
+
457
+ **Per-adapter behavior:**
458
+ - Redis: wraps `SCAN` (non-blocking).
459
+ - PostgreSQL: uses a server-side cursor (`DECLARE CURSOR`) inside a short transaction. Early break releases the cursor and commits.
460
+ - Deno KV: direct `db.list()` pass-through.
461
+ - Memory: yields from the internal `Map`.
462
+
463
+ **Example:**
464
+
465
+ ```typescript
466
+ for await (const k of client.keysIter("user:*")) {
467
+ if (someCondition(k)) break; // safe — cursor is released
468
+ }
319
469
  ```
320
470
 
321
471
  ---
@@ -351,32 +501,40 @@ const clearedAll = await client.clear("*"); // Clear everything
351
501
 
352
502
  ### Batch Operations
353
503
 
354
- #### `setMultiple(keyValuePairs, options?)`
504
+ #### `setMultiple(entries, options?)`
355
505
 
356
506
  Stores multiple key-value pairs in a single batch operation.
357
507
 
358
508
  ```typescript
359
- setMultiple(keyValuePairs: [string, any][], options?: Partial<SetOptions>): Promise<boolean[]>
509
+ setMultiple(
510
+ entries: [string, any][] | { key: string; value: any; ttl?: number }[],
511
+ options?: Partial<SetOptions>
512
+ ): Promise<boolean[]>
360
513
  ```
361
514
 
362
- More efficient than multiple individual `set` calls, especially for Redis and PostgreSQL.
515
+ Accepts either the legacy tuple shape or an object shape that allows a **per-pair `ttl`** overriding `options.ttl`.
516
+
517
+ More efficient than multiple individual `set` calls, especially for Redis, PostgreSQL, and Deno KV (the latter commits atomically).
363
518
 
364
519
  **Parameters:**
365
520
 
366
521
  | Parameter | Type | Description |
367
522
  |-----------|------|-------------|
368
- | `keyValuePairs` | `[string, any][]` | Array of `[key, value]` tuples to store. |
369
- | `options` | `Partial<SetOptions>` | Optional settings applied to all pairs (e.g., TTL). |
523
+ | `entries` | `[string, any][]` or `{ key, value, ttl? }[]` | Pairs to store. |
524
+ | `options` | `Partial<SetOptions>` | Fallback TTL used when a pair has no explicit `ttl`. |
370
525
 
371
- **Returns:** `Promise<boolean[]>` - Array of boolean results for each operation.
526
+ **Returns:** `Promise<boolean[]>` — one per entry.
372
527
 
373
528
  **Example:**
374
529
 
375
530
  ```typescript
376
- await client.setMultiple([
377
- ["user:1", { name: "Alice" }],
378
- ["user:2", { name: "Bob" }],
379
- ], { ttl: 3600 });
531
+ await client.setMultiple(
532
+ [
533
+ ["user:1", { name: "Alice" }], // uses options.ttl
534
+ { key: "user:2", value: { name: "Bob" }, ttl: 60 }, // overrides to 60s
535
+ ],
536
+ { ttl: 3600 }
537
+ );
380
538
  ```
381
539
 
382
540
  ---
@@ -397,13 +555,16 @@ More efficient than multiple individual `get` calls.
397
555
  |-----------|------|-------------|
398
556
  | `keys` | `string[]` | Array of keys to retrieve. |
399
557
 
400
- **Returns:** `Promise<Record<string, any>>` - Object mapping keys to their values. Missing or expired keys will have a value of `null`.
558
+ **Returns:** `Promise<Record<string, any>>` - Object mapping keys to their values. Only **missing** or expired keys are reported as `null`; stored falsy values (`false`, `0`, `""`, `null`) are returned verbatim.
401
559
 
402
560
  **Example:**
403
561
 
404
562
  ```typescript
405
- const users = await client.getMultiple(["user:1", "user:2", "user:3"]);
406
- // { "user:1": { name: "Alice" }, "user:2": null, "user:3": { name: "Charlie" } }
563
+ await client.set("flag", false);
564
+ await client.set("count", 0);
565
+
566
+ const got = await client.getMultiple(["flag", "count", "missing"]);
567
+ // { flag: false, count: 0, missing: null }
407
568
  ```
408
569
 
409
570
  ---
@@ -418,7 +579,16 @@ Executes multiple operations within a single transaction.
418
579
  transaction(operations: Operation[]): Promise<any[]>
419
580
  ```
420
581
 
421
- For adapters that support it (Redis, PostgreSQL), operations are atomic. For memory and Deno KV, operations are executed sequentially.
582
+ Atomicity per adapter:
583
+
584
+ | Adapter | Atomic | Notes |
585
+ |---------|:-:|---|
586
+ | Memory | ✓ | Single-threaded by nature |
587
+ | Redis | ✓ | Uses `MULTI`/`EXEC` |
588
+ | PostgreSQL | ✓ | Pins a single connection for `BEGIN`/…/`COMMIT`, even on a `pg.Pool` |
589
+ | Deno KV | Conditional | Atomic via `Deno.Kv.atomic()` when the transaction contains **no** `get` ops; falls back to sequential (non-atomic) when a `get` is present (Deno.Kv has no atomic-read) |
590
+
591
+ Per-operation `options.ttl` is honored by **all** adapters (Redis, PostgreSQL, Memory, Deno KV).
422
592
 
423
593
  **Parameters:**
424
594
 
@@ -432,7 +602,7 @@ For adapters that support it (Redis, PostgreSQL), operations are atomic. For mem
432
602
 
433
603
  ```typescript
434
604
  const results = await client.transaction([
435
- { type: "set", key: "counter", value: 1 },
605
+ { type: "set", key: "counter", value: 1, options: { ttl: 60 } },
436
606
  { type: "get", key: "counter" },
437
607
  { type: "delete", key: "old:key" },
438
608
  ]);
@@ -479,11 +649,54 @@ interface AdapterAbstractOptions {
479
649
  defaultTtl: number;
480
650
  /** Optional logger instance for debugging and error logging. */
481
651
  logger?: Logger;
652
+ /**
653
+ * When true (default), keys are validated on every operation:
654
+ * - non-empty string
655
+ * - no `\0` characters
656
+ * - total `namespace + key` length ≤ 512
657
+ * Set to false to opt out.
658
+ */
659
+ validateKeys?: boolean;
482
660
  }
483
661
  ```
484
662
 
485
663
  ---
486
664
 
665
+ ### `TtlResult`
666
+
667
+ ```typescript
668
+ type TtlResult =
669
+ | { state: "missing" }
670
+ | { state: "no-ttl" }
671
+ | { state: "expires"; at: Date };
672
+ ```
673
+
674
+ Return shape of `ttl(key)`. See the `ttl()` method above.
675
+
676
+ ---
677
+
678
+ ### `SetMultipleEntry`
679
+
680
+ ```typescript
681
+ type SetMultipleEntry =
682
+ | [string, any]
683
+ | { key: string; value: any; ttl?: number };
684
+ ```
685
+
686
+ Input shape accepted by `setMultiple()`.
687
+
688
+ ---
689
+
690
+ ### `KvRaceError`
691
+
692
+ ```typescript
693
+ class KvRaceError extends Error { /* ... */ }
694
+ ```
695
+
696
+ Thrown by Deno KV-backed CAS primitives (`incr`, `decr`, `getSet`, `cas`) when the retry budget is exhausted due to contention. Configurable via the adapter's `atomicRetryAttempts` option.
697
+
698
+ ---
699
+
487
700
  ### `Operation`
488
701
 
489
702
  Represents a single operation within a transaction.
@@ -539,6 +752,12 @@ interface AdapterRedisOptions extends AdapterAbstractOptions {
539
752
 
540
753
  **Important:** Namespace is required for Redis adapter (cannot be empty string).
541
754
 
755
+ **Connection ownership:**
756
+
757
+ - If the client passed via `db` is **not yet open** when `initialize()` runs, the adapter connects it **and** will close it on `destroy()`.
758
+ - If the client is **already open** when `initialize()` runs, the adapter leaves the connection untouched on `destroy()` — the caller owns the lifecycle. This is the path for sharing one client across multiple adapters with different namespaces.
759
+ - `initialize()` is idempotent — repeated calls do not stack `error` listeners.
760
+
542
761
  ---
543
762
 
544
763
  ### `AdapterPostgresOptions`
@@ -550,6 +769,9 @@ interface AdapterPostgresOptions extends AdapterAbstractOptions {
550
769
  /**
551
770
  * Name of the table to use for storing key-value pairs.
552
771
  * The table will be created automatically if it doesn't exist.
772
+ * May be prefixed with a schema, e.g. "public.kv".
773
+ * Must match `^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$`
774
+ * (word characters, optionally with one `schema.` prefix).
553
775
  * @default "__kv"
554
776
  */
555
777
  tableName: string;
@@ -561,6 +783,9 @@ interface AdapterPostgresOptions extends AdapterAbstractOptions {
561
783
  }
562
784
  ```
563
785
 
786
+ **Transactions on a Pool:**
787
+ `transaction()` checks out a single client from the pool (via `pool.connect()`) for the entire `BEGIN`/`COMMIT`/`ROLLBACK` block, so atomicity holds even when multiple transactions run concurrently against the same `pg.Pool`. On a `pg.Client`, no checkout happens.
788
+
564
789
  **Table Schema:**
565
790
  - `key` (VARCHAR 512) - Primary key
566
791
  - `value` (JSONB) - Stored value
@@ -578,15 +803,32 @@ interface AdapterDenoKvOptions extends AdapterAbstractOptions {
578
803
  * Deno.Kv instance obtained via `Deno.openKv()`.
579
804
  */
580
805
  db: Deno.Kv;
806
+
807
+ /**
808
+ * When true, `delete()` pre-checks the key's existence and returns the
809
+ * real "did it exist?" flag — at the cost of one extra round-trip.
810
+ * Default false preserves the Deno.Kv native always-true behavior.
811
+ */
812
+ strictDeleteResult?: boolean;
813
+
814
+ /**
815
+ * Max retry attempts for CAS-based primitives (incr/decr/getSet/cas)
816
+ * before throwing KvRaceError. Each retry adds exponential-with-jitter
817
+ * backoff capped at 50ms.
818
+ * @default 20
819
+ */
820
+ atomicRetryAttempts?: number;
581
821
  }
582
822
  ```
583
823
 
584
824
  **Limitations:**
585
825
  - Only works in Deno runtime
586
- - `delete()` always returns `true` (Deno.Kv limitation)
826
+ - `delete()` always returns `true` by default (Deno.Kv limitation) — opt-in to strict behavior via `strictDeleteResult: true`
587
827
  - `expire()` is not supported (always returns `false`)
588
- - `ttl()` is not supported (always returns `null`)
828
+ - `ttl()` returns `{ state: "no-ttl" }` for any existing key and `{ state: "missing" }` for absent ones — Deno.Kv cannot report the actual expiration
589
829
  - TTL can be set during `set()` but cannot be queried afterward
830
+ - `transaction()` is atomic (via `Deno.Kv.atomic()`) **only** when the transaction contains no `get` operations — a mixed transaction falls back to sequential, non-atomic execution
831
+ - `cas()` without `options.ttl` is best-effort TTL-preserving: Deno.Kv cannot read the current expiration, so any existing `expireIn` is cleared when the swap succeeds. Supply `options.ttl` explicitly if the key should remain bounded.
590
832
 
591
833
  ---
592
834
 
package/CLAUDE.md ADDED
@@ -0,0 +1,3 @@
1
+ # Project Instructions
2
+
3
+ See [AGENTS.md](./AGENTS.md) for complete project documentation and AI agent instructions.