@mitway/sdk 0.2.3 → 0.3.0

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.
package/dist/index.d.cts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Socket } from 'socket.io-client';
1
2
  import * as _supabase_postgrest_js from '@supabase/postgrest-js';
2
3
 
3
4
  /**
@@ -51,111 +52,339 @@ declare class TokenManager {
51
52
  }
52
53
 
53
54
  /**
54
- * Realtime module — Socket.IO client wrapper for MITWAY-BaaS.
55
+ * Realtime module — Socket.IO client exposing the channel API.
55
56
  *
56
- * Provides a thin, typed layer over `socket.io-client` so app code can
57
- * subscribe / publish / listen without dealing with the underlying
58
- * transport details. The MITWAY-BaaS backend handles auth (JWT / API
59
- * key), RLS, rate limiting, and fan-out across replicas — the SDK just
60
- * opens one socket per `MitwayBaasClient` instance and routes events.
57
+ * Design goals:
58
+ * 1. `client.realtime.channel(topic).on(type, filter, cb).subscribe()` is
59
+ * the single entry point for every primitive.
60
+ * 2. Three binding types coexist on a channel:
61
+ * * `postgres_changes` WAL-based auto-broadcast of DB events,
62
+ * gated by per-subscriber RLS replay in the backend.
63
+ * * `broadcast` — fire-and-forget custom events published
64
+ * via `channel.send({...})` (in-memory fan-out) or via the
65
+ * server-side `realtime.send()` SQL helper.
66
+ * * `presence` — per-channel live "who's here" state.
67
+ * 3. One socket per `Realtime` instance. Multiple channels share it.
68
+ *
69
+ * The wire protocol is defined in the backend's socket.manager.ts.
61
70
  */
62
71
 
63
- /** Standardized meta envelope emitted by the server on every push. */
72
+ type PostgresChangesEventSelector = 'INSERT' | 'UPDATE' | 'DELETE' | '*';
73
+ /** Filter for any event (including the `*` catch-all). */
74
+ interface PostgresChangesFilter {
75
+ event: PostgresChangesEventSelector;
76
+ schema?: string;
77
+ table: string;
78
+ /** PostgREST-style filter: `column=op.value` or `column=in.(a,b,c)`. */
79
+ filter?: string;
80
+ }
81
+ /** Common shape shared by every postgres_changes payload variant. */
82
+ interface PostgresChangesPayloadBase {
83
+ schema: string;
84
+ table: string;
85
+ commit_timestamp: string;
86
+ columns: Array<{
87
+ name: string;
88
+ type: string;
89
+ }>;
90
+ errors?: string[];
91
+ }
92
+ /** INSERT: the new row is in `new`. `old` is kept as an empty object so
93
+ * code that accesses both fields never needs optional chaining. */
94
+ interface PostgresChangesInsertPayload<T = Record<string, unknown>> extends PostgresChangesPayloadBase {
95
+ eventType: 'INSERT';
96
+ new: T;
97
+ old: Record<string, never>;
98
+ }
99
+ /** UPDATE: both `new` and `old` are populated. `old` is `Partial<T>`
100
+ * because RLS / REPLICA IDENTITY may strip columns the subscriber can't
101
+ * see. */
102
+ interface PostgresChangesUpdatePayload<T = Record<string, unknown>> extends PostgresChangesPayloadBase {
103
+ eventType: 'UPDATE';
104
+ new: T;
105
+ old: Partial<T>;
106
+ }
107
+ /** DELETE: the deleted row is in `old`. On RLS-enabled tables only
108
+ * primary-key columns are populated. `new` is always an empty object. */
109
+ interface PostgresChangesDeletePayload<T = Record<string, unknown>> extends PostgresChangesPayloadBase {
110
+ eventType: 'DELETE';
111
+ new: Record<string, never>;
112
+ old: Partial<T>;
113
+ }
114
+ /** Discriminated union — what the `'*'` overload of `on('postgres_changes',
115
+ * ...)` passes to the callback. */
116
+ type PostgresChangesPayload<T = Record<string, unknown>> = PostgresChangesInsertPayload<T> | PostgresChangesUpdatePayload<T> | PostgresChangesDeletePayload<T>;
117
+ interface BroadcastFilter {
118
+ event: string;
119
+ }
120
+ interface BroadcastPayload<T = Record<string, unknown>> {
121
+ type: 'broadcast';
122
+ event: string;
123
+ payload: T;
124
+ }
125
+ /** Presence event selector used with `.on('presence', { event }, cb)`. */
126
+ type PresenceEventSelector = 'sync' | 'join' | 'leave';
127
+ interface PresenceFilter {
128
+ event: PresenceEventSelector;
129
+ }
130
+ /** State map keyed by opaque client key (the socket id on our server side).
131
+ * The client treats these keys as blackboxes — just compare across sync /
132
+ * join / leave deltas to track which participants appeared or departed. */
133
+ type PresenceState<T = Record<string, unknown>> = Record<string, T>;
134
+ interface PresenceSyncPayload<T = Record<string, unknown>> {
135
+ event: 'sync';
136
+ state: PresenceState<T>;
137
+ }
138
+ interface PresenceJoinPayload<T = Record<string, unknown>> {
139
+ event: 'join';
140
+ /** One-entry map `{ [key]: state }` with the new or updated state. */
141
+ joins: PresenceState<T>;
142
+ }
143
+ interface PresenceLeavePayload<T = Record<string, unknown>> {
144
+ event: 'leave';
145
+ /** One-entry map `{ [key]: state }` with the state just before leaving. */
146
+ leaves: PresenceState<T>;
147
+ }
148
+ type PresencePayload<T = Record<string, unknown>> = PresenceSyncPayload<T> | PresenceJoinPayload<T> | PresenceLeavePayload<T>;
64
149
  interface RealtimeMessageMeta {
65
150
  channel?: string;
66
151
  message_id: string;
67
- sender_type: 'system' | 'user';
68
152
  sender_id?: string;
69
153
  timestamp: string;
70
154
  }
71
- /** Subscribe ack returned by the server. */
72
- type SubscribeResult = {
73
- ok: true;
74
- channel: string;
75
- } | {
76
- ok: false;
77
- channel: string;
78
- error: {
79
- code: string;
80
- message: string;
155
+ /**
156
+ * Channel configuration — passed to `client.realtime.channel(topic, opts)`.
157
+ * Every option has a safe default so apps can omit `opts` entirely for the
158
+ * common case.
159
+ */
160
+ interface ChannelOptions {
161
+ config?: {
162
+ /** When true, subscribe is gated on `realtime.authorize_subscribe(role,
163
+ * claims, topic)` at the server side. Replay is also gated if
164
+ * requested on a private channel. Default: `false` (open topic). */
165
+ private?: boolean;
166
+ broadcast?: {
167
+ /** When `false`, the sending socket is excluded from the fan-out.
168
+ * Default: `true` (sender also receives its own broadcasts). */
169
+ self?: boolean;
170
+ };
171
+ presence?: {
172
+ /** Optional stable key that replaces the socket id in the presence
173
+ * hash. Useful to group multiple tabs of the same user under one
174
+ * entry. Default: socket id (each tab is a separate entry). */
175
+ key?: string;
176
+ };
81
177
  };
82
- };
83
- /** Server-pushed unsolicited error. */
84
- interface RealtimeErrorPayload {
85
- channel?: string;
86
- code: string;
87
- message: string;
88
- }
89
- interface RealtimeListener<T = unknown> {
90
- (payload: T, meta: RealtimeMessageMeta): void;
91
178
  }
92
- type ConnectionListener = () => void;
93
- type DisconnectListener = (reason: string) => void;
94
- type ConnectErrorListener = (error: Error) => void;
179
+ type ChannelStatus = 'SUBSCRIBED' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED';
180
+ /** Callback invoked for every channel status transition. The second
181
+ * argument is a standard `Error` (so consumers can annotate it as
182
+ * `err: Error` out of the box) with a non-standard `.code` string
183
+ * attached for programmatic discrimination (`SUBSCRIBE_FAILED`,
184
+ * `CONNECT_FAILED`, `REJOIN_FAILED`, …). */
185
+ type ChannelStatusCallback = (status: ChannelStatus, error?: Error & {
186
+ code?: string;
187
+ }) => void;
95
188
  interface RealtimeOptions {
96
- /** Override the path on the server. Defaults to the Socket.IO default. */
97
189
  path?: string;
98
- /** Transport strategy. Defaults to `['websocket']` — modern browsers
99
- * and Node always support it, no need for the long-polling fallback. */
100
190
  transports?: Array<'websocket' | 'polling'>;
101
- /** Handshake timeout in ms. */
102
191
  timeoutMs?: number;
103
- /** Extra fields merged into socket.handshake.auth. Advanced usage. */
104
192
  extraAuth?: Record<string, string>;
105
193
  }
106
- /**
107
- * MITWAY-BaaS realtime client.
108
- *
109
- * Public API mirrors the InsForge realtime SDK for familiarity, but the
110
- * wire protocol follows our backend (see
111
- * `MITWAY-BaaS/backend/src/infra/socket/socket.manager.ts`):
112
- *
113
- * - Handshake auth uses `auth.token` containing the JWT (preferred)
114
- * or an opaque API key string.
115
- * - `realtime:subscribe` / `realtime:unsubscribe` / `realtime:publish`
116
- * are the client-to-server events.
117
- * - Server pushes the user-defined `event` name with `{ ...payload,
118
- * meta }` shape.
119
- * - `realtime:error` is the unsolicited error channel for publish
120
- * failures and similar.
121
- */
194
+ type BroadcastCallback<T = Record<string, unknown>> = (payload: BroadcastPayload<T>) => void;
195
+ type PresenceSyncCallback = () => void;
196
+ type PresenceJoinCallback<T = Record<string, unknown>> = (payload: PresenceJoinPayload<T>) => void;
197
+ type PresenceLeaveCallback<T = Record<string, unknown>> = (payload: PresenceLeavePayload<T>) => void;
198
+ declare class RealtimeChannel {
199
+ readonly topic: string;
200
+ private readonly realtime;
201
+ private bindings;
202
+ private state;
203
+ private statusCallback;
204
+ /** Local presence state mirror — populated from `presence_state` /
205
+ * `presence_join` / `presence_leave` events. Read via `presenceState()`. */
206
+ private presence;
207
+ /** Latest state this client has tracked. Non-null means the heartbeat
208
+ * timer is active and we'll re-emit this state every TTL/2. */
209
+ private trackedState;
210
+ private presenceHeartbeat;
211
+ /** Timestamp of the most recently received broadcast on this channel —
212
+ * used as the `since` anchor on replay after reconnect. ISO-8601. */
213
+ private lastBroadcastTimestamp;
214
+ /** Configuration from `channel(topic, opts)`. Frozen at construction. */
215
+ private readonly options;
216
+ constructor(topic: string, realtime: Realtime, options?: ChannelOptions);
217
+ /** Whether this channel was opened as `private: true`. */
218
+ private get isPrivate();
219
+ /** The user-supplied presence key, if any. */
220
+ private get presenceKey();
221
+ /** Internal — exposed for Realtime to drive resubscription after a
222
+ * network hiccup. Returns the current lifecycle state. */
223
+ _state(): 'closed' | 'joining' | 'joined' | 'errored';
224
+ /** Internal — called by `Realtime` when Socket.IO reconnects after a
225
+ * drop. Re-runs the registration flow; the backend assigns fresh
226
+ * subscription_ids and Socket.IO rejoins the per-subscription rooms,
227
+ * so events resume without developer intervention. The user-provided
228
+ * statusCallback (from the original subscribe()) fires again with
229
+ * 'SUBSCRIBED' or 'CHANNEL_ERROR' so the app can reflect state. */
230
+ _rejoinAfterReconnect(): Promise<void>;
231
+ on<T = Record<string, unknown>>(type: 'postgres_changes', filter: {
232
+ event: 'INSERT';
233
+ schema?: string;
234
+ table: string;
235
+ filter?: string;
236
+ }, callback: (payload: PostgresChangesInsertPayload<T>) => void): this;
237
+ on<T = Record<string, unknown>>(type: 'postgres_changes', filter: {
238
+ event: 'UPDATE';
239
+ schema?: string;
240
+ table: string;
241
+ filter?: string;
242
+ }, callback: (payload: PostgresChangesUpdatePayload<T>) => void): this;
243
+ on<T = Record<string, unknown>>(type: 'postgres_changes', filter: {
244
+ event: 'DELETE';
245
+ schema?: string;
246
+ table: string;
247
+ filter?: string;
248
+ }, callback: (payload: PostgresChangesDeletePayload<T>) => void): this;
249
+ on<T = Record<string, unknown>>(type: 'postgres_changes', filter: {
250
+ event: '*';
251
+ schema?: string;
252
+ table: string;
253
+ filter?: string;
254
+ }, callback: (payload: PostgresChangesPayload<T>) => void): this;
255
+ on<T = Record<string, unknown>>(type: 'broadcast', filter: BroadcastFilter, callback: BroadcastCallback<T>): this;
256
+ on(type: 'presence', filter: {
257
+ event: 'sync';
258
+ }, callback: PresenceSyncCallback): this;
259
+ on<T = Record<string, unknown>>(type: 'presence', filter: {
260
+ event: 'join';
261
+ }, callback: PresenceJoinCallback<T>): this;
262
+ on<T = Record<string, unknown>>(type: 'presence', filter: {
263
+ event: 'leave';
264
+ }, callback: PresenceLeaveCallback<T>): this;
265
+ /**
266
+ * Register or refresh this client's presence entry on the channel. Safe
267
+ * to call many times — state replaces (not merges). Starts a heartbeat
268
+ * timer at TTL/2 so the entry stays alive while the socket is open.
269
+ * The channel must be `subscribe()`d first (the server enforces this).
270
+ */
271
+ track(state: Record<string, unknown>): Promise<void>;
272
+ /**
273
+ * Remove this client's presence entry immediately, stopping the
274
+ * heartbeat. Safe if the client never called `track`.
275
+ */
276
+ untrack(): void;
277
+ /** Snapshot of the current presence state on this channel. Keys are
278
+ * opaque client identifiers (server-assigned). Re-read inside your
279
+ * `.on('presence', { event: 'sync' }, ...)` handler. */
280
+ presenceState<T = Record<string, unknown>>(): PresenceState<T>;
281
+ /**
282
+ * Register all bindings with the server:
283
+ * * For each `broadcast` binding, ensure we're subscribed to the topic
284
+ * (one `realtime:subscribe` for the channel as a whole).
285
+ * * For each `postgres_changes` binding, emit
286
+ * `realtime:postgres_changes:subscribe` and record the assigned
287
+ * subscription_id.
288
+ *
289
+ * `statusCallback` is invoked with `'SUBSCRIBED'` when every binding
290
+ * has ack'd, or with `'CHANNEL_ERROR' | 'TIMED_OUT'` on failure.
291
+ */
292
+ subscribe(statusCallback?: ChannelStatusCallback): this;
293
+ /**
294
+ * Tear down every binding: unsubscribe from the broadcast topic (if
295
+ * any broadcast bindings exist) and remove every postgres_changes
296
+ * subscription by id. Safe to call when state is already closed.
297
+ */
298
+ unsubscribe(): Promise<void>;
299
+ /**
300
+ * Publish a broadcast event to the topic. Broadcasts are always
301
+ * ephemeral — the server fans out to every subscribed socket in memory,
302
+ * with no DB persistence or webhook fan-out. For audited / durable
303
+ * events, write to your own application table and enable
304
+ * `postgres_changes` on it; the SDK will surface the INSERT as a
305
+ * `postgres_changes` event without a separate channel.send call.
306
+ *
307
+ * The returned promise always resolves with the server ack, so callers
308
+ * can `await channel.send(...)` to confirm delivery + get the server-
309
+ * assigned `message_id`. There's no performance cost — Socket.IO piggy-
310
+ * backs the ack on the same frame. Callers that don't need it just
311
+ * don't await.
312
+ */
313
+ send<T extends Record<string, unknown>>(args: {
314
+ type: 'broadcast';
315
+ event: string;
316
+ payload: T;
317
+ }): Promise<{
318
+ status: 'ok';
319
+ message_id: string;
320
+ } | {
321
+ status: 'error';
322
+ error: {
323
+ code: string;
324
+ message: string;
325
+ };
326
+ }>;
327
+ /**
328
+ * Replay SQL-originated broadcasts on this topic since the given
329
+ * timestamp. Delivered only to this socket (same envelope format as
330
+ * live broadcasts; the SDK routes them through `.on('broadcast', ...)`
331
+ * bindings just like the real-time path). Backend caps the window at
332
+ * 24 h and the limit at 1000.
333
+ */
334
+ replay(args: {
335
+ since: string;
336
+ limit?: number;
337
+ }): Promise<void>;
338
+ /** Internal — called by Realtime's event router on every incoming event. */
339
+ _dispatch(event: string, envelope: Record<string, unknown>): void;
340
+ private firePresence;
341
+ private registerAllBindings;
342
+ }
122
343
  declare class Realtime {
123
344
  private socket;
124
- private baseUrl;
125
- private options;
126
- private anonKey;
127
- private tokenManager;
128
- private listeners;
129
- private reserved;
345
+ private readonly baseUrl;
346
+ private readonly options;
347
+ private readonly anonKey;
348
+ private readonly tokenManager;
349
+ private channels;
130
350
  private connecting;
131
- private subscribedChannels;
351
+ /** Flips to `true` once the initial handshake resolves. Differentiates
352
+ * the first `connect` event (part of `openSocket`) from subsequent
353
+ * reconnect events (which should trigger auto-resubscribe). */
354
+ private firstConnected;
132
355
  constructor(baseUrl: string, tokenManager: TokenManager, anonKey: string | undefined, options?: RealtimeOptions);
133
356
  get isConnected(): boolean;
134
357
  get socketId(): string | undefined;
135
- /** Explicitly open the connection. Safe to call multiple times; only
136
- * opens one socket per instance. Subsequent calls during connection
137
- * return the same in-flight promise. */
358
+ /**
359
+ * Get (or create) a channel for `topic`. Channels are cached so multiple
360
+ * `.channel('same')` calls return the same instance.
361
+ *
362
+ * The optional `opts` argument lets the caller configure the channel:
363
+ * * `config.private` — enable subscribe-side authorization against
364
+ * `realtime.authorize_subscribe(...)` on the tenant DB.
365
+ * * `config.broadcast.self` — `false` excludes the sender from the
366
+ * fan-out (defaults to `true`).
367
+ * * `config.presence.key` — stable presence key to group multiple
368
+ * tabs of the same user under one entry.
369
+ *
370
+ * `channel.send()` always resolves with the server ack (see its own
371
+ * docstring); there is no separate opt-in needed.
372
+ *
373
+ * Options are locked in when the channel is first created; subsequent
374
+ * `.channel('same')` calls with different opts are ignored. Pass a
375
+ * different topic to get a different-configured channel.
376
+ */
377
+ channel(topic: string, opts?: ChannelOptions): RealtimeChannel;
138
378
  connect(): Promise<void>;
139
- private openSocket;
140
- /** Close the socket and clear in-memory subscription state. Reserved
141
- * listeners survive so callers can reconnect later via `connect()`. */
379
+ /**
380
+ * Close the socket. Channels are left as-is so they can re-subscribe
381
+ * on the next `connect()` — useful for auth token refresh flows.
382
+ */
142
383
  disconnect(): void;
143
- subscribe(channel: string): Promise<SubscribeResult>;
144
- /** Fire-and-forget. No ack from the server. */
145
- unsubscribe(channel: string): void;
146
- /** Publish via the Socket.IO transport. Subject to RLS INSERT policy
147
- * on `realtime.messages` (disabled by default — the developer must
148
- * add a policy before clients can publish). Returns immediately; any
149
- * server rejection comes through the `error` reserved event. */
150
- publish(channel: string, event: string, payload: Record<string, unknown>): void;
151
- on(event: 'connect', cb: ConnectionListener): void;
152
- on(event: 'disconnect', cb: DisconnectListener): void;
153
- on(event: 'connect_error', cb: ConnectErrorListener): void;
154
- on(event: 'error', cb: RealtimeListener<RealtimeErrorPayload>): void;
155
- on<T = unknown>(event: string, cb: RealtimeListener<T>): void;
156
- off(event: string, cb: (...args: any[]) => void): void;
384
+ _getSocket(): Socket | null;
385
+ _detachChannel(channel: RealtimeChannel): void;
386
+ private openSocket;
157
387
  private dispatch;
158
- private emitReserved;
159
388
  }
160
389
 
161
390
  /**
@@ -548,7 +777,7 @@ declare class MitwayBaasClient {
548
777
  */
549
778
 
550
779
  /**
551
- * Factory function for creating SDK clients (Supabase-style).
780
+ * Factory function for creating SDK clients.
552
781
  *
553
782
  * @example
554
783
  * ```typescript
@@ -562,4 +791,4 @@ declare class MitwayBaasClient {
562
791
  */
563
792
  declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
564
793
 
565
- export { type ApiError, Auth, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type ConnectErrorListener, type ConnectionListener, Database, type DisconnectListener, HttpClient, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, Realtime, type RealtimeErrorPayload, type RealtimeListener, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, type SubscribeResult, TokenManager, type User, createClient, MitwayBaasClient as default };
794
+ export { type ApiError, Auth, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, Database, HttpClient, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesDeletePayload, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesInsertPayload, type PostgresChangesPayload, type PostgresChangesUpdatePayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, TokenManager, type User, createClient, MitwayBaasClient as default };