-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
phoenix.cjs.js
1564 lines (1553 loc) · 45.4 KB
/
phoenix.cjs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// js/phoenix/index.js
var phoenix_exports = {};
__export(phoenix_exports, {
Channel: () => Channel,
LongPoll: () => LongPoll,
Presence: () => Presence,
Serializer: () => serializer_default,
Socket: () => Socket
});
module.exports = __toCommonJS(phoenix_exports);
// js/phoenix/utils.js
var closure = (value) => {
if (typeof value === "function") {
return value;
} else {
let closure2 = function() {
return value;
};
return closure2;
}
};
// js/phoenix/constants.js
var globalSelf = typeof self !== "undefined" ? self : null;
var phxWindow = typeof window !== "undefined" ? window : null;
var global = globalSelf || phxWindow || global;
var DEFAULT_VSN = "2.0.0";
var SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 };
var DEFAULT_TIMEOUT = 1e4;
var WS_CLOSE_NORMAL = 1e3;
var CHANNEL_STATES = {
closed: "closed",
errored: "errored",
joined: "joined",
joining: "joining",
leaving: "leaving"
};
var CHANNEL_EVENTS = {
close: "phx_close",
error: "phx_error",
join: "phx_join",
reply: "phx_reply",
leave: "phx_leave"
};
var TRANSPORTS = {
longpoll: "longpoll",
websocket: "websocket"
};
var XHR_STATES = {
complete: 4
};
// js/phoenix/push.js
var Push = class {
constructor(channel, event, payload, timeout) {
this.channel = channel;
this.event = event;
this.payload = payload || function() {
return {};
};
this.receivedResp = null;
this.timeout = timeout;
this.timeoutTimer = null;
this.recHooks = [];
this.sent = false;
}
/**
*
* @param {number} timeout
*/
resend(timeout) {
this.timeout = timeout;
this.reset();
this.send();
}
/**
*
*/
send() {
if (this.hasReceived("timeout")) {
return;
}
this.startTimeout();
this.sent = true;
this.channel.socket.push({
topic: this.channel.topic,
event: this.event,
payload: this.payload(),
ref: this.ref,
join_ref: this.channel.joinRef()
});
}
/**
*
* @param {*} status
* @param {*} callback
*/
receive(status, callback) {
if (this.hasReceived(status)) {
callback(this.receivedResp.response);
}
this.recHooks.push({ status, callback });
return this;
}
/**
* @private
*/
reset() {
this.cancelRefEvent();
this.ref = null;
this.refEvent = null;
this.receivedResp = null;
this.sent = false;
}
/**
* @private
*/
matchReceive({ status, response, _ref }) {
this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response));
}
/**
* @private
*/
cancelRefEvent() {
if (!this.refEvent) {
return;
}
this.channel.off(this.refEvent);
}
/**
* @private
*/
cancelTimeout() {
clearTimeout(this.timeoutTimer);
this.timeoutTimer = null;
}
/**
* @private
*/
startTimeout() {
if (this.timeoutTimer) {
this.cancelTimeout();
}
this.ref = this.channel.socket.makeRef();
this.refEvent = this.channel.replyEventName(this.ref);
this.channel.on(this.refEvent, (payload) => {
this.cancelRefEvent();
this.cancelTimeout();
this.receivedResp = payload;
this.matchReceive(payload);
});
this.timeoutTimer = setTimeout(() => {
this.trigger("timeout", {});
}, this.timeout);
}
/**
* @private
*/
hasReceived(status) {
return this.receivedResp && this.receivedResp.status === status;
}
/**
* @private
*/
trigger(status, response) {
this.channel.trigger(this.refEvent, { status, response });
}
};
// js/phoenix/timer.js
var Timer = class {
constructor(callback, timerCalc) {
this.callback = callback;
this.timerCalc = timerCalc;
this.timer = null;
this.tries = 0;
}
reset() {
this.tries = 0;
clearTimeout(this.timer);
}
/**
* Cancels any previous scheduleTimeout and schedules callback
*/
scheduleTimeout() {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.tries = this.tries + 1;
this.callback();
}, this.timerCalc(this.tries + 1));
}
};
// js/phoenix/channel.js
var Channel = class {
constructor(topic, params, socket) {
this.state = CHANNEL_STATES.closed;
this.topic = topic;
this.params = closure(params || {});
this.socket = socket;
this.bindings = [];
this.bindingRef = 0;
this.timeout = this.socket.timeout;
this.joinedOnce = false;
this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
this.pushBuffer = [];
this.stateChangeRefs = [];
this.rejoinTimer = new Timer(() => {
if (this.socket.isConnected()) {
this.rejoin();
}
}, this.socket.rejoinAfterMs);
this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset()));
this.stateChangeRefs.push(
this.socket.onOpen(() => {
this.rejoinTimer.reset();
if (this.isErrored()) {
this.rejoin();
}
})
);
this.joinPush.receive("ok", () => {
this.state = CHANNEL_STATES.joined;
this.rejoinTimer.reset();
this.pushBuffer.forEach((pushEvent) => pushEvent.send());
this.pushBuffer = [];
});
this.joinPush.receive("error", () => {
this.state = CHANNEL_STATES.errored;
if (this.socket.isConnected()) {
this.rejoinTimer.scheduleTimeout();
}
});
this.onClose(() => {
this.rejoinTimer.reset();
if (this.socket.hasLogger())
this.socket.log("channel", `close ${this.topic} ${this.joinRef()}`);
this.state = CHANNEL_STATES.closed;
this.socket.remove(this);
});
this.onError((reason) => {
if (this.socket.hasLogger())
this.socket.log("channel", `error ${this.topic}`, reason);
if (this.isJoining()) {
this.joinPush.reset();
}
this.state = CHANNEL_STATES.errored;
if (this.socket.isConnected()) {
this.rejoinTimer.scheduleTimeout();
}
});
this.joinPush.receive("timeout", () => {
if (this.socket.hasLogger())
this.socket.log("channel", `timeout ${this.topic} (${this.joinRef()})`, this.joinPush.timeout);
let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout);
leavePush.send();
this.state = CHANNEL_STATES.errored;
this.joinPush.reset();
if (this.socket.isConnected()) {
this.rejoinTimer.scheduleTimeout();
}
});
this.on(CHANNEL_EVENTS.reply, (payload, ref) => {
this.trigger(this.replyEventName(ref), payload);
});
}
/**
* Join the channel
* @param {integer} timeout
* @returns {Push}
*/
join(timeout = this.timeout) {
if (this.joinedOnce) {
throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");
} else {
this.timeout = timeout;
this.joinedOnce = true;
this.rejoin();
return this.joinPush;
}
}
/**
* Hook into channel close
* @param {Function} callback
*/
onClose(callback) {
this.on(CHANNEL_EVENTS.close, callback);
}
/**
* Hook into channel errors
* @param {Function} callback
*/
onError(callback) {
return this.on(CHANNEL_EVENTS.error, (reason) => callback(reason));
}
/**
* Subscribes on channel events
*
* Subscription returns a ref counter, which can be used later to
* unsubscribe the exact event listener
*
* @example
* const ref1 = channel.on("event", do_stuff)
* const ref2 = channel.on("event", do_other_stuff)
* channel.off("event", ref1)
* // Since unsubscription, do_stuff won't fire,
* // while do_other_stuff will keep firing on the "event"
*
* @param {string} event
* @param {Function} callback
* @returns {integer} ref
*/
on(event, callback) {
let ref = this.bindingRef++;
this.bindings.push({ event, ref, callback });
return ref;
}
/**
* Unsubscribes off of channel events
*
* Use the ref returned from a channel.on() to unsubscribe one
* handler, or pass nothing for the ref to unsubscribe all
* handlers for the given event.
*
* @example
* // Unsubscribe the do_stuff handler
* const ref1 = channel.on("event", do_stuff)
* channel.off("event", ref1)
*
* // Unsubscribe all handlers from event
* channel.off("event")
*
* @param {string} event
* @param {integer} ref
*/
off(event, ref) {
this.bindings = this.bindings.filter((bind) => {
return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref));
});
}
/**
* @private
*/
canPush() {
return this.socket.isConnected() && this.isJoined();
}
/**
* Sends a message `event` to phoenix with the payload `payload`.
* Phoenix receives this in the `handle_in(event, payload, socket)`
* function. if phoenix replies or it times out (default 10000ms),
* then optionally the reply can be received.
*
* @example
* channel.push("event")
* .receive("ok", payload => console.log("phoenix replied:", payload))
* .receive("error", err => console.log("phoenix errored", err))
* .receive("timeout", () => console.log("timed out pushing"))
* @param {string} event
* @param {Object} payload
* @param {number} [timeout]
* @returns {Push}
*/
push(event, payload, timeout = this.timeout) {
payload = payload || {};
if (!this.joinedOnce) {
throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`);
}
let pushEvent = new Push(this, event, function() {
return payload;
}, timeout);
if (this.canPush()) {
pushEvent.send();
} else {
pushEvent.startTimeout();
this.pushBuffer.push(pushEvent);
}
return pushEvent;
}
/** Leaves the channel
*
* Unsubscribes from server events, and
* instructs channel to terminate on server
*
* Triggers onClose() hooks
*
* To receive leave acknowledgements, use the `receive`
* hook to bind to the server ack, ie:
*
* @example
* channel.leave().receive("ok", () => alert("left!") )
*
* @param {integer} timeout
* @returns {Push}
*/
leave(timeout = this.timeout) {
this.rejoinTimer.reset();
this.joinPush.cancelTimeout();
this.state = CHANNEL_STATES.leaving;
let onClose = () => {
if (this.socket.hasLogger())
this.socket.log("channel", `leave ${this.topic}`);
this.trigger(CHANNEL_EVENTS.close, "leave");
};
let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout);
leavePush.receive("ok", () => onClose()).receive("timeout", () => onClose());
leavePush.send();
if (!this.canPush()) {
leavePush.trigger("ok", {});
}
return leavePush;
}
/**
* Overridable message hook
*
* Receives all events for specialized message handling
* before dispatching to the channel callbacks.
*
* Must return the payload, modified or unmodified
* @param {string} event
* @param {Object} payload
* @param {integer} ref
* @returns {Object}
*/
onMessage(_event, payload, _ref) {
return payload;
}
/**
* @private
*/
isMember(topic, event, payload, joinRef) {
if (this.topic !== topic) {
return false;
}
if (joinRef && joinRef !== this.joinRef()) {
if (this.socket.hasLogger())
this.socket.log("channel", "dropping outdated message", { topic, event, payload, joinRef });
return false;
} else {
return true;
}
}
/**
* @private
*/
joinRef() {
return this.joinPush.ref;
}
/**
* @private
*/
rejoin(timeout = this.timeout) {
if (this.isLeaving()) {
return;
}
this.socket.leaveOpenTopic(this.topic);
this.state = CHANNEL_STATES.joining;
this.joinPush.resend(timeout);
}
/**
* @private
*/
trigger(event, payload, ref, joinRef) {
let handledPayload = this.onMessage(event, payload, ref, joinRef);
if (payload && !handledPayload) {
throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");
}
let eventBindings = this.bindings.filter((bind) => bind.event === event);
for (let i = 0; i < eventBindings.length; i++) {
let bind = eventBindings[i];
bind.callback(handledPayload, ref, joinRef || this.joinRef());
}
}
/**
* @private
*/
replyEventName(ref) {
return `chan_reply_${ref}`;
}
/**
* @private
*/
isClosed() {
return this.state === CHANNEL_STATES.closed;
}
/**
* @private
*/
isErrored() {
return this.state === CHANNEL_STATES.errored;
}
/**
* @private
*/
isJoined() {
return this.state === CHANNEL_STATES.joined;
}
/**
* @private
*/
isJoining() {
return this.state === CHANNEL_STATES.joining;
}
/**
* @private
*/
isLeaving() {
return this.state === CHANNEL_STATES.leaving;
}
};
// js/phoenix/ajax.js
var Ajax = class {
static request(method, endPoint, accept, body, timeout, ontimeout, callback) {
if (global.XDomainRequest) {
let req = new global.XDomainRequest();
return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);
} else {
let req = new global.XMLHttpRequest();
return this.xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback);
}
}
static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {
req.timeout = timeout;
req.open(method, endPoint);
req.onload = () => {
let response = this.parseJSON(req.responseText);
callback && callback(response);
};
if (ontimeout) {
req.ontimeout = ontimeout;
}
req.onprogress = () => {
};
req.send(body);
return req;
}
static xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback) {
req.open(method, endPoint, true);
req.timeout = timeout;
req.setRequestHeader("Content-Type", accept);
req.onerror = () => callback && callback(null);
req.onreadystatechange = () => {
if (req.readyState === XHR_STATES.complete && callback) {
let response = this.parseJSON(req.responseText);
callback(response);
}
};
if (ontimeout) {
req.ontimeout = ontimeout;
}
req.send(body);
return req;
}
static parseJSON(resp) {
if (!resp || resp === "") {
return null;
}
try {
return JSON.parse(resp);
} catch (e) {
console && console.log("failed to parse JSON response", resp);
return null;
}
}
static serialize(obj, parentKey) {
let queryStr = [];
for (var key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
continue;
}
let paramKey = parentKey ? `${parentKey}[${key}]` : key;
let paramVal = obj[key];
if (typeof paramVal === "object") {
queryStr.push(this.serialize(paramVal, paramKey));
} else {
queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal));
}
}
return queryStr.join("&");
}
static appendParams(url, params) {
if (Object.keys(params).length === 0) {
return url;
}
let prefix = url.match(/\?/) ? "&" : "?";
return `${url}${prefix}${this.serialize(params)}`;
}
};
// js/phoenix/longpoll.js
var arrayBufferToBase64 = (buffer) => {
let binary = "";
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
};
var LongPoll = class {
constructor(endPoint) {
this.endPoint = null;
this.token = null;
this.skipHeartbeat = true;
this.reqs = /* @__PURE__ */ new Set();
this.awaitingBatchAck = false;
this.currentBatch = null;
this.currentBatchTimer = null;
this.batchBuffer = [];
this.onopen = function() {
};
this.onerror = function() {
};
this.onmessage = function() {
};
this.onclose = function() {
};
this.pollEndpoint = this.normalizeEndpoint(endPoint);
this.readyState = SOCKET_STATES.connecting;
setTimeout(() => this.poll(), 0);
}
normalizeEndpoint(endPoint) {
return endPoint.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll);
}
endpointURL() {
return Ajax.appendParams(this.pollEndpoint, { token: this.token });
}
closeAndRetry(code, reason, wasClean) {
this.close(code, reason, wasClean);
this.readyState = SOCKET_STATES.connecting;
}
ontimeout() {
this.onerror("timeout");
this.closeAndRetry(1005, "timeout", false);
}
isActive() {
return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting;
}
poll() {
this.ajax("GET", "application/json", null, () => this.ontimeout(), (resp) => {
if (resp) {
var { status, token, messages } = resp;
this.token = token;
} else {
status = 0;
}
switch (status) {
case 200:
messages.forEach((msg) => {
setTimeout(() => this.onmessage({ data: msg }), 0);
});
this.poll();
break;
case 204:
this.poll();
break;
case 410:
this.readyState = SOCKET_STATES.open;
this.onopen({});
this.poll();
break;
case 403:
this.onerror(403);
this.close(1008, "forbidden", false);
break;
case 0:
case 500:
this.onerror(500);
this.closeAndRetry(1011, "internal server error", 500);
break;
default:
throw new Error(`unhandled poll status ${status}`);
}
});
}
// we collect all pushes within the current event loop by
// setTimeout 0, which optimizes back-to-back procedural
// pushes against an empty buffer
send(body) {
if (typeof body !== "string") {
body = arrayBufferToBase64(body);
}
if (this.currentBatch) {
this.currentBatch.push(body);
} else if (this.awaitingBatchAck) {
this.batchBuffer.push(body);
} else {
this.currentBatch = [body];
this.currentBatchTimer = setTimeout(() => {
this.batchSend(this.currentBatch);
this.currentBatch = null;
}, 0);
}
}
batchSend(messages) {
this.awaitingBatchAck = true;
this.ajax("POST", "application/x-ndjson", messages.join("\n"), () => this.onerror("timeout"), (resp) => {
this.awaitingBatchAck = false;
if (!resp || resp.status !== 200) {
this.onerror(resp && resp.status);
this.closeAndRetry(1011, "internal server error", false);
} else if (this.batchBuffer.length > 0) {
this.batchSend(this.batchBuffer);
this.batchBuffer = [];
}
});
}
close(code, reason, wasClean) {
for (let req of this.reqs) {
req.abort();
}
this.readyState = SOCKET_STATES.closed;
let opts = Object.assign({ code: 1e3, reason: void 0, wasClean: true }, { code, reason, wasClean });
this.batchBuffer = [];
clearTimeout(this.currentBatchTimer);
this.currentBatchTimer = null;
if (typeof CloseEvent !== "undefined") {
this.onclose(new CloseEvent("close", opts));
} else {
this.onclose(opts);
}
}
ajax(method, contentType, body, onCallerTimeout, callback) {
let req;
let ontimeout = () => {
this.reqs.delete(req);
onCallerTimeout();
};
req = Ajax.request(method, this.endpointURL(), contentType, body, this.timeout, ontimeout, (resp) => {
this.reqs.delete(req);
if (this.isActive()) {
callback(resp);
}
});
this.reqs.add(req);
}
};
// js/phoenix/presence.js
var Presence = class {
constructor(channel, opts = {}) {
let events = opts.events || { state: "presence_state", diff: "presence_diff" };
this.state = {};
this.pendingDiffs = [];
this.channel = channel;
this.joinRef = null;
this.caller = {
onJoin: function() {
},
onLeave: function() {
},
onSync: function() {
}
};
this.channel.on(events.state, (newState) => {
let { onJoin, onLeave, onSync } = this.caller;
this.joinRef = this.channel.joinRef();
this.state = Presence.syncState(this.state, newState, onJoin, onLeave);
this.pendingDiffs.forEach((diff) => {
this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave);
});
this.pendingDiffs = [];
onSync();
});
this.channel.on(events.diff, (diff) => {
let { onJoin, onLeave, onSync } = this.caller;
if (this.inPendingSyncState()) {
this.pendingDiffs.push(diff);
} else {
this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave);
onSync();
}
});
}
onJoin(callback) {
this.caller.onJoin = callback;
}
onLeave(callback) {
this.caller.onLeave = callback;
}
onSync(callback) {
this.caller.onSync = callback;
}
list(by) {
return Presence.list(this.state, by);
}
inPendingSyncState() {
return !this.joinRef || this.joinRef !== this.channel.joinRef();
}
// lower-level public static API
/**
* Used to sync the list of presences on the server
* with the client's state. An optional `onJoin` and `onLeave` callback can
* be provided to react to changes in the client's local presences across
* disconnects and reconnects with the server.
*
* @returns {Presence}
*/
static syncState(currentState, newState, onJoin, onLeave) {
let state = this.clone(currentState);
let joins = {};
let leaves = {};
this.map(state, (key, presence) => {
if (!newState[key]) {
leaves[key] = presence;
}
});
this.map(newState, (key, newPresence) => {
let currentPresence = state[key];
if (currentPresence) {
let newRefs = newPresence.metas.map((m) => m.phx_ref);
let curRefs = currentPresence.metas.map((m) => m.phx_ref);
let joinedMetas = newPresence.metas.filter((m) => curRefs.indexOf(m.phx_ref) < 0);
let leftMetas = currentPresence.metas.filter((m) => newRefs.indexOf(m.phx_ref) < 0);
if (joinedMetas.length > 0) {
joins[key] = newPresence;
joins[key].metas = joinedMetas;
}
if (leftMetas.length > 0) {
leaves[key] = this.clone(currentPresence);
leaves[key].metas = leftMetas;
}
} else {
joins[key] = newPresence;
}
});
return this.syncDiff(state, { joins, leaves }, onJoin, onLeave);
}
/**
*
* Used to sync a diff of presence join and leave
* events from the server, as they happen. Like `syncState`, `syncDiff`
* accepts optional `onJoin` and `onLeave` callbacks to react to a user
* joining or leaving from a device.
*
* @returns {Presence}
*/
static syncDiff(state, diff, onJoin, onLeave) {
let { joins, leaves } = this.clone(diff);
if (!onJoin) {
onJoin = function() {
};
}
if (!onLeave) {
onLeave = function() {
};
}
this.map(joins, (key, newPresence) => {
let currentPresence = state[key];
state[key] = this.clone(newPresence);
if (currentPresence) {
let joinedRefs = state[key].metas.map((m) => m.phx_ref);
let curMetas = currentPresence.metas.filter((m) => joinedRefs.indexOf(m.phx_ref) < 0);
state[key].metas.unshift(...curMetas);
}
onJoin(key, currentPresence, newPresence);
});
this.map(leaves, (key, leftPresence) => {
let currentPresence = state[key];
if (!currentPresence) {
return;
}
let refsToRemove = leftPresence.metas.map((m) => m.phx_ref);
currentPresence.metas = currentPresence.metas.filter((p) => {
return refsToRemove.indexOf(p.phx_ref) < 0;
});
onLeave(key, currentPresence, leftPresence);
if (currentPresence.metas.length === 0) {
delete state[key];
}
});
return state;
}
/**
* Returns the array of presences, with selected metadata.
*
* @param {Object} presences
* @param {Function} chooser
*
* @returns {Presence}
*/
static list(presences, chooser) {
if (!chooser) {
chooser = function(key, pres) {
return pres;
};
}
return this.map(presences, (key, presence) => {
return chooser(key, presence);
});
}
// private
static map(obj, func) {
return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key]));
}
static clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
};
// js/phoenix/serializer.js
var serializer_default = {
HEADER_LENGTH: 1,
META_LENGTH: 4,
KINDS: { push: 0, reply: 1, broadcast: 2 },
encode(msg, callback) {
if (msg.payload.constructor === ArrayBuffer) {
return callback(this.binaryEncode(msg));
} else {
let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];
return callback(JSON.stringify(payload));
}
},
decode(rawPayload, callback) {
if (rawPayload.constructor === ArrayBuffer) {
return callback(this.binaryDecode(rawPayload));
} else {
let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload);
return callback({ join_ref, ref, topic, event, payload });
}
},
// private
binaryEncode(message) {
let { join_ref, ref, event, topic, payload } = message;
let metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length;
let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
let view = new DataView(header);
let offset = 0;
view.setUint8(offset++, this.KINDS.push);
view.setUint8(offset++, join_ref.length);
view.setUint8(offset++, ref.length);
view.setUint8(offset++, topic.length);
view.setUint8(offset++, event.length);
Array.from(join_ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
Array.from(event, (char) => view.setUint8(offset++, char.charCodeAt(0)));
var combined = new Uint8Array(header.byteLength + payload.byteLength);
combined.set(new Uint8Array(header), 0);
combined.set(new Uint8Array(payload), header.byteLength);
return combined.buffer;
},
binaryDecode(buffer) {
let view = new DataView(buffer);
let kind = view.getUint8(0);
let decoder = new TextDecoder();
switch (kind) {
case this.KINDS.push:
return this.decodePush(buffer, view, decoder);
case this.KINDS.reply:
return this.decodeReply(buffer, view, decoder);
case this.KINDS.broadcast:
return this.decodeBroadcast(buffer, view, decoder);
}
},
decodePush(buffer, view, decoder) {
let joinRefSize = view.getUint8(1);
let topicSize = view.getUint8(2);
let eventSize = view.getUint8(3);
let offset = this.HEADER_LENGTH + this.META_LENGTH - 1;
let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
offset = offset + joinRefSize;
let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
offset = offset + topicSize;
let event = decoder.decode(buffer.slice(offset, offset + eventSize));
offset = offset + eventSize;
let data = buffer.slice(offset, buffer.byteLength);
return { join_ref: joinRef, ref: null, topic, event, payload: data };
},
decodeReply(buffer, view, decoder) {
let joinRefSize = view.getUint8(1);
let refSize = view.getUint8(2);
let topicSize = view.getUint8(3);
let eventSize = view.getUint8(4);
let offset = this.HEADER_LENGTH + this.META_LENGTH;
let joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
offset = offset + joinRefSize;
let ref = decoder.decode(buffer.slice(offset, offset + refSize));
offset = offset + refSize;
let topic = decoder.decode(buffer.slice(offset, offset + topicSize));
offset = offset + topicSize;