Skip to content
salesforcePublic

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Salesforce Chat SDK

An open-source TypeScript SDK for Salesforce's public Enhanced Chat v2.0 messaging API (also known as MIAW, "Messaging for In-App and Web") — the REST + Server-Sent Events API documented at /iamessage/api/v2 and /eventrouter/v1/sse.

This is an official Salesforce project, built from scratch against the public API docs.

Why

The official docs describe the wire protocol but don't ship a client. This SDK provides:

  • A small, dependency-light core client (HTTP + SSE transport, typed request/response models, a unified event-subscription API) that works in Node and browsers, with zero required adapters.
  • Optional adapters for state (Redux Toolkit), auth (REST-backend or dev-only direct token calls), and session continuity (Web Storage persistence/replay, cross-tab sync via BroadcastChannel), plus documented interfaces for writing your own.
  • A React wrapper (hooks + headless render-prop components) with no bundled styling.
  • A mock server for local development against a faithful emulation of the real API, with no Salesforce org required.
  • Two runnable examples — a terminal CLI and a styled React + Redux chat widget.

Packages

Package Description
@salesforce/chat-sdk-types Wire-protocol TypeScript types for the API — requests, responses, SSE envelopes, discriminated unions for message/entry types. Zero runtime code.
@salesforce/chat-sdk-core The SDK itself: ChatClient, HTTP client, SSE transport (via eventsource, with self-owned reconnect/backoff), the addEventListener event registry, the domain-event middleware pipeline, and the AuthAdapter/StateAdapter/MiddlewareAdapter interfaces.
@salesforce/chat-sdk-adapter-redux A StateAdapter backed by a Redux Toolkit slice, plus configureChatStore() for the standalone case.
@salesforce/chat-sdk-adapter-auth Two AuthAdapter implementations: createRestAuthAdapter (delegates token minting to your own backend — production-appropriate) and createDevAuthAdapter (calls Salesforce's unauthenticated token endpoint directly from the client — dev/prototyping only).
@salesforce/chat-sdk-adapter-webstorage A MiddlewareAdapter that persists domain events to IndexedDB (or, optionally, localStorage/sessionStorage) and replays them to rehydrate state after a page reload.
@salesforce/chat-sdk-adapter-broadcast-channel A MiddlewareAdapter that syncs domain events across same-origin tabs via BroadcastChannel, deduping events already applied by another tab.
@salesforce/chat-sdk-adapter-primary-link MessagePort transport for core's primary/secondary mode: a secondary in another frame attaches to the primary client (origin-checked) and never receives the token.
@salesforce/chat-sdk-react Hooks (useConnectionState, useMessages, useSendMessage, useTypingIndicator, useParticipants, ...) and headless components (MessageList, Composer, TypingIndicator, ConnectionStatus) on top of core. Unstyled by design.
@salesforce/chat-sdk-logging-events Opt-in listener that maps domain events to log records and hands them to a Logger (console or your own provider).
@salesforce/chat-sdk-mock-server An in-memory Express server emulating the REST + SSE API, for local dev and testing without a real Salesforce org.

Dependency direction: types → core → {adapter-redux, adapter-auth, adapter-webstorage, adapter-broadcast-channel, adapter-primary-link, react} → examples/*. mock-server depends only on types. No circular dependencies.

Examples

Example Description
examples/cli A Node terminal REPL using core directly (no React, no Redux) — connect, create a conversation, send/receive messages from stdin/stdout.
examples/react-client A Vite + React chat widget using core + react + adapter-redux together — a floating bubble launcher with a real Redux store backing its state (visible in Redux DevTools).

Both examples point at the local mock server by default and can be redirected at a real org via env vars — see each example's own README.

Quick start

git clone <this repo>
cd enhanced-chat-sdk
corepack enable   # ensures the pinned Yarn version from packageManager is used
yarn install
yarn build
yarn test

Try an example against the mock server:

# Terminal 1
yarn workspace @salesforce/chat-sdk-mock-server run start

# Terminal 2 — CLI
yarn workspace @salesforce/chat-sdk-example-cli run start

# ...or the React widget
yarn workspace @salesforce/chat-sdk-example-react-client run dev

Using the SDK in your own app

import { ChatClient } from '@salesforce/chat-sdk-core';
import { createDevAuthAdapter } from '@salesforce/chat-sdk-adapter-auth';

const scrtUrl = 'https://<org>.my.salesforce-scrt.com';
const orgId = '00Dxxxxxxxxxxxxxxx';
const esDeveloperName = 'MyDeployment';

const client = new ChatClient({
  scrtUrl,
  orgId,
  esDeveloperName,
  // dev-only — calls Salesforce's unauthenticated token endpoint directly from the client.
  // See adapter-auth's README for the production-appropriate createRestAuthAdapter instead.
  authAdapter: createDevAuthAdapter({ mode: 'unauthenticated', scrtUrl, orgId, esDeveloperName }),
});

client.addEventListener('message', (event) => {
  if (event.type === 'message') {
    console.log(event.payload.abstractMessage);
  }
});

await client.connect();
await client.conversations.create({ conversationId: crypto.randomUUID() });

No adapter is ever required — core ships a built-in in-memory StateAdapter if you don't supply one. See each package's README for the full API and for wiring up Redux state, a REST auth backend, or the React hooks.

Connecting and reconnecting

await client.connect() resolves only once the SSE stream has opened, so a resolved call means "ready to receive". If the stream can't open (HTTP 401/403, a network error, or a 30s timeout) it rejects and the client ends up disconnected; calling disconnect() while connecting rejects with an AbortError.

After an established stream drops, the SDK reconnects on its own with exponential backoff. It resumes from the last SSE frame's id: (sent as Last-Event-Id) and then backfills entries the stream missed via conversations.listEntries (newest 100 per known conversation), de-duplicated by entry identifier against what the stream already delivered. A failed backfill is reported as a transport:error event and does not stop the stream. The very first connection has no cursor (there is nothing to resume) and does not backfill; replay a persisted transcript via client.dispatch before connect() as described under session continuity.

Opt-in SSE resilience

By default the SDK retries a dropped stream forever and trusts the connection as long as it is open. Three options on ChatClient (all off by default) change that:

  • maxSseReconnectAttempts: stop after this many consecutive failed reconnects (the count resets whenever the stream opens). The client then emits a final transport:error event with terminal: true and reports connectionStatus: 'disconnected'; call connect() to start over.
  • sseLivenessTimeoutMs: treat a stream that delivers no frame for this long as dropped and reconnect through the normal path (same resume cursor and backfill). Set it above the server's heartbeat interval. Note that SSE comment lines (: ping) are not visible to the SDK, so the server needs to send a named frame to keep an idle stream alive.
  • sseHeartbeatEventNames: named frames (for example ping) that only reset the watchdog; they are not parsed and emit no events.
const client = new ChatClient({
  // ...
  maxSseReconnectAttempts: 8,
  sseLivenessTimeoutMs: 45_000,
  sseHeartbeatEventNames: ['ping'],
});
client.addEventListener('transport:error', (event) => {
  if (event.type === 'transport:error' && event.terminal) showOfflineBanner();
});

Own-message echo

client.messages.send() dispatches a message event as soon as the 202 arrives, and the live service also echoes the end user's own message over SSE. The client de-duplicates message events by (conversationId, abstractMessage.id) ahead of middleware, so raw client.addEventListener('message', ...) listeners, middleware, and the state adapter see each message once regardless of arrival order (last 2,000 messages remembered). The first copy wins, so the sender's own message keeps the locally synthesized sender and clientTimestamp.

Expired-token handling

Both transports detect an expired/invalid token (HTTP 401/403 on a REST call, or the equivalent over SSE) and route it through one internal AuthRecoveryController, so a dead token never just surfaces as a raw console exception with no recovery:

  1. Consumer callback first. If you pass onAuthError to ChatClient, it's invoked with the transport:error event that triggered recovery. Return (or resolve to) { handled: true } to signal you've resolved it yourself — e.g. refreshed the token out of band — and the SDK skips its own recovery entirely.
  2. Automatic default otherwise. With no onAuthError, or if it returns { handled: false }/ undefined/throws, the SDK discards the dead session on its own: authAdapter.revoke?.() (best-effort — the token is discarded client-side regardless of whether the server-side revoke call itself succeeds), disconnect(), then it emits an auth:sessionDiscarded domain event (every built-in/adapter StateAdapter resets its transcript on this event) and reconnects.
const client = new ChatClient({
  scrtUrl,
  orgId,
  esDeveloperName,
  authAdapter,
  onAuthError: async (error) => {
    await myOwnTokenRefresh();
    return { handled: true }; // suppress the SDK's automatic discard-and-restart
  },
});

Deliberately out of scope for auth:sessionDiscarded: recreating the conversation. This SDK doesn't own conversation creation for any lifecycle event (see conversation:closed below), so a consumer listens for it and calls client.conversations.create(...) itself — core's ConversationLifecycleController (and the useConversationLifecycle React hook that wraps it) is the reference implementation, structurally identical for conversation:closed.

For your own AuthAdapter, this means revoke() must actually make the next getAccessToken() fetch a fresh token rather than replay the same (expired) cached one — see @salesforce/chat-sdk-adapter-auth's createRestAuthAdapter/createDevAuthAdapter for that pattern; a staticToken-mode dev adapter has no such story and will 401 forever once its one token expires.

Event subscriptions

Modeled on Redux Toolkit's createListenerMiddleware: register against an exact event type or an arbitrary predicate, rather than a plain string-keyed emitter. A bare event type is shorthand for { type } — matching both Redux's startListening({ type }) and the DOM EventTarget.addEventListener(type, listener) convention —

client.addEventListener('typing:started', (event) => { ... });
client.addEventListener(
  {
    predicate: (event) =>
      event.type === 'message' &&
      event.payload.abstractMessage.messageType === 'StaticContentMessage' &&
      event.payload.abstractMessage.staticContent.formatType === 'RichLink',
  },
  (event) => { ... },
);

This one primitive is also how adapter-redux and adapter-auth are built — they're ordinary consumers of addEventListener, not special-cased plugins. A custom adapter of your own uses the exact same public API.

Unrecognized SSE event names

The service may send named SSE frames this SDK version has no listener for (observed live: ping, CONVERSATION_CONVERSATION_UPDATED). The API only requires clients to ignore unknown event types without failing, so nothing needs to handle these, but rather than dropping them silently the SDK emits a diagnostic sse:unrecognizedEvent domain event carrying the raw eventName and unparsed data string:

client.addEventListener('sse:unrecognizedEvent', (event) => {
  console.debug('unrecognized SSE event', event.eventName, event.data);
});

It is distinct from unknown (a known frame name with an unrecognized entryType), so it keeps its shape as the SDK gains first-class support for more names. Unnamed frames do not produce it. It has no conversationId, never changes state adapters, is not persisted by adapter-webstorage, and is not relayed by adapter-broadcast-channel (each tab has its own SSE connection and sees the frame itself). Its frame id: still advances the reconnect cursor.

Middleware & continuity

ChatClientOptions.middleware is an ordered pipeline every domain event passes through before it reaches addEventListener listeners or the active StateAdapter — the same idea as Redux middleware, generalized to this SDK's event stream instead of a store's actions:

export interface MiddlewareAdapter {
  process(event: DomainEvent, next: (event: DomainEvent) => void): void;
}

A middleware calls next(event) to pass the event through unchanged, calls next(transformed) to rewrite it, or returns without calling next to veto it — nothing downstream (later middleware, listeners, the state adapter) ever sees a vetoed event. Two things follow directly from that:

  • Array order is execution order, and it's part of the public contract. The first middleware in ChatClientOptions.middleware sees (and can veto) an event before any later one does. A dedup/continuity middleware generally belongs first.
  • Veto is unrestricted by design. Keeping application state consistent under a veto or transform is the adapter author's responsibility, not something the pipeline enforces — this is deliberate, since the main use case (dropping a duplicate delivery of an event already applied) requires exactly that power. This is independent of transport-level resumption: SseClient updates its own reconnect cursor from each SSE frame's id: line before an event ever reaches middleware, so vetoing a DomainEvent cannot affect it.

This is why MiddlewareAdapter — not StateAdapter — is the integration point for session continuity: ChatState is shaped differently by every StateAdapter (a flat shape in the built-in InMemoryStateAdapter, an RTK-normalized shape in adapter-redux), while the DomainEvent stream feeding all of them is the one shape-agnostic layer a continuity adapter can persist, replay, or dedupe against.

Two adapters built on this:

  • @salesforce/chat-sdk-adapter-webstorage — persists state-affecting events to IndexedDB by default (opt into localStorage/sessionStorage via backend) and exposes an async replay() function to rehydrate whichever StateAdapter is active (by feeding stored events back through client.dispatch) before connect() is called, so a reloaded page starts from its prior transcript instead of empty state. Also exposes an async clear() to delete the persisted log outright — for a consumer ending one conversation and starting another under the same storage key, so a later replay() never rehydrates events belonging to the conversation that just ended.
  • @salesforce/chat-sdk-adapter-broadcast-channel — syncs events across same-origin tabs via BroadcastChannel. Each tab holds its own independent SSE connection (there's no leader election), so this adapter's job is deduping the resulting duplicate deliveries and syncing locally-originated state that never travels over SSE. Takes an optional appId, appended to channelName, so multiple independent apps built on this SDK and open in tabs on the same origin don't cross-talk — omit it if only one app instance is ever in play. appId scopes only the channel (events and presence): the claimed-id key (claimKey), the lifecycle controller's storage key and the continuity key are separate options with shared defaults, so apps that share an origin must give each of those its own value too (see examples/react-client). Also provides createBroadcastChannelCoordinator, a full InstanceCoordinator (pass it as instanceCoordinator; the client always runs its relay first) with conversation-claim arbitration, and hasOtherTabs(timeoutMs?), a minimal presence check (broadcasts a ping, resolves true if any other tab on the channel answers within the timeout) — deliberately not leader election, just a yes/no signal a consumer can use to decide whether it's the only tab active on a conversation.

Continuity is opt-in — omitting middleware entirely (the default) leaves every event's path to listeners/state exactly as it was before this pipeline existed.

Multi-tab reference implementation

examples/react-client wires both adapters together into a fuller reference for what real multi-tab continuity looks like end-to-end, matching how Salesforce's own internal ECv2 client behaves in production:

  • Shared auth token. chatSetup.ts caches the dev auth adapter's token in localStorage (rather than the in-memory-only default) so every tab authenticates as the same participant subject. This is what makes cross-tab sync meaningful in the first place: the mock server (and the real API) publishes SSE events keyed by subject, so two tabs with different subjects would never observe each other's conversation over SSE at all — adapter-broadcast-channel would only ever relay locally-originated events, never dedupe genuine server deliveries.
  • Cold-start coordination. Two tabs opening with no conversation persisted yet would otherwise each generate and create their own conversation. The coordinator's claim() (used by core's ConversationLifecycleController) avoids that with a short settle-and-reconcile window over localStorage: a tab that finds nothing stored writes its own candidate id, waits briefly, then re-reads storage so any tab that raced it converges on whichever id was written last.
  • Cross-tab "end chat," explicit restart. The mock server's scripted responder closes the conversation server-side (emitting CloseConversation over SSE) when the end user sends a message starting with "stop"/"goodbye"/etc. Since every tab shares one subject, every tab's own SSE connection receives that conversation:closed event directly. Each tab reacts by clearing its local transcript (ReduxStateAdapter.resetConversation()) and the persisted continuity log (continuity.clear()), then surfaces a "Start new conversation" button rather than claiming a new one automatically — see ConversationLifecycleController's doc comment (core) for why restarting (here and after an auth:sessionDiscarded) is deliberately an explicit user action, not automatic. Clicking it in any open tab runs the same claim-and-create routine a cold start uses, so every open tab still converges on one new conversation, not just the tab whose button was clicked.
  • Sole-tab reconciliation against the server. continuity.replay() rehydrates whatever was last persisted locally, which can be stale after a long-idle reload. The controller's sole-instance reconciliation runs once, right after the initial bootstrap: if coordinator.hasOtherInstances() resolves false (no other tab is presumably keeping things fresh via its own live SSE connection), it fetches the conversation's most recent entries via client.conversations.listEntries(), converts each one to a DomainEvent with normalizeConversationEntry (core), and re-dispatches them through the normal client.dispatch path. This never runs again on a later startConversation() restart, and it's best-effort — any error (e.g. the conversation no longer exists server-side) is swallowed rather than failing the bootstrap.

Development

This is a Yarn Berry (v4) workspace monorepo — plain yarn workspaces foreach scripts, no Turborepo/Nx.

yarn build            # build every package, in dependency order
yarn test             # run Vitest across every package
yarn test:coverage    # with coverage
yarn test:e2e         # run the Playwright suite (e2e/) against the mock server
yarn typecheck        # tsc --noEmit in every package
yarn lint             # eslint .
yarn format           # prettier --write .
yarn format:check     # prettier --check .
yarn clean            # remove build output in every package

Each package builds dual ESM/CJS + .d.ts via tsup and is tested with Vitest (colocated *.test.ts/*.test.tsx files). CI (.github/workflows/ci.yml) runs typecheck, lint, format check, build, and test on every push/PR to main.

Release acceptance: clean-install check

yarn verify:install [--managers=npm,yarn,pnpm] [--keep]

Run before releasing; CI is not relied on. Builds, packs every public package, and installs the tarballs into throwaway npm, Yarn and pnpm projects in the OS temp dir (nothing is installed in this repo). Each project loads every package as ESM and CJS, constructs a ChatClient, and starts the installed chat-sdk-mock-server command, checking that it serves a request and shuts down cleanly on SIGTERM. A manager that is missing or too old (pnpm < 8) is skipped with a warning unless named explicitly in --managers, in which case it fails.

Producing npm-ready deliverables

yarn build:deliverables

Builds every package and assembles dist/ at the repo root:

dist/
  manifest.json
  packages/<package-name>/    # package.json (workspace:^ deps rewritten to real semver),
                               # compiled dist/, README.md, LICENSE — no src
  examples/<example-dir>/     # example source, copied verbatim (no node_modules, no .env*)

Each package folder is produced via yarn workspace <name> pack, so it's installable standalone (e.g. npm install <path-to-folder>) without relying on the rest of the monorepo. Packages are kept separate on purpose — nothing here is bundled together, so consumers can pull in only the packages they need without depending on tree-shaking to drop the rest. Private workspaces (e.g. the examples themselves, mock-server's dev tooling) are skipped automatically.

manifest.json lists every package/example produced, with dir given as a path relative to dist/ itself (e.g. packages/@salesforce/chat-sdk-core), so the manifest stays valid if dist/ is copied or moved elsewhere.

The assembly logic lives in tools/build-deliverables (private workspace, not published) — see its source for the underlying buildDeliverables() API if you need to script around it.

Scope and non-goals

  • Push notifications: core exposes thin, typed bindings for the register/unregister REST endpoints only. Obtaining an APNS or FCM device token is inherently platform-specific and is the consumer's responsibility — see core's README for details.
  • No any/unknown in public APIs: the SDK is strictly typed throughout.
  • Not a fit for React Native/native mobile out of the box — core itself is platform-agnostic, but the react package assumes a DOM environment (headless components, no native primitives).

Contributing and support

Issues are welcome: bug reports, feature requests, and questions. Pull requests are not currently accepted. See CONTRIBUTING.md for how to file a good issue. To report a security vulnerability, follow SECURITY.md.

License

MIT — see LICENSE.

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages