@poolse/sdk

The headless TypeScript client. It wraps the poolse REST API and the realtime WebSocket. It has no UI and no framework dependency. If you use React, the @poolse/react hooks sit on top of it.

npm install @poolse/sdk

The package depends on phoenix (the Phoenix Channels client), which npm installs with it. It ships ESM and CommonJS builds with type definitions.

Requirements

  • REST needs a global fetch: browsers, React Native, Deno, Bun and Node 18+. You can pass your own with the fetch option.
  • Realtime needs a global WebSocket: browsers, React Native, Deno, Bun and Node 22+. The poolse socket doesn't accept long-polling. On older Node, assign a WebSocket implementation to globalThis.WebSocket before your first realtime call.
  • Upload progress (onProgress) needs XMLHttpRequest, so it only works in browsers. Elsewhere the upload still works but no progress events fire.

Authentication model

The SDK runs as one end user. It authenticates with a short-lived end-user JWT that your backend mints with its API key (POST /v1/users/:user_id/tokens). Never put an API key in client code. See Authentication.

The SDK calls your getToken function when it needs a JWT, caches the result and refreshes it before it expires. See Token caching.

Quick start

import { Poolse } from '@poolse/sdk';

const poolse = new Poolse({
  getToken: async () => {
    const res = await fetch('/api/chat-token', { method: 'POST' });
    const { token } = await res.json();
    return token;
  },
});

const me = await poolse.me.show();
const { data: conversations } = await poolse.conversations.list();

const conv = poolse.conversations.one(conversations[0].id);
const { data: messages } = await conv.messages.list({ limit: 50 });
await conv.messages.send({ body: 'Hello' });

const live = poolse.realtime.conversation(conv.id);
const off = live.onMessage((msg) => console.log('new message', msg.body));

// Later
off();
poolse.destroy();

new Poolse(config)

Create one instance per signed-in user. When the user signs out or you switch tenants, call destroy() and create a new instance.

FieldTypeDefaultMeaning
getToken() => Promise<string | null> | string | nullrequiredReturns an end-user JWT. Return null to send a request without Authorization (the server rejects it). The constructor throws if this isn't a function.
apiUrlstring'https://api.poolse.dev'API origin without /v1. A trailing slash is removed.
wsUrlstringapiUrl with http replaced by wsOrigin of the realtime socket, for deployments where it differs from the API.
socketPathstring'/socket'Path of the realtime socket.
fetchtypeof fetchglobalThis.fetchCustom fetch (tests, polyfills). It is bound to globalThis. The constructor throws if no fetch exists.
maxRetriesnumber3Retries after the first attempt for network errors, 5xx and 429. 0 disables retries.
baseBackoffMsnumber250Base of the exponential backoff.
maxBackoffMsnumber30000Upper bound for one retry delay.
generateIdempotencyKey() => stringsafeUuidGenerates the Idempotency-Key for non-GET requests.
onSocketError(err: Error) => void—Called on socket errors and when getToken fails before the socket opens. Phoenix keeps reconnecting on its own.
userResolver(externalId: string) => Promise<PoolseUserProfile | null> | PoolseUserProfile | null—Maps your user id (external_id) to { displayName, avatarUrl? }. Used by poolse.users and every UI component.

POOLSE_API_URL is exported as the constant 'https://api.poolse.dev'.

Instance members

MemberTypeWhat it is
meMeResourceThe signed-in user. →
conversationsConversationsResourceConversations, members, messages. →
messagesMessagesResourceOperations on one message by id. →
attachmentsAttachmentsResourceUploads and downloads. →
usersUsersResourceCache over your userResolver. →
devicesDevicesResourcePush tokens for phones. →
liveCallsLiveCallsResourceWhether a call or room is live on a conversation. →
roomsRoomsResourceStart, ring and leave rooms. →
callTokensCallTokensResourceSFU credentials for call media. →
realtimePoolseRealtimeThe WebSocket and its channels. →
restRestClientLow-level request method. →
call(conversationId, opts)CallRoomCall media on the web. →
destroy()voidCloses the socket and drops every channel.

destroy() only closes realtime. It doesn't clear the token cache or the users cache; drop the instance after calling it.

REST behaviour

These rules apply to every REST method below.

  • Return values. Each method resolves with the parsed JSON body, or undefined/null for 204 No Content.
  • Cancellation. Methods take an AbortSignal: as the last argument, or as { signal } inside the options object where the signature says so. An aborted request rejects with the original DOMException named AbortError. It isn't wrapped and isn't retried.
  • Retries. Network errors, 5xx responses and 429 responses are retried up to maxRetries times (so up to 4 attempts by default). The delay is a random value between 0 and min(maxBackoffMs, baseBackoffMs × 2^attempt). On 429 the SDK waits at least the Retry-After header (seconds) when the server sends one. Other 4xx responses throw at once.
  • 401. On the first 401 the SDK drops its cached token, calls getToken again and retries once. A second 401 throws AuthError. This retry doesn't count against maxRetries.
  • Idempotency. Every POST, PATCH, PUT and DELETE carries an Idempotency-Key header. A retry reuses the same key, so the server replays the first 2xx response instead of doing the work twice. The server keeps 2xx responses for 24 hours per tenant, caller, method, path and key. Error responses aren't kept, so a retry after a 4xx runs again.
  • Errors. Non-2xx responses throw one of the error classes.

poolse.me

The end user the JWT belongs to. MeResource remembers the last user it fetched, so every screen sees a change at once.

me.show(signal?)

GET /v1/me. Resolves with Me and notifies onChange listeners.

interface Me {
  id: string;            // poolse user id (uuid)
  tenant_id: string;
  external_id: string;   // your id for this user
  display_name: string | null;
  custom_data: Record<string, unknown>;
  is_blocked: boolean;
  inserted_at: string;
  updated_at: string;
  read_receipts?: ReadReceiptsState; // absent on older servers: treat as on
}

interface ReadReceiptsState {
  mode: 'on' | 'off' | 'user'; // the workspace setting
  shared: boolean;              // others see when this user reads
  can_change: boolean;          // true only in 'user' mode
  visible: boolean;             // this user sees other people's read state
}

me.update(body, signal?)

PATCH /v1/me. body is UpdateMeRequest:

FieldTypeMeaning
read_receiptsbooleanShare this user's read receipts. Only accepted while read_receipts.can_change is true; otherwise the server answers 409 read_receipts_fixed. Turning it off also hides other people's receipts from this user.

Resolves with the updated Me and notifies onChange listeners.

me.peek()

Returns the last Me that show or update returned, or null before the first call. It doesn't make a request.

me.onChange(fn)

Calls fn(me) every time show or update returns. Returns an unsubscribe function.

poolse.conversations

conversations.list(signal?)

GET /v1/conversations. Resolves with { data: Conversation[] }: every conversation the user is a member of. Only this method fills in unread_count and member_external_ids reliably.

conversations.create(attrs, signal?)

POST /v1/conversations. The caller becomes the conversation's owner. Resolves with the new Conversation. attrs is ConversationCreateRequest:

FieldTypeMeaning
type'direct' | 'group'Required.
namestring | nullDisplay name, mostly for groups.
avatar_urlstring | null
member_limitnumber | nullMaximum members; null uses the workspace default.
member_external_idsstring[]Your user ids to add as members. Ids poolse hasn't seen yet are created as users, up to 50 new users per hour per caller; past that the server answers 429 lazy_provision_rate_limited.
custom_dataRecord<string, unknown>Your own JSON, stored as is.
settingsRecord<string, unknown>

For a direct conversation with exactly one other member: if a direct conversation between the two users already exists, the server returns it instead of creating a second one.

conversations.one(id)

Returns a ConversationHandle for one conversation. It makes no request.

const conv = poolse.conversations.one(conversationId);
conv.id; // the id you passed

ConversationHandle

MethodRequestResolves with
show(signal?)GET /v1/conversations/:idConversation
update(attrs, signal?)PATCH /v1/conversations/:idConversation
listMembers(signal?)GET /v1/conversations/:id/members{ data: Membership[] }
addMembers(externalIds, opts?)POST /v1/conversations/:id/members with { external_ids, role? }{ data: Membership[] }
addMember(externalId, opts?)same, with one idMembership
removeMember(userId, signal?)DELETE /v1/conversations/:id/members/:user_idnothing
messages—ConversationMessages (below)
  • update(attrs) takes ConversationUpdateRequest: name, avatar_url, member_limit, custom_data, settings, all optional.
  • opts for addMembers / addMember is AddMemberOptions: { role?: 'owner' | 'admin' | 'member'; signal?: AbortSignal }. The role defaults to member on the server. Adding members needs the caller to be an owner or admin of the conversation. Unknown external ids are created as users, with the same 50-per-hour limit as create.
  • removeMember takes the member's poolse user id (Membership.user_id), not your external id. The useMembers hook does the lookup for you.

There is no API to delete a conversation.

ConversationMessages (handle.messages)

messages.list(opts?, signal?)

GET /v1/conversations/:id/messages. Resolves with { data: Message[] }, newest first.

OptionTypeDefaultMeaning
limitnumber50Page size. The server caps it at 100.
beforenumber—Only messages with sequence lower than this. Pass the oldest sequence you have to load the previous page.

The list leaves out thread replies (they come from replies) and deleted messages.

messages.send(attrs, signal?)

POST /v1/conversations/:id/messages. Resolves with the created Message.

FieldTypeMeaning
bodystring | nullText. May be empty or omitted only when attachment_ids is non-empty; a blank body with no attachments fails with 422 validation_failed.
type'text' | 'system' | 'custom'Defaults to text. A custom body must be valid JSON.
reply_to_idstringMakes this a thread reply. The server sets thread_root_id to the parent's root (or the parent itself).
quoted_message_idstringQuote a message from the same conversation. The new message stays in the main list.
mentionsstring[]poolse user ids of members to mention. Every id must be a member.
attachment_idsstring[]Ids from attachments.upload. At most 10, no duplicates. Linking marks them ready.
idstringClient-generated message id. If you omit it, the SDK generates one.

The message id is also what makes a send safe to retry: sending the same id again returns the original message. The realtime message:new event carries the same id, so an optimistic row can be matched by id.

messages.markRead(messageId, signal?)

POST /v1/conversations/:id/read with { message_id }. Moves the caller's read cursor to that message. Other members get a member:read event. See Read receipts & unread.

poolse.messages

messages.one(id)

Returns a MessageHandle for one message (handle.id is the id). It makes no request.

MessageHandle

MethodRequestResolves with
update({ body }, signal?)PATCH /v1/messages/:idMessage
delete(signal?)DELETE /v1/messages/:idnothing (soft delete)
replies(opts?, signal?)GET /v1/messages/:id/replies{ data: Message[] }, oldest first
addReaction(emoji, signal?)POST /v1/messages/:id/reactions with { emoji }Message
removeReaction(emoji, signal?)DELETE /v1/messages/:id/reactions/:emoji (URL-encoded)Message

replies options: limit (default 500, capped at 1000 by the server) and after (only replies with a higher sequence). The root message isn't in the result, and deleted replies are left out.

poolse.attachments

Files go straight from the client to storage (poolse's, or your own bucket) with a presigned URL; the bytes don't pass through the API server. The full flow is in the Attachment uploads guide.

attachments.upload(input, opts?)

Requests an upload URL, then PUTs the bytes to it. Resolves with the Attachment row. Send a message with its id in attachment_ids to use it.

input is AttachmentUploadInput:

FieldTypeMeaning
bodyBodyInitThe bytes: a File or Blob in browsers; a Uint8Array, ArrayBuffer or other value your fetch accepts elsewhere.
contentTypestringMIME type. It is signed into the upload URL, so the PUT must use it.
byteSizenumberThe real size in bytes. Counted against plan limits. If the stored file turns out larger, sending a message with it fails with 422 send_failed.
filenamestringOptional. Kept as original_filename.

opts is AttachmentOptions:

FieldTypeMeaning
signalAbortSignalCancels the request and the PUT.
onProgress(e: { loaded: number; total: number }) => voidUpload progress (AttachmentProgressEvent). When set and XMLHttpRequest exists, the PUT uses XHR; otherwise it uses fetch and the callback never fires.

A failed PUT rejects with a plain Error whose message starts with Poolse: presigned upload PUT failed. The row is returned with status: 'pending'; it becomes ready when a message links it. Rows that are never linked are deleted after 24 hours.

attachments.requestUpload(attrs, opts?)

POST /v1/attachments/upload-url. The low-level first step, for when you want to do the PUT yourself. attrs is { content_type: string; byte_size: number; original_filename?: string }. Resolves with:

interface AttachmentUploadResponse {
  attachment: Attachment;
  upload: {
    url: string;                     // presigned PUT URL, valid for 15 minutes
    method: 'put';
    headers: Record<string, string>; // send these on the PUT
  };
}

attachments.one(id)

Returns an AttachmentHandle:

MethodRequestResolves with
downloadUrl(opts?)GET /v1/attachments/:id/download-url{ url: string; method: 'get' }. The URL is valid for one hour. While the attachment is pending only the uploader may fetch it; once linked, any member of its conversation.
delete(opts?)DELETE /v1/attachments/:idnothing. Allowed for the uploader while pending; once linked, for the message's sender or a conversation owner or admin.

opts is { signal? }.

poolse.users

A cache over your config.userResolver. poolse doesn't store names or avatars for the UI; your resolver supplies them. All methods take your external id.

MethodReturnsBehaviour
get(externalId)Promise<PoolseUserProfile | null>Returns the cached profile, or calls the resolver once. Concurrent calls for the same id share one call. With no resolver, resolves null. If the resolver throws, the error is logged with console.error and the id is cached as null.
peek(externalId)PoolseUserProfile | null | undefinedCache only. undefined means not fetched yet; null means the resolver returned nothing.
subscribe(externalId, listener)() => voidlistener() runs when that id's entry changes. Returns an unsubscribe function.
invalidate(externalId)voidDrops one entry; the next get calls the resolver again.
invalidateAll()voidDrops every entry (for example after a bulk rename).
interface PoolseUserProfile {
  displayName: string;
  avatarUrl?: string | null;
}

poolse.devices

Push tokens for phones, so poolse can ring a call or show a notification when the app isn't running. On a phone, @poolse/native is what receives the pushes. See Push notifications.

devices.register(body, signal?)

POST /v1/devices. Idempotent: call it on every launch and whenever the token changes. Resolves with Device (the token itself isn't echoed).

FieldTypeMeaning
tokenstringRequired. iOS: the PushKit VoIP token or the regular APNs token. Android: the FCM token.
platform'ios' | 'android'Required.
environment'production' | 'sandbox'APNs environment the token belongs to. Defaults to production on the server. A debug build's token is sandbox.
kind'voip' | 'alert'iOS only. voip (the default) for the PushKit token, which only carries incoming calls; alert for the regular APNs token, used for chat notifications and missed calls. Register both. Leave it out on Android.
interface Device {
  id: string;
  tenant_id: string;
  user_id: string;
  platform: 'ios' | 'android';
  environment: 'production' | 'sandbox';
  kind: 'voip' | 'alert';
  last_registered_at: string | null;
  inserted_at: string;
  updated_at: string;
}

devices.unregister(token, signal?)

DELETE /v1/devices/:token. Call it on sign-out, or the phone keeps receiving pushes for that user.

poolse.liveCalls

liveCalls.get(conversationId, signal?)

GET /v1/conversations/:id/call. Resolves with the LiveCall running on the conversation, or null when there is none. Use it for a "Join" banner when a screen opens; live changes arrive as call:* events on the conversation channel.

interface LiveCall {
  id: string;
  conversation_id: string;
  conversation_name: string | null;
  media: 'audio' | 'video';
  kind?: 'call' | 'room';     // 'room' rang nobody; absent on older servers: 'call'
  state: 'live' | 'finished';
  started_by: LiveCallMember;
  started_at: string | null;
  ended_at: string | null;
  participants: LiveCallMember[];  // who is in it right now
  ring_states: Record<string, 'ringing' | 'answered' | 'declined' | 'missed'>; // by user id
  video_allowed?: boolean;    // false: hide the camera button
  max_participants?: number;  // one more is refused with call_full
}

interface LiveCallMember {
  user_id: string;
  external_id: string | null;
  display_name: string | null;
}

poolse.rooms

A room is a conversation's drop-in call: members join and leave while the chat carries on, and nobody's phone rings. There is one room per conversation. A room ends by itself once it has been empty for a short time. See Calls & rooms.

MethodRequestBehaviour
start(conversationId, media = 'audio', signal?)POST /v1/conversations/:id/room with { media }Starts the room, or joins whatever is already live there (a ringing call included).
ring(conversationId, media = 'audio', signal?)POST /v1/conversations/:id/calls with { media }Like start, but rings the other members' phones. Joins what is live instead, like start.
leave(session)POST /v1/calls/:id/hangup, authorized with session.control_tokenLeaves. It never ends the room for the others.

start and ring resolve with RoomSession:

interface RoomSession {
  cv: number;
  created: boolean;   // true when this request started it
  call: LiveCall;
  livekit: { url: string; token: string };  // SFU credentials for you
  control_token: string;                    // authorizes leave()
}

rooms only manages membership. To send and receive audio and video, connect the media with poolse.call, or use useRoom, which does both.

poolse.callTokens

callTokens.create(conversationId, signal?)

POST /v1/conversations/:id/call-token. Resolves with SFU credentials, or null when the deployment has no SFU (the server answers 503). Other errors throw as ApiError. The server only issues them to members of the conversation, and only while a call or room is live on it: start one first with rooms.start / rooms.ring, or a call from a phone, or this throws 409 no_live_call. When the month's call minutes for the live call's medium are used up it throws 402 call_minutes_exhausted.

interface CallConnection {
  url: string;
  token: string;
  room: string;
  expires_at: number;
}

You normally don't call this yourself; poolse.call uses it.

Rooms and call media on the web

poolse.rooms decides who is in a room. The audio and video go through an SFU (LiveKit). CallRoom connects to it. Phones carry calls in @poolse/native instead.

Install livekit-client yourself and pass the module in. The SDK can't import it for you, because React Native bundles would then lose it.

npm install livekit-client

poolse.call(conversationId, opts)

Returns a CallRoom for the conversation's call media. A call or room must be live on the conversation before join() (see callTokens.create): register it with rooms.start first, as below. opts is CallRoomOptions (tokenProvider is optional here and defaults to callTokens.create(conversationId)):

OptionTypeDefaultMeaning
livekitLiveKitModulerequiredimport * as livekit from 'livekit-client'.
tokenProvider() => Promise<CallConnection | null>callTokens.createWhere SFU credentials come from. null means no SFU.
videobooleanfalsePublish the camera when joining.
mutedbooleanfalseJoin with the microphone off.
facing'user' | 'environment''user'Which camera opens first.
aloneGraceMsnumber1500How long you may be alone, after someone else was there, before onAlone fires. 0 turns it off.
import * as livekit from 'livekit-client';

const session = await poolse.rooms.start(conversationId, 'video');
const media = poolse.call(conversationId, { livekit, video: true });
const connected = await media.join();   // false: no SFU on this deployment
media.onParticipants((people) => render(people));

// Later
media.leave();
await poolse.rooms.leave(session);

CallRoom

You can also construct one with new CallRoom(options), passing every CallRoomOptions field, tokenProvider included.

MemberReturnsBehaviour
join()Promise<boolean>Connects, publishes the microphone (and the camera if video), starts audio playback. Resolves true when connected, false when there is no SFU. Rejects if getting a token or connecting fails (status becomes error). Calling join again on a connected room adds a holder and resolves true.
leave()voidRemoves one holder. Disconnects when none are left.
getStatus()CallRoomStatus'idle' | 'connecting' | 'connected' | 'error'.
onStatus(fn)unsubscribeStatus changes.
getParticipants()CallParticipant[]You first, then everyone else. Empty when not connected.
onParticipants(fn)unsubscribeFires with the full list on every change.
onError(fn)unsubscribeErrors such as a camera that can't open or a device switch the browser refused.
onAlone(fn)unsubscribeEveryone else has left (after aloneGraceMs). Fires only after someone else has been on the call. It doesn't hang up for you.
setMicrophoneEnabled(on)Promise<void>Mute or unmute.
setCameraEnabled(on)Promise<void>Turn the camera on or off. Off stops publishing.
switchCamera()Promise<void>Swap front and rear cameras. Does nothing while the camera is off.
getFacingMode()CameraFacing'user' or 'environment'.
isMicrophoneEnabled() / isCameraEnabled()boolean
listDevices(kind)Promise<CallDevice[]>Microphones (audioinput), cameras (videoinput) or outputs (audiooutput). Labels are empty until the page has media permission.
getActiveDevice(kind)string | undefinedDevice id in use.
setActiveDevice(kind, deviceId)Promise<void>Switch device. Choosing an audiooutput fails on browsers without setSinkId; that is reported through onError.
onDevices(fn)unsubscribeDevices were plugged in or removed.
getSelfId()string | nullYour SFU identity (your poolse user id) once connected.
interface CallParticipant {
  userId: string;           // poolse user id
  name?: string;
  isSelf: boolean;
  micEnabled: boolean;
  cameraEnabled: boolean;
  speaking: boolean;
  videoTrack: LiveKitTrack | null;               // attach to a <video> element
  videoTrackRef: LiveKitTrackReference | null;   // for LiveKit's React Native <VideoTrack>
}

interface CallDevice {
  deviceId: string;
  kind: 'videoinput' | 'audioinput' | 'audiooutput';  // CallDeviceKind
  label: string;
}

Types for the LiveKit boundary. LiveKitModule, CheckedLiveKitModule, LiveKitRoomHandle, LiveKitParticipant, LiveKitPublication, LiveKitTrack, LiveKitLocalVideoTrack and LiveKitTrackReference are structural types. They describe the parts of livekit-client the SDK uses, so the SDK has no hard dependency on a LiveKit version. You don't create them; you pass the real livekit-client module and receive its tracks. LiveKitTrack has optional attach() and detach() methods (from livekit-client) for putting a track into a media element.

CallMedia is 'audio' | 'video', the media a call opens with.

Realtime

poolse.realtime is a PoolseRealtime: one WebSocket per Poolse instance, carrying one channel per conversation plus the user's own channel. The wire protocol is described in Socket & channels.

  • The socket opens on the first conversation() or user() call. Before that nothing connects.
  • Asking for the same conversation twice returns the same handle.
  • Channels you subscribe to before the socket is open are joined when it opens.
  • If the connection drops, Phoenix reconnects and rejoins every channel except those the server closed (see ConversationChannel). It reads the token again on each connect.
  • When the server refuses the handshake (for example because the cached token was revoked), the SDK asks getToken for a fresh token, at most once every 30 seconds, and the next reconnect uses it (3.1). A network outage triggers the same refresh.
  • The server closes all of a user's sockets when the user is blocked or one of their tokens is revoked. The SDK then reconnects as after any drop. A device whose token is still valid reconnects at once; one whose token was revoked recovers as soon as your backend gives it a new token. A blocked user's reconnects keep being refused.
  • Events sent while the socket was down are not replayed. Reload from REST after a reconnect: watch onStatus for connected. The React hooks useMessages, useConversations and useLiveCall already do this.

PoolseRealtime

MethodReturnsBehaviour
conversation(conversationId)ConversationChannelOpens the socket if needed and joins conversation:<id>. Only members can join.
user(userId)UserChannelJoins user:<id>. Pass me.id (the poolse user id); the server refuses anyone else's. Returns the existing handle if one is open.
leave(conversationId)voidLeaves one conversation channel and drops its listeners.
getStatus()RealtimeStatusSee below.
onStatus(fn)UnsubscribeStatus changes.
connect()voidOpens the socket. Idempotent; the methods above call it for you.
pause()voidCloses the socket but keeps every channel handle and its listeners. Status becomes closed. Does nothing if the socket was never opened or is already paused. (3.1)
resume()voidReopens a paused socket. It first gets a token (from cache or getToken), then connects; Phoenix rejoins the channels and your listeners keep working. Status goes connecting → connected. Does nothing unless paused. (3.1)
disconnect()voidCloses the socket and destroys every channel handle and listener. Use it on sign-out, through poolse.destroy(). Handles you held are dead afterwards. Calling conversation() later opens a fresh socket.

RealtimeStatus is 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed': idle before the first connect, reconnecting after an unexpected drop or a socket error, closed after pause() or disconnect().

When to pause. Use pause() when your app goes to the background and resume() when it comes back. On React Native, useAppStateLifecycle does this for you. While paused, nothing arrives over the socket. On phones, poolse's push notifications cover that gap.

import { AppState } from 'react-native';

AppState.addEventListener('change', (state) => {
  if (state === 'background') poolse.realtime.pause();
  else if (state === 'active') poolse.realtime.resume();
});

ConversationChannel

Returned by realtime.conversation(id). channel.conversationId holds the id. Every on… method returns an Unsubscribe function (() => void).

MethodEventPayload
onMessage(fn)message:newMessage (MessageNewEvent). Thread replies arrive here too, with thread_root_id set.
onMessageUpdated(fn)message:updatedMessage (MessageUpdatedEvent)
onMessageDeleted(fn)message:deleted{ id, conversation_id, deleted_at: string | null } (MessageDeletedEvent)
onTypingStart(fn)typing:start{ user_id, external_id: string | null } (TypingEvent)
onTypingStop(fn)typing:stopsame
onReactionAdded(fn)reaction:added{ message_id, conversation_id, emoji, user_id } (ReactionEvent)
onReactionRemoved(fn)reaction:removedsame
onMemberRead(fn)member:read{ user_id, conversation_id, last_read_message_id, last_read_at } (MemberReadEvent)
onCallStarted(fn)call:started{ cv, call: LiveCall } (CallStartedEvent)
onCallParticipants(fn)call:participants{ cv, call_id, participants: string[] }: user ids in the call now (CallParticipantsEvent)
onCallFinished(fn)call:finished{ cv, call_id, ended_at?, duration_ms?, joined_user_ids?, reason?, conversation_id? }; reason is finished, declined_all, busy_all, no_answer or cancelled (CallFinishedEvent). conversation_id is only set on the user-channel copy.
onPresenceState(fn)presence_statePresenceSnapshot. If the snapshot already arrived, fn is called with it immediately.
onPresenceDiff(fn)presence_diff{ joins, leaves }, each a PresenceSnapshot.
onClosed(fn)channel closedNo payload. The channel closed for good: the server removed you from the conversation, or leave() / disconnect() was called. (3.1)
type PresenceSnapshot = Record<string /* user id */, {
  metas: Array<{ phx_ref: string; online_at: number; external_id?: string }>;
}>;

Other methods:

  • getPresenceState() returns the current presence snapshot, with diffs applied.
  • sendTyping() tells the others you are typing. It sends on every call; the server rate-limits it per user and conversation. Call it as the user types and throttle it yourself (the React useTyping hook sends at most every 500 ms). The server sends typing:stop for you when you send a message.

When the user is removed from the conversation, the server closes their channel at once. From 3.1 the handle fires onClosed and is dropped from the SDK's cache. It receives no more events and isn't rejoined after a reconnect. The next realtime.conversation(id) returns a fresh handle and joins again, which succeeds once the user is a member again. Code that still holds the old handle keeps it, so use onClosed to resubscribe or clear your UI. The React hooks don't do this for you; they pick up a fresh channel when they remount.

const conv = poolse.realtime.conversation(conversationId);
conv.onMessage(render);
conv.onClosed(() => showRemovedNotice());

There is no markRead on the channel; use messages.markRead over REST.

UserChannel

Returned by realtime.user(me.id). Events for the signed-in user across all conversations.

MethodEventPayload
onMention(fn)mention:new{ message_id, conversation_id, sender_id: string | null } (MentionEvent). Fetch the message over REST for its body.
onConversationCreated(fn)conversation:createdConversation (ConversationCreatedEvent): the user was added to a conversation, including one they created.
onConversationUpdated(fn)conversation:updated{ conversation: Conversation; by_user_id: string | null } (ConversationUpdatedEvent). Fires after every message in any of the user's conversations, carrying the new last_message_preview, last_message_at and last_sequence. by_user_id is the sender.
onRingEnded(fn)call:ring_endedRingEndedEvent (below): your ring for a call is over, so stop ringing on this device. (3.1)
onCallFinished(fn)call:finishedCallFinishedEvent with conversation_id set: a call you were rung for or joined is over. Arrives here even after you left the conversation's channel. (3.1)
interface RingEndedEvent {
  cv: number;
  call_id: string;
  conversation_id: string;
  reason: 'answered_elsewhere' | 'declined' | 'cancelled' | 'timeout' | 'finished';
  device_id?: string;  // the device that resolved it, e.g. the one that answered
}

reason (typed as string):

ValueMeaning
answered_elsewhereYou answered on another device. That device's id is in device_id, so it can ignore the event about itself.
declinedYou declined, on this or another device.
cancelledThe caller hung up before anyone answered.
timeoutNobody answered in time.
finishedThe call ended for any other reason while you were still being rung.

On phones, pass both events to @poolse/native.

channel.userId holds the id you joined with.

poolse.rest

For endpoints the typed methods don't cover. Same token, retry and idempotency behaviour as above.

const result = await poolse.rest.request<MyShape>({
  method: 'GET',            // 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
  path: '/v1/me/calls',     // added to apiUrl
  query: { limit: 20 },     // optional; null and undefined values are dropped
  body: undefined,          // optional; sent as JSON
  idempotencyKey: undefined,// optional; a fresh key by default for non-GET, null to omit
  maxRetries: undefined,    // optional; overrides config.maxRetries
  signal: undefined,        // optional AbortSignal
  bearer: undefined,        // optional; use this token instead of the session JWT (no 401 retry)
});

It resolves with the parsed JSON body (typed as T), not a Response.

Errors

import { PoolseError, ApiError, AuthError, RateLimitedError, NetworkError } from '@poolse/sdk';
ClassExtendsThrown whenFields
PoolseErrorErrorBase class of the others; also used for socket errors passed to onSocketError.message
ApiErrorPoolseErrorAny non-2xx response not covered below, including 5xx after retries.status, code, docUrl, details
AuthErrorApiError401 after the one refresh retry, for example token_revoked or user_blocked.as ApiError, status 401
RateLimitedErrorApiError429 after retries ran out.as ApiError, plus retryAfterMs (0 when the server sent no Retry-After)
NetworkErrorPoolseErrorfetch rejected after retries.cause (the original error)

code is the server's error code, for example validation_failed or not_found. docUrl links to that code on the Errors page. details holds per-field messages for validation errors. If a response has no poolse error body, code is unknown_error.

Not every failure is one of these classes. Aborts reject with the DOMException AbortError, a failed upload PUT rejects with a plain Error, and the constructor throws a plain Error when getToken or fetch is missing.

try {
  await poolse.messages.one(id).update({ body: 'edited' });
} catch (err) {
  if (err instanceof AuthError) signOut();
  else if (err instanceof RateLimitedError) retryLater(err.retryAfterMs);
  else if (err instanceof ApiError) showError(err.code);
  else if (err instanceof NetworkError) showOffline();
  else throw err;
}

Token caching

The SDK keeps the JWT in memory.

  • It decodes the token's exp claim (without verifying the signature) and reuses the token until 30 seconds before it expires.
  • A token that isn't a JWT, or has no exp, is reused for 60 seconds.
  • Concurrent requests that need a token share one getToken call.
  • null is never cached.
  • A 401 drops the cached token (see REST behaviour).

Your getToken should return a fresh token each time it is called. Tokens minted by poolse live for one hour.

Sequence numbers

Each message has a sequence that the server assigns per conversation at insert time. It increases with every message, so you can sort and page by it (before for the main list, after for replies) and use it to de-duplicate.

Wire types

These are exported as TypeScript types and match the JSON the API returns.

type Uuid = string;
type IsoDateTime = string;

interface Conversation {
  id: Uuid;
  tenant_id: Uuid;
  type: 'direct' | 'group';            // ConversationType
  name: string | null;
  avatar_url: string | null;
  created_by_user_id: Uuid | null;
  member_limit: number | null;
  custom_data: Record<string, unknown>;
  settings: Record<string, unknown>;
  last_message_at: IsoDateTime | null;
  last_message_preview: string | null; // first ~80 characters, stored unencrypted
  last_sequence: number;
  unread_count?: number;               // filled in by conversations.list()
  member_external_ids?: string[];      // filled in by conversations.list(); may be empty elsewhere
  inserted_at: IsoDateTime;
  updated_at: IsoDateTime;
}

interface Membership {
  id: Uuid;
  conversation_id: Uuid;
  user_id: Uuid;                       // poolse user id
  external_id: string;                 // your user id
  role: 'owner' | 'admin' | 'member';  // MemberRole
  last_read_message_id: Uuid | null;
  last_read_sequence: number | null;
  last_read_at: IsoDateTime | null;
  inserted_at: IsoDateTime;
  updated_at: IsoDateTime;
}

interface Message {
  id: Uuid;
  tenant_id: Uuid;
  conversation_id: Uuid;
  sender_id: Uuid | null;              // null for system messages
  sender_external_id: string | null;
  type: 'text' | 'system' | 'custom';  // MessageType
  body: string | null;
  reply_to_id: Uuid | null;
  thread_root_id: Uuid | null;
  reply_count?: number;
  quoted_message_id?: Uuid | null;
  quoted_message?: QuotedMessagePreview | null;
  mentions: Uuid[];
  reactions: Record<string /* emoji */, Uuid[] /* user ids */>;
  attachments?: Attachment[];
  edited_at: IsoDateTime | null;
  deleted_at: IsoDateTime | null;
  sequence: number;
  inserted_at: IsoDateTime;
  updated_at: IsoDateTime;
}

interface QuotedMessagePreview {
  id: Uuid;
  sender_id: Uuid | null;
  sender_external_id: string | null;
  body: string | null;                 // trimmed to about 200 characters; null if deleted
  deleted_at: IsoDateTime | null;
  inserted_at: IsoDateTime;
}

interface Attachment {
  id: Uuid;
  tenant_id: Uuid;
  message_id: Uuid | null;             // null while pending
  sender_id: Uuid | null;
  content_type: string;
  byte_size: number;
  sha256: string | null;
  original_filename: string | null;
  status: 'pending' | 'ready';         // AttachmentStatus
  inserted_at: IsoDateTime;
  updated_at: IsoDateTime;
}

interface ErrorEnvelope {
  error: { code: string; message: string; doc_url: string; details?: Record<string, unknown> };
}

Request and list types, also exported:

TypeShape
ConversationList{ data: Conversation[] }
MembershipList{ data: Membership[] }
MessageList{ data: Message[] }
ConversationCreateRequestsee create
ConversationUpdateRequest{ name?, avatar_url?, member_limit?, custom_data?, settings? }
MembershipCreateRequest{ external_ids: string[]; role?: MemberRole }
MessageCreateRequestsee send
MessageUpdateRequest{ body: string }
ReactionRequest{ emoji: string }
ReadRequest{ message_id: Uuid }
AttachmentUploadRequest{ content_type: string; byte_size: number; original_filename?: string }
AttachmentDownloadResponse{ url: string; method: 'get' }
UpdateMeRequest{ read_receipts?: boolean }
RegisterDeviceRequestsee devices.register
DevicePlatform / DeviceEnvironment / DeviceKind'ios' | 'android' / 'production' | 'sandbox' / 'voip' | 'alert'

The resource and channel classes (ConversationsResource, ConversationHandle, ConversationMessages, MessagesResource, MessageHandle, AttachmentsResource, AttachmentHandle, MeResource, UsersResource, DevicesResource, LiveCallsResource, RoomsResource, CallTokensResource, PoolseRealtime, ConversationChannel, UserChannel, CallRoom) are exported for type annotations. Apart from CallRoom, create them through new Poolse(), not directly.

Call-log helpers

When a call or room ends, poolse posts a system message whose body is JSON describing the call. These helpers turn it into display text. The UI packages use them, and so can your own UI.

FunctionReturnsBehaviour
parseCallLog(message)CallLog | nullParses a system or custom message. null for other types, deleted messages and bodies that aren't a call log.
parseCallLogBody(body)CallLog | nullThe same for a raw string, such as last_message_preview.
isCallLogMessage(message)booleanWhether parseCallLog finds a call log.
describeCallLog(log, currentUserId)CallLogDisplay | nullDisplay text for the viewer (currentUserId is the poolse user id). null when the viewer shouldn't see it (a missed-call marker for someone else).
callLogDisplayFor(message, currentUserId)CallLogDisplay | null | undefinedParse and describe in one step. undefined: not a call log; null: hidden for this viewer.
isMessageVisibleTo(message, currentUserId)booleanfalse only for call logs hidden from this viewer. Use it to filter a message list.
formatCallLogPreview(preview, currentUserId)string | nullOne-line text for a conversation list row ("Video call · 3:12"). null when the string isn't a call log, so show it as is.
formatCallDuration(ms)string0:05, 3:12, 1:02:03.
interface CallLogDisplay {
  media: 'audio' | 'video';
  title: string;            // "Outgoing voice call", "Missed video call", …
  detail: string | null;    // "3:12", "No answer", "Declined", …
  missed: boolean;          // show in an error colour
  summary: string;          // short form for previews
  direction: 'outgoing' | 'incoming' | null;
  callBack: boolean;        // worth offering "Call back"
}

type CallLog = CallLogEntry | CallMissedEntry;

interface CallLogEntry {
  kind: 'call';
  callId: string;
  media: 'audio' | 'video';                      // CallLogMedia
  durationMs: number | null;                     // null when nobody answered
  joinedUserIds: string[];
  version: 1 | 2;
  callKind: 'call' | 'room';
  callerUserId: string | null;
  participants: Array<{ userId: string; status: 'joined' | 'declined' | 'busy' | 'missed' }>; // CallParticipantStatus
  endReason: 'finished' | 'declined_all' | 'no_answer' | 'cancelled' | null;                // CallEndReason
  startedAt: number | null;                      // epoch ms
  endedAt: number | null;
}

interface CallMissedEntry {
  kind: 'call_missed';
  callId: string;
  userId: string;           // the person who missed it
  media: 'audio' | 'video' | null;
}

The text is English. To localise, build your own strings from the CallLog.

Other exports

ExportWhat it is
versionThe package version as a string, for diagnostics.
safeUuid()Returns a UUID v4. Uses crypto.randomUUID when present, then crypto.getRandomValues, then Math.random. The SDK uses it for message ids and idempotency keys.
POOLSE_API_URL'https://api.poolse.dev'.
PoolseConfigThe type of the constructor's config.
@poolse/sdk · poolse docs