@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/payments.js CHANGED
@@ -1,180 +1,14 @@
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
- const STRIPE_API_BASE = 'https://api.stripe.com/v1';
21
- /** 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. */
22
- export class StripePaymentsProviderError extends Error {
23
- /** The HTTP status Stripe (or a local pre-flight check) returned. */
24
- status;
25
- /** 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. */
26
- stripeType;
27
- /** Stripe's `error.code`, when present. */
28
- stripeCode;
29
- constructor(message, status, stripeType, stripeCode) {
30
- super(message);
31
- this.name = 'StripePaymentsProviderError';
32
- this.status = status;
33
- if (stripeType !== undefined)
34
- this.stripeType = stripeType;
35
- if (stripeCode !== undefined)
36
- this.stripeCode = stripeCode;
37
- }
38
- }
39
- /**
40
- * Maps a raw Stripe Charge JSON object's `status` (`'succeeded' | 'pending' | 'failed'` per
41
- * Stripe's documented Charge object) plus its separate `refunded` boolean onto this port's
42
- * `ChargeStatus`. `refunded: true` always wins — Stripe leaves `status` at `'succeeded'` even
43
- * after a full refund, but this port's `ChargeStatus` models "refunded" as its own terminal
44
- * state distinct from "succeeded", so a charge this adapter itself refunded (or that was
45
- * refunded directly in Stripe) reports as `'refunded'` here.
46
- */
47
- function mapStripeChargeStatus(raw, refunded) {
48
- if (refunded === true)
49
- return 'refunded';
50
- if (raw === 'succeeded' || raw === 'pending' || raw === 'failed')
51
- return raw;
52
- // Stripe's Charge.status is documented as exactly succeeded | pending | failed — this branch
53
- // has no real reachable path against Stripe's actual contract, but keeps the mapping total
54
- // against `unknown` JSON (an arbitrary HTTP response body) rather than asserting.
55
- return 'pending';
56
- }
57
- /**
58
- * `PaymentsProvider` adapter against Stripe's real Charges/Refunds REST API. No mock/simulated
59
- * money movement — every `charge`/`getCharge`/`refund` call is a real HTTP request to
60
- * `api.stripe.com` (or `options.apiBase` in tests), authenticated the way Stripe's own docs
61
- * specify: HTTP Basic auth with the secret key as the username and an empty password
62
- * (`Authorization: Basic base64("sk_...:")`), request bodies form-encoded
63
- * (`application/x-www-form-urlencoded`), not JSON.
64
- *
65
- * `ChargeInput.customerRef` is sent as Stripe's `customer` parameter — this adapter always
66
- * charges an existing Stripe Customer (who must already have a default/attached payment method),
67
- * never a one-off `source`/token; `ChargeInput` has no field for a raw card token, and inventing
68
- * one wasn't part of this port's brief.
69
- */
70
- export class StripePaymentsProvider {
71
- options;
72
- fetchFn;
73
- apiBase;
74
- constructor(options) {
75
- this.options = options;
76
- if (!options.secretKey) {
77
- throw new StripePaymentsProviderError('StripePaymentsProvider requires a non-empty options.secretKey', 401);
78
- }
79
- const fn = options.fetchFn ?? globalThis.fetch;
80
- if (!fn) {
81
- throw new StripePaymentsProviderError('StripePaymentsProvider requires a fetch implementation', 500);
82
- }
83
- this.fetchFn = fn;
84
- this.apiBase = (options.apiBase ?? STRIPE_API_BASE).replace(/\/+$/, '');
85
- }
86
- async charge(input) {
87
- if (input.amountCents <= 0) {
88
- throw new StripePaymentsProviderError('amountCents must be positive', 400);
89
- }
90
- const body = new URLSearchParams({
91
- amount: String(input.amountCents),
92
- currency: input.currency,
93
- customer: input.customerRef,
94
- });
95
- if (input.description !== undefined)
96
- body.set('description', input.description);
97
- const json = await this.request('POST', '/charges', body);
98
- return this.toCharge(json);
99
- }
100
- async getCharge(id) {
101
- try {
102
- const json = await this.request('GET', `/charges/${encodeURIComponent(id)}`);
103
- return this.toCharge(json);
104
- }
105
- catch (err) {
106
- if (err instanceof StripePaymentsProviderError && err.status === 404)
107
- return null;
108
- throw err;
109
- }
110
- }
111
- /**
112
- * `PaymentsProvider.refund` returns a completed `Charge`, but a real Stripe `Refund` object's
113
- * own `status` can be `'succeeded'`, `'pending'` (common for bank-sourced refunds that settle
114
- * over days), `'failed'`, or `'canceled'` — a richer state machine than this port's
115
- * `ChargeStatus` has room for. Since `ChargeStatus` has no "refund in flight" state, `'pending'`
116
- * is treated the same as `'succeeded'` here (Stripe accepted the refund; it will settle) and
117
- * only `'failed'`/`'canceled'` reject. A host that needs to distinguish "refund accepted" from
118
- * "refund settled" should track Stripe's own refund object separately — out of scope for this
119
- * port's `Charge`-shaped return value.
120
- */
121
- async refund(id) {
122
- const existing = await this.getCharge(id);
123
- if (!existing) {
124
- throw new StripePaymentsProviderError(`unknown charge: ${id}`, 404);
125
- }
126
- if (existing.status !== 'succeeded') {
127
- throw new StripePaymentsProviderError(`charge ${id} is not refundable from status "${existing.status}"`, 400);
128
- }
129
- const json = await this.request('POST', '/refunds', new URLSearchParams({ charge: id }));
130
- const refundStatus = json.status;
131
- if (refundStatus === 'failed' || refundStatus === 'canceled') {
132
- throw new StripePaymentsProviderError(`Stripe refund ${String(refundStatus)} for charge ${id}`, 402, 'api_error');
133
- }
134
- return { ...existing, status: 'refunded' };
135
- }
136
- authHeader() {
137
- return `Basic ${Buffer.from(`${this.options.secretKey}:`).toString('base64')}`;
138
- }
139
- async request(method, path, formBody) {
140
- const headers = { Authorization: this.authHeader() };
141
- const init = { method, headers };
142
- if (formBody) {
143
- headers['Content-Type'] = 'application/x-www-form-urlencoded';
144
- init.body = formBody.toString();
145
- }
146
- const res = await this.fetchFn(`${this.apiBase}${path}`, init);
147
- const json = await this.safeJson(res);
148
- if (!res.ok)
149
- throw this.toError(res.status, json);
150
- return json;
151
- }
152
- async safeJson(res) {
153
- try {
154
- const parsed = await res.json();
155
- return parsed && typeof parsed === 'object' ? parsed : {};
156
- }
157
- catch {
158
- return {};
159
- }
160
- }
161
- toError(status, json) {
162
- const errorObj = json.error && typeof json.error === 'object' ? json.error : {};
163
- const message = typeof errorObj.message === 'string' && errorObj.message ? errorObj.message : `Stripe request failed (${status}).`;
164
- const stripeType = typeof errorObj.type === 'string' ? errorObj.type : undefined;
165
- const stripeCode = typeof errorObj.code === 'string' ? errorObj.code : undefined;
166
- return new StripePaymentsProviderError(message, status, stripeType, stripeCode);
167
- }
168
- toCharge(json) {
169
- return {
170
- id: typeof json.id === 'string' ? json.id : '',
171
- status: mapStripeChargeStatus(json.status, json.refunded),
172
- amountCents: typeof json.amount === 'number' ? json.amount : 0,
173
- currency: typeof json.currency === 'string' ? json.currency : '',
174
- customerRef: typeof json.customer === 'string' ? json.customer : '',
175
- // Stripe's `created` is Unix seconds; this port's `createdAt` is epoch milliseconds.
176
- createdAt: typeof json.created === 'number' ? json.created * 1000 : Date.now(),
177
- };
178
- }
179
- }
13
+ export {};
180
14
  //# sourceMappingURL=payments.js.map
@@ -1,86 +1,32 @@
1
1
  /**
2
- * `RealtimeProvider` — a swappable pub/sub port (live updates pushed to
3
- * subscribers). Speculative port-design exploration (see `source-map.md`) —
4
- * no OD source; named in `foundry/docs/jini-port/recon/r5b-consumers-matrix.md` §3.3
5
- * as part of the Zana/Tovu-convergent capability set (Supabase Realtime is
6
- * Zana's reference adapter).
2
+ * Swappable pub/sub port for live updates. 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 (`WebSocketRealtimeProvider` +
10
- * `createWebSocketRealtimeProvider`, added 2026-07-21 — see
11
- * `source-map.md`'s dated section) using WebSockets (the `ws` package) — no
12
- * external hosted-realtime-service dependency (no Pusher/Ably/Supabase
13
- * Realtime). The in-memory reference implementation
14
- * (`createInMemoryRealtimeProvider`) is a separate, non-production stub that
15
- * lives under `src/unsafe-reference/`, exported only from the separate
4
+ * This file defines only the port's stable interface/type surface. The one
5
+ * real, production-quality adapter (`WebSocketRealtimeProvider` +
6
+ * `createWebSocketRealtimeProvider`, using the `ws` package) lives at the
7
+ * separate `@jini-ai/capability-providers/adapters/ws` entry point so the main barrel, which imports this
8
+ * module, is never forced to resolve `ws` just for the port type. The
9
+ * in-memory reference implementation (`createInMemoryRealtimeProvider`) is a
10
+ * separate, non-production stub that lives under `src/unsafe-reference/`,
11
+ * exported only from the separate
16
12
  * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
17
13
  * directory's `index.ts` header for the full warning.
18
14
  */
19
- import { WebSocketServer, type ServerOptions } from 'ws';
20
- export type RealtimeHandler<T = unknown> = (event: T) => void;
15
+ export type RealtimeHandler<T = unknown> = (required: {
16
+ event: T;
17
+ }) => void;
21
18
  /** Call to stop receiving events for the subscription that returned it. Idempotent. */
22
19
  export type RealtimeUnsubscribe = () => void;
23
20
  export interface RealtimeProvider {
24
21
  /** Delivers `event` synchronously to every current subscriber of `channel`. Resolves once all handlers have run. */
25
- publish<T>(channel: string, event: T): Promise<void>;
22
+ publish<T>(required: {
23
+ channel: string;
24
+ event: T;
25
+ }): Promise<void>;
26
26
  /** Registers `handler` for every future `publish` on `channel`. Returns an unsubscribe function. */
27
- subscribe<T>(channel: string, handler: RealtimeHandler<T>): RealtimeUnsubscribe;
27
+ subscribe<T>(required: {
28
+ channel: string;
29
+ handler: RealtimeHandler<T>;
30
+ }): RealtimeUnsubscribe;
28
31
  }
29
- /**
30
- * The minimal structural subset of a `ws` `WebSocket` connection this adapter depends on. A real
31
- * `ws.WebSocket` instance satisfies this without any adaptation; tests construct a plain fake
32
- * (an `EventEmitter`-backed object) satisfying the same shape, so `WebSocketRealtimeProvider`'s
33
- * core logic is fully unit-testable with zero real sockets/ports.
34
- */
35
- export interface RealtimeWebSocketLike {
36
- readonly readyState: number;
37
- send(data: string): void;
38
- on(event: 'message', listener: (data: unknown) => void): void;
39
- on(event: 'close', listener: () => void): void;
40
- on(event: 'error', listener: (err: Error) => void): void;
41
- }
42
- /** The minimal structural subset of a `ws` `WebSocketServer` this adapter depends on. */
43
- export interface RealtimeWebSocketServerLike {
44
- on(event: 'connection', listener: (socket: RealtimeWebSocketLike) => void): void;
45
- }
46
- export interface WebSocketRealtimeProviderOptions {
47
- /** The (real or fake) WebSocket server to accept subscriber connections from. */
48
- readonly server: RealtimeWebSocketServerLike;
49
- }
50
- /**
51
- * `RealtimeProvider` adapter using WebSockets: a self-contained pub/sub server, no external
52
- * hosted-realtime-service dependency. Two subscriber shapes fan out from the same `publish()`:
53
- *
54
- * 1. **In-process** subscribers registered via `subscribe()` — called synchronously, exactly
55
- * like the in-memory reference adapter (same handler-Set-per-channel bookkeeping).
56
- * 2. **Remote WebSocket clients** — connect through the injected server, then send
57
- * `{"type":"subscribe","channel":"..."}` / `{"type":"unsubscribe","channel":"..."}` JSON
58
- * messages to opt in/out of channels. `publish()` sends each currently-subscribed, still-open
59
- * socket a `{"type":"event","channel":"...","event":...}` JSON message. A closed connection is
60
- * cleaned out of every channel it was subscribed to.
61
- *
62
- * The constructor takes a `RealtimeWebSocketServerLike` — structurally satisfied by a real
63
- * `ws.WebSocketServer` (see `createWebSocketRealtimeProvider` below) or, in tests, a fake with no
64
- * real socket/port — so the channel-routing/subscription-bookkeeping core here is fully
65
- * unit-testable without any real network I/O.
66
- */
67
- export declare class WebSocketRealtimeProvider implements RealtimeProvider {
68
- private readonly handlersByChannel;
69
- private readonly socketsByChannel;
70
- constructor(options: WebSocketRealtimeProviderOptions);
71
- private handleConnection;
72
- private socketsFor;
73
- private handlersFor;
74
- publish<T>(channel: string, event: T): Promise<void>;
75
- subscribe<T>(channel: string, handler: RealtimeHandler<T>): RealtimeUnsubscribe;
76
- }
77
- export interface CreateWebSocketRealtimeProviderOptions {
78
- /** Passed straight through to `ws`'s `WebSocketServer` constructor — e.g. `{ port: 8080 }` to listen standalone, or `{ server: httpServer }`/`{ noServer: true }` to share an existing HTTP server's upgrade handling. */
79
- readonly wsOptions: ServerOptions;
80
- }
81
- /** The real, production entry point: constructs an actual `ws.WebSocketServer` and wires a `WebSocketRealtimeProvider` to it. Callers that want to inject a fake server for tests should construct `WebSocketRealtimeProvider` directly instead. */
82
- export declare function createWebSocketRealtimeProvider(options: CreateWebSocketRealtimeProviderOptions): {
83
- readonly provider: WebSocketRealtimeProvider;
84
- readonly server: WebSocketServer;
85
- };
86
32
  //# sourceMappingURL=realtime.d.ts.map
package/dist/realtime.js CHANGED
@@ -1,147 +1,16 @@
1
1
  /**
2
- * `RealtimeProvider` — a swappable pub/sub port (live updates pushed to
3
- * subscribers). Speculative port-design exploration (see `source-map.md`) —
4
- * no OD source; named in `foundry/docs/jini-port/recon/r5b-consumers-matrix.md` §3.3
5
- * as part of the Zana/Tovu-convergent capability set (Supabase Realtime is
6
- * Zana's reference adapter).
2
+ * Swappable pub/sub port for live updates. 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 (`WebSocketRealtimeProvider` +
10
- * `createWebSocketRealtimeProvider`, added 2026-07-21 — see
11
- * `source-map.md`'s dated section) using WebSockets (the `ws` package) — no
12
- * external hosted-realtime-service dependency (no Pusher/Ably/Supabase
13
- * Realtime). The in-memory reference implementation
14
- * (`createInMemoryRealtimeProvider`) is a separate, non-production stub that
15
- * lives under `src/unsafe-reference/`, exported only from the separate
4
+ * This file defines only the port's stable interface/type surface. The one
5
+ * real, production-quality adapter (`WebSocketRealtimeProvider` +
6
+ * `createWebSocketRealtimeProvider`, using the `ws` package) lives at the
7
+ * separate `@jini-ai/capability-providers/adapters/ws` entry point so the main barrel, which imports this
8
+ * module, is never forced to resolve `ws` just for the port type. The
9
+ * in-memory reference implementation (`createInMemoryRealtimeProvider`) is a
10
+ * separate, non-production stub that lives under `src/unsafe-reference/`,
11
+ * exported only from the separate
16
12
  * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
17
13
  * directory's `index.ts` header for the full warning.
18
14
  */
19
- import { WebSocketServer } from 'ws';
20
- /** WebSocket `readyState` value meaning "open and ready to communicate" (WHATWG WebSocket spec; `ws`'s `WebSocket.OPEN` is the same constant `1`). Spelled out locally so `WebSocketRealtimeProvider`'s core class has no runtime import of `ws` — only the `RealtimeWebSocketLike`/`RealtimeWebSocketServerLike` structural types below, and the `createWebSocketRealtimeProvider` factory, actually touch the real package. */
21
- const WEBSOCKET_OPEN_STATE = 1;
22
- /** Parses one inbound client message. Returns `null` for anything not shaped like `{type: 'subscribe'|'unsubscribe', channel: string}` — malformed/unrecognized messages are silently ignored rather than closing the connection, matching a pub/sub transport's normal tolerance for unknown message shapes (e.g. a future protocol version). */
23
- function parseClientMessage(raw) {
24
- let text;
25
- if (typeof raw === 'string') {
26
- text = raw;
27
- }
28
- else if (Buffer.isBuffer(raw)) {
29
- text = raw.toString('utf8');
30
- }
31
- else if (raw instanceof ArrayBuffer) {
32
- text = Buffer.from(raw).toString('utf8');
33
- }
34
- else {
35
- return null;
36
- }
37
- let parsed;
38
- try {
39
- parsed = JSON.parse(text);
40
- }
41
- catch {
42
- return null;
43
- }
44
- if (!parsed || typeof parsed !== 'object')
45
- return null;
46
- const obj = parsed;
47
- if ((obj.type !== 'subscribe' && obj.type !== 'unsubscribe') || typeof obj.channel !== 'string')
48
- return null;
49
- return { type: obj.type, channel: obj.channel };
50
- }
51
- /**
52
- * `RealtimeProvider` adapter using WebSockets: a self-contained pub/sub server, no external
53
- * hosted-realtime-service dependency. Two subscriber shapes fan out from the same `publish()`:
54
- *
55
- * 1. **In-process** subscribers registered via `subscribe()` — called synchronously, exactly
56
- * like the in-memory reference adapter (same handler-Set-per-channel bookkeeping).
57
- * 2. **Remote WebSocket clients** — connect through the injected server, then send
58
- * `{"type":"subscribe","channel":"..."}` / `{"type":"unsubscribe","channel":"..."}` JSON
59
- * messages to opt in/out of channels. `publish()` sends each currently-subscribed, still-open
60
- * socket a `{"type":"event","channel":"...","event":...}` JSON message. A closed connection is
61
- * cleaned out of every channel it was subscribed to.
62
- *
63
- * The constructor takes a `RealtimeWebSocketServerLike` — structurally satisfied by a real
64
- * `ws.WebSocketServer` (see `createWebSocketRealtimeProvider` below) or, in tests, a fake with no
65
- * real socket/port — so the channel-routing/subscription-bookkeeping core here is fully
66
- * unit-testable without any real network I/O.
67
- */
68
- export class WebSocketRealtimeProvider {
69
- handlersByChannel = new Map();
70
- socketsByChannel = new Map();
71
- constructor(options) {
72
- options.server.on('connection', (socket) => this.handleConnection(socket));
73
- }
74
- handleConnection(socket) {
75
- const subscribedChannels = new Set();
76
- socket.on('message', (raw) => {
77
- const message = parseClientMessage(raw);
78
- if (!message)
79
- return;
80
- if (message.type === 'subscribe') {
81
- subscribedChannels.add(message.channel);
82
- this.socketsFor(message.channel).add(socket);
83
- }
84
- else {
85
- subscribedChannels.delete(message.channel);
86
- this.socketsByChannel.get(message.channel)?.delete(socket);
87
- }
88
- });
89
- socket.on('close', () => {
90
- for (const channel of subscribedChannels) {
91
- this.socketsByChannel.get(channel)?.delete(socket);
92
- }
93
- });
94
- // Swallow — `ws` always follows an 'error' with a 'close' for the same socket, which already
95
- // performs the subscription cleanup above; there is nothing additional to do here.
96
- socket.on('error', () => { });
97
- }
98
- socketsFor(channel) {
99
- let sockets = this.socketsByChannel.get(channel);
100
- if (!sockets) {
101
- sockets = new Set();
102
- this.socketsByChannel.set(channel, sockets);
103
- }
104
- return sockets;
105
- }
106
- handlersFor(channel) {
107
- let handlers = this.handlersByChannel.get(channel);
108
- if (!handlers) {
109
- handlers = new Set();
110
- this.handlersByChannel.set(channel, handlers);
111
- }
112
- return handlers;
113
- }
114
- async publish(channel, event) {
115
- const handlers = this.handlersByChannel.get(channel);
116
- if (handlers) {
117
- for (const handler of [...handlers])
118
- handler(event);
119
- }
120
- const sockets = this.socketsByChannel.get(channel);
121
- if (sockets && sockets.size > 0) {
122
- const payload = JSON.stringify({ type: 'event', channel, event });
123
- for (const socket of [...sockets]) {
124
- if (socket.readyState === WEBSOCKET_OPEN_STATE)
125
- socket.send(payload);
126
- }
127
- }
128
- }
129
- subscribe(channel, handler) {
130
- const handlers = this.handlersFor(channel);
131
- handlers.add(handler);
132
- let unsubscribed = false;
133
- return () => {
134
- if (unsubscribed)
135
- return;
136
- unsubscribed = true;
137
- handlers.delete(handler);
138
- };
139
- }
140
- }
141
- /** The real, production entry point: constructs an actual `ws.WebSocketServer` and wires a `WebSocketRealtimeProvider` to it. Callers that want to inject a fake server for tests should construct `WebSocketRealtimeProvider` directly instead. */
142
- export function createWebSocketRealtimeProvider(options) {
143
- const server = new WebSocketServer(options.wsOptions);
144
- const provider = new WebSocketRealtimeProvider({ server });
145
- return { provider, server };
146
- }
15
+ export {};
147
16
  //# sourceMappingURL=realtime.js.map
package/dist/storage.d.ts CHANGED
@@ -1,18 +1,15 @@
1
1
  /**
2
- * `StorageProvider` — a swappable blob-storage port (file uploads, generated
3
- * assets). Speculative port-design exploration (see `source-map.md`) — no OD
4
- * source; the shape is the object-storage capability Zana's `app-chassis`
5
- * (`packages/storage`) and Tovu-Runner's ports layer both name explicitly.
2
+ * Swappable blob-storage port for uploads and generated assets. See index.ts for capability-provider ownership and adoption scope.
6
3
  *
7
- * This file defines the port's stable interface/type surface, plus one real,
8
- * production-quality adapter (`BlobStorageProvider`, added 2026-07-21 — see
9
- * `source-map.md`'s dated section). The in-memory reference implementation
10
- * (`createInMemoryStorageProvider`) is a separate, non-production stub that
11
- * lives under `src/unsafe-reference/`, exported only from the separate
12
- * `@jini-ai/capability-providers/unsafe-reference` entry point — see that
13
- * 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 `StorageProvider`
6
+ * themselves installs nothing. The one real, production-quality adapter
7
+ * (`BlobStorageProvider`, delegating to `@jini-ai/platform`'s `BlobStorage`)
8
+ * lives at the separate `@jini-ai/capability-providers/adapters/blob-storage`
9
+ * entry point; the non-production in-memory reference stub
10
+ * (`createInMemoryStorageProvider`) lives under `src/unsafe-reference/`,
11
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
14
12
  */
15
- import type { BlobStorage } from '@jini-ai/platform';
16
13
  export interface StorageObjectMeta {
17
14
  readonly key: string;
18
15
  readonly size: number;
@@ -24,47 +21,21 @@ export interface StoragePutOptions {
24
21
  }
25
22
  export interface StorageProvider {
26
23
  /** Writes `data` at `key`, overwriting any existing object. */
27
- put(key: string, data: Uint8Array, options?: StoragePutOptions): Promise<StorageObjectMeta>;
24
+ put(required: {
25
+ key: string;
26
+ data: Uint8Array;
27
+ }, options?: StoragePutOptions): Promise<StorageObjectMeta>;
28
28
  /** Reads the object at `key`, or `null` if it doesn't exist. */
29
- get(key: string): Promise<Uint8Array | null>;
29
+ get(required: {
30
+ key: string;
31
+ }): Promise<Uint8Array | null>;
30
32
  /** Deletes the object at `key`. A no-op if it doesn't exist. */
31
- delete(key: string): Promise<void>;
33
+ delete(required: {
34
+ key: string;
35
+ }): Promise<void>;
32
36
  /** Lists objects whose key starts with `prefix` (all objects when `prefix` is omitted), sorted by key. */
33
- list(prefix?: string): Promise<StorageObjectMeta[]>;
34
- }
35
- export interface BlobStorageProviderOptions {
36
- /**
37
- * The `BlobStorage` namespace this provider scopes every `StorageProvider` key under (see
38
- * `BlobStorage`'s own module doc: "a tenant id, a workspace id, a project id, whatever the
39
- * host application scopes storage by"). `StorageProvider`'s `key` maps 1:1 onto `BlobStorage`'s
40
- * `relpath` within this fixed namespace — this adapter does not expose namespace switching,
41
- * matching `StorageProvider`'s single flat `key` surface (bind a separate `BlobStorageProvider`
42
- * per namespace if a host needs more than one).
43
- */
44
- readonly namespace: string;
45
- }
46
- /**
47
- * `StorageProvider` adapter that delegates to an injected `BlobStorage` instance
48
- * (`@jini-ai/platform`'s real, tested port — `LocalBlobStorage` or `S3BlobStorage`). A thin
49
- * method-shape mapping, not a reimplementation: every operation is one `BlobStorage` call plus
50
- * field renaming (`path`→`key`, `mtimeMs`→`updatedAt`).
51
- *
52
- * Known limitation: `BlobFileMeta` (the metadata `BlobStorage` actually persists) has no
53
- * `contentType` field, so `StoragePutOptions.contentType` cannot be durably stored — `put()`
54
- * echoes it straight back in the `StorageObjectMeta` it returns (matching the option the caller
55
- * just passed), but a later `get`-equivalent lookup (`list()`) can never recover it, since
56
- * nothing under `../platform` persists it. `StorageObjectMeta.contentType` is optional
57
- * specifically so an adapter is free to omit it when the backing store can't carry it — this is
58
- * a deliberate, documented adapter-level gap, not a `StorageProvider` interface change.
59
- */
60
- export declare class BlobStorageProvider implements StorageProvider {
61
- private readonly blobStorage;
62
- private readonly options;
63
- constructor(blobStorage: BlobStorage, options: BlobStorageProviderOptions);
64
- put(key: string, data: Uint8Array, options?: StoragePutOptions): Promise<StorageObjectMeta>;
65
- get(key: string): Promise<Uint8Array | null>;
66
- delete(key: string): Promise<void>;
67
- list(prefix?: string): Promise<StorageObjectMeta[]>;
68
- private toObjectMeta;
37
+ list(required: Record<string, never>, optional?: {
38
+ prefix?: string;
39
+ }): Promise<StorageObjectMeta[]>;
69
40
  }
70
41
  //# sourceMappingURL=storage.d.ts.map
package/dist/storage.js CHANGED
@@ -1,61 +1,14 @@
1
- import { StorageError as BlobStorageError } from '@jini-ai/platform';
2
1
  /**
3
- * `StorageProvider` adapter that delegates to an injected `BlobStorage` instance
4
- * (`@jini-ai/platform`'s real, tested port — `LocalBlobStorage` or `S3BlobStorage`). A thin
5
- * method-shape mapping, not a reimplementation: every operation is one `BlobStorage` call plus
6
- * field renaming (`path`→`key`, `mtimeMs`→`updatedAt`).
2
+ * Swappable blob-storage port for uploads and generated assets. See index.ts for capability-provider ownership and adoption scope.
7
3
  *
8
- * Known limitation: `BlobFileMeta` (the metadata `BlobStorage` actually persists) has no
9
- * `contentType` field, so `StoragePutOptions.contentType` cannot be durably stored — `put()`
10
- * echoes it straight back in the `StorageObjectMeta` it returns (matching the option the caller
11
- * just passed), but a later `get`-equivalent lookup (`list()`) can never recover it, since
12
- * nothing under `../platform` persists it. `StorageObjectMeta.contentType` is optional
13
- * specifically so an adapter is free to omit it when the backing store can't carry it — this is
14
- * a deliberate, documented adapter-level gap, not a `StorageProvider` interface change.
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 `StorageProvider`
6
+ * themselves installs nothing. The one real, production-quality adapter
7
+ * (`BlobStorageProvider`, delegating to `@jini-ai/platform`'s `BlobStorage`)
8
+ * lives at the separate `@jini-ai/capability-providers/adapters/blob-storage`
9
+ * entry point; the non-production in-memory reference stub
10
+ * (`createInMemoryStorageProvider`) lives under `src/unsafe-reference/`,
11
+ * exported only from `@jini-ai/capability-providers/unsafe-reference`.
15
12
  */
16
- export class BlobStorageProvider {
17
- blobStorage;
18
- options;
19
- constructor(blobStorage, options) {
20
- this.blobStorage = blobStorage;
21
- this.options = options;
22
- if (!options.namespace) {
23
- throw new Error('BlobStorageProvider requires a non-empty options.namespace');
24
- }
25
- }
26
- async put(key, data, options = {}) {
27
- const meta = await this.blobStorage.writeFile(this.options.namespace, key, Buffer.from(data));
28
- return this.toObjectMeta(meta, options.contentType);
29
- }
30
- async get(key) {
31
- try {
32
- return await this.blobStorage.readFile(this.options.namespace, key);
33
- }
34
- catch (err) {
35
- if (err instanceof BlobStorageError && err.code === 'NOT_FOUND')
36
- return null;
37
- throw err;
38
- }
39
- }
40
- async delete(key) {
41
- // `BlobStorage.deleteFile` is already documented idempotent (missing files don't throw),
42
- // matching `StorageProvider.delete`'s "no-op if it doesn't exist" contract directly.
43
- await this.blobStorage.deleteFile(this.options.namespace, key);
44
- }
45
- async list(prefix = '') {
46
- const files = await this.blobStorage.listFiles(this.options.namespace);
47
- return files
48
- .filter((file) => file.path.startsWith(prefix))
49
- .map((file) => this.toObjectMeta(file))
50
- .sort((a, b) => a.key.localeCompare(b.key));
51
- }
52
- toObjectMeta(meta, contentType) {
53
- return {
54
- key: meta.path,
55
- size: meta.size,
56
- updatedAt: meta.mtimeMs,
57
- ...(contentType !== undefined ? { contentType } : {}),
58
- };
59
- }
60
- }
13
+ export {};
61
14
  //# sourceMappingURL=storage.js.map
package/dist/tokens.js CHANGED
@@ -1,18 +1,9 @@
1
- /**
2
- * Typed DI tokens for each capability-provider port, following the exact
3
- * pattern `@jini-ai/core`'s `token()` establishes (see
4
- * `packages/core/src/token.ts`) and the naming convention `@jini-ai/daemon`'s
5
- * `src/tokens.ts` / `@jini-ai/media`'s `src/tokens.ts` already set
6
- * (bare-interface-name-suffixed-`Token`).
7
- *
8
- * These tokens are exported for a future consumer to `bind()` in its own
9
- * composition — this package itself does not bind them anywhere, and
10
- * nothing else in this repo imports this package (see `source-map.md`).
11
- */
1
+ /** Typed capability-provider DI tokens built with core's token() owner. Names use the
2
+ * bare-interface-name + Token convention. Hosts bind each port in their own composition. */
12
3
  import { token } from '@jini-ai/core';
13
- export const AuthProviderToken = token('jini.capabilityProviders.auth');
14
- export const StorageProviderToken = token('jini.capabilityProviders.storage');
15
- export const PaymentsProviderToken = token('jini.capabilityProviders.payments');
16
- export const DbProviderToken = token('jini.capabilityProviders.db');
17
- export const RealtimeProviderToken = token('jini.capabilityProviders.realtime');
4
+ export const AuthProviderToken = token({ id: 'jini.capabilityProviders.auth' });
5
+ export const StorageProviderToken = token({ id: 'jini.capabilityProviders.storage' });
6
+ export const PaymentsProviderToken = token({ id: 'jini.capabilityProviders.payments' });
7
+ export const DbProviderToken = token({ id: 'jini.capabilityProviders.db' });
8
+ export const RealtimeProviderToken = token({ id: 'jini.capabilityProviders.realtime' });
18
9
  //# sourceMappingURL=tokens.js.map