@poolse/sdk 2.26.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/LICENSE +206 -21
- package/README.md +86 -350
- package/dist/index.cjs +101 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -15
- package/dist/index.d.ts +66 -15
- package/dist/index.js +101 -12
- package/dist/index.js.map +1 -1
- package/package.json +12 -11
package/README.md
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
# `@poolse/sdk`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The headless TypeScript client for [poolse](https://poolse.dev): REST, the
|
|
4
|
+
realtime WebSocket, rooms and call media on the web. No UI and no framework.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
If you use React, [`@poolse/react`](https://www.npmjs.com/package/@poolse/react)
|
|
7
|
+
(hooks) and [`@poolse/react-ui`](https://www.npmjs.com/package/@poolse/react-ui)
|
|
8
|
+
(components) sit on top of this package.
|
|
6
9
|
|
|
7
|
-
|
|
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
|
+
Full reference: <https://poolse.dev/docs/sdk/sdk>
|
|
10
11
|
|
|
11
12
|
## Install
|
|
12
13
|
|
|
@@ -14,384 +15,119 @@ If you're using React, you'll usually want [`@poolse/react`](https://www.npmjs.c
|
|
|
14
15
|
npm install @poolse/sdk
|
|
15
16
|
```
|
|
16
17
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
## Authentication model
|
|
18
|
+
`phoenix` (the Phoenix Channels client) is a dependency and installs with it.
|
|
20
19
|
|
|
21
|
-
|
|
20
|
+
Requirements: a global `fetch` for REST (browsers, React Native, Deno, Bun,
|
|
21
|
+
Node 18+) and a global `WebSocket` for realtime (browsers, React Native,
|
|
22
|
+
Deno, Bun, Node 22+). On older Node, set `globalThis.WebSocket` before the
|
|
23
|
+
first realtime call. Upload progress needs `XMLHttpRequest` (browsers only).
|
|
22
24
|
|
|
23
|
-
|
|
24
|
-
┌────────────┐ API key ┌─────────┐ user JWT ┌─────────────┐
|
|
25
|
-
│ your │ ────────▶ │ poolse │ ─────────▶ │ your │
|
|
26
|
-
│ backend │ │ REST │ │ frontend │
|
|
27
|
-
│ (mints │ │ │ │ (this SDK) │
|
|
28
|
-
│ JWTs) │ ◀──────── │ │ ◀───────── │ │
|
|
29
|
-
└────────────┘ └─────────┘ └─────────────┘
|
|
30
|
-
```
|
|
25
|
+
## Authentication
|
|
31
26
|
|
|
32
|
-
|
|
27
|
+
The SDK acts as one end user, with a short-lived JWT that your backend mints
|
|
28
|
+
with its API key (`POST /v1/users/:user_id/tokens`). Never ship an API key to
|
|
29
|
+
a client. The SDK calls your `getToken` when it needs a JWT, caches it until
|
|
30
|
+
30 seconds before it expires, and asks again once after a 401.
|
|
33
31
|
|
|
34
32
|
## Quick start
|
|
35
33
|
|
|
36
34
|
```ts
|
|
37
35
|
import { Poolse } from '@poolse/sdk';
|
|
38
36
|
|
|
39
|
-
const
|
|
40
|
-
apiUrl: 'https://api.poolse.dev', // optional; this is the default
|
|
37
|
+
const poolse = new Poolse({
|
|
41
38
|
getToken: async () => {
|
|
42
39
|
const res = await fetch('/api/chat-token', { method: 'POST' });
|
|
43
40
|
const { token } = await res.json();
|
|
44
|
-
return token;
|
|
41
|
+
return token;
|
|
45
42
|
},
|
|
46
43
|
});
|
|
47
44
|
|
|
48
|
-
|
|
49
|
-
const
|
|
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 });
|
|
45
|
+
const { data: conversations } = await poolse.conversations.list();
|
|
46
|
+
const conv = poolse.conversations.one(conversations[0].id);
|
|
53
47
|
await conv.messages.send({ body: 'Hello' });
|
|
54
48
|
|
|
55
|
-
|
|
56
|
-
const
|
|
57
|
-
const off = live.onMessage((msg) => console.log('new', msg));
|
|
49
|
+
const live = poolse.realtime.conversation(conv.id);
|
|
50
|
+
const off = live.onMessage((msg) => console.log(msg.body));
|
|
58
51
|
|
|
59
|
-
// Clean up when you're done.
|
|
60
52
|
off();
|
|
61
|
-
|
|
53
|
+
poolse.destroy();
|
|
62
54
|
```
|
|
63
55
|
|
|
64
56
|
## Configuration
|
|
65
57
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
|
69
|
-
|
|
|
70
|
-
| `
|
|
71
|
-
| `
|
|
72
|
-
| `
|
|
73
|
-
| `
|
|
74
|
-
| `
|
|
75
|
-
| `
|
|
76
|
-
| `
|
|
77
|
-
| `
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
`
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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.
|
|
58
|
+
| Field | Default | Meaning |
|
|
59
|
+
| -------------------------------- | --------------------------- | ---------------------------------------------------------------------- |
|
|
60
|
+
| `getToken` | required | `() => Promise<string \| null> \| string \| null` |
|
|
61
|
+
| `apiUrl` | `https://api.poolse.dev` | API origin, without `/v1`. |
|
|
62
|
+
| `wsUrl` | `apiUrl` with `http` → `ws` | Socket origin. |
|
|
63
|
+
| `socketPath` | `/socket` | |
|
|
64
|
+
| `fetch` | `globalThis.fetch` | |
|
|
65
|
+
| `maxRetries` | `3` | Retries for network errors, 5xx and 429. |
|
|
66
|
+
| `baseBackoffMs` / `maxBackoffMs` | `250` / `30000` | Backoff. |
|
|
67
|
+
| `generateIdempotencyKey` | `safeUuid` | |
|
|
68
|
+
| `onSocketError` | — | `(err: Error) => void` |
|
|
69
|
+
| `userResolver` | — | `(externalId) => { displayName, avatarUrl? } \| null` (sync or async). |
|
|
70
|
+
|
|
71
|
+
## What's in it
|
|
72
|
+
|
|
73
|
+
| Member | Covers |
|
|
74
|
+
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
75
|
+
| `poolse.me` | `show`, `update({ read_receipts })`, `peek`, `onChange` |
|
|
76
|
+
| `poolse.conversations` | `list`, `create`, `one(id)` → `show`, `update`, `listMembers`, `addMembers`, `addMember`, `removeMember(userId)`, `messages.list / send / markRead` |
|
|
77
|
+
| `poolse.messages` | `one(id)` → `update`, `delete`, `replies`, `addReaction`, `removeReaction` |
|
|
78
|
+
| `poolse.attachments` | `upload`, `requestUpload`, `one(id)` → `downloadUrl`, `delete` |
|
|
79
|
+
| `poolse.users` | Cache over `userResolver`: `get`, `peek`, `subscribe`, `invalidate`, `invalidateAll` |
|
|
80
|
+
| `poolse.devices` | `register`, `unregister` (push tokens) |
|
|
81
|
+
| `poolse.liveCalls` | `get(conversationId)` |
|
|
82
|
+
| `poolse.rooms` | `start`, `ring`, `leave` |
|
|
83
|
+
| `poolse.callTokens` | `create(conversationId)` |
|
|
84
|
+
| `poolse.call(conversationId, { livekit, … })` | `CallRoom`: call media on the web (pass your `livekit-client` import) |
|
|
85
|
+
| `poolse.realtime` | `conversation(id)`, `user(id)`, `leave`, `getStatus`, `onStatus`, `connect`, `pause`, `resume`, `disconnect` |
|
|
86
|
+
| `poolse.rest.request({ method, path, … })` | Any endpoint, with the same auth, retries and idempotency |
|
|
87
|
+
|
|
88
|
+
Conversation channels emit `onMessage`, `onMessageUpdated`,
|
|
89
|
+
`onMessageDeleted`, `onTypingStart`, `onTypingStop`, `onReactionAdded`,
|
|
90
|
+
`onReactionRemoved`, `onMemberRead`, `onCallStarted`, `onCallParticipants`,
|
|
91
|
+
`onCallFinished`, `onPresenceState`, `onPresenceDiff` and `onClosed`, and
|
|
92
|
+
have `sendTyping()` and `getPresenceState()`. The user channel emits
|
|
93
|
+
`onMention`, `onConversationCreated`, `onConversationUpdated`, `onRingEnded`
|
|
94
|
+
(`RingEndedEvent`: `reason` is `answered_elsewhere`, `declined`,
|
|
95
|
+
`cancelled`, `timeout` or `finished`) and `onCallFinished` (with
|
|
96
|
+
`conversation_id`).
|
|
97
|
+
|
|
98
|
+
Events sent while the socket is down aren't replayed; reload from REST when
|
|
99
|
+
`onStatus` reports `connected` again. `realtime.pause()` / `resume()` close
|
|
100
|
+
and reopen the socket while keeping every channel and listener, for an app
|
|
101
|
+
going to the background. `disconnect()` destroys them.
|
|
102
|
+
|
|
103
|
+
A channel the server closes (you were removed from the conversation) fires
|
|
104
|
+
`onClosed` and is dropped, so a later `realtime.conversation(id)` joins
|
|
105
|
+
afresh. After a refused socket handshake (for example a revoked token) the
|
|
106
|
+
SDK fetches a new token from `getToken`, at most every 30 seconds.
|
|
337
107
|
|
|
338
108
|
## Errors
|
|
339
109
|
|
|
340
|
-
All errors extend `PoolseError` and are `instanceof`-checkable:
|
|
341
|
-
|
|
342
110
|
```ts
|
|
343
|
-
import { ApiError, AuthError, RateLimitedError, NetworkError
|
|
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
|
-
}
|
|
111
|
+
import { PoolseError, ApiError, AuthError, RateLimitedError, NetworkError } from '@poolse/sdk';
|
|
358
112
|
```
|
|
359
113
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
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
|
|
114
|
+
`ApiError` (any non-2xx) carries `status`, `code`, `docUrl` and `details`.
|
|
115
|
+
`AuthError` is a 401 after one refresh, `RateLimitedError` a 429 after
|
|
116
|
+
retries (with `retryAfterMs`), `NetworkError` a failed `fetch` (with
|
|
117
|
+
`cause`). Aborted requests reject with the `AbortError` `DOMException`.
|
|
386
118
|
|
|
387
|
-
|
|
119
|
+
Also exported: the call-log helpers (`parseCallLog`, `describeCallLog`,
|
|
120
|
+
`formatCallLogPreview`, …), `safeUuid`, `version`, `POOLSE_API_URL` and every
|
|
121
|
+
wire type (`Conversation`, `Message`, `Membership`, `Attachment`, `Me`, …).
|
|
388
122
|
|
|
389
123
|
## Links
|
|
390
124
|
|
|
391
|
-
-
|
|
392
|
-
-
|
|
393
|
-
-
|
|
125
|
+
- Docs: <https://poolse.dev/docs/sdk/sdk>
|
|
126
|
+
- Migrating to 3.0: <https://poolse.dev/docs/guides/migrating-to-3>
|
|
127
|
+
- Source: <https://github.com/poolse-hq/js-sdk>
|
|
128
|
+
- Issues: <https://github.com/poolse-hq/js-sdk/issues>
|
|
394
129
|
|
|
395
130
|
## License
|
|
396
131
|
|
|
397
|
-
|
|
132
|
+
Licensed under the [poolse SDK License](./LICENSE) from 3.0.0; versions
|
|
133
|
+
before 3.0.0 remain MIT.
|