@poolse/sdk 2.12.1 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,397 +1,397 @@
1
- # `@poolse/sdk`
2
-
3
- Headless TypeScript chat SDK — the REST + WebSocket client for the [poolse](https://poolse.dev) realtime backend. Drop-in for any runtime with `fetch` + `WebSocket`: browsers, Node ≥ 18, Bun, Deno, React Native. No UI, no framework dependency, fully typed surface.
4
-
5
- > **MIT-licensed alternative to Sendbird, Stream Chat, Pusher Chat, TalkJS, and CometChat.** SDK is open source; the hosted backend is paid (free tier available, no time limit).
6
-
7
- If you're using React, you'll usually want [`@poolse/react`](https://www.npmjs.com/package/@poolse/react) (hooks) or [`@poolse/react-ui`](https://www.npmjs.com/package/@poolse/react-ui) (prebuilt chat surface). Both sit on top of this package; you can drop down to it whenever you outgrow them.
8
-
9
- > **⚠️ Upgrading from 1.x?** See [MIGRATING.md](https://github.com/poolse-hq/js-sdk/blob/main/MIGRATING.md). 2.0 is a breaking change: identity APIs are now keyed by your `external_id` instead of poolse uuids — `userResolver`, `useUser`, member operations all flip.
10
-
11
- ## Install
12
-
13
- ```bash
14
- npm install @poolse/sdk
15
- ```
16
-
17
- The Phoenix Channels client (`phoenix@^1.8`) is bundled into the dist — you don't need to install it separately.
18
-
19
- ## Authentication model
20
-
21
- poolse separates **API keys** (server-side, full tenant scope) from **End User JWTs** (client-side, short-lived, single-user). The SDK is designed for the JWT side: your backend exchanges its API key for an End User JWT (`POST /v1/users/:user_id/tokens`), and the SDK uses that JWT for every REST call and the WebSocket handshake.
22
-
23
- ```
24
- ┌────────────┐ API key ┌─────────┐ user JWT ┌─────────────┐
25
- │ your │ ────────▶ │ poolse │ ─────────▶ │ your │
26
- │ backend │ │ REST │ │ frontend │
27
- │ (mints │ │ │ │ (this SDK) │
28
- │ JWTs) │ ◀──────── │ │ ◀───────── │ │
29
- └────────────┘ └─────────┘ └─────────────┘
30
- ```
31
-
32
- Never embed an API key in a client bundle. The SDK calls your `getToken` whenever it needs the JWT; cache + refresh happen inside the SDK.
33
-
34
- ## Quick start
35
-
36
- ```ts
37
- import { Poolse } from '@poolse/sdk';
38
-
39
- const chat = new Poolse({
40
- apiUrl: 'https://api.poolse.dev', // optional; this is the default
41
- getToken: async () => {
42
- const res = await fetch('/api/chat-token', { method: 'POST' });
43
- const { token } = await res.json();
44
- return token; // string, or null for an anonymous request
45
- },
46
- });
47
-
48
- // REST
49
- const me = await chat.me.show();
50
- const { data: conversations } = await chat.conversations.list();
51
- const conv = chat.conversations.one('00000000-0000-0000-0000-000000000000');
52
- const { data: messages } = await conv.messages.list({ limit: 50 });
53
- await conv.messages.send({ body: 'Hello' });
54
-
55
- // Realtime — socket opens lazily on the first conversation() / user() call.
56
- const live = chat.realtime.conversation(conv.id);
57
- const off = live.onMessage((msg) => console.log('new', msg));
58
-
59
- // Clean up when you're done.
60
- off();
61
- chat.destroy(); // closes WebSocket, leaves every joined channel
62
- ```
63
-
64
- ## Configuration
65
-
66
- `new Poolse(config)` — every field but `getToken` has a default.
67
-
68
- | Field | Type | Default | Notes |
69
- | ------------------------ | ----------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
70
- | `getToken` | `() => Promise<string \| null> \| string \| null` | — _required_ | Called when the SDK needs a JWT. Return `null` to make an unauthenticated request (rare — the server requires a JWT for most routes). |
71
- | `apiUrl` | `string` | `https://api.poolse.dev` | Base URL **without** `/v1`. Strip the trailing slash if present (the SDK does this too). |
72
- | `wsUrl` | `string` | `apiUrl` with `http(s)` → `ws(s)` | Override for split-host deployments where the WebSocket gateway is on a different origin. |
73
- | `socketPath` | `string` | `/socket` | Phoenix Channels mount point. |
74
- | `fetch` | `typeof fetch` | `globalThis.fetch` | Inject a fetch implementation (tests, restricted environments). Must be bound to `globalThis` if you pass the global one explicitly. |
75
- | `maxRetries` | `number` | `3` | Retry budget for transient failures, per request. |
76
- | `baseBackoffMs` | `number` | `250` | Base of the exponential backoff. |
77
- | `maxBackoffMs` | `number` | `30000` | Hard ceiling on a single retry delay. |
78
- | `generateIdempotencyKey` | `() => string` | `crypto.randomUUID()` | Override the key generator. Defaults throws at construction time if no `crypto.randomUUID` is available. |
79
- | `onSocketError` | `(err: Error) => void` | — | Fired on non-fatal socket errors (Phoenix handles reconnect internally; this is for surface-level banners). |
80
- | `userResolver` | `(externalId: string) => Promise<PoolseUserProfile \| null> \| PoolseUserProfile \| null` | — | Optional. Resolve the tenant's own user identifier (`external_id` — same string you pass when minting JWTs) to `{ displayName, avatarUrl }` from your app's user data. The UI packages pick this up automatically. |
81
-
82
- ## REST surface
83
-
84
- All methods accept an optional `AbortSignal` (or `{ signal }`) and return parsed JSON. Errors throw typed exceptions — see [Errors](#errors) below.
85
-
86
- ### `chat.me`
87
-
88
- ```ts
89
- chat.me.show(signal?): Promise<Me>; // GET /v1/me
90
- ```
91
-
92
- ### `chat.conversations`
93
-
94
- ```ts
95
- chat.conversations.list(signal?): Promise<{ data: Conversation[] }>;
96
- chat.conversations.create(attrs, signal?): Promise<Conversation>;
97
- chat.conversations.one(id): ConversationHandle;
98
- ```
99
-
100
- `ConversationCreateRequest`:
101
-
102
- ```ts
103
- {
104
- type: 'direct' | 'group';
105
- name?: string | null;
106
- avatar_url?: string | null;
107
- member_limit?: number | null;
108
- member_external_ids?: string[];
109
- custom_data?: Record<string, unknown>;
110
- settings?: Record<string, unknown>;
111
- }
112
- ```
113
-
114
- `member_external_ids` is your tenant's own ids — poolse looks them up by tenant and lazily provisions any that don't exist yet. The returned `Conversation` carries `member_external_ids` (the array of external_ids for every member) and `last_message_preview` (server-denormalized first ~80 chars of the most recent message body, used to render inbox rows without a per-row decrypt round-trip).
115
-
116
- `ConversationHandle` (returned by `chat.conversations.one(id)`):
117
-
118
- ```ts
119
- handle.show(signal?): Promise<Conversation>; // GET /v1/conversations/:id
120
- handle.update(attrs, signal?): Promise<Conversation>; // PATCH /v1/conversations/:id
121
-
122
- handle.listMembers(signal?): Promise<{ data: Membership[] }>; // GET /v1/conversations/:id/members
123
- handle.addMembers(externalIds, { role?, signal? }?): Promise<{ data: Membership[] }>;
124
- handle.addMember(externalId, { role?, signal? }?): Promise<Membership>;
125
- handle.removeMember(userId, signal?): Promise<void>;
126
-
127
- handle.messages: ConversationMessages;
128
- ```
129
-
130
- `handle.messages`:
131
-
132
- ```ts
133
- handle.messages.list({ limit?, before? }?, signal?): Promise<{ data: Message[] }>;
134
- handle.messages.send(attrs, signal?): Promise<Message>;
135
- handle.messages.markRead(messageId, signal?): Promise<void>; // POST /v1/conversations/:id/read
136
- ```
137
-
138
- Messages are paginated **newest-first** by per-conversation `sequence`. To load older messages: `list({ limit: 50, before: oldestSequence })`.
139
-
140
- `MessageCreateRequest`:
141
-
142
- ```ts
143
- {
144
- id?: Uuid; // optional client-supplied id for retry-safe sends
145
- body?: string | null; // optional ONLY when attachment_ids is non-empty
146
- type?: 'text' | 'system' | 'custom';
147
- reply_to_id?: Uuid; // setting this promotes the message to a thread reply
148
- quoted_message_id?: Uuid; // WhatsApp-style quote — stays in main feed
149
- mentions?: Uuid[]; // user_ids to notify
150
- attachment_ids?: Uuid[]; // attach pre-uploaded files; max 10
151
- }
152
- ```
153
-
154
- If you omit `id`, `send` auto-generates one via `crypto.randomUUID()` so retries are idempotent and the realtime echo can be deduped against your optimistic insert.
155
-
156
- ### `chat.messages`
157
-
158
- The message handle is keyed by message id (not conversation), because some operations need the message id but not the conversation id.
159
-
160
- ```ts
161
- chat.messages.one(id): MessageHandle;
162
- ```
163
-
164
- `MessageHandle`:
165
-
166
- ```ts
167
- handle.update({ body }, signal?): Promise<Message>; // PATCH /v1/messages/:id
168
- handle.delete(signal?): Promise<void>; // DELETE /v1/messages/:id (soft-delete)
169
- handle.replies({ limit?, after? }?, signal?): Promise<{ data: Message[] }>; // GET /v1/messages/:id/replies
170
- handle.addReaction(emoji, signal?): Promise<Message>; // POST /v1/messages/:id/reactions
171
- handle.removeReaction(emoji, signal?): Promise<Message>; // DELETE /v1/messages/:id/reactions/:emoji
172
- ```
173
-
174
- Thread replies are paginated **oldest-first** with an `after` cursor (opposite of the main feed). The default `limit` for replies is 500 — most threads load in one request.
175
-
176
- ### `chat.attachments`
177
-
178
- Two-step upload: presign → PUT. The SDK has a one-call helper too.
179
-
180
- ```ts
181
- chat.attachments.requestUpload(attrs, opts?): Promise<AttachmentUploadResponse>; // POST /v1/attachments/upload-url
182
- chat.attachments.upload(input, opts?): Promise<Attachment>; // presign + PUT, returns the row
183
- chat.attachments.one(id): AttachmentHandle;
184
- ```
185
-
186
- `AttachmentUploadInput`:
187
-
188
- ```ts
189
- {
190
- body: BodyInit; // Blob, File, ArrayBufferView, string, etc.
191
- contentType: string; // matches what you'll PUT
192
- byteSize: number; // matches Content-Length of `body`
193
- filename?: string; // shown in the download UI
194
- }
195
- ```
196
-
197
- `AttachmentOptions`:
198
-
199
- ```ts
200
- {
201
- signal?: AbortSignal;
202
- onProgress?: (event: { loaded: number; total: number }) => void;
203
- }
204
- ```
205
-
206
- `onProgress` switches the PUT to `XMLHttpRequest` (the only browser API that exposes upload progress). When you don't pass `onProgress`, the SDK uses `fetch` and you get no progress events. `XMLHttpRequest` is browser-only, so progress in Node will silently no-op.
207
-
208
- To attach to a message, take the returned `attachment.id` and pass it as part of `attachment_ids` on the next `send`. The server links + flips status to `ready` in the same transaction.
209
-
210
- `AttachmentHandle`:
211
-
212
- ```ts
213
- handle.downloadUrl(opts?): Promise<{ url: string; method: 'get' }>; // ~1h TTL
214
- handle.delete(opts?): Promise<void>;
215
- ```
216
-
217
- ### `chat.users`
218
-
219
- A small read-through cache for the **customer-supplied** profile (display name + avatar). The SDK doesn't store these — it asks your `config.userResolver` when it doesn't have them.
220
-
221
- ```ts
222
- chat.users.peek(userId): PoolseUserProfile | null | undefined;
223
- // undefined → not yet fetched (or no resolver)
224
- // null → resolver ran, returned null
225
- // profile → cached hit
226
-
227
- chat.users.get(userId): Promise<PoolseUserProfile | null>;
228
- chat.users.subscribe(userId, listener): () => void; // fires when an entry changes
229
- chat.users.invalidate(userId): void;
230
- chat.users.invalidateAll(): void; // sign-out, tenant swap
231
- ```
232
-
233
- Concurrent `get(userId)` calls for the same id share one in-flight resolver promise — a busy chat with 50 messages from 5 senders calls your resolver 5 times.
234
-
235
- ### `chat.rest`
236
-
237
- Escape hatch for endpoints not yet covered by the typed resources (e.g., admin routes). Same retry + auth + idempotency behavior as the typed methods.
238
-
239
- ```ts
240
- const result = await chat.rest.request<MyShape>({
241
- method: 'POST',
242
- path: '/v1/something',
243
- body: { foo: 'bar' },
244
- query: { limit: 10 },
245
- idempotencyKey: 'my-custom-key', // or null to omit; defaults to a fresh UUID for non-GETs
246
- signal,
247
- });
248
- ```
249
-
250
- ## Realtime
251
-
252
- The WebSocket is **lazily opened** on the first `conversation()` or `user()` call — until then the realtime layer is dormant and won't try to authenticate.
253
-
254
- ```ts
255
- chat.realtime.connect(): void; // idempotent; usually you don't call this directly
256
- chat.realtime.disconnect(): void;
257
- chat.realtime.getStatus(): RealtimeStatus;
258
- chat.realtime.onStatus(fn): Unsubscribe;
259
- chat.realtime.conversation(id): ConversationChannel;
260
- chat.realtime.user(id): UserChannel;
261
- chat.realtime.leave(id): void; // drop a conversation handle
262
- ```
263
-
264
- `RealtimeStatus`: `'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed'`.
265
-
266
- Reconnect with backoff is handled by the underlying Phoenix Socket. On reconnect the JWT is re-read via `getToken`, so a refreshed token lands on the next handshake without manual intervention.
267
-
268
- ### `ConversationChannel`
269
-
270
- Returned by `chat.realtime.conversation(id)`. Reusing the same id returns the same handle (no second channel join).
271
-
272
- ```ts
273
- channel.onMessage(fn): Unsubscribe; // message:new
274
- channel.onMessageUpdated(fn): Unsubscribe; // message:updated
275
- channel.onMessageDeleted(fn): Unsubscribe; // message:deleted
276
- channel.onReactionAdded(fn): Unsubscribe; // reaction:added
277
- channel.onReactionRemoved(fn): Unsubscribe; // reaction:removed
278
- channel.onMemberRead(fn): Unsubscribe; // member:read (read receipts)
279
- channel.onTypingStart(fn): Unsubscribe;
280
- channel.onTypingStop(fn): Unsubscribe;
281
- channel.onPresenceState(fn): Unsubscribe; // initial snapshot (replayed to late subscribers)
282
- channel.onPresenceDiff(fn): Unsubscribe; // joins/leaves deltas
283
- channel.getPresenceState(): PresenceSnapshot; // synchronous read
284
-
285
- channel.sendTyping(): void; // server is rate-limited; safe to spam
286
- ```
287
-
288
- The server filters `typing` to peers — you won't receive your own typing event back.
289
-
290
- Payload shapes are exact:
291
-
292
- | Event | Payload |
293
- | ------------------------------------- | ------------------------------------------------------------------------------------------- |
294
- | `message:new` / `message:updated` | `Message` (full row, with `attachments` preloaded and `quoted_message` set when applicable) |
295
- | `message:deleted` | `{ id: Uuid; conversation_id: Uuid; deleted_at: string \| null }` |
296
- | `reaction:added` / `reaction:removed` | `{ message_id, conversation_id, emoji, user_id }` |
297
- | `member:read` | `{ user_id, conversation_id, last_read_message_id, last_read_at }` |
298
- | `typing:start` / `typing:stop` | `{ user_id }` |
299
- | `presence_state` | `Record<user_id, { metas: Array<{ phx_ref, online_at, external_id? }> }>` |
300
- | `presence_diff` | Same shape, partitioned into `{ joins, leaves }` |
301
-
302
- ### `UserChannel`
303
-
304
- Returned by `chat.realtime.user(id)`. Only the user matching the JWT can join their own channel — the server rejects other ids.
305
-
306
- ```ts
307
- channel.onMention(fn): Unsubscribe;
308
- channel.onConversationCreated(fn): Unsubscribe;
309
- channel.onConversationUpdated(fn): Unsubscribe;
310
- ```
311
-
312
- `onMention` corresponds to the `mention:new` push and carries `{ message_id, conversation_id, sender_id }` — fetch the full message via REST if you need the body.
313
-
314
- `onConversationCreated` corresponds to the `conversation:created` push, which fires whenever the user is added to a conversation (including ones they created themselves) and carries the full `Conversation` row with `member_external_ids` preloaded.
315
-
316
- `onConversationUpdated` corresponds to the `conversation:updated` push and fires after every message sent in any of the user's conversations. Payload shape is `{ conversation: Conversation, by_user_id: Uuid | null }` — `by_user_id` is the sender's id, so a client can avoid bumping its own unread when the server already advanced its read cursor in the same transaction. The `conversation` carries the freshly written `last_message_preview`, `last_message_at`, and `last_sequence` so an inbox UI can update without a refetch.
317
-
318
- ## Token caching
319
-
320
- `config.getToken` is called once per JWT lifetime, not per request. The cache decodes the JWT's `exp` claim and refreshes 30s before expiry. Concurrent callers share the in-flight refresh promise.
321
-
322
- On a 401, the SDK invalidates the cache and retries the request **once** with a fresh token. If the second attempt also 401s, `AuthError` is thrown.
323
-
324
- If you sign the user out or rotate tenants, drop the current `Poolse` instance (or, in `@poolse/react`, give `<PoolseProvider>` a new `key`) — there's no in-place invalidate API at the SDK level because mutating connection-shaped config after construction doesn't reach the open socket anyway.
325
-
326
- ## Idempotency
327
-
328
- Every non-GET request carries an auto-generated `Idempotency-Key` header. The server caches 2xx responses per `(tenant, method, path, key)` for 24 hours, so a retry after a flaky network drop returns the same row instead of creating a duplicate. Non-2xx responses are never cached — you can retry with the same key after fixing a validation error.
329
-
330
- To override the key (e.g., to make a deliberate retry intentional), pass `idempotencyKey` on `chat.rest.request`. Pass `null` to omit the header entirely. Resource methods auto-generate a fresh key per call.
331
-
332
- ## Retry behavior
333
-
334
- Transient failures (network errors, 5xx, 429) are retried with exponential backoff + full jitter, capped by `maxBackoffMs`. On a 429 the server's `Retry-After` (seconds) is honored if present and larger than the computed backoff. Aborts (`DOMException('AbortError')`) are propagated, never wrapped.
335
-
336
- The retry budget is `maxRetries` (default 3) attempts after the initial request — up to 4 attempts total per logical call.
337
-
338
- ## Errors
339
-
340
- All errors extend `PoolseError` and are `instanceof`-checkable:
341
-
342
- ```ts
343
- import { ApiError, AuthError, RateLimitedError, NetworkError, PoolseError } from '@poolse/sdk';
344
-
345
- try {
346
- await chat.messages.one(id).update({ body: 'edit' });
347
- } catch (err) {
348
- if (err instanceof AuthError) {
349
- // 401: the JWT is invalid even after one refresh attempt. Re-auth the user.
350
- } else if (err instanceof RateLimitedError) {
351
- // 429: err.retryAfterMs is parsed from the Retry-After header (0 if absent).
352
- } else if (err instanceof ApiError) {
353
- // Other 4xx/5xx with a canonical envelope: err.status, err.code, err.docUrl, err.details
354
- } else if (err instanceof NetworkError) {
355
- // fetch() rejected; err.cause is the original failure.
356
- }
357
- }
358
- ```
359
-
360
- The server's error envelope is exposed via the `code` / `docUrl` / `details` fields on `ApiError`. Codes are stable strings like `validation_failed`, `forbidden`, `message_deleted`, `attachment_too_large` — see the docs at `err.docUrl` for the full list per endpoint.
361
-
362
- ## Sequence numbers
363
-
364
- Every message has a monotonic per-conversation `sequence`. It's assigned in the same transaction as the insert, so server order is unambiguous regardless of clock skew. The SDK uses it for pagination (`before` / `after` cursors) and for sorting optimistic-vs-server-echo races: the optimistic local insert can sort to the very end until the server-assigned `sequence` arrives, at which point the dedup-by-id upsert puts it in the right place.
365
-
366
- ## Cancellation
367
-
368
- Every method that touches the network accepts an `AbortSignal`. The SDK propagates abort to the underlying `fetch` (and to `XMLHttpRequest` on the progress-enabled upload path). Aborted requests throw `DOMException('AbortError')` — they are **not** retried.
369
-
370
- ```ts
371
- const controller = new AbortController();
372
- const promise = chat.messages.one(id).replies({ limit: 100 }, controller.signal);
373
- // later:
374
- controller.abort();
375
- ```
376
-
377
- ## Environments
378
-
379
- - **Browsers (modern)** — works out of the box.
380
- - **Node ≥ 18** — uses the global `fetch` and `WebSocket`. Upload progress is browser-only (silently no-ops in Node).
381
- - **React Native** — works on RN ≥ 0.72 (`fetch` + `WebSocket` are built in). The `phoenix` client is bundled.
382
- - **Bun / Deno** — works; same caveat on upload progress.
383
- - **Web Workers** — works for REST; sockets work where `WebSocket` is available.
384
-
385
- ## Exports
386
-
387
- The package exports the `Poolse` class, the resource and channel classes (`ConversationsResource`, `ConversationHandle`, `MessagesResource`, `MessageHandle`, `AttachmentsResource`, `AttachmentHandle`, `MeResource`, `UsersResource`, `PoolseRealtime`, `ConversationChannel`, `UserChannel`), all error classes, every interface from the wire protocol (`Message`, `Conversation`, `Membership`, `User`, `Attachment`, etc.), the `RealtimeStatus` union, the `POOLSE_API_URL` default, and a `version` constant for diagnostics.
388
-
389
- ## Links
390
-
391
- - Full docs — <https://poolse.dev/docs>
392
- - Source — <https://github.com/poolse-hq/js-sdk>
393
- - Issues — <https://github.com/poolse-hq/js-sdk/issues>
394
-
395
- ## License
396
-
397
- MIT
1
+ # `@poolse/sdk`
2
+
3
+ Headless TypeScript chat SDK — the REST + WebSocket client for the [poolse](https://poolse.dev) realtime backend. Drop-in for any runtime with `fetch` + `WebSocket`: browsers, Node ≥ 18, Bun, Deno, React Native. No UI, no framework dependency, fully typed surface.
4
+
5
+ > **MIT-licensed alternative to Sendbird, Stream Chat, Pusher Chat, TalkJS, and CometChat.** SDK is open source; the hosted backend is paid (free tier available, no time limit).
6
+
7
+ If you're using React, you'll usually want [`@poolse/react`](https://www.npmjs.com/package/@poolse/react) (hooks) or [`@poolse/react-ui`](https://www.npmjs.com/package/@poolse/react-ui) (prebuilt chat surface). Both sit on top of this package; you can drop down to it whenever you outgrow them.
8
+
9
+ > **⚠️ Upgrading from 1.x?** See [MIGRATING.md](https://github.com/poolse-hq/js-sdk/blob/main/MIGRATING.md). 2.0 is a breaking change: identity APIs are now keyed by your `external_id` instead of poolse uuids — `userResolver`, `useUser`, member operations all flip.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @poolse/sdk
15
+ ```
16
+
17
+ The Phoenix Channels client (`phoenix@^1.8`) is bundled into the dist — you don't need to install it separately.
18
+
19
+ ## Authentication model
20
+
21
+ poolse separates **API keys** (server-side, full tenant scope) from **End User JWTs** (client-side, short-lived, single-user). The SDK is designed for the JWT side: your backend exchanges its API key for an End User JWT (`POST /v1/users/:user_id/tokens`), and the SDK uses that JWT for every REST call and the WebSocket handshake.
22
+
23
+ ```
24
+ ┌────────────┐ API key ┌─────────┐ user JWT ┌─────────────┐
25
+ │ your │ ────────▶ │ poolse │ ─────────▶ │ your │
26
+ │ backend │ │ REST │ │ frontend │
27
+ │ (mints │ │ │ │ (this SDK) │
28
+ │ JWTs) │ ◀──────── │ │ ◀───────── │ │
29
+ └────────────┘ └─────────┘ └─────────────┘
30
+ ```
31
+
32
+ Never embed an API key in a client bundle. The SDK calls your `getToken` whenever it needs the JWT; cache + refresh happen inside the SDK.
33
+
34
+ ## Quick start
35
+
36
+ ```ts
37
+ import { Poolse } from '@poolse/sdk';
38
+
39
+ const chat = new Poolse({
40
+ apiUrl: 'https://api.poolse.dev', // optional; this is the default
41
+ getToken: async () => {
42
+ const res = await fetch('/api/chat-token', { method: 'POST' });
43
+ const { token } = await res.json();
44
+ return token; // string, or null for an anonymous request
45
+ },
46
+ });
47
+
48
+ // REST
49
+ const me = await chat.me.show();
50
+ const { data: conversations } = await chat.conversations.list();
51
+ const conv = chat.conversations.one('00000000-0000-0000-0000-000000000000');
52
+ const { data: messages } = await conv.messages.list({ limit: 50 });
53
+ await conv.messages.send({ body: 'Hello' });
54
+
55
+ // Realtime — socket opens lazily on the first conversation() / user() call.
56
+ const live = chat.realtime.conversation(conv.id);
57
+ const off = live.onMessage((msg) => console.log('new', msg));
58
+
59
+ // Clean up when you're done.
60
+ off();
61
+ chat.destroy(); // closes WebSocket, leaves every joined channel
62
+ ```
63
+
64
+ ## Configuration
65
+
66
+ `new Poolse(config)` — every field but `getToken` has a default.
67
+
68
+ | Field | Type | Default | Notes |
69
+ | ------------------------ | ----------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
70
+ | `getToken` | `() => Promise<string \| null> \| string \| null` | — _required_ | Called when the SDK needs a JWT. Return `null` to make an unauthenticated request (rare — the server requires a JWT for most routes). |
71
+ | `apiUrl` | `string` | `https://api.poolse.dev` | Base URL **without** `/v1`. Strip the trailing slash if present (the SDK does this too). |
72
+ | `wsUrl` | `string` | `apiUrl` with `http(s)` → `ws(s)` | Override for split-host deployments where the WebSocket gateway is on a different origin. |
73
+ | `socketPath` | `string` | `/socket` | Phoenix Channels mount point. |
74
+ | `fetch` | `typeof fetch` | `globalThis.fetch` | Inject a fetch implementation (tests, restricted environments). Must be bound to `globalThis` if you pass the global one explicitly. |
75
+ | `maxRetries` | `number` | `3` | Retry budget for transient failures, per request. |
76
+ | `baseBackoffMs` | `number` | `250` | Base of the exponential backoff. |
77
+ | `maxBackoffMs` | `number` | `30000` | Hard ceiling on a single retry delay. |
78
+ | `generateIdempotencyKey` | `() => string` | `crypto.randomUUID()` | Override the key generator. Defaults throws at construction time if no `crypto.randomUUID` is available. |
79
+ | `onSocketError` | `(err: Error) => void` | — | Fired on non-fatal socket errors (Phoenix handles reconnect internally; this is for surface-level banners). |
80
+ | `userResolver` | `(externalId: string) => Promise<PoolseUserProfile \| null> \| PoolseUserProfile \| null` | — | Optional. Resolve the tenant's own user identifier (`external_id` — same string you pass when minting JWTs) to `{ displayName, avatarUrl }` from your app's user data. The UI packages pick this up automatically. |
81
+
82
+ ## REST surface
83
+
84
+ All methods accept an optional `AbortSignal` (or `{ signal }`) and return parsed JSON. Errors throw typed exceptions — see [Errors](#errors) below.
85
+
86
+ ### `chat.me`
87
+
88
+ ```ts
89
+ chat.me.show(signal?): Promise<Me>; // GET /v1/me
90
+ ```
91
+
92
+ ### `chat.conversations`
93
+
94
+ ```ts
95
+ chat.conversations.list(signal?): Promise<{ data: Conversation[] }>;
96
+ chat.conversations.create(attrs, signal?): Promise<Conversation>;
97
+ chat.conversations.one(id): ConversationHandle;
98
+ ```
99
+
100
+ `ConversationCreateRequest`:
101
+
102
+ ```ts
103
+ {
104
+ type: 'direct' | 'group';
105
+ name?: string | null;
106
+ avatar_url?: string | null;
107
+ member_limit?: number | null;
108
+ member_external_ids?: string[];
109
+ custom_data?: Record<string, unknown>;
110
+ settings?: Record<string, unknown>;
111
+ }
112
+ ```
113
+
114
+ `member_external_ids` is your tenant's own ids — poolse looks them up by tenant and lazily provisions any that don't exist yet. The returned `Conversation` carries `member_external_ids` (the array of external_ids for every member) and `last_message_preview` (server-denormalized first ~80 chars of the most recent message body, used to render inbox rows without a per-row decrypt round-trip).
115
+
116
+ `ConversationHandle` (returned by `chat.conversations.one(id)`):
117
+
118
+ ```ts
119
+ handle.show(signal?): Promise<Conversation>; // GET /v1/conversations/:id
120
+ handle.update(attrs, signal?): Promise<Conversation>; // PATCH /v1/conversations/:id
121
+
122
+ handle.listMembers(signal?): Promise<{ data: Membership[] }>; // GET /v1/conversations/:id/members
123
+ handle.addMembers(externalIds, { role?, signal? }?): Promise<{ data: Membership[] }>;
124
+ handle.addMember(externalId, { role?, signal? }?): Promise<Membership>;
125
+ handle.removeMember(userId, signal?): Promise<void>;
126
+
127
+ handle.messages: ConversationMessages;
128
+ ```
129
+
130
+ `handle.messages`:
131
+
132
+ ```ts
133
+ handle.messages.list({ limit?, before? }?, signal?): Promise<{ data: Message[] }>;
134
+ handle.messages.send(attrs, signal?): Promise<Message>;
135
+ handle.messages.markRead(messageId, signal?): Promise<void>; // POST /v1/conversations/:id/read
136
+ ```
137
+
138
+ Messages are paginated **newest-first** by per-conversation `sequence`. To load older messages: `list({ limit: 50, before: oldestSequence })`.
139
+
140
+ `MessageCreateRequest`:
141
+
142
+ ```ts
143
+ {
144
+ id?: Uuid; // optional client-supplied id for retry-safe sends
145
+ body?: string | null; // optional ONLY when attachment_ids is non-empty
146
+ type?: 'text' | 'system' | 'custom';
147
+ reply_to_id?: Uuid; // setting this promotes the message to a thread reply
148
+ quoted_message_id?: Uuid; // WhatsApp-style quote — stays in main feed
149
+ mentions?: Uuid[]; // user_ids to notify
150
+ attachment_ids?: Uuid[]; // attach pre-uploaded files; max 10
151
+ }
152
+ ```
153
+
154
+ If you omit `id`, `send` auto-generates one via `crypto.randomUUID()` so retries are idempotent and the realtime echo can be deduped against your optimistic insert.
155
+
156
+ ### `chat.messages`
157
+
158
+ The message handle is keyed by message id (not conversation), because some operations need the message id but not the conversation id.
159
+
160
+ ```ts
161
+ chat.messages.one(id): MessageHandle;
162
+ ```
163
+
164
+ `MessageHandle`:
165
+
166
+ ```ts
167
+ handle.update({ body }, signal?): Promise<Message>; // PATCH /v1/messages/:id
168
+ handle.delete(signal?): Promise<void>; // DELETE /v1/messages/:id (soft-delete)
169
+ handle.replies({ limit?, after? }?, signal?): Promise<{ data: Message[] }>; // GET /v1/messages/:id/replies
170
+ handle.addReaction(emoji, signal?): Promise<Message>; // POST /v1/messages/:id/reactions
171
+ handle.removeReaction(emoji, signal?): Promise<Message>; // DELETE /v1/messages/:id/reactions/:emoji
172
+ ```
173
+
174
+ Thread replies are paginated **oldest-first** with an `after` cursor (opposite of the main feed). The default `limit` for replies is 500 — most threads load in one request.
175
+
176
+ ### `chat.attachments`
177
+
178
+ Two-step upload: presign → PUT. The SDK has a one-call helper too.
179
+
180
+ ```ts
181
+ chat.attachments.requestUpload(attrs, opts?): Promise<AttachmentUploadResponse>; // POST /v1/attachments/upload-url
182
+ chat.attachments.upload(input, opts?): Promise<Attachment>; // presign + PUT, returns the row
183
+ chat.attachments.one(id): AttachmentHandle;
184
+ ```
185
+
186
+ `AttachmentUploadInput`:
187
+
188
+ ```ts
189
+ {
190
+ body: BodyInit; // Blob, File, ArrayBufferView, string, etc.
191
+ contentType: string; // matches what you'll PUT
192
+ byteSize: number; // matches Content-Length of `body`
193
+ filename?: string; // shown in the download UI
194
+ }
195
+ ```
196
+
197
+ `AttachmentOptions`:
198
+
199
+ ```ts
200
+ {
201
+ signal?: AbortSignal;
202
+ onProgress?: (event: { loaded: number; total: number }) => void;
203
+ }
204
+ ```
205
+
206
+ `onProgress` switches the PUT to `XMLHttpRequest` (the only browser API that exposes upload progress). When you don't pass `onProgress`, the SDK uses `fetch` and you get no progress events. `XMLHttpRequest` is browser-only, so progress in Node will silently no-op.
207
+
208
+ To attach to a message, take the returned `attachment.id` and pass it as part of `attachment_ids` on the next `send`. The server links + flips status to `ready` in the same transaction.
209
+
210
+ `AttachmentHandle`:
211
+
212
+ ```ts
213
+ handle.downloadUrl(opts?): Promise<{ url: string; method: 'get' }>; // ~1h TTL
214
+ handle.delete(opts?): Promise<void>;
215
+ ```
216
+
217
+ ### `chat.users`
218
+
219
+ A small read-through cache for the **customer-supplied** profile (display name + avatar). The SDK doesn't store these — it asks your `config.userResolver` when it doesn't have them.
220
+
221
+ ```ts
222
+ chat.users.peek(userId): PoolseUserProfile | null | undefined;
223
+ // undefined → not yet fetched (or no resolver)
224
+ // null → resolver ran, returned null
225
+ // profile → cached hit
226
+
227
+ chat.users.get(userId): Promise<PoolseUserProfile | null>;
228
+ chat.users.subscribe(userId, listener): () => void; // fires when an entry changes
229
+ chat.users.invalidate(userId): void;
230
+ chat.users.invalidateAll(): void; // sign-out, tenant swap
231
+ ```
232
+
233
+ Concurrent `get(userId)` calls for the same id share one in-flight resolver promise — a busy chat with 50 messages from 5 senders calls your resolver 5 times.
234
+
235
+ ### `chat.rest`
236
+
237
+ Escape hatch for endpoints not yet covered by the typed resources (e.g., admin routes). Same retry + auth + idempotency behavior as the typed methods.
238
+
239
+ ```ts
240
+ const result = await chat.rest.request<MyShape>({
241
+ method: 'POST',
242
+ path: '/v1/something',
243
+ body: { foo: 'bar' },
244
+ query: { limit: 10 },
245
+ idempotencyKey: 'my-custom-key', // or null to omit; defaults to a fresh UUID for non-GETs
246
+ signal,
247
+ });
248
+ ```
249
+
250
+ ## Realtime
251
+
252
+ The WebSocket is **lazily opened** on the first `conversation()` or `user()` call — until then the realtime layer is dormant and won't try to authenticate.
253
+
254
+ ```ts
255
+ chat.realtime.connect(): void; // idempotent; usually you don't call this directly
256
+ chat.realtime.disconnect(): void;
257
+ chat.realtime.getStatus(): RealtimeStatus;
258
+ chat.realtime.onStatus(fn): Unsubscribe;
259
+ chat.realtime.conversation(id): ConversationChannel;
260
+ chat.realtime.user(id): UserChannel;
261
+ chat.realtime.leave(id): void; // drop a conversation handle
262
+ ```
263
+
264
+ `RealtimeStatus`: `'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed'`.
265
+
266
+ Reconnect with backoff is handled by the underlying Phoenix Socket. On reconnect the JWT is re-read via `getToken`, so a refreshed token lands on the next handshake without manual intervention.
267
+
268
+ ### `ConversationChannel`
269
+
270
+ Returned by `chat.realtime.conversation(id)`. Reusing the same id returns the same handle (no second channel join).
271
+
272
+ ```ts
273
+ channel.onMessage(fn): Unsubscribe; // message:new
274
+ channel.onMessageUpdated(fn): Unsubscribe; // message:updated
275
+ channel.onMessageDeleted(fn): Unsubscribe; // message:deleted
276
+ channel.onReactionAdded(fn): Unsubscribe; // reaction:added
277
+ channel.onReactionRemoved(fn): Unsubscribe; // reaction:removed
278
+ channel.onMemberRead(fn): Unsubscribe; // member:read (read receipts)
279
+ channel.onTypingStart(fn): Unsubscribe;
280
+ channel.onTypingStop(fn): Unsubscribe;
281
+ channel.onPresenceState(fn): Unsubscribe; // initial snapshot (replayed to late subscribers)
282
+ channel.onPresenceDiff(fn): Unsubscribe; // joins/leaves deltas
283
+ channel.getPresenceState(): PresenceSnapshot; // synchronous read
284
+
285
+ channel.sendTyping(): void; // server is rate-limited; safe to spam
286
+ ```
287
+
288
+ The server filters `typing` to peers — you won't receive your own typing event back.
289
+
290
+ Payload shapes are exact:
291
+
292
+ | Event | Payload |
293
+ | ------------------------------------- | ------------------------------------------------------------------------------------------- |
294
+ | `message:new` / `message:updated` | `Message` (full row, with `attachments` preloaded and `quoted_message` set when applicable) |
295
+ | `message:deleted` | `{ id: Uuid; conversation_id: Uuid; deleted_at: string \| null }` |
296
+ | `reaction:added` / `reaction:removed` | `{ message_id, conversation_id, emoji, user_id }` |
297
+ | `member:read` | `{ user_id, conversation_id, last_read_message_id, last_read_at }` |
298
+ | `typing:start` / `typing:stop` | `{ user_id }` |
299
+ | `presence_state` | `Record<user_id, { metas: Array<{ phx_ref, online_at, external_id? }> }>` |
300
+ | `presence_diff` | Same shape, partitioned into `{ joins, leaves }` |
301
+
302
+ ### `UserChannel`
303
+
304
+ Returned by `chat.realtime.user(id)`. Only the user matching the JWT can join their own channel — the server rejects other ids.
305
+
306
+ ```ts
307
+ channel.onMention(fn): Unsubscribe;
308
+ channel.onConversationCreated(fn): Unsubscribe;
309
+ channel.onConversationUpdated(fn): Unsubscribe;
310
+ ```
311
+
312
+ `onMention` corresponds to the `mention:new` push and carries `{ message_id, conversation_id, sender_id }` — fetch the full message via REST if you need the body.
313
+
314
+ `onConversationCreated` corresponds to the `conversation:created` push, which fires whenever the user is added to a conversation (including ones they created themselves) and carries the full `Conversation` row with `member_external_ids` preloaded.
315
+
316
+ `onConversationUpdated` corresponds to the `conversation:updated` push and fires after every message sent in any of the user's conversations. Payload shape is `{ conversation: Conversation, by_user_id: Uuid | null }` — `by_user_id` is the sender's id, so a client can avoid bumping its own unread when the server already advanced its read cursor in the same transaction. The `conversation` carries the freshly written `last_message_preview`, `last_message_at`, and `last_sequence` so an inbox UI can update without a refetch.
317
+
318
+ ## Token caching
319
+
320
+ `config.getToken` is called once per JWT lifetime, not per request. The cache decodes the JWT's `exp` claim and refreshes 30s before expiry. Concurrent callers share the in-flight refresh promise.
321
+
322
+ On a 401, the SDK invalidates the cache and retries the request **once** with a fresh token. If the second attempt also 401s, `AuthError` is thrown.
323
+
324
+ If you sign the user out or rotate tenants, drop the current `Poolse` instance (or, in `@poolse/react`, give `<PoolseProvider>` a new `key`) — there's no in-place invalidate API at the SDK level because mutating connection-shaped config after construction doesn't reach the open socket anyway.
325
+
326
+ ## Idempotency
327
+
328
+ Every non-GET request carries an auto-generated `Idempotency-Key` header. The server caches 2xx responses per `(tenant, method, path, key)` for 24 hours, so a retry after a flaky network drop returns the same row instead of creating a duplicate. Non-2xx responses are never cached — you can retry with the same key after fixing a validation error.
329
+
330
+ To override the key (e.g., to make a deliberate retry intentional), pass `idempotencyKey` on `chat.rest.request`. Pass `null` to omit the header entirely. Resource methods auto-generate a fresh key per call.
331
+
332
+ ## Retry behavior
333
+
334
+ Transient failures (network errors, 5xx, 429) are retried with exponential backoff + full jitter, capped by `maxBackoffMs`. On a 429 the server's `Retry-After` (seconds) is honored if present and larger than the computed backoff. Aborts (`DOMException('AbortError')`) are propagated, never wrapped.
335
+
336
+ The retry budget is `maxRetries` (default 3) attempts after the initial request — up to 4 attempts total per logical call.
337
+
338
+ ## Errors
339
+
340
+ All errors extend `PoolseError` and are `instanceof`-checkable:
341
+
342
+ ```ts
343
+ import { ApiError, AuthError, RateLimitedError, NetworkError, PoolseError } from '@poolse/sdk';
344
+
345
+ try {
346
+ await chat.messages.one(id).update({ body: 'edit' });
347
+ } catch (err) {
348
+ if (err instanceof AuthError) {
349
+ // 401: the JWT is invalid even after one refresh attempt. Re-auth the user.
350
+ } else if (err instanceof RateLimitedError) {
351
+ // 429: err.retryAfterMs is parsed from the Retry-After header (0 if absent).
352
+ } else if (err instanceof ApiError) {
353
+ // Other 4xx/5xx with a canonical envelope: err.status, err.code, err.docUrl, err.details
354
+ } else if (err instanceof NetworkError) {
355
+ // fetch() rejected; err.cause is the original failure.
356
+ }
357
+ }
358
+ ```
359
+
360
+ The server's error envelope is exposed via the `code` / `docUrl` / `details` fields on `ApiError`. Codes are stable strings like `validation_failed`, `forbidden`, `message_deleted`, `attachment_too_large` — see the docs at `err.docUrl` for the full list per endpoint.
361
+
362
+ ## Sequence numbers
363
+
364
+ Every message has a monotonic per-conversation `sequence`. It's assigned in the same transaction as the insert, so server order is unambiguous regardless of clock skew. The SDK uses it for pagination (`before` / `after` cursors) and for sorting optimistic-vs-server-echo races: the optimistic local insert can sort to the very end until the server-assigned `sequence` arrives, at which point the dedup-by-id upsert puts it in the right place.
365
+
366
+ ## Cancellation
367
+
368
+ Every method that touches the network accepts an `AbortSignal`. The SDK propagates abort to the underlying `fetch` (and to `XMLHttpRequest` on the progress-enabled upload path). Aborted requests throw `DOMException('AbortError')` — they are **not** retried.
369
+
370
+ ```ts
371
+ const controller = new AbortController();
372
+ const promise = chat.messages.one(id).replies({ limit: 100 }, controller.signal);
373
+ // later:
374
+ controller.abort();
375
+ ```
376
+
377
+ ## Environments
378
+
379
+ - **Browsers (modern)** — works out of the box.
380
+ - **Node ≥ 18** — uses the global `fetch` and `WebSocket`. Upload progress is browser-only (silently no-ops in Node).
381
+ - **React Native** — works on RN ≥ 0.72 (`fetch` + `WebSocket` are built in). The `phoenix` client is bundled.
382
+ - **Bun / Deno** — works; same caveat on upload progress.
383
+ - **Web Workers** — works for REST; sockets work where `WebSocket` is available.
384
+
385
+ ## Exports
386
+
387
+ The package exports the `Poolse` class, the resource and channel classes (`ConversationsResource`, `ConversationHandle`, `MessagesResource`, `MessageHandle`, `AttachmentsResource`, `AttachmentHandle`, `MeResource`, `UsersResource`, `PoolseRealtime`, `ConversationChannel`, `UserChannel`), all error classes, every interface from the wire protocol (`Message`, `Conversation`, `Membership`, `User`, `Attachment`, etc.), the `RealtimeStatus` union, the `POOLSE_API_URL` default, and a `version` constant for diagnostics.
388
+
389
+ ## Links
390
+
391
+ - Full docs — <https://poolse.dev/docs>
392
+ - Source — <https://github.com/poolse-hq/js-sdk>
393
+ - Issues — <https://github.com/poolse-hq/js-sdk/issues>
394
+
395
+ ## License
396
+
397
+ MIT