@jini-ai/capability-providers 0.1.2 → 0.4.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +101 -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 +18 -47
  14. package/dist/auth.js +11 -178
  15. package/dist/db.d.ts +9 -51
  16. package/dist/db.js +10 -79
  17. package/dist/index.d.ts +8 -13
  18. package/dist/index.js +8 -13
  19. package/dist/payments.d.ts +18 -75
  20. package/dist/payments.js +10 -176
  21. package/dist/realtime.d.ts +20 -74
  22. package/dist/realtime.js +10 -141
  23. package/dist/storage.d.ts +22 -51
  24. package/dist/storage.js +10 -57
  25. package/dist/tokens.js +7 -16
  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 +79 -8
  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,15 @@
1
+ /**
2
+ * Swappable identity/session port. See index.ts for capability-provider ownership and adoption scope.
3
+ *
4
+ * This file defines the port's stable interface/type surface and nothing else —
5
+ * it has no imports at all, so a consumer implementing `AuthProvider`
6
+ * themselves installs nothing. The one real, production-quality adapter
7
+ * (`JwtAuthProvider`, self-contained HS256 JWT sessions over `node:crypto`)
8
+ * lives at the separate `@jini-ai/capability-providers/adapters/jwt-auth`
9
+ * entry point; the non-production in-memory reference stub
10
+ * (`createInMemoryAuthProvider`) lives under `src/unsafe-reference/`,
11
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
12
+ */
1
13
  export interface AuthCredentials {
2
14
  readonly email: string;
3
15
  readonly password: string;
@@ -18,53 +30,12 @@ export interface AuthProvider {
18
30
  /** Exchanges valid credentials for a new session. Rejects on an unknown email or wrong password. */
19
31
  signIn(credentials: AuthCredentials): Promise<AuthSession>;
20
32
  /** Invalidates a session token. A no-op on an already-invalid/unknown token. */
21
- signOut(token: string): Promise<void>;
33
+ signOut(required: {
34
+ token: string;
35
+ }): Promise<void>;
22
36
  /** 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>;
37
+ verifySession(required: {
38
+ token: string;
39
+ }): Promise<AuthUser | null>;
69
40
  }
70
41
  //# sourceMappingURL=auth.d.ts.map
package/dist/auth.js CHANGED
@@ -1,181 +1,14 @@
1
1
  /**
2
- * `AuthProvider` — a swappable identity/session port. Speculative
3
- * port-design exploration (see `source-map.md`): Zana and Tovu-Runner 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.
2
+ * Swappable identity/session port. See index.ts for capability-provider ownership and adoption scope.
7
3
  *
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.
17
- */
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
- }
4
+ * This file defines the port's stable interface/type surface and nothing else —
5
+ * it has no imports at all, so a consumer implementing `AuthProvider`
6
+ * themselves installs nothing. The one real, production-quality adapter
7
+ * (`JwtAuthProvider`, self-contained HS256 JWT sessions over `node:crypto`)
8
+ * lives at the separate `@jini-ai/capability-providers/adapters/jwt-auth`
9
+ * entry point; the non-production in-memory reference stub
10
+ * (`createInMemoryAuthProvider`) lives under `src/unsafe-reference/`,
11
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
12
+ */
13
+ export {};
181
14
  //# sourceMappingURL=auth.js.map
package/dist/db.d.ts CHANGED
@@ -1,24 +1,15 @@
1
1
  /**
2
- * `DbProvider` — a swappable, minimal document-store port (collection +
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)
7
- * both built explicitly.
2
+ * Swappable minimal document-store port: collections and record ids, not a query language. See index.ts for capability-provider ownership and adoption scope.
8
3
  *
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.
4
+ * This file defines the port's stable interface/type surface and nothing else —
5
+ * it has no imports at all, so a consumer implementing `DbProvider` themselves
6
+ * installs nothing. The one real, production-quality adapter
7
+ * (`SqliteDbProvider`, backed by `better-sqlite3`) lives at the separate
8
+ * `@jini-ai/capability-providers/adapters/sqlite` entry point; the
9
+ * non-production in-memory reference stub (`createInMemoryDbProvider`) lives
10
+ * under `src/unsafe-reference/`, exported only from
11
+ * `@jini-ai/capability-providers/unsafe-reference`.
20
12
  */
21
- import type Database from 'better-sqlite3';
22
13
  export interface DbRecord {
23
14
  readonly id: string;
24
15
  readonly [field: string]: unknown;
@@ -39,37 +30,4 @@ export interface DbProvider {
39
30
  /** Returns every record in `collection` matching `query.where` (all records when `query` is omitted). */
40
31
  query(collection: string, query?: DbQuery): Promise<DbRecord[]>;
41
32
  }
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
33
  //# sourceMappingURL=db.d.ts.map
package/dist/db.js CHANGED
@@ -1,83 +1,14 @@
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
+ * Swappable minimal document-store port: collections and record ids, not a query language. See index.ts for capability-provider ownership and adoption scope.
15
3
  *
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.
4
+ * This file defines the port's stable interface/type surface and nothing else —
5
+ * it has no imports at all, so a consumer implementing `DbProvider` themselves
6
+ * installs nothing. The one real, production-quality adapter
7
+ * (`SqliteDbProvider`, backed by `better-sqlite3`) lives at the separate
8
+ * `@jini-ai/capability-providers/adapters/sqlite` entry point; the
9
+ * non-production in-memory reference stub (`createInMemoryDbProvider`) lives
10
+ * under `src/unsafe-reference/`, exported only from
11
+ * `@jini-ai/capability-providers/unsafe-reference`.
21
12
  */
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
- }
13
+ export {};
83
14
  //# sourceMappingURL=db.js.map
package/dist/index.d.ts CHANGED
@@ -1,17 +1,12 @@
1
1
  /**
2
- * `@jini-ai/capability-providers` — abstract, swappable capability-provider
3
- * ports (auth/storage/payments/db/realtime): stable interfaces and typed DI
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
6
- * status.
7
- *
8
- * This entry point intentionally does NOT export any concrete
9
- * implementation. The non-cryptographic, non-production in-memory
10
- * reference stubs that prove each port is genuinely implementable
11
- * (`createInMemoryAuthProvider` and friends) live under
12
- * `src/unsafe-reference/` and are exported only from the separate
13
- * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
14
- * directory's `index.ts` header before importing anything from it.
2
+ * @jini-ai/capability-providers supplies independently bindable auth/storage/payment/db/realtime
3
+ * ports and tokens, with no current consumer commitment. Avoid an optional-method umbrella bag:
4
+ * a consumer should see only the capabilities it binds. One adapter can implement several ports
5
+ * and bind to several tokens at the composition site.
6
+ * @jini-ai/core's bindings already own registration; this package must not create a second registry.
7
+ * Concrete implementations are separate entries. unsafe-reference stubs prove the interfaces are
8
+ * implementable, with non-cryptographic/non-production behavior; never infer production guarantees
9
+ * from them. See that entry's index header for its specific limitations.
15
10
  */
16
11
  export * from './auth.js';
17
12
  export * from './storage.js';
package/dist/index.js CHANGED
@@ -1,17 +1,12 @@
1
1
  /**
2
- * `@jini-ai/capability-providers` — abstract, swappable capability-provider
3
- * ports (auth/storage/payments/db/realtime): stable interfaces and typed DI
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
6
- * status.
7
- *
8
- * This entry point intentionally does NOT export any concrete
9
- * implementation. The non-cryptographic, non-production in-memory
10
- * reference stubs that prove each port is genuinely implementable
11
- * (`createInMemoryAuthProvider` and friends) live under
12
- * `src/unsafe-reference/` and are exported only from the separate
13
- * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
14
- * directory's `index.ts` header before importing anything from it.
2
+ * @jini-ai/capability-providers supplies independently bindable auth/storage/payment/db/realtime
3
+ * ports and tokens, with no current consumer commitment. Avoid an optional-method umbrella bag:
4
+ * a consumer should see only the capabilities it binds. One adapter can implement several ports
5
+ * and bind to several tokens at the composition site.
6
+ * @jini-ai/core's bindings already own registration; this package must not create a second registry.
7
+ * Concrete implementations are separate entries. unsafe-reference stubs prove the interfaces are
8
+ * implementable, with non-cryptographic/non-production behavior; never infer production guarantees
9
+ * from them. See that entry's index header for its specific limitations.
15
10
  */
16
11
  export * from './auth.js';
17
12
  export * from './storage.js';
@@ -1,28 +1,20 @@
1
1
  /**
2
- * `PaymentsProvider` — a swappable payment-charge port. Speculative
3
- * port-design exploration (see `source-map.md`) — no OD source; named
4
- * explicitly in `foundry/docs/jini-port/recon/r5b-consumers-matrix.md` §3.3 as one
5
- * of the capabilities Zana/Tovu's independent provider layers converge on
6
- * (alongside auth/storage/db/realtime).
2
+ * Swappable payment-charge port. See index.ts for capability-provider ownership and adoption scope.
7
3
  *
8
- * This file defines the port's stable interface/type surface, plus one real,
9
- * production-quality adapter (`StripePaymentsProvider`, added 2026-07-21 —
10
- * see `source-map.md`'s dated section) against Stripe's real, documented
11
- * Charges/Refunds REST API (`https://docs.stripe.com/api/charges`,
12
- * `https://docs.stripe.com/api/refunds`) — verified against Stripe's own
13
- * docs while building this, not guessed from memory (request shape, Basic
14
- * auth over the secret key, form-encoded body, JSON error envelope). The
15
- * in-memory reference implementation (`createInMemoryPaymentsProvider`) is a
16
- * separate, non-production stub that lives under `src/unsafe-reference/`,
17
- * exported only from the separate `@jini-ai/capability-providers/unsafe-reference`
18
- * entry point — see that directory's `index.ts` header for the full warning.
4
+ * This file defines the port's stable interface/type surface and nothing else —
5
+ * it has no imports at all, so a consumer implementing `PaymentsProvider`
6
+ * themselves installs nothing. The one real, production-quality adapter
7
+ * (`StripePaymentsProvider`, against Stripe's Charges/Refunds REST API) lives
8
+ * at the separate `@jini-ai/capability-providers/adapters/stripe` entry point;
9
+ * the non-production in-memory reference stub
10
+ * (`createInMemoryPaymentsProvider`) lives under `src/unsafe-reference/`,
11
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
19
12
  */
20
13
  export type ChargeStatus = 'pending' | 'succeeded' | 'failed' | 'refunded';
21
14
  export interface ChargeInput {
22
15
  readonly amountCents: number;
23
16
  readonly currency: string;
24
17
  readonly customerRef: string;
25
- readonly description?: string;
26
18
  }
27
19
  export interface Charge {
28
20
  readonly id: string;
@@ -34,65 +26,16 @@ export interface Charge {
34
26
  }
35
27
  export interface PaymentsProvider {
36
28
  /** Creates and (in the reference stub) immediately settles a charge. Rejects on a non-positive amount. */
37
- charge(input: ChargeInput): Promise<Charge>;
29
+ charge(input: ChargeInput, optional?: {
30
+ description?: string;
31
+ }): Promise<Charge>;
38
32
  /** Looks up a previously created charge by id, or `null` if unknown. */
39
- getCharge(id: string): Promise<Charge | null>;
33
+ getCharge(required: {
34
+ id: string;
35
+ }): Promise<Charge | null>;
40
36
  /** Refunds a `'succeeded'` charge. Rejects if the charge is unknown or not in a refundable state. */
41
- refund(id: string): Promise<Charge>;
42
- }
43
- /** Error thrown by {@link StripePaymentsProvider}, carrying Stripe's own error envelope fields (`https://docs.stripe.com/api/errors`) when the failure came from a Stripe API response. */
44
- export declare class StripePaymentsProviderError extends Error {
45
- /** The HTTP status Stripe (or a local pre-flight check) returned. */
46
- readonly status: number;
47
- /** Stripe's `error.type` — one of `api_error`, `card_error`, `idempotency_error`, `invalid_request_error`. Undefined for a local pre-flight rejection (e.g. a non-positive amount) that never reached Stripe. */
48
- readonly stripeType?: string;
49
- /** Stripe's `error.code`, when present. */
50
- readonly stripeCode?: string;
51
- constructor(message: string, status: number, stripeType?: string, stripeCode?: string);
52
- }
53
- export interface StripePaymentsProviderOptions {
54
- /** Stripe secret key (`sk_live_...`/`sk_test_...`). Required and explicit — never read from an environment variable inside this adapter. */
55
- readonly secretKey: string;
56
- /** Pluggable fetch for tests. Defaults to `globalThis.fetch`, matching `S3BlobStorage`/`netlify.ts`'s precedent in this repo. */
57
- readonly fetchFn?: typeof fetch;
58
- /** Overrides Stripe's API base URL. Tests only — production leaves this unset. */
59
- readonly apiBase?: string;
60
- }
61
- /**
62
- * `PaymentsProvider` adapter against Stripe's real Charges/Refunds REST API. No mock/simulated
63
- * money movement — every `charge`/`getCharge`/`refund` call is a real HTTP request to
64
- * `api.stripe.com` (or `options.apiBase` in tests), authenticated the way Stripe's own docs
65
- * specify: HTTP Basic auth with the secret key as the username and an empty password
66
- * (`Authorization: Basic base64("sk_...:")`), request bodies form-encoded
67
- * (`application/x-www-form-urlencoded`), not JSON.
68
- *
69
- * `ChargeInput.customerRef` is sent as Stripe's `customer` parameter — this adapter always
70
- * charges an existing Stripe Customer (who must already have a default/attached payment method),
71
- * never a one-off `source`/token; `ChargeInput` has no field for a raw card token, and inventing
72
- * one wasn't part of this port's brief.
73
- */
74
- export declare class StripePaymentsProvider implements PaymentsProvider {
75
- private readonly options;
76
- private readonly fetchFn;
77
- private readonly apiBase;
78
- constructor(options: StripePaymentsProviderOptions);
79
- charge(input: ChargeInput): Promise<Charge>;
80
- getCharge(id: string): Promise<Charge | null>;
81
- /**
82
- * `PaymentsProvider.refund` returns a completed `Charge`, but a real Stripe `Refund` object's
83
- * own `status` can be `'succeeded'`, `'pending'` (common for bank-sourced refunds that settle
84
- * over days), `'failed'`, or `'canceled'` — a richer state machine than this port's
85
- * `ChargeStatus` has room for. Since `ChargeStatus` has no "refund in flight" state, `'pending'`
86
- * is treated the same as `'succeeded'` here (Stripe accepted the refund; it will settle) and
87
- * only `'failed'`/`'canceled'` reject. A host that needs to distinguish "refund accepted" from
88
- * "refund settled" should track Stripe's own refund object separately — out of scope for this
89
- * port's `Charge`-shaped return value.
90
- */
91
- refund(id: string): Promise<Charge>;
92
- private authHeader;
93
- private request;
94
- private safeJson;
95
- private toError;
96
- private toCharge;
37
+ refund(required: {
38
+ id: string;
39
+ }): Promise<Charge>;
97
40
  }
98
41
  //# sourceMappingURL=payments.d.ts.map