@rebasepro/client 0.9.1-canary.f2f61da → 0.9.1-canary.faee831

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Broadcast channels and presence, as an SDK surface.
3
+ *
4
+ * The realtime engine has supported `join_channel`, `broadcast`,
5
+ * `presence_track`, `presence_untrack` and `presence_state` for a while, but
6
+ * the client only recognised those types well enough to send them
7
+ * fire-and-forget: there were no methods to call and no way to receive channel
8
+ * or broadcast events, since `on()` handles only connect / disconnect /
9
+ * reconnect / error. Anything wanting presence therefore opened a *second*
10
+ * socket and reimplemented the AUTHENTICATE → AUTH_SUCCESS handshake, the
11
+ * reconnect backoff, and the presence heartbeat — a couple of hundred lines
12
+ * per app, all of it duplicating this package.
13
+ *
14
+ * Two protocol details this hides, because both are easy to get wrong and
15
+ * neither is discoverable from the message list:
16
+ *
17
+ * - **A joining client is told only about its own join.** The `presence_diff`
18
+ * it receives after `presence_track` contains just itself. The existing
19
+ * roster arrives only in response to an explicit `presence_state` request,
20
+ * so `join()` sends one.
21
+ * - **Presence expires after 30s** (`PRESENCE_TIMEOUT_MS` server-side). A
22
+ * client that tracks once and goes quiet silently vanishes from everyone
23
+ * else's roster while still sitting in the document, so `track()` starts a
24
+ * heartbeat and `leave()` stops it.
25
+ */
26
+ /** Presence state keyed by the server's client id. */
27
+ export type PresenceState = Record<string, Record<string, unknown>>;
28
+ export interface PresenceDiff {
29
+ joins: PresenceState;
30
+ leaves: PresenceState;
31
+ }
32
+ export interface BroadcastEvent {
33
+ event: string;
34
+ payload: unknown;
35
+ /**
36
+ * Per-channel sequence number, present only on retained channels.
37
+ *
38
+ * Monotonically increasing and dense, so a consumer that remembers the last
39
+ * one it applied can tell the server exactly where to resume from.
40
+ */
41
+ seq?: number;
42
+ /**
43
+ * True when this arrived through catch-up rather than live.
44
+ *
45
+ * Handlers do not have to care — replayed messages are delivered to the
46
+ * same `onBroadcast` handlers, in sequence order, so an operation stream
47
+ * needs no second code path. It is exposed for consumers that want to,
48
+ * for example, skip an animation while fast-forwarding.
49
+ */
50
+ replayed?: boolean;
51
+ }
52
+ /** One retained message, as returned by {@link RebaseRealtimeChannel.history}. */
53
+ export interface ChannelHistoryEntry {
54
+ seq: number;
55
+ event: string;
56
+ payload: unknown;
57
+ senderId?: string;
58
+ at?: string;
59
+ }
60
+ /** The answer to a catch-up request. */
61
+ export interface ChannelHistoryResult {
62
+ messages: ChannelHistoryEntry[];
63
+ /**
64
+ * Whether the server retains anything for this channel.
65
+ *
66
+ * False means there is no retention rule configured for it, so the empty
67
+ * list means "never keeps history" rather than "you missed nothing" — a
68
+ * client that needs to converge has to fall back to a full resync.
69
+ */
70
+ retained: boolean;
71
+ /** Highest sequence the server holds, even if this batch was capped. */
72
+ latestSeq?: number;
73
+ }
74
+ /** Options for a channel handle. */
75
+ export interface ChannelOptions {
76
+ /**
77
+ * Ask the server to replay what this client missed, on join and on every
78
+ * reconnect.
79
+ *
80
+ * Only meaningful for a channel the *server* has a retention rule for —
81
+ * retention is configured on the backend, since a channel is created by
82
+ * whoever names it and a client-chosen history depth would let any visitor
83
+ * commit the backend to unbounded storage. On a channel with no rule the
84
+ * server answers `retained: false` and this is inert.
85
+ */
86
+ history?: boolean;
87
+ }
88
+ /** The socket operations a channel needs; satisfied by RebaseWebSocketClient. */
89
+ export interface ChannelTransport {
90
+ sendMessage(message: Record<string, unknown>): Promise<unknown>;
91
+ onChannelMessage(channel: string, handler: (message: Record<string, unknown>) => void): () => void;
92
+ onReconnect(handler: () => void): () => void;
93
+ }
94
+ export declare class RebaseRealtimeChannel {
95
+ readonly name: string;
96
+ private transport;
97
+ private presenceHandlers;
98
+ private broadcastHandlers;
99
+ private unsubscribers;
100
+ /** Last known roster, kept so handlers always get a full picture. */
101
+ private presences;
102
+ /** What this client last tracked, replayed on reconnect and heartbeat. */
103
+ private trackedState;
104
+ private heartbeat;
105
+ private joined;
106
+ /** Whether this handle asks the server to replay missed messages. */
107
+ private wantsHistory;
108
+ /**
109
+ * Highest sequence number delivered to handlers so far.
110
+ *
111
+ * This is the resume point sent as `sinceSeq`, and the watermark that makes
112
+ * replay idempotent: catch-up ranges overlap with what arrived live, and
113
+ * anything at or below this has already been seen.
114
+ */
115
+ private lastSeq;
116
+ /**
117
+ * Live messages that arrived while a catch-up was in flight.
118
+ *
119
+ * Without this they would be delivered ahead of the older messages being
120
+ * fetched, and — worse — would advance {@link lastSeq} past them, so the
121
+ * catch-up response would then be discarded as already-seen and those
122
+ * messages would be lost for good. Held here and flushed, in order, once
123
+ * the replay lands.
124
+ */
125
+ private pendingLive;
126
+ private catchUpInFlight;
127
+ /**
128
+ * Deadline for a catch-up response.
129
+ *
130
+ * Buffering live messages is only safe because the wait is bounded. A
131
+ * catch-up frame that never arrives — a server that dropped it, a socket
132
+ * that died between request and reply — would otherwise leave the channel
133
+ * silently holding every subsequent edit forever, which is a worse failure
134
+ * than the one replay was added to fix.
135
+ */
136
+ private catchUpTimeout;
137
+ /**
138
+ * Callers of {@link history} awaiting the next `channel_history` frame.
139
+ *
140
+ * These frames are addressed by channel rather than by request id, so they
141
+ * are matched in arrival order. Requests on one channel are serialized by
142
+ * the socket, so FIFO is the right correlation here.
143
+ */
144
+ private historyWaiters;
145
+ constructor(name: string, transport: ChannelTransport, options?: ChannelOptions);
146
+ /**
147
+ * Turn on catch-up for a handle that was created without it.
148
+ *
149
+ * The client hands back the same channel object for a given name, so a
150
+ * later `channel(name, { history: true })` has no new object to configure —
151
+ * it upgrades this one instead. Idempotent, and never downgrades: one
152
+ * caller asking for history must not be switched off by another that did
153
+ * not ask.
154
+ */
155
+ enableHistory(): void;
156
+ /**
157
+ * Join the channel and ask for the current roster.
158
+ *
159
+ * Called automatically by `track`, `broadcast`, `onPresence` and
160
+ * `onBroadcast`; calling it directly is only needed to start receiving
161
+ * before there is anything to send.
162
+ */
163
+ /**
164
+ * Send a channel message.
165
+ *
166
+ * Every channel message is read by the server out of a `payload` envelope
167
+ * (`payload?.channel`, `payload?.state`, `payload?.event`). Sending those
168
+ * fields flat does not error: `payload?.channel` simply reads as
169
+ * `undefined`, so the client is registered into channel `undefined` with
170
+ * empty state, and the echo comes back with no `channel` for
171
+ * `onChannelMessage` to match — presence and broadcast both go quiet with
172
+ * nothing logged. Funnelled through one place so a new message type cannot
173
+ * reintroduce that.
174
+ */
175
+ private send;
176
+ join(): Promise<void>;
177
+ private rejoin;
178
+ /**
179
+ * Ask the server for everything after {@link lastSeq}.
180
+ *
181
+ * Live messages are buffered from here until the answer arrives — see
182
+ * {@link pendingLive}.
183
+ */
184
+ private requestHistory;
185
+ /**
186
+ * Give up waiting for a catch-up and release what was held back.
187
+ *
188
+ * The buffered messages are still the freshest thing this client has, so
189
+ * they are delivered rather than dropped. Callers of {@link history} are
190
+ * answered with `retained: false` — accurate in the sense that matters:
191
+ * this client has no history to work from and has to resync.
192
+ */
193
+ private abandonCatchUp;
194
+ /**
195
+ * Publish this client's presence state, and keep publishing it.
196
+ *
197
+ * Calling `track` again replaces the state (and restarts the heartbeat),
198
+ * which is how you update e.g. a cursor position.
199
+ */
200
+ track(state: Record<string, unknown>): Promise<void>;
201
+ /** Stop publishing presence, without leaving the channel. */
202
+ untrack(): Promise<void>;
203
+ /**
204
+ * Observe the roster. The handler fires immediately with what is already
205
+ * known, then on every change.
206
+ */
207
+ onPresence(handler: (state: PresenceState, diff?: PresenceDiff) => void): () => void;
208
+ /** Send a broadcast. The sender does not receive its own message. */
209
+ broadcast(event: string, payload: unknown): Promise<void>;
210
+ /** Observe broadcasts. Pass an event name to filter. */
211
+ onBroadcast(handler: (event: BroadcastEvent) => void): () => void;
212
+ onBroadcast(event: string, handler: (payload: unknown) => void): () => void;
213
+ /**
214
+ * The last sequence number this channel has delivered.
215
+ *
216
+ * Zero on a channel that retains nothing. Persist it if you want catch-up
217
+ * to survive a page reload as well as a reconnect, and pass it back via
218
+ * {@link history}.
219
+ */
220
+ get sequence(): number;
221
+ /**
222
+ * Fetch retained messages explicitly, instead of waiting for join or
223
+ * reconnect to do it.
224
+ *
225
+ * Defaults to resuming from {@link sequence}. Messages are delivered to
226
+ * `onBroadcast` handlers as usual — the returned value is for callers that
227
+ * want to inspect the batch, or to learn from `retained` that the channel
228
+ * keeps no history at all.
229
+ */
230
+ history(options?: {
231
+ sinceSeq?: number;
232
+ limit?: number;
233
+ }): Promise<ChannelHistoryResult>;
234
+ /** Leave the channel and release every listener and timer. */
235
+ leave(): Promise<void>;
236
+ private stopHeartbeat;
237
+ /** Fold an incoming frame into the roster and fan it out. */
238
+ private handle;
239
+ /** Deliver everything held back during a catch-up, in sequence order. */
240
+ private flushPendingLive;
241
+ private deliver;
242
+ private emitPresence;
243
+ }
@@ -23,6 +23,23 @@ export declare class RebaseWebSocketClient {
23
23
  getAuthToken?: () => Promise<string | null>;
24
24
  private subscriptions;
25
25
  private listeners;
26
+ /** Channel-name → handlers, for broadcast and presence frames. */
27
+ private channelHandlers;
28
+ /** Set by `close()`. Blocks any later operation from silently redialling. */
29
+ private closedByCaller;
30
+ /**
31
+ * Whether a socket exists at all (open or still opening).
32
+ *
33
+ * Lets callers distinguish "authenticate the live socket" from "there is
34
+ * nothing to authenticate yet", without that question forcing a dial.
35
+ */
36
+ get hasSocket(): boolean;
37
+ /** So the "no WebSocket in this environment" warning is said once, not per call. */
38
+ private warnedNoWebSocket;
39
+ /** Subscribe to broadcast/presence frames for one channel. */
40
+ onChannelMessage(channel: string, handler: (message: Record<string, unknown>) => void): () => void;
41
+ /** Notified after the socket comes back, so channels can re-join. */
42
+ onReconnect(handler: () => void): () => void;
26
43
  on(event: "connect" | "disconnect" | "reconnect" | "error", cb: (...args: unknown[]) => void): () => boolean;
27
44
  private emit;
28
45
  private collectionSubscriptions;
@@ -35,6 +52,7 @@ export declare class RebaseWebSocketClient {
35
52
  private isConnected;
36
53
  private messageQueue;
37
54
  private requestTimeoutMs;
55
+ private subscriptionTimeoutMs;
38
56
  private reconnectTimeout;
39
57
  private isAuthenticated;
40
58
  private authPromise;
@@ -42,6 +60,14 @@ export declare class RebaseWebSocketClient {
42
60
  onUnauthorized?: () => Promise<boolean>;
43
61
  private refreshInProgress;
44
62
  constructor(config: RebaseWebSocketConfig);
63
+ /**
64
+ * Open the socket if it is not open (or opening) already.
65
+ *
66
+ * Idempotent, synchronous, and safe to call on every operation that needs a
67
+ * live socket — `initWebSocket` already no-ops on an open socket and is
68
+ * re-entrant, since the reconnect path has always called it.
69
+ */
70
+ ensureConnected(): void;
45
71
  /**
46
72
  * Authenticate the WebSocket connection
47
73
  */
@@ -50,7 +76,15 @@ export declare class RebaseWebSocketClient {
50
76
  * Set the auth token getter function
51
77
  */
52
78
  setAuthTokenGetter(getAuthToken: () => Promise<string | null>): void;
53
- disconnect(): void;
79
+ /**
80
+ * Drop the socket.
81
+ *
82
+ * `permanent` distinguishes the two callers. Signing out drops the socket
83
+ * but the client stays usable — a later subscribe should reconnect
84
+ * anonymously. `client.close()` is the caller saying they are done, and
85
+ * must not be undone by a stray queued frame.
86
+ */
87
+ disconnect(permanent?: boolean): void;
54
88
  private initWebSocket;
55
89
  private processMessageQueue;
56
90
  private attemptReconnect;
@@ -64,7 +98,11 @@ export declare class RebaseWebSocketClient {
64
98
  private handleWebSocketMessage;
65
99
  private ensureAuthenticated;
66
100
  reauthenticate(): Promise<void>;
67
- private sendMessage;
101
+ /**
102
+ * Public because `RebaseRealtimeChannel` sends channel frames through it.
103
+ * Not part of the stable surface — prefer `client.realtime.channel(name)`.
104
+ */
105
+ sendMessage(message: Record<string, unknown>): Promise<unknown>;
68
106
  private doSendMessage;
69
107
  fetchCollection<M extends Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<Record<string, unknown>[]>;
70
108
  fetchOne<M extends Record<string, unknown>>(props: FetchOneProps<M>): Promise<Record<string, unknown> | undefined>;
@@ -76,6 +114,7 @@ export declare class RebaseWebSocketClient {
76
114
  }): Promise<Record<string, unknown>[]>;
77
115
  fetchAvailableDatabases(): Promise<string[]>;
78
116
  fetchAvailableRoles(): Promise<string[]>;
117
+ fetchApplicationRoles(): Promise<string[]>;
79
118
  fetchCurrentDatabase(): Promise<string | undefined>;
80
119
  checkUniqueField(path: string, name: string, value: unknown, id?: string, collection?: CollectionConfig): Promise<boolean>;
81
120
  count<M extends Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<number>;
@@ -114,6 +153,48 @@ export declare class RebaseWebSocketClient {
114
153
  private mergeRows;
115
154
  listenCollection<M extends Record<string, unknown>>(props: FetchCollectionProps<M>, onUpdate: (rows: Record<string, unknown>[]) => void, onError?: (error: Error) => void): () => void;
116
155
  listenOne<M extends Record<string, unknown>>(props: FetchOneProps<M>, onUpdate: (row: Record<string, unknown> | null) => void, onError?: (error: Error) => void): () => void;
156
+ /**
157
+ * Send a `subscribe_collection` for an already-registered subscription and
158
+ * arm its watchdog.
159
+ *
160
+ * Every path that registers a collection subscription goes through here, so
161
+ * that a subscribe which never lands — a rejected send, or a server that
162
+ * never answers — always ends up in `failCollectionSubscription` rather than
163
+ * leaving the entry parked with `isInitialDataReceived === false` forever.
164
+ */
165
+ private sendCollectionSubscribe;
166
+ /** The `listenOne` counterpart of {@link sendCollectionSubscribe}. */
167
+ private sendEntitySubscribe;
168
+ /**
169
+ * Report a subscribe failure to every listener and drop the registration.
170
+ *
171
+ * Dropping it is the point: the callbacks stay live (their components are
172
+ * still mounted and have been told), but the next `listenCollection` for
173
+ * these params finds no entry and issues a fresh subscribe instead of
174
+ * silently attaching to a dead one.
175
+ */
176
+ private failCollectionSubscription;
177
+ /** The `listenOne` counterpart of {@link failCollectionSubscription}. */
178
+ private failEntitySubscription;
179
+ /**
180
+ * Stop the watchdogs without failing anything — used when the socket drops,
181
+ * since the reconnect path re-subscribes everything anyway and a watchdog
182
+ * firing mid-reconnect would tear down healthy subscriptions.
183
+ */
184
+ private suspendSubscribeWatchdogs;
185
+ /**
186
+ * Arm watchdogs for subscribes that were requested while offline and have
187
+ * just been flushed to the socket. Their timers were deliberately not set at
188
+ * request time, so without this they would have no timeout at all.
189
+ */
190
+ private armPendingSubscribeWatchdogs;
191
+ private sendCollectionSubscribeWatchdog;
192
+ private sendEntitySubscribeWatchdog;
193
+ /**
194
+ * Fail every subscription that never received data. Called when reconnection
195
+ * is given up on, so views surface an error instead of spinning forever.
196
+ */
197
+ private failAllPendingSubscriptions;
117
198
  /**
118
199
  * Re-send all active subscriptions to the backend after a reconnect.
119
200
  * The server wipes subscription state when a client disconnects, so
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rebasepro/client",
3
3
  "type": "module",
4
- "version": "0.9.1-canary.f2f61da",
4
+ "version": "0.9.1-canary.faee831",
5
5
  "description": "HTTP SDK client for the Rebase custom backend",
6
6
  "funding": {
7
7
  "url": "https://github.com/sponsors/rebaseco"
@@ -29,20 +29,22 @@
29
29
  "./package.json": "./package.json"
30
30
  },
31
31
  "dependencies": {
32
- "@rebasepro/common": "0.9.1-canary.f2f61da",
33
- "@rebasepro/types": "0.9.1-canary.f2f61da",
34
- "@rebasepro/utils": "0.9.1-canary.f2f61da"
32
+ "@rebasepro/common": "0.9.1-canary.faee831",
33
+ "@rebasepro/types": "0.9.1-canary.faee831",
34
+ "@rebasepro/utils": "0.9.1-canary.faee831"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@jest/globals": "^30.4.1",
38
38
  "@types/jest": "^30.0.0",
39
39
  "@types/node": "^25.9.3",
40
+ "@types/ws": "^8.18.1",
40
41
  "cross-env": "^10.1.0",
41
42
  "jest": "^30.4.2",
42
43
  "ts-jest": "^29.4.11",
43
44
  "tsd": "^0.33.0",
44
45
  "typescript": "^6.0.3",
45
- "vite": "^8.0.16"
46
+ "vite": "^8.0.16",
47
+ "ws": "^8.21.0"
46
48
  },
47
49
  "files": [
48
50
  "dist",
package/src/auth.ts CHANGED
@@ -516,6 +516,37 @@ newPassword })
516
516
  });
517
517
  }
518
518
 
519
+ /**
520
+ * Link an OAuth provider to the **currently signed-in** account.
521
+ *
522
+ * Use this when `signIn*` failed with `EMAIL_NOT_VERIFIED` — an account
523
+ * with that email already exists under a different sign-in method — or to
524
+ * attach a provider whose email differs from the account's.
525
+ *
526
+ * The payload is the same one the provider's sign-in method takes, e.g.
527
+ * `linkProvider("google", { idToken })`.
528
+ *
529
+ * Unlike sign-in, this does not require the provider to have verified the
530
+ * email, and the emails need not match: the active session already proves
531
+ * account ownership.
532
+ *
533
+ * Throws `IDENTITY_ALREADY_LINKED` (409) if that provider identity is
534
+ * attached to a different user. Succeeds idempotently (`alreadyLinked:
535
+ * true`) if it is already attached to the current one.
536
+ */
537
+ async function linkProvider(
538
+ providerId: string,
539
+ payload: Record<string, unknown>
540
+ ) {
541
+ return transport.request<{ success: boolean; provider: string; alreadyLinked: boolean; }>(
542
+ authPath + "/link/" + providerId,
543
+ {
544
+ method: "POST",
545
+ body: JSON.stringify(payload)
546
+ }
547
+ );
548
+ }
549
+
519
550
  async function sendVerificationEmail() {
520
551
  return transport.request<{ success: boolean; message: string; }>(authPath + "/send-verification", {
521
552
  method: "POST"
@@ -666,6 +697,7 @@ refreshToken: session.refreshToken };
666
697
  resetPasswordForEmail,
667
698
  resetPassword,
668
699
  changePassword,
700
+ linkProvider,
669
701
  sendVerificationEmail,
670
702
  verifyEmail,
671
703
  sendMagicLink,
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ import { createFunctionsClient } from "./functions";
10
10
  import { createStorage } from "./storage";
11
11
  import { ClientStorageSourceRegistry } from "./storage-registry";
12
12
  import { RebaseWebSocketClient } from "./websocket";
13
+ import { RebaseRealtimeChannel, type ChannelOptions } from "./realtime-channel";
13
14
  import {
14
15
  DEFAULT_STORAGE_SOURCE_KEY,
15
16
  InsertOf,
@@ -76,6 +77,16 @@ export type { FunctionInvokeOptions, FunctionsClient } from "./functions";
76
77
  // but re-exported (see @internal on the class) because the `client-postgres`
77
78
  // driver constructs it directly. Not a stable app-facing API.
78
79
  export { RebaseWebSocketClient } from "./websocket";
80
+ export { RebaseRealtimeChannel } from "./realtime-channel";
81
+ export type {
82
+ PresenceState,
83
+ PresenceDiff,
84
+ BroadcastEvent,
85
+ ChannelTransport,
86
+ ChannelOptions,
87
+ ChannelHistoryEntry,
88
+ ChannelHistoryResult
89
+ } from "./realtime-channel";
79
90
 
80
91
  export interface CreateRebaseClientOptions extends RebaseClientConfig {
81
92
  auth?: CreateAuthOptions;
@@ -142,6 +153,24 @@ export type CreateRebaseClientResult<DB = Record<string, unknown>> = Omit<Rebase
142
153
  apiKeys: ReturnType<typeof createApiKeys>;
143
154
  functions: ReturnType<typeof createFunctionsClient>;
144
155
  ws?: RebaseWebSocketClient;
156
+ /**
157
+ * Broadcast and presence channels.
158
+ *
159
+ * Was missing from this type while present on the returned object, which
160
+ * made `client.realtime.channel(...)` a type error and forced every adopter
161
+ * to cast around the feature before they could reach it.
162
+ */
163
+ realtime: {
164
+ /**
165
+ * Join a broadcast/presence channel. Repeated calls with the same name
166
+ * return the same channel object. Throws only when the client was
167
+ * created with `realtime: false`.
168
+ *
169
+ * Pass `{ history: true }` to have the channel replay what it missed on
170
+ * join and on every reconnect, for channels the server retains.
171
+ */
172
+ channel: (name: string, options?: ChannelOptions) => RebaseRealtimeChannel;
173
+ };
145
174
  /**
146
175
  * Release the realtime socket and its reconnect timer.
147
176
  *
@@ -256,6 +285,8 @@ export function createRebaseClient<DB = Record<string, unknown>>(options: Create
256
285
  : undefined;
257
286
 
258
287
  let ws: RebaseWebSocketClient | undefined;
288
+ /** One channel object per name — see `realtime.channel`. */
289
+ const realtimeChannels = new Map<string, RebaseRealtimeChannel>();
259
290
  if (resolvedWsUrl) {
260
291
  const wsOnUnauthorized = options.onUnauthorized || (async () => {
261
292
  try {
@@ -283,9 +314,15 @@ export function createRebaseClient<DB = Record<string, unknown>>(options: Create
283
314
  auth.onAuthStateChange((event, session) => {
284
315
  if (!ws) return;
285
316
  if (event === "SIGNED_OUT") {
317
+ // Not permanent: the client stays usable, and a later subscribe
318
+ // should reconnect anonymously.
286
319
  ws.disconnect();
287
320
  } else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
288
- if (session?.accessToken) {
321
+ // Only re-authenticate a socket that already exists. Signing in
322
+ // is not a request for realtime, and dialling here would undo
323
+ // lazy connect for every app with a login. A socket opened
324
+ // later authenticates itself from `getAuthToken` on open.
325
+ if (session?.accessToken && ws.hasSocket) {
289
326
  ws.authenticate(session.accessToken).catch(console.warn);
290
327
  }
291
328
  }
@@ -423,6 +460,40 @@ export function createRebaseClient<DB = Record<string, unknown>>(options: Create
423
460
  createStorageSource,
424
461
  fetchStorageSources,
425
462
  ws,
463
+ realtime: {
464
+ /**
465
+ * Join a broadcast/presence channel.
466
+ *
467
+ * Repeated calls with the same name return the same channel, so
468
+ * separate components can attach handlers without each opening its
469
+ * own membership — and `leave()` from one would otherwise silently
470
+ * cut off the others.
471
+ */
472
+ channel: (name: string, options?: ChannelOptions): RebaseRealtimeChannel => {
473
+ // Only `realtime: false` gets here — a hard opt-out, so this
474
+ // stays an error. Being merely *unconnected* does not: the
475
+ // socket opens on the first channel operation, which is the
476
+ // whole point of asking for a channel before you use one.
477
+ if (!ws) {
478
+ throw new RebaseClientError(
479
+ "Realtime is disabled on this client (realtime: false), so channels are unavailable."
480
+ );
481
+ }
482
+ let existing = realtimeChannels.get(name);
483
+ if (!existing) {
484
+ existing = new RebaseRealtimeChannel(name, ws, options);
485
+ realtimeChannels.set(name, existing);
486
+ } else if (options?.history) {
487
+ // Same object by name, so options on a later call have no
488
+ // new channel to apply to. Asking for history upgrades the
489
+ // one that exists rather than being quietly ignored — but
490
+ // never the reverse, so a caller that omits the option
491
+ // cannot switch it off under one that asked for it.
492
+ existing.enableHistory();
493
+ }
494
+ return existing;
495
+ }
496
+ },
426
497
  /**
427
498
  * Release the realtime socket and its reconnect timer.
428
499
  *
@@ -431,7 +502,14 @@ export function createRebaseClient<DB = Record<string, unknown>>(options: Create
431
502
  * was never started, and safe to call twice.
432
503
  */
433
504
  close: () => {
434
- ws?.disconnect();
505
+ // Channels hold presence heartbeat timers, which would otherwise
506
+ // keep firing (and keep a Node process alive) after the socket
507
+ // they publish over is gone.
508
+ for (const channel of realtimeChannels.values()) void channel.leave();
509
+ realtimeChannels.clear();
510
+ // Permanent: nothing queued afterwards may redial and keep the
511
+ // event loop alive, which is the reason this method exists.
512
+ ws?.disconnect(true);
435
513
  },
436
514
  setToken: transport.setToken,
437
515
  setAuthTokenGetter: transport.setAuthTokenGetter,