/** * Live: one websocket at `/v1/live` (`/realtime/v1` in the old vocabulary), carrying signals, * the roster (who is present) and table changes. * * The wire is Phoenix channels (protocol 1.0.0): every frame is JSON * `{ topic, event, payload, ref, join_ref }`. A topic named `room:42` is `live:room:42` on the * wire; it is joined with a `phx_join` whose payload says what it wants (signal options, a * roster key, which table changes), answered by a `phx_reply` carrying the same `ref`. The * socket is kept alive by a `heartbeat` on the `phoenix` topic every 25 seconds, and when it * drops it is reopened and every topic that was joined is joined again, so a listener survives * a network blip without writing any code for it. * * In the old vocabulary the same frames say `realtime:`, `broadcast`, `presence` and * `postgres_changes`. Everything inside this file speaks the old names; a frame is put into the * new ones as it leaves and back as it arrives (`speak`, `hear`), as the server does. * * The socket opens on the first `join()`, not before: a page that never joins never holds a * connection. */ import { type Transport, type Vocabulary } from './http.js'; export type ChannelState = 'closed' | 'joining' | 'joined' | 'leaving' | 'errored'; export type SubscribeStatus = 'SUBSCRIBED' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED'; export type SendStatus = 'ok' | 'error' | 'timed out'; export interface SignalOptions { /** Hear your own signals. */ self?: boolean; /** `signal()` waits for the server to confirm. */ ack?: boolean; replay?: { since: number; limit?: number; }; } export interface RosterOptions { /** The key this client is announced under. A random one when omitted. */ key?: string; enabled?: boolean; } export interface ChannelOptions { config?: { signal?: SignalOptions; roster?: RosterOptions; /** @deprecated Since 0.4.0: `signal`. */ broadcast?: SignalOptions; /** @deprecated Since 0.4.0: `roster`. */ presence?: RosterOptions; /** Authorised by RLS on the project's live signals table rather than open to anyone with the key. */ private?: boolean; }; } /** What `live.topic()` takes. */ export type TopicOptions = ChannelOptions; export interface ChangesFilter { event: '*' | 'INSERT' | 'UPDATE' | 'DELETE'; schema: string; table?: string; /** One condition in PostgREST syntax, `id=eq.7`. */ filter?: string; } /** @deprecated Since 0.4.0: `ChangesFilter`. */ export type PostgresChangesFilter = ChangesFilter; export interface ChangesPayload> { schema: string; table: string; commit_timestamp: string; eventType: 'INSERT' | 'UPDATE' | 'DELETE'; /** The row after the change; `{}` for a delete. */ new: Partial; /** The row before it: the primary key only, unless the table is REPLICA IDENTITY FULL. */ old: Partial; errors: string[] | null; } /** @deprecated Since 0.4.0: `ChangesPayload`. */ export type PostgresChangesPayload> = ChangesPayload; /** A signal as it arrives. `type` is the vocabulary's own name for it. */ export interface SignalMessage> { type: 'signal' | 'broadcast'; event: string; payload: T; } /** @deprecated Since 0.4.0: `SignalMessage`. */ export type BroadcastMessage> = SignalMessage; export type Presence> = T & { presence_ref: string; }; export interface RosterJoin> { event: 'join'; key: string; currentPresences: Presence[]; newPresences: Presence[]; } /** @deprecated Since 0.4.0: `RosterJoin`. */ export type PresenceJoin> = RosterJoin; export interface RosterLeave> { event: 'leave'; key: string; currentPresences: Presence[]; leftPresences: Presence[]; } /** @deprecated Since 0.4.0: `RosterLeave`. */ export type PresenceLeave> = RosterLeave; interface Frame { topic: string; event: string; payload: Record; ref: string | null; join_ref?: string | null; } type Reply = { status: string; response: Record; }; /** * A realtime handler (`realtime.on()`) that did not complete. `code` is `unauthorized`, * `timeout`, `no_handler`, `not_joined`, `timed_out` (no reply came), or the SQLSTATE the * handler raised (`P0001` for a plain `raise exception`). */ export declare class RealtimeHandlerError extends Error { readonly code: string; constructor(message: string, code: string); } export interface RealtimeOptions { /** A WebSocket constructor, where the platform has none. Node 22 and every browser do. */ transport?: typeof WebSocket; heartbeatIntervalMs?: number; /** How long a join, leave or acknowledged send may wait for its reply. */ timeoutMs?: number; params?: Record; } export declare class RealtimeClient { /** The `wss://` URL, for inspection. */ readonly url: string; private readonly key; private readonly options; private readonly transport; private readonly httpUrl; private readonly tokenSource; private socket; private readonly channels; private readonly pending; private buffer; private ref; private heartbeat; private heartbeatRef; private reconnectTimer; private reconnectTries; private closedByUs; /** @internal */ accessToken: string | null; /** @internal Which names the wire speaks. */ readonly vocabulary: Vocabulary; /** @deprecated Since 0.4.0: use `topic()`, the same function. Removed in 0.5.0. */ channel: RealtimeClient['topic']; constructor(url: string, key: string, transport: Transport, tokenSource: () => Promise, options?: RealtimeOptions, vocabulary?: Vocabulary); /** @internal */ get timeoutMs(): number; /** @internal */ nextRef(): string; /** A topic to listen on and signal to. Nothing is sent until `join()`. */ topic(name: string, options?: TopicOptions): RealtimeChannel; getChannels(): RealtimeChannel[]; removeChannel(channel: RealtimeChannel): Promise; removeAllChannels(): Promise; isConnected(): boolean; /** Re-authorise every joined topic with a new access token, after a sign-in or refresh. */ setAuth(token: string | null): void; /** @internal */ token(): Promise; /** @internal Opens the socket if it is not open or opening. */ connect(): void; /** Closes the socket and keeps it closed. */ disconnect(): void; /** @internal */ push(frame: Frame): void; /** @internal A frame that expects a `phx_reply` with its ref. */ request(frame: Frame, timeoutMs?: number): Promise; /** @internal The wire topic for a name, in this client's vocabulary. */ topicFor(name: string): string; /** A frame as it leaves: in the new vocabulary, its event, its payload's `type` and a join's config keys renamed. */ private speak; /** * A frame as it arrives, in the old names this file works in: its event, a `system` message's * extension and a reply's keys. A signal's own `type` is left as the server said it, since it * is handed to the listener as it came. */ private hear; /** @internal A signal over HTTP, for a topic that is not joined. */ broadcastOverHttp(topic: string, event: string, payload: unknown, isPrivate: boolean): Promise; private opened; private closed; private received; private startHeartbeat; private stopHeartbeat; } export declare class RealtimeChannel { /** The topic on the wire: `live:` (`realtime:` in the old vocabulary). */ readonly topic: string; /** The name it was created with. */ readonly name: string; state: ChannelState; /** @internal */ joinRef: string | null; /** @internal Whether the caller wants this joined; a dropped socket rejoins only these. */ wanted: boolean; private readonly options; private readonly client; private readonly bindings; private presence; /** * What this client last announced with `track`, re-sent on every rejoin. * * Presence lives on the server as long as the channel process that tracked it. When the * channel is closed (the server's "Too many messages per second", a dropped socket, a * restart), the rejoin is automatic but the presence was not: everybody else saw this * player leave and never come back, although the socket was fine. Remembering the state is * what makes a rejoin restore the player as well as the channel. */ private tracked; private statusCallback; private rejoinTimer; private rejoinTries; /** Set while a joined channel waits for Realtime to say its table changes are live. */ private awaitingChanges; /** * What Realtime said about the table changes while the join still waited for its reply * (null: they are live). In Node one socket read can carry the reply AND that message, * and both are handled before the join sees its reply, so it is kept for the join. */ private earlyChanges; constructor(name: string, options: ChannelOptions, client: RealtimeClient); /** @deprecated Since 0.4.0: use `listen()`, the same function, with `changes`, `signal` or `roster`. Removed in 0.5.0. */ on: { (type: 'broadcast', filter: { event: string; }, callback: (message: SignalMessage) => void): RealtimeChannel; (type: 'presence', filter: { event: 'sync'; }, callback: () => void): RealtimeChannel; (type: 'presence', filter: { event: 'join'; }, callback: (join: RosterJoin) => void): RealtimeChannel; (type: 'presence', filter: { event: 'leave'; }, callback: (leave: RosterLeave) => void): RealtimeChannel; = Record>(type: 'postgres_changes', filter: ChangesFilter, callback: (payload: ChangesPayload) => void): RealtimeChannel; (type: 'system', filter: Record, callback: (message: Record) => void): RealtimeChannel; }; /** @deprecated Since 0.4.0: use `join()`, the same function. Removed in 0.5.0. */ subscribe: RealtimeChannel['join']; /** @deprecated Since 0.4.0: use `signal()`, the same function. Removed in 0.5.0. */ send: RealtimeChannel['signal']; /** @deprecated Since 0.4.0: use `announce()`, the same function. Removed in 0.5.0. */ track: RealtimeChannel['announce']; /** Hear `signal`s (by event name), the `roster` (`sync`, `join`, `leave`), table `changes`, or `system` messages. */ listen(type: 'signal', filter: { event: string; }, callback: (message: SignalMessage) => void): this; listen(type: 'roster', filter: { event: 'sync'; }, callback: () => void): this; listen(type: 'roster', filter: { event: 'join'; }, callback: (join: RosterJoin) => void): this; listen(type: 'roster', filter: { event: 'leave'; }, callback: (leave: RosterLeave) => void): this; listen = Record>(type: 'changes', filter: ChangesFilter, callback: (payload: ChangesPayload) => void): this; listen(type: 'system', filter: Record, callback: (message: Record) => void): this; /** * Joins. `callback` hears SUBSCRIBED, and afterwards CHANNEL_ERROR, TIMED_OUT or CLOSED; * after an error the topic keeps trying to rejoin on its own. */ join(callback?: (status: SubscribeStatus, error?: Error) => void): this; /** Leaves. The topic can be discarded afterwards; `removeChannel` also forgets it. */ unsubscribe(): Promise; /** * Sends a signal, or a roster announce/untrack (`type` in either vocabulary). On a joined * topic it goes over the socket; on one that is not joined, a signal goes over HTTP instead, * so a server can signal without holding a socket open. */ signal(message: { type: 'signal' | 'roster' | 'broadcast' | 'presence'; event: string; payload?: unknown; [field: string]: unknown; }): Promise; /** * Runs the project's realtime handler for `event` on this channel (registered with * `realtime.on()` in SQL) as the signed-in user, and resolves with what it returned. What the * handler sends with `realtime.emit()` reaches the channel only if it succeeded. The channel * must be joined. */ call(event: string, payload?: unknown): Promise<{ data: T | null; error: RealtimeHandlerError | null; }>; /** Announce this client on the topic's roster with `state`, replacing what it announced before. */ announce(state: Record): Promise; /** Leaves the roster, staying on the topic. */ untrack(): Promise; private signalOptions; private rosterOptions; /** After a join: announce again whatever was tracked before the channel was lost. */ private retrack; /** Everyone present, by key. Each key may be present more than once (two tabs). */ presenceState = Record>(): Record[]>; /** @internal */ socketOpened(): void; /** @internal */ socketClosed(): void; private attach; private changesLive; private scheduleRejoin; /** @internal */ receive(frame: Frame): void; private dispatch; private postgresChange; private presenceSync; private presenceDiff; private emitPresence; } export {};