@depup/supabase__realtime-js 2.99.3-depup.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.
Files changed (104) hide show
  1. package/README.md +32 -0
  2. package/changes.json +14 -0
  3. package/dist/main/RealtimeChannel.d.ts +370 -0
  4. package/dist/main/RealtimeChannel.d.ts.map +1 -0
  5. package/dist/main/RealtimeChannel.js +644 -0
  6. package/dist/main/RealtimeChannel.js.map +1 -0
  7. package/dist/main/RealtimeClient.d.ts +238 -0
  8. package/dist/main/RealtimeClient.d.ts.map +1 -0
  9. package/dist/main/RealtimeClient.js +870 -0
  10. package/dist/main/RealtimeClient.js.map +1 -0
  11. package/dist/main/RealtimePresence.d.ts +76 -0
  12. package/dist/main/RealtimePresence.d.ts.map +1 -0
  13. package/dist/main/RealtimePresence.js +237 -0
  14. package/dist/main/RealtimePresence.js.map +1 -0
  15. package/dist/main/index.d.ts +6 -0
  16. package/dist/main/index.d.ts.map +1 -0
  17. package/dist/main/index.js +18 -0
  18. package/dist/main/index.js.map +1 -0
  19. package/dist/main/lib/constants.d.ts +39 -0
  20. package/dist/main/lib/constants.d.ts.map +1 -0
  21. package/dist/main/lib/constants.js +48 -0
  22. package/dist/main/lib/constants.js.map +1 -0
  23. package/dist/main/lib/push.d.ts +48 -0
  24. package/dist/main/lib/push.d.ts.map +1 -0
  25. package/dist/main/lib/push.js +102 -0
  26. package/dist/main/lib/push.js.map +1 -0
  27. package/dist/main/lib/serializer.d.ts +33 -0
  28. package/dist/main/lib/serializer.d.ts.map +1 -0
  29. package/dist/main/lib/serializer.js +155 -0
  30. package/dist/main/lib/serializer.js.map +1 -0
  31. package/dist/main/lib/timer.d.ts +22 -0
  32. package/dist/main/lib/timer.d.ts.map +1 -0
  33. package/dist/main/lib/timer.js +39 -0
  34. package/dist/main/lib/timer.js.map +1 -0
  35. package/dist/main/lib/transformers.d.ts +109 -0
  36. package/dist/main/lib/transformers.d.ts.map +1 -0
  37. package/dist/main/lib/transformers.js +241 -0
  38. package/dist/main/lib/transformers.js.map +1 -0
  39. package/dist/main/lib/version.d.ts +2 -0
  40. package/dist/main/lib/version.d.ts.map +1 -0
  41. package/dist/main/lib/version.js +11 -0
  42. package/dist/main/lib/version.js.map +1 -0
  43. package/dist/main/lib/websocket-factory.d.ts +81 -0
  44. package/dist/main/lib/websocket-factory.d.ts.map +1 -0
  45. package/dist/main/lib/websocket-factory.js +131 -0
  46. package/dist/main/lib/websocket-factory.js.map +1 -0
  47. package/dist/module/RealtimeChannel.d.ts +370 -0
  48. package/dist/module/RealtimeChannel.d.ts.map +1 -0
  49. package/dist/module/RealtimeChannel.js +639 -0
  50. package/dist/module/RealtimeChannel.js.map +1 -0
  51. package/dist/module/RealtimeClient.d.ts +238 -0
  52. package/dist/module/RealtimeClient.d.ts.map +1 -0
  53. package/dist/module/RealtimeClient.js +866 -0
  54. package/dist/module/RealtimeClient.js.map +1 -0
  55. package/dist/module/RealtimePresence.d.ts +76 -0
  56. package/dist/module/RealtimePresence.d.ts.map +1 -0
  57. package/dist/module/RealtimePresence.js +233 -0
  58. package/dist/module/RealtimePresence.js.map +1 -0
  59. package/dist/module/index.d.ts +6 -0
  60. package/dist/module/index.d.ts.map +1 -0
  61. package/dist/module/index.js +6 -0
  62. package/dist/module/index.js.map +1 -0
  63. package/dist/module/lib/constants.d.ts +39 -0
  64. package/dist/module/lib/constants.d.ts.map +1 -0
  65. package/dist/module/lib/constants.js +45 -0
  66. package/dist/module/lib/constants.js.map +1 -0
  67. package/dist/module/lib/push.d.ts +48 -0
  68. package/dist/module/lib/push.d.ts.map +1 -0
  69. package/dist/module/lib/push.js +99 -0
  70. package/dist/module/lib/push.js.map +1 -0
  71. package/dist/module/lib/serializer.d.ts +33 -0
  72. package/dist/module/lib/serializer.d.ts.map +1 -0
  73. package/dist/module/lib/serializer.js +152 -0
  74. package/dist/module/lib/serializer.js.map +1 -0
  75. package/dist/module/lib/timer.d.ts +22 -0
  76. package/dist/module/lib/timer.d.ts.map +1 -0
  77. package/dist/module/lib/timer.js +36 -0
  78. package/dist/module/lib/timer.js.map +1 -0
  79. package/dist/module/lib/transformers.d.ts +109 -0
  80. package/dist/module/lib/transformers.d.ts.map +1 -0
  81. package/dist/module/lib/transformers.js +229 -0
  82. package/dist/module/lib/transformers.js.map +1 -0
  83. package/dist/module/lib/version.d.ts +2 -0
  84. package/dist/module/lib/version.d.ts.map +1 -0
  85. package/dist/module/lib/version.js +8 -0
  86. package/dist/module/lib/version.js.map +1 -0
  87. package/dist/module/lib/websocket-factory.d.ts +81 -0
  88. package/dist/module/lib/websocket-factory.d.ts.map +1 -0
  89. package/dist/module/lib/websocket-factory.js +127 -0
  90. package/dist/module/lib/websocket-factory.js.map +1 -0
  91. package/dist/tsconfig.module.tsbuildinfo +1 -0
  92. package/dist/tsconfig.tsbuildinfo +1 -0
  93. package/package.json +85 -0
  94. package/src/RealtimeChannel.ts +1039 -0
  95. package/src/RealtimeClient.ts +1023 -0
  96. package/src/RealtimePresence.ts +346 -0
  97. package/src/index.ts +53 -0
  98. package/src/lib/constants.ts +49 -0
  99. package/src/lib/push.ts +121 -0
  100. package/src/lib/serializer.ts +203 -0
  101. package/src/lib/timer.ts +43 -0
  102. package/src/lib/transformers.ts +270 -0
  103. package/src/lib/version.ts +7 -0
  104. package/src/lib/websocket-factory.ts +192 -0
@@ -0,0 +1,866 @@
1
+ import WebSocketFactory from './lib/websocket-factory';
2
+ import { CHANNEL_EVENTS, CONNECTION_STATE, DEFAULT_VERSION, DEFAULT_TIMEOUT, SOCKET_STATES, TRANSPORTS, DEFAULT_VSN, VSN_1_0_0, VSN_2_0_0, WS_CLOSE_NORMAL, } from './lib/constants';
3
+ import Serializer from './lib/serializer';
4
+ import Timer from './lib/timer';
5
+ import { httpEndpointURL } from './lib/transformers';
6
+ import RealtimeChannel from './RealtimeChannel';
7
+ const noop = () => { };
8
+ // Connection-related constants
9
+ const CONNECTION_TIMEOUTS = {
10
+ HEARTBEAT_INTERVAL: 25000,
11
+ RECONNECT_DELAY: 10,
12
+ HEARTBEAT_TIMEOUT_FALLBACK: 100,
13
+ };
14
+ const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000];
15
+ const DEFAULT_RECONNECT_FALLBACK = 10000;
16
+ const WORKER_SCRIPT = `
17
+ addEventListener("message", (e) => {
18
+ if (e.data.event === "start") {
19
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
20
+ }
21
+ });`;
22
+ export default class RealtimeClient {
23
+ /**
24
+ * Initializes the Socket.
25
+ *
26
+ * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol)
27
+ * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol)
28
+ * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation
29
+ * @param options.timeout The default timeout in milliseconds to trigger push timeouts.
30
+ * @param options.params The optional params to pass when connecting.
31
+ * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future.
32
+ * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message.
33
+ * @param options.heartbeatCallback The optional function to handle heartbeat status and latency.
34
+ * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }
35
+ * @param options.logLevel Sets the log level for Realtime
36
+ * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload))
37
+ * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode.
38
+ * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off.
39
+ * @param options.worker Use Web Worker to set a side flow. Defaults to false.
40
+ * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive.
41
+ * @param options.vsn The protocol version to use when connecting. Supported versions are "1.0.0" and "2.0.0". Defaults to "2.0.0".
42
+ * @example
43
+ * ```ts
44
+ * import RealtimeClient from '@supabase/realtime-js'
45
+ *
46
+ * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', {
47
+ * params: { apikey: 'public-anon-key' },
48
+ * })
49
+ * client.connect()
50
+ * ```
51
+ */
52
+ constructor(endPoint, options) {
53
+ var _a;
54
+ this.accessTokenValue = null;
55
+ this.apiKey = null;
56
+ this._manuallySetToken = false;
57
+ this.channels = new Array();
58
+ this.endPoint = '';
59
+ this.httpEndpoint = '';
60
+ /** @deprecated headers cannot be set on websocket connections */
61
+ this.headers = {};
62
+ this.params = {};
63
+ this.timeout = DEFAULT_TIMEOUT;
64
+ this.transport = null;
65
+ this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL;
66
+ this.heartbeatTimer = undefined;
67
+ this.pendingHeartbeatRef = null;
68
+ this.heartbeatCallback = noop;
69
+ this.ref = 0;
70
+ this.reconnectTimer = null;
71
+ this.vsn = DEFAULT_VSN;
72
+ this.logger = noop;
73
+ this.conn = null;
74
+ this.sendBuffer = [];
75
+ this.serializer = new Serializer();
76
+ this.stateChangeCallbacks = {
77
+ open: [],
78
+ close: [],
79
+ error: [],
80
+ message: [],
81
+ };
82
+ this.accessToken = null;
83
+ this._connectionState = 'disconnected';
84
+ this._wasManualDisconnect = false;
85
+ this._authPromise = null;
86
+ this._heartbeatSentAt = null;
87
+ /**
88
+ * Use either custom fetch, if provided, or default fetch to make HTTP requests
89
+ *
90
+ * @internal
91
+ */
92
+ this._resolveFetch = (customFetch) => {
93
+ if (customFetch) {
94
+ return (...args) => customFetch(...args);
95
+ }
96
+ return (...args) => fetch(...args);
97
+ };
98
+ // Validate required parameters
99
+ if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) {
100
+ throw new Error('API key is required to connect to Realtime');
101
+ }
102
+ this.apiKey = options.params.apikey;
103
+ // Initialize endpoint URLs
104
+ this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;
105
+ this.httpEndpoint = httpEndpointURL(endPoint);
106
+ this._initializeOptions(options);
107
+ this._setupReconnectionTimer();
108
+ this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch);
109
+ }
110
+ /**
111
+ * Connects the socket, unless already connected.
112
+ */
113
+ connect() {
114
+ // Skip if already connecting, disconnecting, or connected
115
+ if (this.isConnecting() ||
116
+ this.isDisconnecting() ||
117
+ (this.conn !== null && this.isConnected())) {
118
+ return;
119
+ }
120
+ this._setConnectionState('connecting');
121
+ // Trigger auth if needed and not already in progress
122
+ // This ensures auth is called for standalone RealtimeClient usage
123
+ // while avoiding race conditions with SupabaseClient's immediate setAuth call
124
+ if (this.accessToken && !this._authPromise) {
125
+ this._setAuthSafely('connect');
126
+ }
127
+ // Establish WebSocket connection
128
+ if (this.transport) {
129
+ // Use custom transport if provided
130
+ this.conn = new this.transport(this.endpointURL());
131
+ }
132
+ else {
133
+ // Try to use native WebSocket
134
+ try {
135
+ this.conn = WebSocketFactory.createWebSocket(this.endpointURL());
136
+ }
137
+ catch (error) {
138
+ this._setConnectionState('disconnected');
139
+ const errorMessage = error.message;
140
+ // Provide helpful error message based on environment
141
+ if (errorMessage.includes('Node.js')) {
142
+ throw new Error(`${errorMessage}\n\n` +
143
+ 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' +
144
+ 'Option 1: Use Node.js 22+ which has native WebSocket support\n' +
145
+ 'Option 2: Install and provide the "ws" package:\n\n' +
146
+ ' npm install ws\n\n' +
147
+ ' import ws from "ws"\n' +
148
+ ' const client = new RealtimeClient(url, {\n' +
149
+ ' ...options,\n' +
150
+ ' transport: ws\n' +
151
+ ' })');
152
+ }
153
+ throw new Error(`WebSocket not available: ${errorMessage}`);
154
+ }
155
+ }
156
+ this._setupConnectionHandlers();
157
+ }
158
+ /**
159
+ * Returns the URL of the websocket.
160
+ * @returns string The URL of the websocket.
161
+ */
162
+ endpointURL() {
163
+ return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn }));
164
+ }
165
+ /**
166
+ * Disconnects the socket.
167
+ *
168
+ * @param code A numeric status code to send on disconnect.
169
+ * @param reason A custom reason for the disconnect.
170
+ */
171
+ disconnect(code, reason) {
172
+ if (this.isDisconnecting()) {
173
+ return;
174
+ }
175
+ this._setConnectionState('disconnecting', true);
176
+ if (this.conn) {
177
+ // Setup fallback timer to prevent hanging in disconnecting state
178
+ const fallbackTimer = setTimeout(() => {
179
+ this._setConnectionState('disconnected');
180
+ }, 100);
181
+ this.conn.onclose = () => {
182
+ clearTimeout(fallbackTimer);
183
+ this._setConnectionState('disconnected');
184
+ };
185
+ // Close the WebSocket connection if close method exists
186
+ if (typeof this.conn.close === 'function') {
187
+ if (code) {
188
+ this.conn.close(code, reason !== null && reason !== void 0 ? reason : '');
189
+ }
190
+ else {
191
+ this.conn.close();
192
+ }
193
+ }
194
+ this._teardownConnection();
195
+ }
196
+ else {
197
+ this._setConnectionState('disconnected');
198
+ }
199
+ }
200
+ /**
201
+ * Returns all created channels
202
+ */
203
+ getChannels() {
204
+ return this.channels;
205
+ }
206
+ /**
207
+ * Unsubscribes and removes a single channel
208
+ * @param channel A RealtimeChannel instance
209
+ */
210
+ async removeChannel(channel) {
211
+ const status = await channel.unsubscribe();
212
+ if (this.channels.length === 0) {
213
+ this.disconnect();
214
+ }
215
+ return status;
216
+ }
217
+ /**
218
+ * Unsubscribes and removes all channels
219
+ */
220
+ async removeAllChannels() {
221
+ const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe()));
222
+ this.channels = [];
223
+ this.disconnect();
224
+ return values_1;
225
+ }
226
+ /**
227
+ * Logs the message.
228
+ *
229
+ * For customized logging, `this.logger` can be overridden.
230
+ */
231
+ log(kind, msg, data) {
232
+ this.logger(kind, msg, data);
233
+ }
234
+ /**
235
+ * Returns the current state of the socket.
236
+ */
237
+ connectionState() {
238
+ switch (this.conn && this.conn.readyState) {
239
+ case SOCKET_STATES.connecting:
240
+ return CONNECTION_STATE.Connecting;
241
+ case SOCKET_STATES.open:
242
+ return CONNECTION_STATE.Open;
243
+ case SOCKET_STATES.closing:
244
+ return CONNECTION_STATE.Closing;
245
+ default:
246
+ return CONNECTION_STATE.Closed;
247
+ }
248
+ }
249
+ /**
250
+ * Returns `true` is the connection is open.
251
+ */
252
+ isConnected() {
253
+ return this.connectionState() === CONNECTION_STATE.Open;
254
+ }
255
+ /**
256
+ * Returns `true` if the connection is currently connecting.
257
+ */
258
+ isConnecting() {
259
+ return this._connectionState === 'connecting';
260
+ }
261
+ /**
262
+ * Returns `true` if the connection is currently disconnecting.
263
+ */
264
+ isDisconnecting() {
265
+ return this._connectionState === 'disconnecting';
266
+ }
267
+ /**
268
+ * Creates (or reuses) a {@link RealtimeChannel} for the provided topic.
269
+ *
270
+ * Topics are automatically prefixed with `realtime:` to match the Realtime service.
271
+ * If a channel with the same topic already exists it will be returned instead of creating
272
+ * a duplicate connection.
273
+ */
274
+ channel(topic, params = { config: {} }) {
275
+ const realtimeTopic = `realtime:${topic}`;
276
+ const exists = this.getChannels().find((c) => c.topic === realtimeTopic);
277
+ if (!exists) {
278
+ const chan = new RealtimeChannel(`realtime:${topic}`, params, this);
279
+ this.channels.push(chan);
280
+ return chan;
281
+ }
282
+ else {
283
+ return exists;
284
+ }
285
+ }
286
+ /**
287
+ * Push out a message if the socket is connected.
288
+ *
289
+ * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established.
290
+ */
291
+ push(data) {
292
+ const { topic, event, payload, ref } = data;
293
+ const callback = () => {
294
+ this.encode(data, (result) => {
295
+ var _a;
296
+ (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result);
297
+ });
298
+ };
299
+ this.log('push', `${topic} ${event} (${ref})`, payload);
300
+ if (this.isConnected()) {
301
+ callback();
302
+ }
303
+ else {
304
+ this.sendBuffer.push(callback);
305
+ }
306
+ }
307
+ /**
308
+ * Sets the JWT access token used for channel subscription authorization and Realtime RLS.
309
+ *
310
+ * If param is null it will use the `accessToken` callback function or the token set on the client.
311
+ *
312
+ * On callback used, it will set the value of the token internal to the client.
313
+ *
314
+ * When a token is explicitly provided, it will be preserved across channel operations
315
+ * (including removeChannel and resubscribe). The `accessToken` callback will not be
316
+ * invoked until `setAuth()` is called without arguments.
317
+ *
318
+ * @param token A JWT string to override the token set on the client.
319
+ *
320
+ * @example
321
+ * // Use a manual token (preserved across resubscribes, ignores accessToken callback)
322
+ * client.realtime.setAuth('my-custom-jwt')
323
+ *
324
+ * // Switch back to using the accessToken callback
325
+ * client.realtime.setAuth()
326
+ */
327
+ async setAuth(token = null) {
328
+ this._authPromise = this._performAuth(token);
329
+ try {
330
+ await this._authPromise;
331
+ }
332
+ finally {
333
+ this._authPromise = null;
334
+ }
335
+ }
336
+ /**
337
+ * Returns true if the current access token was explicitly set via setAuth(token),
338
+ * false if it was obtained via the accessToken callback.
339
+ * @internal
340
+ */
341
+ _isManualToken() {
342
+ return this._manuallySetToken;
343
+ }
344
+ /**
345
+ * Sends a heartbeat message if the socket is connected.
346
+ */
347
+ async sendHeartbeat() {
348
+ var _a;
349
+ if (!this.isConnected()) {
350
+ try {
351
+ this.heartbeatCallback('disconnected');
352
+ }
353
+ catch (e) {
354
+ this.log('error', 'error in heartbeat callback', e);
355
+ }
356
+ return;
357
+ }
358
+ // Handle heartbeat timeout and force reconnection if needed
359
+ if (this.pendingHeartbeatRef) {
360
+ this.pendingHeartbeatRef = null;
361
+ this._heartbeatSentAt = null;
362
+ this.log('transport', 'heartbeat timeout. Attempting to re-establish connection');
363
+ try {
364
+ this.heartbeatCallback('timeout');
365
+ }
366
+ catch (e) {
367
+ this.log('error', 'error in heartbeat callback', e);
368
+ }
369
+ // Force reconnection after heartbeat timeout
370
+ this._wasManualDisconnect = false;
371
+ (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(WS_CLOSE_NORMAL, 'heartbeat timeout');
372
+ setTimeout(() => {
373
+ var _a;
374
+ if (!this.isConnected()) {
375
+ (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout();
376
+ }
377
+ }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK);
378
+ return;
379
+ }
380
+ // Send heartbeat message to server
381
+ this._heartbeatSentAt = Date.now();
382
+ this.pendingHeartbeatRef = this._makeRef();
383
+ this.push({
384
+ topic: 'phoenix',
385
+ event: 'heartbeat',
386
+ payload: {},
387
+ ref: this.pendingHeartbeatRef,
388
+ });
389
+ try {
390
+ this.heartbeatCallback('sent');
391
+ }
392
+ catch (e) {
393
+ this.log('error', 'error in heartbeat callback', e);
394
+ }
395
+ this._setAuthSafely('heartbeat');
396
+ }
397
+ /**
398
+ * Sets a callback that receives lifecycle events for internal heartbeat messages.
399
+ * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected).
400
+ */
401
+ onHeartbeat(callback) {
402
+ this.heartbeatCallback = callback;
403
+ }
404
+ /**
405
+ * Flushes send buffer
406
+ */
407
+ flushSendBuffer() {
408
+ if (this.isConnected() && this.sendBuffer.length > 0) {
409
+ this.sendBuffer.forEach((callback) => callback());
410
+ this.sendBuffer = [];
411
+ }
412
+ }
413
+ /**
414
+ * Return the next message ref, accounting for overflows
415
+ *
416
+ * @internal
417
+ */
418
+ _makeRef() {
419
+ let newRef = this.ref + 1;
420
+ if (newRef === this.ref) {
421
+ this.ref = 0;
422
+ }
423
+ else {
424
+ this.ref = newRef;
425
+ }
426
+ return this.ref.toString();
427
+ }
428
+ /**
429
+ * Unsubscribe from channels with the specified topic.
430
+ *
431
+ * @internal
432
+ */
433
+ _leaveOpenTopic(topic) {
434
+ let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining()));
435
+ if (dupChannel) {
436
+ this.log('transport', `leaving duplicate topic "${topic}"`);
437
+ dupChannel.unsubscribe();
438
+ }
439
+ }
440
+ /**
441
+ * Removes a subscription from the socket.
442
+ *
443
+ * @param channel An open subscription.
444
+ *
445
+ * @internal
446
+ */
447
+ _remove(channel) {
448
+ this.channels = this.channels.filter((c) => c.topic !== channel.topic);
449
+ }
450
+ /** @internal */
451
+ _onConnMessage(rawMessage) {
452
+ this.decode(rawMessage.data, (msg) => {
453
+ // Handle heartbeat responses
454
+ if (msg.topic === 'phoenix' &&
455
+ msg.event === 'phx_reply' &&
456
+ msg.ref &&
457
+ msg.ref === this.pendingHeartbeatRef) {
458
+ const latency = this._heartbeatSentAt ? Date.now() - this._heartbeatSentAt : undefined;
459
+ try {
460
+ this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error', latency);
461
+ }
462
+ catch (e) {
463
+ this.log('error', 'error in heartbeat callback', e);
464
+ }
465
+ this._heartbeatSentAt = null;
466
+ this.pendingHeartbeatRef = null;
467
+ }
468
+ // Log incoming message
469
+ const { topic, event, payload, ref } = msg;
470
+ const refString = ref ? `(${ref})` : '';
471
+ const status = payload.status || '';
472
+ this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload);
473
+ // Route message to appropriate channels
474
+ this.channels
475
+ .filter((channel) => channel._isMember(topic))
476
+ .forEach((channel) => channel._trigger(event, payload, ref));
477
+ this._triggerStateCallbacks('message', msg);
478
+ });
479
+ }
480
+ /**
481
+ * Clear specific timer
482
+ * @internal
483
+ */
484
+ _clearTimer(timer) {
485
+ var _a;
486
+ if (timer === 'heartbeat' && this.heartbeatTimer) {
487
+ clearInterval(this.heartbeatTimer);
488
+ this.heartbeatTimer = undefined;
489
+ }
490
+ else if (timer === 'reconnect') {
491
+ (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset();
492
+ }
493
+ }
494
+ /**
495
+ * Clear all timers
496
+ * @internal
497
+ */
498
+ _clearAllTimers() {
499
+ this._clearTimer('heartbeat');
500
+ this._clearTimer('reconnect');
501
+ }
502
+ /**
503
+ * Setup connection handlers for WebSocket events
504
+ * @internal
505
+ */
506
+ _setupConnectionHandlers() {
507
+ if (!this.conn)
508
+ return;
509
+ // Set binary type if supported (browsers and most WebSocket implementations)
510
+ if ('binaryType' in this.conn) {
511
+ ;
512
+ this.conn.binaryType = 'arraybuffer';
513
+ }
514
+ this.conn.onopen = () => this._onConnOpen();
515
+ this.conn.onerror = (error) => this._onConnError(error);
516
+ this.conn.onmessage = (event) => this._onConnMessage(event);
517
+ this.conn.onclose = (event) => this._onConnClose(event);
518
+ if (this.conn.readyState === SOCKET_STATES.open) {
519
+ this._onConnOpen();
520
+ }
521
+ }
522
+ /**
523
+ * Teardown connection and cleanup resources
524
+ * @internal
525
+ */
526
+ _teardownConnection() {
527
+ if (this.conn) {
528
+ if (this.conn.readyState === SOCKET_STATES.open ||
529
+ this.conn.readyState === SOCKET_STATES.connecting) {
530
+ try {
531
+ this.conn.close();
532
+ }
533
+ catch (e) {
534
+ this.log('error', 'Error closing connection', e);
535
+ }
536
+ }
537
+ this.conn.onopen = null;
538
+ this.conn.onerror = null;
539
+ this.conn.onmessage = null;
540
+ this.conn.onclose = null;
541
+ this.conn = null;
542
+ }
543
+ this._clearAllTimers();
544
+ this._terminateWorker();
545
+ this.channels.forEach((channel) => channel.teardown());
546
+ }
547
+ /** @internal */
548
+ _onConnOpen() {
549
+ this._setConnectionState('connected');
550
+ this.log('transport', `connected to ${this.endpointURL()}`);
551
+ // Wait for any pending auth operations before flushing send buffer
552
+ // This ensures channel join messages include the correct access token
553
+ const authPromise = this._authPromise ||
554
+ (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve());
555
+ authPromise
556
+ .then(() => {
557
+ // When subscribe() is called before the accessToken callback has
558
+ // resolved (common on React Native / Expo where token storage is
559
+ // async), the phx_join payload captured at subscribe()-time will
560
+ // have no access_token. By this point auth has settled and
561
+ // this.accessTokenValue holds the real JWT.
562
+ //
563
+ // The stale join messages sitting in sendBuffer captured the old
564
+ // (token-less) payload in a closure, so we cannot simply flush
565
+ // them. Instead we:
566
+ // 1. Patch each channel's joinPush payload with the real token
567
+ // 2. Drop the stale buffered messages
568
+ // 3. Re-send the join for any channel still in "joining" state
569
+ //
570
+ // On browsers this is a harmless no-op: accessTokenValue was
571
+ // already set synchronously before subscribe() ran, so the join
572
+ // payload already had the correct token.
573
+ if (this.accessTokenValue) {
574
+ this.channels.forEach((channel) => {
575
+ channel.updateJoinPayload({ access_token: this.accessTokenValue });
576
+ });
577
+ this.sendBuffer = [];
578
+ this.channels.forEach((channel) => {
579
+ if (channel._isJoining()) {
580
+ channel.joinPush.sent = false;
581
+ channel.joinPush.send();
582
+ }
583
+ });
584
+ }
585
+ this.flushSendBuffer();
586
+ })
587
+ .catch((e) => {
588
+ this.log('error', 'error waiting for auth on connect', e);
589
+ // Proceed anyway to avoid hanging connections
590
+ this.flushSendBuffer();
591
+ });
592
+ this._clearTimer('reconnect');
593
+ if (!this.worker) {
594
+ this._startHeartbeat();
595
+ }
596
+ else {
597
+ if (!this.workerRef) {
598
+ this._startWorkerHeartbeat();
599
+ }
600
+ }
601
+ this._triggerStateCallbacks('open');
602
+ }
603
+ /** @internal */
604
+ _startHeartbeat() {
605
+ this.heartbeatTimer && clearInterval(this.heartbeatTimer);
606
+ this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
607
+ }
608
+ /** @internal */
609
+ _startWorkerHeartbeat() {
610
+ if (this.workerUrl) {
611
+ this.log('worker', `starting worker for from ${this.workerUrl}`);
612
+ }
613
+ else {
614
+ this.log('worker', `starting default worker`);
615
+ }
616
+ const objectUrl = this._workerObjectUrl(this.workerUrl);
617
+ this.workerRef = new Worker(objectUrl);
618
+ this.workerRef.onerror = (error) => {
619
+ this.log('worker', 'worker error', error.message);
620
+ this._terminateWorker();
621
+ };
622
+ this.workerRef.onmessage = (event) => {
623
+ if (event.data.event === 'keepAlive') {
624
+ this.sendHeartbeat();
625
+ }
626
+ };
627
+ this.workerRef.postMessage({
628
+ event: 'start',
629
+ interval: this.heartbeatIntervalMs,
630
+ });
631
+ }
632
+ /**
633
+ * Terminate the Web Worker and clear the reference
634
+ * @internal
635
+ */
636
+ _terminateWorker() {
637
+ if (this.workerRef) {
638
+ this.log('worker', 'terminating worker');
639
+ this.workerRef.terminate();
640
+ this.workerRef = undefined;
641
+ }
642
+ }
643
+ /** @internal */
644
+ _onConnClose(event) {
645
+ var _a;
646
+ this._setConnectionState('disconnected');
647
+ this.log('transport', 'close', event);
648
+ this._triggerChanError();
649
+ this._clearTimer('heartbeat');
650
+ // Only schedule reconnection if it wasn't a manual disconnect
651
+ if (!this._wasManualDisconnect) {
652
+ (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout();
653
+ }
654
+ this._triggerStateCallbacks('close', event);
655
+ }
656
+ /** @internal */
657
+ _onConnError(error) {
658
+ this._setConnectionState('disconnected');
659
+ this.log('transport', `${error}`);
660
+ this._triggerChanError();
661
+ this._triggerStateCallbacks('error', error);
662
+ try {
663
+ this.heartbeatCallback('error');
664
+ }
665
+ catch (e) {
666
+ this.log('error', 'error in heartbeat callback', e);
667
+ }
668
+ }
669
+ /** @internal */
670
+ _triggerChanError() {
671
+ this.channels.forEach((channel) => channel._trigger(CHANNEL_EVENTS.error));
672
+ }
673
+ /** @internal */
674
+ _appendParams(url, params) {
675
+ if (Object.keys(params).length === 0) {
676
+ return url;
677
+ }
678
+ const prefix = url.match(/\?/) ? '&' : '?';
679
+ const query = new URLSearchParams(params);
680
+ return `${url}${prefix}${query}`;
681
+ }
682
+ _workerObjectUrl(url) {
683
+ let result_url;
684
+ if (url) {
685
+ result_url = url;
686
+ }
687
+ else {
688
+ const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' });
689
+ result_url = URL.createObjectURL(blob);
690
+ }
691
+ return result_url;
692
+ }
693
+ /**
694
+ * Set connection state with proper state management
695
+ * @internal
696
+ */
697
+ _setConnectionState(state, manual = false) {
698
+ this._connectionState = state;
699
+ if (state === 'connecting') {
700
+ this._wasManualDisconnect = false;
701
+ }
702
+ else if (state === 'disconnecting') {
703
+ this._wasManualDisconnect = manual;
704
+ }
705
+ }
706
+ /**
707
+ * Perform the actual auth operation
708
+ * @internal
709
+ */
710
+ async _performAuth(token = null) {
711
+ let tokenToSend;
712
+ let isManualToken = false;
713
+ if (token) {
714
+ tokenToSend = token;
715
+ // Track if this is a manually-provided token
716
+ isManualToken = true;
717
+ }
718
+ else if (this.accessToken) {
719
+ // Call the accessToken callback to get fresh token
720
+ try {
721
+ tokenToSend = await this.accessToken();
722
+ }
723
+ catch (e) {
724
+ this.log('error', 'Error fetching access token from callback', e);
725
+ // Fall back to cached value if callback fails
726
+ tokenToSend = this.accessTokenValue;
727
+ }
728
+ }
729
+ else {
730
+ tokenToSend = this.accessTokenValue;
731
+ }
732
+ // Track whether this token was manually set or fetched via callback
733
+ if (isManualToken) {
734
+ this._manuallySetToken = true;
735
+ }
736
+ else if (this.accessToken) {
737
+ // If we used the callback, clear the manual flag
738
+ this._manuallySetToken = false;
739
+ }
740
+ if (this.accessTokenValue != tokenToSend) {
741
+ this.accessTokenValue = tokenToSend;
742
+ this.channels.forEach((channel) => {
743
+ const payload = {
744
+ access_token: tokenToSend,
745
+ version: DEFAULT_VERSION,
746
+ };
747
+ tokenToSend && channel.updateJoinPayload(payload);
748
+ if (channel.joinedOnce && channel._isJoined()) {
749
+ channel._push(CHANNEL_EVENTS.access_token, {
750
+ access_token: tokenToSend,
751
+ });
752
+ }
753
+ });
754
+ }
755
+ }
756
+ /**
757
+ * Wait for any in-flight auth operations to complete
758
+ * @internal
759
+ */
760
+ async _waitForAuthIfNeeded() {
761
+ if (this._authPromise) {
762
+ await this._authPromise;
763
+ }
764
+ }
765
+ /**
766
+ * Safely call setAuth with standardized error handling
767
+ * @internal
768
+ */
769
+ _setAuthSafely(context = 'general') {
770
+ // Only refresh auth if using callback-based tokens
771
+ if (!this._isManualToken()) {
772
+ this.setAuth().catch((e) => {
773
+ this.log('error', `Error setting auth in ${context}`, e);
774
+ });
775
+ }
776
+ }
777
+ /**
778
+ * Trigger state change callbacks with proper error handling
779
+ * @internal
780
+ */
781
+ _triggerStateCallbacks(event, data) {
782
+ try {
783
+ this.stateChangeCallbacks[event].forEach((callback) => {
784
+ try {
785
+ callback(data);
786
+ }
787
+ catch (e) {
788
+ this.log('error', `error in ${event} callback`, e);
789
+ }
790
+ });
791
+ }
792
+ catch (e) {
793
+ this.log('error', `error triggering ${event} callbacks`, e);
794
+ }
795
+ }
796
+ /**
797
+ * Setup reconnection timer with proper configuration
798
+ * @internal
799
+ */
800
+ _setupReconnectionTimer() {
801
+ this.reconnectTimer = new Timer(async () => {
802
+ setTimeout(async () => {
803
+ await this._waitForAuthIfNeeded();
804
+ if (!this.isConnected()) {
805
+ this.connect();
806
+ }
807
+ }, CONNECTION_TIMEOUTS.RECONNECT_DELAY);
808
+ }, this.reconnectAfterMs);
809
+ }
810
+ /**
811
+ * Initialize client options with defaults
812
+ * @internal
813
+ */
814
+ _initializeOptions(options) {
815
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
816
+ // Set defaults
817
+ this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null;
818
+ this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT;
819
+ this.heartbeatIntervalMs =
820
+ (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL;
821
+ this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false;
822
+ this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null;
823
+ this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop;
824
+ this.vsn = (_g = options === null || options === void 0 ? void 0 : options.vsn) !== null && _g !== void 0 ? _g : DEFAULT_VSN;
825
+ // Handle special cases
826
+ if (options === null || options === void 0 ? void 0 : options.params)
827
+ this.params = options.params;
828
+ if (options === null || options === void 0 ? void 0 : options.logger)
829
+ this.logger = options.logger;
830
+ if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) {
831
+ this.logLevel = options.logLevel || options.log_level;
832
+ this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel });
833
+ }
834
+ // Set up functions with defaults
835
+ this.reconnectAfterMs =
836
+ (_h = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _h !== void 0 ? _h : ((tries) => {
837
+ return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK;
838
+ });
839
+ switch (this.vsn) {
840
+ case VSN_1_0_0:
841
+ this.encode =
842
+ (_j = options === null || options === void 0 ? void 0 : options.encode) !== null && _j !== void 0 ? _j : ((payload, callback) => {
843
+ return callback(JSON.stringify(payload));
844
+ });
845
+ this.decode =
846
+ (_k = options === null || options === void 0 ? void 0 : options.decode) !== null && _k !== void 0 ? _k : ((payload, callback) => {
847
+ return callback(JSON.parse(payload));
848
+ });
849
+ break;
850
+ case VSN_2_0_0:
851
+ this.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : this.serializer.encode.bind(this.serializer);
852
+ this.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : this.serializer.decode.bind(this.serializer);
853
+ break;
854
+ default:
855
+ throw new Error(`Unsupported serializer version: ${this.vsn}`);
856
+ }
857
+ // Handle worker setup
858
+ if (this.worker) {
859
+ if (typeof window !== 'undefined' && !window.Worker) {
860
+ throw new Error('Web Worker is not supported');
861
+ }
862
+ this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl;
863
+ }
864
+ }
865
+ }
866
+ //# sourceMappingURL=RealtimeClient.js.map