@marianmeres/kv 1.2.2 → 1.3.1

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 ADDED
@@ -0,0 +1,133 @@
1
+ # @marianmeres/kv - Agent Reference
2
+
3
+ Machine-friendly reference for AI agents working with this codebase.
4
+
5
+ ## Package Identity
6
+
7
+ - **Name**: `@marianmeres/kv`
8
+ - **Version**: 1.2.2
9
+ - **License**: MIT
10
+ - **Runtime**: Deno (primary), Node.js (via npm build)
11
+ - **Language**: TypeScript
12
+
13
+ ## Purpose
14
+
15
+ Key-value storage abstraction layer providing a unified Redis-inspired API across multiple storage backends.
16
+
17
+ ## Supported Adapters
18
+
19
+ | Adapter | Type String | Required Options | Limitations |
20
+ |---------|-------------|------------------|-------------|
21
+ | Memory | `"memory"` | None | Not persisted |
22
+ | Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
23
+ | PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | None |
24
+ | Deno KV | `"deno-kv"` | `db` (Deno.Kv) | Deno runtime only; `delete()` always true; `expire()`/`ttl()` not supported |
25
+
26
+ ## File Structure
27
+
28
+ ```
29
+ src/
30
+ ├── mod.ts # Main entry point, re-exports kv.ts
31
+ ├── kv.ts # Factory function and all exports
32
+ ├── adapter/
33
+ │ ├── abstract.ts # Base class + shared types
34
+ │ ├── memory.ts # In-memory adapter
35
+ │ ├── redis.ts # Redis adapter
36
+ │ ├── postgres.ts # PostgreSQL adapter
37
+ │ └── deno-kv.ts # Deno KV adapter
38
+ └── utils/
39
+ └── sleep.ts # Sleep utility function
40
+
41
+ tests/
42
+ ├── kv.test.ts # Main test file
43
+ ├── _tests-runner.ts # Test harness
44
+ ├── _redis.ts # Redis test helper
45
+ └── _pg.ts # PostgreSQL test helper
46
+ ```
47
+
48
+ ## Core API
49
+
50
+ ### Factory
51
+
52
+ ```typescript
53
+ createKVClient(namespace?: string, type?: AdapterType, options?: AdapterOptions): Adapter
54
+ ```
55
+
56
+ ### Client Methods
57
+
58
+ ```
59
+ initialize(): Promise<void>
60
+ destroy(hard?: boolean): Promise<void>
61
+ info(): AdapterInfo
62
+ set(key: string, value: any, options?: SetOptions): Promise<boolean>
63
+ get(key: string): Promise<any>
64
+ delete(key: string): Promise<boolean>
65
+ exists(key: string): Promise<boolean>
66
+ keys(pattern: string): Promise<string[]>
67
+ clear(pattern: string): Promise<number>
68
+ setMultiple(pairs: [string, any][], options?: SetOptions): Promise<boolean[]>
69
+ getMultiple(keys: string[]): Promise<Record<string, any>>
70
+ transaction(operations: Operation[]): Promise<any[]>
71
+ expire(key: string, ttl: number): Promise<boolean>
72
+ ttl(key: string): Promise<Date | null | false>
73
+ ```
74
+
75
+ ## Key Types
76
+
77
+ ```typescript
78
+ interface SetOptions { ttl: number }
79
+ interface AdapterInfo { type: string }
80
+ interface AdapterAbstractOptions { defaultTtl: number; logger?: Logger }
81
+ interface Operation { type: "set" | "get" | "delete"; key: string; value?: any; options?: SetOptions }
82
+ ```
83
+
84
+ ## Commands
85
+
86
+ ```bash
87
+ # Run tests (requires --unstable-kv for Deno KV)
88
+ deno test --unstable-kv -A --env-file
89
+
90
+ # Run tests with watch mode
91
+ deno test --unstable-kv -A --env-file --watch
92
+
93
+ # Build npm package
94
+ deno run -A scripts/build-npm.ts
95
+
96
+ # Publish to npm
97
+ deno run -A scripts/build-npm.ts && cd ./.npm-dist && npm publish --access=public
98
+ ```
99
+
100
+ ## Test Environment Variables
101
+
102
+ ```
103
+ TEST_PG_HOST=localhost
104
+ TEST_PG_PORT=5432
105
+ TEST_PG_DATABASE=<required>
106
+ TEST_PG_USER=<required>
107
+ TEST_PG_PASSWORD=<required>
108
+ TEST_REDIS_URL=redis://localhost:6379
109
+ ```
110
+
111
+ ## Implementation Notes
112
+
113
+ 1. **Namespace**: Must end with `:` or be empty string
114
+ 2. **Value Serialization**: All values JSON-stringified internally
115
+ 3. **TTL**: In seconds; stored as absolute Date internally
116
+ 4. **Pattern Matching**: Redis-style (`*` = any chars, `?` = single char)
117
+ 5. **Transactions**: Atomic for Redis/PostgreSQL; sequential for memory/Deno KV
118
+
119
+ ## Dependencies
120
+
121
+ - `@marianmeres/clog` - Logging
122
+ - `pg` - PostgreSQL driver
123
+ - `redis` - Redis client
124
+
125
+ ## Extending
126
+
127
+ To add a new adapter:
128
+ 1. Create `src/adapter/<name>.ts`
129
+ 2. Extend `AdapterAbstract`
130
+ 3. Implement all abstract/interface methods
131
+ 4. Add to `KnownTypes` in `src/kv.ts`
132
+ 5. Add case in `createKVClient` factory
133
+ 6. Export from `src/kv.ts`
package/API.md ADDED
@@ -0,0 +1,624 @@
1
+ # @marianmeres/kv API Reference
2
+
3
+ Complete API documentation for the key-value storage abstraction layer.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Factory Function](#factory-function)
8
+ - [Client Methods](#client-methods)
9
+ - [Types and Interfaces](#types-and-interfaces)
10
+ - [Adapter-Specific Options](#adapter-specific-options)
11
+ - [Utility Functions](#utility-functions)
12
+
13
+ ---
14
+
15
+ ## Factory Function
16
+
17
+ ### `createKVClient<T>(namespace?, type?, options?)`
18
+
19
+ Creates and returns a KV client configured for the specified storage backend.
20
+
21
+ ```typescript
22
+ function createKVClient<T extends keyof KnownTypes>(
23
+ namespace: string = "",
24
+ type: T = "memory",
25
+ options: Partial<KnownTypes[T]["options"]> = {}
26
+ ): KnownTypes[T]["adapter"]
27
+ ```
28
+
29
+ **Type Parameters:**
30
+ - `T` - The adapter type (inferred from the `type` parameter)
31
+
32
+ **Parameters:**
33
+
34
+ | Parameter | Type | Default | Description |
35
+ |-----------|------|---------|-------------|
36
+ | `namespace` | `string` | `""` | Key prefix applied to all operations. Must end with `:` or be empty. |
37
+ | `type` | `"memory" \| "redis" \| "postgres" \| "deno-kv"` | `"memory"` | The storage backend to use. |
38
+ | `options` | `Partial<AdapterOptions>` | `{}` | Adapter-specific configuration options. |
39
+
40
+ **Returns:** A configured adapter instance. Call `initialize()` before use.
41
+
42
+ **Throws:**
43
+ - `TypeError` - If namespace doesn't end with `:` (and is not empty)
44
+ - `TypeError` - If an unsupported adapter type is specified
45
+ - `Error` - If `"deno-kv"` is used outside the Deno runtime
46
+ - `Error` - If required options (like `db`) are missing for the adapter
47
+
48
+ **Example:**
49
+
50
+ ```typescript
51
+ import { createKVClient } from "@marianmeres/kv";
52
+
53
+ // In-memory storage (great for testing)
54
+ const memoryClient = createKVClient("test:", "memory");
55
+ await memoryClient.initialize();
56
+
57
+ // Redis storage
58
+ import { createClient } from "redis";
59
+ const redisClient = createClient();
60
+ const redis = createKVClient("myapp:", "redis", { db: redisClient });
61
+ await redis.initialize();
62
+
63
+ // PostgreSQL storage
64
+ import pg from "pg";
65
+ const pool = new pg.Pool({ connectionString: "..." });
66
+ const postgres = createKVClient("myapp:", "postgres", { db: pool });
67
+ await postgres.initialize();
68
+
69
+ // Deno KV (Deno runtime only)
70
+ const kv = await Deno.openKv();
71
+ const denoKv = createKVClient("myapp:", "deno-kv", { db: kv });
72
+ await denoKv.initialize();
73
+ ```
74
+
75
+ ---
76
+
77
+ ## Client Methods
78
+
79
+ All adapter instances implement the following methods:
80
+
81
+ ### Lifecycle Methods
82
+
83
+ #### `initialize()`
84
+
85
+ Initializes the adapter and connects to the underlying storage.
86
+
87
+ ```typescript
88
+ initialize(): Promise<void>
89
+ ```
90
+
91
+ Must be called before any other operations. For some adapters (like memory), this is a no-op, but should always be called for consistency.
92
+
93
+ **Throws:** `Error` - If connection fails.
94
+
95
+ ---
96
+
97
+ #### `destroy(hard?)`
98
+
99
+ Destroys the adapter and releases all resources.
100
+
101
+ ```typescript
102
+ destroy(hard?: boolean): Promise<void>
103
+ ```
104
+
105
+ **Parameters:**
106
+
107
+ | Parameter | Type | Default | Description |
108
+ |-----------|------|---------|-------------|
109
+ | `hard` | `boolean` | `false` | If `true`, performs a hard cleanup (e.g., drops tables in PostgreSQL). |
110
+
111
+ ---
112
+
113
+ #### `info()`
114
+
115
+ Returns information about the current adapter instance.
116
+
117
+ ```typescript
118
+ info(): AdapterInfo
119
+ ```
120
+
121
+ **Returns:** `{ type: string }` - Object containing adapter metadata.
122
+
123
+ ```typescript
124
+ const info = client.info();
125
+ console.log(info.type); // "redis", "postgres", "memory", or "deno-kv"
126
+ ```
127
+
128
+ ---
129
+
130
+ ### Single Key Operations
131
+
132
+ #### `set(key, value, options?)`
133
+
134
+ Stores a key-value pair in the storage.
135
+
136
+ ```typescript
137
+ set(key: string, value: any, options?: Partial<SetOptions>): Promise<boolean>
138
+ ```
139
+
140
+ Values are automatically serialized to JSON. If the key already exists, it will be overwritten.
141
+
142
+ **Parameters:**
143
+
144
+ | Parameter | Type | Description |
145
+ |-----------|------|-------------|
146
+ | `key` | `string` | The key to store the value under. |
147
+ | `value` | `any` | The value to store. Can be any JSON-serializable value. `undefined` is stored as `null`. |
148
+ | `options` | `Partial<SetOptions>` | Optional settings including TTL. |
149
+
150
+ **Returns:** `Promise<boolean>` - `true` if the operation was successful.
151
+
152
+ **Example:**
153
+
154
+ ```typescript
155
+ await client.set("user:123", { name: "John" });
156
+ await client.set("session:abc", { token: "xyz" }, { ttl: 3600 }); // expires in 1 hour
157
+ ```
158
+
159
+ ---
160
+
161
+ #### `get(key)`
162
+
163
+ Retrieves a value by its key.
164
+
165
+ ```typescript
166
+ get(key: string): Promise<any>
167
+ ```
168
+
169
+ **Parameters:**
170
+
171
+ | Parameter | Type | Description |
172
+ |-----------|------|-------------|
173
+ | `key` | `string` | The key to retrieve. |
174
+
175
+ **Returns:** `Promise<any>` - The stored value, or `null` if the key doesn't exist or has expired.
176
+
177
+ **Example:**
178
+
179
+ ```typescript
180
+ const user = await client.get("user:123");
181
+ if (user) {
182
+ console.log(user.name);
183
+ }
184
+ ```
185
+
186
+ ---
187
+
188
+ #### `delete(key)`
189
+
190
+ Deletes a key from the storage.
191
+
192
+ ```typescript
193
+ delete(key: string): Promise<boolean>
194
+ ```
195
+
196
+ **Parameters:**
197
+
198
+ | Parameter | Type | Description |
199
+ |-----------|------|-------------|
200
+ | `key` | `string` | The key to delete. |
201
+
202
+ **Returns:** `Promise<boolean>` - `true` if the key existed and was deleted, `false` if it didn't exist.
203
+
204
+ > **Note:** Deno KV always returns `true`, even for non-existent keys.
205
+
206
+ ---
207
+
208
+ #### `exists(key)`
209
+
210
+ Checks if a key exists in the storage.
211
+
212
+ ```typescript
213
+ exists(key: string): Promise<boolean>
214
+ ```
215
+
216
+ **Parameters:**
217
+
218
+ | Parameter | Type | Description |
219
+ |-----------|------|-------------|
220
+ | `key` | `string` | The key to check. |
221
+
222
+ **Returns:** `Promise<boolean>` - `true` if the key exists and hasn't expired.
223
+
224
+ ---
225
+
226
+ #### `expire(key, ttl)`
227
+
228
+ Sets a new expiration time on an existing key.
229
+
230
+ ```typescript
231
+ expire(key: string, ttl: number): Promise<boolean>
232
+ ```
233
+
234
+ **Parameters:**
235
+
236
+ | Parameter | Type | Description |
237
+ |-----------|------|-------------|
238
+ | `key` | `string` | The key to set expiration on. |
239
+ | `ttl` | `number` | Time-to-live in seconds from now. |
240
+
241
+ **Returns:** `Promise<boolean>` - `true` if the expiration was set, `false` if the key doesn't exist.
242
+
243
+ > **Note:** Not supported in Deno KV (always returns `false`).
244
+
245
+ **Example:**
246
+
247
+ ```typescript
248
+ await client.set("session:abc", { user: "john" });
249
+ await client.expire("session:abc", 1800); // Expire in 30 minutes
250
+ ```
251
+
252
+ ---
253
+
254
+ #### `ttl(key)`
255
+
256
+ Gets the expiration time of a key.
257
+
258
+ ```typescript
259
+ ttl(key: string): Promise<Date | null | false>
260
+ ```
261
+
262
+ **Parameters:**
263
+
264
+ | Parameter | Type | Description |
265
+ |-----------|------|-------------|
266
+ | `key` | `string` | The key to check. |
267
+
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
272
+
273
+ > **Note:** Deno KV always returns `null` (TTL query not supported).
274
+
275
+ **Example:**
276
+
277
+ ```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");
285
+ }
286
+ ```
287
+
288
+ ---
289
+
290
+ ### Pattern-Based Operations
291
+
292
+ #### `keys(pattern)`
293
+
294
+ Lists all keys matching a pattern.
295
+
296
+ ```typescript
297
+ keys(pattern: string): Promise<string[]>
298
+ ```
299
+
300
+ Uses Redis-style wildcard patterns:
301
+ - `*` matches any number of characters
302
+ - `?` matches exactly one character
303
+
304
+ **Parameters:**
305
+
306
+ | Parameter | Type | Description |
307
+ |-----------|------|-------------|
308
+ | `pattern` | `string` | The pattern to match keys against (e.g., `"user:*"`, `"session:???"`). |
309
+
310
+ **Returns:** `Promise<string[]>` - Array of matching keys (without namespace prefix), sorted alphabetically.
311
+
312
+ **Throws:** `Error` - In Redis cluster mode.
313
+
314
+ **Example:**
315
+
316
+ ```typescript
317
+ const userKeys = await client.keys("user:*");
318
+ const allKeys = await client.keys("*");
319
+ ```
320
+
321
+ ---
322
+
323
+ #### `clear(pattern)`
324
+
325
+ Deletes all keys matching a pattern.
326
+
327
+ ```typescript
328
+ clear(pattern: string): Promise<number>
329
+ ```
330
+
331
+ Uses the same pattern syntax as `keys()`.
332
+
333
+ **Parameters:**
334
+
335
+ | Parameter | Type | Description |
336
+ |-----------|------|-------------|
337
+ | `pattern` | `string` | The pattern to match keys against. |
338
+
339
+ **Returns:** `Promise<number>` - The number of keys deleted.
340
+
341
+ **Throws:** `Error` - In Redis cluster mode.
342
+
343
+ **Example:**
344
+
345
+ ```typescript
346
+ const deleted = await client.clear("session:*"); // Clear all sessions
347
+ const clearedAll = await client.clear("*"); // Clear everything
348
+ ```
349
+
350
+ ---
351
+
352
+ ### Batch Operations
353
+
354
+ #### `setMultiple(keyValuePairs, options?)`
355
+
356
+ Stores multiple key-value pairs in a single batch operation.
357
+
358
+ ```typescript
359
+ setMultiple(keyValuePairs: [string, any][], options?: Partial<SetOptions>): Promise<boolean[]>
360
+ ```
361
+
362
+ More efficient than multiple individual `set` calls, especially for Redis and PostgreSQL.
363
+
364
+ **Parameters:**
365
+
366
+ | Parameter | Type | Description |
367
+ |-----------|------|-------------|
368
+ | `keyValuePairs` | `[string, any][]` | Array of `[key, value]` tuples to store. |
369
+ | `options` | `Partial<SetOptions>` | Optional settings applied to all pairs (e.g., TTL). |
370
+
371
+ **Returns:** `Promise<boolean[]>` - Array of boolean results for each operation.
372
+
373
+ **Example:**
374
+
375
+ ```typescript
376
+ await client.setMultiple([
377
+ ["user:1", { name: "Alice" }],
378
+ ["user:2", { name: "Bob" }],
379
+ ], { ttl: 3600 });
380
+ ```
381
+
382
+ ---
383
+
384
+ #### `getMultiple(keys)`
385
+
386
+ Retrieves multiple values in a single batch operation.
387
+
388
+ ```typescript
389
+ getMultiple(keys: string[]): Promise<Record<string, any>>
390
+ ```
391
+
392
+ More efficient than multiple individual `get` calls.
393
+
394
+ **Parameters:**
395
+
396
+ | Parameter | Type | Description |
397
+ |-----------|------|-------------|
398
+ | `keys` | `string[]` | Array of keys to retrieve. |
399
+
400
+ **Returns:** `Promise<Record<string, any>>` - Object mapping keys to their values. Missing or expired keys will have a value of `null`.
401
+
402
+ **Example:**
403
+
404
+ ```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" } }
407
+ ```
408
+
409
+ ---
410
+
411
+ ### Transactions
412
+
413
+ #### `transaction(operations)`
414
+
415
+ Executes multiple operations within a single transaction.
416
+
417
+ ```typescript
418
+ transaction(operations: Operation[]): Promise<any[]>
419
+ ```
420
+
421
+ For adapters that support it (Redis, PostgreSQL), operations are atomic. For memory and Deno KV, operations are executed sequentially.
422
+
423
+ **Parameters:**
424
+
425
+ | Parameter | Type | Description |
426
+ |-----------|------|-------------|
427
+ | `operations` | `Operation[]` | Array of operations to execute. |
428
+
429
+ **Returns:** `Promise<any[]>` - Array of results for each operation.
430
+
431
+ **Example:**
432
+
433
+ ```typescript
434
+ const results = await client.transaction([
435
+ { type: "set", key: "counter", value: 1 },
436
+ { type: "get", key: "counter" },
437
+ { type: "delete", key: "old:key" },
438
+ ]);
439
+ // [true, 1, true]
440
+ ```
441
+
442
+ ---
443
+
444
+ ## Types and Interfaces
445
+
446
+ ### `SetOptions`
447
+
448
+ Options for the `set` operation.
449
+
450
+ ```typescript
451
+ interface SetOptions {
452
+ /** Time-to-live in seconds. After this time, the key will expire. */
453
+ ttl: number;
454
+ }
455
+ ```
456
+
457
+ ---
458
+
459
+ ### `AdapterInfo`
460
+
461
+ Information about the adapter instance.
462
+
463
+ ```typescript
464
+ interface AdapterInfo {
465
+ /** The adapter type identifier. */
466
+ type: string; // "redis" | "postgres" | "memory" | "deno-kv"
467
+ }
468
+ ```
469
+
470
+ ---
471
+
472
+ ### `AdapterAbstractOptions`
473
+
474
+ Base options shared by all adapter implementations.
475
+
476
+ ```typescript
477
+ interface AdapterAbstractOptions {
478
+ /** Default TTL in seconds applied to all set operations when not explicitly specified. Set to 0 to disable. */
479
+ defaultTtl: number;
480
+ /** Optional logger instance for debugging and error logging. */
481
+ logger?: Logger;
482
+ }
483
+ ```
484
+
485
+ ---
486
+
487
+ ### `Operation`
488
+
489
+ Represents a single operation within a transaction.
490
+
491
+ ```typescript
492
+ interface Operation {
493
+ /** The type of operation to perform. */
494
+ type: "set" | "get" | "delete";
495
+ /** The key to operate on. */
496
+ key: string;
497
+ /** The value to set (only used for "set" operations). */
498
+ value?: any;
499
+ /** Optional settings for the operation (only used for "set" operations). */
500
+ options?: Partial<SetOptions>;
501
+ }
502
+ ```
503
+
504
+ ---
505
+
506
+ ## Adapter-Specific Options
507
+
508
+ ### `AdapterMemoryOptions`
509
+
510
+ ```typescript
511
+ interface AdapterMemoryOptions extends AdapterAbstractOptions {
512
+ /**
513
+ * Interval in seconds for automatic cleanup of expired keys.
514
+ * Set to 0 to disable automatic cleanup (expired keys will still be
515
+ * lazily removed on access).
516
+ */
517
+ ttlCleanupIntervalSec: number;
518
+ }
519
+ ```
520
+
521
+ ---
522
+
523
+ ### `AdapterRedisOptions`
524
+
525
+ ```typescript
526
+ interface AdapterRedisOptions extends AdapterAbstractOptions {
527
+ /**
528
+ * Redis client instance created via `createClient()` or `createClientPool()`.
529
+ * Pool support is experimental and not fully tested.
530
+ */
531
+ db: ReturnType<typeof createClient> | ReturnType<typeof createClientPool>;
532
+ /**
533
+ * Set to `true` if connecting to a Redis Cluster.
534
+ * Note: `keys()` and `clear()` operations are not supported in cluster mode.
535
+ */
536
+ isCluster: boolean;
537
+ }
538
+ ```
539
+
540
+ **Important:** Namespace is required for Redis adapter (cannot be empty string).
541
+
542
+ ---
543
+
544
+ ### `AdapterPostgresOptions`
545
+
546
+ ```typescript
547
+ interface AdapterPostgresOptions extends AdapterAbstractOptions {
548
+ /** PostgreSQL connection instance - either `pg.Pool` or `pg.Client`. */
549
+ db: pg.Pool | pg.Client;
550
+ /**
551
+ * Name of the table to use for storing key-value pairs.
552
+ * The table will be created automatically if it doesn't exist.
553
+ * @default "__kv"
554
+ */
555
+ tableName: string;
556
+ /**
557
+ * Interval in seconds for automatic cleanup of expired keys.
558
+ * Set to 0 to disable automatic cleanup.
559
+ */
560
+ ttlCleanupIntervalSec: number;
561
+ }
562
+ ```
563
+
564
+ **Table Schema:**
565
+ - `key` (VARCHAR 512) - Primary key
566
+ - `value` (JSONB) - Stored value
567
+ - `expires_at` (TIMESTAMP WITH TIME ZONE) - Expiration time
568
+ - `created_at` (TIMESTAMP WITH TIME ZONE) - Creation time
569
+ - `updated_at` (TIMESTAMP WITH TIME ZONE) - Last update time
570
+
571
+ ---
572
+
573
+ ### `AdapterDenoKvOptions`
574
+
575
+ ```typescript
576
+ interface AdapterDenoKvOptions extends AdapterAbstractOptions {
577
+ /**
578
+ * Deno.Kv instance obtained via `Deno.openKv()`.
579
+ */
580
+ db: Deno.Kv;
581
+ }
582
+ ```
583
+
584
+ **Limitations:**
585
+ - Only works in Deno runtime
586
+ - `delete()` always returns `true` (Deno.Kv limitation)
587
+ - `expire()` is not supported (always returns `false`)
588
+ - `ttl()` is not supported (always returns `null`)
589
+ - TTL can be set during `set()` but cannot be queried afterward
590
+
591
+ ---
592
+
593
+ ## Utility Functions
594
+
595
+ ### `sleep(timeout, __timeout_ref__?)`
596
+
597
+ Delays execution for the specified number of milliseconds.
598
+
599
+ ```typescript
600
+ function sleep(
601
+ timeout: number,
602
+ __timeout_ref__?: { id: number }
603
+ ): Promise<void>
604
+ ```
605
+
606
+ **Parameters:**
607
+
608
+ | Parameter | Type | Default | Description |
609
+ |-----------|------|---------|-------------|
610
+ | `timeout` | `number` | - | The delay in milliseconds. |
611
+ | `__timeout_ref__` | `{ id: number }` | `{ id: -1 }` | Optional reference object to capture the timeout ID for cleanup. |
612
+
613
+ **Example:**
614
+
615
+ ```typescript
616
+ import { sleep } from "@marianmeres/kv";
617
+
618
+ await sleep(1000); // Wait 1 second
619
+
620
+ // With timeout reference for cleanup
621
+ const ref = { id: -1 };
622
+ const sleepPromise = sleep(5000, ref);
623
+ // Later: clearTimeout(ref.id);
624
+ ```
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # @marianmeres/kv
2
2
 
3
- Key-value storage abstraction layer with support of multiple backend adapters:
3
+ [![NPM version](https://img.shields.io/npm/v/@marianmeres/kv.svg)](https://www.npmjs.com/package/@marianmeres/kv)
4
+ [![JSR version](https://jsr.io/badges/@marianmeres/kv)](https://jsr.io/@marianmeres/kv)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ Key-value storage abstraction layer with support for multiple backend adapters:
4
8
  - redis
5
9
  - postgresql
6
10
  - memory
@@ -77,9 +81,6 @@ client.ttl(key: string): Promise<Date | null | false>
77
81
  - Data is not persisted (in-memory only)
78
82
  - Supports optional TTL cleanup via `ttlCleanupIntervalSec` option
79
83
 
80
- ## Package Identity
84
+ ## Full API Reference
81
85
 
82
- - **Name:** @marianmeres/kv
83
- - **Author:** Marian Meres
84
- - **Repository:** https://github.com/marianmeres/kv
85
- - **License:** MIT
86
+ For complete API documentation including all methods, types, and adapter-specific options, see [API.md](API.md).
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Abstract base class and shared types for all KV adapters.
5
+ */
1
6
  import type { Logger } from "@marianmeres/clog";
2
7
  /**
3
8
  * Options for the `set` operation.
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Abstract base class and shared types for all KV adapters.
5
+ */
1
6
  function notImplemented() {
2
7
  throw new Error("Not implemented");
3
8
  }
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Deno KV key-value storage adapter implementation.
5
+ */
1
6
  import { AdapterAbstract, type Operation, type SetOptions, type AdapterAbstractOptions } from "./abstract.js";
2
7
  /**
3
8
  * Configuration options for the Deno KV adapter.
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Deno KV key-value storage adapter implementation.
5
+ */
1
6
  import { createClog } from "@marianmeres/clog";
2
7
  import { AdapterAbstract, } from "./abstract.js";
3
8
  /**
@@ -27,7 +32,7 @@ export class AdapterDenoKv extends AdapterAbstract {
27
32
  _type = "deno-kv";
28
33
  options = {
29
34
  defaultTtl: 0, // no ttl by default
30
- db: null,
35
+ db: null, // will be set in constructor via options merge
31
36
  logger: createClog("KV/deno-kv"),
32
37
  };
33
38
  constructor(namespace = "", options = {}) {
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * In-memory key-value storage adapter implementation.
5
+ */
1
6
  import { AdapterAbstract, type AdapterAbstractOptions, type Operation, type SetOptions } from "./abstract.js";
2
7
  /**
3
8
  * Configuration options for the in-memory KV adapter.
@@ -65,7 +70,7 @@ export declare class AdapterMemory extends AdapterAbstract {
65
70
  /** @inheritdoc */
66
71
  transaction(operations: Operation[]): Promise<any[]>;
67
72
  __debug_dump(): Promise<Record<string, {
68
- value: any;
73
+ value: unknown;
69
74
  ttl: Date | null | false;
70
75
  }>>;
71
76
  }
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * In-memory key-value storage adapter implementation.
5
+ */
1
6
  import { createClog } from "@marianmeres/clog";
2
7
  import { AdapterAbstract, } from "./abstract.js";
3
8
  /**
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * PostgreSQL key-value storage adapter implementation.
5
+ */
1
6
  import { AdapterAbstract, type Operation, type SetOptions, type AdapterAbstractOptions } from "./abstract.js";
2
7
  import type pg from "pg";
3
8
  /**
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * PostgreSQL key-value storage adapter implementation.
5
+ */
1
6
  import { AdapterAbstract, } from "./abstract.js";
2
7
  import { createClog } from "@marianmeres/clog";
3
8
  /**
@@ -33,7 +38,7 @@ export class AdapterPostgres extends AdapterAbstract {
33
38
  options = {
34
39
  defaultTtl: 0, // no ttl by default
35
40
  logger: createClog("KV/postgres"),
36
- db: null,
41
+ db: null, // will be set in constructor via options merge
37
42
  tableName: "__kv",
38
43
  ttlCleanupIntervalSec: 0,
39
44
  };
@@ -66,6 +71,11 @@ export class AdapterPostgres extends AdapterAbstract {
66
71
  ON ${tableName} (expires_at)
67
72
  WHERE expires_at IS NOT NULL
68
73
  `);
74
+ // Index for efficient prefix lookups with LIKE 'prefix%' queries
75
+ await db.query(`
76
+ CREATE INDEX IF NOT EXISTS idx_${safe(tableName)}_key_prefix
77
+ ON ${tableName} (key text_pattern_ops)
78
+ `);
69
79
  this._initialized = true;
70
80
  this.#maybeTTLCleanup();
71
81
  }
@@ -175,16 +185,21 @@ export class AdapterPostgres extends AdapterAbstract {
175
185
  async clear(pattern) {
176
186
  this._assertInitialized();
177
187
  const { db, tableName } = this.options;
178
- let params = [];
179
- const query = `DELETE FROM ${tableName} WHERE key LIKE $1`;
180
- if (pattern === "*") {
181
- params = [this.namespace + "%"];
182
- }
183
- else {
184
- params = [this.namespace + this.#likePattern(pattern)];
185
- }
186
- const { rowCount } = await db.query(query, params);
187
- return rowCount;
188
+ const likePattern = pattern === "*"
189
+ ? this.namespace + "%"
190
+ : this.namespace + this.#likePattern(pattern);
191
+ // Batch large deletions to prevent long-running transactions
192
+ const batchSize = 10000;
193
+ let totalDeleted = 0;
194
+ let deleted;
195
+ do {
196
+ const { rowCount } = await db.query(`DELETE FROM ${tableName} WHERE key IN (
197
+ SELECT key FROM ${tableName} WHERE key LIKE $1 LIMIT $2
198
+ )`, [likePattern, batchSize]);
199
+ deleted = rowCount ?? 0;
200
+ totalDeleted += deleted;
201
+ } while (deleted === batchSize);
202
+ return totalDeleted;
188
203
  }
189
204
  /** @inheritdoc */
190
205
  async setMultiple(keyValuePairs, options = {}) {
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Redis key-value storage adapter implementation.
5
+ */
1
6
  import type { createClient, createClientPool } from "redis";
2
7
  import { AdapterAbstract, type AdapterAbstractOptions, type Operation, type SetOptions } from "./abstract.js";
3
8
  /**
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Redis key-value storage adapter implementation.
5
+ */
1
6
  import { AdapterAbstract, } from "./abstract.js";
2
7
  import { createClog } from "@marianmeres/clog";
3
8
  /**
@@ -31,7 +36,7 @@ export class AdapterRedis extends AdapterAbstract {
31
36
  options = {
32
37
  defaultTtl: 0, // no ttl by default
33
38
  logger: createClog("KV/redis"),
34
- db: null,
39
+ db: null, // will be set in constructor via options merge
35
40
  isCluster: false,
36
41
  };
37
42
  constructor(namespace = "", options = {}) {
@@ -92,7 +97,7 @@ export class AdapterRedis extends AdapterAbstract {
92
97
  this._assertInitialized();
93
98
  key = this._withNs(key);
94
99
  const { db } = this.options;
95
- return parseInt((await db.del(key))) > 0;
100
+ return Number(await db.del(key)) > 0;
96
101
  }
97
102
  /** @inheritdoc */
98
103
  async exists(key) {
@@ -106,9 +111,20 @@ export class AdapterRedis extends AdapterAbstract {
106
111
  this._assertInitialized();
107
112
  const { db, isCluster } = this.options;
108
113
  if (isCluster) {
109
- throw new Error("KEYS command not supported in Redis Cluster mode");
114
+ throw new Error("keys() is not supported in Redis Cluster mode");
110
115
  }
111
- const keys = (await db.keys(this.namespace + pattern));
116
+ // Use SCAN instead of KEYS for non-blocking iteration
117
+ const fullPattern = this.namespace + pattern;
118
+ const keys = [];
119
+ let cursor = "0";
120
+ do {
121
+ const result = await db.scan(cursor, {
122
+ MATCH: fullPattern,
123
+ COUNT: 100,
124
+ });
125
+ cursor = `${result.cursor}`;
126
+ keys.push(...result.keys.map((k) => String(k)));
127
+ } while (cursor !== "0");
112
128
  return keys
113
129
  .map((k) => {
114
130
  // strip namespace if exists
@@ -128,7 +144,8 @@ export class AdapterRedis extends AdapterAbstract {
128
144
  const keys = await this.keys(pattern);
129
145
  if (keys.length === 0)
130
146
  return 0;
131
- return parseInt((await db.del(keys.map((k) => this._withNs(k)))));
147
+ // Use UNLINK instead of DEL for non-blocking memory reclamation
148
+ return Number(await db.unlink(keys.map((k) => this._withNs(k))));
132
149
  }
133
150
  /** @inheritdoc */
134
151
  async setMultiple(keyValuePairs, options = {}) {
@@ -141,7 +158,7 @@ export class AdapterRedis extends AdapterAbstract {
141
158
  pipeline.set(key, JSON.stringify(value), { EX: ttl });
142
159
  }
143
160
  const res = await pipeline.exec();
144
- return res.map((v) => v === "OK");
161
+ return res.map((v) => String(v) === "OK");
145
162
  }
146
163
  /** @inheritdoc */
147
164
  async getMultiple(keys) {
@@ -171,7 +188,7 @@ export class AdapterRedis extends AdapterAbstract {
171
188
  async expire(key, ttl) {
172
189
  this._assertInitialized();
173
190
  key = this._withNs(key);
174
- return parseInt((await this.options.db.expire(key, ttl))) > 0;
191
+ return Number(await this.options.db.expire(key, ttl)) > 0;
175
192
  }
176
193
  /** @inheritdoc */
177
194
  async ttl(key) {
@@ -211,18 +228,18 @@ export class AdapterRedis extends AdapterAbstract {
211
228
  for (const [i, op] of operations.entries()) {
212
229
  switch (op.type) {
213
230
  case "set":
214
- res[i] = res[i] === "OK";
231
+ res[i] = String(res[i]) === "OK";
215
232
  break;
216
233
  case "get":
217
234
  try {
218
- res[i] = JSON.parse(res[i]);
235
+ res[i] = JSON.parse(String(res[i]));
219
236
  }
220
237
  catch (_e) {
221
238
  /**/
222
239
  }
223
240
  break;
224
241
  case "delete":
225
- res[i] = res[i] > 0;
242
+ res[i] = Number(res[i]) > 0;
226
243
  break;
227
244
  }
228
245
  }
@@ -236,7 +253,7 @@ export class AdapterRedis extends AdapterAbstract {
236
253
  const keys = (await db.keys("*")).toSorted();
237
254
  const out = {};
238
255
  for (const _key of keys) {
239
- const key = this._withoutNs(_key);
256
+ const key = this._withoutNs(String(_key));
240
257
  out[key] = {
241
258
  value: await this.get(key),
242
259
  ttl: await this.ttl(key),
package/dist/kv.d.ts CHANGED
@@ -1,7 +1,22 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Factory module for creating KV client instances.
5
+ *
6
+ * Exports the main {@link createKVClient} factory function and re-exports
7
+ * all adapter classes, types, and interfaces.
8
+ */
1
9
  import { AdapterDenoKv, type AdapterDenoKvOptions } from "./adapter/deno-kv.js";
2
10
  import { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.js";
3
11
  import { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.js";
4
12
  import { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.js";
13
+ export type { SetOptions, AdapterInfo, AdapterAbstractOptions, Operation } from "./adapter/abstract.js";
14
+ export { AdapterAbstract } from "./adapter/abstract.js";
15
+ export { AdapterMemory, type AdapterMemoryOptions } from "./adapter/memory.js";
16
+ export { AdapterRedis, type AdapterRedisOptions } from "./adapter/redis.js";
17
+ export { AdapterPostgres, type AdapterPostgresOptions } from "./adapter/postgres.js";
18
+ export { AdapterDenoKv, type AdapterDenoKvOptions } from "./adapter/deno-kv.js";
19
+ export { sleep } from "./utils/sleep.js";
5
20
  /**
6
21
  * Type mapping for all supported KV adapter types.
7
22
  * @internal
@@ -73,4 +88,3 @@ interface KnownTypes {
73
88
  * ```
74
89
  */
75
90
  export declare function createKVClient<T extends keyof KnownTypes>(namespace?: string, type?: T, options?: Partial<KnownTypes[T]["options"]>): KnownTypes[T]["adapter"];
76
- export {};
package/dist/kv.js CHANGED
@@ -1,7 +1,21 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Factory module for creating KV client instances.
5
+ *
6
+ * Exports the main {@link createKVClient} factory function and re-exports
7
+ * all adapter classes, types, and interfaces.
8
+ */
1
9
  import { AdapterDenoKv } from "./adapter/deno-kv.js";
2
10
  import { AdapterMemory } from "./adapter/memory.js";
3
11
  import { AdapterPostgres, } from "./adapter/postgres.js";
4
12
  import { AdapterRedis } from "./adapter/redis.js";
13
+ export { AdapterAbstract } from "./adapter/abstract.js";
14
+ export { AdapterMemory } from "./adapter/memory.js";
15
+ export { AdapterRedis } from "./adapter/redis.js";
16
+ export { AdapterPostgres } from "./adapter/postgres.js";
17
+ export { AdapterDenoKv } from "./adapter/deno-kv.js";
18
+ export { sleep } from "./utils/sleep.js";
5
19
  /**
6
20
  * Factory function to create a KV client with the specified adapter type.
7
21
  *
package/dist/mod.d.ts CHANGED
@@ -1 +1,33 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Key-value storage abstraction layer with support for multiple backend adapters.
5
+ *
6
+ * This module provides a unified API for key-value operations across different storage backends:
7
+ * - **memory** - In-memory storage (default, not persisted)
8
+ * - **redis** - Redis server
9
+ * - **postgres** - PostgreSQL database
10
+ * - **deno-kv** - Deno KV (Deno runtime only)
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { createKVClient } from "@marianmeres/kv";
15
+ *
16
+ * // Create an in-memory client
17
+ * const client = createKVClient("myapp:", "memory");
18
+ * await client.initialize();
19
+ *
20
+ * // Basic operations
21
+ * await client.set("user:123", { name: "John" });
22
+ * const user = await client.get("user:123");
23
+ * await client.delete("user:123");
24
+ *
25
+ * // Pattern matching
26
+ * const keys = await client.keys("user:*");
27
+ * await client.clear("session:*");
28
+ *
29
+ * // Cleanup
30
+ * await client.destroy();
31
+ * ```
32
+ */
1
33
  export * from "./kv.js";
package/dist/mod.js CHANGED
@@ -1 +1,33 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Key-value storage abstraction layer with support for multiple backend adapters.
5
+ *
6
+ * This module provides a unified API for key-value operations across different storage backends:
7
+ * - **memory** - In-memory storage (default, not persisted)
8
+ * - **redis** - Redis server
9
+ * - **postgres** - PostgreSQL database
10
+ * - **deno-kv** - Deno KV (Deno runtime only)
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { createKVClient } from "@marianmeres/kv";
15
+ *
16
+ * // Create an in-memory client
17
+ * const client = createKVClient("myapp:", "memory");
18
+ * await client.initialize();
19
+ *
20
+ * // Basic operations
21
+ * await client.set("user:123", { name: "John" });
22
+ * const user = await client.get("user:123");
23
+ * await client.delete("user:123");
24
+ *
25
+ * // Pattern matching
26
+ * const keys = await client.keys("user:*");
27
+ * await client.clear("session:*");
28
+ *
29
+ * // Cleanup
30
+ * await client.destroy();
31
+ * ```
32
+ */
1
33
  export * from "./kv.js";
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Utility functions for the KV package.
5
+ */
1
6
  /**
2
7
  * Delays execution for `timeout` milliseconds.
3
8
  *
@@ -1,4 +1,9 @@
1
1
  // deno-lint-ignore-file no-explicit-any
2
+ /**
3
+ * @module
4
+ *
5
+ * Utility functions for the KV package.
6
+ */
2
7
  /**
3
8
  * Delays execution for `timeout` milliseconds.
4
9
  *
package/package.json CHANGED
@@ -1,25 +1,29 @@
1
1
  {
2
2
  "name": "@marianmeres/kv",
3
- "version": "1.2.2",
3
+ "version": "1.3.1",
4
4
  "type": "module",
5
5
  "main": "dist/mod.js",
6
6
  "types": "dist/mod.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/mod.d.ts",
10
+ "import": "./dist/mod.js"
11
+ }
12
+ },
7
13
  "author": "Marian Meres",
8
14
  "license": "MIT",
15
+ "dependencies": {
16
+ "@marianmeres/clog": "^3.15.0",
17
+ "@types/pg": "^8.16.0",
18
+ "@types/redis": "^4.0.10",
19
+ "pg": "^8.17.1",
20
+ "redis": "^5.10.0"
21
+ },
9
22
  "repository": {
10
23
  "type": "git",
11
24
  "url": "git+https://github.com/marianmeres/kv.git"
12
25
  },
13
26
  "bugs": {
14
27
  "url": "https://github.com/marianmeres/kv/issues"
15
- },
16
- "dependencies": {
17
- "@marianmeres/clog": "^3.2.2",
18
- "pg": "^8.16.3",
19
- "redis": "^5.10.0"
20
- },
21
- "devDependencies": {
22
- "@types/node": "latest",
23
- "@types/pg": "latest"
24
28
  }
25
29
  }