@jini-ai/capability-providers 0.1.2 → 0.4.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +174 -0
  3. package/dist/adapters/blob-storage/index.d.ts +67 -0
  4. package/dist/adapters/blob-storage/index.js +62 -0
  5. package/dist/adapters/jwt-auth/index.d.ts +53 -0
  6. package/dist/adapters/jwt-auth/index.js +182 -0
  7. package/dist/adapters/sqlite/index.d.ts +56 -0
  8. package/dist/adapters/sqlite/index.js +83 -0
  9. package/dist/adapters/stripe/index.d.ts +94 -0
  10. package/dist/adapters/stripe/index.js +167 -0
  11. package/dist/adapters/ws/index.d.ts +95 -0
  12. package/dist/adapters/ws/index.js +161 -0
  13. package/dist/auth.d.ts +22 -47
  14. package/dist/auth.js +10 -173
  15. package/dist/db.d.ts +11 -48
  16. package/dist/db.js +15 -79
  17. package/dist/index.d.ts +54 -1
  18. package/dist/index.js +54 -1
  19. package/dist/payments.d.ts +21 -74
  20. package/dist/payments.js +13 -175
  21. package/dist/realtime.d.ts +24 -73
  22. package/dist/realtime.js +14 -140
  23. package/dist/storage.d.ts +23 -49
  24. package/dist/storage.js +13 -57
  25. package/dist/tokens.js +6 -6
  26. package/dist/unsafe-reference/auth.d.ts +1 -1
  27. package/dist/unsafe-reference/auth.js +3 -3
  28. package/dist/unsafe-reference/db.d.ts +2 -2
  29. package/dist/unsafe-reference/index.d.ts +1 -1
  30. package/dist/unsafe-reference/index.js +1 -1
  31. package/dist/unsafe-reference/payments.d.ts +3 -1
  32. package/dist/unsafe-reference/payments.js +6 -5
  33. package/dist/unsafe-reference/realtime.d.ts +1 -1
  34. package/dist/unsafe-reference/realtime.js +4 -4
  35. package/dist/unsafe-reference/storage.d.ts +3 -1
  36. package/dist/unsafe-reference/storage.js +7 -6
  37. package/dist/visitor-auth/definitions.d.ts +32 -0
  38. package/dist/visitor-auth/definitions.js +57 -0
  39. package/dist/visitor-auth/index.d.ts +17 -0
  40. package/dist/visitor-auth/index.js +17 -0
  41. package/dist/visitor-auth/lifecycle.d.ts +101 -0
  42. package/dist/visitor-auth/lifecycle.js +326 -0
  43. package/dist/visitor-auth/ports.d.ts +134 -0
  44. package/dist/visitor-auth/ports.js +2 -0
  45. package/dist/visitor-auth/registry.d.ts +38 -0
  46. package/dist/visitor-auth/registry.js +78 -0
  47. package/dist/visitor-auth/tokens.d.ts +10 -0
  48. package/dist/visitor-auth/tokens.js +9 -0
  49. package/package.json +66 -9
  50. package/dist/auth.d.ts.map +0 -1
  51. package/dist/auth.js.map +0 -1
  52. package/dist/db.d.ts.map +0 -1
  53. package/dist/db.js.map +0 -1
  54. package/dist/index.d.ts.map +0 -1
  55. package/dist/index.js.map +0 -1
  56. package/dist/payments.d.ts.map +0 -1
  57. package/dist/payments.js.map +0 -1
  58. package/dist/realtime.d.ts.map +0 -1
  59. package/dist/realtime.js.map +0 -1
  60. package/dist/storage.d.ts.map +0 -1
  61. package/dist/storage.js.map +0 -1
  62. package/dist/tokens.d.ts.map +0 -1
  63. package/dist/tokens.js.map +0 -1
  64. package/dist/unsafe-reference/auth.d.ts.map +0 -1
  65. package/dist/unsafe-reference/auth.js.map +0 -1
  66. package/dist/unsafe-reference/db.d.ts.map +0 -1
  67. package/dist/unsafe-reference/db.js.map +0 -1
  68. package/dist/unsafe-reference/index.d.ts.map +0 -1
  69. package/dist/unsafe-reference/index.js.map +0 -1
  70. package/dist/unsafe-reference/payments.d.ts.map +0 -1
  71. package/dist/unsafe-reference/payments.js.map +0 -1
  72. package/dist/unsafe-reference/realtime.d.ts.map +0 -1
  73. package/dist/unsafe-reference/realtime.js.map +0 -1
  74. package/dist/unsafe-reference/storage.d.ts.map +0 -1
  75. package/dist/unsafe-reference/storage.js.map +0 -1
package/dist/auth.d.ts CHANGED
@@ -1,3 +1,19 @@
1
+ /**
2
+ * `AuthProvider` — a swappable identity/session port. Speculative
3
+ * port-design exploration (see `archived provenance ledger`): Zana and a fleet orchestrator each
4
+ * independently built an explicit capability-provider layer with auth as one
5
+ * of the swappable capabilities (Supabase/sqlite-backed) — this is the
6
+ * engine-level shape that convergence points at, not a lift from either.
7
+ *
8
+ * This file defines the port's stable interface/type surface and nothing else —
9
+ * it has no imports at all, so a consumer implementing `AuthProvider`
10
+ * themselves installs nothing. The one real, production-quality adapter
11
+ * (`JwtAuthProvider`, self-contained HS256 JWT sessions over `node:crypto`)
12
+ * lives at the separate `@jini-ai/capability-providers/adapters/jwt-auth`
13
+ * entry point; the non-production in-memory reference stub
14
+ * (`createInMemoryAuthProvider`) lives under `src/unsafe-reference/`,
15
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
16
+ */
1
17
  export interface AuthCredentials {
2
18
  readonly email: string;
3
19
  readonly password: string;
@@ -18,53 +34,12 @@ export interface AuthProvider {
18
34
  /** Exchanges valid credentials for a new session. Rejects on an unknown email or wrong password. */
19
35
  signIn(credentials: AuthCredentials): Promise<AuthSession>;
20
36
  /** Invalidates a session token. A no-op on an already-invalid/unknown token. */
21
- signOut(token: string): Promise<void>;
37
+ signOut(required: {
38
+ token: string;
39
+ }): Promise<void>;
22
40
  /** Resolves a session token to its user, or `null` if the token is unknown, invalidated, or expired. */
23
- verifySession(token: string): Promise<AuthUser | null>;
24
- }
25
- export interface JwtAuthProviderOptions {
26
- /** HMAC-SHA256 signing secret for session tokens. Required and explicit — never read from an environment variable inside this adapter. */
27
- readonly secret: string;
28
- /** Session lifetime in ms. Defaults to 1 hour, matching the in-memory reference adapter's default. */
29
- readonly sessionTtlMs?: number;
30
- /** Injectable clock for deterministic tests; defaults to `Date.now`. */
31
- readonly now?: () => number;
32
- }
33
- /**
34
- * `AuthProvider` adapter using self-signed HS256 JWTs as session tokens — no external
35
- * auth-service dependency (no Auth0/Clerk/Supabase Auth call), just `node:crypto` and a
36
- * host-supplied `secret`. Real password hashing (`scrypt` + per-user random salt +
37
- * constant-time comparison), unlike the in-memory reference adapter's plaintext storage.
38
- *
39
- * Two deliberate, documented scope limits:
40
- *
41
- * 1. **User storage is in-process memory, not durable.** `AuthProvider`'s interface has no
42
- * concept of user persistence beyond what `signUp`/`signIn`/`verifySession` need — pair this
43
- * with `SqliteDbProvider`/`BlobStorageProvider` at the binding site (per `source-map.md`'s
44
- * "composition happens at the binding site, not in this package" design decision) if a host
45
- * needs users to survive a process restart. A session JWT signed by one `JwtAuthProvider`
46
- * instance verifies its *signature* successfully against any instance sharing the same
47
- * `secret` (including a fresh instance after a restart), but `verifySession` still returns
48
- * `null` for it once the signing instance's in-memory `usersById` no longer has that user —
49
- * tested explicitly below.
50
- * 2. **Revocation is an in-memory deny-list, not a JWT property.** JWTs are stateless by design;
51
- * `signOut` records the session's `jti` in a process-local `Set` so `verifySession` can reject
52
- * it before expiry. Like (1), this deny-list does not survive a process restart — a signed-out
53
- * token is memory-safe under normal operation but session revocation is not honored across a
54
- * restart of the process holding the deny-list.
55
- */
56
- export declare class JwtAuthProvider implements AuthProvider {
57
- private readonly secret;
58
- private readonly sessionTtlMs;
59
- private readonly now;
60
- private readonly usersByEmail;
61
- private readonly usersById;
62
- private readonly revokedJti;
63
- private nextId;
64
- constructor(options: JwtAuthProviderOptions);
65
- signUp(credentials: AuthCredentials): Promise<AuthUser>;
66
- signIn(credentials: AuthCredentials): Promise<AuthSession>;
67
- signOut(token: string): Promise<void>;
68
- verifySession(token: string): Promise<AuthUser | null>;
41
+ verifySession(required: {
42
+ token: string;
43
+ }): Promise<AuthUser | null>;
69
44
  }
70
45
  //# sourceMappingURL=auth.d.ts.map
package/dist/auth.js CHANGED
@@ -1,181 +1,18 @@
1
1
  /**
2
2
  * `AuthProvider` — a swappable identity/session port. Speculative
3
- * port-design exploration (see `source-map.md`): Zana and Tovu-Runner each
3
+ * port-design exploration (see `archived provenance ledger`): Zana and a fleet orchestrator each
4
4
  * independently built an explicit capability-provider layer with auth as one
5
5
  * of the swappable capabilities (Supabase/sqlite-backed) — this is the
6
6
  * engine-level shape that convergence points at, not a lift from either.
7
7
  *
8
- * This file defines the port's stable interface/type surface, plus one real,
9
- * production-quality adapter (`JwtAuthProvider`, added 2026-07-21 — see
10
- * `source-map.md`'s dated section): self-contained HS256 JWT session tokens
11
- * signed with a host-supplied secret, `node:crypto` `scrypt` password
12
- * hashing, no external auth-service dependency. The in-memory reference
13
- * implementation (`createInMemoryAuthProvider`) is a separate, non-production
14
- * stub that lives under `src/unsafe-reference/`, exported only from the
15
- * separate `@jini-ai/capability-providers/unsafe-reference` entry point — see
16
- * that directory's `index.ts` header for the full warning.
8
+ * This file defines the port's stable interface/type surface and nothing else —
9
+ * it has no imports at all, so a consumer implementing `AuthProvider`
10
+ * themselves installs nothing. The one real, production-quality adapter
11
+ * (`JwtAuthProvider`, self-contained HS256 JWT sessions over `node:crypto`)
12
+ * lives at the separate `@jini-ai/capability-providers/adapters/jwt-auth`
13
+ * entry point; the non-production in-memory reference stub
14
+ * (`createInMemoryAuthProvider`) lives under `src/unsafe-reference/`,
15
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
17
16
  */
18
- import { createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
19
- const SCRYPT_KEYLEN = 64;
20
- const SCRYPT_SALT_BYTES = 16;
21
- const DEFAULT_SESSION_TTL_MS = 60 * 60 * 1000;
22
- function base64url(input) {
23
- return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
24
- }
25
- function base64urlToBuffer(input) {
26
- const padded = input.replace(/-/g, '+').replace(/_/g, '/');
27
- const padLength = padded.length % 4 === 0 ? 0 : 4 - (padded.length % 4);
28
- return Buffer.from(padded + '='.repeat(padLength), 'base64');
29
- }
30
- /** Hashes `password` with `scrypt` under a fresh random salt, returned as a `<saltHex>:<hashHex>` string. */
31
- function hashPassword(password) {
32
- const salt = randomBytes(SCRYPT_SALT_BYTES);
33
- const hash = scryptSync(password, salt, SCRYPT_KEYLEN);
34
- return `${salt.toString('hex')}:${hash.toString('hex')}`;
35
- }
36
- /**
37
- * Verifies `password` against a `<saltHex>:<hashHex>` string previously produced by
38
- * {@link hashPassword}. `stored` is always this class's own `hashPassword` output — nothing
39
- * external ever writes to a user's `passwordHash` field — so both halves are trusted to be
40
- * well-formed hex by construction; no defensive "malformed stored hash" branch is needed (there
41
- * is no real caller path that could exercise one).
42
- */
43
- function verifyPassword(password, stored) {
44
- const separatorIndex = stored.indexOf(':');
45
- const salt = Buffer.from(stored.slice(0, separatorIndex), 'hex');
46
- const expected = Buffer.from(stored.slice(separatorIndex + 1), 'hex');
47
- const actual = scryptSync(password, salt, SCRYPT_KEYLEN);
48
- return timingSafeEqual(actual, expected);
49
- }
50
- /** Signs `payload` as an HS256 JWT (`base64url(header).base64url(payload).base64url(hmacSha256Signature)`). */
51
- function signSessionJwt(payload, secret) {
52
- const header = { alg: 'HS256', typ: 'JWT' };
53
- const signingInput = `${base64url(Buffer.from(JSON.stringify(header)))}.${base64url(Buffer.from(JSON.stringify(payload)))}`;
54
- const signature = base64url(createHmac('sha256', secret).update(signingInput).digest());
55
- return `${signingInput}.${signature}`;
56
- }
57
- /**
58
- * Verifies an HS256 session JWT's signature and claim shape against `secret`. Deliberately does
59
- * NOT check expiry or revocation — those are session-store concerns (`revokedJti`, `now()`) that
60
- * `JwtAuthProvider.verifySession` layers on top, so this stays a pure "is this token
61
- * authentically signed and well-formed" check reusable by both `verifySession` and `signOut`.
62
- */
63
- function verifySessionJwt(token, secret) {
64
- const parts = token.split('.');
65
- if (parts.length !== 3)
66
- return { ok: false };
67
- // Array destructuring can't narrow past noUncheckedIndexedAccess; the length check above
68
- // guarantees all three are real strings, not undefined.
69
- const headerPart = parts[0];
70
- const payloadPart = parts[1];
71
- const signaturePart = parts[2];
72
- const expectedSignature = createHmac('sha256', secret).update(`${headerPart}.${payloadPart}`).digest();
73
- const actualSignature = base64urlToBuffer(signaturePart);
74
- if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) {
75
- return { ok: false };
76
- }
77
- let parsed;
78
- try {
79
- parsed = JSON.parse(base64urlToBuffer(payloadPart).toString('utf8'));
80
- }
81
- catch {
82
- return { ok: false };
83
- }
84
- if (!parsed ||
85
- typeof parsed !== 'object' ||
86
- typeof parsed.sub !== 'string' ||
87
- typeof parsed.jti !== 'string' ||
88
- typeof parsed.exp !== 'number') {
89
- return { ok: false };
90
- }
91
- return { ok: true, payload: parsed };
92
- }
93
- /**
94
- * `AuthProvider` adapter using self-signed HS256 JWTs as session tokens — no external
95
- * auth-service dependency (no Auth0/Clerk/Supabase Auth call), just `node:crypto` and a
96
- * host-supplied `secret`. Real password hashing (`scrypt` + per-user random salt +
97
- * constant-time comparison), unlike the in-memory reference adapter's plaintext storage.
98
- *
99
- * Two deliberate, documented scope limits:
100
- *
101
- * 1. **User storage is in-process memory, not durable.** `AuthProvider`'s interface has no
102
- * concept of user persistence beyond what `signUp`/`signIn`/`verifySession` need — pair this
103
- * with `SqliteDbProvider`/`BlobStorageProvider` at the binding site (per `source-map.md`'s
104
- * "composition happens at the binding site, not in this package" design decision) if a host
105
- * needs users to survive a process restart. A session JWT signed by one `JwtAuthProvider`
106
- * instance verifies its *signature* successfully against any instance sharing the same
107
- * `secret` (including a fresh instance after a restart), but `verifySession` still returns
108
- * `null` for it once the signing instance's in-memory `usersById` no longer has that user —
109
- * tested explicitly below.
110
- * 2. **Revocation is an in-memory deny-list, not a JWT property.** JWTs are stateless by design;
111
- * `signOut` records the session's `jti` in a process-local `Set` so `verifySession` can reject
112
- * it before expiry. Like (1), this deny-list does not survive a process restart — a signed-out
113
- * token is memory-safe under normal operation but session revocation is not honored across a
114
- * restart of the process holding the deny-list.
115
- */
116
- export class JwtAuthProvider {
117
- secret;
118
- sessionTtlMs;
119
- now;
120
- usersByEmail = new Map();
121
- usersById = new Map();
122
- revokedJti = new Set();
123
- nextId = 1;
124
- constructor(options) {
125
- if (!options.secret) {
126
- throw new Error('JwtAuthProvider requires a non-empty options.secret');
127
- }
128
- this.secret = options.secret;
129
- this.sessionTtlMs = options.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS;
130
- this.now = options.now ?? Date.now;
131
- }
132
- async signUp(credentials) {
133
- if (this.usersByEmail.has(credentials.email)) {
134
- throw new Error(`email already registered: ${credentials.email}`);
135
- }
136
- const user = {
137
- id: `user-${this.nextId++}`,
138
- email: credentials.email,
139
- createdAt: this.now(),
140
- passwordHash: hashPassword(credentials.password),
141
- };
142
- this.usersByEmail.set(credentials.email, user);
143
- this.usersById.set(user.id, user);
144
- return { id: user.id, email: user.email, createdAt: user.createdAt };
145
- }
146
- async signIn(credentials) {
147
- const user = this.usersByEmail.get(credentials.email);
148
- if (!user || !verifyPassword(credentials.password, user.passwordHash)) {
149
- throw new Error('invalid email or password');
150
- }
151
- const nowMs = this.now();
152
- const expiresAt = nowMs + this.sessionTtlMs;
153
- const token = signSessionJwt({
154
- sub: user.id,
155
- jti: randomBytes(16).toString('hex'),
156
- iat: Math.floor(nowMs / 1000),
157
- exp: Math.floor(expiresAt / 1000),
158
- }, this.secret);
159
- return { token, userId: user.id, expiresAt };
160
- }
161
- async signOut(token) {
162
- const result = verifySessionJwt(token, this.secret);
163
- if (result.ok) {
164
- this.revokedJti.add(result.payload.jti);
165
- }
166
- }
167
- async verifySession(token) {
168
- const result = verifySessionJwt(token, this.secret);
169
- if (!result.ok)
170
- return null;
171
- if (this.revokedJti.has(result.payload.jti))
172
- return null;
173
- if (result.payload.exp * 1000 <= this.now())
174
- return null;
175
- const user = this.usersById.get(result.payload.sub);
176
- if (!user)
177
- return null;
178
- return { id: user.id, email: user.email, createdAt: user.createdAt };
179
- }
180
- }
17
+ export {};
181
18
  //# sourceMappingURL=auth.js.map
package/dist/db.d.ts CHANGED
@@ -1,24 +1,20 @@
1
1
  /**
2
2
  * `DbProvider` — a swappable, minimal document-store port (collection +
3
3
  * record id, not a query language). Speculative port-design exploration
4
- * (see `source-map.md`) — no OD source; the capability
5
- * `foundry/docs/jini-port/recon/r5b-consumers-matrix.md` §3.3 names as the one Zana
6
- * (Supabase→db+auth+storage+realtime) and Tovu-Runner (ports+sqlite/memory)
4
+ * (see `archived provenance ledger`) — no OD source; the capability
5
+ * `ADS-memory/reports/jini-port/recon/r5b-consumers-matrix.md` §3.3 names as the one Zana
6
+ * (Supabase→db+auth+storage+realtime) and a fleet orchestrator (ports+sqlite/memory)
7
7
  * both built explicitly.
8
8
  *
9
- * This file defines the port's stable interface/type surface, plus one real,
10
- * production-quality adapter (`SqliteDbProvider`, added 2026-07-21 — see
11
- * `source-map.md`'s dated section) backed directly by `better-sqlite3` — the
12
- * same driver `@jini-ai/sqlite`'s `createSqliteEventLog` uses, following that
13
- * module's DI/schema conventions (an injected, already-open `Database`
14
- * handle; idempotent `CREATE TABLE IF NOT EXISTS`; multi-statement writes
15
- * wrapped in `db.transaction()`). The in-memory reference implementation
16
- * (`createInMemoryDbProvider`) is a separate, non-production stub that lives
17
- * under `src/unsafe-reference/`, exported only from the separate
18
- * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
19
- * directory's `index.ts` header for the full warning.
9
+ * This file defines the port's stable interface/type surface and nothing else —
10
+ * it has no imports at all, so a consumer implementing `DbProvider` themselves
11
+ * installs nothing. The one real, production-quality adapter
12
+ * (`SqliteDbProvider`, backed by `better-sqlite3`) lives at the separate
13
+ * `@jini-ai/capability-providers/adapters/sqlite` entry point; the
14
+ * non-production in-memory reference stub (`createInMemoryDbProvider`) lives
15
+ * under `src/unsafe-reference/`, exported only from
16
+ * `@jini-ai/capability-providers/unsafe-reference`.
20
17
  */
21
- import type Database from 'better-sqlite3';
22
18
  export interface DbRecord {
23
19
  readonly id: string;
24
20
  readonly [field: string]: unknown;
@@ -39,37 +35,4 @@ export interface DbProvider {
39
35
  /** Returns every record in `collection` matching `query.where` (all records when `query` is omitted). */
40
36
  query(collection: string, query?: DbQuery): Promise<DbRecord[]>;
41
37
  }
42
- /** Alias for a `better-sqlite3` `Database` handle, matching `@jini-ai/sqlite`'s own `SqliteDb` alias (`packages/sqlite/src/db/core/types.ts`). */
43
- type SqliteDatabase = Database.Database;
44
- /**
45
- * `DbProvider` adapter backed by an injected, already-open `better-sqlite3` `Database` handle.
46
- * Every collection's records live in one physical table (`collection`, `id`, JSON-serialized
47
- * `data`), primary-keyed on `(collection, id)`; `query()`'s exact-match `where` filter is applied
48
- * client-side over every row in the collection after a plain `SELECT ... WHERE collection = ?` —
49
- * deliberately not compiled to SQL predicates, matching `DbQuery`'s own "not a query language"
50
- * framing and the in-memory reference adapter's identical semantics, so behavior is identical
51
- * between the two adapters for every input.
52
- *
53
- * Callers own the `Database` handle's lifecycle (open/close, WAL mode, file path or `:memory:`)
54
- * — this class only creates its own table on construction (`CREATE TABLE IF NOT EXISTS`, safe to
55
- * re-run against an already-migrated handle) and never opens or closes a connection itself,
56
- * mirroring `createSqliteEventLog`'s "pass `':memory:'` for a non-durable in-process database"
57
- * convention for tests.
58
- */
59
- export declare class SqliteDbProvider implements DbProvider {
60
- private readonly getStmt;
61
- private readonly insertStmt;
62
- private readonly updateStmt;
63
- private readonly deleteStmt;
64
- private readonly queryStmt;
65
- private readonly insertTxn;
66
- private readonly updateTxn;
67
- constructor(db: SqliteDatabase);
68
- insert(collection: string, record: DbRecord): Promise<DbRecord>;
69
- get(collection: string, id: string): Promise<DbRecord | null>;
70
- update(collection: string, id: string, patch: Readonly<Record<string, unknown>>): Promise<DbRecord | null>;
71
- delete(collection: string, id: string): Promise<void>;
72
- query(collection: string, query?: DbQuery): Promise<DbRecord[]>;
73
- }
74
- export {};
75
38
  //# sourceMappingURL=db.d.ts.map
package/dist/db.js CHANGED
@@ -1,83 +1,19 @@
1
- /** Exact-match filter used by both `query()` here and the in-memory reference adapter's own `matchesWhere` — kept as an independent, self-contained copy rather than a shared import so this adapter has no dependency on `src/unsafe-reference/`. */
2
- function matchesWhere(record, where) {
3
- if (!where)
4
- return true;
5
- return Object.entries(where).every(([key, value]) => record[key] === value);
6
- }
7
1
  /**
8
- * `DbProvider` adapter backed by an injected, already-open `better-sqlite3` `Database` handle.
9
- * Every collection's records live in one physical table (`collection`, `id`, JSON-serialized
10
- * `data`), primary-keyed on `(collection, id)`; `query()`'s exact-match `where` filter is applied
11
- * client-side over every row in the collection after a plain `SELECT ... WHERE collection = ?` —
12
- * deliberately not compiled to SQL predicates, matching `DbQuery`'s own "not a query language"
13
- * framing and the in-memory reference adapter's identical semantics, so behavior is identical
14
- * between the two adapters for every input.
2
+ * `DbProvider` — a swappable, minimal document-store port (collection +
3
+ * record id, not a query language). Speculative port-design exploration
4
+ * (see `archived provenance ledger`) — no OD source; the capability
5
+ * `ADS-memory/reports/jini-port/recon/r5b-consumers-matrix.md` §3.3 names as the one Zana
6
+ * (Supabase→db+auth+storage+realtime) and a fleet orchestrator (ports+sqlite/memory)
7
+ * both built explicitly.
15
8
  *
16
- * Callers own the `Database` handle's lifecycle (open/close, WAL mode, file path or `:memory:`)
17
- * — this class only creates its own table on construction (`CREATE TABLE IF NOT EXISTS`, safe to
18
- * re-run against an already-migrated handle) and never opens or closes a connection itself,
19
- * mirroring `createSqliteEventLog`'s "pass `':memory:'` for a non-durable in-process database"
20
- * convention for tests.
9
+ * This file defines the port's stable interface/type surface and nothing else —
10
+ * it has no imports at all, so a consumer implementing `DbProvider` themselves
11
+ * installs nothing. The one real, production-quality adapter
12
+ * (`SqliteDbProvider`, backed by `better-sqlite3`) lives at the separate
13
+ * `@jini-ai/capability-providers/adapters/sqlite` entry point; the
14
+ * non-production in-memory reference stub (`createInMemoryDbProvider`) lives
15
+ * under `src/unsafe-reference/`, exported only from
16
+ * `@jini-ai/capability-providers/unsafe-reference`.
21
17
  */
22
- export class SqliteDbProvider {
23
- getStmt;
24
- insertStmt;
25
- updateStmt;
26
- deleteStmt;
27
- queryStmt;
28
- insertTxn;
29
- updateTxn;
30
- constructor(db) {
31
- db.exec(`
32
- CREATE TABLE IF NOT EXISTS jini_capability_db_records (
33
- collection TEXT NOT NULL,
34
- id TEXT NOT NULL,
35
- data TEXT NOT NULL,
36
- PRIMARY KEY (collection, id)
37
- );
38
- `);
39
- this.getStmt = db.prepare('SELECT collection, id, data FROM jini_capability_db_records WHERE collection = ? AND id = ?');
40
- this.insertStmt = db.prepare('INSERT INTO jini_capability_db_records (collection, id, data) VALUES (?, ?, ?)');
41
- this.updateStmt = db.prepare('UPDATE jini_capability_db_records SET data = ? WHERE collection = ? AND id = ?');
42
- this.deleteStmt = db.prepare('DELETE FROM jini_capability_db_records WHERE collection = ? AND id = ?');
43
- this.queryStmt = db.prepare('SELECT collection, id, data FROM jini_capability_db_records WHERE collection = ?');
44
- // Wrapped in db.transaction() for the same reason createSqliteEventLog wraps its
45
- // dedupe-check + insert: a single atomic unit of work at the SQL level, not a JS-level race
46
- // guard (better-sqlite3 is synchronous, so no other JS can run between the get() and run()
47
- // calls within one process either way).
48
- this.insertTxn = db.transaction((collection, record) => {
49
- const existing = this.getStmt.get(collection, record.id);
50
- if (existing) {
51
- throw new Error(`record already exists: ${collection}/${record.id}`);
52
- }
53
- this.insertStmt.run(collection, record.id, JSON.stringify(record));
54
- return record;
55
- });
56
- this.updateTxn = db.transaction((collection, id, patch) => {
57
- const row = this.getStmt.get(collection, id);
58
- if (!row)
59
- return null;
60
- const updated = { ...JSON.parse(row.data), ...patch, id };
61
- this.updateStmt.run(JSON.stringify(updated), collection, id);
62
- return updated;
63
- });
64
- }
65
- async insert(collection, record) {
66
- return this.insertTxn(collection, record);
67
- }
68
- async get(collection, id) {
69
- const row = this.getStmt.get(collection, id);
70
- return row ? JSON.parse(row.data) : null;
71
- }
72
- async update(collection, id, patch) {
73
- return this.updateTxn(collection, id, patch);
74
- }
75
- async delete(collection, id) {
76
- this.deleteStmt.run(collection, id);
77
- }
78
- async query(collection, query = {}) {
79
- const rows = this.queryStmt.all(collection);
80
- return rows.map((row) => JSON.parse(row.data)).filter((record) => matchesWhere(record, query.where));
81
- }
82
- }
18
+ export {};
83
19
  //# sourceMappingURL=db.js.map
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * `@jini-ai/capability-providers` — abstract, swappable capability-provider
3
3
  * ports (auth/storage/payments/db/realtime): stable interfaces and typed DI
4
4
  * tokens only. Speculative port-design exploration, built with no current
5
- * consumer — see `source-map.md` for the full scope note and sign-off
5
+ * consumer — see `archived provenance ledger` for the full scope note and sign-off
6
6
  * status.
7
7
  *
8
8
  * This entry point intentionally does NOT export any concrete
@@ -12,6 +12,59 @@
12
12
  * `src/unsafe-reference/` and are exported only from the separate
13
13
  * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
14
14
  * directory's `index.ts` header before importing anything from it.
15
+
16
+ * Archived provenance rationale:
17
+ * ## Why this exists (the gap it names)
18
+ *
19
+ * `ADS-memory/reports/jini-port/recon/r5b-consumers-matrix.md` §2 (the capability matrix) and
20
+ * §3.3 identify a **capability-provider registry with auth / storage /
21
+ * payments / db / realtime as Zana + a fleet orchestrator convergent** — both consumers
22
+ * independently built an explicit port+provider layer (Zana: `app-chassis`'s
23
+ * "rigid core, flexible edges" thesis, `packages/{core,ai,db,auth,storage,
24
+ * payments}` + `providers/supabase` declaring which capabilities it
25
+ * implements; the fleet orchestrator: "ports+sqlite/memory"), while Open Design itself
26
+ * only models these capabilities thinly. §3.3 states this "should be an engine
27
+ * primitive... so products swap Supabase/SQLite/Stripe without touching core"
28
+ * — that is the shape this package builds: 5 independent ports (not one
29
+ * umbrella "CapabilityProvider" interface — see "Design decisions" below) each
30
+ * with a typed DI token (`packages/core/src/token.ts`'s pattern) and a minimal
31
+ * in-memory reference implementation proving the port is genuinely
32
+ * implementable.
33
+ *
34
+ * ## Design decisions
35
+ *
36
+ * **Five separate port interfaces, not one `CapabilityProvider` union.** Zana's
37
+ * own model has a single adapter (Supabase) implementing multiple capabilities
38
+ * at once, which might suggest one umbrella interface with optional methods.
39
+ * Rejected: extraction-plan.md §2.2's core lesson (the reason typed tokens beat
40
+ * a structural dependency object in the first place) is that a union/bag
41
+ * interface is exactly the shape that decays into an OD-`ServerContext`-style
42
+ * god-object as capabilities accrete. Five independently bindable tokens means
43
+ * a consumer wiring only `DbProviderToken` + `StorageProviderToken` never sees
44
+ * `AuthProvider`/`PaymentsProvider`/`RealtimeProvider` in its type surface. A
45
+ * real adapter that happens to implement several (a future `SupabaseAdapter`)
46
+ * is free to be one class satisfying multiple interfaces and bound to multiple
47
+ * tokens — that composition happens at the binding site, not in this package.
48
+ *
49
+ * **No registry/discovery module.** The task brief's scope constraint says
50
+ * "abstract port/interface definitions... plus at minimum one trivial
51
+ * reference/stub implementation" and explicitly forbids wiring this into any
52
+ * other package. `@jini/core`'s existing typed-token + `bindings()` mechanism
53
+ * already *is* the registration/discovery layer (extraction-plan.md §2.2) —
54
+ * building a second, parallel registry inside this package would duplicate
55
+ * that machinery for no reason and blur the "zero other package depends on
56
+ * this" boundary the brief asked for. A consumer registers these tokens in its
57
+ * own `createDaemon({ bindings: bindings().bind(AuthProviderToken, ...) })`
58
+ * call; this package supplies only the tokens and the interfaces they carry.
59
+ *
60
+ * **In-memory reference stubs, not "the obvious real adapter."** The brief is
61
+ * explicit: interfaces + minimal stubs only, no full per-provider-type
62
+ * implementations (no real Stripe/Auth0/Supabase integration). Every stub here
63
+ * optimizes for proving the port's shape is satisfiable and unit-testable, not
64
+ * for production use — see each file's header comment for the specific corners
65
+ * cut (plaintext passwords, deterministic always-succeeding charges, no
66
+ * cross-process realtime fan-out, no query language beyond exact-match
67
+ * `where`).
15
68
  */
16
69
  export * from './auth.js';
17
70
  export * from './storage.js';
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * `@jini-ai/capability-providers` — abstract, swappable capability-provider
3
3
  * ports (auth/storage/payments/db/realtime): stable interfaces and typed DI
4
4
  * tokens only. Speculative port-design exploration, built with no current
5
- * consumer — see `source-map.md` for the full scope note and sign-off
5
+ * consumer — see `archived provenance ledger` for the full scope note and sign-off
6
6
  * status.
7
7
  *
8
8
  * This entry point intentionally does NOT export any concrete
@@ -12,6 +12,59 @@
12
12
  * `src/unsafe-reference/` and are exported only from the separate
13
13
  * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
14
14
  * directory's `index.ts` header before importing anything from it.
15
+
16
+ * Archived provenance rationale:
17
+ * ## Why this exists (the gap it names)
18
+ *
19
+ * `ADS-memory/reports/jini-port/recon/r5b-consumers-matrix.md` §2 (the capability matrix) and
20
+ * §3.3 identify a **capability-provider registry with auth / storage /
21
+ * payments / db / realtime as Zana + a fleet orchestrator convergent** — both consumers
22
+ * independently built an explicit port+provider layer (Zana: `app-chassis`'s
23
+ * "rigid core, flexible edges" thesis, `packages/{core,ai,db,auth,storage,
24
+ * payments}` + `providers/supabase` declaring which capabilities it
25
+ * implements; the fleet orchestrator: "ports+sqlite/memory"), while Open Design itself
26
+ * only models these capabilities thinly. §3.3 states this "should be an engine
27
+ * primitive... so products swap Supabase/SQLite/Stripe without touching core"
28
+ * — that is the shape this package builds: 5 independent ports (not one
29
+ * umbrella "CapabilityProvider" interface — see "Design decisions" below) each
30
+ * with a typed DI token (`packages/core/src/token.ts`'s pattern) and a minimal
31
+ * in-memory reference implementation proving the port is genuinely
32
+ * implementable.
33
+ *
34
+ * ## Design decisions
35
+ *
36
+ * **Five separate port interfaces, not one `CapabilityProvider` union.** Zana's
37
+ * own model has a single adapter (Supabase) implementing multiple capabilities
38
+ * at once, which might suggest one umbrella interface with optional methods.
39
+ * Rejected: extraction-plan.md §2.2's core lesson (the reason typed tokens beat
40
+ * a structural dependency object in the first place) is that a union/bag
41
+ * interface is exactly the shape that decays into an OD-`ServerContext`-style
42
+ * god-object as capabilities accrete. Five independently bindable tokens means
43
+ * a consumer wiring only `DbProviderToken` + `StorageProviderToken` never sees
44
+ * `AuthProvider`/`PaymentsProvider`/`RealtimeProvider` in its type surface. A
45
+ * real adapter that happens to implement several (a future `SupabaseAdapter`)
46
+ * is free to be one class satisfying multiple interfaces and bound to multiple
47
+ * tokens — that composition happens at the binding site, not in this package.
48
+ *
49
+ * **No registry/discovery module.** The task brief's scope constraint says
50
+ * "abstract port/interface definitions... plus at minimum one trivial
51
+ * reference/stub implementation" and explicitly forbids wiring this into any
52
+ * other package. `@jini/core`'s existing typed-token + `bindings()` mechanism
53
+ * already *is* the registration/discovery layer (extraction-plan.md §2.2) —
54
+ * building a second, parallel registry inside this package would duplicate
55
+ * that machinery for no reason and blur the "zero other package depends on
56
+ * this" boundary the brief asked for. A consumer registers these tokens in its
57
+ * own `createDaemon({ bindings: bindings().bind(AuthProviderToken, ...) })`
58
+ * call; this package supplies only the tokens and the interfaces they carry.
59
+ *
60
+ * **In-memory reference stubs, not "the obvious real adapter."** The brief is
61
+ * explicit: interfaces + minimal stubs only, no full per-provider-type
62
+ * implementations (no real Stripe/Auth0/Supabase integration). Every stub here
63
+ * optimizes for proving the port's shape is satisfiable and unit-testable, not
64
+ * for production use — see each file's header comment for the specific corners
65
+ * cut (plaintext passwords, deterministic always-succeeding charges, no
66
+ * cross-process realtime fan-out, no query language beyond exact-match
67
+ * `where`).
15
68
  */
16
69
  export * from './auth.js';
17
70
  export * from './storage.js';