@supabase/phoenix 0.1.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 (49) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +122 -0
  3. package/assets/js/phoenix/ajax.js +116 -0
  4. package/assets/js/phoenix/channel.js +331 -0
  5. package/assets/js/phoenix/constants.js +35 -0
  6. package/assets/js/phoenix/index.js +212 -0
  7. package/assets/js/phoenix/longpoll.js +192 -0
  8. package/assets/js/phoenix/presence.js +208 -0
  9. package/assets/js/phoenix/push.js +134 -0
  10. package/assets/js/phoenix/serializer.js +133 -0
  11. package/assets/js/phoenix/socket.js +747 -0
  12. package/assets/js/phoenix/timer.js +48 -0
  13. package/assets/js/phoenix/types.js +184 -0
  14. package/assets/js/phoenix/utils.js +16 -0
  15. package/package.json +58 -0
  16. package/priv/static/favicon.ico +0 -0
  17. package/priv/static/phoenix-orange.png +0 -0
  18. package/priv/static/phoenix.cjs.js +1812 -0
  19. package/priv/static/phoenix.cjs.js.map +7 -0
  20. package/priv/static/phoenix.js +1834 -0
  21. package/priv/static/phoenix.min.js +2 -0
  22. package/priv/static/phoenix.mjs +1789 -0
  23. package/priv/static/phoenix.mjs.map +7 -0
  24. package/priv/static/phoenix.png +0 -0
  25. package/priv/static/types/ajax.d.ts +10 -0
  26. package/priv/static/types/ajax.d.ts.map +1 -0
  27. package/priv/static/types/channel.d.ts +167 -0
  28. package/priv/static/types/channel.d.ts.map +1 -0
  29. package/priv/static/types/constants.d.ts +36 -0
  30. package/priv/static/types/constants.d.ts.map +1 -0
  31. package/priv/static/types/index.d.ts +10 -0
  32. package/priv/static/types/index.d.ts.map +1 -0
  33. package/priv/static/types/longpoll.d.ts +29 -0
  34. package/priv/static/types/longpoll.d.ts.map +1 -0
  35. package/priv/static/types/presence.d.ts +107 -0
  36. package/priv/static/types/presence.d.ts.map +1 -0
  37. package/priv/static/types/push.d.ts +70 -0
  38. package/priv/static/types/push.d.ts.map +1 -0
  39. package/priv/static/types/serializer.d.ts +74 -0
  40. package/priv/static/types/serializer.d.ts.map +1 -0
  41. package/priv/static/types/socket.d.ts +284 -0
  42. package/priv/static/types/socket.d.ts.map +1 -0
  43. package/priv/static/types/timer.d.ts +36 -0
  44. package/priv/static/types/timer.d.ts.map +1 -0
  45. package/priv/static/types/types.d.ts +280 -0
  46. package/priv/static/types/types.d.ts.map +1 -0
  47. package/priv/static/types/utils.d.ts +2 -0
  48. package/priv/static/types/utils.d.ts.map +1 -0
  49. package/tsconfig.json +20 -0
@@ -0,0 +1,1834 @@
1
+ "use strict";
2
+ var Phoenix = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+
41
+ // js/phoenix/index.js
42
+ var phoenix_exports = {};
43
+ __export(phoenix_exports, {
44
+ Channel: () => Channel,
45
+ LongPoll: () => LongPoll,
46
+ Presence: () => Presence,
47
+ Push: () => Push,
48
+ Serializer: () => serializer_default,
49
+ Socket: () => Socket,
50
+ Timer: () => Timer
51
+ });
52
+
53
+ // js/phoenix/utils.js
54
+ var closure = (value) => {
55
+ if (typeof value === "function") {
56
+ return (
57
+ /** @type {() => T} */
58
+ value
59
+ );
60
+ } else {
61
+ let closure2 = function() {
62
+ return value;
63
+ };
64
+ return closure2;
65
+ }
66
+ };
67
+
68
+ // js/phoenix/constants.js
69
+ var globalSelf = typeof self !== "undefined" ? self : null;
70
+ var phxWindow = typeof window !== "undefined" ? window : null;
71
+ var global = globalSelf || phxWindow || globalThis;
72
+ var DEFAULT_VSN = "2.0.0";
73
+ var DEFAULT_TIMEOUT = 1e4;
74
+ var WS_CLOSE_NORMAL = 1e3;
75
+ var SOCKET_STATES = (
76
+ /** @type {const} */
77
+ { connecting: 0, open: 1, closing: 2, closed: 3 }
78
+ );
79
+ var CHANNEL_STATES = (
80
+ /** @type {const} */
81
+ {
82
+ closed: "closed",
83
+ errored: "errored",
84
+ joined: "joined",
85
+ joining: "joining",
86
+ leaving: "leaving"
87
+ }
88
+ );
89
+ var CHANNEL_EVENTS = (
90
+ /** @type {const} */
91
+ {
92
+ close: "phx_close",
93
+ error: "phx_error",
94
+ join: "phx_join",
95
+ reply: "phx_reply",
96
+ leave: "phx_leave"
97
+ }
98
+ );
99
+ var TRANSPORTS = (
100
+ /** @type {const} */
101
+ {
102
+ longpoll: "longpoll",
103
+ websocket: "websocket"
104
+ }
105
+ );
106
+ var XHR_STATES = (
107
+ /** @type {const} */
108
+ {
109
+ complete: 4
110
+ }
111
+ );
112
+ var AUTH_TOKEN_PREFIX = "base64url.bearer.phx.";
113
+
114
+ // js/phoenix/push.js
115
+ var Push = class {
116
+ /**
117
+ * Initializes the Push
118
+ * @param {Channel} channel - The Channel
119
+ * @param {ChannelEvent} event - The event, for example `"phx_join"`
120
+ * @param {() => Record<string, unknown>} payload - The payload, for example `{user_id: 123}`
121
+ * @param {number} timeout - The push timeout in milliseconds
122
+ */
123
+ constructor(channel, event, payload, timeout) {
124
+ this.channel = channel;
125
+ this.event = event;
126
+ this.payload = payload || function() {
127
+ return {};
128
+ };
129
+ this.receivedResp = null;
130
+ this.timeout = timeout;
131
+ this.timeoutTimer = null;
132
+ this.recHooks = [];
133
+ this.sent = false;
134
+ this.ref = void 0;
135
+ }
136
+ /**
137
+ *
138
+ * @param {number} timeout
139
+ */
140
+ resend(timeout) {
141
+ this.timeout = timeout;
142
+ this.reset();
143
+ this.send();
144
+ }
145
+ /**
146
+ *
147
+ */
148
+ send() {
149
+ if (this.hasReceived("timeout")) {
150
+ return;
151
+ }
152
+ this.startTimeout();
153
+ this.sent = true;
154
+ this.channel.socket.push({
155
+ topic: this.channel.topic,
156
+ event: this.event,
157
+ payload: this.payload(),
158
+ ref: this.ref,
159
+ join_ref: this.channel.joinRef()
160
+ });
161
+ }
162
+ /**
163
+ *
164
+ * @param {string} status
165
+ * @param {(response: any) => void} callback
166
+ */
167
+ receive(status, callback) {
168
+ if (this.hasReceived(status)) {
169
+ callback(this.receivedResp.response);
170
+ }
171
+ this.recHooks.push({ status, callback });
172
+ return this;
173
+ }
174
+ reset() {
175
+ this.cancelRefEvent();
176
+ this.ref = null;
177
+ this.refEvent = null;
178
+ this.receivedResp = null;
179
+ this.sent = false;
180
+ }
181
+ destroy() {
182
+ this.cancelRefEvent();
183
+ this.cancelTimeout();
184
+ }
185
+ /**
186
+ * @private
187
+ */
188
+ matchReceive({ status, response, _ref }) {
189
+ this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response));
190
+ }
191
+ /**
192
+ * @private
193
+ */
194
+ cancelRefEvent() {
195
+ if (!this.refEvent) {
196
+ return;
197
+ }
198
+ this.channel.off(this.refEvent);
199
+ }
200
+ cancelTimeout() {
201
+ clearTimeout(this.timeoutTimer);
202
+ this.timeoutTimer = null;
203
+ }
204
+ startTimeout() {
205
+ if (this.timeoutTimer) {
206
+ this.cancelTimeout();
207
+ }
208
+ this.ref = this.channel.socket.makeRef();
209
+ this.refEvent = this.channel.replyEventName(this.ref);
210
+ this.channel.on(this.refEvent, (payload) => {
211
+ this.cancelRefEvent();
212
+ this.cancelTimeout();
213
+ this.receivedResp = payload;
214
+ this.matchReceive(payload);
215
+ });
216
+ this.timeoutTimer = setTimeout(() => {
217
+ this.trigger("timeout", {});
218
+ }, this.timeout);
219
+ }
220
+ /**
221
+ * @private
222
+ */
223
+ hasReceived(status) {
224
+ return this.receivedResp && this.receivedResp.status === status;
225
+ }
226
+ trigger(status, response) {
227
+ this.channel.trigger(this.refEvent, { status, response });
228
+ }
229
+ };
230
+
231
+ // js/phoenix/timer.js
232
+ var Timer = class {
233
+ /**
234
+ * @param {() => void} callback
235
+ * @param {(tries: number) => number} timerCalc
236
+ */
237
+ constructor(callback, timerCalc) {
238
+ this.callback = callback;
239
+ this.timerCalc = timerCalc;
240
+ this.timer = void 0;
241
+ this.tries = 0;
242
+ }
243
+ reset() {
244
+ this.tries = 0;
245
+ clearTimeout(this.timer);
246
+ }
247
+ /**
248
+ * Cancels any previous scheduleTimeout and schedules callback
249
+ */
250
+ scheduleTimeout() {
251
+ clearTimeout(this.timer);
252
+ this.timer = setTimeout(() => {
253
+ this.tries = this.tries + 1;
254
+ this.callback();
255
+ }, this.timerCalc(this.tries + 1));
256
+ }
257
+ };
258
+
259
+ // js/phoenix/channel.js
260
+ var Channel = class {
261
+ /**
262
+ * @param {string} topic
263
+ * @param {Params | (() => Params)} params
264
+ * @param {Socket} socket
265
+ */
266
+ constructor(topic, params, socket) {
267
+ this.state = CHANNEL_STATES.closed;
268
+ this.topic = topic;
269
+ this.params = closure(params || {});
270
+ this.socket = socket;
271
+ this.bindings = [];
272
+ this.bindingRef = 0;
273
+ this.timeout = this.socket.timeout;
274
+ this.joinedOnce = false;
275
+ this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
276
+ this.pushBuffer = [];
277
+ this.stateChangeRefs = [];
278
+ this.rejoinTimer = new Timer(() => {
279
+ if (this.socket.isConnected()) {
280
+ this.rejoin();
281
+ }
282
+ }, this.socket.rejoinAfterMs);
283
+ this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset()));
284
+ this.stateChangeRefs.push(
285
+ this.socket.onOpen(() => {
286
+ this.rejoinTimer.reset();
287
+ if (this.isErrored()) {
288
+ this.rejoin();
289
+ }
290
+ })
291
+ );
292
+ this.joinPush.receive("ok", () => {
293
+ this.state = CHANNEL_STATES.joined;
294
+ this.rejoinTimer.reset();
295
+ this.pushBuffer.forEach((pushEvent) => pushEvent.send());
296
+ this.pushBuffer = [];
297
+ });
298
+ this.joinPush.receive("error", (reason) => {
299
+ this.state = CHANNEL_STATES.errored;
300
+ if (this.socket.hasLogger()) this.socket.log("channel", `error ${this.topic}`, reason);
301
+ if (this.socket.isConnected()) {
302
+ this.rejoinTimer.scheduleTimeout();
303
+ }
304
+ });
305
+ this.onClose(() => {
306
+ this.rejoinTimer.reset();
307
+ if (this.socket.hasLogger()) this.socket.log("channel", `close ${this.topic}`);
308
+ this.state = CHANNEL_STATES.closed;
309
+ this.socket.remove(this);
310
+ });
311
+ this.onError((reason) => {
312
+ if (this.socket.hasLogger()) this.socket.log("channel", `error ${this.topic}`, reason);
313
+ if (this.isJoining()) {
314
+ this.joinPush.reset();
315
+ }
316
+ this.state = CHANNEL_STATES.errored;
317
+ if (this.socket.isConnected()) {
318
+ this.rejoinTimer.scheduleTimeout();
319
+ }
320
+ });
321
+ this.joinPush.receive("timeout", () => {
322
+ if (this.socket.hasLogger()) this.socket.log("channel", `timeout ${this.topic}`, this.joinPush.timeout);
323
+ let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout);
324
+ leavePush.send();
325
+ this.state = CHANNEL_STATES.errored;
326
+ this.joinPush.reset();
327
+ if (this.socket.isConnected()) {
328
+ this.rejoinTimer.scheduleTimeout();
329
+ }
330
+ });
331
+ this.on(CHANNEL_EVENTS.reply, (payload, ref) => {
332
+ this.trigger(this.replyEventName(ref), payload);
333
+ });
334
+ }
335
+ /**
336
+ * Join the channel
337
+ * @param {number} timeout
338
+ * @returns {Push}
339
+ */
340
+ join(timeout = this.timeout) {
341
+ if (this.joinedOnce) {
342
+ throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");
343
+ } else {
344
+ this.timeout = timeout;
345
+ this.joinedOnce = true;
346
+ this.rejoin();
347
+ return this.joinPush;
348
+ }
349
+ }
350
+ /**
351
+ * Teardown the channel.
352
+ *
353
+ * Destroys and stops related timers.
354
+ */
355
+ teardown() {
356
+ this.pushBuffer.forEach((push) => push.destroy());
357
+ this.pushBuffer = [];
358
+ this.rejoinTimer.reset();
359
+ this.joinPush.destroy();
360
+ this.state = CHANNEL_STATES.closed;
361
+ this.bindings = {};
362
+ }
363
+ /**
364
+ * Hook into channel close
365
+ * @param {ChannelBindingCallback} callback
366
+ */
367
+ onClose(callback) {
368
+ this.on(CHANNEL_EVENTS.close, callback);
369
+ }
370
+ /**
371
+ * Hook into channel errors
372
+ * @param {ChannelOnErrorCallback} callback
373
+ * @return {number}
374
+ */
375
+ onError(callback) {
376
+ return this.on(CHANNEL_EVENTS.error, (reason) => callback(reason));
377
+ }
378
+ /**
379
+ * Subscribes on channel events
380
+ *
381
+ * Subscription returns a ref counter, which can be used later to
382
+ * unsubscribe the exact event listener
383
+ *
384
+ * @example
385
+ * const ref1 = channel.on("event", do_stuff)
386
+ * const ref2 = channel.on("event", do_other_stuff)
387
+ * channel.off("event", ref1)
388
+ * // Since unsubscription, do_stuff won't fire,
389
+ * // while do_other_stuff will keep firing on the "event"
390
+ *
391
+ * @param {string} event
392
+ * @param {ChannelBindingCallback} callback
393
+ * @returns {number} ref
394
+ */
395
+ on(event, callback) {
396
+ let ref = this.bindingRef++;
397
+ this.bindings.push({ event, ref, callback });
398
+ return ref;
399
+ }
400
+ /**
401
+ * Unsubscribes off of channel events
402
+ *
403
+ * Use the ref returned from a channel.on() to unsubscribe one
404
+ * handler, or pass nothing for the ref to unsubscribe all
405
+ * handlers for the given event.
406
+ *
407
+ * @example
408
+ * // Unsubscribe the do_stuff handler
409
+ * const ref1 = channel.on("event", do_stuff)
410
+ * channel.off("event", ref1)
411
+ *
412
+ * // Unsubscribe all handlers from event
413
+ * channel.off("event")
414
+ *
415
+ * @param {string} event
416
+ * @param {number} [ref]
417
+ */
418
+ off(event, ref) {
419
+ this.bindings = this.bindings.filter((bind) => {
420
+ return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref));
421
+ });
422
+ }
423
+ /**
424
+ * @private
425
+ */
426
+ canPush() {
427
+ return this.socket.isConnected() && this.isJoined();
428
+ }
429
+ /**
430
+ * Sends a message `event` to phoenix with the payload `payload`.
431
+ * Phoenix receives this in the `handle_in(event, payload, socket)`
432
+ * function. if phoenix replies or it times out (default 10000ms),
433
+ * then optionally the reply can be received.
434
+ *
435
+ * @example
436
+ * channel.push("event")
437
+ * .receive("ok", payload => console.log("phoenix replied:", payload))
438
+ * .receive("error", err => console.log("phoenix errored", err))
439
+ * .receive("timeout", () => console.log("timed out pushing"))
440
+ * @param {string} event
441
+ * @param {Object} payload
442
+ * @param {number} [timeout]
443
+ * @returns {Push}
444
+ */
445
+ push(event, payload, timeout = this.timeout) {
446
+ payload = payload || {};
447
+ if (!this.joinedOnce) {
448
+ throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`);
449
+ }
450
+ let pushEvent = new Push(this, event, function() {
451
+ return payload;
452
+ }, timeout);
453
+ if (this.canPush()) {
454
+ pushEvent.send();
455
+ } else {
456
+ pushEvent.startTimeout();
457
+ this.pushBuffer.push(pushEvent);
458
+ }
459
+ return pushEvent;
460
+ }
461
+ /** Leaves the channel
462
+ *
463
+ * Unsubscribes from server events, and
464
+ * instructs channel to terminate on server
465
+ *
466
+ * Triggers onClose() hooks
467
+ *
468
+ * To receive leave acknowledgements, use the `receive`
469
+ * hook to bind to the server ack, ie:
470
+ *
471
+ * @example
472
+ * channel.leave().receive("ok", () => alert("left!") )
473
+ *
474
+ * @param {number} timeout
475
+ * @returns {Push}
476
+ */
477
+ leave(timeout = this.timeout) {
478
+ this.rejoinTimer.reset();
479
+ this.joinPush.cancelTimeout();
480
+ this.state = CHANNEL_STATES.leaving;
481
+ let onClose = () => {
482
+ if (this.socket.hasLogger()) this.socket.log("channel", `leave ${this.topic}`);
483
+ this.trigger(CHANNEL_EVENTS.close, "leave");
484
+ };
485
+ let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout);
486
+ leavePush.receive("ok", () => onClose()).receive("timeout", () => onClose());
487
+ leavePush.send();
488
+ if (!this.canPush()) {
489
+ leavePush.trigger("ok", {});
490
+ }
491
+ return leavePush;
492
+ }
493
+ /**
494
+ * Overridable message hook
495
+ *
496
+ * Receives all events for specialized message handling
497
+ * before dispatching to the channel callbacks.
498
+ *
499
+ * Must return the payload, modified or unmodified
500
+ * @type{ChannelOnMessage}
501
+ */
502
+ onMessage(_event, payload, _ref) {
503
+ return payload;
504
+ }
505
+ /**
506
+ * Overridable filter hook
507
+ *
508
+ * If this function returns `true`, `binding`'s callback will be called.
509
+ *
510
+ * @type{ChannelFilterBindings}
511
+ */
512
+ filterBindings(_binding, _payload, _ref) {
513
+ return true;
514
+ }
515
+ isMember(topic, event, payload, joinRef) {
516
+ if (this.topic !== topic) {
517
+ return false;
518
+ }
519
+ if (joinRef && joinRef !== this.joinRef()) {
520
+ if (this.socket.hasLogger()) this.socket.log("channel", "dropping outdated message", { topic, event, payload, joinRef });
521
+ return false;
522
+ } else {
523
+ return true;
524
+ }
525
+ }
526
+ joinRef() {
527
+ return this.joinPush.ref;
528
+ }
529
+ /**
530
+ * @private
531
+ */
532
+ rejoin(timeout = this.timeout) {
533
+ if (this.isLeaving()) {
534
+ return;
535
+ }
536
+ this.socket.leaveOpenTopic(this.topic);
537
+ this.state = CHANNEL_STATES.joining;
538
+ this.joinPush.resend(timeout);
539
+ }
540
+ /**
541
+ * @param {string} event
542
+ * @param {unknown} [payload]
543
+ * @param {?string} [ref]
544
+ * @param {?string} [joinRef]
545
+ */
546
+ trigger(event, payload, ref, joinRef) {
547
+ let handledPayload = this.onMessage(event, payload, ref, joinRef);
548
+ if (payload && !handledPayload) {
549
+ throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");
550
+ }
551
+ let eventBindings = this.bindings.filter((bind) => bind.event === event && this.filterBindings(bind, payload, ref));
552
+ for (let i = 0; i < eventBindings.length; i++) {
553
+ let bind = eventBindings[i];
554
+ bind.callback(handledPayload, ref, joinRef || this.joinRef());
555
+ }
556
+ }
557
+ /**
558
+ * @param {string} ref
559
+ */
560
+ replyEventName(ref) {
561
+ return `chan_reply_${ref}`;
562
+ }
563
+ isClosed() {
564
+ return this.state === CHANNEL_STATES.closed;
565
+ }
566
+ isErrored() {
567
+ return this.state === CHANNEL_STATES.errored;
568
+ }
569
+ isJoined() {
570
+ return this.state === CHANNEL_STATES.joined;
571
+ }
572
+ isJoining() {
573
+ return this.state === CHANNEL_STATES.joining;
574
+ }
575
+ isLeaving() {
576
+ return this.state === CHANNEL_STATES.leaving;
577
+ }
578
+ };
579
+
580
+ // js/phoenix/ajax.js
581
+ var Ajax = class {
582
+ static request(method, endPoint, headers, body, timeout, ontimeout, callback) {
583
+ if (global.XDomainRequest) {
584
+ let req = new global.XDomainRequest();
585
+ return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);
586
+ } else if (global.XMLHttpRequest) {
587
+ let req = new global.XMLHttpRequest();
588
+ return this.xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback);
589
+ } else if (global.fetch && global.AbortController) {
590
+ return this.fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback);
591
+ } else {
592
+ throw new Error("No suitable XMLHttpRequest implementation found");
593
+ }
594
+ }
595
+ static fetchRequest(method, endPoint, headers, body, timeout, ontimeout, callback) {
596
+ let options = {
597
+ method,
598
+ headers,
599
+ body
600
+ };
601
+ let controller = null;
602
+ if (timeout) {
603
+ controller = new AbortController();
604
+ const _timeoutId = setTimeout(() => controller.abort(), timeout);
605
+ options.signal = controller.signal;
606
+ }
607
+ global.fetch(endPoint, options).then((response) => response.text()).then((data) => this.parseJSON(data)).then((data) => callback && callback(data)).catch((err) => {
608
+ if (err.name === "AbortError" && ontimeout) {
609
+ ontimeout();
610
+ } else {
611
+ callback && callback(null);
612
+ }
613
+ });
614
+ return controller;
615
+ }
616
+ static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {
617
+ req.timeout = timeout;
618
+ req.open(method, endPoint);
619
+ req.onload = () => {
620
+ let response = this.parseJSON(req.responseText);
621
+ callback && callback(response);
622
+ };
623
+ if (ontimeout) {
624
+ req.ontimeout = ontimeout;
625
+ }
626
+ req.onprogress = () => {
627
+ };
628
+ req.send(body);
629
+ return req;
630
+ }
631
+ static xhrRequest(req, method, endPoint, headers, body, timeout, ontimeout, callback) {
632
+ req.open(method, endPoint, true);
633
+ req.timeout = timeout;
634
+ for (let [key, value] of Object.entries(headers)) {
635
+ req.setRequestHeader(key, value);
636
+ }
637
+ req.onerror = () => callback && callback(null);
638
+ req.onreadystatechange = () => {
639
+ if (req.readyState === XHR_STATES.complete && callback) {
640
+ let response = this.parseJSON(req.responseText);
641
+ callback(response);
642
+ }
643
+ };
644
+ if (ontimeout) {
645
+ req.ontimeout = ontimeout;
646
+ }
647
+ req.send(body);
648
+ return req;
649
+ }
650
+ static parseJSON(resp) {
651
+ if (!resp || resp === "") {
652
+ return null;
653
+ }
654
+ try {
655
+ return JSON.parse(resp);
656
+ } catch (e) {
657
+ console && console.log("failed to parse JSON response", resp);
658
+ return null;
659
+ }
660
+ }
661
+ static serialize(obj, parentKey) {
662
+ let queryStr = [];
663
+ for (var key in obj) {
664
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) {
665
+ continue;
666
+ }
667
+ let paramKey = parentKey ? `${parentKey}[${key}]` : key;
668
+ let paramVal = obj[key];
669
+ if (typeof paramVal === "object") {
670
+ queryStr.push(this.serialize(paramVal, paramKey));
671
+ } else {
672
+ queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal));
673
+ }
674
+ }
675
+ return queryStr.join("&");
676
+ }
677
+ static appendParams(url, params) {
678
+ if (Object.keys(params).length === 0) {
679
+ return url;
680
+ }
681
+ let prefix = url.match(/\?/) ? "&" : "?";
682
+ return `${url}${prefix}${this.serialize(params)}`;
683
+ }
684
+ };
685
+
686
+ // js/phoenix/longpoll.js
687
+ var arrayBufferToBase64 = (buffer) => {
688
+ let binary = "";
689
+ let bytes = new Uint8Array(buffer);
690
+ let len = bytes.byteLength;
691
+ for (let i = 0; i < len; i++) {
692
+ binary += String.fromCharCode(bytes[i]);
693
+ }
694
+ return btoa(binary);
695
+ };
696
+ var LongPoll = class {
697
+ constructor(endPoint, protocols) {
698
+ if (protocols && protocols.length === 2 && protocols[1].startsWith(AUTH_TOKEN_PREFIX)) {
699
+ this.authToken = atob(protocols[1].slice(AUTH_TOKEN_PREFIX.length));
700
+ }
701
+ this.endPoint = null;
702
+ this.token = null;
703
+ this.skipHeartbeat = true;
704
+ this.reqs = /* @__PURE__ */ new Set();
705
+ this.awaitingBatchAck = false;
706
+ this.currentBatch = null;
707
+ this.currentBatchTimer = null;
708
+ this.batchBuffer = [];
709
+ this.onopen = function() {
710
+ };
711
+ this.onerror = function() {
712
+ };
713
+ this.onmessage = function() {
714
+ };
715
+ this.onclose = function() {
716
+ };
717
+ this.pollEndpoint = this.normalizeEndpoint(endPoint);
718
+ this.readyState = SOCKET_STATES.connecting;
719
+ setTimeout(() => this.poll(), 0);
720
+ }
721
+ normalizeEndpoint(endPoint) {
722
+ return endPoint.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll);
723
+ }
724
+ endpointURL() {
725
+ return Ajax.appendParams(this.pollEndpoint, { token: this.token });
726
+ }
727
+ closeAndRetry(code, reason, wasClean) {
728
+ this.close(code, reason, wasClean);
729
+ this.readyState = SOCKET_STATES.connecting;
730
+ }
731
+ ontimeout() {
732
+ this.onerror("timeout");
733
+ this.closeAndRetry(1005, "timeout", false);
734
+ }
735
+ isActive() {
736
+ return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting;
737
+ }
738
+ poll() {
739
+ const headers = { "Accept": "application/json" };
740
+ if (this.authToken) {
741
+ headers["X-Phoenix-AuthToken"] = this.authToken;
742
+ }
743
+ this.ajax("GET", headers, null, () => this.ontimeout(), (resp) => {
744
+ if (resp) {
745
+ var { status, token, messages } = resp;
746
+ if (status === 410 && this.token !== null) {
747
+ this.onerror(410);
748
+ this.closeAndRetry(3410, "session_gone", false);
749
+ return;
750
+ }
751
+ this.token = token;
752
+ } else {
753
+ status = 0;
754
+ }
755
+ switch (status) {
756
+ case 200:
757
+ messages.forEach((msg) => {
758
+ setTimeout(() => this.onmessage({ data: msg }), 0);
759
+ });
760
+ this.poll();
761
+ break;
762
+ case 204:
763
+ this.poll();
764
+ break;
765
+ case 410:
766
+ this.readyState = SOCKET_STATES.open;
767
+ this.onopen({});
768
+ this.poll();
769
+ break;
770
+ case 403:
771
+ this.onerror(403);
772
+ this.close(1008, "forbidden", false);
773
+ break;
774
+ case 0:
775
+ case 500:
776
+ this.onerror(500);
777
+ this.closeAndRetry(1011, "internal server error", 500);
778
+ break;
779
+ default:
780
+ throw new Error(`unhandled poll status ${status}`);
781
+ }
782
+ });
783
+ }
784
+ // we collect all pushes within the current event loop by
785
+ // setTimeout 0, which optimizes back-to-back procedural
786
+ // pushes against an empty buffer
787
+ send(body) {
788
+ if (typeof body !== "string") {
789
+ body = arrayBufferToBase64(body);
790
+ }
791
+ if (this.currentBatch) {
792
+ this.currentBatch.push(body);
793
+ } else if (this.awaitingBatchAck) {
794
+ this.batchBuffer.push(body);
795
+ } else {
796
+ this.currentBatch = [body];
797
+ this.currentBatchTimer = setTimeout(() => {
798
+ this.batchSend(this.currentBatch);
799
+ this.currentBatch = null;
800
+ }, 0);
801
+ }
802
+ }
803
+ batchSend(messages) {
804
+ this.awaitingBatchAck = true;
805
+ this.ajax("POST", { "Content-Type": "application/x-ndjson" }, messages.join("\n"), () => this.onerror("timeout"), (resp) => {
806
+ this.awaitingBatchAck = false;
807
+ if (!resp || resp.status !== 200) {
808
+ this.onerror(resp && resp.status);
809
+ this.closeAndRetry(1011, "internal server error", false);
810
+ } else if (this.batchBuffer.length > 0) {
811
+ this.batchSend(this.batchBuffer);
812
+ this.batchBuffer = [];
813
+ }
814
+ });
815
+ }
816
+ close(code, reason, wasClean) {
817
+ for (let req of this.reqs) {
818
+ req.abort();
819
+ }
820
+ this.readyState = SOCKET_STATES.closed;
821
+ let opts = Object.assign({ code: 1e3, reason: void 0, wasClean: true }, { code, reason, wasClean });
822
+ this.batchBuffer = [];
823
+ clearTimeout(this.currentBatchTimer);
824
+ this.currentBatchTimer = null;
825
+ if (typeof CloseEvent !== "undefined") {
826
+ this.onclose(new CloseEvent("close", opts));
827
+ } else {
828
+ this.onclose(opts);
829
+ }
830
+ }
831
+ ajax(method, headers, body, onCallerTimeout, callback) {
832
+ let req;
833
+ let ontimeout = () => {
834
+ this.reqs.delete(req);
835
+ onCallerTimeout();
836
+ };
837
+ req = Ajax.request(method, this.endpointURL(), headers, body, this.timeout, ontimeout, (resp) => {
838
+ this.reqs.delete(req);
839
+ if (this.isActive()) {
840
+ callback(resp);
841
+ }
842
+ });
843
+ this.reqs.add(req);
844
+ }
845
+ };
846
+
847
+ // js/phoenix/presence.js
848
+ var Presence = class _Presence {
849
+ /**
850
+ * Initializes the Presence
851
+ * @param {Channel} channel - The Channel
852
+ * @param {PresenceOptions} [opts] - The options, for example `{events: {state: "state", diff: "diff"}}`
853
+ */
854
+ constructor(channel, opts = {}) {
855
+ let events = opts.events || /** @type {PresenceEvents} */
856
+ { state: "presence_state", diff: "presence_diff" };
857
+ this.state = {};
858
+ this.pendingDiffs = [];
859
+ this.channel = channel;
860
+ this.joinRef = null;
861
+ this.caller = {
862
+ onJoin: function() {
863
+ },
864
+ onLeave: function() {
865
+ },
866
+ onSync: function() {
867
+ }
868
+ };
869
+ this.channel.on(events.state, (newState) => {
870
+ let { onJoin, onLeave, onSync } = this.caller;
871
+ this.joinRef = this.channel.joinRef();
872
+ this.state = _Presence.syncState(this.state, newState, onJoin, onLeave);
873
+ this.pendingDiffs.forEach((diff) => {
874
+ this.state = _Presence.syncDiff(this.state, diff, onJoin, onLeave);
875
+ });
876
+ this.pendingDiffs = [];
877
+ onSync();
878
+ });
879
+ this.channel.on(events.diff, (diff) => {
880
+ let { onJoin, onLeave, onSync } = this.caller;
881
+ if (this.inPendingSyncState()) {
882
+ this.pendingDiffs.push(diff);
883
+ } else {
884
+ this.state = _Presence.syncDiff(this.state, diff, onJoin, onLeave);
885
+ onSync();
886
+ }
887
+ });
888
+ }
889
+ /**
890
+ * @param {PresenceOnJoin} callback
891
+ */
892
+ onJoin(callback) {
893
+ this.caller.onJoin = callback;
894
+ }
895
+ /**
896
+ * @param {PresenceOnLeave} callback
897
+ */
898
+ onLeave(callback) {
899
+ this.caller.onLeave = callback;
900
+ }
901
+ /**
902
+ * @param {PresenceOnSync} callback
903
+ */
904
+ onSync(callback) {
905
+ this.caller.onSync = callback;
906
+ }
907
+ /**
908
+ * Returns the array of presences, with selected metadata.
909
+ *
910
+ * @template [T=PresenceState]
911
+ * @param {((key: string, obj: PresenceState) => T)} [by]
912
+ *
913
+ * @returns {T[]}
914
+ */
915
+ list(by) {
916
+ return _Presence.list(this.state, by);
917
+ }
918
+ inPendingSyncState() {
919
+ return !this.joinRef || this.joinRef !== this.channel.joinRef();
920
+ }
921
+ // lower-level public static API
922
+ /**
923
+ * Used to sync the list of presences on the server
924
+ * with the client's state. An optional `onJoin` and `onLeave` callback can
925
+ * be provided to react to changes in the client's local presences across
926
+ * disconnects and reconnects with the server.
927
+ *
928
+ * @param {Record<string, PresenceState>} currentState
929
+ * @param {Record<string, PresenceState>} newState
930
+ * @param {PresenceOnJoin} onJoin
931
+ * @param {PresenceOnLeave} onLeave
932
+ *
933
+ * @returns {Record<string, PresenceState>}
934
+ */
935
+ static syncState(currentState, newState, onJoin, onLeave) {
936
+ let state = this.clone(currentState);
937
+ let joins = {};
938
+ let leaves = {};
939
+ this.map(state, (key, presence) => {
940
+ if (!newState[key]) {
941
+ leaves[key] = presence;
942
+ }
943
+ });
944
+ this.map(newState, (key, newPresence) => {
945
+ let currentPresence = state[key];
946
+ if (currentPresence) {
947
+ let newRefs = newPresence.metas.map((m) => m.phx_ref);
948
+ let curRefs = currentPresence.metas.map((m) => m.phx_ref);
949
+ let joinedMetas = newPresence.metas.filter((m) => curRefs.indexOf(m.phx_ref) < 0);
950
+ let leftMetas = currentPresence.metas.filter((m) => newRefs.indexOf(m.phx_ref) < 0);
951
+ if (joinedMetas.length > 0) {
952
+ joins[key] = newPresence;
953
+ joins[key].metas = joinedMetas;
954
+ }
955
+ if (leftMetas.length > 0) {
956
+ leaves[key] = this.clone(currentPresence);
957
+ leaves[key].metas = leftMetas;
958
+ }
959
+ } else {
960
+ joins[key] = newPresence;
961
+ }
962
+ });
963
+ return this.syncDiff(state, { joins, leaves }, onJoin, onLeave);
964
+ }
965
+ /**
966
+ *
967
+ * Used to sync a diff of presence join and leave
968
+ * events from the server, as they happen. Like `syncState`, `syncDiff`
969
+ * accepts optional `onJoin` and `onLeave` callbacks to react to a user
970
+ * joining or leaving from a device.
971
+ *
972
+ * @param {Record<string, PresenceState>} state
973
+ * @param {PresenceDiff} diff
974
+ * @param {PresenceOnJoin} onJoin
975
+ * @param {PresenceOnLeave} onLeave
976
+ *
977
+ * @returns {Record<string, PresenceState>}
978
+ */
979
+ static syncDiff(state, diff, onJoin, onLeave) {
980
+ let { joins, leaves } = this.clone(diff);
981
+ if (!onJoin) {
982
+ onJoin = function() {
983
+ };
984
+ }
985
+ if (!onLeave) {
986
+ onLeave = function() {
987
+ };
988
+ }
989
+ this.map(joins, (key, newPresence) => {
990
+ let currentPresence = state[key];
991
+ state[key] = this.clone(newPresence);
992
+ if (currentPresence) {
993
+ let joinedRefs = state[key].metas.map((m) => m.phx_ref);
994
+ let curMetas = currentPresence.metas.filter((m) => joinedRefs.indexOf(m.phx_ref) < 0);
995
+ state[key].metas.unshift(...curMetas);
996
+ }
997
+ onJoin(key, currentPresence, newPresence);
998
+ });
999
+ this.map(leaves, (key, leftPresence) => {
1000
+ let currentPresence = state[key];
1001
+ if (!currentPresence) {
1002
+ return;
1003
+ }
1004
+ let refsToRemove = leftPresence.metas.map((m) => m.phx_ref);
1005
+ currentPresence.metas = currentPresence.metas.filter((p) => {
1006
+ return refsToRemove.indexOf(p.phx_ref) < 0;
1007
+ });
1008
+ onLeave(key, currentPresence, leftPresence);
1009
+ if (currentPresence.metas.length === 0) {
1010
+ delete state[key];
1011
+ }
1012
+ });
1013
+ return state;
1014
+ }
1015
+ /**
1016
+ * Returns the array of presences, with selected metadata.
1017
+ *
1018
+ * @template [T=PresenceState]
1019
+ * @param {Record<string, PresenceState>} presences
1020
+ * @param {((key: string, obj: PresenceState) => T)} [chooser]
1021
+ *
1022
+ * @returns {T[]}
1023
+ */
1024
+ static list(presences, chooser) {
1025
+ if (!chooser) {
1026
+ chooser = function(key, pres) {
1027
+ return pres;
1028
+ };
1029
+ }
1030
+ return this.map(presences, (key, presence) => {
1031
+ return chooser(key, presence);
1032
+ });
1033
+ }
1034
+ // private
1035
+ /**
1036
+ * @template T
1037
+ * @param {Record<string, PresenceState>} obj
1038
+ * @param {(key: string, obj: PresenceState) => T} func
1039
+ */
1040
+ static map(obj, func) {
1041
+ return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key]));
1042
+ }
1043
+ /**
1044
+ * @template T
1045
+ * @param {T} obj
1046
+ * @returns {T}
1047
+ */
1048
+ static clone(obj) {
1049
+ return JSON.parse(JSON.stringify(obj));
1050
+ }
1051
+ };
1052
+
1053
+ // js/phoenix/serializer.js
1054
+ var serializer_default = {
1055
+ HEADER_LENGTH: 1,
1056
+ META_LENGTH: 4,
1057
+ KINDS: { push: 0, reply: 1, broadcast: 2 },
1058
+ /**
1059
+ * @template T
1060
+ * @param {Message<Record<string, any>>} msg
1061
+ * @param {(msg: ArrayBuffer | string) => T} callback
1062
+ * @returns {T}
1063
+ */
1064
+ encode(msg, callback) {
1065
+ if (msg.payload.constructor === ArrayBuffer) {
1066
+ return callback(this.binaryEncode(msg));
1067
+ } else {
1068
+ let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];
1069
+ return callback(JSON.stringify(payload));
1070
+ }
1071
+ },
1072
+ /**
1073
+ * @template T
1074
+ * @param {ArrayBuffer | string} rawPayload
1075
+ * @param {(msg: Message<unknown>) => T} callback
1076
+ * @returns {T}
1077
+ */
1078
+ decode(rawPayload, callback) {
1079
+ if (rawPayload.constructor === ArrayBuffer) {
1080
+ return callback(this.binaryDecode(rawPayload));
1081
+ } else {
1082
+ let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload);
1083
+ return callback({ join_ref, ref, topic, event, payload });
1084
+ }
1085
+ },
1086
+ /** @private */
1087
+ binaryEncode(message) {
1088
+ let { join_ref, ref, event, topic, payload } = message;
1089
+ let metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length;
1090
+ let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
1091
+ let view = new DataView(header);
1092
+ let offset = 0;
1093
+ view.setUint8(offset++, this.KINDS.push);
1094
+ view.setUint8(offset++, join_ref.length);
1095
+ view.setUint8(offset++, ref.length);
1096
+ view.setUint8(offset++, topic.length);
1097
+ view.setUint8(offset++, event.length);
1098
+ Array.from(join_ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1099
+ Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1100
+ Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1101
+ Array.from(event, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1102
+ var combined = new Uint8Array(header.byteLength + payload.byteLength);
1103
+ combined.set(new Uint8Array(header), 0);
1104
+ combined.set(new Uint8Array(payload), header.byteLength);
1105
+ return combined.buffer;
1106
+ },
1107
+ /**
1108
+ * @private
1109
+ */
1110
+ binaryDecode(buffer) {
1111
+ let view = new DataView(buffer);
1112
+ let kind = view.getUint8(0);
1113
+ let decoder = new TextDecoder();
1114
+ switch (kind) {
1115
+ case this.KINDS.push:
1116
+ return this.decodePush(buffer, view, decoder);
1117
+ case this.KINDS.reply:
1118
+ return this.decodeReply(buffer, view, decoder);
1119
+ case this.KINDS.broadcast:
1120
+ return this.decodeBroadcast(buffer, view, decoder);
1121
+ }
1122
+ },
1123
+ /** @private */
1124
+ decodePush(buffer, view, decoder) {
1125
+ let joinRefSize = view.getUint8(1);
1126
+ let topicSize = view.getUint8(2);
1127
+ let eventSize = view.getUint8(3);
1128
+ let offset = this.HEADER_LENGTH + this.META_LENGTH - 1;
1129
+ let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
1130
+ offset = offset + joinRefSize;
1131
+ let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
1132
+ offset = offset + topicSize;
1133
+ let event = decoder.decode(buffer.slice(offset, offset + eventSize));
1134
+ offset = offset + eventSize;
1135
+ let data = buffer.slice(offset, buffer.byteLength);
1136
+ return { join_ref: joinRef, ref: null, topic, event, payload: data };
1137
+ },
1138
+ /** @private */
1139
+ decodeReply(buffer, view, decoder) {
1140
+ let joinRefSize = view.getUint8(1);
1141
+ let refSize = view.getUint8(2);
1142
+ let topicSize = view.getUint8(3);
1143
+ let eventSize = view.getUint8(4);
1144
+ let offset = this.HEADER_LENGTH + this.META_LENGTH;
1145
+ let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
1146
+ offset = offset + joinRefSize;
1147
+ let ref = decoder.decode(buffer.slice(offset, offset + refSize));
1148
+ offset = offset + refSize;
1149
+ let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
1150
+ offset = offset + topicSize;
1151
+ let event = decoder.decode(buffer.slice(offset, offset + eventSize));
1152
+ offset = offset + eventSize;
1153
+ let data = buffer.slice(offset, buffer.byteLength);
1154
+ let payload = { status: event, response: data };
1155
+ return { join_ref: joinRef, ref, topic, event: CHANNEL_EVENTS.reply, payload };
1156
+ },
1157
+ /** @private */
1158
+ decodeBroadcast(buffer, view, decoder) {
1159
+ let topicSize = view.getUint8(1);
1160
+ let eventSize = view.getUint8(2);
1161
+ let offset = this.HEADER_LENGTH + 2;
1162
+ let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
1163
+ offset = offset + topicSize;
1164
+ let event = decoder.decode(buffer.slice(offset, offset + eventSize));
1165
+ offset = offset + eventSize;
1166
+ let data = buffer.slice(offset, buffer.byteLength);
1167
+ return { join_ref: null, ref: null, topic, event, payload: data };
1168
+ }
1169
+ };
1170
+
1171
+ // js/phoenix/socket.js
1172
+ var Socket = class {
1173
+ /** Initializes the Socket *
1174
+ *
1175
+ * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)
1176
+ *
1177
+ * @constructor
1178
+ * @param {string} endPoint - The string WebSocket endpoint, ie, `"ws://example.com/socket"`,
1179
+ * `"wss://example.com"`
1180
+ * `"/socket"` (inherited host & protocol)
1181
+ * @param {SocketOptions} [opts] - Optional configuration
1182
+ */
1183
+ constructor(endPoint, opts = {}) {
1184
+ var _a, _b;
1185
+ this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] };
1186
+ this.channels = [];
1187
+ this.sendBuffer = [];
1188
+ this.ref = 0;
1189
+ this.fallbackRef = null;
1190
+ this.timeout = opts.timeout || DEFAULT_TIMEOUT;
1191
+ this.transport = opts.transport || global.WebSocket || LongPoll;
1192
+ this.conn = void 0;
1193
+ this.primaryPassedHealthCheck = false;
1194
+ this.longPollFallbackMs = opts.longPollFallbackMs;
1195
+ this.fallbackTimer = null;
1196
+ this.sessionStore = opts.sessionStorage || global && global.sessionStorage;
1197
+ this.establishedConnections = 0;
1198
+ this.defaultEncoder = serializer_default.encode.bind(serializer_default);
1199
+ this.defaultDecoder = serializer_default.decode.bind(serializer_default);
1200
+ this.closeWasClean = false;
1201
+ this.disconnecting = false;
1202
+ this.binaryType = opts.binaryType || "arraybuffer";
1203
+ this.connectClock = 1;
1204
+ this.pageHidden = false;
1205
+ this.encode = void 0;
1206
+ this.decode = void 0;
1207
+ if (this.transport !== LongPoll) {
1208
+ this.encode = opts.encode || this.defaultEncoder;
1209
+ this.decode = opts.decode || this.defaultDecoder;
1210
+ } else {
1211
+ this.encode = this.defaultEncoder;
1212
+ this.decode = this.defaultDecoder;
1213
+ }
1214
+ let awaitingConnectionOnPageShow = null;
1215
+ if (phxWindow && phxWindow.addEventListener) {
1216
+ phxWindow.addEventListener("pagehide", (_e) => {
1217
+ if (this.conn) {
1218
+ this.disconnect();
1219
+ awaitingConnectionOnPageShow = this.connectClock;
1220
+ }
1221
+ });
1222
+ phxWindow.addEventListener("pageshow", (_e) => {
1223
+ if (awaitingConnectionOnPageShow === this.connectClock) {
1224
+ awaitingConnectionOnPageShow = null;
1225
+ this.connect();
1226
+ }
1227
+ });
1228
+ phxWindow.addEventListener("visibilitychange", () => {
1229
+ if (document.visibilityState === "hidden") {
1230
+ this.pageHidden = true;
1231
+ } else {
1232
+ this.pageHidden = false;
1233
+ if (!this.isConnected()) {
1234
+ this.teardown(() => this.connect());
1235
+ }
1236
+ }
1237
+ });
1238
+ }
1239
+ this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 3e4;
1240
+ this.autoSendHeartbeat = (_a = opts.autoSendHeartbeat) != null ? _a : true;
1241
+ this.heartbeatCallback = (_b = opts.heartbeatCallback) != null ? _b : () => {
1242
+ };
1243
+ this.rejoinAfterMs = (tries) => {
1244
+ if (opts.rejoinAfterMs) {
1245
+ return opts.rejoinAfterMs(tries);
1246
+ } else {
1247
+ return [1e3, 2e3, 5e3][tries - 1] || 1e4;
1248
+ }
1249
+ };
1250
+ this.reconnectAfterMs = (tries) => {
1251
+ if (opts.reconnectAfterMs) {
1252
+ return opts.reconnectAfterMs(tries);
1253
+ } else {
1254
+ return [10, 50, 100, 150, 200, 250, 500, 1e3, 2e3][tries - 1] || 5e3;
1255
+ }
1256
+ };
1257
+ this.logger = opts.logger || null;
1258
+ if (!this.logger && opts.debug) {
1259
+ this.logger = (kind, msg, data) => {
1260
+ console.log(`${kind}: ${msg}`, data);
1261
+ };
1262
+ }
1263
+ this.longpollerTimeout = opts.longpollerTimeout || 2e4;
1264
+ this.params = closure(opts.params || {});
1265
+ this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`;
1266
+ this.vsn = opts.vsn || DEFAULT_VSN;
1267
+ this.heartbeatTimeoutTimer = null;
1268
+ this.heartbeatTimer = null;
1269
+ this.heartbeatSentAt = null;
1270
+ this.pendingHeartbeatRef = null;
1271
+ this.reconnectTimer = new Timer(() => {
1272
+ if (this.pageHidden) {
1273
+ this.log("Not reconnecting as page is hidden!");
1274
+ this.teardown();
1275
+ return;
1276
+ }
1277
+ this.teardown(() => __async(this, null, function* () {
1278
+ if (opts.beforeReconnect) yield opts.beforeReconnect();
1279
+ this.connect();
1280
+ }));
1281
+ }, this.reconnectAfterMs);
1282
+ this.authToken = opts.authToken;
1283
+ }
1284
+ /**
1285
+ * Returns the LongPoll transport reference
1286
+ */
1287
+ getLongPollTransport() {
1288
+ return LongPoll;
1289
+ }
1290
+ /**
1291
+ * Disconnects and replaces the active transport
1292
+ *
1293
+ * @param {SocketTransport} newTransport - The new transport class to instantiate
1294
+ *
1295
+ */
1296
+ replaceTransport(newTransport) {
1297
+ this.connectClock++;
1298
+ this.closeWasClean = true;
1299
+ clearTimeout(this.fallbackTimer);
1300
+ this.reconnectTimer.reset();
1301
+ if (this.conn) {
1302
+ this.conn.close();
1303
+ this.conn = null;
1304
+ }
1305
+ this.transport = newTransport;
1306
+ }
1307
+ /**
1308
+ * Returns the socket protocol
1309
+ *
1310
+ * @returns {"wss" | "ws"}
1311
+ */
1312
+ protocol() {
1313
+ return location.protocol.match(/^https/) ? "wss" : "ws";
1314
+ }
1315
+ /**
1316
+ * The fully qualified socket url
1317
+ *
1318
+ * @returns {string}
1319
+ */
1320
+ endPointURL() {
1321
+ let uri = Ajax.appendParams(
1322
+ Ajax.appendParams(this.endPoint, this.params()),
1323
+ { vsn: this.vsn }
1324
+ );
1325
+ if (uri.charAt(0) !== "/") {
1326
+ return uri;
1327
+ }
1328
+ if (uri.charAt(1) === "/") {
1329
+ return `${this.protocol()}:${uri}`;
1330
+ }
1331
+ return `${this.protocol()}://${location.host}${uri}`;
1332
+ }
1333
+ /**
1334
+ * Disconnects the socket
1335
+ *
1336
+ * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes.
1337
+ *
1338
+ * @param {() => void} [callback] - Optional callback which is called after socket is disconnected.
1339
+ * @param {number} [code] - A status code for disconnection (Optional).
1340
+ * @param {string} [reason] - A textual description of the reason to disconnect. (Optional)
1341
+ */
1342
+ disconnect(callback, code, reason) {
1343
+ this.connectClock++;
1344
+ this.disconnecting = true;
1345
+ this.closeWasClean = true;
1346
+ clearTimeout(this.fallbackTimer);
1347
+ this.reconnectTimer.reset();
1348
+ this.teardown(() => {
1349
+ this.disconnecting = false;
1350
+ callback && callback();
1351
+ }, code, reason);
1352
+ }
1353
+ /**
1354
+ * @param {Params} [params] - [DEPRECATED] The params to send when connecting, for example `{user_id: userToken}`
1355
+ *
1356
+ * Passing params to connect is deprecated; pass them in the Socket constructor instead:
1357
+ * `new Socket("/socket", {params: {user_id: userToken}})`.
1358
+ */
1359
+ connect(params) {
1360
+ if (params) {
1361
+ console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor");
1362
+ this.params = closure(params);
1363
+ }
1364
+ if (this.conn && !this.disconnecting) {
1365
+ return;
1366
+ }
1367
+ if (this.longPollFallbackMs && this.transport !== LongPoll) {
1368
+ this.connectWithFallback(LongPoll, this.longPollFallbackMs);
1369
+ } else {
1370
+ this.transportConnect();
1371
+ }
1372
+ }
1373
+ /**
1374
+ * Logs the message. Override `this.logger` for specialized logging. noops by default
1375
+ * @param {string} kind
1376
+ * @param {string} msg
1377
+ * @param {Object} data
1378
+ */
1379
+ log(kind, msg, data) {
1380
+ this.logger && this.logger(kind, msg, data);
1381
+ }
1382
+ /**
1383
+ * Returns true if a logger has been set on this socket.
1384
+ */
1385
+ hasLogger() {
1386
+ return this.logger !== null;
1387
+ }
1388
+ /**
1389
+ * Registers callbacks for connection open events
1390
+ *
1391
+ * @example socket.onOpen(function(){ console.info("the socket was opened") })
1392
+ *
1393
+ * @param {SocketOnOpen} callback
1394
+ */
1395
+ onOpen(callback) {
1396
+ let ref = this.makeRef();
1397
+ this.stateChangeCallbacks.open.push([ref, callback]);
1398
+ return ref;
1399
+ }
1400
+ /**
1401
+ * Registers callbacks for connection close events
1402
+ * @param {SocketOnClose} callback
1403
+ * @returns {string}
1404
+ */
1405
+ onClose(callback) {
1406
+ let ref = this.makeRef();
1407
+ this.stateChangeCallbacks.close.push([ref, callback]);
1408
+ return ref;
1409
+ }
1410
+ /**
1411
+ * Registers callbacks for connection error events
1412
+ *
1413
+ * @example socket.onError(function(error){ alert("An error occurred") })
1414
+ *
1415
+ * @param {SocketOnError} callback
1416
+ * @returns {string}
1417
+ */
1418
+ onError(callback) {
1419
+ let ref = this.makeRef();
1420
+ this.stateChangeCallbacks.error.push([ref, callback]);
1421
+ return ref;
1422
+ }
1423
+ /**
1424
+ * Registers callbacks for connection message events
1425
+ * @param {SocketOnMessage} callback
1426
+ * @returns {string}
1427
+ */
1428
+ onMessage(callback) {
1429
+ let ref = this.makeRef();
1430
+ this.stateChangeCallbacks.message.push([ref, callback]);
1431
+ return ref;
1432
+ }
1433
+ /**
1434
+ * Sets a callback that receives lifecycle events for internal heartbeat messages.
1435
+ * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected).
1436
+ * @param {HeartbeatCallback} callback
1437
+ */
1438
+ onHeartbeat(callback) {
1439
+ this.heartbeatCallback = callback;
1440
+ }
1441
+ /**
1442
+ * Pings the server and invokes the callback with the RTT in milliseconds
1443
+ * @param {(timeDelta: number) => void} callback
1444
+ *
1445
+ * Returns true if the ping was pushed or false if unable to be pushed.
1446
+ */
1447
+ ping(callback) {
1448
+ if (!this.isConnected()) {
1449
+ return false;
1450
+ }
1451
+ let ref = this.makeRef();
1452
+ let startTime = Date.now();
1453
+ this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref });
1454
+ let onMsgRef = this.onMessage((msg) => {
1455
+ if (msg.ref === ref) {
1456
+ this.off([onMsgRef]);
1457
+ callback(Date.now() - startTime);
1458
+ }
1459
+ });
1460
+ return true;
1461
+ }
1462
+ /**
1463
+ * @private
1464
+ */
1465
+ transportConnect() {
1466
+ this.connectClock++;
1467
+ this.closeWasClean = false;
1468
+ let protocols = void 0;
1469
+ if (this.authToken) {
1470
+ protocols = ["phoenix", `${AUTH_TOKEN_PREFIX}${btoa(this.authToken).replace(/=/g, "")}`];
1471
+ }
1472
+ this.conn = new this.transport(this.endPointURL(), protocols);
1473
+ this.conn.binaryType = this.binaryType;
1474
+ this.conn.timeout = this.longpollerTimeout;
1475
+ this.conn.onopen = () => this.onConnOpen();
1476
+ this.conn.onerror = (error) => this.onConnError(error);
1477
+ this.conn.onmessage = (event) => this.onConnMessage(event);
1478
+ this.conn.onclose = (event) => this.onConnClose(event);
1479
+ }
1480
+ getSession(key) {
1481
+ return this.sessionStore && this.sessionStore.getItem(key);
1482
+ }
1483
+ storeSession(key, val) {
1484
+ this.sessionStore && this.sessionStore.setItem(key, val);
1485
+ }
1486
+ connectWithFallback(fallbackTransport, fallbackThreshold = 2500) {
1487
+ clearTimeout(this.fallbackTimer);
1488
+ let established = false;
1489
+ let primaryTransport = true;
1490
+ let openRef, errorRef;
1491
+ let fallback = (reason) => {
1492
+ this.log("transport", `falling back to ${fallbackTransport.name}...`, reason);
1493
+ this.off([openRef, errorRef]);
1494
+ primaryTransport = false;
1495
+ this.replaceTransport(fallbackTransport);
1496
+ this.transportConnect();
1497
+ };
1498
+ if (this.getSession(`phx:fallback:${fallbackTransport.name}`)) {
1499
+ return fallback("memorized");
1500
+ }
1501
+ this.fallbackTimer = setTimeout(fallback, fallbackThreshold);
1502
+ errorRef = this.onError((reason) => {
1503
+ this.log("transport", "error", reason);
1504
+ if (primaryTransport && !established) {
1505
+ clearTimeout(this.fallbackTimer);
1506
+ fallback(reason);
1507
+ }
1508
+ });
1509
+ if (this.fallbackRef) {
1510
+ this.off([this.fallbackRef]);
1511
+ }
1512
+ this.fallbackRef = this.onOpen(() => {
1513
+ established = true;
1514
+ if (!primaryTransport) {
1515
+ if (!this.primaryPassedHealthCheck) {
1516
+ this.storeSession(`phx:fallback:${fallbackTransport.name}`, "true");
1517
+ }
1518
+ return this.log("transport", `established ${fallbackTransport.name} fallback`);
1519
+ }
1520
+ clearTimeout(this.fallbackTimer);
1521
+ this.fallbackTimer = setTimeout(fallback, fallbackThreshold);
1522
+ this.ping((rtt) => {
1523
+ this.log("transport", "connected to primary after", rtt);
1524
+ this.primaryPassedHealthCheck = true;
1525
+ clearTimeout(this.fallbackTimer);
1526
+ });
1527
+ });
1528
+ this.transportConnect();
1529
+ }
1530
+ clearHeartbeats() {
1531
+ clearTimeout(this.heartbeatTimer);
1532
+ clearTimeout(this.heartbeatTimeoutTimer);
1533
+ }
1534
+ onConnOpen() {
1535
+ if (this.hasLogger()) this.log("transport", `connected to ${this.endPointURL()}`);
1536
+ this.closeWasClean = false;
1537
+ this.disconnecting = false;
1538
+ this.establishedConnections++;
1539
+ this.flushSendBuffer();
1540
+ this.reconnectTimer.reset();
1541
+ if (this.autoSendHeartbeat) {
1542
+ this.resetHeartbeat();
1543
+ }
1544
+ this.triggerStateCallbacks("open");
1545
+ }
1546
+ /**
1547
+ * @private
1548
+ */
1549
+ heartbeatTimeout() {
1550
+ if (this.pendingHeartbeatRef) {
1551
+ this.pendingHeartbeatRef = null;
1552
+ this.heartbeatSentAt = null;
1553
+ if (this.hasLogger()) {
1554
+ this.log("transport", "heartbeat timeout. Attempting to re-establish connection");
1555
+ }
1556
+ try {
1557
+ this.heartbeatCallback("timeout");
1558
+ } catch (e) {
1559
+ this.log("error", "error in heartbeat callback", e);
1560
+ }
1561
+ this.triggerChanError();
1562
+ this.closeWasClean = false;
1563
+ this.teardown(() => this.reconnectTimer.scheduleTimeout(), WS_CLOSE_NORMAL, "heartbeat timeout");
1564
+ }
1565
+ }
1566
+ resetHeartbeat() {
1567
+ if (this.conn && this.conn.skipHeartbeat) {
1568
+ return;
1569
+ }
1570
+ this.pendingHeartbeatRef = null;
1571
+ this.clearHeartbeats();
1572
+ this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
1573
+ }
1574
+ teardown(callback, code, reason) {
1575
+ if (!this.conn) {
1576
+ return callback && callback();
1577
+ }
1578
+ let connectClock = this.connectClock;
1579
+ this.waitForBufferDone(() => {
1580
+ if (connectClock !== this.connectClock) {
1581
+ return;
1582
+ }
1583
+ if (this.conn) {
1584
+ if (code) {
1585
+ this.conn.close(code, reason || "");
1586
+ } else {
1587
+ this.conn.close();
1588
+ }
1589
+ }
1590
+ this.waitForSocketClosed(() => {
1591
+ if (connectClock !== this.connectClock) {
1592
+ return;
1593
+ }
1594
+ if (this.conn) {
1595
+ this.conn.onopen = function() {
1596
+ };
1597
+ this.conn.onerror = function() {
1598
+ };
1599
+ this.conn.onmessage = function() {
1600
+ };
1601
+ this.conn.onclose = function() {
1602
+ };
1603
+ this.conn = null;
1604
+ }
1605
+ callback && callback();
1606
+ });
1607
+ });
1608
+ }
1609
+ waitForBufferDone(callback, tries = 1) {
1610
+ if (tries === 5 || !this.conn || !this.conn.bufferedAmount) {
1611
+ callback();
1612
+ return;
1613
+ }
1614
+ setTimeout(() => {
1615
+ this.waitForBufferDone(callback, tries + 1);
1616
+ }, 150 * tries);
1617
+ }
1618
+ waitForSocketClosed(callback, tries = 1) {
1619
+ if (tries === 5 || !this.conn || this.conn.readyState === SOCKET_STATES.closed) {
1620
+ callback();
1621
+ return;
1622
+ }
1623
+ setTimeout(() => {
1624
+ this.waitForSocketClosed(callback, tries + 1);
1625
+ }, 150 * tries);
1626
+ }
1627
+ /**
1628
+ * @param {CloseEvent} event
1629
+ */
1630
+ onConnClose(event) {
1631
+ if (this.conn) this.conn.onclose = () => {
1632
+ };
1633
+ if (this.hasLogger()) this.log("transport", "close", event);
1634
+ this.triggerChanError();
1635
+ this.clearHeartbeats();
1636
+ if (!this.closeWasClean) {
1637
+ this.reconnectTimer.scheduleTimeout();
1638
+ }
1639
+ this.triggerStateCallbacks("close", event);
1640
+ }
1641
+ /**
1642
+ * @private
1643
+ * @param {Event} error
1644
+ */
1645
+ onConnError(error) {
1646
+ if (this.hasLogger()) this.log("transport", error);
1647
+ let transportBefore = this.transport;
1648
+ let establishedBefore = this.establishedConnections;
1649
+ this.triggerStateCallbacks("error", error, transportBefore, establishedBefore);
1650
+ if (transportBefore === this.transport || establishedBefore > 0) {
1651
+ this.triggerChanError();
1652
+ }
1653
+ }
1654
+ /**
1655
+ * @private
1656
+ */
1657
+ triggerChanError() {
1658
+ this.channels.forEach((channel) => {
1659
+ if (!(channel.isErrored() || channel.isLeaving() || channel.isClosed())) {
1660
+ channel.trigger(CHANNEL_EVENTS.error);
1661
+ }
1662
+ });
1663
+ }
1664
+ /**
1665
+ * @returns {string}
1666
+ */
1667
+ connectionState() {
1668
+ switch (this.conn && this.conn.readyState) {
1669
+ case SOCKET_STATES.connecting:
1670
+ return "connecting";
1671
+ case SOCKET_STATES.open:
1672
+ return "open";
1673
+ case SOCKET_STATES.closing:
1674
+ return "closing";
1675
+ default:
1676
+ return "closed";
1677
+ }
1678
+ }
1679
+ /**
1680
+ * @returns {boolean}
1681
+ */
1682
+ isConnected() {
1683
+ return this.connectionState() === "open";
1684
+ }
1685
+ /**
1686
+ *
1687
+ * @param {Channel} channel
1688
+ */
1689
+ remove(channel) {
1690
+ this.off(channel.stateChangeRefs);
1691
+ this.channels = this.channels.filter((c) => c !== channel);
1692
+ }
1693
+ /**
1694
+ * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations.
1695
+ *
1696
+ * @param {string[]} refs - list of refs returned by calls to
1697
+ * `onOpen`, `onClose`, `onError,` and `onMessage`
1698
+ */
1699
+ off(refs) {
1700
+ for (let key in this.stateChangeCallbacks) {
1701
+ this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => {
1702
+ return refs.indexOf(ref) === -1;
1703
+ });
1704
+ }
1705
+ }
1706
+ /**
1707
+ * Initiates a new channel for the given topic
1708
+ *
1709
+ * @param {string} topic
1710
+ * @param {Params | (() => Params)} [chanParams]- Parameters for the channel
1711
+ * @returns {Channel}
1712
+ */
1713
+ channel(topic, chanParams = {}) {
1714
+ let chan = new Channel(topic, chanParams, this);
1715
+ this.channels.push(chan);
1716
+ return chan;
1717
+ }
1718
+ /**
1719
+ * @param {Message<Record<string, any>>} data
1720
+ */
1721
+ push(data) {
1722
+ if (this.hasLogger()) {
1723
+ let { topic, event, payload, ref, join_ref } = data;
1724
+ this.log("push", `${topic} ${event} (${join_ref}, ${ref})`, payload);
1725
+ }
1726
+ if (this.isConnected()) {
1727
+ this.encode(data, (result) => this.conn.send(result));
1728
+ } else {
1729
+ this.sendBuffer.push(() => this.encode(data, (result) => this.conn.send(result)));
1730
+ }
1731
+ }
1732
+ /**
1733
+ * Return the next message ref, accounting for overflows
1734
+ * @returns {string}
1735
+ */
1736
+ makeRef() {
1737
+ let newRef = this.ref + 1;
1738
+ if (newRef === this.ref) {
1739
+ this.ref = 0;
1740
+ } else {
1741
+ this.ref = newRef;
1742
+ }
1743
+ return this.ref.toString();
1744
+ }
1745
+ sendHeartbeat() {
1746
+ if (!this.isConnected()) {
1747
+ try {
1748
+ this.heartbeatCallback("disconnected");
1749
+ } catch (e) {
1750
+ this.log("error", "error in heartbeat callback", e);
1751
+ }
1752
+ return;
1753
+ }
1754
+ if (this.pendingHeartbeatRef) {
1755
+ this.heartbeatTimeout();
1756
+ return;
1757
+ }
1758
+ this.pendingHeartbeatRef = this.makeRef();
1759
+ this.heartbeatSentAt = Date.now();
1760
+ this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef });
1761
+ try {
1762
+ this.heartbeatCallback("sent");
1763
+ } catch (e) {
1764
+ this.log("error", "error in heartbeat callback", e);
1765
+ }
1766
+ this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs);
1767
+ }
1768
+ flushSendBuffer() {
1769
+ if (this.isConnected() && this.sendBuffer.length > 0) {
1770
+ this.sendBuffer.forEach((callback) => callback());
1771
+ this.sendBuffer = [];
1772
+ }
1773
+ }
1774
+ /**
1775
+ * @param {MessageEvent<any>} rawMessage
1776
+ */
1777
+ onConnMessage(rawMessage) {
1778
+ this.decode(rawMessage.data, (msg) => {
1779
+ let { topic, event, payload, ref, join_ref } = msg;
1780
+ if (ref && ref === this.pendingHeartbeatRef) {
1781
+ const latency = this.heartbeatSentAt ? Date.now() - this.heartbeatSentAt : void 0;
1782
+ this.clearHeartbeats();
1783
+ try {
1784
+ this.heartbeatCallback(payload.status === "ok" ? "ok" : "error", latency);
1785
+ } catch (e) {
1786
+ this.log("error", "error in heartbeat callback", e);
1787
+ }
1788
+ this.pendingHeartbeatRef = null;
1789
+ this.heartbeatSentAt = null;
1790
+ if (this.autoSendHeartbeat) {
1791
+ this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs);
1792
+ }
1793
+ }
1794
+ if (this.hasLogger()) this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`.trim(), payload);
1795
+ for (let i = 0; i < this.channels.length; i++) {
1796
+ const channel = this.channels[i];
1797
+ if (!channel.isMember(topic, event, payload, join_ref)) {
1798
+ continue;
1799
+ }
1800
+ channel.trigger(event, payload, ref, join_ref);
1801
+ }
1802
+ this.triggerStateCallbacks("message", msg);
1803
+ });
1804
+ }
1805
+ /**
1806
+ * @private
1807
+ * @template {keyof SocketStateChangeCallbacks} K
1808
+ * @param {K} event
1809
+ * @param {...Parameters<SocketStateChangeCallbacks[K][number][1]>} args
1810
+ * @returns {void}
1811
+ */
1812
+ triggerStateCallbacks(event, ...args) {
1813
+ try {
1814
+ this.stateChangeCallbacks[event].forEach(([_, callback]) => {
1815
+ try {
1816
+ callback(...args);
1817
+ } catch (e) {
1818
+ this.log("error", `error in ${event} callback`, e);
1819
+ }
1820
+ });
1821
+ } catch (e) {
1822
+ this.log("error", `error triggering ${event} callbacks`, e);
1823
+ }
1824
+ }
1825
+ leaveOpenTopic(topic) {
1826
+ let dupChannel = this.channels.find((c) => c.topic === topic && (c.isJoined() || c.isJoining()));
1827
+ if (dupChannel) {
1828
+ if (this.hasLogger()) this.log("transport", `leaving duplicate topic "${topic}"`);
1829
+ dupChannel.leave();
1830
+ }
1831
+ }
1832
+ };
1833
+ return __toCommonJS(phoenix_exports);
1834
+ })();