This repository has been archived by the owner on Jan 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
primus.js
7102 lines (5949 loc) · 172 KB
/
primus.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, plugins) {
context[name] = definition.call(context);
for (var i = 0; i < plugins.length; i++) {
plugins[i](context[name])
}
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 wrapper() {
var define, module, exports
, Primus = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
'use strict';
/**
* Create a function that will cleanup the instance.
*
* @param {Array|String} keys Properties on the instance that needs to be cleared.
* @param {Object} options Additional configuration.
* @returns {Function} Destroy function
* @api public
*/
module.exports = function demolish(keys, options) {
var split = /[, ]+/;
options = options || {};
keys = keys || [];
if ('string' === typeof keys) keys = keys.split(split);
/**
* Run addition cleanup hooks.
*
* @param {String} key Name of the clean up hook to run.
* @param {Mixed} selfie Reference to the instance we're cleaning up.
* @api private
*/
function run(key, selfie) {
if (!options[key]) return;
if ('string' === typeof options[key]) options[key] = options[key].split(split);
if ('function' === typeof options[key]) return options[key].call(selfie);
for (var i = 0, type, what; i < options[key].length; i++) {
what = options[key][i];
type = typeof what;
if ('function' === type) {
what.call(selfie);
} else if ('string' === type && 'function' === typeof selfie[what]) {
selfie[what]();
}
}
}
/**
* Destroy the instance completely and clean up all the existing references.
*
* @returns {Boolean}
* @api public
*/
return function destroy() {
var selfie = this
, i = 0
, prop;
if (selfie[keys[0]] === null) return false;
run('before', selfie);
for (; i < keys.length; i++) {
prop = keys[i];
if (selfie[prop]) {
if ('function' === typeof selfie[prop].destroy) selfie[prop].destroy();
selfie[prop] = null;
}
}
if (selfie.emit) selfie.emit('destroy');
run('after', selfie);
return true;
};
};
},{}],2:[function(_dereq_,module,exports){
'use strict';
/**
* Returns a function that when invoked executes all the listeners of the
* given event with the given arguments.
*
* @returns {Function} The function that emits all the things.
* @api public
*/
module.exports = function emits() {
var self = this
, parser;
for (var i = 0, l = arguments.length, args = new Array(l); i < l; i++) {
args[i] = arguments[i];
}
//
// If the last argument is a function, assume that it's a parser.
//
if ('function' !== typeof args[args.length - 1]) return function emitter() {
for (var i = 0, l = arguments.length, arg = new Array(l); i < l; i++) {
arg[i] = arguments[i];
}
return self.emit.apply(self, args.concat(arg));
};
parser = args.pop();
/**
* The actual function that emits the given event. It returns a boolean
* indicating if the event was emitted.
*
* @returns {Boolean}
* @api public
*/
return function emitter() {
for (var i = 0, l = arguments.length, arg = new Array(l + 1); i < l; i++) {
arg[i + 1] = arguments[i];
}
/**
* Async completion method for the parser.
*
* @param {Error} err Optional error when parsing failed.
* @param {Mixed} returned Emit instructions.
* @api private
*/
arg[0] = function next(err, returned) {
if (err) return self.emit('error', err);
arg = returned === undefined
? arg.slice(1) : returned === null
? [] : returned;
self.emit.apply(self, args.concat(arg));
};
parser.apply(self, arg);
return true;
};
};
},{}],3:[function(_dereq_,module,exports){
'use strict';
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @api private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {Mixed} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @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() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @api public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Boolean} exists Only check if there are listeners.
* @returns {Array|Boolean}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event, exists) {
var evt = prefix ? prefix + event : event
, available = this._events[evt];
if (exists) return !!available;
if (!available) return [];
if (available.fn) return [available.fn];
for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
ee[i] = available[i].fn;
}
return ee;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {String|Symbol} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, 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, undefined, 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;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); 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;
};
/**
* Add a listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Add a one-time listener for a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn The listener function.
* @param {Mixed} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true)
, evt = prefix ? prefix + event : event;
if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
else if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [this._events[evt], listener];
return this;
};
/**
* Remove the listeners of a given event.
*
* @param {String|Symbol} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {Mixed} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn
&& (!once || listeners.once)
&& (!context || listeners.context === context)
) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn
|| (once && !listeners[i].once)
|| (context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {String|Symbol} [event] The event name.
* @returns {EventEmitter} `this`.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) {
if (--this._eventsCount === 0) this._events = new Events();
else delete this._events[evt];
}
} else {
this._events = new Events();
this._eventsCount = 0;
}
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;
};
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if ('undefined' !== typeof module) {
module.exports = EventEmitter;
}
},{}],4:[function(_dereq_,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],5:[function(_dereq_,module,exports){
'use strict';
var regex = new RegExp('^((?:\\d+)?\\.?\\d+) *('+ [
'milliseconds?',
'msecs?',
'ms',
'seconds?',
'secs?',
's',
'minutes?',
'mins?',
'm',
'hours?',
'hrs?',
'h',
'days?',
'd',
'weeks?',
'wks?',
'w',
'years?',
'yrs?',
'y'
].join('|') +')?$', 'i');
var second = 1000
, minute = second * 60
, hour = minute * 60
, day = hour * 24
, week = day * 7
, year = day * 365;
/**
* Parse a time string and return the number value of it.
*
* @param {String} ms Time string.
* @returns {Number}
* @api private
*/
module.exports = function millisecond(ms) {
var type = typeof ms
, amount
, match;
if ('number' === type) return ms;
else if ('string' !== type || '0' === ms || !ms) return 0;
else if (+ms) return +ms;
//
// We are vulnerable to the regular expression denial of service (ReDoS).
// In order to mitigate this we don't parse the input string if it is too long.
// See https://nodesecurity.io/advisories/46.
//
if (ms.length > 10000 || !(match = regex.exec(ms))) return 0;
amount = parseFloat(match[1]);
switch (match[2].toLowerCase()) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return amount * year;
case 'weeks':
case 'week':
case 'wks':
case 'wk':
case 'w':
return amount * week;
case 'days':
case 'day':
case 'd':
return amount * day;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return amount * hour;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return amount * minute;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return amount * second;
default:
return amount;
}
};
},{}],6:[function(_dereq_,module,exports){
'use strict';
/**
* Wrap callbacks to prevent double execution.
*
* @param {Function} fn Function that should only be called once.
* @returns {Function} A wrapped callback which prevents execution.
* @api public
*/
module.exports = function one(fn) {
var called = 0
, value;
/**
* The function that prevents double execution.
*
* @api private
*/
function onetime() {
if (called) return value;
called = 1;
value = fn.apply(this, arguments);
fn = null;
return value;
}
//
// To make debugging more easy we want to use the name of the supplied
// function. So when you look at the functions that are assigned to event
// listeners you don't see a load of `onetime` functions but actually the
// names of the functions that this module will call.
//
onetime.displayName = fn.displayName || fn.name || onetime.displayName || onetime.name;
return onetime;
};
},{}],7:[function(_dereq_,module,exports){
'use strict';
var has = Object.prototype.hasOwnProperty;
/**
* Simple query string parser.
*
* @param {String} query The query string that needs to be parsed.
* @returns {Object}
* @api public
*/
function querystring(query) {
var parser = /([^=?&]+)=?([^&]*)/g
, result = {}
, part;
//
// Little nifty parsing hack, leverage the fact that RegExp.exec increments
// the lastIndex property so we can continue executing this loop until we've
// parsed all results.
//
for (;
part = parser.exec(query);
result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
);
return result;
}
/**
* Transform a query string to an object.
*
* @param {Object} obj Object that should be transformed.
* @param {String} prefix Optional prefix.
* @returns {String}
* @api public
*/
function querystringify(obj, prefix) {
prefix = prefix || '';
var pairs = [];
//
// Optionally prefix with a '?' if needed
//
if ('string' !== typeof prefix) prefix = '?';
for (var key in obj) {
if (has.call(obj, key)) {
pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
}
}
return pairs.length ? prefix + pairs.join('&') : '';
}
//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;
},{}],8:[function(_dereq_,module,exports){
'use strict';
var EventEmitter = _dereq_('eventemitter3')
, millisecond = _dereq_('millisecond')
, destroy = _dereq_('demolish')
, Tick = _dereq_('tick-tock')
, one = _dereq_('one-time');
/**
* Returns sane defaults about a given value.
*
* @param {String} name Name of property we want.
* @param {Recovery} selfie Recovery instance that got created.
* @param {Object} opts User supplied options we want to check.
* @returns {Number} Some default value.
* @api private
*/
function defaults(name, selfie, opts) {
return millisecond(
name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
);
}
/**
* Attempt to recover your connection with reconnection attempt.
*
* @constructor
* @param {Object} options Configuration
* @api public
*/
function Recovery(options) {
var recovery = this;
if (!(recovery instanceof Recovery)) return new Recovery(options);
options = options || {};
recovery.attempt = null; // Stores the current reconnect attempt.
recovery._fn = null; // Stores the callback.
recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
recovery.retries = defaults('retries', recovery, options);
recovery.factor = defaults('factor', recovery, options);
recovery.max = defaults('max', recovery, options);
recovery.min = defaults('min', recovery, options);
recovery.timers = new Tick(recovery);
}
Recovery.prototype = new EventEmitter();
Recovery.prototype.constructor = Recovery;
Recovery['reconnect timeout'] = '30 seconds'; // Maximum time to wait for an answer.
Recovery.max = Infinity; // Maximum delay.
Recovery.min = '500 ms'; // Minimum delay.
Recovery.retries = 10; // Maximum amount of retries.
Recovery.factor = 2; // Exponential back off factor.
/**
* Start a new reconnect procedure.
*
* @returns {Recovery}
* @api public
*/
Recovery.prototype.reconnect = function reconnect() {
var recovery = this;
return recovery.backoff(function backedoff(err, opts) {
opts.duration = (+new Date()) - opts.start;
if (err) return recovery.emit('reconnect failed', err, opts);
recovery.emit('reconnected', opts);
}, recovery.attempt);
};
/**
* Exponential back off algorithm for retry operations. It uses a randomized
* retry so we don't DDOS our server when it goes down under pressure.
*
* @param {Function} fn Callback to be called after the timeout.
* @param {Object} opts Options for configuring the timeout.
* @returns {Recovery}
* @api private
*/
Recovery.prototype.backoff = function backoff(fn, opts) {
var recovery = this;
opts = opts || recovery.attempt || {};
//
// Bailout when we already have a back off process running. We shouldn't call
// the callback then.
//
if (opts.backoff) return recovery;
opts['reconnect timeout'] = defaults('reconnect timeout', recovery, opts);
opts.retries = defaults('retries', recovery, opts);
opts.factor = defaults('factor', recovery, opts);
opts.max = defaults('max', recovery, opts);
opts.min = defaults('min', recovery, opts);
opts.start = +opts.start || +new Date();
opts.duration = +opts.duration || 0;
opts.attempt = +opts.attempt || 0;
//
// Bailout if we are about to make too much attempts.
//
if (opts.attempt === opts.retries) {
fn.call(recovery, new Error('Unable to recover'), opts);
return recovery;
}
//
// Prevent duplicate back off attempts using the same options object and
// increment our attempt as we're about to have another go at this thing.
//
opts.backoff = true;
opts.attempt++;
recovery.attempt = opts;
//
// Calculate the timeout, but make it randomly so we don't retry connections
// at the same interval and defeat the purpose. This exponential back off is
// based on the work of:
//
// http://dthain.blogspot.nl/2009/02/exponential-backoff-in-distributed.html
//
opts.scheduled = opts.attempt !== 1
? Math.min(Math.round(
(Math.random() + 1) * opts.min * Math.pow(opts.factor, opts.attempt - 1)
), opts.max)
: opts.min;
recovery.timers.setTimeout('reconnect', function delay() {
opts.duration = (+new Date()) - opts.start;
opts.backoff = false;
recovery.timers.clear('reconnect, timeout');
//
// Create a `one` function which can only be called once. So we can use the
// same function for different types of invocations to create a much better
// and usable API.
//
var connect = recovery._fn = one(function connect(err) {
recovery.reset();
if (err) return recovery.backoff(fn, opts);
fn.call(recovery, undefined, opts);
});
recovery.emit('reconnect', opts, connect);
recovery.timers.setTimeout('timeout', function timeout() {
var err = new Error('Failed to reconnect in a timely manner');
opts.duration = (+new Date()) - opts.start;
recovery.emit('reconnect timeout', err, opts);
connect(err);
}, opts['reconnect timeout']);
}, opts.scheduled);
//
// Emit a `reconnecting` event with current reconnect options. This allows
// them to update the UI and provide their users with feedback.
//
recovery.emit('reconnect scheduled', opts);
return recovery;
};
/**
* Check if the reconnection process is currently reconnecting.
*
* @returns {Boolean}
* @api public
*/
Recovery.prototype.reconnecting = function reconnecting() {
return !!this.attempt;
};
/**
* Tell our reconnection procedure that we're passed.
*
* @param {Error} err Reconnection failed.
* @returns {Recovery}
* @api public
*/
Recovery.prototype.reconnected = function reconnected(err) {
if (this._fn) this._fn(err);
return this;
};
/**
* Reset the reconnection attempt so it can be re-used again.
*
* @returns {Recovery}
* @api public
*/
Recovery.prototype.reset = function reset() {
this._fn = this.attempt = null;
this.timers.clear('reconnect, timeout');
return this;
};
/**
* Clean up the instance.
*
* @type {Function}
* @returns {Boolean}
* @api public
*/
Recovery.prototype.destroy = destroy('timers attempt _fn');
//
// Expose the module.
//
module.exports = Recovery;
},{"demolish":1,"eventemitter3":9,"millisecond":5,"one-time":6,"tick-tock":11}],9:[function(_dereq_,module,exports){
'use strict';
//
// We store our EE objects in a plain object whose properties are event names.
// If `Object.create(null)` is not supported we prefix the event names with a
// `~` to make sure that the built-in object properties are not overridden or
// used as an attack vector.
// We also assume that `Object.create(null)` is available when the event name
// is an ES6 Symbol.
//
var prefix = typeof Object.create !== 'function' ? '~' : false;
/**
* 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.
* @param {Boolean} exists We only need to know if there are listeners.
* @returns {Array|Boolean}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event, exists) {
var evt = prefix ? prefix + event : event
, available = this._events && this._events[evt];
if (exists) return !!available;
if (!available) return [];
if (available.fn) return [available.fn];
for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
ee[i] = available[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) {
var evt = prefix ? prefix + event : event;
if (!this._events || !this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;