JavaScript SDK: client, session and storage
Dependency-free ES modules for modern browsers and Node 20. Keep one client per authenticated identity and fixed tenant context. Do not put refresh/access tokens in localStorage. On logout/discard: dispose both client and store.
import {SenseverClient} from './client.mjs';
import {HistoryStore} from './history.mjs';
const api = new SenseverClient({tokens});
const view = new HistoryStore(api, {onChange: state => render(state)});
await view.refreshInbox();
await view.open(threadId);
api.markRead(threadId, lastVisibleSeq);
// Wire authorized WS message frames into view.event(frame).
// After successful WS subscription/reconnection:
await view.reconnect();All IDs/seq are canonical decimal strings; comparisons use BigInt. send requires a retained client_message_id. Network failures are not blindly retried; retry the same immutable message request within the server's idempotency window. Refresh rotation is single-flight, triggered only by token_expired, not revoked sessions.
markRead coalesces for 1500ms per Thread and never overlaps its own request. A trailing maximum survives an in-flight request or network failure. Call flushReads on page visibility change/thread switch; failed demand is retried on reconnect. Dispose cancels pending timers; requests already sent cannot be recalled.
HistoryStore bounds each visible Thread window, deduplicates seq and event_id, updates known inbox preview/activity/badge immediately from created frames, refetches updated/deleted messages, and restores after_seq history on reconnect. Holes are legal; it does not invent missing messages. It refreshes the latest visible window to discover edits/deletes and discards previous cached pages. Inbox is a live feed; this initial view model holds the first 100 entries only. UI pagination beyond that window and the WebSocket connection/ticket transport remain to be connected.
A successful unit suite does not prove a real WS deployment. Current tests inject HTTP/fake scheduling, cover failure/order/precision behavior and do not contact production.
node --test sdk/js/*.test.mjsSocket transport
import {RealtimeConnection} from './realtime.mjs';
const socket = new RealtimeConnection(api, view, {onError: showConnectionError});
await socket.watch(threadId);
await socket.start();
// Thread switch: flush previous reads and change watched threads.
await api.flushReads();
socket.unwatch(threadId);
await socket.watch(otherThreadId);
// On logout:
socket.stop(); view.dispose(); await api.logout();The transport fetches a fresh one-use ticket per connection, authenticates in the first frame, subscribes sequentially, and only then performs HTTP recovery. The ticket endpoint must match the API host over WSS at /ws/v1; credentials are never appended to URLs. Reconnect uses exponential backoff with jitter capped at 30s; ping every 25s with a 10s deadline. stop cancels retry/heartbeat timers and pending connection/subscription promises. Session revocation stops automatic reconnect; the application must obtain a new login. A denied subscription is removed instead of retrying it forever. Socket transport tests inject a fake socket; server-side real WSS smoke and Python socket suite are separate checks.
Typing: realtime.typing(threadId, true, 'self') (or tenant/thread) sends only while connected. Call about once per 3s while editing, then typing(threadId,false,sendAs) on stop. Subscribe to onTyping(frame) in RealtimeConnection options. The callback is separate from HistoryStore; do not update badges/message cursors. Clear UI hints on false/disconnect/expiry, at most 5s after receipt. There is no offline queue or retry for typing. Gateway enforces sender permissions and rate limits; SDK method does not schedule periodic typing automatically.
Global inbox message routing works right after authentication, without watching each Thread. data.inbox_item lets HistoryStore add a new Thread/preview/badge locally; null removes an archived Thread. watch() is needed for an open history and typing. On a stale created event, the SDK doesn't decrease last_seq or replace a newer preview. HTTP getInbox remains the recovery/live-pagination source; WS doesn't guarantee delivery of every event.
Inbox refresh merges the HTTP page with Thread changes/removals received while that request was in flight. A delayed response cannot erase a new global Thread, resurrect an archived Thread, or restore a deleted preview. WS InboxItem snapshots update existing rows when seq/read/activity boundaries do not move backward. Tests use deferred HTTP responses to exercise these races; this is live pagination, not snapshot pagination.
Presence: realtime.presence(threadId) requests an authorized active-member snapshot; receive it via onPresence(frame) option. Query roughly every 10s for the open Thread, not every render. online means authenticated activity within 45s, not an exact socket count. Share-presence opt-out and blocked peers are omitted. Clear stale hints on disconnect. Presence is independent of HistoryStore and message cursors; a 25s ping keeps the current side active.
Memory limits
HistoryStore defaults to windowSize: 50, maxIdleThreads: 100 and maxInboxItems: 100. Global events retain only the newest inbox window (activity timestamp, then thread ID); older inbox pages remain available through the HTTP cursor API and are not represented by this minimal view model. Closed histories are evicted in least-recently-used order. Open histories and histories with queued/running operations are protected, so temporary in-flight work and explicitly opened views are additional memory; call close(thread) when leaving a view and dispose() on logout. Evicted histories reload through open(thread) from PostgreSQL. Limits must be positive integers; message window remains 1–100.
Integration test: node scripts/contracts/test-sdk-integration.mjs requires isolated testing HTTP 127.0.0.1:18080 and WS 127.0.0.1:18087 servers plus Python websockets in /tmp/sensever-ws-test-tools. It maps network destinations through test-only adapters while exercising the real SDK, Laravel kernel, PostgreSQL, Redis and gateway. Details and limits are in docs/dev/acceptance.md. Never point its destructive fixtures at production or run parallel test DB suites.
Browser startup shares one CSRF-protected session request between Chat, Projects and Push clients on the same document, API base and CSRF token. The result is reused in page memory for at most 60 seconds (never beyond the access token safety margin). Tenant headers and read queues remain per client. Explicit refresh always checks the browser session; concurrent refreshes share only the in-flight request. Logout invalidates the shared entry and rejects an already pending refresh. Server-side Accounts verification and revocation checks remain unchanged on every API request.
The inbox view uses HistoryStore.refreshInbox's returned page for pagination rather than fetching a second copy. WebSocket startup runs alongside the first inbox load; its post-subscription recovery remains in place to cover messages sent during connection. Initial list placeholders disappear after the first successful response, and background refresh keeps previously loaded rows.
Bình luận