@marianmeres/kv 2.3.1 → 3.0.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
@@ -4,9 +4,10 @@ Machine-friendly reference for AI agents working with this codebase.
4
4
 
5
5
  ## Quick Reference
6
6
 
7
- - **Stack**: TypeScript, Deno (primary), Node.js (via npm build)
8
- - **Run**: `deno task test` | **Build**: `deno task npm:build`
9
- - **Version**: 2.1.0
7
+ - **Stack**: TypeScript (erasable-only), Node LTS (`.node-version`), pnpm, `node:test`, Biome.
8
+ - **Install**: `pnpm install` | **Test**: `pnpm test` (needs Postgres + Redis, see below) |
9
+ **Check all**: `pnpm run ci` | **Build**: `pnpm run build`
10
+ - **Published**: npm (`dist/`, built by `tsc`) and JSR (`src/` via `jsr.json`, for Deno consumers)
10
11
 
11
12
  ## Purpose
12
13
 
@@ -16,55 +17,68 @@ Key-value storage abstraction layer providing a unified Redis-inspired API acros
16
17
 
17
18
  ```
18
19
  src/
19
- ├── mod.ts — Main entry point (re-exports kv.ts)
20
+ ├── index.ts — The only entry point (package.json "exports", jsr.json "exports")
20
21
  ├── kv.ts — Factory function and all exports
21
22
  ├── adapter/
22
23
  │ ├── abstract.ts — Base class + shared types
23
24
  │ ├── memory.ts — In-memory adapter
24
25
  │ ├── redis.ts — Redis adapter
25
- │ ├── postgres.ts — PostgreSQL adapter
26
- │ └── deno-kv.ts — Deno KV adapter
26
+ │ └── postgres.ts — PostgreSQL adapter
27
27
  └── utils/
28
28
  └── sleep.ts — Sleep utility function
29
29
 
30
30
  tests/
31
- ├── kv.test.ts — Main test file
32
- ├── _tests-runner.ts — Test harness
31
+ ├── kv.test.ts — Main test file (node:test); every test runs against all adapters
32
+ ├── _tests-runner.ts — Test harness: builds one client per adapter per test
33
33
  ├── _redis.ts — Redis test helper
34
34
  └── _pg.ts — PostgreSQL test helper
35
+
36
+ dist/ — `tsc -p tsconfig.build.json` output; gitignored; the npm payload
35
37
  ```
36
38
 
37
39
  ## Critical Conventions
38
40
 
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`.
41
+ 1. **Runtime policy** — Node at the keyboard and in production, npm as the registry. No
42
+ `Deno.*`, `Bun.*`, `bun:*`, `jsr:` or `npm:` specifiers. Web standards first; `node:*`
43
+ where they don't reach. Nothing is built, tested or documented for Bun or Deno; JSR is
44
+ published only while Deno consumers exist (`publish:jsr` runs `test:deno` first).
45
+ 2. **Erasable TypeScript** — no `enum`, `namespace`, constructor parameter properties;
46
+ `import type` for types; explicit `.ts` import extensions (rewritten to `.js` on emit).
47
+ Node strips types and never checks them: `pnpm run typecheck` is the only type gate.
48
+ 3. **Formatting & lint** — tabs, 4 wide, 90 columns, double quotes (`biome.json`);
49
+ manifests at 2 spaces. `pnpm run format` before committing. `noExplicitAny` is off
50
+ because stored values are arbitrary JSON and `any` is public API; `noNonNullAssertion`
51
+ is off for the `db: null!` option defaults and `Map#get` after `has()`.
52
+ 4. Namespace must end with `:` or be empty string. Validated in the `AdapterAbstract`
53
+ constructor; adapters pass it via `super(namespace)`.
54
+ 5. Adapters re-declare `options` with a field initializer and merge user options again in
55
+ their own constructor (the field replaces what the base constructor set).
56
+ 6. Values are JSON-stringified internally.
57
+ 7. TTL is in seconds; stored as absolute `Date` internally.
58
+ 8. Pattern matching: Redis-style (`*` = any chars, `?` = single char). All other characters — including `.`, `(`, `[`, `%`, `_` — are matched **literally**.
59
+ 9. TTL resolution: `options.ttl ?? defaultTtl`; `0` or negative disables expiration for that call (explicitly overrides `defaultTtl`).
60
+ 10. All pattern-to-regex / pattern-to-LIKE conversion lives in `abstract.ts` — use `_globToRegex()`, `_resolveTtl()`, `_normalizePairs()`; do not re-implement per-adapter.
61
+ 11. Postgres `transaction()` must pin a single connection via `pool.connect()`; every nested query uses that client, not `this.options.db`.
62
+ 12. Redis adapter owns the connection iff `initialize()` opened it (`#weOpened` flag).
63
+ 13. Key validation lives in `_withNs()` — enforced when `options.validateKeys !== false`. Reject empty strings, keys with `\0`, and total `namespace + key` length > 512.
64
+ 14. `ttl()` returns `TtlResult = { state: "missing" | "no-ttl" | "expires"; at? }` — discriminated union, not `Date | null | false`.
65
+ 15. `incr`/`decr`/`getSet`/`cas`/`setIfAbsent` must be atomic: Redis = Lua or NX; Postgres = UPSERT/UPDATE with RETURNING; Memory = plain read-modify-write (single-threaded).
66
+ 16. Non-numeric `incr`/`decr` target throws `TypeError("KV value is not a number")`. In Postgres, detect via error code `22P02`.
67
+ 17. `keysIter` must clean up on early consumer break — PG releases its server-side cursor in the generator's `finally`.
53
68
 
54
69
  ## Before Making Changes
55
70
 
56
71
  - [ ] Check existing patterns in adapter implementations
57
- - [ ] Run tests: `deno test --unstable-kv -A --env-file`
58
- - [ ] Verify adapter limitations are documented
72
+ - [ ] Add or extend a test in `tests/kv.test.ts`, then run `pnpm run ci`
73
+ - [ ] Verify adapter limitations are documented (README feature matrix, API.md)
59
74
 
60
75
  ## Supported Adapters
61
76
 
62
- | Adapter | Type String | Required Options | Limitations |
63
- |---------|-------------|------------------|-------------|
64
- | Memory | `"memory"` | None | Not persisted |
65
- | Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
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 |
77
+ | Adapter | Type String | Required Options | Limitations |
78
+ | ---------- | ------------ | --------------------- | ------------------------------------------------------------------ |
79
+ | Memory | `"memory"` | None | Not persisted |
80
+ | Redis | `"redis"` | `db` (Redis client) | Namespace required; `keys()`/`clear()` unavailable in cluster mode |
81
+ | PostgreSQL | `"postgres"` | `db` (pg.Pool/Client) | `tableName` limited to `[A-Za-z0-9_]` + optional `schema.` prefix |
68
82
 
69
83
  ## Core API
70
84
 
@@ -111,58 +125,75 @@ ttl(key): Promise<TtlResult>
111
125
  ## Key Types
112
126
 
113
127
  ```typescript
114
- interface SetOptions { ttl: number }
115
- interface AdapterInfo { type: string }
116
- interface AdapterAbstractOptions { defaultTtl: number; logger?: Logger; validateKeys?: boolean }
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 };
128
+ interface SetOptions {
129
+ ttl: number;
130
+ }
131
+ interface AdapterInfo {
132
+ type: string;
133
+ }
134
+ interface AdapterAbstractOptions {
135
+ defaultTtl: number;
136
+ logger?: Logger;
137
+ validateKeys?: boolean;
138
+ }
139
+ interface Operation {
140
+ type: "set" | "get" | "delete";
141
+ key: string;
142
+ value?: any;
143
+ options?: SetOptions;
144
+ }
145
+
146
+ type SetMultipleEntry = [string, any] | { key: string; value: any; ttl?: number };
122
147
 
123
148
  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
149
+ | { state: "missing" }
150
+ | { state: "no-ttl" }
151
+ | { state: "expires"; at: Date };
129
152
  ```
130
153
 
131
154
  ## Commands
132
155
 
133
156
  ```bash
134
- # Run tests (requires --unstable-kv for Deno KV)
135
- deno test --unstable-kv -A --env-file
136
-
137
- # Run tests with watch mode
138
- deno test --unstable-kv -A --env-file --watch
139
-
140
- # Build npm package
141
- deno run -A scripts/build-npm.ts
157
+ pnpm test # node --test over tests/**/*.test.ts, loads .env if present
158
+ pnpm run test:watch
159
+ pnpm run typecheck # tsc --noEmit
160
+ pnpm run lint # biome check . (read-only); `pnpm run format` writes
161
+ pnpm run ci # typecheck + lint + test — what CI runs
162
+ pnpm run build # tsc -p tsconfig.build.json → dist/
163
+ pnpm run test:deno # the same suite on Deno; only gates publish:jsr
142
164
  ```
143
165
 
166
+ Releasing (`pnpm run rp` / `rpm`, or `pnpm run release major` + `pnpm run publish:all`) is a
167
+ human action.
168
+
144
169
  ## Test Environment Variables
145
170
 
171
+ Every test runs against all three adapters, so tests need a live Postgres and Redis. Put
172
+ these in `.env` (see `.env.example`); CI provides them via service containers
173
+ (`.github/workflows/ci.yml`). The harness deletes **every key** in the Redis DB before each
174
+ test — use a scratch DB.
175
+
146
176
  ```
147
177
  TEST_PG_HOST=localhost
148
178
  TEST_PG_PORT=5432
149
179
  TEST_PG_DATABASE=<required>
150
180
  TEST_PG_USER=<required>
151
181
  TEST_PG_PASSWORD=<required>
152
- TEST_REDIS_URL=redis://localhost:6379
182
+ TEST_REDIS_URL=redis://localhost:6379/13
153
183
  ```
154
184
 
155
185
  ## Extending
156
186
 
157
187
  To add a new adapter:
158
188
  1. Create `src/adapter/<name>.ts`
159
- 2. Extend `AdapterAbstract`
189
+ 2. Extend `AdapterAbstract`; call `super(namespace)` and re-merge `options` (convention 5)
160
190
  3. Implement all abstract/interface methods
161
191
  4. Add to `KnownTypes` in `src/kv.ts`
162
192
  5. Add case in `createKVClient` factory
163
193
  6. Export from `src/kv.ts`
194
+ 7. Add a client for it in `tests/_tests-runner.ts`; it must run on Node
164
195
 
165
196
  ## Documentation Index
166
197
 
167
198
  - [API Reference](./API.md) — Complete API documentation
168
- - [README](./README.md) — Quick start and installation
199
+ - [README](./README.md) — Quick start, feature matrix, breaking changes, development