@depup/primus 8.0.9-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +36 -0
  3. package/changes.json +30 -0
  4. package/dist/primus.js +3663 -0
  5. package/errors.js +51 -0
  6. package/index.js +1153 -0
  7. package/middleware/access-control.js +20 -0
  8. package/middleware/authorization.js +57 -0
  9. package/middleware/error.js +41 -0
  10. package/middleware/forwarded.js +18 -0
  11. package/middleware/no-cache.js +25 -0
  12. package/middleware/primus.js +47 -0
  13. package/middleware/spec.js +36 -0
  14. package/middleware/xss.js +28 -0
  15. package/package.json +140 -0
  16. package/parsers/binary.js +54 -0
  17. package/parsers/ejson.js +41 -0
  18. package/parsers/json.js +35 -0
  19. package/parsers/msgpack.js +55 -0
  20. package/parsers.json +12 -0
  21. package/primus.js +1158 -0
  22. package/spark.js +515 -0
  23. package/transformer.js +237 -0
  24. package/transformers/browserchannel/client.js +92 -0
  25. package/transformers/browserchannel/index.js +19 -0
  26. package/transformers/browserchannel/server.js +64 -0
  27. package/transformers/engine.io/README.md +34 -0
  28. package/transformers/engine.io/client.js +111 -0
  29. package/transformers/engine.io/index.js +15 -0
  30. package/transformers/engine.io/library.js +2273 -0
  31. package/transformers/engine.io/server.js +63 -0
  32. package/transformers/faye/client.js +103 -0
  33. package/transformers/faye/index.js +12 -0
  34. package/transformers/faye/server.js +85 -0
  35. package/transformers/sockjs/README.md +31 -0
  36. package/transformers/sockjs/client.js +86 -0
  37. package/transformers/sockjs/index.js +15 -0
  38. package/transformers/sockjs/library.js +4201 -0
  39. package/transformers/sockjs/server.js +108 -0
  40. package/transformers/uws/index.js +12 -0
  41. package/transformers/uws/server.js +131 -0
  42. package/transformers/websockets/client.js +112 -0
  43. package/transformers/websockets/index.js +12 -0
  44. package/transformers/websockets/server.js +77 -0
  45. package/transformers.json +26 -0
package/dist/primus.js ADDED
@@ -0,0 +1,3663 @@
1
+ (function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.Primus=f()})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
2
+ 'use strict';
3
+
4
+ /**
5
+ * Create a function that will cleanup the instance.
6
+ *
7
+ * @param {Array|String} keys Properties on the instance that needs to be cleared.
8
+ * @param {Object} options Additional configuration.
9
+ * @returns {Function} Destroy function
10
+ * @api public
11
+ */
12
+ module.exports = function demolish(keys, options) {
13
+ var split = /[, ]+/;
14
+
15
+ options = options || {};
16
+ keys = keys || [];
17
+
18
+ if ('string' === typeof keys) keys = keys.split(split);
19
+
20
+ /**
21
+ * Run addition cleanup hooks.
22
+ *
23
+ * @param {String} key Name of the clean up hook to run.
24
+ * @param {Mixed} selfie Reference to the instance we're cleaning up.
25
+ * @api private
26
+ */
27
+ function run(key, selfie) {
28
+ if (!options[key]) return;
29
+ if ('string' === typeof options[key]) options[key] = options[key].split(split);
30
+ if ('function' === typeof options[key]) return options[key].call(selfie);
31
+
32
+ for (var i = 0, type, what; i < options[key].length; i++) {
33
+ what = options[key][i];
34
+ type = typeof what;
35
+
36
+ if ('function' === type) {
37
+ what.call(selfie);
38
+ } else if ('string' === type && 'function' === typeof selfie[what]) {
39
+ selfie[what]();
40
+ }
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Destroy the instance completely and clean up all the existing references.
46
+ *
47
+ * @returns {Boolean}
48
+ * @api public
49
+ */
50
+ return function destroy() {
51
+ var selfie = this
52
+ , i = 0
53
+ , prop;
54
+
55
+ if (selfie[keys[0]] === null) return false;
56
+ run('before', selfie);
57
+
58
+ for (; i < keys.length; i++) {
59
+ prop = keys[i];
60
+
61
+ if (selfie[prop]) {
62
+ if ('function' === typeof selfie[prop].destroy) selfie[prop].destroy();
63
+ selfie[prop] = null;
64
+ }
65
+ }
66
+
67
+ if (selfie.emit) selfie.emit('destroy');
68
+ run('after', selfie);
69
+
70
+ return true;
71
+ };
72
+ };
73
+
74
+ },{}],2:[function(_dereq_,module,exports){
75
+ 'use strict';
76
+
77
+ /**
78
+ * Returns a function that when invoked executes all the listeners of the
79
+ * given event with the given arguments.
80
+ *
81
+ * @returns {Function} The function that emits all the things.
82
+ * @api public
83
+ */
84
+ module.exports = function emits() {
85
+ var self = this
86
+ , parser;
87
+
88
+ for (var i = 0, l = arguments.length, args = new Array(l); i < l; i++) {
89
+ args[i] = arguments[i];
90
+ }
91
+
92
+ //
93
+ // If the last argument is a function, assume that it's a parser.
94
+ //
95
+ if ('function' !== typeof args[args.length - 1]) return function emitter() {
96
+ for (var i = 0, l = arguments.length, arg = new Array(l); i < l; i++) {
97
+ arg[i] = arguments[i];
98
+ }
99
+
100
+ return self.emit.apply(self, args.concat(arg));
101
+ };
102
+
103
+ parser = args.pop();
104
+
105
+ /**
106
+ * The actual function that emits the given event. It returns a boolean
107
+ * indicating if the event was emitted.
108
+ *
109
+ * @returns {Boolean}
110
+ * @api public
111
+ */
112
+ return function emitter() {
113
+ for (var i = 0, l = arguments.length, arg = new Array(l + 1); i < l; i++) {
114
+ arg[i + 1] = arguments[i];
115
+ }
116
+
117
+ /**
118
+ * Async completion method for the parser.
119
+ *
120
+ * @param {Error} err Optional error when parsing failed.
121
+ * @param {Mixed} returned Emit instructions.
122
+ * @api private
123
+ */
124
+ arg[0] = function next(err, returned) {
125
+ if (err) return self.emit('error', err);
126
+
127
+ arg = returned === undefined
128
+ ? arg.slice(1) : returned === null
129
+ ? [] : returned;
130
+
131
+ self.emit.apply(self, args.concat(arg));
132
+ };
133
+
134
+ parser.apply(self, arg);
135
+ return true;
136
+ };
137
+ };
138
+
139
+ },{}],3:[function(_dereq_,module,exports){
140
+ 'use strict';
141
+
142
+ var has = Object.prototype.hasOwnProperty
143
+ , prefix = '~';
144
+
145
+ /**
146
+ * Constructor to create a storage for our `EE` objects.
147
+ * An `Events` instance is a plain object whose properties are event names.
148
+ *
149
+ * @constructor
150
+ * @private
151
+ */
152
+ function Events() {}
153
+
154
+ //
155
+ // We try to not inherit from `Object.prototype`. In some engines creating an
156
+ // instance in this way is faster than calling `Object.create(null)` directly.
157
+ // If `Object.create(null)` is not supported we prefix the event names with a
158
+ // character to make sure that the built-in object properties are not
159
+ // overridden or used as an attack vector.
160
+ //
161
+ if (Object.create) {
162
+ Events.prototype = Object.create(null);
163
+
164
+ //
165
+ // This hack is needed because the `__proto__` property is still inherited in
166
+ // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
167
+ //
168
+ if (!new Events().__proto__) prefix = false;
169
+ }
170
+
171
+ /**
172
+ * Representation of a single event listener.
173
+ *
174
+ * @param {Function} fn The listener function.
175
+ * @param {*} context The context to invoke the listener with.
176
+ * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
177
+ * @constructor
178
+ * @private
179
+ */
180
+ function EE(fn, context, once) {
181
+ this.fn = fn;
182
+ this.context = context;
183
+ this.once = once || false;
184
+ }
185
+
186
+ /**
187
+ * Add a listener for a given event.
188
+ *
189
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
190
+ * @param {(String|Symbol)} event The event name.
191
+ * @param {Function} fn The listener function.
192
+ * @param {*} context The context to invoke the listener with.
193
+ * @param {Boolean} once Specify if the listener is a one-time listener.
194
+ * @returns {EventEmitter}
195
+ * @private
196
+ */
197
+ function addListener(emitter, event, fn, context, once) {
198
+ if (typeof fn !== 'function') {
199
+ throw new TypeError('The listener must be a function');
200
+ }
201
+
202
+ var listener = new EE(fn, context || emitter, once)
203
+ , evt = prefix ? prefix + event : event;
204
+
205
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
206
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
207
+ else emitter._events[evt] = [emitter._events[evt], listener];
208
+
209
+ return emitter;
210
+ }
211
+
212
+ /**
213
+ * Clear event by name.
214
+ *
215
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
216
+ * @param {(String|Symbol)} evt The Event name.
217
+ * @private
218
+ */
219
+ function clearEvent(emitter, evt) {
220
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
221
+ else delete emitter._events[evt];
222
+ }
223
+
224
+ /**
225
+ * Minimal `EventEmitter` interface that is molded against the Node.js
226
+ * `EventEmitter` interface.
227
+ *
228
+ * @constructor
229
+ * @public
230
+ */
231
+ function EventEmitter() {
232
+ this._events = new Events();
233
+ this._eventsCount = 0;
234
+ }
235
+
236
+ /**
237
+ * Return an array listing the events for which the emitter has registered
238
+ * listeners.
239
+ *
240
+ * @returns {Array}
241
+ * @public
242
+ */
243
+ EventEmitter.prototype.eventNames = function eventNames() {
244
+ var names = []
245
+ , events
246
+ , name;
247
+
248
+ if (this._eventsCount === 0) return names;
249
+
250
+ for (name in (events = this._events)) {
251
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
252
+ }
253
+
254
+ if (Object.getOwnPropertySymbols) {
255
+ return names.concat(Object.getOwnPropertySymbols(events));
256
+ }
257
+
258
+ return names;
259
+ };
260
+
261
+ /**
262
+ * Return the listeners registered for a given event.
263
+ *
264
+ * @param {(String|Symbol)} event The event name.
265
+ * @returns {Array} The registered listeners.
266
+ * @public
267
+ */
268
+ EventEmitter.prototype.listeners = function listeners(event) {
269
+ var evt = prefix ? prefix + event : event
270
+ , handlers = this._events[evt];
271
+
272
+ if (!handlers) return [];
273
+ if (handlers.fn) return [handlers.fn];
274
+
275
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
276
+ ee[i] = handlers[i].fn;
277
+ }
278
+
279
+ return ee;
280
+ };
281
+
282
+ /**
283
+ * Return the number of listeners listening to a given event.
284
+ *
285
+ * @param {(String|Symbol)} event The event name.
286
+ * @returns {Number} The number of listeners.
287
+ * @public
288
+ */
289
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
290
+ var evt = prefix ? prefix + event : event
291
+ , listeners = this._events[evt];
292
+
293
+ if (!listeners) return 0;
294
+ if (listeners.fn) return 1;
295
+ return listeners.length;
296
+ };
297
+
298
+ /**
299
+ * Calls each of the listeners registered for a given event.
300
+ *
301
+ * @param {(String|Symbol)} event The event name.
302
+ * @returns {Boolean} `true` if the event had listeners, else `false`.
303
+ * @public
304
+ */
305
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
306
+ var evt = prefix ? prefix + event : event;
307
+
308
+ if (!this._events[evt]) return false;
309
+
310
+ var listeners = this._events[evt]
311
+ , len = arguments.length
312
+ , args
313
+ , i;
314
+
315
+ if (listeners.fn) {
316
+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
317
+
318
+ switch (len) {
319
+ case 1: return listeners.fn.call(listeners.context), true;
320
+ case 2: return listeners.fn.call(listeners.context, a1), true;
321
+ case 3: return listeners.fn.call(listeners.context, a1, a2), true;
322
+ case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
323
+ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
324
+ case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
325
+ }
326
+
327
+ for (i = 1, args = new Array(len -1); i < len; i++) {
328
+ args[i - 1] = arguments[i];
329
+ }
330
+
331
+ listeners.fn.apply(listeners.context, args);
332
+ } else {
333
+ var length = listeners.length
334
+ , j;
335
+
336
+ for (i = 0; i < length; i++) {
337
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
338
+
339
+ switch (len) {
340
+ case 1: listeners[i].fn.call(listeners[i].context); break;
341
+ case 2: listeners[i].fn.call(listeners[i].context, a1); break;
342
+ case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
343
+ case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
344
+ default:
345
+ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
346
+ args[j - 1] = arguments[j];
347
+ }
348
+
349
+ listeners[i].fn.apply(listeners[i].context, args);
350
+ }
351
+ }
352
+ }
353
+
354
+ return true;
355
+ };
356
+
357
+ /**
358
+ * Add a listener for a given event.
359
+ *
360
+ * @param {(String|Symbol)} event The event name.
361
+ * @param {Function} fn The listener function.
362
+ * @param {*} [context=this] The context to invoke the listener with.
363
+ * @returns {EventEmitter} `this`.
364
+ * @public
365
+ */
366
+ EventEmitter.prototype.on = function on(event, fn, context) {
367
+ return addListener(this, event, fn, context, false);
368
+ };
369
+
370
+ /**
371
+ * Add a one-time listener for a given event.
372
+ *
373
+ * @param {(String|Symbol)} event The event name.
374
+ * @param {Function} fn The listener function.
375
+ * @param {*} [context=this] The context to invoke the listener with.
376
+ * @returns {EventEmitter} `this`.
377
+ * @public
378
+ */
379
+ EventEmitter.prototype.once = function once(event, fn, context) {
380
+ return addListener(this, event, fn, context, true);
381
+ };
382
+
383
+ /**
384
+ * Remove the listeners of a given event.
385
+ *
386
+ * @param {(String|Symbol)} event The event name.
387
+ * @param {Function} fn Only remove the listeners that match this function.
388
+ * @param {*} context Only remove the listeners that have this context.
389
+ * @param {Boolean} once Only remove one-time listeners.
390
+ * @returns {EventEmitter} `this`.
391
+ * @public
392
+ */
393
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
394
+ var evt = prefix ? prefix + event : event;
395
+
396
+ if (!this._events[evt]) return this;
397
+ if (!fn) {
398
+ clearEvent(this, evt);
399
+ return this;
400
+ }
401
+
402
+ var listeners = this._events[evt];
403
+
404
+ if (listeners.fn) {
405
+ if (
406
+ listeners.fn === fn &&
407
+ (!once || listeners.once) &&
408
+ (!context || listeners.context === context)
409
+ ) {
410
+ clearEvent(this, evt);
411
+ }
412
+ } else {
413
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
414
+ if (
415
+ listeners[i].fn !== fn ||
416
+ (once && !listeners[i].once) ||
417
+ (context && listeners[i].context !== context)
418
+ ) {
419
+ events.push(listeners[i]);
420
+ }
421
+ }
422
+
423
+ //
424
+ // Reset the array, or remove it completely if we have no more listeners.
425
+ //
426
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
427
+ else clearEvent(this, evt);
428
+ }
429
+
430
+ return this;
431
+ };
432
+
433
+ /**
434
+ * Remove all listeners, or those of the specified event.
435
+ *
436
+ * @param {(String|Symbol)} [event] The event name.
437
+ * @returns {EventEmitter} `this`.
438
+ * @public
439
+ */
440
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
441
+ var evt;
442
+
443
+ if (event) {
444
+ evt = prefix ? prefix + event : event;
445
+ if (this._events[evt]) clearEvent(this, evt);
446
+ } else {
447
+ this._events = new Events();
448
+ this._eventsCount = 0;
449
+ }
450
+
451
+ return this;
452
+ };
453
+
454
+ //
455
+ // Alias methods names because people roll like that.
456
+ //
457
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
458
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
459
+
460
+ //
461
+ // Expose the prefix.
462
+ //
463
+ EventEmitter.prefixed = prefix;
464
+
465
+ //
466
+ // Allow `EventEmitter` to be imported as module namespace.
467
+ //
468
+ EventEmitter.EventEmitter = EventEmitter;
469
+
470
+ //
471
+ // Expose the module.
472
+ //
473
+ if ('undefined' !== typeof module) {
474
+ module.exports = EventEmitter;
475
+ }
476
+
477
+ },{}],4:[function(_dereq_,module,exports){
478
+ if (typeof Object.create === 'function') {
479
+ // implementation from standard node.js 'util' module
480
+ module.exports = function inherits(ctor, superCtor) {
481
+ if (superCtor) {
482
+ ctor.super_ = superCtor
483
+ ctor.prototype = Object.create(superCtor.prototype, {
484
+ constructor: {
485
+ value: ctor,
486
+ enumerable: false,
487
+ writable: true,
488
+ configurable: true
489
+ }
490
+ })
491
+ }
492
+ };
493
+ } else {
494
+ // old school shim for old browsers
495
+ module.exports = function inherits(ctor, superCtor) {
496
+ if (superCtor) {
497
+ ctor.super_ = superCtor
498
+ var TempCtor = function () {}
499
+ TempCtor.prototype = superCtor.prototype
500
+ ctor.prototype = new TempCtor()
501
+ ctor.prototype.constructor = ctor
502
+ }
503
+ }
504
+ }
505
+
506
+ },{}],5:[function(_dereq_,module,exports){
507
+ 'use strict';
508
+
509
+ var regex = new RegExp('^((?:\\d+)?\\.?\\d+) *('+ [
510
+ 'milliseconds?',
511
+ 'msecs?',
512
+ 'ms',
513
+ 'seconds?',
514
+ 'secs?',
515
+ 's',
516
+ 'minutes?',
517
+ 'mins?',
518
+ 'm',
519
+ 'hours?',
520
+ 'hrs?',
521
+ 'h',
522
+ 'days?',
523
+ 'd',
524
+ 'weeks?',
525
+ 'wks?',
526
+ 'w',
527
+ 'years?',
528
+ 'yrs?',
529
+ 'y'
530
+ ].join('|') +')?$', 'i');
531
+
532
+ var second = 1000
533
+ , minute = second * 60
534
+ , hour = minute * 60
535
+ , day = hour * 24
536
+ , week = day * 7
537
+ , year = day * 365;
538
+
539
+ /**
540
+ * Parse a time string and return the number value of it.
541
+ *
542
+ * @param {String} ms Time string.
543
+ * @returns {Number}
544
+ * @api private
545
+ */
546
+ module.exports = function millisecond(ms) {
547
+ var type = typeof ms
548
+ , amount
549
+ , match;
550
+
551
+ if ('number' === type) return ms;
552
+ else if ('string' !== type || '0' === ms || !ms) return 0;
553
+ else if (+ms) return +ms;
554
+
555
+ //
556
+ // We are vulnerable to the regular expression denial of service (ReDoS).
557
+ // In order to mitigate this we don't parse the input string if it is too long.
558
+ // See https://nodesecurity.io/advisories/46.
559
+ //
560
+ if (ms.length > 10000 || !(match = regex.exec(ms))) return 0;
561
+
562
+ amount = parseFloat(match[1]);
563
+
564
+ switch (match[2].toLowerCase()) {
565
+ case 'years':
566
+ case 'year':
567
+ case 'yrs':
568
+ case 'yr':
569
+ case 'y':
570
+ return amount * year;
571
+
572
+ case 'weeks':
573
+ case 'week':
574
+ case 'wks':
575
+ case 'wk':
576
+ case 'w':
577
+ return amount * week;
578
+
579
+ case 'days':
580
+ case 'day':
581
+ case 'd':
582
+ return amount * day;
583
+
584
+ case 'hours':
585
+ case 'hour':
586
+ case 'hrs':
587
+ case 'hr':
588
+ case 'h':
589
+ return amount * hour;
590
+
591
+ case 'minutes':
592
+ case 'minute':
593
+ case 'mins':
594
+ case 'min':
595
+ case 'm':
596
+ return amount * minute;
597
+
598
+ case 'seconds':
599
+ case 'second':
600
+ case 'secs':
601
+ case 'sec':
602
+ case 's':
603
+ return amount * second;
604
+
605
+ default:
606
+ return amount;
607
+ }
608
+ };
609
+
610
+ },{}],6:[function(_dereq_,module,exports){
611
+ 'use strict';
612
+
613
+ /**
614
+ * Wrap callbacks to prevent double execution.
615
+ *
616
+ * @param {Function} fn Function that should only be called once.
617
+ * @returns {Function} A wrapped callback which prevents execution.
618
+ * @api public
619
+ */
620
+ module.exports = function one(fn) {
621
+ var called = 0
622
+ , value;
623
+
624
+ /**
625
+ * The function that prevents double execution.
626
+ *
627
+ * @api private
628
+ */
629
+ function onetime() {
630
+ if (called) return value;
631
+
632
+ called = 1;
633
+ value = fn.apply(this, arguments);
634
+ fn = null;
635
+
636
+ return value;
637
+ }
638
+
639
+ //
640
+ // To make debugging more easy we want to use the name of the supplied
641
+ // function. So when you look at the functions that are assigned to event
642
+ // listeners you don't see a load of `onetime` functions but actually the
643
+ // names of the functions that this module will call.
644
+ //
645
+ onetime.displayName = fn.displayName || fn.name || onetime.displayName || onetime.name;
646
+ return onetime;
647
+ };
648
+
649
+ },{}],7:[function(_dereq_,module,exports){
650
+ // shim for using process in browser
651
+ var process = module.exports = {};
652
+
653
+ // cached from whatever global is present so that test runners that stub it
654
+ // don't break things. But we need to wrap it in a try catch in case it is
655
+ // wrapped in strict mode code which doesn't define any globals. It's inside a
656
+ // function because try/catches deoptimize in certain engines.
657
+
658
+ var cachedSetTimeout;
659
+ var cachedClearTimeout;
660
+
661
+ function defaultSetTimout() {
662
+ throw new Error('setTimeout has not been defined');
663
+ }
664
+ function defaultClearTimeout () {
665
+ throw new Error('clearTimeout has not been defined');
666
+ }
667
+ (function () {
668
+ try {
669
+ if (typeof setTimeout === 'function') {
670
+ cachedSetTimeout = setTimeout;
671
+ } else {
672
+ cachedSetTimeout = defaultSetTimout;
673
+ }
674
+ } catch (e) {
675
+ cachedSetTimeout = defaultSetTimout;
676
+ }
677
+ try {
678
+ if (typeof clearTimeout === 'function') {
679
+ cachedClearTimeout = clearTimeout;
680
+ } else {
681
+ cachedClearTimeout = defaultClearTimeout;
682
+ }
683
+ } catch (e) {
684
+ cachedClearTimeout = defaultClearTimeout;
685
+ }
686
+ } ())
687
+ function runTimeout(fun) {
688
+ if (cachedSetTimeout === setTimeout) {
689
+ //normal enviroments in sane situations
690
+ return setTimeout(fun, 0);
691
+ }
692
+ // if setTimeout wasn't available but was latter defined
693
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
694
+ cachedSetTimeout = setTimeout;
695
+ return setTimeout(fun, 0);
696
+ }
697
+ try {
698
+ // when when somebody has screwed with setTimeout but no I.E. maddness
699
+ return cachedSetTimeout(fun, 0);
700
+ } catch(e){
701
+ try {
702
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
703
+ return cachedSetTimeout.call(null, fun, 0);
704
+ } catch(e){
705
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
706
+ return cachedSetTimeout.call(this, fun, 0);
707
+ }
708
+ }
709
+
710
+
711
+ }
712
+ function runClearTimeout(marker) {
713
+ if (cachedClearTimeout === clearTimeout) {
714
+ //normal enviroments in sane situations
715
+ return clearTimeout(marker);
716
+ }
717
+ // if clearTimeout wasn't available but was latter defined
718
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
719
+ cachedClearTimeout = clearTimeout;
720
+ return clearTimeout(marker);
721
+ }
722
+ try {
723
+ // when when somebody has screwed with setTimeout but no I.E. maddness
724
+ return cachedClearTimeout(marker);
725
+ } catch (e){
726
+ try {
727
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
728
+ return cachedClearTimeout.call(null, marker);
729
+ } catch (e){
730
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
731
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
732
+ return cachedClearTimeout.call(this, marker);
733
+ }
734
+ }
735
+
736
+
737
+
738
+ }
739
+ var queue = [];
740
+ var draining = false;
741
+ var currentQueue;
742
+ var queueIndex = -1;
743
+
744
+ function cleanUpNextTick() {
745
+ if (!draining || !currentQueue) {
746
+ return;
747
+ }
748
+ draining = false;
749
+ if (currentQueue.length) {
750
+ queue = currentQueue.concat(queue);
751
+ } else {
752
+ queueIndex = -1;
753
+ }
754
+ if (queue.length) {
755
+ drainQueue();
756
+ }
757
+ }
758
+
759
+ function drainQueue() {
760
+ if (draining) {
761
+ return;
762
+ }
763
+ var timeout = runTimeout(cleanUpNextTick);
764
+ draining = true;
765
+
766
+ var len = queue.length;
767
+ while(len) {
768
+ currentQueue = queue;
769
+ queue = [];
770
+ while (++queueIndex < len) {
771
+ if (currentQueue) {
772
+ currentQueue[queueIndex].run();
773
+ }
774
+ }
775
+ queueIndex = -1;
776
+ len = queue.length;
777
+ }
778
+ currentQueue = null;
779
+ draining = false;
780
+ runClearTimeout(timeout);
781
+ }
782
+
783
+ process.nextTick = function (fun) {
784
+ var args = new Array(arguments.length - 1);
785
+ if (arguments.length > 1) {
786
+ for (var i = 1; i < arguments.length; i++) {
787
+ args[i - 1] = arguments[i];
788
+ }
789
+ }
790
+ queue.push(new Item(fun, args));
791
+ if (queue.length === 1 && !draining) {
792
+ runTimeout(drainQueue);
793
+ }
794
+ };
795
+
796
+ // v8 likes predictible objects
797
+ function Item(fun, array) {
798
+ this.fun = fun;
799
+ this.array = array;
800
+ }
801
+ Item.prototype.run = function () {
802
+ this.fun.apply(null, this.array);
803
+ };
804
+ process.title = 'browser';
805
+ process.browser = true;
806
+ process.env = {};
807
+ process.argv = [];
808
+ process.version = ''; // empty string to avoid regexp issues
809
+ process.versions = {};
810
+
811
+ function noop() {}
812
+
813
+ process.on = noop;
814
+ process.addListener = noop;
815
+ process.once = noop;
816
+ process.off = noop;
817
+ process.removeListener = noop;
818
+ process.removeAllListeners = noop;
819
+ process.emit = noop;
820
+ process.prependListener = noop;
821
+ process.prependOnceListener = noop;
822
+
823
+ process.listeners = function (name) { return [] }
824
+
825
+ process.binding = function (name) {
826
+ throw new Error('process.binding is not supported');
827
+ };
828
+
829
+ process.cwd = function () { return '/' };
830
+ process.chdir = function (dir) {
831
+ throw new Error('process.chdir is not supported');
832
+ };
833
+ process.umask = function() { return 0; };
834
+
835
+ },{}],8:[function(_dereq_,module,exports){
836
+ 'use strict';
837
+
838
+ var has = Object.prototype.hasOwnProperty
839
+ , undef;
840
+
841
+ /**
842
+ * Decode a URI encoded string.
843
+ *
844
+ * @param {String} input The URI encoded string.
845
+ * @returns {String|Null} The decoded string.
846
+ * @api private
847
+ */
848
+ function decode(input) {
849
+ try {
850
+ return decodeURIComponent(input.replace(/\+/g, ' '));
851
+ } catch (e) {
852
+ return null;
853
+ }
854
+ }
855
+
856
+ /**
857
+ * Attempts to encode a given input.
858
+ *
859
+ * @param {String} input The string that needs to be encoded.
860
+ * @returns {String|Null} The encoded string.
861
+ * @api private
862
+ */
863
+ function encode(input) {
864
+ try {
865
+ return encodeURIComponent(input);
866
+ } catch (e) {
867
+ return null;
868
+ }
869
+ }
870
+
871
+ /**
872
+ * Simple query string parser.
873
+ *
874
+ * @param {String} query The query string that needs to be parsed.
875
+ * @returns {Object}
876
+ * @api public
877
+ */
878
+ function querystring(query) {
879
+ var parser = /([^=?#&]+)=?([^&]*)/g
880
+ , result = {}
881
+ , part;
882
+
883
+ while (part = parser.exec(query)) {
884
+ var key = decode(part[1])
885
+ , value = decode(part[2]);
886
+
887
+ //
888
+ // Prevent overriding of existing properties. This ensures that build-in
889
+ // methods like `toString` or __proto__ are not overriden by malicious
890
+ // querystrings.
891
+ //
892
+ // In the case if failed decoding, we want to omit the key/value pairs
893
+ // from the result.
894
+ //
895
+ if (key === null || value === null || key in result) continue;
896
+ result[key] = value;
897
+ }
898
+
899
+ return result;
900
+ }
901
+
902
+ /**
903
+ * Transform a query string to an object.
904
+ *
905
+ * @param {Object} obj Object that should be transformed.
906
+ * @param {String} prefix Optional prefix.
907
+ * @returns {String}
908
+ * @api public
909
+ */
910
+ function querystringify(obj, prefix) {
911
+ prefix = prefix || '';
912
+
913
+ var pairs = []
914
+ , value
915
+ , key;
916
+
917
+ //
918
+ // Optionally prefix with a '?' if needed
919
+ //
920
+ if ('string' !== typeof prefix) prefix = '?';
921
+
922
+ for (key in obj) {
923
+ if (has.call(obj, key)) {
924
+ value = obj[key];
925
+
926
+ //
927
+ // Edge cases where we actually want to encode the value to an empty
928
+ // string instead of the stringified value.
929
+ //
930
+ if (!value && (value === null || value === undef || isNaN(value))) {
931
+ value = '';
932
+ }
933
+
934
+ key = encode(key);
935
+ value = encode(value);
936
+
937
+ //
938
+ // If we failed to encode the strings, we should bail out as we don't
939
+ // want to add invalid strings to the query.
940
+ //
941
+ if (key === null || value === null) continue;
942
+ pairs.push(key +'='+ value);
943
+ }
944
+ }
945
+
946
+ return pairs.length ? prefix + pairs.join('&') : '';
947
+ }
948
+
949
+ //
950
+ // Expose the module.
951
+ //
952
+ exports.stringify = querystringify;
953
+ exports.parse = querystring;
954
+
955
+ },{}],9:[function(_dereq_,module,exports){
956
+ 'use strict';
957
+
958
+ var EventEmitter = _dereq_('eventemitter3')
959
+ , millisecond = _dereq_('millisecond')
960
+ , destroy = _dereq_('demolish')
961
+ , Tick = _dereq_('tick-tock')
962
+ , one = _dereq_('one-time');
963
+
964
+ /**
965
+ * Returns sane defaults about a given value.
966
+ *
967
+ * @param {String} name Name of property we want.
968
+ * @param {Recovery} selfie Recovery instance that got created.
969
+ * @param {Object} opts User supplied options we want to check.
970
+ * @returns {Number} Some default value.
971
+ * @api private
972
+ */
973
+ function defaults(name, selfie, opts) {
974
+ return millisecond(
975
+ name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
976
+ );
977
+ }
978
+
979
+ /**
980
+ * Attempt to recover your connection with reconnection attempt.
981
+ *
982
+ * @constructor
983
+ * @param {Object} options Configuration
984
+ * @api public
985
+ */
986
+ function Recovery(options) {
987
+ var recovery = this;
988
+
989
+ if (!(recovery instanceof Recovery)) return new Recovery(options);
990
+
991
+ options = options || {};
992
+
993
+ recovery.attempt = null; // Stores the current reconnect attempt.
994
+ recovery._fn = null; // Stores the callback.
995
+
996
+ recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
997
+ recovery.retries = defaults('retries', recovery, options);
998
+ recovery.factor = defaults('factor', recovery, options);
999
+ recovery.max = defaults('max', recovery, options);
1000
+ recovery.min = defaults('min', recovery, options);
1001
+ recovery.timers = new Tick(recovery);
1002
+ }
1003
+
1004
+ Recovery.prototype = new EventEmitter();
1005
+ Recovery.prototype.constructor = Recovery;
1006
+
1007
+ Recovery['reconnect timeout'] = '30 seconds'; // Maximum time to wait for an answer.
1008
+ Recovery.max = Infinity; // Maximum delay.
1009
+ Recovery.min = '500 ms'; // Minimum delay.
1010
+ Recovery.retries = 10; // Maximum amount of retries.
1011
+ Recovery.factor = 2; // Exponential back off factor.
1012
+
1013
+ /**
1014
+ * Start a new reconnect procedure.
1015
+ *
1016
+ * @returns {Recovery}
1017
+ * @api public
1018
+ */
1019
+ Recovery.prototype.reconnect = function reconnect() {
1020
+ var recovery = this;
1021
+
1022
+ return recovery.backoff(function backedoff(err, opts) {
1023
+ opts.duration = (+new Date()) - opts.start;
1024
+
1025
+ if (err) return recovery.emit('reconnect failed', err, opts);
1026
+
1027
+ recovery.emit('reconnected', opts);
1028
+ }, recovery.attempt);
1029
+ };
1030
+
1031
+ /**
1032
+ * Exponential back off algorithm for retry operations. It uses a randomized
1033
+ * retry so we don't DDOS our server when it goes down under pressure.
1034
+ *
1035
+ * @param {Function} fn Callback to be called after the timeout.
1036
+ * @param {Object} opts Options for configuring the timeout.
1037
+ * @returns {Recovery}
1038
+ * @api private
1039
+ */
1040
+ Recovery.prototype.backoff = function backoff(fn, opts) {
1041
+ var recovery = this;
1042
+
1043
+ opts = opts || recovery.attempt || {};
1044
+
1045
+ //
1046
+ // Bailout when we already have a back off process running. We shouldn't call
1047
+ // the callback then.
1048
+ //
1049
+ if (opts.backoff) return recovery;
1050
+
1051
+ opts['reconnect timeout'] = defaults('reconnect timeout', recovery, opts);
1052
+ opts.retries = defaults('retries', recovery, opts);
1053
+ opts.factor = defaults('factor', recovery, opts);
1054
+ opts.max = defaults('max', recovery, opts);
1055
+ opts.min = defaults('min', recovery, opts);
1056
+
1057
+ opts.start = +opts.start || +new Date();
1058
+ opts.duration = +opts.duration || 0;
1059
+ opts.attempt = +opts.attempt || 0;
1060
+
1061
+ //
1062
+ // Bailout if we are about to make too much attempts.
1063
+ //
1064
+ if (opts.attempt === opts.retries) {
1065
+ fn.call(recovery, new Error('Unable to recover'), opts);
1066
+ return recovery;
1067
+ }
1068
+
1069
+ //
1070
+ // Prevent duplicate back off attempts using the same options object and
1071
+ // increment our attempt as we're about to have another go at this thing.
1072
+ //
1073
+ opts.backoff = true;
1074
+ opts.attempt++;
1075
+
1076
+ recovery.attempt = opts;
1077
+
1078
+ //
1079
+ // Calculate the timeout, but make it randomly so we don't retry connections
1080
+ // at the same interval and defeat the purpose. This exponential back off is
1081
+ // based on the work of:
1082
+ //
1083
+ // http://dthain.blogspot.nl/2009/02/exponential-backoff-in-distributed.html
1084
+ //
1085
+ opts.scheduled = opts.attempt !== 1
1086
+ ? Math.min(Math.round(
1087
+ (Math.random() + 1) * opts.min * Math.pow(opts.factor, opts.attempt - 1)
1088
+ ), opts.max)
1089
+ : opts.min;
1090
+
1091
+ recovery.timers.setTimeout('reconnect', function delay() {
1092
+ opts.duration = (+new Date()) - opts.start;
1093
+ opts.backoff = false;
1094
+ recovery.timers.clear('reconnect, timeout');
1095
+
1096
+ //
1097
+ // Create a `one` function which can only be called once. So we can use the
1098
+ // same function for different types of invocations to create a much better
1099
+ // and usable API.
1100
+ //
1101
+ var connect = recovery._fn = one(function connect(err) {
1102
+ recovery.reset();
1103
+
1104
+ if (err) return recovery.backoff(fn, opts);
1105
+
1106
+ fn.call(recovery, undefined, opts);
1107
+ });
1108
+
1109
+ recovery.emit('reconnect', opts, connect);
1110
+ recovery.timers.setTimeout('timeout', function timeout() {
1111
+ var err = new Error('Failed to reconnect in a timely manner');
1112
+ opts.duration = (+new Date()) - opts.start;
1113
+
1114
+ recovery.emit('reconnect timeout', err, opts);
1115
+ connect(err);
1116
+ }, opts['reconnect timeout']);
1117
+ }, opts.scheduled);
1118
+
1119
+ //
1120
+ // Emit a `reconnecting` event with current reconnect options. This allows
1121
+ // them to update the UI and provide their users with feedback.
1122
+ //
1123
+ recovery.emit('reconnect scheduled', opts);
1124
+
1125
+ return recovery;
1126
+ };
1127
+
1128
+ /**
1129
+ * Check if the reconnection process is currently reconnecting.
1130
+ *
1131
+ * @returns {Boolean}
1132
+ * @api public
1133
+ */
1134
+ Recovery.prototype.reconnecting = function reconnecting() {
1135
+ return !!this.attempt;
1136
+ };
1137
+
1138
+ /**
1139
+ * Tell our reconnection procedure that we're passed.
1140
+ *
1141
+ * @param {Error} err Reconnection failed.
1142
+ * @returns {Recovery}
1143
+ * @api public
1144
+ */
1145
+ Recovery.prototype.reconnected = function reconnected(err) {
1146
+ if (this._fn) this._fn(err);
1147
+ return this;
1148
+ };
1149
+
1150
+ /**
1151
+ * Reset the reconnection attempt so it can be re-used again.
1152
+ *
1153
+ * @returns {Recovery}
1154
+ * @api public
1155
+ */
1156
+ Recovery.prototype.reset = function reset() {
1157
+ this._fn = this.attempt = null;
1158
+ this.timers.clear('reconnect, timeout');
1159
+
1160
+ return this;
1161
+ };
1162
+
1163
+ /**
1164
+ * Clean up the instance.
1165
+ *
1166
+ * @type {Function}
1167
+ * @returns {Boolean}
1168
+ * @api public
1169
+ */
1170
+ Recovery.prototype.destroy = destroy('timers attempt _fn');
1171
+
1172
+ //
1173
+ // Expose the module.
1174
+ //
1175
+ module.exports = Recovery;
1176
+
1177
+ },{"demolish":1,"eventemitter3":10,"millisecond":5,"one-time":6,"tick-tock":12}],10:[function(_dereq_,module,exports){
1178
+ 'use strict';
1179
+
1180
+ //
1181
+ // We store our EE objects in a plain object whose properties are event names.
1182
+ // If `Object.create(null)` is not supported we prefix the event names with a
1183
+ // `~` to make sure that the built-in object properties are not overridden or
1184
+ // used as an attack vector.
1185
+ // We also assume that `Object.create(null)` is available when the event name
1186
+ // is an ES6 Symbol.
1187
+ //
1188
+ var prefix = typeof Object.create !== 'function' ? '~' : false;
1189
+
1190
+ /**
1191
+ * Representation of a single EventEmitter function.
1192
+ *
1193
+ * @param {Function} fn Event handler to be called.
1194
+ * @param {Mixed} context Context for function execution.
1195
+ * @param {Boolean} once Only emit once
1196
+ * @api private
1197
+ */
1198
+ function EE(fn, context, once) {
1199
+ this.fn = fn;
1200
+ this.context = context;
1201
+ this.once = once || false;
1202
+ }
1203
+
1204
+ /**
1205
+ * Minimal EventEmitter interface that is molded against the Node.js
1206
+ * EventEmitter interface.
1207
+ *
1208
+ * @constructor
1209
+ * @api public
1210
+ */
1211
+ function EventEmitter() { /* Nothing to set */ }
1212
+
1213
+ /**
1214
+ * Holds the assigned EventEmitters by name.
1215
+ *
1216
+ * @type {Object}
1217
+ * @private
1218
+ */
1219
+ EventEmitter.prototype._events = undefined;
1220
+
1221
+ /**
1222
+ * Return a list of assigned event listeners.
1223
+ *
1224
+ * @param {String} event The events that should be listed.
1225
+ * @param {Boolean} exists We only need to know if there are listeners.
1226
+ * @returns {Array|Boolean}
1227
+ * @api public
1228
+ */
1229
+ EventEmitter.prototype.listeners = function listeners(event, exists) {
1230
+ var evt = prefix ? prefix + event : event
1231
+ , available = this._events && this._events[evt];
1232
+
1233
+ if (exists) return !!available;
1234
+ if (!available) return [];
1235
+ if (available.fn) return [available.fn];
1236
+
1237
+ for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
1238
+ ee[i] = available[i].fn;
1239
+ }
1240
+
1241
+ return ee;
1242
+ };
1243
+
1244
+ /**
1245
+ * Emit an event to all registered event listeners.
1246
+ *
1247
+ * @param {String} event The name of the event.
1248
+ * @returns {Boolean} Indication if we've emitted an event.
1249
+ * @api public
1250
+ */
1251
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
1252
+ var evt = prefix ? prefix + event : event;
1253
+
1254
+ if (!this._events || !this._events[evt]) return false;
1255
+
1256
+ var listeners = this._events[evt]
1257
+ , len = arguments.length
1258
+ , args
1259
+ , i;
1260
+
1261
+ if ('function' === typeof listeners.fn) {
1262
+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
1263
+
1264
+ switch (len) {
1265
+ case 1: return listeners.fn.call(listeners.context), true;
1266
+ case 2: return listeners.fn.call(listeners.context, a1), true;
1267
+ case 3: return listeners.fn.call(listeners.context, a1, a2), true;
1268
+ case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
1269
+ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
1270
+ case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
1271
+ }
1272
+
1273
+ for (i = 1, args = new Array(len -1); i < len; i++) {
1274
+ args[i - 1] = arguments[i];
1275
+ }
1276
+
1277
+ listeners.fn.apply(listeners.context, args);
1278
+ } else {
1279
+ var length = listeners.length
1280
+ , j;
1281
+
1282
+ for (i = 0; i < length; i++) {
1283
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
1284
+
1285
+ switch (len) {
1286
+ case 1: listeners[i].fn.call(listeners[i].context); break;
1287
+ case 2: listeners[i].fn.call(listeners[i].context, a1); break;
1288
+ case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
1289
+ default:
1290
+ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
1291
+ args[j - 1] = arguments[j];
1292
+ }
1293
+
1294
+ listeners[i].fn.apply(listeners[i].context, args);
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ return true;
1300
+ };
1301
+
1302
+ /**
1303
+ * Register a new EventListener for the given event.
1304
+ *
1305
+ * @param {String} event Name of the event.
1306
+ * @param {Functon} fn Callback function.
1307
+ * @param {Mixed} context The context of the function.
1308
+ * @api public
1309
+ */
1310
+ EventEmitter.prototype.on = function on(event, fn, context) {
1311
+ var listener = new EE(fn, context || this)
1312
+ , evt = prefix ? prefix + event : event;
1313
+
1314
+ if (!this._events) this._events = prefix ? {} : Object.create(null);
1315
+ if (!this._events[evt]) this._events[evt] = listener;
1316
+ else {
1317
+ if (!this._events[evt].fn) this._events[evt].push(listener);
1318
+ else this._events[evt] = [
1319
+ this._events[evt], listener
1320
+ ];
1321
+ }
1322
+
1323
+ return this;
1324
+ };
1325
+
1326
+ /**
1327
+ * Add an EventListener that's only called once.
1328
+ *
1329
+ * @param {String} event Name of the event.
1330
+ * @param {Function} fn Callback function.
1331
+ * @param {Mixed} context The context of the function.
1332
+ * @api public
1333
+ */
1334
+ EventEmitter.prototype.once = function once(event, fn, context) {
1335
+ var listener = new EE(fn, context || this, true)
1336
+ , evt = prefix ? prefix + event : event;
1337
+
1338
+ if (!this._events) this._events = prefix ? {} : Object.create(null);
1339
+ if (!this._events[evt]) this._events[evt] = listener;
1340
+ else {
1341
+ if (!this._events[evt].fn) this._events[evt].push(listener);
1342
+ else this._events[evt] = [
1343
+ this._events[evt], listener
1344
+ ];
1345
+ }
1346
+
1347
+ return this;
1348
+ };
1349
+
1350
+ /**
1351
+ * Remove event listeners.
1352
+ *
1353
+ * @param {String} event The event we want to remove.
1354
+ * @param {Function} fn The listener that we need to find.
1355
+ * @param {Mixed} context Only remove listeners matching this context.
1356
+ * @param {Boolean} once Only remove once listeners.
1357
+ * @api public
1358
+ */
1359
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
1360
+ var evt = prefix ? prefix + event : event;
1361
+
1362
+ if (!this._events || !this._events[evt]) return this;
1363
+
1364
+ var listeners = this._events[evt]
1365
+ , events = [];
1366
+
1367
+ if (fn) {
1368
+ if (listeners.fn) {
1369
+ if (
1370
+ listeners.fn !== fn
1371
+ || (once && !listeners.once)
1372
+ || (context && listeners.context !== context)
1373
+ ) {
1374
+ events.push(listeners);
1375
+ }
1376
+ } else {
1377
+ for (var i = 0, length = listeners.length; i < length; i++) {
1378
+ if (
1379
+ listeners[i].fn !== fn
1380
+ || (once && !listeners[i].once)
1381
+ || (context && listeners[i].context !== context)
1382
+ ) {
1383
+ events.push(listeners[i]);
1384
+ }
1385
+ }
1386
+ }
1387
+ }
1388
+
1389
+ //
1390
+ // Reset the array, or remove it completely if we have no more listeners.
1391
+ //
1392
+ if (events.length) {
1393
+ this._events[evt] = events.length === 1 ? events[0] : events;
1394
+ } else {
1395
+ delete this._events[evt];
1396
+ }
1397
+
1398
+ return this;
1399
+ };
1400
+
1401
+ /**
1402
+ * Remove all listeners or only the listeners for the specified event.
1403
+ *
1404
+ * @param {String} event The event want to remove all listeners for.
1405
+ * @api public
1406
+ */
1407
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
1408
+ if (!this._events) return this;
1409
+
1410
+ if (event) delete this._events[prefix ? prefix + event : event];
1411
+ else this._events = prefix ? {} : Object.create(null);
1412
+
1413
+ return this;
1414
+ };
1415
+
1416
+ //
1417
+ // Alias methods names because people roll like that.
1418
+ //
1419
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
1420
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
1421
+
1422
+ //
1423
+ // This function doesn't apply anymore.
1424
+ //
1425
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
1426
+ return this;
1427
+ };
1428
+
1429
+ //
1430
+ // Expose the prefix.
1431
+ //
1432
+ EventEmitter.prefixed = prefix;
1433
+
1434
+ //
1435
+ // Expose the module.
1436
+ //
1437
+ if ('undefined' !== typeof module) {
1438
+ module.exports = EventEmitter;
1439
+ }
1440
+
1441
+ },{}],11:[function(_dereq_,module,exports){
1442
+ 'use strict';
1443
+
1444
+ /**
1445
+ * Check if we're required to add a port number.
1446
+ *
1447
+ * @see https://url.spec.whatwg.org/#default-port
1448
+ * @param {Number|String} port Port number we need to check
1449
+ * @param {String} protocol Protocol we need to check against.
1450
+ * @returns {Boolean} Is it a default port for the given protocol
1451
+ * @api private
1452
+ */
1453
+ module.exports = function required(port, protocol) {
1454
+ protocol = protocol.split(':')[0];
1455
+ port = +port;
1456
+
1457
+ if (!port) return false;
1458
+
1459
+ switch (protocol) {
1460
+ case 'http':
1461
+ case 'ws':
1462
+ return port !== 80;
1463
+
1464
+ case 'https':
1465
+ case 'wss':
1466
+ return port !== 443;
1467
+
1468
+ case 'ftp':
1469
+ return port !== 21;
1470
+
1471
+ case 'gopher':
1472
+ return port !== 70;
1473
+
1474
+ case 'file':
1475
+ return false;
1476
+ }
1477
+
1478
+ return port !== 0;
1479
+ };
1480
+
1481
+ },{}],12:[function(_dereq_,module,exports){
1482
+ (function (setImmediate,clearImmediate){(function (){
1483
+ 'use strict';
1484
+
1485
+ var has = Object.prototype.hasOwnProperty
1486
+ , ms = _dereq_('millisecond');
1487
+
1488
+ /**
1489
+ * Timer instance.
1490
+ *
1491
+ * @constructor
1492
+ * @param {Object} timer New timer instance.
1493
+ * @param {Function} clear Clears the timer instance.
1494
+ * @param {Function} duration Duration of the timer.
1495
+ * @param {Function} fn The functions that need to be executed.
1496
+ * @api private
1497
+ */
1498
+ function Timer(timer, clear, duration, fn) {
1499
+ this.start = +(new Date());
1500
+ this.duration = duration;
1501
+ this.clear = clear;
1502
+ this.timer = timer;
1503
+ this.fns = [fn];
1504
+ }
1505
+
1506
+ /**
1507
+ * Calculate the time left for a given timer.
1508
+ *
1509
+ * @returns {Number} Time in milliseconds.
1510
+ * @api public
1511
+ */
1512
+ Timer.prototype.remaining = function remaining() {
1513
+ return this.duration - this.taken();
1514
+ };
1515
+
1516
+ /**
1517
+ * Calculate the amount of time it has taken since we've set the timer.
1518
+ *
1519
+ * @returns {Number}
1520
+ * @api public
1521
+ */
1522
+ Timer.prototype.taken = function taken() {
1523
+ return +(new Date()) - this.start;
1524
+ };
1525
+
1526
+ /**
1527
+ * Custom wrappers for the various of clear{whatever} functions. We cannot
1528
+ * invoke them directly as this will cause thrown errors in Google Chrome with
1529
+ * an Illegal Invocation Error
1530
+ *
1531
+ * @see #2
1532
+ * @type {Function}
1533
+ * @api private
1534
+ */
1535
+ function unsetTimeout(id) { clearTimeout(id); }
1536
+ function unsetInterval(id) { clearInterval(id); }
1537
+ function unsetImmediate(id) { clearImmediate(id); }
1538
+
1539
+ /**
1540
+ * Simple timer management.
1541
+ *
1542
+ * @constructor
1543
+ * @param {Mixed} context Context of the callbacks that we execute.
1544
+ * @api public
1545
+ */
1546
+ function Tick(context) {
1547
+ if (!(this instanceof Tick)) return new Tick(context);
1548
+
1549
+ this.timers = {};
1550
+ this.context = context || this;
1551
+ }
1552
+
1553
+ /**
1554
+ * Return a function which will just iterate over all assigned callbacks and
1555
+ * optionally clear the timers from memory if needed.
1556
+ *
1557
+ * @param {String} name Name of the timer we need to execute.
1558
+ * @param {Boolean} clear Also clear from memory.
1559
+ * @returns {Function}
1560
+ * @api private
1561
+ */
1562
+ Tick.prototype.tock = function ticktock(name, clear) {
1563
+ var tock = this;
1564
+
1565
+ return function tickedtock() {
1566
+ if (!(name in tock.timers)) return;
1567
+
1568
+ var timer = tock.timers[name]
1569
+ , fns = timer.fns.slice()
1570
+ , l = fns.length
1571
+ , i = 0;
1572
+
1573
+ if (clear) tock.clear(name);
1574
+ else tock.start = +new Date();
1575
+
1576
+ for (; i < l; i++) {
1577
+ fns[i].call(tock.context);
1578
+ }
1579
+ };
1580
+ };
1581
+
1582
+ /**
1583
+ * Add a new timeout.
1584
+ *
1585
+ * @param {String} name Name of the timer.
1586
+ * @param {Function} fn Completion callback.
1587
+ * @param {Mixed} time Duration of the timer.
1588
+ * @returns {Tick}
1589
+ * @api public
1590
+ */
1591
+ Tick.prototype.setTimeout = function timeout(name, fn, time) {
1592
+ var tick = this
1593
+ , tock;
1594
+
1595
+ if (tick.timers[name]) {
1596
+ tick.timers[name].fns.push(fn);
1597
+ return tick;
1598
+ }
1599
+
1600
+ tock = ms(time);
1601
+ tick.timers[name] = new Timer(
1602
+ setTimeout(tick.tock(name, true), ms(time)),
1603
+ unsetTimeout,
1604
+ tock,
1605
+ fn
1606
+ );
1607
+
1608
+ return tick;
1609
+ };
1610
+
1611
+ /**
1612
+ * Add a new interval.
1613
+ *
1614
+ * @param {String} name Name of the timer.
1615
+ * @param {Function} fn Completion callback.
1616
+ * @param {Mixed} time Interval of the timer.
1617
+ * @returns {Tick}
1618
+ * @api public
1619
+ */
1620
+ Tick.prototype.setInterval = function interval(name, fn, time) {
1621
+ var tick = this
1622
+ , tock;
1623
+
1624
+ if (tick.timers[name]) {
1625
+ tick.timers[name].fns.push(fn);
1626
+ return tick;
1627
+ }
1628
+
1629
+ tock = ms(time);
1630
+ tick.timers[name] = new Timer(
1631
+ setInterval(tick.tock(name), ms(time)),
1632
+ unsetInterval,
1633
+ tock,
1634
+ fn
1635
+ );
1636
+
1637
+ return tick;
1638
+ };
1639
+
1640
+ /**
1641
+ * Add a new setImmediate.
1642
+ *
1643
+ * @param {String} name Name of the timer.
1644
+ * @param {Function} fn Completion callback.
1645
+ * @returns {Tick}
1646
+ * @api public
1647
+ */
1648
+ Tick.prototype.setImmediate = function immediate(name, fn) {
1649
+ var tick = this;
1650
+
1651
+ if ('function' !== typeof setImmediate) return tick.setTimeout(name, fn, 0);
1652
+
1653
+ if (tick.timers[name]) {
1654
+ tick.timers[name].fns.push(fn);
1655
+ return tick;
1656
+ }
1657
+
1658
+ tick.timers[name] = new Timer(
1659
+ setImmediate(tick.tock(name, true)),
1660
+ unsetImmediate,
1661
+ 0,
1662
+ fn
1663
+ );
1664
+
1665
+ return tick;
1666
+ };
1667
+
1668
+ /**
1669
+ * Check if we have a timer set.
1670
+ *
1671
+ * @param {String} name
1672
+ * @returns {Boolean}
1673
+ * @api public
1674
+ */
1675
+ Tick.prototype.active = function active(name) {
1676
+ return name in this.timers;
1677
+ };
1678
+
1679
+ /**
1680
+ * Properly clean up all timeout references. If no arguments are supplied we
1681
+ * will attempt to clear every single timer that is present.
1682
+ *
1683
+ * @param {Arguments} ..args.. The names of the timeouts we need to clear
1684
+ * @returns {Tick}
1685
+ * @api public
1686
+ */
1687
+ Tick.prototype.clear = function clear() {
1688
+ var args = arguments.length ? arguments : []
1689
+ , tick = this
1690
+ , timer, i, l;
1691
+
1692
+ if (args.length === 1 && 'string' === typeof args[0]) {
1693
+ args = args[0].split(/[, ]+/);
1694
+ }
1695
+
1696
+ if (!args.length) {
1697
+ for (timer in tick.timers) {
1698
+ if (has.call(tick.timers, timer)) args.push(timer);
1699
+ }
1700
+ }
1701
+
1702
+ for (i = 0, l = args.length; i < l; i++) {
1703
+ timer = tick.timers[args[i]];
1704
+
1705
+ if (!timer) continue;
1706
+ timer.clear(timer.timer);
1707
+
1708
+ timer.fns = timer.timer = timer.clear = null;
1709
+ delete tick.timers[args[i]];
1710
+ }
1711
+
1712
+ return tick;
1713
+ };
1714
+
1715
+ /**
1716
+ * Adjust a timeout or interval to a new duration.
1717
+ *
1718
+ * @returns {Tick}
1719
+ * @api public
1720
+ */
1721
+ Tick.prototype.adjust = function adjust(name, time) {
1722
+ var interval
1723
+ , tick = this
1724
+ , tock = ms(time)
1725
+ , timer = tick.timers[name];
1726
+
1727
+ if (!timer) return tick;
1728
+
1729
+ interval = timer.clear === unsetInterval;
1730
+ timer.clear(timer.timer);
1731
+ timer.start = +(new Date());
1732
+ timer.duration = tock;
1733
+ timer.timer = (interval ? setInterval : setTimeout)(tick.tock(name, !interval), tock);
1734
+
1735
+ return tick;
1736
+ };
1737
+
1738
+ /**
1739
+ * We will no longer use this module, prepare your self for global cleanups.
1740
+ *
1741
+ * @returns {Boolean}
1742
+ * @api public
1743
+ */
1744
+ Tick.prototype.end = Tick.prototype.destroy = function end() {
1745
+ if (!this.context) return false;
1746
+
1747
+ this.clear();
1748
+ this.context = this.timers = null;
1749
+
1750
+ return true;
1751
+ };
1752
+
1753
+ //
1754
+ // Expose the timer factory.
1755
+ //
1756
+ Tick.Timer = Timer;
1757
+ module.exports = Tick;
1758
+
1759
+ }).call(this)}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
1760
+ },{"millisecond":5,"timers":13}],13:[function(_dereq_,module,exports){
1761
+ (function (setImmediate,clearImmediate){(function (){
1762
+ var nextTick = _dereq_('process/browser.js').nextTick;
1763
+ var apply = Function.prototype.apply;
1764
+ var slice = Array.prototype.slice;
1765
+ var immediateIds = {};
1766
+ var nextImmediateId = 0;
1767
+
1768
+ // DOM APIs, for completeness
1769
+
1770
+ exports.setTimeout = function() {
1771
+ return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
1772
+ };
1773
+ exports.setInterval = function() {
1774
+ return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
1775
+ };
1776
+ exports.clearTimeout =
1777
+ exports.clearInterval = function(timeout) { timeout.close(); };
1778
+
1779
+ function Timeout(id, clearFn) {
1780
+ this._id = id;
1781
+ this._clearFn = clearFn;
1782
+ }
1783
+ Timeout.prototype.unref = Timeout.prototype.ref = function() {};
1784
+ Timeout.prototype.close = function() {
1785
+ this._clearFn.call(window, this._id);
1786
+ };
1787
+
1788
+ // Does not start the time, just sets up the members needed.
1789
+ exports.enroll = function(item, msecs) {
1790
+ clearTimeout(item._idleTimeoutId);
1791
+ item._idleTimeout = msecs;
1792
+ };
1793
+
1794
+ exports.unenroll = function(item) {
1795
+ clearTimeout(item._idleTimeoutId);
1796
+ item._idleTimeout = -1;
1797
+ };
1798
+
1799
+ exports._unrefActive = exports.active = function(item) {
1800
+ clearTimeout(item._idleTimeoutId);
1801
+
1802
+ var msecs = item._idleTimeout;
1803
+ if (msecs >= 0) {
1804
+ item._idleTimeoutId = setTimeout(function onTimeout() {
1805
+ if (item._onTimeout)
1806
+ item._onTimeout();
1807
+ }, msecs);
1808
+ }
1809
+ };
1810
+
1811
+ // That's not how node.js implements it but the exposed api is the same.
1812
+ exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
1813
+ var id = nextImmediateId++;
1814
+ var args = arguments.length < 2 ? false : slice.call(arguments, 1);
1815
+
1816
+ immediateIds[id] = true;
1817
+
1818
+ nextTick(function onNextTick() {
1819
+ if (immediateIds[id]) {
1820
+ // fn.call() is faster so we optimize for the common use-case
1821
+ // @see http://jsperf.com/call-apply-segu
1822
+ if (args) {
1823
+ fn.apply(null, args);
1824
+ } else {
1825
+ fn.call(null);
1826
+ }
1827
+ // Prevent ids from leaking
1828
+ exports.clearImmediate(id);
1829
+ }
1830
+ });
1831
+
1832
+ return id;
1833
+ };
1834
+
1835
+ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
1836
+ delete immediateIds[id];
1837
+ };
1838
+ }).call(this)}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
1839
+ },{"process/browser.js":7,"timers":13}],14:[function(_dereq_,module,exports){
1840
+ (function (global){(function (){
1841
+ 'use strict';
1842
+
1843
+ var required = _dereq_('requires-port')
1844
+ , qs = _dereq_('querystringify')
1845
+ , controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
1846
+ , CRHTLF = /[\n\r\t]/g
1847
+ , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
1848
+ , port = /:\d+$/
1849
+ , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
1850
+ , windowsDriveLetter = /^[a-zA-Z]:/;
1851
+
1852
+ /**
1853
+ * Remove control characters and whitespace from the beginning of a string.
1854
+ *
1855
+ * @param {Object|String} str String to trim.
1856
+ * @returns {String} A new string representing `str` stripped of control
1857
+ * characters and whitespace from its beginning.
1858
+ * @public
1859
+ */
1860
+ function trimLeft(str) {
1861
+ return (str ? str : '').toString().replace(controlOrWhitespace, '');
1862
+ }
1863
+
1864
+ /**
1865
+ * These are the parse rules for the URL parser, it informs the parser
1866
+ * about:
1867
+ *
1868
+ * 0. The char it Needs to parse, if it's a string it should be done using
1869
+ * indexOf, RegExp using exec and NaN means set as current value.
1870
+ * 1. The property we should set when parsing this value.
1871
+ * 2. Indication if it's backwards or forward parsing, when set as number it's
1872
+ * the value of extra chars that should be split off.
1873
+ * 3. Inherit from location if non existing in the parser.
1874
+ * 4. `toLowerCase` the resulting value.
1875
+ */
1876
+ var rules = [
1877
+ ['#', 'hash'], // Extract from the back.
1878
+ ['?', 'query'], // Extract from the back.
1879
+ function sanitize(address, url) { // Sanitize what is left of the address
1880
+ return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address;
1881
+ },
1882
+ ['/', 'pathname'], // Extract from the back.
1883
+ ['@', 'auth', 1], // Extract from the front.
1884
+ [NaN, 'host', undefined, 1, 1], // Set left over value.
1885
+ [/:(\d*)$/, 'port', undefined, 1], // RegExp the back.
1886
+ [NaN, 'hostname', undefined, 1, 1] // Set left over.
1887
+ ];
1888
+
1889
+ /**
1890
+ * These properties should not be copied or inherited from. This is only needed
1891
+ * for all non blob URL's as a blob URL does not include a hash, only the
1892
+ * origin.
1893
+ *
1894
+ * @type {Object}
1895
+ * @private
1896
+ */
1897
+ var ignore = { hash: 1, query: 1 };
1898
+
1899
+ /**
1900
+ * The location object differs when your code is loaded through a normal page,
1901
+ * Worker or through a worker using a blob. And with the blobble begins the
1902
+ * trouble as the location object will contain the URL of the blob, not the
1903
+ * location of the page where our code is loaded in. The actual origin is
1904
+ * encoded in the `pathname` so we can thankfully generate a good "default"
1905
+ * location from it so we can generate proper relative URL's again.
1906
+ *
1907
+ * @param {Object|String} loc Optional default location object.
1908
+ * @returns {Object} lolcation object.
1909
+ * @public
1910
+ */
1911
+ function lolcation(loc) {
1912
+ var globalVar;
1913
+
1914
+ if (typeof window !== 'undefined') globalVar = window;
1915
+ else if (typeof global !== 'undefined') globalVar = global;
1916
+ else if (typeof self !== 'undefined') globalVar = self;
1917
+ else globalVar = {};
1918
+
1919
+ var location = globalVar.location || {};
1920
+ loc = loc || location;
1921
+
1922
+ var finaldestination = {}
1923
+ , type = typeof loc
1924
+ , key;
1925
+
1926
+ if ('blob:' === loc.protocol) {
1927
+ finaldestination = new Url(unescape(loc.pathname), {});
1928
+ } else if ('string' === type) {
1929
+ finaldestination = new Url(loc, {});
1930
+ for (key in ignore) delete finaldestination[key];
1931
+ } else if ('object' === type) {
1932
+ for (key in loc) {
1933
+ if (key in ignore) continue;
1934
+ finaldestination[key] = loc[key];
1935
+ }
1936
+
1937
+ if (finaldestination.slashes === undefined) {
1938
+ finaldestination.slashes = slashes.test(loc.href);
1939
+ }
1940
+ }
1941
+
1942
+ return finaldestination;
1943
+ }
1944
+
1945
+ /**
1946
+ * Check whether a protocol scheme is special.
1947
+ *
1948
+ * @param {String} The protocol scheme of the URL
1949
+ * @return {Boolean} `true` if the protocol scheme is special, else `false`
1950
+ * @private
1951
+ */
1952
+ function isSpecial(scheme) {
1953
+ return (
1954
+ scheme === 'file:' ||
1955
+ scheme === 'ftp:' ||
1956
+ scheme === 'http:' ||
1957
+ scheme === 'https:' ||
1958
+ scheme === 'ws:' ||
1959
+ scheme === 'wss:'
1960
+ );
1961
+ }
1962
+
1963
+ /**
1964
+ * @typedef ProtocolExtract
1965
+ * @type Object
1966
+ * @property {String} protocol Protocol matched in the URL, in lowercase.
1967
+ * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
1968
+ * @property {String} rest Rest of the URL that is not part of the protocol.
1969
+ */
1970
+
1971
+ /**
1972
+ * Extract protocol information from a URL with/without double slash ("//").
1973
+ *
1974
+ * @param {String} address URL we want to extract from.
1975
+ * @param {Object} location
1976
+ * @return {ProtocolExtract} Extracted information.
1977
+ * @private
1978
+ */
1979
+ function extractProtocol(address, location) {
1980
+ address = trimLeft(address);
1981
+ address = address.replace(CRHTLF, '');
1982
+ location = location || {};
1983
+
1984
+ var match = protocolre.exec(address);
1985
+ var protocol = match[1] ? match[1].toLowerCase() : '';
1986
+ var forwardSlashes = !!match[2];
1987
+ var otherSlashes = !!match[3];
1988
+ var slashesCount = 0;
1989
+ var rest;
1990
+
1991
+ if (forwardSlashes) {
1992
+ if (otherSlashes) {
1993
+ rest = match[2] + match[3] + match[4];
1994
+ slashesCount = match[2].length + match[3].length;
1995
+ } else {
1996
+ rest = match[2] + match[4];
1997
+ slashesCount = match[2].length;
1998
+ }
1999
+ } else {
2000
+ if (otherSlashes) {
2001
+ rest = match[3] + match[4];
2002
+ slashesCount = match[3].length;
2003
+ } else {
2004
+ rest = match[4]
2005
+ }
2006
+ }
2007
+
2008
+ if (protocol === 'file:') {
2009
+ if (slashesCount >= 2) {
2010
+ rest = rest.slice(2);
2011
+ }
2012
+ } else if (isSpecial(protocol)) {
2013
+ rest = match[4];
2014
+ } else if (protocol) {
2015
+ if (forwardSlashes) {
2016
+ rest = rest.slice(2);
2017
+ }
2018
+ } else if (slashesCount >= 2 && isSpecial(location.protocol)) {
2019
+ rest = match[4];
2020
+ }
2021
+
2022
+ return {
2023
+ protocol: protocol,
2024
+ slashes: forwardSlashes || isSpecial(protocol),
2025
+ slashesCount: slashesCount,
2026
+ rest: rest
2027
+ };
2028
+ }
2029
+
2030
+ /**
2031
+ * Resolve a relative URL pathname against a base URL pathname.
2032
+ *
2033
+ * @param {String} relative Pathname of the relative URL.
2034
+ * @param {String} base Pathname of the base URL.
2035
+ * @return {String} Resolved pathname.
2036
+ * @private
2037
+ */
2038
+ function resolve(relative, base) {
2039
+ if (relative === '') return base;
2040
+
2041
+ var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
2042
+ , i = path.length
2043
+ , last = path[i - 1]
2044
+ , unshift = false
2045
+ , up = 0;
2046
+
2047
+ while (i--) {
2048
+ if (path[i] === '.') {
2049
+ path.splice(i, 1);
2050
+ } else if (path[i] === '..') {
2051
+ path.splice(i, 1);
2052
+ up++;
2053
+ } else if (up) {
2054
+ if (i === 0) unshift = true;
2055
+ path.splice(i, 1);
2056
+ up--;
2057
+ }
2058
+ }
2059
+
2060
+ if (unshift) path.unshift('');
2061
+ if (last === '.' || last === '..') path.push('');
2062
+
2063
+ return path.join('/');
2064
+ }
2065
+
2066
+ /**
2067
+ * The actual URL instance. Instead of returning an object we've opted-in to
2068
+ * create an actual constructor as it's much more memory efficient and
2069
+ * faster and it pleases my OCD.
2070
+ *
2071
+ * It is worth noting that we should not use `URL` as class name to prevent
2072
+ * clashes with the global URL instance that got introduced in browsers.
2073
+ *
2074
+ * @constructor
2075
+ * @param {String} address URL we want to parse.
2076
+ * @param {Object|String} [location] Location defaults for relative paths.
2077
+ * @param {Boolean|Function} [parser] Parser for the query string.
2078
+ * @private
2079
+ */
2080
+ function Url(address, location, parser) {
2081
+ address = trimLeft(address);
2082
+ address = address.replace(CRHTLF, '');
2083
+
2084
+ if (!(this instanceof Url)) {
2085
+ return new Url(address, location, parser);
2086
+ }
2087
+
2088
+ var relative, extracted, parse, instruction, index, key
2089
+ , instructions = rules.slice()
2090
+ , type = typeof location
2091
+ , url = this
2092
+ , i = 0;
2093
+
2094
+ //
2095
+ // The following if statements allows this module two have compatibility with
2096
+ // 2 different API:
2097
+ //
2098
+ // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
2099
+ // where the boolean indicates that the query string should also be parsed.
2100
+ //
2101
+ // 2. The `URL` interface of the browser which accepts a URL, object as
2102
+ // arguments. The supplied object will be used as default values / fall-back
2103
+ // for relative paths.
2104
+ //
2105
+ if ('object' !== type && 'string' !== type) {
2106
+ parser = location;
2107
+ location = null;
2108
+ }
2109
+
2110
+ if (parser && 'function' !== typeof parser) parser = qs.parse;
2111
+
2112
+ location = lolcation(location);
2113
+
2114
+ //
2115
+ // Extract protocol information before running the instructions.
2116
+ //
2117
+ extracted = extractProtocol(address || '', location);
2118
+ relative = !extracted.protocol && !extracted.slashes;
2119
+ url.slashes = extracted.slashes || relative && location.slashes;
2120
+ url.protocol = extracted.protocol || location.protocol || '';
2121
+ address = extracted.rest;
2122
+
2123
+ //
2124
+ // When the authority component is absent the URL starts with a path
2125
+ // component.
2126
+ //
2127
+ if (
2128
+ extracted.protocol === 'file:' && (
2129
+ extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||
2130
+ (!extracted.slashes &&
2131
+ (extracted.protocol ||
2132
+ extracted.slashesCount < 2 ||
2133
+ !isSpecial(url.protocol)))
2134
+ ) {
2135
+ instructions[3] = [/(.*)/, 'pathname'];
2136
+ }
2137
+
2138
+ for (; i < instructions.length; i++) {
2139
+ instruction = instructions[i];
2140
+
2141
+ if (typeof instruction === 'function') {
2142
+ address = instruction(address, url);
2143
+ continue;
2144
+ }
2145
+
2146
+ parse = instruction[0];
2147
+ key = instruction[1];
2148
+
2149
+ if (parse !== parse) {
2150
+ url[key] = address;
2151
+ } else if ('string' === typeof parse) {
2152
+ index = parse === '@'
2153
+ ? address.lastIndexOf(parse)
2154
+ : address.indexOf(parse);
2155
+
2156
+ if (~index) {
2157
+ if ('number' === typeof instruction[2]) {
2158
+ url[key] = address.slice(0, index);
2159
+ address = address.slice(index + instruction[2]);
2160
+ } else {
2161
+ url[key] = address.slice(index);
2162
+ address = address.slice(0, index);
2163
+ }
2164
+ }
2165
+ } else if ((index = parse.exec(address))) {
2166
+ url[key] = index[1];
2167
+ address = address.slice(0, index.index);
2168
+ }
2169
+
2170
+ url[key] = url[key] || (
2171
+ relative && instruction[3] ? location[key] || '' : ''
2172
+ );
2173
+
2174
+ //
2175
+ // Hostname, host and protocol should be lowercased so they can be used to
2176
+ // create a proper `origin`.
2177
+ //
2178
+ if (instruction[4]) url[key] = url[key].toLowerCase();
2179
+ }
2180
+
2181
+ //
2182
+ // Also parse the supplied query string in to an object. If we're supplied
2183
+ // with a custom parser as function use that instead of the default build-in
2184
+ // parser.
2185
+ //
2186
+ if (parser) url.query = parser(url.query);
2187
+
2188
+ //
2189
+ // If the URL is relative, resolve the pathname against the base URL.
2190
+ //
2191
+ if (
2192
+ relative
2193
+ && location.slashes
2194
+ && url.pathname.charAt(0) !== '/'
2195
+ && (url.pathname !== '' || location.pathname !== '')
2196
+ ) {
2197
+ url.pathname = resolve(url.pathname, location.pathname);
2198
+ }
2199
+
2200
+ //
2201
+ // Default to a / for pathname if none exists. This normalizes the URL
2202
+ // to always have a /
2203
+ //
2204
+ if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {
2205
+ url.pathname = '/' + url.pathname;
2206
+ }
2207
+
2208
+ //
2209
+ // We should not add port numbers if they are already the default port number
2210
+ // for a given protocol. As the host also contains the port number we're going
2211
+ // override it with the hostname which contains no port number.
2212
+ //
2213
+ if (!required(url.port, url.protocol)) {
2214
+ url.host = url.hostname;
2215
+ url.port = '';
2216
+ }
2217
+
2218
+ //
2219
+ // Parse down the `auth` for the username and password.
2220
+ //
2221
+ url.username = url.password = '';
2222
+
2223
+ if (url.auth) {
2224
+ index = url.auth.indexOf(':');
2225
+
2226
+ if (~index) {
2227
+ url.username = url.auth.slice(0, index);
2228
+ url.username = encodeURIComponent(decodeURIComponent(url.username));
2229
+
2230
+ url.password = url.auth.slice(index + 1);
2231
+ url.password = encodeURIComponent(decodeURIComponent(url.password))
2232
+ } else {
2233
+ url.username = encodeURIComponent(decodeURIComponent(url.auth));
2234
+ }
2235
+
2236
+ url.auth = url.password ? url.username +':'+ url.password : url.username;
2237
+ }
2238
+
2239
+ url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
2240
+ ? url.protocol +'//'+ url.host
2241
+ : 'null';
2242
+
2243
+ //
2244
+ // The href is just the compiled result.
2245
+ //
2246
+ url.href = url.toString();
2247
+ }
2248
+
2249
+ /**
2250
+ * This is convenience method for changing properties in the URL instance to
2251
+ * insure that they all propagate correctly.
2252
+ *
2253
+ * @param {String} part Property we need to adjust.
2254
+ * @param {Mixed} value The newly assigned value.
2255
+ * @param {Boolean|Function} fn When setting the query, it will be the function
2256
+ * used to parse the query.
2257
+ * When setting the protocol, double slash will be
2258
+ * removed from the final url if it is true.
2259
+ * @returns {URL} URL instance for chaining.
2260
+ * @public
2261
+ */
2262
+ function set(part, value, fn) {
2263
+ var url = this;
2264
+
2265
+ switch (part) {
2266
+ case 'query':
2267
+ if ('string' === typeof value && value.length) {
2268
+ value = (fn || qs.parse)(value);
2269
+ }
2270
+
2271
+ url[part] = value;
2272
+ break;
2273
+
2274
+ case 'port':
2275
+ url[part] = value;
2276
+
2277
+ if (!required(value, url.protocol)) {
2278
+ url.host = url.hostname;
2279
+ url[part] = '';
2280
+ } else if (value) {
2281
+ url.host = url.hostname +':'+ value;
2282
+ }
2283
+
2284
+ break;
2285
+
2286
+ case 'hostname':
2287
+ url[part] = value;
2288
+
2289
+ if (url.port) value += ':'+ url.port;
2290
+ url.host = value;
2291
+ break;
2292
+
2293
+ case 'host':
2294
+ url[part] = value;
2295
+
2296
+ if (port.test(value)) {
2297
+ value = value.split(':');
2298
+ url.port = value.pop();
2299
+ url.hostname = value.join(':');
2300
+ } else {
2301
+ url.hostname = value;
2302
+ url.port = '';
2303
+ }
2304
+
2305
+ break;
2306
+
2307
+ case 'protocol':
2308
+ url.protocol = value.toLowerCase();
2309
+ url.slashes = !fn;
2310
+ break;
2311
+
2312
+ case 'pathname':
2313
+ case 'hash':
2314
+ if (value) {
2315
+ var char = part === 'pathname' ? '/' : '#';
2316
+ url[part] = value.charAt(0) !== char ? char + value : value;
2317
+ } else {
2318
+ url[part] = value;
2319
+ }
2320
+ break;
2321
+
2322
+ case 'username':
2323
+ case 'password':
2324
+ url[part] = encodeURIComponent(value);
2325
+ break;
2326
+
2327
+ case 'auth':
2328
+ var index = value.indexOf(':');
2329
+
2330
+ if (~index) {
2331
+ url.username = value.slice(0, index);
2332
+ url.username = encodeURIComponent(decodeURIComponent(url.username));
2333
+
2334
+ url.password = value.slice(index + 1);
2335
+ url.password = encodeURIComponent(decodeURIComponent(url.password));
2336
+ } else {
2337
+ url.username = encodeURIComponent(decodeURIComponent(value));
2338
+ }
2339
+ }
2340
+
2341
+ for (var i = 0; i < rules.length; i++) {
2342
+ var ins = rules[i];
2343
+
2344
+ if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
2345
+ }
2346
+
2347
+ url.auth = url.password ? url.username +':'+ url.password : url.username;
2348
+
2349
+ url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
2350
+ ? url.protocol +'//'+ url.host
2351
+ : 'null';
2352
+
2353
+ url.href = url.toString();
2354
+
2355
+ return url;
2356
+ }
2357
+
2358
+ /**
2359
+ * Transform the properties back in to a valid and full URL string.
2360
+ *
2361
+ * @param {Function} stringify Optional query stringify function.
2362
+ * @returns {String} Compiled version of the URL.
2363
+ * @public
2364
+ */
2365
+ function toString(stringify) {
2366
+ if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
2367
+
2368
+ var query
2369
+ , url = this
2370
+ , host = url.host
2371
+ , protocol = url.protocol;
2372
+
2373
+ if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
2374
+
2375
+ var result =
2376
+ protocol +
2377
+ ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');
2378
+
2379
+ if (url.username) {
2380
+ result += url.username;
2381
+ if (url.password) result += ':'+ url.password;
2382
+ result += '@';
2383
+ } else if (url.password) {
2384
+ result += ':'+ url.password;
2385
+ result += '@';
2386
+ } else if (
2387
+ url.protocol !== 'file:' &&
2388
+ isSpecial(url.protocol) &&
2389
+ !host &&
2390
+ url.pathname !== '/'
2391
+ ) {
2392
+ //
2393
+ // Add back the empty userinfo, otherwise the original invalid URL
2394
+ // might be transformed into a valid one with `url.pathname` as host.
2395
+ //
2396
+ result += '@';
2397
+ }
2398
+
2399
+ //
2400
+ // Trailing colon is removed from `url.host` when it is parsed. If it still
2401
+ // ends with a colon, then add back the trailing colon that was removed. This
2402
+ // prevents an invalid URL from being transformed into a valid one.
2403
+ //
2404
+ if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {
2405
+ host += ':';
2406
+ }
2407
+
2408
+ result += host + url.pathname;
2409
+
2410
+ query = 'object' === typeof url.query ? stringify(url.query) : url.query;
2411
+ if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
2412
+
2413
+ if (url.hash) result += url.hash;
2414
+
2415
+ return result;
2416
+ }
2417
+
2418
+ Url.prototype = { set: set, toString: toString };
2419
+
2420
+ //
2421
+ // Expose the URL parser and some additional properties that might be useful for
2422
+ // others or testing.
2423
+ //
2424
+ Url.extractProtocol = extractProtocol;
2425
+ Url.location = lolcation;
2426
+ Url.trimLeft = trimLeft;
2427
+ Url.qs = qs;
2428
+
2429
+ module.exports = Url;
2430
+
2431
+ }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
2432
+ },{"querystringify":8,"requires-port":11}],15:[function(_dereq_,module,exports){
2433
+ 'use strict';
2434
+
2435
+ var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
2436
+ , length = 64
2437
+ , map = {}
2438
+ , seed = 0
2439
+ , i = 0
2440
+ , prev;
2441
+
2442
+ /**
2443
+ * Return a string representing the specified number.
2444
+ *
2445
+ * @param {Number} num The number to convert.
2446
+ * @returns {String} The string representation of the number.
2447
+ * @api public
2448
+ */
2449
+ function encode(num) {
2450
+ var encoded = '';
2451
+
2452
+ do {
2453
+ encoded = alphabet[num % length] + encoded;
2454
+ num = Math.floor(num / length);
2455
+ } while (num > 0);
2456
+
2457
+ return encoded;
2458
+ }
2459
+
2460
+ /**
2461
+ * Return the integer value specified by the given string.
2462
+ *
2463
+ * @param {String} str The string to convert.
2464
+ * @returns {Number} The integer value represented by the string.
2465
+ * @api public
2466
+ */
2467
+ function decode(str) {
2468
+ var decoded = 0;
2469
+
2470
+ for (i = 0; i < str.length; i++) {
2471
+ decoded = decoded * length + map[str.charAt(i)];
2472
+ }
2473
+
2474
+ return decoded;
2475
+ }
2476
+
2477
+ /**
2478
+ * Yeast: A tiny growing id generator.
2479
+ *
2480
+ * @returns {String} A unique id.
2481
+ * @api public
2482
+ */
2483
+ function yeast() {
2484
+ var now = encode(+new Date());
2485
+
2486
+ if (now !== prev) return seed = 0, prev = now;
2487
+ return now +'.'+ encode(seed++);
2488
+ }
2489
+
2490
+ //
2491
+ // Map each character to its index.
2492
+ //
2493
+ for (; i < length; i++) map[alphabet[i]] = i;
2494
+
2495
+ //
2496
+ // Expose the `yeast`, `encode` and `decode` functions.
2497
+ //
2498
+ yeast.encode = encode;
2499
+ yeast.decode = decode;
2500
+ module.exports = yeast;
2501
+
2502
+ },{}],16:[function(_dereq_,module,exports){
2503
+ /*globals require, define */
2504
+ 'use strict';
2505
+
2506
+ var EventEmitter = _dereq_('eventemitter3')
2507
+ , TickTock = _dereq_('tick-tock')
2508
+ , Recovery = _dereq_('recovery')
2509
+ , qs = _dereq_('querystringify')
2510
+ , inherits = _dereq_('inherits')
2511
+ , destroy = _dereq_('demolish')
2512
+ , yeast = _dereq_('yeast')
2513
+ , u2028 = /\u2028/g
2514
+ , u2029 = /\u2029/g;
2515
+
2516
+ /**
2517
+ * Context assertion, ensure that some of our public Primus methods are called
2518
+ * with the correct context to ensure that
2519
+ *
2520
+ * @param {Primus} self The context of the function.
2521
+ * @param {String} method The method name.
2522
+ * @api private
2523
+ */
2524
+ function context(self, method) {
2525
+ if (self instanceof Primus) return;
2526
+
2527
+ var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance');
2528
+
2529
+ if ('function' !== typeof self.listeners || !self.listeners('error').length) {
2530
+ throw failure;
2531
+ }
2532
+
2533
+ self.emit('error', failure);
2534
+ }
2535
+
2536
+ //
2537
+ // Sets the default connection URL, it uses the default origin of the browser
2538
+ // when supported but degrades for older browsers. In Node.js, we cannot guess
2539
+ // where the user wants to connect to, so we just default to localhost.
2540
+ //
2541
+ var defaultUrl;
2542
+
2543
+ try {
2544
+ if (location.origin) {
2545
+ defaultUrl = location.origin;
2546
+ } else {
2547
+ defaultUrl = location.protocol +'//'+ location.host;
2548
+ }
2549
+ } catch (e) {
2550
+ defaultUrl = 'http://127.0.0.1';
2551
+ }
2552
+
2553
+ /**
2554
+ * Primus is a real-time library agnostic framework for establishing real-time
2555
+ * connections with servers.
2556
+ *
2557
+ * Options:
2558
+ * - reconnect, configuration for the reconnect process.
2559
+ * - manual, don't automatically call `.open` to start the connection.
2560
+ * - websockets, force the use of WebSockets, even when you should avoid them.
2561
+ * - timeout, connect timeout, server didn't respond in a timely manner.
2562
+ * - pingTimeout, The maximum amount of time to wait for the server to send a ping.
2563
+ * - network, Use network events as leading method for network connection drops.
2564
+ * - strategy, Reconnection strategies.
2565
+ * - transport, Transport options.
2566
+ * - url, uri, The URL to use connect with the server.
2567
+ *
2568
+ * @constructor
2569
+ * @param {String} url The URL of your server.
2570
+ * @param {Object} options The configuration.
2571
+ * @api public
2572
+ */
2573
+ function Primus(url, options) {
2574
+ if (!(this instanceof Primus)) return new Primus(url, options);
2575
+
2576
+ Primus.Stream.call(this);
2577
+
2578
+ if ('function' !== typeof this.client) {
2579
+ return this.critical(new Error(
2580
+ 'The client library has not been compiled correctly, see '+
2581
+ 'https://github.com/primus/primus#client-library for more details'
2582
+ ));
2583
+ }
2584
+
2585
+ if ('object' === typeof url) {
2586
+ options = url;
2587
+ url = options.url || options.uri || defaultUrl;
2588
+ } else {
2589
+ options = options || {};
2590
+ }
2591
+
2592
+ if ('ping' in options || 'pong' in options) {
2593
+ return this.critical(new Error(
2594
+ 'The `ping` and `pong` options have been removed'
2595
+ ));
2596
+ }
2597
+
2598
+ var primus = this;
2599
+
2600
+ // The maximum number of messages that can be placed in queue.
2601
+ options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
2602
+
2603
+ // Connection timeout duration.
2604
+ options.timeout = 'timeout' in options ? options.timeout : 10e3;
2605
+
2606
+ // Stores the back off configuration.
2607
+ options.reconnect = 'reconnect' in options ? options.reconnect : {};
2608
+
2609
+ // Heartbeat ping interval.
2610
+ options.pingTimeout = 'pingTimeout' in options ? options.pingTimeout : 45e3;
2611
+
2612
+ // Reconnect strategies.
2613
+ options.strategy = 'strategy' in options ? options.strategy : [];
2614
+
2615
+ // Custom transport options.
2616
+ options.transport = 'transport' in options ? options.transport : {};
2617
+
2618
+ primus.buffer = []; // Stores premature send data.
2619
+ primus.writable = true; // Silly stream compatibility.
2620
+ primus.readable = true; // Silly stream compatibility.
2621
+ primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
2622
+ primus.readyState = Primus.CLOSED; // The readyState of the connection.
2623
+ primus.options = options; // Reference to the supplied options.
2624
+ primus.timers = new TickTock(this); // Contains all our timers.
2625
+ primus.socket = null; // Reference to the internal connection.
2626
+ primus.disconnect = false; // Did we receive a disconnect packet?
2627
+ primus.transport = options.transport; // Transport options.
2628
+ primus.transformers = { // Message transformers.
2629
+ outgoing: [],
2630
+ incoming: []
2631
+ };
2632
+
2633
+ //
2634
+ // Create our reconnection instance.
2635
+ //
2636
+ primus.recovery = new Recovery(options.reconnect);
2637
+
2638
+ //
2639
+ // Parse the reconnection strategy. It can have the following strategies:
2640
+ //
2641
+ // - timeout: Reconnect when we have a network timeout.
2642
+ // - disconnect: Reconnect when we have an unexpected disconnect.
2643
+ // - online: Reconnect when we're back online.
2644
+ //
2645
+ if ('string' === typeof options.strategy) {
2646
+ options.strategy = options.strategy.split(/\s?,\s?/g);
2647
+ }
2648
+
2649
+ if (false === options.strategy) {
2650
+ //
2651
+ // Strategies are disabled, but we still need an empty array to join it in
2652
+ // to nothing.
2653
+ //
2654
+ options.strategy = [];
2655
+ } else if (!options.strategy.length) {
2656
+ options.strategy.push('disconnect', 'online');
2657
+
2658
+ //
2659
+ // Timeout based reconnection should only be enabled conditionally. When
2660
+ // authorization is enabled it could trigger.
2661
+ //
2662
+ if (!this.authorization) options.strategy.push('timeout');
2663
+ }
2664
+
2665
+ options.strategy = options.strategy.join(',').toLowerCase();
2666
+
2667
+ //
2668
+ // Force the use of WebSockets, even when we've detected some potential
2669
+ // broken WebSocket implementation.
2670
+ //
2671
+ if ('websockets' in options) {
2672
+ primus.AVOID_WEBSOCKETS = !options.websockets;
2673
+ }
2674
+
2675
+ //
2676
+ // Force or disable the use of NETWORK events as leading client side
2677
+ // disconnection detection.
2678
+ //
2679
+ if ('network' in options) {
2680
+ primus.NETWORK_EVENTS = options.network;
2681
+ }
2682
+
2683
+ //
2684
+ // Check if the user wants to manually initialise a connection. If they don't,
2685
+ // we want to do it after a really small timeout so we give the users enough
2686
+ // time to listen for `error` events etc.
2687
+ //
2688
+ if (!options.manual) primus.timers.setTimeout('open', function open() {
2689
+ primus.timers.clear('open');
2690
+ primus.open();
2691
+ }, 0);
2692
+
2693
+ primus.initialise(options);
2694
+ }
2695
+
2696
+ /**
2697
+ * Simple require wrapper to make browserify, node and require.js play nice.
2698
+ *
2699
+ * @param {String} name The module to require.
2700
+ * @returns {Object|Undefined} The module that we required.
2701
+ * @api private
2702
+ */
2703
+ Primus.requires = Primus.require = function requires(name) {
2704
+ if ('function' !== typeof _dereq_) return undefined;
2705
+
2706
+ return !('function' === typeof define && define.amd)
2707
+ ? _dereq_(name)
2708
+ : undefined;
2709
+ };
2710
+
2711
+ //
2712
+ // It's possible that we're running in Node.js or in a Node.js compatible
2713
+ // environment. In this cases we try to inherit from the Stream base class.
2714
+ //
2715
+ try {
2716
+ Primus.Stream = Primus.requires('stream');
2717
+ } catch (e) { }
2718
+
2719
+ if (!Primus.Stream) Primus.Stream = EventEmitter;
2720
+
2721
+ inherits(Primus, Primus.Stream);
2722
+
2723
+ /**
2724
+ * Primus readyStates, used internally to set the correct ready state.
2725
+ *
2726
+ * @type {Number}
2727
+ * @private
2728
+ */
2729
+ Primus.OPENING = 1; // We're opening the connection.
2730
+ Primus.CLOSED = 2; // No active connection.
2731
+ Primus.OPEN = 3; // The connection is open.
2732
+
2733
+ /**
2734
+ * Are we working with a potentially broken WebSockets implementation? This
2735
+ * boolean can be used by transformers to remove `WebSockets` from their
2736
+ * supported transports.
2737
+ *
2738
+ * @type {Boolean}
2739
+ * @private
2740
+ */
2741
+ Primus.prototype.AVOID_WEBSOCKETS = false;
2742
+
2743
+ /**
2744
+ * Some browsers support registering emitting `online` and `offline` events when
2745
+ * the connection has been dropped on the client. We're going to detect it in
2746
+ * a simple `try {} catch (e) {}` statement so we don't have to do complicated
2747
+ * feature detection.
2748
+ *
2749
+ * @type {Boolean}
2750
+ * @private
2751
+ */
2752
+ Primus.prototype.NETWORK_EVENTS = false;
2753
+ Primus.prototype.online = true;
2754
+
2755
+ try {
2756
+ if (
2757
+ Primus.prototype.NETWORK_EVENTS = 'onLine' in navigator
2758
+ && (window.addEventListener || document.body.attachEvent)
2759
+ ) {
2760
+ if (!navigator.onLine) {
2761
+ Primus.prototype.online = false;
2762
+ }
2763
+ }
2764
+ } catch (e) { }
2765
+
2766
+ /**
2767
+ * The Ark contains all our plugins definitions. It's namespaced by
2768
+ * name => plugin.
2769
+ *
2770
+ * @type {Object}
2771
+ * @private
2772
+ */
2773
+ Primus.prototype.ark = {};
2774
+
2775
+ /**
2776
+ * Simple emit wrapper that returns a function that emits an event once it's
2777
+ * called. This makes it easier for transports to emit specific events.
2778
+ *
2779
+ * @returns {Function} A function that will emit the event when called.
2780
+ * @api public
2781
+ */
2782
+ Primus.prototype.emits = _dereq_('emits');
2783
+
2784
+ /**
2785
+ * Return the given plugin.
2786
+ *
2787
+ * @param {String} name The name of the plugin.
2788
+ * @returns {Object|undefined} The plugin or undefined.
2789
+ * @api public
2790
+ */
2791
+ Primus.prototype.plugin = function plugin(name) {
2792
+ context(this, 'plugin');
2793
+
2794
+ if (name) return this.ark[name];
2795
+
2796
+ var plugins = {};
2797
+
2798
+ for (name in this.ark) {
2799
+ plugins[name] = this.ark[name];
2800
+ }
2801
+
2802
+ return plugins;
2803
+ };
2804
+
2805
+ /**
2806
+ * Checks if the given event is an emitted event by Primus.
2807
+ *
2808
+ * @param {String} evt The event name.
2809
+ * @returns {Boolean} Indication of the event is reserved for internal use.
2810
+ * @api public
2811
+ */
2812
+ Primus.prototype.reserved = function reserved(evt) {
2813
+ return (/^(incoming|outgoing)::/).test(evt)
2814
+ || evt in this.reserved.events;
2815
+ };
2816
+
2817
+ /**
2818
+ * The actual events that are used by the client.
2819
+ *
2820
+ * @type {Object}
2821
+ * @public
2822
+ */
2823
+ Primus.prototype.reserved.events = {
2824
+ 'reconnect scheduled': 1,
2825
+ 'reconnect timeout': 1,
2826
+ 'readyStateChange': 1,
2827
+ 'reconnect failed': 1,
2828
+ 'reconnected': 1,
2829
+ 'reconnect': 1,
2830
+ 'offline': 1,
2831
+ 'timeout': 1,
2832
+ 'destroy': 1,
2833
+ 'online': 1,
2834
+ 'error': 1,
2835
+ 'close': 1,
2836
+ 'open': 1,
2837
+ 'data': 1,
2838
+ 'end': 1
2839
+ };
2840
+
2841
+ /**
2842
+ * Initialise the Primus and setup all parsers and internal listeners.
2843
+ *
2844
+ * @param {Object} options The original options object.
2845
+ * @returns {Primus}
2846
+ * @api private
2847
+ */
2848
+ Primus.prototype.initialise = function initialise(options) {
2849
+ var primus = this;
2850
+
2851
+ primus.recovery
2852
+ .on('reconnected', primus.emits('reconnected'))
2853
+ .on('reconnect failed', primus.emits('reconnect failed', function failed(next) {
2854
+ primus.emit('end');
2855
+ next();
2856
+ }))
2857
+ .on('reconnect timeout', primus.emits('reconnect timeout'))
2858
+ .on('reconnect scheduled', primus.emits('reconnect scheduled'))
2859
+ .on('reconnect', primus.emits('reconnect', function reconnect(next) {
2860
+ primus.emit('outgoing::reconnect');
2861
+ next();
2862
+ }));
2863
+
2864
+ primus.on('outgoing::open', function opening() {
2865
+ var readyState = primus.readyState;
2866
+
2867
+ primus.readyState = Primus.OPENING;
2868
+ if (readyState !== primus.readyState) {
2869
+ primus.emit('readyStateChange', 'opening');
2870
+ }
2871
+ });
2872
+
2873
+ primus.on('incoming::open', function opened() {
2874
+ var readyState = primus.readyState;
2875
+
2876
+ if (primus.recovery.reconnecting()) {
2877
+ primus.recovery.reconnected();
2878
+ }
2879
+
2880
+ //
2881
+ // The connection has been opened so we should set our state to
2882
+ // (writ|read)able so our stream compatibility works as intended.
2883
+ //
2884
+ primus.writable = true;
2885
+ primus.readable = true;
2886
+
2887
+ //
2888
+ // Make sure we are flagged as `online` as we've successfully opened the
2889
+ // connection.
2890
+ //
2891
+ if (!primus.online) {
2892
+ primus.online = true;
2893
+ primus.emit('online');
2894
+ }
2895
+
2896
+ primus.readyState = Primus.OPEN;
2897
+ if (readyState !== primus.readyState) {
2898
+ primus.emit('readyStateChange', 'open');
2899
+ }
2900
+
2901
+ primus.heartbeat();
2902
+
2903
+ if (primus.buffer.length) {
2904
+ var data = primus.buffer.slice()
2905
+ , length = data.length
2906
+ , i = 0;
2907
+
2908
+ primus.buffer.length = 0;
2909
+
2910
+ for (; i < length; i++) {
2911
+ primus._write(data[i]);
2912
+ }
2913
+ }
2914
+
2915
+ primus.emit('open');
2916
+ });
2917
+
2918
+ primus.on('incoming::ping', function ping(time) {
2919
+ primus.online = true;
2920
+ primus.heartbeat();
2921
+ primus.emit('outgoing::pong', time);
2922
+ primus._write('primus::pong::'+ time);
2923
+ });
2924
+
2925
+ primus.on('incoming::error', function error(e) {
2926
+ var connect = primus.timers.active('connect')
2927
+ , err = e;
2928
+
2929
+ //
2930
+ // When the error is not an Error instance we try to normalize it.
2931
+ //
2932
+ if ('string' === typeof e) {
2933
+ err = new Error(e);
2934
+ } else if (!(e instanceof Error) && 'object' === typeof e) {
2935
+ //
2936
+ // BrowserChannel and SockJS returns an object which contains some
2937
+ // details of the error. In order to have a proper error we "copy" the
2938
+ // details in an Error instance.
2939
+ //
2940
+ err = new Error(e.message || e.reason);
2941
+ for (var key in e) {
2942
+ if (Object.prototype.hasOwnProperty.call(e, key))
2943
+ err[key] = e[key];
2944
+ }
2945
+ }
2946
+ //
2947
+ // We're still doing a reconnect attempt, it could be that we failed to
2948
+ // connect because the server was down. Failing connect attempts should
2949
+ // always emit an `error` event instead of a `open` event.
2950
+ //
2951
+ //
2952
+ if (primus.recovery.reconnecting()) return primus.recovery.reconnected(err);
2953
+ if (primus.listeners('error').length) primus.emit('error', err);
2954
+
2955
+ //
2956
+ // We received an error while connecting, this most likely the result of an
2957
+ // unauthorized access to the server.
2958
+ //
2959
+ if (connect) {
2960
+ if (~primus.options.strategy.indexOf('timeout')) {
2961
+ primus.recovery.reconnect();
2962
+ } else {
2963
+ primus.end();
2964
+ }
2965
+ }
2966
+ });
2967
+
2968
+ primus.on('incoming::data', function message(raw) {
2969
+ primus.decoder(raw, function decoding(err, data) {
2970
+ //
2971
+ // Do a "safe" emit('error') when we fail to parse a message. We don't
2972
+ // want to throw here as listening to errors should be optional.
2973
+ //
2974
+ if (err) return primus.listeners('error').length && primus.emit('error', err);
2975
+
2976
+ //
2977
+ // Handle all "primus::" prefixed protocol messages.
2978
+ //
2979
+ if (primus.protocol(data)) return;
2980
+ primus.transforms(primus, primus, 'incoming', data, raw);
2981
+ });
2982
+ });
2983
+
2984
+ primus.on('incoming::end', function end() {
2985
+ var readyState = primus.readyState;
2986
+
2987
+ //
2988
+ // This `end` started with the receiving of a primus::server::close packet
2989
+ // which indicated that the user/developer on the server closed the
2990
+ // connection and it was not a result of a network disruption. So we should
2991
+ // kill the connection without doing a reconnect.
2992
+ //
2993
+ if (primus.disconnect) {
2994
+ primus.disconnect = false;
2995
+
2996
+ return primus.end();
2997
+ }
2998
+
2999
+ //
3000
+ // Always set the readyState to closed, and if we're still connecting, close
3001
+ // the connection so we're sure that everything after this if statement block
3002
+ // is only executed because our readyState is set to `open`.
3003
+ //
3004
+ primus.readyState = Primus.CLOSED;
3005
+ if (readyState !== primus.readyState) {
3006
+ primus.emit('readyStateChange', 'end');
3007
+ }
3008
+
3009
+ if (primus.timers.active('connect')) primus.end();
3010
+ if (readyState !== Primus.OPEN) {
3011
+ return primus.recovery.reconnecting()
3012
+ ? primus.recovery.reconnect()
3013
+ : false;
3014
+ }
3015
+
3016
+ this.writable = false;
3017
+ this.readable = false;
3018
+
3019
+ //
3020
+ // Clear all timers in case we're not going to reconnect.
3021
+ //
3022
+ this.timers.clear();
3023
+
3024
+ //
3025
+ // Fire the `close` event as an indication of connection disruption.
3026
+ // This is also fired by `primus#end` so it is emitted in all cases.
3027
+ //
3028
+ primus.emit('close');
3029
+
3030
+ //
3031
+ // The disconnect was unintentional, probably because the server has
3032
+ // shutdown, so if the reconnection is enabled start a reconnect procedure.
3033
+ //
3034
+ if (~primus.options.strategy.indexOf('disconnect')) {
3035
+ return primus.recovery.reconnect();
3036
+ }
3037
+
3038
+ primus.emit('outgoing::end');
3039
+ primus.emit('end');
3040
+ });
3041
+
3042
+ //
3043
+ // Setup the real-time client.
3044
+ //
3045
+ primus.client();
3046
+
3047
+ //
3048
+ // Process the potential plugins.
3049
+ //
3050
+ for (var plugin in primus.ark) {
3051
+ primus.ark[plugin].call(primus, primus, options);
3052
+ }
3053
+
3054
+ //
3055
+ // NOTE: The following code is only required if we're supporting network
3056
+ // events as it requires access to browser globals.
3057
+ //
3058
+ if (!primus.NETWORK_EVENTS) return primus;
3059
+
3060
+ /**
3061
+ * Handler for offline notifications.
3062
+ *
3063
+ * @api private
3064
+ */
3065
+ primus.offlineHandler = function offline() {
3066
+ if (!primus.online) return; // Already or still offline, bailout.
3067
+
3068
+ primus.online = false;
3069
+ primus.emit('offline');
3070
+ primus.end();
3071
+
3072
+ //
3073
+ // It is certainly possible that we're in a reconnection loop and that the
3074
+ // user goes offline. In this case we want to kill the existing attempt so
3075
+ // when the user goes online, it will attempt to reconnect freshly again.
3076
+ //
3077
+ primus.recovery.reset();
3078
+ };
3079
+
3080
+ /**
3081
+ * Handler for online notifications.
3082
+ *
3083
+ * @api private
3084
+ */
3085
+ primus.onlineHandler = function online() {
3086
+ if (primus.online) return; // Already or still online, bailout.
3087
+
3088
+ primus.online = true;
3089
+ primus.emit('online');
3090
+
3091
+ if (~primus.options.strategy.indexOf('online')) {
3092
+ primus.recovery.reconnect();
3093
+ }
3094
+ };
3095
+
3096
+ if (window.addEventListener) {
3097
+ window.addEventListener('offline', primus.offlineHandler, false);
3098
+ window.addEventListener('online', primus.onlineHandler, false);
3099
+ } else if (document.body.attachEvent){
3100
+ document.body.attachEvent('onoffline', primus.offlineHandler);
3101
+ document.body.attachEvent('ononline', primus.onlineHandler);
3102
+ }
3103
+
3104
+ return primus;
3105
+ };
3106
+
3107
+ /**
3108
+ * Really dead simple protocol parser. We simply assume that every message that
3109
+ * is prefixed with `primus::` could be used as some sort of protocol definition
3110
+ * for Primus.
3111
+ *
3112
+ * @param {String} msg The data.
3113
+ * @returns {Boolean} Is a protocol message.
3114
+ * @api private
3115
+ */
3116
+ Primus.prototype.protocol = function protocol(msg) {
3117
+ if (
3118
+ 'string' !== typeof msg
3119
+ || msg.indexOf('primus::') !== 0
3120
+ ) return false;
3121
+
3122
+ var last = msg.indexOf(':', 8)
3123
+ , value = msg.slice(last + 2);
3124
+
3125
+ switch (msg.slice(8, last)) {
3126
+ case 'ping':
3127
+ this.emit('incoming::ping', +value);
3128
+ break;
3129
+
3130
+ case 'server':
3131
+ //
3132
+ // The server is closing the connection, forcefully disconnect so we don't
3133
+ // reconnect again.
3134
+ //
3135
+ if ('close' === value) {
3136
+ this.disconnect = true;
3137
+ }
3138
+ break;
3139
+
3140
+ case 'id':
3141
+ this.emit('incoming::id', value);
3142
+ break;
3143
+
3144
+ //
3145
+ // Unknown protocol, somebody is probably sending `primus::` prefixed
3146
+ // messages.
3147
+ //
3148
+ default:
3149
+ return false;
3150
+ }
3151
+
3152
+ return true;
3153
+ };
3154
+
3155
+ /**
3156
+ * Execute the set of message transformers from Primus on the incoming or
3157
+ * outgoing message.
3158
+ * This function and it's content should be in sync with Spark#transforms in
3159
+ * spark.js.
3160
+ *
3161
+ * @param {Primus} primus Reference to the Primus instance with message transformers.
3162
+ * @param {Spark|Primus} connection Connection that receives or sends data.
3163
+ * @param {String} type The type of message, 'incoming' or 'outgoing'.
3164
+ * @param {Mixed} data The data to send or that has been received.
3165
+ * @param {String} raw The raw encoded data.
3166
+ * @returns {Primus}
3167
+ * @api public
3168
+ */
3169
+ Primus.prototype.transforms = function transforms(primus, connection, type, data, raw) {
3170
+ var packet = { data: data }
3171
+ , fns = primus.transformers[type];
3172
+
3173
+ //
3174
+ // Iterate in series over the message transformers so we can allow optional
3175
+ // asynchronous execution of message transformers which could for example
3176
+ // retrieve additional data from the server, do extra decoding or even
3177
+ // message validation.
3178
+ //
3179
+ (function transform(index, done) {
3180
+ var transformer = fns[index++];
3181
+
3182
+ if (!transformer) return done();
3183
+
3184
+ if (1 === transformer.length) {
3185
+ if (false === transformer.call(connection, packet)) {
3186
+ //
3187
+ // When false is returned by an incoming transformer it means that's
3188
+ // being handled by the transformer and we should not emit the `data`
3189
+ // event.
3190
+ //
3191
+ return;
3192
+ }
3193
+
3194
+ return transform(index, done);
3195
+ }
3196
+
3197
+ transformer.call(connection, packet, function finished(err, arg) {
3198
+ if (err) return connection.emit('error', err);
3199
+ if (false === arg) return;
3200
+
3201
+ transform(index, done);
3202
+ });
3203
+ }(0, function done() {
3204
+ //
3205
+ // We always emit 2 arguments for the data event, the first argument is the
3206
+ // parsed data and the second argument is the raw string that we received.
3207
+ // This allows you, for example, to do some validation on the parsed data
3208
+ // and then save the raw string in your database without the stringify
3209
+ // overhead.
3210
+ //
3211
+ if ('incoming' === type) return connection.emit('data', packet.data, raw);
3212
+
3213
+ connection._write(packet.data);
3214
+ }));
3215
+
3216
+ return this;
3217
+ };
3218
+
3219
+ /**
3220
+ * Retrieve the current id from the server.
3221
+ *
3222
+ * @param {Function} fn Callback function.
3223
+ * @returns {Primus}
3224
+ * @api public
3225
+ */
3226
+ Primus.prototype.id = function id(fn) {
3227
+ if (this.socket && this.socket.id) return fn(this.socket.id);
3228
+
3229
+ this._write('primus::id::');
3230
+ return this.once('incoming::id', fn);
3231
+ };
3232
+
3233
+ /**
3234
+ * Establish a connection with the server. When this function is called we
3235
+ * assume that we don't have any open connections. If you do call it when you
3236
+ * have a connection open, it could cause duplicate connections.
3237
+ *
3238
+ * @returns {Primus}
3239
+ * @api public
3240
+ */
3241
+ Primus.prototype.open = function open() {
3242
+ context(this, 'open');
3243
+
3244
+ //
3245
+ // Only start a `connection timeout` procedure if we're not reconnecting as
3246
+ // that shouldn't count as an initial connection. This should be started
3247
+ // before the connection is opened to capture failing connections and kill the
3248
+ // timeout.
3249
+ //
3250
+ if (!this.recovery.reconnecting() && this.options.timeout) this.timeout();
3251
+
3252
+ this.emit('outgoing::open');
3253
+ return this;
3254
+ };
3255
+
3256
+ /**
3257
+ * Send a new message.
3258
+ *
3259
+ * @param {Mixed} data The data that needs to be written.
3260
+ * @returns {Boolean} Always returns true as we don't support back pressure.
3261
+ * @api public
3262
+ */
3263
+ Primus.prototype.write = function write(data) {
3264
+ context(this, 'write');
3265
+ this.transforms(this, this, 'outgoing', data);
3266
+
3267
+ return true;
3268
+ };
3269
+
3270
+ /**
3271
+ * The actual message writer.
3272
+ *
3273
+ * @param {Mixed} data The message that needs to be written.
3274
+ * @returns {Boolean} Successful write to the underlaying transport.
3275
+ * @api private
3276
+ */
3277
+ Primus.prototype._write = function write(data) {
3278
+ var primus = this;
3279
+
3280
+ //
3281
+ // The connection is closed, normally this would already be done in the
3282
+ // `spark.write` method, but as `_write` is used internally, we should also
3283
+ // add the same check here to prevent potential crashes by writing to a dead
3284
+ // socket.
3285
+ //
3286
+ if (Primus.OPEN !== primus.readyState) {
3287
+ //
3288
+ // If the buffer is at capacity, remove the first item.
3289
+ //
3290
+ if (this.buffer.length === this.options.queueSize) {
3291
+ this.buffer.splice(0, 1);
3292
+ }
3293
+
3294
+ this.buffer.push(data);
3295
+ return false;
3296
+ }
3297
+
3298
+ primus.encoder(data, function encoded(err, packet) {
3299
+ //
3300
+ // Do a "safe" emit('error') when we fail to parse a message. We don't
3301
+ // want to throw here as listening to errors should be optional.
3302
+ //
3303
+ if (err) return primus.listeners('error').length && primus.emit('error', err);
3304
+
3305
+ //
3306
+ // Hack 1: \u2028 and \u2029 are allowed inside a JSON string, but JavaScript
3307
+ // defines them as newline separators. Unescaped control characters are not
3308
+ // allowed inside JSON strings, so this causes an error at parse time. We
3309
+ // work around this issue by escaping these characters. This can cause
3310
+ // errors with JSONP requests or if the string is just evaluated.
3311
+ //
3312
+ if ('string' === typeof packet) {
3313
+ if (~packet.indexOf('\u2028')) packet = packet.replace(u2028, '\\u2028');
3314
+ if (~packet.indexOf('\u2029')) packet = packet.replace(u2029, '\\u2029');
3315
+ }
3316
+
3317
+ primus.emit('outgoing::data', packet);
3318
+ });
3319
+
3320
+ return true;
3321
+ };
3322
+
3323
+ /**
3324
+ * Set a timer that, upon expiration, closes the client.
3325
+ *
3326
+ * @returns {Primus}
3327
+ * @api private
3328
+ */
3329
+ Primus.prototype.heartbeat = function heartbeat() {
3330
+ if (!this.options.pingTimeout) return this;
3331
+
3332
+ this.timers.clear('heartbeat');
3333
+ this.timers.setTimeout('heartbeat', function expired() {
3334
+ //
3335
+ // The network events already captured the offline event.
3336
+ //
3337
+ if (!this.online) return;
3338
+
3339
+ this.online = false;
3340
+ this.emit('offline');
3341
+ this.emit('incoming::end');
3342
+ }, this.options.pingTimeout);
3343
+
3344
+ return this;
3345
+ };
3346
+
3347
+ /**
3348
+ * Start a connection timeout.
3349
+ *
3350
+ * @returns {Primus}
3351
+ * @api private
3352
+ */
3353
+ Primus.prototype.timeout = function timeout() {
3354
+ var primus = this;
3355
+
3356
+ /**
3357
+ * Remove all references to the timeout listener as we've received an event
3358
+ * that can be used to determine state.
3359
+ *
3360
+ * @api private
3361
+ */
3362
+ function remove() {
3363
+ primus.removeListener('error', remove)
3364
+ .removeListener('open', remove)
3365
+ .removeListener('end', remove)
3366
+ .timers.clear('connect');
3367
+ }
3368
+
3369
+ primus.timers.setTimeout('connect', function expired() {
3370
+ remove(); // Clean up old references.
3371
+
3372
+ if (primus.readyState === Primus.OPEN || primus.recovery.reconnecting()) {
3373
+ return;
3374
+ }
3375
+
3376
+ primus.emit('timeout');
3377
+
3378
+ //
3379
+ // We failed to connect to the server.
3380
+ //
3381
+ if (~primus.options.strategy.indexOf('timeout')) {
3382
+ primus.recovery.reconnect();
3383
+ } else {
3384
+ primus.end();
3385
+ }
3386
+ }, primus.options.timeout);
3387
+
3388
+ return primus.on('error', remove)
3389
+ .on('open', remove)
3390
+ .on('end', remove);
3391
+ };
3392
+
3393
+ /**
3394
+ * Close the connection completely.
3395
+ *
3396
+ * @param {Mixed} data last packet of data.
3397
+ * @returns {Primus}
3398
+ * @api public
3399
+ */
3400
+ Primus.prototype.end = function end(data) {
3401
+ context(this, 'end');
3402
+
3403
+ if (
3404
+ this.readyState === Primus.CLOSED
3405
+ && !this.timers.active('connect')
3406
+ && !this.timers.active('open')
3407
+ ) {
3408
+ //
3409
+ // If we are reconnecting stop the reconnection procedure.
3410
+ //
3411
+ if (this.recovery.reconnecting()) {
3412
+ this.recovery.reset();
3413
+ this.emit('end');
3414
+ }
3415
+
3416
+ return this;
3417
+ }
3418
+
3419
+ if (data !== undefined) this.write(data);
3420
+
3421
+ this.writable = false;
3422
+ this.readable = false;
3423
+
3424
+ var readyState = this.readyState;
3425
+ this.readyState = Primus.CLOSED;
3426
+
3427
+ if (readyState !== this.readyState) {
3428
+ this.emit('readyStateChange', 'end');
3429
+ }
3430
+
3431
+ this.timers.clear();
3432
+ this.emit('outgoing::end');
3433
+ this.emit('close');
3434
+ this.emit('end');
3435
+
3436
+ return this;
3437
+ };
3438
+
3439
+ /**
3440
+ * Completely demolish the Primus instance and forcefully nuke all references.
3441
+ *
3442
+ * @returns {Boolean}
3443
+ * @api public
3444
+ */
3445
+ Primus.prototype.destroy = destroy('url timers options recovery socket transport transformers', {
3446
+ before: 'end',
3447
+ after: ['removeAllListeners', function detach() {
3448
+ if (!this.NETWORK_EVENTS) return;
3449
+
3450
+ if (window.addEventListener) {
3451
+ window.removeEventListener('offline', this.offlineHandler);
3452
+ window.removeEventListener('online', this.onlineHandler);
3453
+ } else if (document.body.attachEvent){
3454
+ document.body.detachEvent('onoffline', this.offlineHandler);
3455
+ document.body.detachEvent('ononline', this.onlineHandler);
3456
+ }
3457
+ }]
3458
+ });
3459
+
3460
+ /**
3461
+ * Create a shallow clone of a given object.
3462
+ *
3463
+ * @param {Object} obj The object that needs to be cloned.
3464
+ * @returns {Object} Copy.
3465
+ * @api private
3466
+ */
3467
+ Primus.prototype.clone = function clone(obj) {
3468
+ return this.merge({}, obj);
3469
+ };
3470
+
3471
+ /**
3472
+ * Merge different objects in to one target object.
3473
+ *
3474
+ * @param {Object} target The object where everything should be merged in.
3475
+ * @returns {Object} Original target with all merged objects.
3476
+ * @api private
3477
+ */
3478
+ Primus.prototype.merge = function merge(target) {
3479
+ for (var i = 1, key, obj; i < arguments.length; i++) {
3480
+ obj = arguments[i];
3481
+
3482
+ for (key in obj) {
3483
+ if (Object.prototype.hasOwnProperty.call(obj, key))
3484
+ target[key] = obj[key];
3485
+ }
3486
+ }
3487
+
3488
+ return target;
3489
+ };
3490
+
3491
+ /**
3492
+ * Parse the connection string.
3493
+ *
3494
+ * @type {Function}
3495
+ * @param {String} url Connection URL.
3496
+ * @returns {Object} Parsed connection.
3497
+ * @api private
3498
+ */
3499
+ Primus.prototype.parse = _dereq_('url-parse');
3500
+
3501
+ /**
3502
+ * Parse a query string.
3503
+ *
3504
+ * @param {String} query The query string that needs to be parsed.
3505
+ * @returns {Object} Parsed query string.
3506
+ * @api private
3507
+ */
3508
+ Primus.prototype.querystring = qs.parse;
3509
+ /**
3510
+ * Transform a query string object back into string equiv.
3511
+ *
3512
+ * @param {Object} obj The query string object.
3513
+ * @returns {String}
3514
+ * @api private
3515
+ */
3516
+ Primus.prototype.querystringify = qs.stringify;
3517
+
3518
+ /**
3519
+ * Generates a connection URI.
3520
+ *
3521
+ * @param {String} protocol The protocol that should used to crate the URI.
3522
+ * @returns {String|options} The URL.
3523
+ * @api private
3524
+ */
3525
+ Primus.prototype.uri = function uri(options) {
3526
+ var url = this.url
3527
+ , server = []
3528
+ , qsa = false;
3529
+
3530
+ //
3531
+ // Query strings are only allowed when we've received clearance for it.
3532
+ //
3533
+ if (options.query) qsa = true;
3534
+
3535
+ options = options || {};
3536
+ options.protocol = 'protocol' in options
3537
+ ? options.protocol
3538
+ : 'http:';
3539
+ options.query = url.query && qsa
3540
+ ? url.query.slice(1)
3541
+ : false;
3542
+ options.secure = 'secure' in options
3543
+ ? options.secure
3544
+ : url.protocol === 'https:' || url.protocol === 'wss:';
3545
+ options.auth = 'auth' in options
3546
+ ? options.auth
3547
+ : url.auth;
3548
+ options.pathname = 'pathname' in options
3549
+ ? options.pathname
3550
+ : this.pathname;
3551
+ options.port = 'port' in options
3552
+ ? +options.port
3553
+ : +url.port || (options.secure ? 443 : 80);
3554
+
3555
+ //
3556
+ // We need to make sure that we create a unique connection URL every time to
3557
+ // prevent back forward cache from becoming an issue. We're doing this by
3558
+ // forcing an cache busting query string in to the URL.
3559
+ //
3560
+ var querystring = this.querystring(options.query || '');
3561
+ querystring._primuscb = yeast();
3562
+ options.query = this.querystringify(querystring);
3563
+
3564
+ //
3565
+ // Allow transformation of the options before we construct a full URL from it.
3566
+ //
3567
+ this.emit('outgoing::url', options);
3568
+
3569
+ //
3570
+ // Automatically suffix the protocol so we can supply `ws:` and `http:` and
3571
+ // it gets transformed correctly.
3572
+ //
3573
+ server.push(options.secure ? options.protocol.replace(':', 's:') : options.protocol, '');
3574
+
3575
+ server.push(options.auth ? options.auth +'@'+ url.host : url.host);
3576
+
3577
+ //
3578
+ // Pathnames are optional as some Transformers would just use the pathname
3579
+ // directly.
3580
+ //
3581
+ if (options.pathname) server.push(options.pathname.slice(1));
3582
+
3583
+ //
3584
+ // Optionally add a search query.
3585
+ //
3586
+ if (qsa) server[server.length - 1] += '?'+ options.query;
3587
+ else delete options.query;
3588
+
3589
+ if (options.object) return options;
3590
+ return server.join('/');
3591
+ };
3592
+
3593
+ /**
3594
+ * Register a new message transformer. This allows you to easily manipulate incoming
3595
+ * and outgoing data which is particularity handy for plugins that want to send
3596
+ * meta data together with the messages.
3597
+ *
3598
+ * @param {String} type Incoming or outgoing
3599
+ * @param {Function} fn A new message transformer.
3600
+ * @returns {Primus}
3601
+ * @api public
3602
+ */
3603
+ Primus.prototype.transform = function transform(type, fn) {
3604
+ context(this, 'transform');
3605
+
3606
+ if (!(type in this.transformers)) {
3607
+ return this.critical(new Error('Invalid transformer type'));
3608
+ }
3609
+
3610
+ this.transformers[type].push(fn);
3611
+ return this;
3612
+ };
3613
+
3614
+ /**
3615
+ * A critical error has occurred, if we have an `error` listener, emit it there.
3616
+ * If not, throw it, so we get a stack trace + proper error message.
3617
+ *
3618
+ * @param {Error} err The critical error.
3619
+ * @returns {Primus}
3620
+ * @api private
3621
+ */
3622
+ Primus.prototype.critical = function critical(err) {
3623
+ if (this.emit('error', err)) return this;
3624
+
3625
+ throw err;
3626
+ };
3627
+
3628
+ /**
3629
+ * Syntax sugar, adopt a Socket.IO like API.
3630
+ *
3631
+ * @param {String} url The URL we want to connect to.
3632
+ * @param {Object} options Connection options.
3633
+ * @returns {Primus}
3634
+ * @api public
3635
+ */
3636
+ Primus.connect = function connect(url, options) {
3637
+ return new Primus(url, options);
3638
+ };
3639
+
3640
+ //
3641
+ // Expose the EventEmitter so it can be re-used by wrapping libraries we're also
3642
+ // exposing the Stream interface.
3643
+ //
3644
+ Primus.EventEmitter = EventEmitter;
3645
+
3646
+ //
3647
+ // These libraries are automatically inserted at the server-side using the
3648
+ // Primus#library method.
3649
+ //
3650
+ Primus.prototype.client = null; // @import {primus::client};
3651
+ Primus.prototype.authorization = null; // @import {primus::auth};
3652
+ Primus.prototype.pathname = null; // @import {primus::pathname};
3653
+ Primus.prototype.encoder = null; // @import {primus::encoder};
3654
+ Primus.prototype.decoder = null; // @import {primus::decoder};
3655
+ Primus.prototype.version = null; // @import {primus::version};
3656
+
3657
+ //
3658
+ // Expose the library.
3659
+ //
3660
+ module.exports = Primus;
3661
+
3662
+ },{"demolish":1,"emits":2,"eventemitter3":3,"inherits":4,"querystringify":8,"recovery":9,"tick-tock":12,"url-parse":14,"yeast":15}]},{},[16])(16)
3663
+ });