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