-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1765 lines (1504 loc) · 49.3 KB
/
index.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 UMDish(name, context, definition) { context[name] = definition.call(context); if (typeof module !== "undefined" && module.exports) { module.exports = context[name]; } else if (typeof define == "function" && define.amd) { define(function reference() { return context[name]; }); }})("Primus", this, function Primus() {/*globals require, define */
'use strict';
/**
* Representation of a single EventEmitter function.
*
* @param {Function} fn Event handler to be called.
* @param {Mixed} context Context for function execution.
* @param {Boolean} once Only emit once
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal EventEmitter interface that is molded against the Node.js
* EventEmitter interface.
*
* @constructor
* @api public
*/
function EventEmitter() { /* Nothing to set */ }
/**
* Holds the assigned EventEmitters by name.
*
* @type {Object}
* @private
*/
EventEmitter.prototype._events = undefined;
/**
* Return a list of assigned event listeners.
*
* @param {String} event The events that should be listed.
* @returns {Array}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event) {
if (!this._events || !this._events[event]) return [];
if (this._events[event].fn) return [this._events[event].fn];
for (var i = 0, l = this._events[event].length, ee = new Array(l); i < l; i++) {
ee[i] = this._events[event][i].fn;
}
return ee;
};
/**
* Emit an event to all registered event listeners.
*
* @param {String} event The name of the event.
* @returns {Boolean} Indication if we've emitted an event.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
if (!this._events || !this._events[event]) return false;
var listeners = this._events[event]
, len = arguments.length
, args
, i;
if ('function' === typeof listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Register a new EventListener for the given event.
*
* @param {String} event Name of the event.
* @param {Functon} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this);
if (!this._events) this._events = {};
if (!this._events[event]) this._events[event] = listener;
else {
if (!this._events[event].fn) this._events[event].push(listener);
else this._events[event] = [
this._events[event], listener
];
}
return this;
};
/**
* Add an EventListener that's only called once.
*
* @param {String} event Name of the event.
* @param {Function} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true);
if (!this._events) this._events = {};
if (!this._events[event]) this._events[event] = listener;
else {
if (!this._events[event].fn) this._events[event].push(listener);
else this._events[event] = [
this._events[event], listener
];
}
return this;
};
/**
* Remove event listeners.
*
* @param {String} event The event we want to remove.
* @param {Function} fn The listener that we need to find.
* @param {Boolean} once Only remove once listeners.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, once) {
if (!this._events || !this._events[event]) return this;
var listeners = this._events[event]
, events = [];
if (fn) {
if (listeners.fn && (listeners.fn !== fn || (once && !listeners.once))) {
events.push(listeners);
}
if (!listeners.fn) for (var i = 0, length = listeners.length; i < length; i++) {
if (listeners[i].fn !== fn || (once && !listeners[i].once)) {
events.push(listeners[i]);
}
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) {
this._events[event] = events.length === 1 ? events[0] : events;
} else {
delete this._events[event];
}
return this;
};
/**
* Remove all listeners or only the listeners for the specified event.
*
* @param {String} event The event want to remove all listeners for.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
if (!this._events) return this;
if (event) delete this._events[event];
else this._events = {};
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
/**
* Context assertion, ensure that some of our public Primus methods are called
* with the correct context to ensure that
*
* @param {Primus} self The context of the function.
* @param {String} method The method name.
* @api private
*/
function context(self, method) {
if (self instanceof Primus) return;
var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance');
if ('function' !== typeof self.listeners || !self.listeners('error').length) {
throw failure;
}
self.emit('error', failure);
}
//
// Sets the default connection URL, it uses the default origin of the browser
// when supported but degrades for older browsers. In Node.js, we cannot guess
// where the user wants to connect to, so we just default to localhost.
//
var defaultUrl;
try {
if (location.origin) {
defaultUrl = location.origin;
} else {
defaultUrl = location.protocol +'//'+ location.hostname + (location.port ? ':'+ location.port : '');
}
} catch (e) {
defaultUrl = 'http://127.0.0.1';
}
/**
* Primus in a real-time library agnostic framework for establishing real-time
* connections with servers.
*
* Options:
* - reconnect, configuration for the reconnect process.
* - manual, don't automatically call `.open` to start the connection.
* - websockets, force the use of WebSockets, even when you should avoid them.
* - timeout, connect timeout, server didn't respond in a timely manner.
* - ping, The heartbeat interval for sending a ping packet to the server.
* - pong, The heartbeat timeout for receiving a response to the ping.
* - network, Use network events as leading method for network connection drops.
* - strategy, Reconnection strategies.
* - transport, Transport options.
* - url, uri, The URL to use connect with the server.
*
* @constructor
* @param {String} url The URL of your server.
* @param {Object} options The configuration.
* @api public
*/
function Primus(url, options) {
if (!(this instanceof Primus)) return new Primus(url, options);
if ('function' !== typeof this.client) {
var message = 'The client library has not been compiled correctly, ' +
'see https://github.com/primus/primus#client-library for more details';
return this.critical(new Error(message));
}
if ('object' === typeof url) {
options = url;
url = options.url || options.uri || defaultUrl;
} else {
options = options || {};
}
var primus = this;
// The maximum number of messages that can be placed in queue.
options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
// Connection timeout duration.
options.timeout = 'timeout' in options ? options.timeout : 10e3;
// Stores the back off configuration.
options.reconnect = 'reconnect' in options ? options.reconnect : {};
// Heartbeat ping interval.
options.ping = 'ping' in options ? options.ping : 25000;
// Heartbeat pong response timeout.
options.pong = 'pong' in options ? options.pong : 10e3;
// Reconnect strategies.
options.strategy = 'strategy' in options ? options.strategy : [];
// Custom transport options.
options.transport = 'transport' in options ? options.transport : {};
primus.buffer = []; // Stores premature send data.
primus.writable = true; // Silly stream compatibility.
primus.readable = true; // Silly stream compatibility.
primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
primus.readyState = Primus.CLOSED; // The readyState of the connection.
primus.options = options; // Reference to the supplied options.
primus.timers = {}; // Contains all our timers.
primus.attempt = null; // Current back off attempt.
primus.socket = null; // Reference to the internal connection.
primus.latency = 0; // Latency between messages.
primus.stamps = 0; // Counter to make timestamps unqiue.
primus.disconnect = false; // Did we receive a disconnect packet?
primus.transport = options.transport; // Transport options.
primus.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
//
// Parse the reconnection strategy. It can have the following strategies:
//
// - timeout: Reconnect when we have a network timeout.
// - disconnect: Reconnect when we have an unexpected disconnect.
// - online: Reconnect when we're back online.
//
if ('string' === typeof options.strategy) {
options.strategy = options.strategy.split(/\s?\,\s?/g);
}
if (false === options.strategy) {
//
// Strategies are disabled, but we still need an empty array to join it in
// to nothing.
//
options.strategy = [];
} else if (!options.strategy.length) {
options.strategy.push('disconnect', 'online');
//
// Timeout based reconnection should only be enabled conditionally. When
// authorization is enabled it could trigger.
//
if (!this.authorization) options.strategy.push('timeout');
}
options.strategy = options.strategy.join(',').toLowerCase();
//
// Only initialise the EventEmitter interface if we're running in a plain
// browser environment. The Stream interface is inherited differently when it
// runs on browserify and on Node.js.
//
if (!Stream) EventEmitter.call(primus);
//
// Force the use of WebSockets, even when we've detected some potential
// broken WebSocket implementation.
//
if ('websockets' in options) {
primus.AVOID_WEBSOCKETS = !options.websockets;
}
//
// Force or disable the use of NETWORK events as leading client side
// disconnection detection.
//
if ('network' in options) {
primus.NETWORK_EVENTS = options.network;
}
//
// Check if the user wants to manually initialise a connection. If they don't,
// we want to do it after a really small timeout so we give the users enough
// time to listen for `error` events etc.
//
if (!options.manual) primus.timers.open = setTimeout(function open() {
primus.clearTimeout('open').open();
}, 0);
primus.initialise(options);
}
/**
* Simple require wrapper to make browserify, node and require.js play nice.
*
* @param {String} name The module to require.
* @returns {Object|Undefined} The module that we required.
* @api private
*/
Primus.require = function requires(name) {
if ('function' !== typeof require) return undefined;
return !('function' === typeof define && define.amd)
? require(name)
: undefined;
};
//
// It's possible that we're running in Node.js or in a Node.js compatible
// environment such as browserify. In these cases we want to use some build in
// libraries to minimize our dependence on the DOM.
//
var Stream, parse;
try {
Primus.Stream = Stream = Primus.require('stream');
parse = Primus.require('url').parse;
//
// Normally inheritance is done in the same way as we do in our catch
// statement. But due to changes to the EventEmitter interface in Node 0.10
// this will trigger annoying memory leak warnings and other potential issues
// outlined in the issue linked below.
//
// @see https://github.com/joyent/node/issues/4971
//
Primus.require('util').inherits(Primus, Stream);
} catch (e) {
Primus.Stream = EventEmitter;
Primus.prototype = new EventEmitter();
//
// In the browsers we can leverage the DOM to parse the URL for us. It will
// automatically default to host of the current server when we supply it path
// etc.
//
parse = function parse(url) {
var a = document.createElement('a')
, data = {}
, key;
a.href = url;
//
// Transform it from a readOnly object to a read/writable object so we can
// change some parsed values. This is required if we ever want to override
// a port number etc. (as browsers remove port 443 and 80 from the URL's).
//
for (key in a) {
if ('string' === typeof a[key] || 'number' === typeof a[key]) {
data[key] = a[key];
}
}
//
// We need to make sure that the URL is properly encoded because IE doesn't
// do this automatically.
//
data.href = encodeURI(decodeURI(data.href));
//
// If we don't obtain a port number (e.g. when using zombie) then try
// and guess at a value from the 'href' value.
//
if (!data.port) {
var splits = (data.href || '').split('/');
if (splits.length > 2) {
var host = splits[2]
, atSignIndex = host.lastIndexOf('@');
if (~atSignIndex) host = host.slice(atSignIndex + 1);
splits = host.split(':');
if (splits.length === 2) data.port = splits[1];
}
}
//
// IE quirk: The `protocol` is parsed as ":" or "" when a protocol agnostic
// URL is used. In this case we extract the value from the `href` value.
//
if (!data.protocol || ':' === data.protocol) {
data.protocol = data.href.substr(0, data.href.indexOf(':') + 1);
}
//
// Safari 5.1.7 (windows) quirk: When parsing a URL without a port number
// the `port` in the data object will default to "0" instead of the expected
// "". We're going to do an explicit check on "0" and force it to "".
//
if ('0' === data.port) data.port = '';
//
// Browsers do not parse authorization information, so we need to extract
// that from the URL.
//
if (~data.href.indexOf('@') && !data.auth) {
var start = data.protocol.length + 2;
data.auth = data.href.slice(start, data.href.indexOf(data.pathname, start)).split('@')[0];
}
return data;
};
}
/**
* Primus readyStates, used internally to set the correct ready state.
*
* @type {Number}
* @private
*/
Primus.OPENING = 1; // We're opening the connection.
Primus.CLOSED = 2; // No active connection.
Primus.OPEN = 3; // The connection is open.
/**
* Are we working with a potentially broken WebSockets implementation? This
* boolean can be used by transformers to remove `WebSockets` from their
* supported transports.
*
* @type {Boolean}
* @private
*/
Primus.prototype.AVOID_WEBSOCKETS = false;
/**
* Some browsers support registering emitting `online` and `offline` events when
* the connection has been dropped on the client. We're going to detect it in
* a simple `try {} catch (e) {}` statement so we don't have to do complicated
* feature detection.
*
* @type {Boolean}
* @private
*/
Primus.prototype.NETWORK_EVENTS = false;
Primus.prototype.online = true;
try {
if (
Primus.prototype.NETWORK_EVENTS = 'onLine' in navigator
&& (window.addEventListener || document.body.attachEvent)
) {
if (!navigator.onLine) {
Primus.prototype.online = false;
}
}
} catch (e) { }
/**
* The Ark contains all our plugins definitions. It's namespaced by
* name => plugin.
*
* @type {Object}
* @private
*/
Primus.prototype.ark = {};
/**
* Return the given plugin.
*
* @param {String} name The name of the plugin.
* @returns {Object|undefined} The plugin or undefined.
* @api public
*/
Primus.prototype.plugin = function plugin(name) {
context(this, 'plugin');
if (name) return this.ark[name];
var plugins = {};
for (name in this.ark) {
plugins[name] = this.ark[name];
}
return plugins;
};
/**
* Checks if the given event is an emitted event by Primus.
*
* @param {String} evt The event name.
* @returns {Boolean} Indication of the event is reserved for internal use.
* @api public
*/
Primus.prototype.reserved = function reserved(evt) {
return (/^(incoming|outgoing)::/).test(evt)
|| evt in this.reserved.events;
};
/**
* The actual events that are used by the client.
*
* @type {Object}
* @public
*/
Primus.prototype.reserved.events = {
readyStateChange: 1,
reconnecting: 1,
reconnected: 1,
reconnect: 1,
offline: 1,
timeout: 1,
online: 1,
error: 1,
close: 1,
open: 1,
data: 1,
end: 1
};
/**
* Initialise the Primus and setup all parsers and internal listeners.
*
* @param {Object} options The original options object.
* @returns {Primus}
* @api private
*/
Primus.prototype.initialise = function initialise(options) {
var primus = this
, start;
primus.on('outgoing::open', function opening() {
var readyState = primus.readyState;
primus.readyState = Primus.OPENING;
if (readyState !== primus.readyState) {
primus.emit('readyStateChange', 'opening');
}
start = +new Date();
});
primus.on('incoming::open', function opened() {
var readyState = primus.readyState
, reconnect = primus.attempt;
if (primus.attempt) primus.attempt = null;
//
// The connection has been openend so we should set our state to
// (writ|read)able so our stream compatibility works as intended.
//
primus.writable = true;
primus.readable = true;
//
// Make sure we are flagged as `online` as we've successfully opened the
// connection.
//
if (!primus.online) {
primus.online = true;
primus.emit('online');
}
primus.readyState = Primus.OPEN;
if (readyState !== primus.readyState) {
primus.emit('readyStateChange', 'open');
}
primus.latency = +new Date() - start;
primus.emit('open');
if (reconnect) primus.emit('reconnected');
primus.clearTimeout('ping', 'pong').heartbeat();
if (primus.buffer.length) {
var data = primus.buffer.slice()
, length = data.length
, i = 0;
primus.buffer.length = 0;
for (; i < length; i++) {
primus._write(data[i]);
}
}
});
primus.on('incoming::pong', function pong(time) {
primus.online = true;
primus.clearTimeout('pong').heartbeat();
primus.latency = (+new Date()) - time;
});
primus.on('incoming::error', function error(e) {
var connect = primus.timers.connect
, err = e;
//
// We're still doing a reconnect attempt, it could be that we failed to
// connect because the server was down. Failing connect attempts should
// always emit an `error` event instead of a `open` event.
//
if (primus.attempt) return primus.reconnect();
//
// When the error is not an Error instance we try to normalize it.
//
if ('string' === typeof e) {
err = new Error(e);
} else if (!(e instanceof Error) && 'object' === typeof e) {
//
// BrowserChannel and SockJS returns an object which contains some
// details of the error. In order to have a proper error we "copy" the
// details in an Error instance.
//
err = new Error(e.message || e.reason);
for (var key in e) {
if (e.hasOwnProperty(key)) err[key] = e[key];
}
}
if (primus.listeners('error').length) primus.emit('error', err);
//
// We received an error while connecting, this most likely the result of an
// unauthorized access to the server.
//
if (connect) {
if (~primus.options.strategy.indexOf('timeout')) primus.reconnect();
else primus.end();
}
});
primus.on('incoming::data', function message(raw) {
primus.decoder(raw, function decoding(err, data) {
//
// Do a "save" emit('error') when we fail to parse a message. We don't
// want to throw here as listening to errors should be optional.
//
if (err) return primus.listeners('error').length && primus.emit('error', err);
//
// Handle all "primus::" prefixed protocol messages.
//
if (primus.protocol(data)) return;
primus.transforms(primus, primus, 'incoming', data, raw);
});
});
primus.on('incoming::end', function end() {
var readyState = primus.readyState;
//
// This `end` started with the receiving of a primus::server::close packet
// which indicated that the user/developer on the server closed the
// connection and it was not a result of a network disruption. So we should
// kill the connection without doing a reconnect.
//
if (primus.disconnect) {
primus.disconnect = false;
return primus.end();
}
//
// Always set the readyState to closed, and if we're still connecting, close
// the connection so we're sure that everything after this if statement block
// is only executed because our readyState is set to `open`.
//
primus.readyState = Primus.CLOSED;
if (readyState !== primus.readyState) {
primus.emit('readyStateChange', 'end');
}
if (primus.timers.connect) primus.end();
if (readyState !== Primus.OPEN) {
return primus.attempt ? primus.reconnect() : false;
}
this.writable = false;
this.readable = false;
//
// Clear all timers in case we're not going to reconnect.
//
for (var timeout in this.timers) {
this.clearTimeout(timeout);
}
//
// Fire the `close` event as an indication of connection disruption.
// This is also fired by `primus#end` so it is emitted in all cases.
//
primus.emit('close');
//
// The disconnect was unintentional, probably because the server has
// shutdown, so if the reconnection is enabled start a reconnect procedure.
//
if (~primus.options.strategy.indexOf('disconnect')) {
return primus.reconnect();
}
primus.emit('outgoing::end');
primus.emit('end');
});
//
// Setup the real-time client.
//
primus.client();
//
// Process the potential plugins.
//
for (var plugin in primus.ark) {
primus.ark[plugin].call(primus, primus, options);
}
//
// NOTE: The following code is only required if we're supporting network
// events as it requires access to browser globals.
//
if (!primus.NETWORK_EVENTS) return primus;
/**
* Handler for offline notifications.
*
* @api private
*/
function offline() {
if (!primus.online) return; // Already or still offline, bailout.
primus.online = false;
primus.emit('offline');
primus.end();
//
// It is certainly possible that we're in a reconnection loop and that the
// user goes offline. In this case we want to kill the existing attempt so
// when the user goes online, it will attempt to reconnect freshly again.
//
primus.clearTimeout('reconnect');
primus.attempt = null;
}
/**
* Handler for online notifications.
*
* @api private
*/
function online() {
if (primus.online) return; // Already or still online, bailout
primus.online = true;
primus.emit('online');
if (~primus.options.strategy.indexOf('online')) primus.reconnect();
}
if (window.addEventListener) {
window.addEventListener('offline', offline, false);
window.addEventListener('online', online, false);
} else if (document.body.attachEvent){
document.body.attachEvent('onoffline', offline);
document.body.attachEvent('ononline', online);
}
return primus;
};
/**
* Really dead simple protocol parser. We simply assume that every message that
* is prefixed with `primus::` could be used as some sort of protocol definition
* for Primus.
*
* @param {String} msg The data.
* @returns {Boolean} Is a protocol message.
* @api private
*/
Primus.prototype.protocol = function protocol(msg) {
if (
'string' !== typeof msg
|| msg.indexOf('primus::') !== 0
) return false;
var last = msg.indexOf(':', 8)
, value = msg.slice(last + 2);
switch (msg.slice(8, last)) {
case 'pong':
this.emit('incoming::pong', value);
break;
case 'server':
//
// The server is closing the connection, forcefully disconnect so we don't
// reconnect again.
//
if ('close' === value) {
this.disconnect = true;
}
break;
case 'id':
this.emit('incoming::id', value);
break;
//
// Unknown protocol, somebody is probably sending `primus::` prefixed
// messages.
//
default:
return false;
}
return true;
};
/**
* Execute the set of message transformers from Primus on the incoming or
* outgoing message.
* This function and it's content should be in sync with Spark#transforms in
* spark.js.
*
* @param {Primus} primus Reference to the Primus instance with message transformers.
* @param {Spark|Primus} connection Connection that receives or sends data.
* @param {String} type The type of message, 'incoming' or 'outgoing'.
* @param {Mixed} data The data to send or that has been received.
* @param {String} raw The raw encoded data.
* @returns {Primus}
* @api public
*/
Primus.prototype.transforms = function transforms(primus, connection, type, data, raw) {
var packet = { data: data }
, fns = primus.transformers[type];
//
// Iterate in series over the message transformers so we can allow optional
// asynchronous execution of message transformers which could for example
// retrieve additional data from the server, do extra decoding or even
// message validation.
//
(function transform(index, done) {
var transformer = fns[index++];
if (!transformer) return done();
if (1 === transformer.length) {
if (false === transformer.call(connection, packet)) {
//
// When false is returned by an incoming transformer it means that's
// being handled by the transformer and we should not emit the `data`
// event.
//
return;
}
return transform(index, done);
}
transformer.call(connection, packet, function finished(err, arg) {
if (err) return connection.emit('error', err);
if (false === arg) return;
transform(index, done);
});
}(0, function done() {
//
// We always emit 2 arguments for the data event, the first argument is the
// parsed data and the second argument is the raw string that we received.
// This allows you, for example, to do some validation on the parsed data
// and then save the raw string in your database without the stringify
// overhead.
//
if ('incoming' === type) return connection.emit('data', packet.data, raw);
connection._write(packet.data);
}));
return this;
};
/**
* Retrieve the current id from the server.
*
* @param {Function} fn Callback function.
* @returns {Primus}
* @api public
*/
Primus.prototype.id = function id(fn) {
if (this.socket && this.socket.id) return fn(this.socket.id);
this._write('primus::id::');
return this.once('incoming::id', fn);
};
/**
* Establish a connection with the server. When this function is called we
* assume that we don't have any open connections. If you do call it when you
* have a connection open, it could cause duplicate connections.
*
* @returns {Primus}