forked from phoenixframework/phoenix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phoenix.js
1026 lines (933 loc) · 30 KB
/
phoenix.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
(function(exports){
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Phoenix Channels JavaScript client
//
// ## Socket Connection
//
// A single connection is established to the server and
// channels are mulitplexed over the connection.
// Connect to the server using the `Socket` class:
//
// let socket = new Socket("/ws", {params: {userToken: "123"}})
// socket.connect()
//
// The `Socket` constructor takes the mount point of the socket,
// the authentication params, as well as options that can be found in
// the Socket docs, such as configuring the `LongPoll` transport, and
// heartbeat.
//
// ## Channels
//
// Channels are isolated, concurrent processes on the server that
// subscribe to topics and broker events between the client and server.
// To join a channel, you must provide the topic, and channel params for
// authorization. Here's an example chat room example where `"new_msg"`
// events are listened for, messages are pushed to the server, and
// the channel is joined with ok/error/timeout matches:
//
// let channel = socket.channel("rooms:123", {token: roomToken})
// channel.on("new_msg", msg => console.log("Got message", msg) )
// $input.onEnter( e => {
// channel.push("new_msg", {body: e.target.val}, 10000)
// .receive("ok", (msg) => console.log("created message", msg) )
// .receive("error", (reasons) => console.log("create failed", reasons) )
// .receive("timeout", () => console.log("Networking issue...") )
// })
// channel.join()
// .receive("ok", ({messages}) => console.log("catching up", messages) )
// .receive("error", ({reason}) => console.log("failed join", reason) )
// .receive("timeout", () => console.log("Networking issue. Still waiting...") )
//
//
// ## Joining
//
// Creating a channel with `socket.channel(topic, params)`, binds the params to
// `channel.params`, which are sent up on `channel.join()`.
// Subsequent rejoins will send up the modified params for
// updating authorization params, or passing up last_message_id information.
// Successful joins receive an "ok" status, while unsuccessful joins
// receive "error".
//
//
// ## Pushing Messages
//
// From the previous example, we can see that pushing messages to the server
// can be done with `channel.push(eventName, payload)` and we can optionally
// receive responses from the push. Additionally, we can use
// `receive("timeout", callback)` to abort waiting for our other `receive` hooks
// and take action after some period of waiting. The default timeout is 5000ms.
//
//
// ## Socket Hooks
//
// Lifecycle events of the multiplexed connection can be hooked into via
// `socket.onError()` and `socket.onClose()` events, ie:
//
// socket.onError( () => console.log("there was an error with the connection!") )
// socket.onClose( () => console.log("the connection dropped") )
//
//
// ## Channel Hooks
//
// For each joined channel, you can bind to `onError` and `onClose` events
// to monitor the channel lifecycle, ie:
//
// channel.onError( () => console.log("there was an error!") )
// channel.onClose( () => console.log("the channel has gone away gracefully") )
//
// ### onError hooks
//
// `onError` hooks are invoked if the socket connection drops, or the channel
// crashes on the server. In either case, a channel rejoin is attemtped
// automatically in an exponential backoff manner.
//
// ### onClose hooks
//
// `onClose` hooks are invoked only in two cases. 1) the channel explicitly
// closed on the server, or 2). The client explicitly closed, by calling
// `channel.leave()`
//
var VSN = "1.0.0";
var SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 };
var DEFAULT_TIMEOUT = 10000;
var CHANNEL_STATES = {
closed: "closed",
errored: "errored",
joined: "joined",
joining: "joining"
};
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 Push = function () {
// Initializes the Push
//
// channel - The Channel
// event - The event, for example `"phx_join"`
// payload - The payload, for example `{user_id: 123}`
// timeout - The push timeout in milliseconds
//
function Push(channel, event, payload, timeout) {
_classCallCheck(this, Push);
this.channel = channel;
this.event = event;
this.payload = payload || {};
this.receivedResp = null;
this.timeout = timeout;
this.timeoutTimer = null;
this.recHooks = [];
this.sent = false;
}
_createClass(Push, [{
key: "resend",
value: function resend(timeout) {
this.timeout = timeout;
this.cancelRefEvent();
this.ref = null;
this.refEvent = null;
this.receivedResp = null;
this.sent = false;
this.send();
}
}, {
key: "send",
value: function 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
});
}
}, {
key: "receive",
value: function receive(status, callback) {
if (this.hasReceived(status)) {
callback(this.receivedResp.response);
}
this.recHooks.push({ status: status, callback: callback });
return this;
}
// private
}, {
key: "matchReceive",
value: function matchReceive(_ref) {
var status = _ref.status;
var response = _ref.response;
var ref = _ref.ref;
this.recHooks.filter(function (h) {
return h.status === status;
}).forEach(function (h) {
return h.callback(response);
});
}
}, {
key: "cancelRefEvent",
value: function cancelRefEvent() {
if (!this.refEvent) {
return;
}
this.channel.off(this.refEvent);
}
}, {
key: "cancelTimeout",
value: function cancelTimeout() {
clearTimeout(this.timeoutTimer);
this.timeoutTimer = null;
}
}, {
key: "startTimeout",
value: function startTimeout() {
var _this = this;
if (this.timeoutTimer) {
return;
}
this.ref = this.channel.socket.makeRef();
this.refEvent = this.channel.replyEventName(this.ref);
this.channel.on(this.refEvent, function (payload) {
_this.cancelRefEvent();
_this.cancelTimeout();
_this.receivedResp = payload;
_this.matchReceive(payload);
});
this.timeoutTimer = setTimeout(function () {
_this.trigger("timeout", {});
}, this.timeout);
}
}, {
key: "hasReceived",
value: function hasReceived(status) {
return this.receivedResp && this.receivedResp.status === status;
}
}, {
key: "trigger",
value: function trigger(status, response) {
this.channel.trigger(this.refEvent, { status: status, response: response });
}
}]);
return Push;
}();
var Channel = exports.Channel = function () {
function Channel(topic, params, socket) {
var _this2 = this;
_classCallCheck(this, Channel);
this.state = CHANNEL_STATES.closed;
this.topic = topic;
this.params = params || {};
this.socket = socket;
this.bindings = [];
this.timeout = this.socket.timeout;
this.joinedOnce = false;
this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
this.pushBuffer = [];
this.rejoinTimer = new Timer(function () {
return _this2.rejoinUntilConnected();
}, this.socket.reconnectAfterMs);
this.joinPush.receive("ok", function () {
_this2.state = CHANNEL_STATES.joined;
_this2.rejoinTimer.reset();
_this2.pushBuffer.forEach(function (pushEvent) {
return pushEvent.send();
});
_this2.pushBuffer = [];
});
this.onClose(function () {
_this2.socket.log("channel", "close " + _this2.topic);
_this2.state = CHANNEL_STATES.closed;
_this2.socket.remove(_this2);
});
this.onError(function (reason) {
_this2.socket.log("channel", "error " + _this2.topic, reason);
_this2.state = CHANNEL_STATES.errored;
_this2.rejoinTimer.scheduleTimeout();
});
this.joinPush.receive("timeout", function () {
if (_this2.state !== CHANNEL_STATES.joining) {
return;
}
_this2.socket.log("channel", "timeout " + _this2.topic, _this2.joinPush.timeout);
_this2.state = CHANNEL_STATES.errored;
_this2.rejoinTimer.scheduleTimeout();
});
this.on(CHANNEL_EVENTS.reply, function (payload, ref) {
_this2.trigger(_this2.replyEventName(ref), payload);
});
}
_createClass(Channel, [{
key: "rejoinUntilConnected",
value: function rejoinUntilConnected() {
this.rejoinTimer.scheduleTimeout();
if (this.socket.isConnected()) {
this.rejoin();
}
}
}, {
key: "join",
value: function join() {
var timeout = arguments.length <= 0 || arguments[0] === undefined ? this.timeout : arguments[0];
if (this.joinedOnce) {
throw "tried to join multiple times. 'join' can only be called a single time per channel instance";
} else {
this.joinedOnce = true;
}
this.rejoin(timeout);
return this.joinPush;
}
}, {
key: "onClose",
value: function onClose(callback) {
this.on(CHANNEL_EVENTS.close, callback);
}
}, {
key: "onError",
value: function onError(callback) {
this.on(CHANNEL_EVENTS.error, function (reason) {
return callback(reason);
});
}
}, {
key: "on",
value: function on(event, callback) {
this.bindings.push({ event: event, callback: callback });
}
}, {
key: "off",
value: function off(event) {
this.bindings = this.bindings.filter(function (bind) {
return bind.event !== event;
});
}
}, {
key: "canPush",
value: function canPush() {
return this.socket.isConnected() && this.state === CHANNEL_STATES.joined;
}
}, {
key: "push",
value: function push(event, payload) {
var timeout = arguments.length <= 2 || arguments[2] === undefined ? this.timeout : arguments[2];
if (!this.joinedOnce) {
throw "tried to push '" + event + "' to '" + this.topic + "' before joining. Use channel.join() before pushing events";
}
var pushEvent = new Push(this, event, 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 a `receive`
// hook to bind to the server ack, ie:
//
// channel.leave().receive("ok", () => alert("left!") )
//
}, {
key: "leave",
value: function leave() {
var _this3 = this;
var timeout = arguments.length <= 0 || arguments[0] === undefined ? this.timeout : arguments[0];
var onClose = function onClose() {
_this3.socket.log("channel", "leave " + _this3.topic);
_this3.trigger(CHANNEL_EVENTS.close, "leave");
};
var leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout);
leavePush.receive("ok", function () {
return onClose();
}).receive("timeout", function () {
return onClose();
});
leavePush.send();
if (!this.canPush()) {
leavePush.trigger("ok", {});
}
return leavePush;
}
// Overridable message hook
//
// Receives all events for specialized message handling
}, {
key: "onMessage",
value: function onMessage(event, payload, ref) {}
// private
}, {
key: "isMember",
value: function isMember(topic) {
return this.topic === topic;
}
}, {
key: "sendJoin",
value: function sendJoin(timeout) {
this.state = CHANNEL_STATES.joining;
this.joinPush.resend(timeout);
}
}, {
key: "rejoin",
value: function rejoin() {
var timeout = arguments.length <= 0 || arguments[0] === undefined ? this.timeout : arguments[0];
this.sendJoin(timeout);
}
}, {
key: "trigger",
value: function trigger(triggerEvent, payload, ref) {
this.onMessage(triggerEvent, payload, ref);
this.bindings.filter(function (bind) {
return bind.event === triggerEvent;
}).map(function (bind) {
return bind.callback(payload, ref);
});
}
}, {
key: "replyEventName",
value: function replyEventName(ref) {
return "chan_reply_" + ref;
}
}]);
return Channel;
}();
var Socket = exports.Socket = function () {
// Initializes the Socket
//
// endPoint - The string WebSocket endpoint, ie, "ws://example.com/ws",
// "wss://example.com"
// "/ws" (inherited host & protocol)
// opts - Optional configuration
// transport - The Websocket Transport, for example WebSocket or Phoenix.LongPoll.
// Defaults to WebSocket with automatic LongPoll fallback.
// timeout - The default timeout in milliseconds to trigger push timeouts.
// Defaults `DEFAULT_TIMEOUT`
// heartbeatIntervalMs - The millisec interval to send a heartbeat message
// reconnectAfterMs - The optional function that returns the millsec
// reconnect interval. Defaults to stepped backoff of:
//
// function(tries){
// return [1000, 5000, 10000][tries - 1] || 10000
// }
//
// logger - The optional function for specialized logging, ie:
// `logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }
//
// longpollerTimeout - The maximum timeout of a long poll AJAX request.
// Defaults to 20s (double the server long poll timer).
//
// params - The optional params to pass when connecting
//
// For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)
//
function Socket(endPoint) {
var _this4 = this;
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, Socket);
this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] };
this.channels = [];
this.sendBuffer = [];
this.ref = 0;
this.timeout = opts.timeout || DEFAULT_TIMEOUT;
this.transport = opts.transport || window.WebSocket || LongPoll;
this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 30000;
this.reconnectAfterMs = opts.reconnectAfterMs || function (tries) {
return [1000, 2000, 5000, 10000][tries - 1] || 10000;
};
this.logger = opts.logger || function () {}; // noop
this.longpollerTimeout = opts.longpollerTimeout || 20000;
this.params = opts.params || {};
this.endPoint = endPoint + "/" + TRANSPORTS.websocket;
this.reconnectTimer = new Timer(function () {
_this4.disconnect(function () {
return _this4.connect();
});
}, this.reconnectAfterMs);
}
_createClass(Socket, [{
key: "protocol",
value: function protocol() {
return location.protocol.match(/^https/) ? "wss" : "ws";
}
}, {
key: "endPointURL",
value: function endPointURL() {
var uri = Ajax.appendParams(Ajax.appendParams(this.endPoint, this.params), { vsn: VSN });
if (uri.charAt(0) !== "/") {
return uri;
}
if (uri.charAt(1) === "/") {
return this.protocol() + ":" + uri;
}
return this.protocol() + "://" + location.host + uri;
}
}, {
key: "disconnect",
value: function disconnect(callback, code, reason) {
if (this.conn) {
this.conn.onclose = function () {}; // noop
if (code) {
this.conn.close(code, reason || "");
} else {
this.conn.close();
}
this.conn = null;
}
callback && callback();
}
// params - The params to send when connecting, for example `{user_id: userToken}`
}, {
key: "connect",
value: function connect(params) {
var _this5 = this;
if (params) {
console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor");
this.params = params;
}
if (this.conn) {
return;
}
this.conn = new this.transport(this.endPointURL());
this.conn.timeout = this.longpollerTimeout;
this.conn.onopen = function () {
return _this5.onConnOpen();
};
this.conn.onerror = function (error) {
return _this5.onConnError(error);
};
this.conn.onmessage = function (event) {
return _this5.onConnMessage(event);
};
this.conn.onclose = function (event) {
return _this5.onConnClose(event);
};
}
// Logs the message. Override `this.logger` for specialized logging. noops by default
}, {
key: "log",
value: function log(kind, msg, data) {
this.logger(kind, msg, data);
}
// Registers callbacks for connection state change events
//
// Examples
//
// socket.onError(function(error){ alert("An error occurred") })
//
}, {
key: "onOpen",
value: function onOpen(callback) {
this.stateChangeCallbacks.open.push(callback);
}
}, {
key: "onClose",
value: function onClose(callback) {
this.stateChangeCallbacks.close.push(callback);
}
}, {
key: "onError",
value: function onError(callback) {
this.stateChangeCallbacks.error.push(callback);
}
}, {
key: "onMessage",
value: function onMessage(callback) {
this.stateChangeCallbacks.message.push(callback);
}
}, {
key: "onConnOpen",
value: function onConnOpen() {
var _this6 = this;
this.log("transport", "connected to " + this.endPointURL(), this.transport.prototype);
this.flushSendBuffer();
this.reconnectTimer.reset();
if (!this.conn.skipHeartbeat) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = setInterval(function () {
return _this6.sendHeartbeat();
}, this.heartbeatIntervalMs);
}
this.stateChangeCallbacks.open.forEach(function (callback) {
return callback();
});
}
}, {
key: "onConnClose",
value: function onConnClose(event) {
this.log("transport", "close", event);
this.triggerChanError();
clearInterval(this.heartbeatTimer);
this.reconnectTimer.scheduleTimeout();
this.stateChangeCallbacks.close.forEach(function (callback) {
return callback(event);
});
}
}, {
key: "onConnError",
value: function onConnError(error) {
this.log("transport", error);
this.triggerChanError();
this.stateChangeCallbacks.error.forEach(function (callback) {
return callback(error);
});
}
}, {
key: "triggerChanError",
value: function triggerChanError() {
this.channels.forEach(function (channel) {
return channel.trigger(CHANNEL_EVENTS.error);
});
}
}, {
key: "connectionState",
value: function connectionState() {
switch (this.conn && this.conn.readyState) {
case SOCKET_STATES.connecting:
return "connecting";
case SOCKET_STATES.open:
return "open";
case SOCKET_STATES.closing:
return "closing";
default:
return "closed";
}
}
}, {
key: "isConnected",
value: function isConnected() {
return this.connectionState() === "open";
}
}, {
key: "remove",
value: function remove(channel) {
this.channels = this.channels.filter(function (c) {
return !c.isMember(channel.topic);
});
}
}, {
key: "channel",
value: function channel(topic) {
var chanParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var chan = new Channel(topic, chanParams, this);
this.channels.push(chan);
return chan;
}
}, {
key: "push",
value: function push(data) {
var _this7 = this;
var topic = data.topic;
var event = data.event;
var payload = data.payload;
var ref = data.ref;
var callback = function callback() {
return _this7.conn.send(JSON.stringify(data));
};
this.log("push", topic + " " + event + " (" + ref + ")", payload);
if (this.isConnected()) {
callback();
} else {
this.sendBuffer.push(callback);
}
}
// Return the next message ref, accounting for overflows
}, {
key: "makeRef",
value: function makeRef() {
var newRef = this.ref + 1;
if (newRef === this.ref) {
this.ref = 0;
} else {
this.ref = newRef;
}
return this.ref.toString();
}
}, {
key: "sendHeartbeat",
value: function sendHeartbeat() {
if (!this.isConnected()) {
return;
}
this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref: this.makeRef() });
}
}, {
key: "flushSendBuffer",
value: function flushSendBuffer() {
if (this.isConnected() && this.sendBuffer.length > 0) {
this.sendBuffer.forEach(function (callback) {
return callback();
});
this.sendBuffer = [];
}
}
}, {
key: "onConnMessage",
value: function onConnMessage(rawMessage) {
var msg = JSON.parse(rawMessage.data);
var topic = msg.topic;
var event = msg.event;
var payload = msg.payload;
var ref = msg.ref;
this.log("receive", (payload.status || "") + " " + topic + " " + event + " " + (ref && "(" + ref + ")" || ""), payload);
this.channels.filter(function (channel) {
return channel.isMember(topic);
}).forEach(function (channel) {
return channel.trigger(event, payload, ref);
});
this.stateChangeCallbacks.message.forEach(function (callback) {
return callback(msg);
});
}
}]);
return Socket;
}();
var LongPoll = exports.LongPoll = function () {
function LongPoll(endPoint) {
_classCallCheck(this, LongPoll);
this.endPoint = null;
this.token = null;
this.skipHeartbeat = true;
this.onopen = function () {}; // noop
this.onerror = function () {}; // noop
this.onmessage = function () {}; // noop
this.onclose = function () {}; // noop
this.pollEndpoint = this.normalizeEndpoint(endPoint);
this.readyState = SOCKET_STATES.connecting;
this.poll();
}
_createClass(LongPoll, [{
key: "normalizeEndpoint",
value: function normalizeEndpoint(endPoint) {
return endPoint.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)\/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll);
}
}, {
key: "endpointURL",
value: function endpointURL() {
return Ajax.appendParams(this.pollEndpoint, { token: this.token });
}
}, {
key: "closeAndRetry",
value: function closeAndRetry() {
this.close();
this.readyState = SOCKET_STATES.connecting;
}
}, {
key: "ontimeout",
value: function ontimeout() {
this.onerror("timeout");
this.closeAndRetry();
}
}, {
key: "poll",
value: function poll() {
var _this8 = this;
if (!(this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting)) {
return;
}
Ajax.request("GET", this.endpointURL(), "application/json", null, this.timeout, this.ontimeout.bind(this), function (resp) {
if (resp) {
var status = resp.status;
var token = resp.token;
var messages = resp.messages;
_this8.token = token;
} else {
var status = 0;
}
switch (status) {
case 200:
messages.forEach(function (msg) {
return _this8.onmessage({ data: JSON.stringify(msg) });
});
_this8.poll();
break;
case 204:
_this8.poll();
break;
case 410:
_this8.readyState = SOCKET_STATES.open;
_this8.onopen();
_this8.poll();
break;
case 0:
case 500:
_this8.onerror();
_this8.closeAndRetry();
break;
default:
throw "unhandled poll status " + status;
}
});
}
}, {
key: "send",
value: function send(body) {
var _this9 = this;
Ajax.request("POST", this.endpointURL(), "application/json", body, this.timeout, this.onerror.bind(this, "timeout"), function (resp) {
if (!resp || resp.status !== 200) {
_this9.onerror(status);
_this9.closeAndRetry();
}
});
}
}, {
key: "close",
value: function close(code, reason) {
this.readyState = SOCKET_STATES.closed;
this.onclose();
}
}]);
return LongPoll;
}();
var Ajax = exports.Ajax = function () {
function Ajax() {
_classCallCheck(this, Ajax);
}
_createClass(Ajax, null, [{
key: "request",
value: function request(method, endPoint, accept, body, timeout, ontimeout, callback) {
if (window.XDomainRequest) {
var req = new XDomainRequest(); // IE8, IE9
this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);
} else {
var req = window.XMLHttpRequest ? new XMLHttpRequest() : // IE7+, Firefox, Chrome, Opera, Safari
new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
this.xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback);
}
}
}, {
key: "xdomainRequest",
value: function xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {
var _this10 = this;
req.timeout = timeout;
req.open(method, endPoint);
req.onload = function () {
var response = _this10.parseJSON(req.responseText);
callback && callback(response);
};
if (ontimeout) {
req.ontimeout = ontimeout;
}
// Work around bug in IE9 that requires an attached onprogress handler
req.onprogress = function () {};
req.send(body);
}
}, {
key: "xhrRequest",
value: function xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback) {
var _this11 = this;
req.timeout = timeout;
req.open(method, endPoint, true);
req.setRequestHeader("Content-Type", accept);
req.onerror = function () {
callback && callback(null);
};
req.onreadystatechange = function () {
if (req.readyState === _this11.states.complete && callback) {
var response = _this11.parseJSON(req.responseText);
callback(response);
}
};
if (ontimeout) {
req.ontimeout = ontimeout;
}
req.send(body);
}
}, {
key: "parseJSON",
value: function parseJSON(resp) {
return resp && resp !== "" ? JSON.parse(resp) : null;
}
}, {
key: "serialize",
value: function serialize(obj, parentKey) {
var queryStr = [];
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
var paramKey = parentKey ? parentKey + "[" + key + "]" : key;
var paramVal = obj[key];
if ((typeof paramVal === "undefined" ? "undefined" : _typeof(paramVal)) === "object") {
queryStr.push(this.serialize(paramVal, paramKey));
} else {
queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal));
}
}
return queryStr.join("&");
}
}, {
key: "appendParams",
value: function appendParams(url, params) {
if (Object.keys(params).length === 0) {
return url;
}
var prefix = url.match(/\?/) ? "&" : "?";
return "" + url + prefix + this.serialize(params);
}
}]);
return Ajax;
}();
Ajax.states = { complete: 4 };
// Creates a timer that accepts a `timerCalc` function to perform
// calculated timeout retries, such as exponential backoff.
//
// ## Examples
//
// let reconnectTimer = new Timer(() => this.connect(), function(tries){
// return [1000, 5000, 10000][tries - 1] || 10000
// })
// reconnectTimer.scheduleTimeout() // fires after 1000
// reconnectTimer.scheduleTimeout() // fires after 5000
// reconnectTimer.reset()
// reconnectTimer.scheduleTimeout() // fires after 1000
//
var Timer = function () {
function Timer(callback, timerCalc) {
_classCallCheck(this, Timer);
this.callback = callback;
this.timerCalc = timerCalc;
this.timer = null;
this.tries = 0;
}
_createClass(Timer, [{
key: "reset",