Skip to content
alzafchat / Developers

Documentation / Integrations

JavaScript SDK

Build your own interface with the headless client.

Integration guide
On this pageAttachments and emojiPending sends and navigationLogin, renewal and logoutHost project AGENTS.md

Use the SDK when you own the chat interface. Install the local workspace package with pnpm; restricted GitHub Packages publication requires the release workflow. Build SDK before consumers: pnpm --filter @alzaf-it/chat-sdk build.

ts
import { ChatClient, createMessageId } from '@alzaf-it/chat-sdk';
const client = new ChatClient({
  apiBaseUrl: 'https://chat.example.com/api/chat',
  token: async () => obtainCurrentUserToken(),
  authEndpoint: 'https://chat.example.com/api/broadcasting/auth',
  reverb: { key: 'public-app-key', host: 'chat.example.com', port: 443, scheme: 'https' }
});
const me = await client.me();
const conversations = await client.listConversations();
const conversation = conversations[0];
if (conversation) {
  const history = await client.messages(conversation.id, { limit: 100 });
  const stop = await client.subscribe(conversation.id, me.service_id, message => renderMessage(message));
  const retryId = createMessageId();
  await client.sendMessage(conversation.id, 'Hello', retryId);
  // Retry a failed operation with retryId. Unsubscribe when leaving the screen.
  stop();
}
client.disconnect();

obtainCurrentUserToken and renderMessage are your host functions, not SDK exports. The runnable HTML example implements a token input for local demonstration. Production identity is established server-side; browser role/service/provider values never authorize access.

Methods: me, providers, listConversations, createConversation, messages, messagesPage, sendMessage, join, markRead, setStatus, show, uploadAttachment, presignAttachment, confirmAttachment, putToStorage, subscribe, subscribeInbox, subscribeProvider, disconnect. API responses are unwrapped from data. ChatError exposes status and optional validation details; network failures remain transport errors. Do not retry 401/403 indefinitely. For retry, preserve the original message body and ID.

messages accepts after_id, before_id, limit; custom UI owns pagination. Use mergeMessages to deduplicate history and events. ChatSession provides shared ready-made inbox behavior via listen/start/open/create/send/join/loadEarlier/close. Listener cleanup does not disconnect a host-owned client. To send a structured card from a custom interface, pass the optional sidecar to sendMessage(id, body, clientMessageId, card) or use ChatSession.stageCard/clearStagedCard/suggestCard; the isMessageCard, cardView and cardBodyText helpers render it safely. See message cards.

Attachments and emoji#

Messages carry attachments: Attachment[] | null with Attachment = {id, kind: "image"|"file", name, mime, size, url}. Use messageAttachments(message) to get a non-null list and attachmentSizeText(size) for the chip label; url is short-lived (re-fetch history to refresh it) and name/mime are untrusted display strings. Images may be shown inline; every other kind should be presented as a named download, not rendered as content.

The simplest path is the ready-made composer behavior:

ts
const staged = await session.uploadAttachment(file);   // validates + stages
await session.send("");                                // attachment-only message
session.removeStagedAttachment(staged.id);             // or drop it

ChatSession asks the server for the transport mode, so the same call works on a proxy backend and on a direct-to-S3 backend. If you build your own composer, call client.presignAttachment(id, {name, mime, size}) first: {mode:"proxy"} means post the file to uploadAttachment; {mode:"presigned"} means putToStorage(upload_url, headers, file) and then confirmAttachment(id, ticket). Never attach the API token to a storage PUT — the presigned URL is the authorization — and send exactly the returned headers. Then include the ids when sending: sendMessage(id, body, clientMessageId, card, attachmentIds). body may be blank when attachments or a card are present. ChatSession.attachmentLimits mirrors the server limits for instant feedback (maxBytes, maxPerMessage, mimes); override it when the host configures different values. See attachments.

Emoji: import EMOJI_GROUPS from the SDK for a curated, dependency-free picker and insert the chosen glyph at the caret.

See frontend reference for all options, limits and connection lifecycle.

Pending sends and navigation#

ChatSession ignores obsolete thread completions after navigation, including A → B → A. This protects the new thread's draft, staged files and busy/error state; it does not cancel a server request already sent. A late upload returns undefined and is not staged in the newly opened thread.

The standard adapters preserve draft edits made while a send is pending. A confirmed send consumes only the card/files captured by that send; subsequently staged content remains. Selected files upload sequentially, and navigation stops the remaining batch. A custom composer should follow the same captured-draft and conversation checks.

For custom asynchronous UI work, capture the readonly opaque session.conversationRevision and compare it again before clearing a draft or starting the next file. Every open, backToInbox or close changes the token; ordinary refresh/staging does not. Compare equality only, never persist it or use it to authorize access. A confirmed obsolete send() still returns true; the revision tells the interface whether that result belongs to its opening.

There is no automatic message resend. Retry an unchanged uncertain send in the same selected session to reuse its client_message_id; reopening that same selected conversation retains the key. Payload changes, another conversation, returning to the inbox or a new session end this in-memory protection. Reconcile history before submitting an uncertain message outside that boundary.

Login, renewal and logout#

Use your production host's authenticated user token; the reusable SDK has no built-in login endpoint. A token getter allows renewal without copying credentials to browser storage. On ChatError status 401, the SDK disconnects realtime; clear the authenticated interface and renew/sign in through your host. On logout, call your server's token-revocation/logout endpoint, then disconnect the client and destroy/unmount its interface. Server-side revocation of already active WebSockets must be separately implemented and verified; see the production authentication lifecycle.

Host project AGENTS.md#

The SDK installs an alzaf-chat bin. Its init-agents command writes a short, marker-delimited block into a host project's AGENTS.md telling coding agents to read the shipped package READMEs before changing chat code. Run it once per host project (build the SDK first in this workspace):

bash
pnpm exec alzaf-chat init-agents            # insert or refresh the block
pnpm exec alzaf-chat init-agents --check    # CI: exit 2 when missing or outdated
pnpm exec alzaf-chat init-agents --dry-run  # print the result, write nothing
pnpm exec alzaf-chat init-agents --file docs/AGENTS.md

The command is idempotent: it only rewrites the region between the alzaf-chat:begin and alzaf-chat:end markers and never modifies other text. It creates AGENTS.md at the project root (outermost git root, else the nearest package.json) when absent, or appends the block when the file exists without it, preserving line endings. Exit codes are 0 (success or already up to date), 1 (usage or I/O error, including a half-present marker block) and 2 (--check drift). A host may add "postinstall": "alzaf-chat init-agents" to its own package.json to automate this; a postinstall defined by the package itself would not run, because pnpm blocks dependency build scripts by default. The command is Node 22+ tooling and is never loaded into a browser or SSR bundle.