serverjs/vendor/eureca.io/js/primus.js

  1. (function UMDish(name, context, definition, plugins) {
  2. context[name] = definition.call(context);
  3. for (var i = 0; i < plugins.length; i++) {
  4. plugins[i](context[name])
  5. }
  6. if (typeof module !== "undefined" && module.exports) {
  7. module.exports = context[name];
  8. } else if (typeof define === "function" && define.amd) {
  9. define(function reference() { return context[name]; });
  10. }
  11. })("Primus", this || {}, function wrapper() {
  12. var define, module, exports
  13. , Primus = (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){
  14. 'use strict';
  15. /**
  16. * Create a function that will cleanup the instance.
  17. *
  18. * @param {Array|String} keys Properties on the instance that needs to be cleared.
  19. * @param {Object} options Additional configuration.
  20. * @returns {Function} Destroy function
  21. * @api public
  22. */
  23. module.exports = function demolish(keys, options) {
  24. var split = /[, ]+/;
  25. options = options || {};
  26. keys = keys || [];
  27. if ('string' === typeof keys) keys = keys.split(split);
  28. /**
  29. * Run addition cleanup hooks.
  30. *
  31. * @param {String} key Name of the clean up hook to run.
  32. * @param {Mixed} selfie Reference to the instance we're cleaning up.
  33. * @api private
  34. */
  35. function run(key, selfie) {
  36. if (!options[key]) return;
  37. if ('string' === typeof options[key]) options[key] = options[key].split(split);
  38. if ('function' === typeof options[key]) return options[key].call(selfie);
  39. for (var i = 0, type, what; i < options[key].length; i++) {
  40. what = options[key][i];
  41. type = typeof what;
  42. if ('function' === type) {
  43. what.call(selfie);
  44. } else if ('string' === type && 'function' === typeof selfie[what]) {
  45. selfie[what]();
  46. }
  47. }
  48. }
  49. /**
  50. * Destroy the instance completely and clean up all the existing references.
  51. *
  52. * @returns {Boolean}
  53. * @api public
  54. */
  55. return function destroy() {
  56. var selfie = this
  57. , i = 0
  58. , prop;
  59. if (selfie[keys[0]] === null) return false;
  60. run('before', selfie);
  61. for (; i < keys.length; i++) {
  62. prop = keys[i];
  63. if (selfie[prop]) {
  64. if ('function' === typeof selfie[prop].destroy) selfie[prop].destroy();
  65. selfie[prop] = null;
  66. }
  67. }
  68. if (selfie.emit) selfie.emit('destroy');
  69. run('after', selfie);
  70. return true;
  71. };
  72. };
  73. },{}],2:[function(_dereq_,module,exports){
  74. 'use strict';
  75. /**
  76. * Returns a function that when invoked executes all the listeners of the
  77. * given event with the given arguments.
  78. *
  79. * @returns {Function} The function that emits all the things.
  80. * @api public
  81. */
  82. module.exports = function emits() {
  83. var self = this
  84. , parser;
  85. for (var i = 0, l = arguments.length, args = new Array(l); i < l; i++) {
  86. args[i] = arguments[i];
  87. }
  88. //
  89. // If the last argument is a function, assume that it's a parser.
  90. //
  91. if ('function' !== typeof args[args.length - 1]) return function emitter() {
  92. for (var i = 0, l = arguments.length, arg = new Array(l); i < l; i++) {
  93. arg[i] = arguments[i];
  94. }
  95. return self.emit.apply(self, args.concat(arg));
  96. };
  97. parser = args.pop();
  98. /**
  99. * The actual function that emits the given event. It returns a boolean
  100. * indicating if the event was emitted.
  101. *
  102. * @returns {Boolean}
  103. * @api public
  104. */
  105. return function emitter() {
  106. for (var i = 0, l = arguments.length, arg = new Array(l + 1); i < l; i++) {
  107. arg[i + 1] = arguments[i];
  108. }
  109. /**
  110. * Async completion method for the parser.
  111. *
  112. * @param {Error} err Optional error when parsing failed.
  113. * @param {Mixed} returned Emit instructions.
  114. * @api private
  115. */
  116. arg[0] = function next(err, returned) {
  117. if (err) return self.emit('error', err);
  118. arg = returned === undefined
  119. ? arg.slice(1) : returned === null
  120. ? [] : returned;
  121. self.emit.apply(self, args.concat(arg));
  122. };
  123. parser.apply(self, arg);
  124. return true;
  125. };
  126. };
  127. },{}],3:[function(_dereq_,module,exports){
  128. 'use strict';
  129. var has = Object.prototype.hasOwnProperty
  130. , prefix = '~';
  131. /**
  132. * Constructor to create a storage for our `EE` objects.
  133. * An `Events` instance is a plain object whose properties are event names.
  134. *
  135. * @constructor
  136. * @private
  137. */
  138. function Events() {}
  139. //
  140. // We try to not inherit from `Object.prototype`. In some engines creating an
  141. // instance in this way is faster than calling `Object.create(null)` directly.
  142. // If `Object.create(null)` is not supported we prefix the event names with a
  143. // character to make sure that the built-in object properties are not
  144. // overridden or used as an attack vector.
  145. //
  146. if (Object.create) {
  147. Events.prototype = Object.create(null);
  148. //
  149. // This hack is needed because the `__proto__` property is still inherited in
  150. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  151. //
  152. if (!new Events().__proto__) prefix = false;
  153. }
  154. /**
  155. * Representation of a single event listener.
  156. *
  157. * @param {Function} fn The listener function.
  158. * @param {*} context The context to invoke the listener with.
  159. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  160. * @constructor
  161. * @private
  162. */
  163. function EE(fn, context, once) {
  164. this.fn = fn;
  165. this.context = context;
  166. this.once = once || false;
  167. }
  168. /**
  169. * Add a listener for a given event.
  170. *
  171. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  172. * @param {(String|Symbol)} event The event name.
  173. * @param {Function} fn The listener function.
  174. * @param {*} context The context to invoke the listener with.
  175. * @param {Boolean} once Specify if the listener is a one-time listener.
  176. * @returns {EventEmitter}
  177. * @private
  178. */
  179. function addListener(emitter, event, fn, context, once) {
  180. if (typeof fn !== 'function') {
  181. throw new TypeError('The listener must be a function');
  182. }
  183. var listener = new EE(fn, context || emitter, once)
  184. , evt = prefix ? prefix + event : event;
  185. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  186. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  187. else emitter._events[evt] = [emitter._events[evt], listener];
  188. return emitter;
  189. }
  190. /**
  191. * Clear event by name.
  192. *
  193. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  194. * @param {(String|Symbol)} evt The Event name.
  195. * @private
  196. */
  197. function clearEvent(emitter, evt) {
  198. if (--emitter._eventsCount === 0) emitter._events = new Events();
  199. else delete emitter._events[evt];
  200. }
  201. /**
  202. * Minimal `EventEmitter` interface that is molded against the Node.js
  203. * `EventEmitter` interface.
  204. *
  205. * @constructor
  206. * @public
  207. */
  208. function EventEmitter() {
  209. this._events = new Events();
  210. this._eventsCount = 0;
  211. }
  212. /**
  213. * Return an array listing the events for which the emitter has registered
  214. * listeners.
  215. *
  216. * @returns {Array}
  217. * @public
  218. */
  219. EventEmitter.prototype.eventNames = function eventNames() {
  220. var names = []
  221. , events
  222. , name;
  223. if (this._eventsCount === 0) return names;
  224. for (name in (events = this._events)) {
  225. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  226. }
  227. if (Object.getOwnPropertySymbols) {
  228. return names.concat(Object.getOwnPropertySymbols(events));
  229. }
  230. return names;
  231. };
  232. /**
  233. * Return the listeners registered for a given event.
  234. *
  235. * @param {(String|Symbol)} event The event name.
  236. * @returns {Array} The registered listeners.
  237. * @public
  238. */
  239. EventEmitter.prototype.listeners = function listeners(event) {
  240. var evt = prefix ? prefix + event : event
  241. , handlers = this._events[evt];
  242. if (!handlers) return [];
  243. if (handlers.fn) return [handlers.fn];
  244. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  245. ee[i] = handlers[i].fn;
  246. }
  247. return ee;
  248. };
  249. /**
  250. * Return the number of listeners listening to a given event.
  251. *
  252. * @param {(String|Symbol)} event The event name.
  253. * @returns {Number} The number of listeners.
  254. * @public
  255. */
  256. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  257. var evt = prefix ? prefix + event : event
  258. , listeners = this._events[evt];
  259. if (!listeners) return 0;
  260. if (listeners.fn) return 1;
  261. return listeners.length;
  262. };
  263. /**
  264. * Calls each of the listeners registered for a given event.
  265. *
  266. * @param {(String|Symbol)} event The event name.
  267. * @returns {Boolean} `true` if the event had listeners, else `false`.
  268. * @public
  269. */
  270. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  271. var evt = prefix ? prefix + event : event;
  272. if (!this._events[evt]) return false;
  273. var listeners = this._events[evt]
  274. , len = arguments.length
  275. , args
  276. , i;
  277. if (listeners.fn) {
  278. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  279. switch (len) {
  280. case 1: return listeners.fn.call(listeners.context), true;
  281. case 2: return listeners.fn.call(listeners.context, a1), true;
  282. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  283. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  284. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  285. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  286. }
  287. for (i = 1, args = new Array(len -1); i < len; i++) {
  288. args[i - 1] = arguments[i];
  289. }
  290. listeners.fn.apply(listeners.context, args);
  291. } else {
  292. var length = listeners.length
  293. , j;
  294. for (i = 0; i < length; i++) {
  295. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  296. switch (len) {
  297. case 1: listeners[i].fn.call(listeners[i].context); break;
  298. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  299. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  300. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  301. default:
  302. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  303. args[j - 1] = arguments[j];
  304. }
  305. listeners[i].fn.apply(listeners[i].context, args);
  306. }
  307. }
  308. }
  309. return true;
  310. };
  311. /**
  312. * Add a listener for a given event.
  313. *
  314. * @param {(String|Symbol)} event The event name.
  315. * @param {Function} fn The listener function.
  316. * @param {*} [context=this] The context to invoke the listener with.
  317. * @returns {EventEmitter} `this`.
  318. * @public
  319. */
  320. EventEmitter.prototype.on = function on(event, fn, context) {
  321. return addListener(this, event, fn, context, false);
  322. };
  323. /**
  324. * Add a one-time listener for a given event.
  325. *
  326. * @param {(String|Symbol)} event The event name.
  327. * @param {Function} fn The listener function.
  328. * @param {*} [context=this] The context to invoke the listener with.
  329. * @returns {EventEmitter} `this`.
  330. * @public
  331. */
  332. EventEmitter.prototype.once = function once(event, fn, context) {
  333. return addListener(this, event, fn, context, true);
  334. };
  335. /**
  336. * Remove the listeners of a given event.
  337. *
  338. * @param {(String|Symbol)} event The event name.
  339. * @param {Function} fn Only remove the listeners that match this function.
  340. * @param {*} context Only remove the listeners that have this context.
  341. * @param {Boolean} once Only remove one-time listeners.
  342. * @returns {EventEmitter} `this`.
  343. * @public
  344. */
  345. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  346. var evt = prefix ? prefix + event : event;
  347. if (!this._events[evt]) return this;
  348. if (!fn) {
  349. clearEvent(this, evt);
  350. return this;
  351. }
  352. var listeners = this._events[evt];
  353. if (listeners.fn) {
  354. if (
  355. listeners.fn === fn &&
  356. (!once || listeners.once) &&
  357. (!context || listeners.context === context)
  358. ) {
  359. clearEvent(this, evt);
  360. }
  361. } else {
  362. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  363. if (
  364. listeners[i].fn !== fn ||
  365. (once && !listeners[i].once) ||
  366. (context && listeners[i].context !== context)
  367. ) {
  368. events.push(listeners[i]);
  369. }
  370. }
  371. //
  372. // Reset the array, or remove it completely if we have no more listeners.
  373. //
  374. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  375. else clearEvent(this, evt);
  376. }
  377. return this;
  378. };
  379. /**
  380. * Remove all listeners, or those of the specified event.
  381. *
  382. * @param {(String|Symbol)} [event] The event name.
  383. * @returns {EventEmitter} `this`.
  384. * @public
  385. */
  386. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  387. var evt;
  388. if (event) {
  389. evt = prefix ? prefix + event : event;
  390. if (this._events[evt]) clearEvent(this, evt);
  391. } else {
  392. this._events = new Events();
  393. this._eventsCount = 0;
  394. }
  395. return this;
  396. };
  397. //
  398. // Alias methods names because people roll like that.
  399. //
  400. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  401. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  402. //
  403. // Expose the prefix.
  404. //
  405. EventEmitter.prefixed = prefix;
  406. //
  407. // Allow `EventEmitter` to be imported as module namespace.
  408. //
  409. EventEmitter.EventEmitter = EventEmitter;
  410. //
  411. // Expose the module.
  412. //
  413. if ('undefined' !== typeof module) {
  414. module.exports = EventEmitter;
  415. }
  416. },{}],4:[function(_dereq_,module,exports){
  417. if (typeof Object.create === 'function') {
  418. // implementation from standard node.js 'util' module
  419. module.exports = function inherits(ctor, superCtor) {
  420. if (superCtor) {
  421. ctor.super_ = superCtor
  422. ctor.prototype = Object.create(superCtor.prototype, {
  423. constructor: {
  424. value: ctor,
  425. enumerable: false,
  426. writable: true,
  427. configurable: true
  428. }
  429. })
  430. }
  431. };
  432. } else {
  433. // old school shim for old browsers
  434. module.exports = function inherits(ctor, superCtor) {
  435. if (superCtor) {
  436. ctor.super_ = superCtor
  437. var TempCtor = function () {}
  438. TempCtor.prototype = superCtor.prototype
  439. ctor.prototype = new TempCtor()
  440. ctor.prototype.constructor = ctor
  441. }
  442. }
  443. }
  444. },{}],5:[function(_dereq_,module,exports){
  445. 'use strict';
  446. var regex = new RegExp('^((?:\\d+)?\\.?\\d+) *('+ [
  447. 'milliseconds?',
  448. 'msecs?',
  449. 'ms',
  450. 'seconds?',
  451. 'secs?',
  452. 's',
  453. 'minutes?',
  454. 'mins?',
  455. 'm',
  456. 'hours?',
  457. 'hrs?',
  458. 'h',
  459. 'days?',
  460. 'd',
  461. 'weeks?',
  462. 'wks?',
  463. 'w',
  464. 'years?',
  465. 'yrs?',
  466. 'y'
  467. ].join('|') +')?$', 'i');
  468. var second = 1000
  469. , minute = second * 60
  470. , hour = minute * 60
  471. , day = hour * 24
  472. , week = day * 7
  473. , year = day * 365;
  474. /**
  475. * Parse a time string and return the number value of it.
  476. *
  477. * @param {String} ms Time string.
  478. * @returns {Number}
  479. * @api private
  480. */
  481. module.exports = function millisecond(ms) {
  482. var type = typeof ms
  483. , amount
  484. , match;
  485. if ('number' === type) return ms;
  486. else if ('string' !== type || '0' === ms || !ms) return 0;
  487. else if (+ms) return +ms;
  488. //
  489. // We are vulnerable to the regular expression denial of service (ReDoS).
  490. // In order to mitigate this we don't parse the input string if it is too long.
  491. // See https://nodesecurity.io/advisories/46.
  492. //
  493. if (ms.length > 10000 || !(match = regex.exec(ms))) return 0;
  494. amount = parseFloat(match[1]);
  495. switch (match[2].toLowerCase()) {
  496. case 'years':
  497. case 'year':
  498. case 'yrs':
  499. case 'yr':
  500. case 'y':
  501. return amount * year;
  502. case 'weeks':
  503. case 'week':
  504. case 'wks':
  505. case 'wk':
  506. case 'w':
  507. return amount * week;
  508. case 'days':
  509. case 'day':
  510. case 'd':
  511. return amount * day;
  512. case 'hours':
  513. case 'hour':
  514. case 'hrs':
  515. case 'hr':
  516. case 'h':
  517. return amount * hour;
  518. case 'minutes':
  519. case 'minute':
  520. case 'mins':
  521. case 'min':
  522. case 'm':
  523. return amount * minute;
  524. case 'seconds':
  525. case 'second':
  526. case 'secs':
  527. case 'sec':
  528. case 's':
  529. return amount * second;
  530. default:
  531. return amount;
  532. }
  533. };
  534. },{}],6:[function(_dereq_,module,exports){
  535. 'use strict';
  536. /**
  537. * Wrap callbacks to prevent double execution.
  538. *
  539. * @param {Function} fn Function that should only be called once.
  540. * @returns {Function} A wrapped callback which prevents execution.
  541. * @api public
  542. */
  543. module.exports = function one(fn) {
  544. var called = 0
  545. , value;
  546. /**
  547. * The function that prevents double execution.
  548. *
  549. * @api private
  550. */
  551. function onetime() {
  552. if (called) return value;
  553. called = 1;
  554. value = fn.apply(this, arguments);
  555. fn = null;
  556. return value;
  557. }
  558. //
  559. // To make debugging more easy we want to use the name of the supplied
  560. // function. So when you look at the functions that are assigned to event
  561. // listeners you don't see a load of `onetime` functions but actually the
  562. // names of the functions that this module will call.
  563. //
  564. onetime.displayName = fn.displayName || fn.name || onetime.displayName || onetime.name;
  565. return onetime;
  566. };
  567. },{}],7:[function(_dereq_,module,exports){
  568. // shim for using process in browser
  569. var process = module.exports = {};
  570. // cached from whatever global is present so that test runners that stub it
  571. // don't break things. But we need to wrap it in a try catch in case it is
  572. // wrapped in strict mode code which doesn't define any globals. It's inside a
  573. // function because try/catches deoptimize in certain engines.
  574. var cachedSetTimeout;
  575. var cachedClearTimeout;
  576. function defaultSetTimout() {
  577. throw new Error('setTimeout has not been defined');
  578. }
  579. function defaultClearTimeout () {
  580. throw new Error('clearTimeout has not been defined');
  581. }
  582. (function () {
  583. try {
  584. if (typeof setTimeout === 'function') {
  585. cachedSetTimeout = setTimeout;
  586. } else {
  587. cachedSetTimeout = defaultSetTimout;
  588. }
  589. } catch (e) {
  590. cachedSetTimeout = defaultSetTimout;
  591. }
  592. try {
  593. if (typeof clearTimeout === 'function') {
  594. cachedClearTimeout = clearTimeout;
  595. } else {
  596. cachedClearTimeout = defaultClearTimeout;
  597. }
  598. } catch (e) {
  599. cachedClearTimeout = defaultClearTimeout;
  600. }
  601. } ())
  602. function runTimeout(fun) {
  603. if (cachedSetTimeout === setTimeout) {
  604. //normal enviroments in sane situations
  605. return setTimeout(fun, 0);
  606. }
  607. // if setTimeout wasn't available but was latter defined
  608. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  609. cachedSetTimeout = setTimeout;
  610. return setTimeout(fun, 0);
  611. }
  612. try {
  613. // when when somebody has screwed with setTimeout but no I.E. maddness
  614. return cachedSetTimeout(fun, 0);
  615. } catch(e){
  616. try {
  617. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  618. return cachedSetTimeout.call(null, fun, 0);
  619. } catch(e){
  620. // 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
  621. return cachedSetTimeout.call(this, fun, 0);
  622. }
  623. }
  624. }
  625. function runClearTimeout(marker) {
  626. if (cachedClearTimeout === clearTimeout) {
  627. //normal enviroments in sane situations
  628. return clearTimeout(marker);
  629. }
  630. // if clearTimeout wasn't available but was latter defined
  631. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  632. cachedClearTimeout = clearTimeout;
  633. return clearTimeout(marker);
  634. }
  635. try {
  636. // when when somebody has screwed with setTimeout but no I.E. maddness
  637. return cachedClearTimeout(marker);
  638. } catch (e){
  639. try {
  640. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  641. return cachedClearTimeout.call(null, marker);
  642. } catch (e){
  643. // 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.
  644. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  645. return cachedClearTimeout.call(this, marker);
  646. }
  647. }
  648. }
  649. var queue = [];
  650. var draining = false;
  651. var currentQueue;
  652. var queueIndex = -1;
  653. function cleanUpNextTick() {
  654. if (!draining || !currentQueue) {
  655. return;
  656. }
  657. draining = false;
  658. if (currentQueue.length) {
  659. queue = currentQueue.concat(queue);
  660. } else {
  661. queueIndex = -1;
  662. }
  663. if (queue.length) {
  664. drainQueue();
  665. }
  666. }
  667. function drainQueue() {
  668. if (draining) {
  669. return;
  670. }
  671. var timeout = runTimeout(cleanUpNextTick);
  672. draining = true;
  673. var len = queue.length;
  674. while(len) {
  675. currentQueue = queue;
  676. queue = [];
  677. while (++queueIndex < len) {
  678. if (currentQueue) {
  679. currentQueue[queueIndex].run();
  680. }
  681. }
  682. queueIndex = -1;
  683. len = queue.length;
  684. }
  685. currentQueue = null;
  686. draining = false;
  687. runClearTimeout(timeout);
  688. }
  689. process.nextTick = function (fun) {
  690. var args = new Array(arguments.length - 1);
  691. if (arguments.length > 1) {
  692. for (var i = 1; i < arguments.length; i++) {
  693. args[i - 1] = arguments[i];
  694. }
  695. }
  696. queue.push(new Item(fun, args));
  697. if (queue.length === 1 && !draining) {
  698. runTimeout(drainQueue);
  699. }
  700. };
  701. // v8 likes predictible objects
  702. function Item(fun, array) {
  703. this.fun = fun;
  704. this.array = array;
  705. }
  706. Item.prototype.run = function () {
  707. this.fun.apply(null, this.array);
  708. };
  709. process.title = 'browser';
  710. process.browser = true;
  711. process.env = {};
  712. process.argv = [];
  713. process.version = ''; // empty string to avoid regexp issues
  714. process.versions = {};
  715. function noop() {}
  716. process.on = noop;
  717. process.addListener = noop;
  718. process.once = noop;
  719. process.off = noop;
  720. process.removeListener = noop;
  721. process.removeAllListeners = noop;
  722. process.emit = noop;
  723. process.prependListener = noop;
  724. process.prependOnceListener = noop;
  725. process.listeners = function (name) { return [] }
  726. process.binding = function (name) {
  727. throw new Error('process.binding is not supported');
  728. };
  729. process.cwd = function () { return '/' };
  730. process.chdir = function (dir) {
  731. throw new Error('process.chdir is not supported');
  732. };
  733. process.umask = function() { return 0; };
  734. },{}],8:[function(_dereq_,module,exports){
  735. 'use strict';
  736. var has = Object.prototype.hasOwnProperty
  737. , undef;
  738. /**
  739. * Decode a URI encoded string.
  740. *
  741. * @param {String} input The URI encoded string.
  742. * @returns {String|Null} The decoded string.
  743. * @api private
  744. */
  745. function decode(input) {
  746. try {
  747. return decodeURIComponent(input.replace(/\+/g, ' '));
  748. } catch (e) {
  749. return null;
  750. }
  751. }
  752. /**
  753. * Attempts to encode a given input.
  754. *
  755. * @param {String} input The string that needs to be encoded.
  756. * @returns {String|Null} The encoded string.
  757. * @api private
  758. */
  759. function encode(input) {
  760. try {
  761. return encodeURIComponent(input);
  762. } catch (e) {
  763. return null;
  764. }
  765. }
  766. /**
  767. * Simple query string parser.
  768. *
  769. * @param {String} query The query string that needs to be parsed.
  770. * @returns {Object}
  771. * @api public
  772. */
  773. function querystring(query) {
  774. var parser = /([^=?#&]+)=?([^&]*)/g
  775. , result = {}
  776. , part;
  777. while (part = parser.exec(query)) {
  778. var key = decode(part[1])
  779. , value = decode(part[2]);
  780. //
  781. // Prevent overriding of existing properties. This ensures that build-in
  782. // methods like `toString` or __proto__ are not overriden by malicious
  783. // querystrings.
  784. //
  785. // In the case if failed decoding, we want to omit the key/value pairs
  786. // from the result.
  787. //
  788. if (key === null || value === null || key in result) continue;
  789. result[key] = value;
  790. }
  791. return result;
  792. }
  793. /**
  794. * Transform a query string to an object.
  795. *
  796. * @param {Object} obj Object that should be transformed.
  797. * @param {String} prefix Optional prefix.
  798. * @returns {String}
  799. * @api public
  800. */
  801. function querystringify(obj, prefix) {
  802. prefix = prefix || '';
  803. var pairs = []
  804. , value
  805. , key;
  806. //
  807. // Optionally prefix with a '?' if needed
  808. //
  809. if ('string' !== typeof prefix) prefix = '?';
  810. for (key in obj) {
  811. if (has.call(obj, key)) {
  812. value = obj[key];
  813. //
  814. // Edge cases where we actually want to encode the value to an empty
  815. // string instead of the stringified value.
  816. //
  817. if (!value && (value === null || value === undef || isNaN(value))) {
  818. value = '';
  819. }
  820. key = encode(key);
  821. value = encode(value);
  822. //
  823. // If we failed to encode the strings, we should bail out as we don't
  824. // want to add invalid strings to the query.
  825. //
  826. if (key === null || value === null) continue;
  827. pairs.push(key +'='+ value);
  828. }
  829. }
  830. return pairs.length ? prefix + pairs.join('&') : '';
  831. }
  832. //
  833. // Expose the module.
  834. //
  835. exports.stringify = querystringify;
  836. exports.parse = querystring;
  837. },{}],9:[function(_dereq_,module,exports){
  838. 'use strict';
  839. var EventEmitter = _dereq_('eventemitter3')
  840. , millisecond = _dereq_('millisecond')
  841. , destroy = _dereq_('demolish')
  842. , Tick = _dereq_('tick-tock')
  843. , one = _dereq_('one-time');
  844. /**
  845. * Returns sane defaults about a given value.
  846. *
  847. * @param {String} name Name of property we want.
  848. * @param {Recovery} selfie Recovery instance that got created.
  849. * @param {Object} opts User supplied options we want to check.
  850. * @returns {Number} Some default value.
  851. * @api private
  852. */
  853. function defaults(name, selfie, opts) {
  854. return millisecond(
  855. name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
  856. );
  857. }
  858. /**
  859. * Attempt to recover your connection with reconnection attempt.
  860. *
  861. * @constructor
  862. * @param {Object} options Configuration
  863. * @api public
  864. */
  865. function Recovery(options) {
  866. var recovery = this;
  867. if (!(recovery instanceof Recovery)) return new Recovery(options);
  868. options = options || {};
  869. recovery.attempt = null; // Stores the current reconnect attempt.
  870. recovery._fn = null; // Stores the callback.
  871. recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
  872. recovery.retries = defaults('retries', recovery, options);
  873. recovery.factor = defaults('factor', recovery, options);
  874. recovery.max = defaults('max', recovery, options);
  875. recovery.min = defaults('min', recovery, options);
  876. recovery.timers = new Tick(recovery);
  877. }
  878. Recovery.prototype = new EventEmitter();
  879. Recovery.prototype.constructor = Recovery;
  880. Recovery['reconnect timeout'] = '30 seconds'; // Maximum time to wait for an answer.
  881. Recovery.max = Infinity; // Maximum delay.
  882. Recovery.min = '500 ms'; // Minimum delay.
  883. Recovery.retries = 10; // Maximum amount of retries.
  884. Recovery.factor = 2; // Exponential back off factor.
  885. /**
  886. * Start a new reconnect procedure.
  887. *
  888. * @returns {Recovery}
  889. * @api public
  890. */
  891. Recovery.prototype.reconnect = function reconnect() {
  892. var recovery = this;
  893. return recovery.backoff(function backedoff(err, opts) {
  894. opts.duration = (+new Date()) - opts.start;
  895. if (err) return recovery.emit('reconnect failed', err, opts);
  896. recovery.emit('reconnected', opts);
  897. }, recovery.attempt);
  898. };
  899. /**
  900. * Exponential back off algorithm for retry operations. It uses a randomized
  901. * retry so we don't DDOS our server when it goes down under pressure.
  902. *
  903. * @param {Function} fn Callback to be called after the timeout.
  904. * @param {Object} opts Options for configuring the timeout.
  905. * @returns {Recovery}
  906. * @api private
  907. */
  908. Recovery.prototype.backoff = function backoff(fn, opts) {
  909. var recovery = this;
  910. opts = opts || recovery.attempt || {};
  911. //
  912. // Bailout when we already have a back off process running. We shouldn't call
  913. // the callback then.
  914. //
  915. if (opts.backoff) return recovery;
  916. opts['reconnect timeout'] = defaults('reconnect timeout', recovery, opts);
  917. opts.retries = defaults('retries', recovery, opts);
  918. opts.factor = defaults('factor', recovery, opts);
  919. opts.max = defaults('max', recovery, opts);
  920. opts.min = defaults('min', recovery, opts);
  921. opts.start = +opts.start || +new Date();
  922. opts.duration = +opts.duration || 0;
  923. opts.attempt = +opts.attempt || 0;
  924. //
  925. // Bailout if we are about to make too much attempts.
  926. //
  927. if (opts.attempt === opts.retries) {
  928. fn.call(recovery, new Error('Unable to recover'), opts);
  929. return recovery;
  930. }
  931. //
  932. // Prevent duplicate back off attempts using the same options object and
  933. // increment our attempt as we're about to have another go at this thing.
  934. //
  935. opts.backoff = true;
  936. opts.attempt++;
  937. recovery.attempt = opts;
  938. //
  939. // Calculate the timeout, but make it randomly so we don't retry connections
  940. // at the same interval and defeat the purpose. This exponential back off is
  941. // based on the work of:
  942. //
  943. // http://dthain.blogspot.nl/2009/02/exponential-backoff-in-distributed.html
  944. //
  945. opts.scheduled = opts.attempt !== 1
  946. ? Math.min(Math.round(
  947. (Math.random() + 1) * opts.min * Math.pow(opts.factor, opts.attempt - 1)
  948. ), opts.max)
  949. : opts.min;
  950. recovery.timers.setTimeout('reconnect', function delay() {
  951. opts.duration = (+new Date()) - opts.start;
  952. opts.backoff = false;
  953. recovery.timers.clear('reconnect, timeout');
  954. //
  955. // Create a `one` function which can only be called once. So we can use the
  956. // same function for different types of invocations to create a much better
  957. // and usable API.
  958. //
  959. var connect = recovery._fn = one(function connect(err) {
  960. recovery.reset();
  961. if (err) return recovery.backoff(fn, opts);
  962. fn.call(recovery, undefined, opts);
  963. });
  964. recovery.emit('reconnect', opts, connect);
  965. recovery.timers.setTimeout('timeout', function timeout() {
  966. var err = new Error('Failed to reconnect in a timely manner');
  967. opts.duration = (+new Date()) - opts.start;
  968. recovery.emit('reconnect timeout', err, opts);
  969. connect(err);
  970. }, opts['reconnect timeout']);
  971. }, opts.scheduled);
  972. //
  973. // Emit a `reconnecting` event with current reconnect options. This allows
  974. // them to update the UI and provide their users with feedback.
  975. //
  976. recovery.emit('reconnect scheduled', opts);
  977. return recovery;
  978. };
  979. /**
  980. * Check if the reconnection process is currently reconnecting.
  981. *
  982. * @returns {Boolean}
  983. * @api public
  984. */
  985. Recovery.prototype.reconnecting = function reconnecting() {
  986. return !!this.attempt;
  987. };
  988. /**
  989. * Tell our reconnection procedure that we're passed.
  990. *
  991. * @param {Error} err Reconnection failed.
  992. * @returns {Recovery}
  993. * @api public
  994. */
  995. Recovery.prototype.reconnected = function reconnected(err) {
  996. if (this._fn) this._fn(err);
  997. return this;
  998. };
  999. /**
  1000. * Reset the reconnection attempt so it can be re-used again.
  1001. *
  1002. * @returns {Recovery}
  1003. * @api public
  1004. */
  1005. Recovery.prototype.reset = function reset() {
  1006. this._fn = this.attempt = null;
  1007. this.timers.clear('reconnect, timeout');
  1008. return this;
  1009. };
  1010. /**
  1011. * Clean up the instance.
  1012. *
  1013. * @type {Function}
  1014. * @returns {Boolean}
  1015. * @api public
  1016. */
  1017. Recovery.prototype.destroy = destroy('timers attempt _fn');
  1018. //
  1019. // Expose the module.
  1020. //
  1021. module.exports = Recovery;
  1022. },{"demolish":1,"eventemitter3":10,"millisecond":5,"one-time":6,"tick-tock":12}],10:[function(_dereq_,module,exports){
  1023. 'use strict';
  1024. //
  1025. // We store our EE objects in a plain object whose properties are event names.
  1026. // If `Object.create(null)` is not supported we prefix the event names with a
  1027. // `~` to make sure that the built-in object properties are not overridden or
  1028. // used as an attack vector.
  1029. // We also assume that `Object.create(null)` is available when the event name
  1030. // is an ES6 Symbol.
  1031. //
  1032. var prefix = typeof Object.create !== 'function' ? '~' : false;
  1033. /**
  1034. * Representation of a single EventEmitter function.
  1035. *
  1036. * @param {Function} fn Event handler to be called.
  1037. * @param {Mixed} context Context for function execution.
  1038. * @param {Boolean} once Only emit once
  1039. * @api private
  1040. */
  1041. function EE(fn, context, once) {
  1042. this.fn = fn;
  1043. this.context = context;
  1044. this.once = once || false;
  1045. }
  1046. /**
  1047. * Minimal EventEmitter interface that is molded against the Node.js
  1048. * EventEmitter interface.
  1049. *
  1050. * @constructor
  1051. * @api public
  1052. */
  1053. function EventEmitter() { /* Nothing to set */ }
  1054. /**
  1055. * Holds the assigned EventEmitters by name.
  1056. *
  1057. * @type {Object}
  1058. * @private
  1059. */
  1060. EventEmitter.prototype._events = undefined;
  1061. /**
  1062. * Return a list of assigned event listeners.
  1063. *
  1064. * @param {String} event The events that should be listed.
  1065. * @param {Boolean} exists We only need to know if there are listeners.
  1066. * @returns {Array|Boolean}
  1067. * @api public
  1068. */
  1069. EventEmitter.prototype.listeners = function listeners(event, exists) {
  1070. var evt = prefix ? prefix + event : event
  1071. , available = this._events && this._events[evt];
  1072. if (exists) return !!available;
  1073. if (!available) return [];
  1074. if (available.fn) return [available.fn];
  1075. for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
  1076. ee[i] = available[i].fn;
  1077. }
  1078. return ee;
  1079. };
  1080. /**
  1081. * Emit an event to all registered event listeners.
  1082. *
  1083. * @param {String} event The name of the event.
  1084. * @returns {Boolean} Indication if we've emitted an event.
  1085. * @api public
  1086. */
  1087. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  1088. var evt = prefix ? prefix + event : event;
  1089. if (!this._events || !this._events[evt]) return false;
  1090. var listeners = this._events[evt]
  1091. , len = arguments.length
  1092. , args
  1093. , i;
  1094. if ('function' === typeof listeners.fn) {
  1095. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  1096. switch (len) {
  1097. case 1: return listeners.fn.call(listeners.context), true;
  1098. case 2: return listeners.fn.call(listeners.context, a1), true;
  1099. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  1100. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  1101. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  1102. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  1103. }
  1104. for (i = 1, args = new Array(len -1); i < len; i++) {
  1105. args[i - 1] = arguments[i];
  1106. }
  1107. listeners.fn.apply(listeners.context, args);
  1108. } else {
  1109. var length = listeners.length
  1110. , j;
  1111. for (i = 0; i < length; i++) {
  1112. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  1113. switch (len) {
  1114. case 1: listeners[i].fn.call(listeners[i].context); break;
  1115. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  1116. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  1117. default:
  1118. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  1119. args[j - 1] = arguments[j];
  1120. }
  1121. listeners[i].fn.apply(listeners[i].context, args);
  1122. }
  1123. }
  1124. }
  1125. return true;
  1126. };
  1127. /**
  1128. * Register a new EventListener for the given event.
  1129. *
  1130. * @param {String} event Name of the event.
  1131. * @param {Functon} fn Callback function.
  1132. * @param {Mixed} context The context of the function.
  1133. * @api public
  1134. */
  1135. EventEmitter.prototype.on = function on(event, fn, context) {
  1136. var listener = new EE(fn, context || this)
  1137. , evt = prefix ? prefix + event : event;
  1138. if (!this._events) this._events = prefix ? {} : Object.create(null);
  1139. if (!this._events[evt]) this._events[evt] = listener;
  1140. else {
  1141. if (!this._events[evt].fn) this._events[evt].push(listener);
  1142. else this._events[evt] = [
  1143. this._events[evt], listener
  1144. ];
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Add an EventListener that's only called once.
  1150. *
  1151. * @param {String} event Name of the event.
  1152. * @param {Function} fn Callback function.
  1153. * @param {Mixed} context The context of the function.
  1154. * @api public
  1155. */
  1156. EventEmitter.prototype.once = function once(event, fn, context) {
  1157. var listener = new EE(fn, context || this, true)
  1158. , evt = prefix ? prefix + event : event;
  1159. if (!this._events) this._events = prefix ? {} : Object.create(null);
  1160. if (!this._events[evt]) this._events[evt] = listener;
  1161. else {
  1162. if (!this._events[evt].fn) this._events[evt].push(listener);
  1163. else this._events[evt] = [
  1164. this._events[evt], listener
  1165. ];
  1166. }
  1167. return this;
  1168. };
  1169. /**
  1170. * Remove event listeners.
  1171. *
  1172. * @param {String} event The event we want to remove.
  1173. * @param {Function} fn The listener that we need to find.
  1174. * @param {Mixed} context Only remove listeners matching this context.
  1175. * @param {Boolean} once Only remove once listeners.
  1176. * @api public
  1177. */
  1178. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  1179. var evt = prefix ? prefix + event : event;
  1180. if (!this._events || !this._events[evt]) return this;
  1181. var listeners = this._events[evt]
  1182. , events = [];
  1183. if (fn) {
  1184. if (listeners.fn) {
  1185. if (
  1186. listeners.fn !== fn
  1187. || (once && !listeners.once)
  1188. || (context && listeners.context !== context)
  1189. ) {
  1190. events.push(listeners);
  1191. }
  1192. } else {
  1193. for (var i = 0, length = listeners.length; i < length; i++) {
  1194. if (
  1195. listeners[i].fn !== fn
  1196. || (once && !listeners[i].once)
  1197. || (context && listeners[i].context !== context)
  1198. ) {
  1199. events.push(listeners[i]);
  1200. }
  1201. }
  1202. }
  1203. }
  1204. //
  1205. // Reset the array, or remove it completely if we have no more listeners.
  1206. //
  1207. if (events.length) {
  1208. this._events[evt] = events.length === 1 ? events[0] : events;
  1209. } else {
  1210. delete this._events[evt];
  1211. }
  1212. return this;
  1213. };
  1214. /**
  1215. * Remove all listeners or only the listeners for the specified event.
  1216. *
  1217. * @param {String} event The event want to remove all listeners for.
  1218. * @api public
  1219. */
  1220. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  1221. if (!this._events) return this;
  1222. if (event) delete this._events[prefix ? prefix + event : event];
  1223. else this._events = prefix ? {} : Object.create(null);
  1224. return this;
  1225. };
  1226. //
  1227. // Alias methods names because people roll like that.
  1228. //
  1229. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  1230. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  1231. //
  1232. // This function doesn't apply anymore.
  1233. //
  1234. EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
  1235. return this;
  1236. };
  1237. //
  1238. // Expose the prefix.
  1239. //
  1240. EventEmitter.prefixed = prefix;
  1241. //
  1242. // Expose the module.
  1243. //
  1244. if ('undefined' !== typeof module) {
  1245. module.exports = EventEmitter;
  1246. }
  1247. },{}],11:[function(_dereq_,module,exports){
  1248. 'use strict';
  1249. /**
  1250. * Check if we're required to add a port number.
  1251. *
  1252. * @see https://url.spec.whatwg.org/#default-port
  1253. * @param {Number|String} port Port number we need to check
  1254. * @param {String} protocol Protocol we need to check against.
  1255. * @returns {Boolean} Is it a default port for the given protocol
  1256. * @api private
  1257. */
  1258. module.exports = function required(port, protocol) {
  1259. protocol = protocol.split(':')[0];
  1260. port = +port;
  1261. if (!port) return false;
  1262. switch (protocol) {
  1263. case 'http':
  1264. case 'ws':
  1265. return port !== 80;
  1266. case 'https':
  1267. case 'wss':
  1268. return port !== 443;
  1269. case 'ftp':
  1270. return port !== 21;
  1271. case 'gopher':
  1272. return port !== 70;
  1273. case 'file':
  1274. return false;
  1275. }
  1276. return port !== 0;
  1277. };
  1278. },{}],12:[function(_dereq_,module,exports){
  1279. (function (setImmediate,clearImmediate){(function (){
  1280. 'use strict';
  1281. var has = Object.prototype.hasOwnProperty
  1282. , ms = _dereq_('millisecond');
  1283. /**
  1284. * Timer instance.
  1285. *
  1286. * @constructor
  1287. * @param {Object} timer New timer instance.
  1288. * @param {Function} clear Clears the timer instance.
  1289. * @param {Function} duration Duration of the timer.
  1290. * @param {Function} fn The functions that need to be executed.
  1291. * @api private
  1292. */
  1293. function Timer(timer, clear, duration, fn) {
  1294. this.start = +(new Date());
  1295. this.duration = duration;
  1296. this.clear = clear;
  1297. this.timer = timer;
  1298. this.fns = [fn];
  1299. }
  1300. /**
  1301. * Calculate the time left for a given timer.
  1302. *
  1303. * @returns {Number} Time in milliseconds.
  1304. * @api public
  1305. */
  1306. Timer.prototype.remaining = function remaining() {
  1307. return this.duration - this.taken();
  1308. };
  1309. /**
  1310. * Calculate the amount of time it has taken since we've set the timer.
  1311. *
  1312. * @returns {Number}
  1313. * @api public
  1314. */
  1315. Timer.prototype.taken = function taken() {
  1316. return +(new Date()) - this.start;
  1317. };
  1318. /**
  1319. * Custom wrappers for the various of clear{whatever} functions. We cannot
  1320. * invoke them directly as this will cause thrown errors in Google Chrome with
  1321. * an Illegal Invocation Error
  1322. *
  1323. * @see #2
  1324. * @type {Function}
  1325. * @api private
  1326. */
  1327. function unsetTimeout(id) { clearTimeout(id); }
  1328. function unsetInterval(id) { clearInterval(id); }
  1329. function unsetImmediate(id) { clearImmediate(id); }
  1330. /**
  1331. * Simple timer management.
  1332. *
  1333. * @constructor
  1334. * @param {Mixed} context Context of the callbacks that we execute.
  1335. * @api public
  1336. */
  1337. function Tick(context) {
  1338. if (!(this instanceof Tick)) return new Tick(context);
  1339. this.timers = {};
  1340. this.context = context || this;
  1341. }
  1342. /**
  1343. * Return a function which will just iterate over all assigned callbacks and
  1344. * optionally clear the timers from memory if needed.
  1345. *
  1346. * @param {String} name Name of the timer we need to execute.
  1347. * @param {Boolean} clear Also clear from memory.
  1348. * @returns {Function}
  1349. * @api private
  1350. */
  1351. Tick.prototype.tock = function ticktock(name, clear) {
  1352. var tock = this;
  1353. return function tickedtock() {
  1354. if (!(name in tock.timers)) return;
  1355. var timer = tock.timers[name]
  1356. , fns = timer.fns.slice()
  1357. , l = fns.length
  1358. , i = 0;
  1359. if (clear) tock.clear(name);
  1360. else tock.start = +new Date();
  1361. for (; i < l; i++) {
  1362. fns[i].call(tock.context);
  1363. }
  1364. };
  1365. };
  1366. /**
  1367. * Add a new timeout.
  1368. *
  1369. * @param {String} name Name of the timer.
  1370. * @param {Function} fn Completion callback.
  1371. * @param {Mixed} time Duration of the timer.
  1372. * @returns {Tick}
  1373. * @api public
  1374. */
  1375. Tick.prototype.setTimeout = function timeout(name, fn, time) {
  1376. var tick = this
  1377. , tock;
  1378. if (tick.timers[name]) {
  1379. tick.timers[name].fns.push(fn);
  1380. return tick;
  1381. }
  1382. tock = ms(time);
  1383. tick.timers[name] = new Timer(
  1384. setTimeout(tick.tock(name, true), ms(time)),
  1385. unsetTimeout,
  1386. tock,
  1387. fn
  1388. );
  1389. return tick;
  1390. };
  1391. /**
  1392. * Add a new interval.
  1393. *
  1394. * @param {String} name Name of the timer.
  1395. * @param {Function} fn Completion callback.
  1396. * @param {Mixed} time Interval of the timer.
  1397. * @returns {Tick}
  1398. * @api public
  1399. */
  1400. Tick.prototype.setInterval = function interval(name, fn, time) {
  1401. var tick = this
  1402. , tock;
  1403. if (tick.timers[name]) {
  1404. tick.timers[name].fns.push(fn);
  1405. return tick;
  1406. }
  1407. tock = ms(time);
  1408. tick.timers[name] = new Timer(
  1409. setInterval(tick.tock(name), ms(time)),
  1410. unsetInterval,
  1411. tock,
  1412. fn
  1413. );
  1414. return tick;
  1415. };
  1416. /**
  1417. * Add a new setImmediate.
  1418. *
  1419. * @param {String} name Name of the timer.
  1420. * @param {Function} fn Completion callback.
  1421. * @returns {Tick}
  1422. * @api public
  1423. */
  1424. Tick.prototype.setImmediate = function immediate(name, fn) {
  1425. var tick = this;
  1426. if ('function' !== typeof setImmediate) return tick.setTimeout(name, fn, 0);
  1427. if (tick.timers[name]) {
  1428. tick.timers[name].fns.push(fn);
  1429. return tick;
  1430. }
  1431. tick.timers[name] = new Timer(
  1432. setImmediate(tick.tock(name, true)),
  1433. unsetImmediate,
  1434. 0,
  1435. fn
  1436. );
  1437. return tick;
  1438. };
  1439. /**
  1440. * Check if we have a timer set.
  1441. *
  1442. * @param {String} name
  1443. * @returns {Boolean}
  1444. * @api public
  1445. */
  1446. Tick.prototype.active = function active(name) {
  1447. return name in this.timers;
  1448. };
  1449. /**
  1450. * Properly clean up all timeout references. If no arguments are supplied we
  1451. * will attempt to clear every single timer that is present.
  1452. *
  1453. * @param {Arguments} ..args.. The names of the timeouts we need to clear
  1454. * @returns {Tick}
  1455. * @api public
  1456. */
  1457. Tick.prototype.clear = function clear() {
  1458. var args = arguments.length ? arguments : []
  1459. , tick = this
  1460. , timer, i, l;
  1461. if (args.length === 1 && 'string' === typeof args[0]) {
  1462. args = args[0].split(/[, ]+/);
  1463. }
  1464. if (!args.length) {
  1465. for (timer in tick.timers) {
  1466. if (has.call(tick.timers, timer)) args.push(timer);
  1467. }
  1468. }
  1469. for (i = 0, l = args.length; i < l; i++) {
  1470. timer = tick.timers[args[i]];
  1471. if (!timer) continue;
  1472. timer.clear(timer.timer);
  1473. timer.fns = timer.timer = timer.clear = null;
  1474. delete tick.timers[args[i]];
  1475. }
  1476. return tick;
  1477. };
  1478. /**
  1479. * Adjust a timeout or interval to a new duration.
  1480. *
  1481. * @returns {Tick}
  1482. * @api public
  1483. */
  1484. Tick.prototype.adjust = function adjust(name, time) {
  1485. var interval
  1486. , tick = this
  1487. , tock = ms(time)
  1488. , timer = tick.timers[name];
  1489. if (!timer) return tick;
  1490. interval = timer.clear === unsetInterval;
  1491. timer.clear(timer.timer);
  1492. timer.start = +(new Date());
  1493. timer.duration = tock;
  1494. timer.timer = (interval ? setInterval : setTimeout)(tick.tock(name, !interval), tock);
  1495. return tick;
  1496. };
  1497. /**
  1498. * We will no longer use this module, prepare your self for global cleanups.
  1499. *
  1500. * @returns {Boolean}
  1501. * @api public
  1502. */
  1503. Tick.prototype.end = Tick.prototype.destroy = function end() {
  1504. if (!this.context) return false;
  1505. this.clear();
  1506. this.context = this.timers = null;
  1507. return true;
  1508. };
  1509. //
  1510. // Expose the timer factory.
  1511. //
  1512. Tick.Timer = Timer;
  1513. module.exports = Tick;
  1514. }).call(this)}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  1515. },{"millisecond":5,"timers":13}],13:[function(_dereq_,module,exports){
  1516. (function (setImmediate,clearImmediate){(function (){
  1517. var nextTick = _dereq_('process/browser.js').nextTick;
  1518. var apply = Function.prototype.apply;
  1519. var slice = Array.prototype.slice;
  1520. var immediateIds = {};
  1521. var nextImmediateId = 0;
  1522. // DOM APIs, for completeness
  1523. exports.setTimeout = function() {
  1524. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  1525. };
  1526. exports.setInterval = function() {
  1527. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  1528. };
  1529. exports.clearTimeout =
  1530. exports.clearInterval = function(timeout) { timeout.close(); };
  1531. function Timeout(id, clearFn) {
  1532. this._id = id;
  1533. this._clearFn = clearFn;
  1534. }
  1535. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  1536. Timeout.prototype.close = function() {
  1537. this._clearFn.call(window, this._id);
  1538. };
  1539. // Does not start the time, just sets up the members needed.
  1540. exports.enroll = function(item, msecs) {
  1541. clearTimeout(item._idleTimeoutId);
  1542. item._idleTimeout = msecs;
  1543. };
  1544. exports.unenroll = function(item) {
  1545. clearTimeout(item._idleTimeoutId);
  1546. item._idleTimeout = -1;
  1547. };
  1548. exports._unrefActive = exports.active = function(item) {
  1549. clearTimeout(item._idleTimeoutId);
  1550. var msecs = item._idleTimeout;
  1551. if (msecs >= 0) {
  1552. item._idleTimeoutId = setTimeout(function onTimeout() {
  1553. if (item._onTimeout)
  1554. item._onTimeout();
  1555. }, msecs);
  1556. }
  1557. };
  1558. // That's not how node.js implements it but the exposed api is the same.
  1559. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  1560. var id = nextImmediateId++;
  1561. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  1562. immediateIds[id] = true;
  1563. nextTick(function onNextTick() {
  1564. if (immediateIds[id]) {
  1565. // fn.call() is faster so we optimize for the common use-case
  1566. // @see http://jsperf.com/call-apply-segu
  1567. if (args) {
  1568. fn.apply(null, args);
  1569. } else {
  1570. fn.call(null);
  1571. }
  1572. // Prevent ids from leaking
  1573. exports.clearImmediate(id);
  1574. }
  1575. });
  1576. return id;
  1577. };
  1578. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  1579. delete immediateIds[id];
  1580. };
  1581. }).call(this)}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
  1582. },{"process/browser.js":7,"timers":13}],14:[function(_dereq_,module,exports){
  1583. (function (global){(function (){
  1584. 'use strict';
  1585. var required = _dereq_('requires-port')
  1586. , qs = _dereq_('querystringify')
  1587. , controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
  1588. , CRHTLF = /[\n\r\t]/g
  1589. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
  1590. , port = /:\d+$/
  1591. , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
  1592. , windowsDriveLetter = /^[a-zA-Z]:/;
  1593. /**
  1594. * Remove control characters and whitespace from the beginning of a string.
  1595. *
  1596. * @param {Object|String} str String to trim.
  1597. * @returns {String} A new string representing `str` stripped of control
  1598. * characters and whitespace from its beginning.
  1599. * @public
  1600. */
  1601. function trimLeft(str) {
  1602. return (str ? str : '').toString().replace(controlOrWhitespace, '');
  1603. }
  1604. /**
  1605. * These are the parse rules for the URL parser, it informs the parser
  1606. * about:
  1607. *
  1608. * 0. The char it Needs to parse, if it's a string it should be done using
  1609. * indexOf, RegExp using exec and NaN means set as current value.
  1610. * 1. The property we should set when parsing this value.
  1611. * 2. Indication if it's backwards or forward parsing, when set as number it's
  1612. * the value of extra chars that should be split off.
  1613. * 3. Inherit from location if non existing in the parser.
  1614. * 4. `toLowerCase` the resulting value.
  1615. */
  1616. var rules = [
  1617. ['#', 'hash'], // Extract from the back.
  1618. ['?', 'query'], // Extract from the back.
  1619. function sanitize(address, url) { // Sanitize what is left of the address
  1620. return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address;
  1621. },
  1622. ['/', 'pathname'], // Extract from the back.
  1623. ['@', 'auth', 1], // Extract from the front.
  1624. [NaN, 'host', undefined, 1, 1], // Set left over value.
  1625. [/:(\d*)$/, 'port', undefined, 1], // RegExp the back.
  1626. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  1627. ];
  1628. /**
  1629. * These properties should not be copied or inherited from. This is only needed
  1630. * for all non blob URL's as a blob URL does not include a hash, only the
  1631. * origin.
  1632. *
  1633. * @type {Object}
  1634. * @private
  1635. */
  1636. var ignore = { hash: 1, query: 1 };
  1637. /**
  1638. * The location object differs when your code is loaded through a normal page,
  1639. * Worker or through a worker using a blob. And with the blobble begins the
  1640. * trouble as the location object will contain the URL of the blob, not the
  1641. * location of the page where our code is loaded in. The actual origin is
  1642. * encoded in the `pathname` so we can thankfully generate a good "default"
  1643. * location from it so we can generate proper relative URL's again.
  1644. *
  1645. * @param {Object|String} loc Optional default location object.
  1646. * @returns {Object} lolcation object.
  1647. * @public
  1648. */
  1649. function lolcation(loc) {
  1650. var globalVar;
  1651. if (typeof window !== 'undefined') globalVar = window;
  1652. else if (typeof global !== 'undefined') globalVar = global;
  1653. else if (typeof self !== 'undefined') globalVar = self;
  1654. else globalVar = {};
  1655. var location = globalVar.location || {};
  1656. loc = loc || location;
  1657. var finaldestination = {}
  1658. , type = typeof loc
  1659. , key;
  1660. if ('blob:' === loc.protocol) {
  1661. finaldestination = new Url(unescape(loc.pathname), {});
  1662. } else if ('string' === type) {
  1663. finaldestination = new Url(loc, {});
  1664. for (key in ignore) delete finaldestination[key];
  1665. } else if ('object' === type) {
  1666. for (key in loc) {
  1667. if (key in ignore) continue;
  1668. finaldestination[key] = loc[key];
  1669. }
  1670. if (finaldestination.slashes === undefined) {
  1671. finaldestination.slashes = slashes.test(loc.href);
  1672. }
  1673. }
  1674. return finaldestination;
  1675. }
  1676. /**
  1677. * Check whether a protocol scheme is special.
  1678. *
  1679. * @param {String} The protocol scheme of the URL
  1680. * @return {Boolean} `true` if the protocol scheme is special, else `false`
  1681. * @private
  1682. */
  1683. function isSpecial(scheme) {
  1684. return (
  1685. scheme === 'file:' ||
  1686. scheme === 'ftp:' ||
  1687. scheme === 'http:' ||
  1688. scheme === 'https:' ||
  1689. scheme === 'ws:' ||
  1690. scheme === 'wss:'
  1691. );
  1692. }
  1693. /**
  1694. * @typedef ProtocolExtract
  1695. * @type Object
  1696. * @property {String} protocol Protocol matched in the URL, in lowercase.
  1697. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  1698. * @property {String} rest Rest of the URL that is not part of the protocol.
  1699. */
  1700. /**
  1701. * Extract protocol information from a URL with/without double slash ("//").
  1702. *
  1703. * @param {String} address URL we want to extract from.
  1704. * @param {Object} location
  1705. * @return {ProtocolExtract} Extracted information.
  1706. * @private
  1707. */
  1708. function extractProtocol(address, location) {
  1709. address = trimLeft(address);
  1710. address = address.replace(CRHTLF, '');
  1711. location = location || {};
  1712. var match = protocolre.exec(address);
  1713. var protocol = match[1] ? match[1].toLowerCase() : '';
  1714. var forwardSlashes = !!match[2];
  1715. var otherSlashes = !!match[3];
  1716. var slashesCount = 0;
  1717. var rest;
  1718. if (forwardSlashes) {
  1719. if (otherSlashes) {
  1720. rest = match[2] + match[3] + match[4];
  1721. slashesCount = match[2].length + match[3].length;
  1722. } else {
  1723. rest = match[2] + match[4];
  1724. slashesCount = match[2].length;
  1725. }
  1726. } else {
  1727. if (otherSlashes) {
  1728. rest = match[3] + match[4];
  1729. slashesCount = match[3].length;
  1730. } else {
  1731. rest = match[4]
  1732. }
  1733. }
  1734. if (protocol === 'file:') {
  1735. if (slashesCount >= 2) {
  1736. rest = rest.slice(2);
  1737. }
  1738. } else if (isSpecial(protocol)) {
  1739. rest = match[4];
  1740. } else if (protocol) {
  1741. if (forwardSlashes) {
  1742. rest = rest.slice(2);
  1743. }
  1744. } else if (slashesCount >= 2 && isSpecial(location.protocol)) {
  1745. rest = match[4];
  1746. }
  1747. return {
  1748. protocol: protocol,
  1749. slashes: forwardSlashes || isSpecial(protocol),
  1750. slashesCount: slashesCount,
  1751. rest: rest
  1752. };
  1753. }
  1754. /**
  1755. * Resolve a relative URL pathname against a base URL pathname.
  1756. *
  1757. * @param {String} relative Pathname of the relative URL.
  1758. * @param {String} base Pathname of the base URL.
  1759. * @return {String} Resolved pathname.
  1760. * @private
  1761. */
  1762. function resolve(relative, base) {
  1763. if (relative === '') return base;
  1764. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  1765. , i = path.length
  1766. , last = path[i - 1]
  1767. , unshift = false
  1768. , up = 0;
  1769. while (i--) {
  1770. if (path[i] === '.') {
  1771. path.splice(i, 1);
  1772. } else if (path[i] === '..') {
  1773. path.splice(i, 1);
  1774. up++;
  1775. } else if (up) {
  1776. if (i === 0) unshift = true;
  1777. path.splice(i, 1);
  1778. up--;
  1779. }
  1780. }
  1781. if (unshift) path.unshift('');
  1782. if (last === '.' || last === '..') path.push('');
  1783. return path.join('/');
  1784. }
  1785. /**
  1786. * The actual URL instance. Instead of returning an object we've opted-in to
  1787. * create an actual constructor as it's much more memory efficient and
  1788. * faster and it pleases my OCD.
  1789. *
  1790. * It is worth noting that we should not use `URL` as class name to prevent
  1791. * clashes with the global URL instance that got introduced in browsers.
  1792. *
  1793. * @constructor
  1794. * @param {String} address URL we want to parse.
  1795. * @param {Object|String} [location] Location defaults for relative paths.
  1796. * @param {Boolean|Function} [parser] Parser for the query string.
  1797. * @private
  1798. */
  1799. function Url(address, location, parser) {
  1800. address = trimLeft(address);
  1801. address = address.replace(CRHTLF, '');
  1802. if (!(this instanceof Url)) {
  1803. return new Url(address, location, parser);
  1804. }
  1805. var relative, extracted, parse, instruction, index, key
  1806. , instructions = rules.slice()
  1807. , type = typeof location
  1808. , url = this
  1809. , i = 0;
  1810. //
  1811. // The following if statements allows this module two have compatibility with
  1812. // 2 different API:
  1813. //
  1814. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  1815. // where the boolean indicates that the query string should also be parsed.
  1816. //
  1817. // 2. The `URL` interface of the browser which accepts a URL, object as
  1818. // arguments. The supplied object will be used as default values / fall-back
  1819. // for relative paths.
  1820. //
  1821. if ('object' !== type && 'string' !== type) {
  1822. parser = location;
  1823. location = null;
  1824. }
  1825. if (parser && 'function' !== typeof parser) parser = qs.parse;
  1826. location = lolcation(location);
  1827. //
  1828. // Extract protocol information before running the instructions.
  1829. //
  1830. extracted = extractProtocol(address || '', location);
  1831. relative = !extracted.protocol && !extracted.slashes;
  1832. url.slashes = extracted.slashes || relative && location.slashes;
  1833. url.protocol = extracted.protocol || location.protocol || '';
  1834. address = extracted.rest;
  1835. //
  1836. // When the authority component is absent the URL starts with a path
  1837. // component.
  1838. //
  1839. if (
  1840. extracted.protocol === 'file:' && (
  1841. extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||
  1842. (!extracted.slashes &&
  1843. (extracted.protocol ||
  1844. extracted.slashesCount < 2 ||
  1845. !isSpecial(url.protocol)))
  1846. ) {
  1847. instructions[3] = [/(.*)/, 'pathname'];
  1848. }
  1849. for (; i < instructions.length; i++) {
  1850. instruction = instructions[i];
  1851. if (typeof instruction === 'function') {
  1852. address = instruction(address, url);
  1853. continue;
  1854. }
  1855. parse = instruction[0];
  1856. key = instruction[1];
  1857. if (parse !== parse) {
  1858. url[key] = address;
  1859. } else if ('string' === typeof parse) {
  1860. index = parse === '@'
  1861. ? address.lastIndexOf(parse)
  1862. : address.indexOf(parse);
  1863. if (~index) {
  1864. if ('number' === typeof instruction[2]) {
  1865. url[key] = address.slice(0, index);
  1866. address = address.slice(index + instruction[2]);
  1867. } else {
  1868. url[key] = address.slice(index);
  1869. address = address.slice(0, index);
  1870. }
  1871. }
  1872. } else if ((index = parse.exec(address))) {
  1873. url[key] = index[1];
  1874. address = address.slice(0, index.index);
  1875. }
  1876. url[key] = url[key] || (
  1877. relative && instruction[3] ? location[key] || '' : ''
  1878. );
  1879. //
  1880. // Hostname, host and protocol should be lowercased so they can be used to
  1881. // create a proper `origin`.
  1882. //
  1883. if (instruction[4]) url[key] = url[key].toLowerCase();
  1884. }
  1885. //
  1886. // Also parse the supplied query string in to an object. If we're supplied
  1887. // with a custom parser as function use that instead of the default build-in
  1888. // parser.
  1889. //
  1890. if (parser) url.query = parser(url.query);
  1891. //
  1892. // If the URL is relative, resolve the pathname against the base URL.
  1893. //
  1894. if (
  1895. relative
  1896. && location.slashes
  1897. && url.pathname.charAt(0) !== '/'
  1898. && (url.pathname !== '' || location.pathname !== '')
  1899. ) {
  1900. url.pathname = resolve(url.pathname, location.pathname);
  1901. }
  1902. //
  1903. // Default to a / for pathname if none exists. This normalizes the URL
  1904. // to always have a /
  1905. //
  1906. if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {
  1907. url.pathname = '/' + url.pathname;
  1908. }
  1909. //
  1910. // We should not add port numbers if they are already the default port number
  1911. // for a given protocol. As the host also contains the port number we're going
  1912. // override it with the hostname which contains no port number.
  1913. //
  1914. if (!required(url.port, url.protocol)) {
  1915. url.host = url.hostname;
  1916. url.port = '';
  1917. }
  1918. //
  1919. // Parse down the `auth` for the username and password.
  1920. //
  1921. url.username = url.password = '';
  1922. if (url.auth) {
  1923. index = url.auth.indexOf(':');
  1924. if (~index) {
  1925. url.username = url.auth.slice(0, index);
  1926. url.username = encodeURIComponent(decodeURIComponent(url.username));
  1927. url.password = url.auth.slice(index + 1);
  1928. url.password = encodeURIComponent(decodeURIComponent(url.password))
  1929. } else {
  1930. url.username = encodeURIComponent(decodeURIComponent(url.auth));
  1931. }
  1932. url.auth = url.password ? url.username +':'+ url.password : url.username;
  1933. }
  1934. url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
  1935. ? url.protocol +'//'+ url.host
  1936. : 'null';
  1937. //
  1938. // The href is just the compiled result.
  1939. //
  1940. url.href = url.toString();
  1941. }
  1942. /**
  1943. * This is convenience method for changing properties in the URL instance to
  1944. * insure that they all propagate correctly.
  1945. *
  1946. * @param {String} part Property we need to adjust.
  1947. * @param {Mixed} value The newly assigned value.
  1948. * @param {Boolean|Function} fn When setting the query, it will be the function
  1949. * used to parse the query.
  1950. * When setting the protocol, double slash will be
  1951. * removed from the final url if it is true.
  1952. * @returns {URL} URL instance for chaining.
  1953. * @public
  1954. */
  1955. function set(part, value, fn) {
  1956. var url = this;
  1957. switch (part) {
  1958. case 'query':
  1959. if ('string' === typeof value && value.length) {
  1960. value = (fn || qs.parse)(value);
  1961. }
  1962. url[part] = value;
  1963. break;
  1964. case 'port':
  1965. url[part] = value;
  1966. if (!required(value, url.protocol)) {
  1967. url.host = url.hostname;
  1968. url[part] = '';
  1969. } else if (value) {
  1970. url.host = url.hostname +':'+ value;
  1971. }
  1972. break;
  1973. case 'hostname':
  1974. url[part] = value;
  1975. if (url.port) value += ':'+ url.port;
  1976. url.host = value;
  1977. break;
  1978. case 'host':
  1979. url[part] = value;
  1980. if (port.test(value)) {
  1981. value = value.split(':');
  1982. url.port = value.pop();
  1983. url.hostname = value.join(':');
  1984. } else {
  1985. url.hostname = value;
  1986. url.port = '';
  1987. }
  1988. break;
  1989. case 'protocol':
  1990. url.protocol = value.toLowerCase();
  1991. url.slashes = !fn;
  1992. break;
  1993. case 'pathname':
  1994. case 'hash':
  1995. if (value) {
  1996. var char = part === 'pathname' ? '/' : '#';
  1997. url[part] = value.charAt(0) !== char ? char + value : value;
  1998. } else {
  1999. url[part] = value;
  2000. }
  2001. break;
  2002. case 'username':
  2003. case 'password':
  2004. url[part] = encodeURIComponent(value);
  2005. break;
  2006. case 'auth':
  2007. var index = value.indexOf(':');
  2008. if (~index) {
  2009. url.username = value.slice(0, index);
  2010. url.username = encodeURIComponent(decodeURIComponent(url.username));
  2011. url.password = value.slice(index + 1);
  2012. url.password = encodeURIComponent(decodeURIComponent(url.password));
  2013. } else {
  2014. url.username = encodeURIComponent(decodeURIComponent(value));
  2015. }
  2016. }
  2017. for (var i = 0; i < rules.length; i++) {
  2018. var ins = rules[i];
  2019. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  2020. }
  2021. url.auth = url.password ? url.username +':'+ url.password : url.username;
  2022. url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
  2023. ? url.protocol +'//'+ url.host
  2024. : 'null';
  2025. url.href = url.toString();
  2026. return url;
  2027. }
  2028. /**
  2029. * Transform the properties back in to a valid and full URL string.
  2030. *
  2031. * @param {Function} stringify Optional query stringify function.
  2032. * @returns {String} Compiled version of the URL.
  2033. * @public
  2034. */
  2035. function toString(stringify) {
  2036. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  2037. var query
  2038. , url = this
  2039. , host = url.host
  2040. , protocol = url.protocol;
  2041. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  2042. var result =
  2043. protocol +
  2044. ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');
  2045. if (url.username) {
  2046. result += url.username;
  2047. if (url.password) result += ':'+ url.password;
  2048. result += '@';
  2049. } else if (url.password) {
  2050. result += ':'+ url.password;
  2051. result += '@';
  2052. } else if (
  2053. url.protocol !== 'file:' &&
  2054. isSpecial(url.protocol) &&
  2055. !host &&
  2056. url.pathname !== '/'
  2057. ) {
  2058. //
  2059. // Add back the empty userinfo, otherwise the original invalid URL
  2060. // might be transformed into a valid one with `url.pathname` as host.
  2061. //
  2062. result += '@';
  2063. }
  2064. //
  2065. // Trailing colon is removed from `url.host` when it is parsed. If it still
  2066. // ends with a colon, then add back the trailing colon that was removed. This
  2067. // prevents an invalid URL from being transformed into a valid one.
  2068. //
  2069. if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {
  2070. host += ':';
  2071. }
  2072. result += host + url.pathname;
  2073. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  2074. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  2075. if (url.hash) result += url.hash;
  2076. return result;
  2077. }
  2078. Url.prototype = { set: set, toString: toString };
  2079. //
  2080. // Expose the URL parser and some additional properties that might be useful for
  2081. // others or testing.
  2082. //
  2083. Url.extractProtocol = extractProtocol;
  2084. Url.location = lolcation;
  2085. Url.trimLeft = trimLeft;
  2086. Url.qs = qs;
  2087. module.exports = Url;
  2088. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2089. },{"querystringify":8,"requires-port":11}],15:[function(_dereq_,module,exports){
  2090. 'use strict';
  2091. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
  2092. , length = 64
  2093. , map = {}
  2094. , seed = 0
  2095. , i = 0
  2096. , prev;
  2097. /**
  2098. * Return a string representing the specified number.
  2099. *
  2100. * @param {Number} num The number to convert.
  2101. * @returns {String} The string representation of the number.
  2102. * @api public
  2103. */
  2104. function encode(num) {
  2105. var encoded = '';
  2106. do {
  2107. encoded = alphabet[num % length] + encoded;
  2108. num = Math.floor(num / length);
  2109. } while (num > 0);
  2110. return encoded;
  2111. }
  2112. /**
  2113. * Return the integer value specified by the given string.
  2114. *
  2115. * @param {String} str The string to convert.
  2116. * @returns {Number} The integer value represented by the string.
  2117. * @api public
  2118. */
  2119. function decode(str) {
  2120. var decoded = 0;
  2121. for (i = 0; i < str.length; i++) {
  2122. decoded = decoded * length + map[str.charAt(i)];
  2123. }
  2124. return decoded;
  2125. }
  2126. /**
  2127. * Yeast: A tiny growing id generator.
  2128. *
  2129. * @returns {String} A unique id.
  2130. * @api public
  2131. */
  2132. function yeast() {
  2133. var now = encode(+new Date());
  2134. if (now !== prev) return seed = 0, prev = now;
  2135. return now +'.'+ encode(seed++);
  2136. }
  2137. //
  2138. // Map each character to its index.
  2139. //
  2140. for (; i < length; i++) map[alphabet[i]] = i;
  2141. //
  2142. // Expose the `yeast`, `encode` and `decode` functions.
  2143. //
  2144. yeast.encode = encode;
  2145. yeast.decode = decode;
  2146. module.exports = yeast;
  2147. },{}],16:[function(_dereq_,module,exports){
  2148. /*globals require, define */
  2149. 'use strict';
  2150. var EventEmitter = _dereq_('eventemitter3')
  2151. , TickTock = _dereq_('tick-tock')
  2152. , Recovery = _dereq_('recovery')
  2153. , qs = _dereq_('querystringify')
  2154. , inherits = _dereq_('inherits')
  2155. , destroy = _dereq_('demolish')
  2156. , yeast = _dereq_('yeast')
  2157. , u2028 = /\u2028/g
  2158. , u2029 = /\u2029/g;
  2159. /**
  2160. * Context assertion, ensure that some of our public Primus methods are called
  2161. * with the correct context to ensure that
  2162. *
  2163. * @param {Primus} self The context of the function.
  2164. * @param {String} method The method name.
  2165. * @api private
  2166. */
  2167. function context(self, method) {
  2168. if (self instanceof Primus) return;
  2169. var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance');
  2170. if ('function' !== typeof self.listeners || !self.listeners('error').length) {
  2171. throw failure;
  2172. }
  2173. self.emit('error', failure);
  2174. }
  2175. //
  2176. // Sets the default connection URL, it uses the default origin of the browser
  2177. // when supported but degrades for older browsers. In Node.js, we cannot guess
  2178. // where the user wants to connect to, so we just default to localhost.
  2179. //
  2180. var defaultUrl;
  2181. try {
  2182. if (location.origin) {
  2183. defaultUrl = location.origin;
  2184. } else {
  2185. defaultUrl = location.protocol +'//'+ location.host;
  2186. }
  2187. } catch (e) {
  2188. defaultUrl = 'http://127.0.0.1';
  2189. }
  2190. /**
  2191. * Primus is a real-time library agnostic framework for establishing real-time
  2192. * connections with servers.
  2193. *
  2194. * Options:
  2195. * - reconnect, configuration for the reconnect process.
  2196. * - manual, don't automatically call `.open` to start the connection.
  2197. * - websockets, force the use of WebSockets, even when you should avoid them.
  2198. * - timeout, connect timeout, server didn't respond in a timely manner.
  2199. * - pingTimeout, The maximum amount of time to wait for the server to send a ping.
  2200. * - network, Use network events as leading method for network connection drops.
  2201. * - strategy, Reconnection strategies.
  2202. * - transport, Transport options.
  2203. * - url, uri, The URL to use connect with the server.
  2204. *
  2205. * @constructor
  2206. * @param {String} url The URL of your server.
  2207. * @param {Object} options The configuration.
  2208. * @api public
  2209. */
  2210. function Primus(url, options) {
  2211. if (!(this instanceof Primus)) return new Primus(url, options);
  2212. Primus.Stream.call(this);
  2213. if ('function' !== typeof this.client) {
  2214. return this.critical(new Error(
  2215. 'The client library has not been compiled correctly, see '+
  2216. 'https://github.com/primus/primus#client-library for more details'
  2217. ));
  2218. }
  2219. if ('object' === typeof url) {
  2220. options = url;
  2221. url = options.url || options.uri || defaultUrl;
  2222. } else {
  2223. options = options || {};
  2224. }
  2225. if ('ping' in options || 'pong' in options) {
  2226. return this.critical(new Error(
  2227. 'The `ping` and `pong` options have been removed'
  2228. ));
  2229. }
  2230. var primus = this;
  2231. // The maximum number of messages that can be placed in queue.
  2232. options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
  2233. // Connection timeout duration.
  2234. options.timeout = 'timeout' in options ? options.timeout : 10e3;
  2235. // Stores the back off configuration.
  2236. options.reconnect = 'reconnect' in options ? options.reconnect : {};
  2237. // Heartbeat ping interval.
  2238. options.pingTimeout = 'pingTimeout' in options ? options.pingTimeout : 45000;
  2239. // Reconnect strategies.
  2240. options.strategy = 'strategy' in options ? options.strategy : [];
  2241. // Custom transport options.
  2242. options.transport = 'transport' in options ? options.transport : {};
  2243. primus.buffer = []; // Stores premature send data.
  2244. primus.writable = true; // Silly stream compatibility.
  2245. primus.readable = true; // Silly stream compatibility.
  2246. primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
  2247. primus.readyState = Primus.CLOSED; // The readyState of the connection.
  2248. primus.options = options; // Reference to the supplied options.
  2249. primus.timers = new TickTock(this); // Contains all our timers.
  2250. primus.socket = null; // Reference to the internal connection.
  2251. primus.disconnect = false; // Did we receive a disconnect packet?
  2252. primus.transport = options.transport; // Transport options.
  2253. primus.transformers = { // Message transformers.
  2254. outgoing: [],
  2255. incoming: []
  2256. };
  2257. //
  2258. // Create our reconnection instance.
  2259. //
  2260. primus.recovery = new Recovery(options.reconnect);
  2261. //
  2262. // Parse the reconnection strategy. It can have the following strategies:
  2263. //
  2264. // - timeout: Reconnect when we have a network timeout.
  2265. // - disconnect: Reconnect when we have an unexpected disconnect.
  2266. // - online: Reconnect when we're back online.
  2267. //
  2268. if ('string' === typeof options.strategy) {
  2269. options.strategy = options.strategy.split(/\s?,\s?/g);
  2270. }
  2271. if (false === options.strategy) {
  2272. //
  2273. // Strategies are disabled, but we still need an empty array to join it in
  2274. // to nothing.
  2275. //
  2276. options.strategy = [];
  2277. } else if (!options.strategy.length) {
  2278. options.strategy.push('disconnect', 'online');
  2279. //
  2280. // Timeout based reconnection should only be enabled conditionally. When
  2281. // authorization is enabled it could trigger.
  2282. //
  2283. if (!this.authorization) options.strategy.push('timeout');
  2284. }
  2285. options.strategy = options.strategy.join(',').toLowerCase();
  2286. //
  2287. // Force the use of WebSockets, even when we've detected some potential
  2288. // broken WebSocket implementation.
  2289. //
  2290. if ('websockets' in options) {
  2291. primus.AVOID_WEBSOCKETS = !options.websockets;
  2292. }
  2293. //
  2294. // Force or disable the use of NETWORK events as leading client side
  2295. // disconnection detection.
  2296. //
  2297. if ('network' in options) {
  2298. primus.NETWORK_EVENTS = options.network;
  2299. }
  2300. //
  2301. // Check if the user wants to manually initialise a connection. If they don't,
  2302. // we want to do it after a really small timeout so we give the users enough
  2303. // time to listen for `error` events etc.
  2304. //
  2305. if (!options.manual) primus.timers.setTimeout('open', function open() {
  2306. primus.timers.clear('open');
  2307. primus.open();
  2308. }, 0);
  2309. primus.initialise(options);
  2310. }
  2311. /**
  2312. * Simple require wrapper to make browserify, node and require.js play nice.
  2313. *
  2314. * @param {String} name The module to require.
  2315. * @returns {Object|Undefined} The module that we required.
  2316. * @api private
  2317. */
  2318. Primus.requires = Primus.require = function requires(name) {
  2319. if ('function' !== typeof _dereq_) return undefined;
  2320. return !('function' === typeof define && define.amd)
  2321. ? _dereq_(name)
  2322. : undefined;
  2323. };
  2324. //
  2325. // It's possible that we're running in Node.js or in a Node.js compatible
  2326. // environment. In this cases we try to inherit from the Stream base class.
  2327. //
  2328. try {
  2329. Primus.Stream = Primus.requires('stream');
  2330. } catch (e) { }
  2331. if (!Primus.Stream) Primus.Stream = EventEmitter;
  2332. inherits(Primus, Primus.Stream);
  2333. /**
  2334. * Primus readyStates, used internally to set the correct ready state.
  2335. *
  2336. * @type {Number}
  2337. * @private
  2338. */
  2339. Primus.OPENING = 1; // We're opening the connection.
  2340. Primus.CLOSED = 2; // No active connection.
  2341. Primus.OPEN = 3; // The connection is open.
  2342. /**
  2343. * Are we working with a potentially broken WebSockets implementation? This
  2344. * boolean can be used by transformers to remove `WebSockets` from their
  2345. * supported transports.
  2346. *
  2347. * @type {Boolean}
  2348. * @private
  2349. */
  2350. Primus.prototype.AVOID_WEBSOCKETS = false;
  2351. /**
  2352. * Some browsers support registering emitting `online` and `offline` events when
  2353. * the connection has been dropped on the client. We're going to detect it in
  2354. * a simple `try {} catch (e) {}` statement so we don't have to do complicated
  2355. * feature detection.
  2356. *
  2357. * @type {Boolean}
  2358. * @private
  2359. */
  2360. Primus.prototype.NETWORK_EVENTS = false;
  2361. Primus.prototype.online = true;
  2362. try {
  2363. if (
  2364. Primus.prototype.NETWORK_EVENTS = 'onLine' in navigator
  2365. && (window.addEventListener || document.body.attachEvent)
  2366. ) {
  2367. if (!navigator.onLine) {
  2368. Primus.prototype.online = false;
  2369. }
  2370. }
  2371. } catch (e) { }
  2372. /**
  2373. * The Ark contains all our plugins definitions. It's namespaced by
  2374. * name => plugin.
  2375. *
  2376. * @type {Object}
  2377. * @private
  2378. */
  2379. Primus.prototype.ark = {};
  2380. /**
  2381. * Simple emit wrapper that returns a function that emits an event once it's
  2382. * called. This makes it easier for transports to emit specific events.
  2383. *
  2384. * @returns {Function} A function that will emit the event when called.
  2385. * @api public
  2386. */
  2387. Primus.prototype.emits = _dereq_('emits');
  2388. /**
  2389. * Return the given plugin.
  2390. *
  2391. * @param {String} name The name of the plugin.
  2392. * @returns {Object|undefined} The plugin or undefined.
  2393. * @api public
  2394. */
  2395. Primus.prototype.plugin = function plugin(name) {
  2396. context(this, 'plugin');
  2397. if (name) return this.ark[name];
  2398. var plugins = {};
  2399. for (name in this.ark) {
  2400. plugins[name] = this.ark[name];
  2401. }
  2402. return plugins;
  2403. };
  2404. /**
  2405. * Checks if the given event is an emitted event by Primus.
  2406. *
  2407. * @param {String} evt The event name.
  2408. * @returns {Boolean} Indication of the event is reserved for internal use.
  2409. * @api public
  2410. */
  2411. Primus.prototype.reserved = function reserved(evt) {
  2412. return (/^(incoming|outgoing)::/).test(evt)
  2413. || evt in this.reserved.events;
  2414. };
  2415. /**
  2416. * The actual events that are used by the client.
  2417. *
  2418. * @type {Object}
  2419. * @public
  2420. */
  2421. Primus.prototype.reserved.events = {
  2422. 'reconnect scheduled': 1,
  2423. 'reconnect timeout': 1,
  2424. 'readyStateChange': 1,
  2425. 'reconnect failed': 1,
  2426. 'reconnected': 1,
  2427. 'reconnect': 1,
  2428. 'offline': 1,
  2429. 'timeout': 1,
  2430. 'destroy': 1,
  2431. 'online': 1,
  2432. 'error': 1,
  2433. 'close': 1,
  2434. 'open': 1,
  2435. 'data': 1,
  2436. 'end': 1
  2437. };
  2438. /**
  2439. * Initialise the Primus and setup all parsers and internal listeners.
  2440. *
  2441. * @param {Object} options The original options object.
  2442. * @returns {Primus}
  2443. * @api private
  2444. */
  2445. Primus.prototype.initialise = function initialise(options) {
  2446. var primus = this;
  2447. primus.recovery
  2448. .on('reconnected', primus.emits('reconnected'))
  2449. .on('reconnect failed', primus.emits('reconnect failed', function failed(next) {
  2450. primus.emit('end');
  2451. next();
  2452. }))
  2453. .on('reconnect timeout', primus.emits('reconnect timeout'))
  2454. .on('reconnect scheduled', primus.emits('reconnect scheduled'))
  2455. .on('reconnect', primus.emits('reconnect', function reconnect(next) {
  2456. primus.emit('outgoing::reconnect');
  2457. next();
  2458. }));
  2459. primus.on('outgoing::open', function opening() {
  2460. var readyState = primus.readyState;
  2461. primus.readyState = Primus.OPENING;
  2462. if (readyState !== primus.readyState) {
  2463. primus.emit('readyStateChange', 'opening');
  2464. }
  2465. });
  2466. primus.on('incoming::open', function opened() {
  2467. var readyState = primus.readyState;
  2468. if (primus.recovery.reconnecting()) {
  2469. primus.recovery.reconnected();
  2470. }
  2471. //
  2472. // The connection has been opened so we should set our state to
  2473. // (writ|read)able so our stream compatibility works as intended.
  2474. //
  2475. primus.writable = true;
  2476. primus.readable = true;
  2477. //
  2478. // Make sure we are flagged as `online` as we've successfully opened the
  2479. // connection.
  2480. //
  2481. if (!primus.online) {
  2482. primus.online = true;
  2483. primus.emit('online');
  2484. }
  2485. primus.readyState = Primus.OPEN;
  2486. if (readyState !== primus.readyState) {
  2487. primus.emit('readyStateChange', 'open');
  2488. }
  2489. primus.heartbeat();
  2490. if (primus.buffer.length) {
  2491. var data = primus.buffer.slice()
  2492. , length = data.length
  2493. , i = 0;
  2494. primus.buffer.length = 0;
  2495. for (; i < length; i++) {
  2496. primus._write(data[i]);
  2497. }
  2498. }
  2499. primus.emit('open');
  2500. });
  2501. primus.on('incoming::ping', function ping(time) {
  2502. primus.online = true;
  2503. primus.heartbeat();
  2504. primus.emit('outgoing::pong', time);
  2505. primus._write('primus::pong::'+ time);
  2506. });
  2507. primus.on('incoming::error', function error(e) {
  2508. var connect = primus.timers.active('connect')
  2509. , err = e;
  2510. //
  2511. // When the error is not an Error instance we try to normalize it.
  2512. //
  2513. if ('string' === typeof e) {
  2514. err = new Error(e);
  2515. } else if (!(e instanceof Error) && 'object' === typeof e) {
  2516. //
  2517. // BrowserChannel and SockJS returns an object which contains some
  2518. // details of the error. In order to have a proper error we "copy" the
  2519. // details in an Error instance.
  2520. //
  2521. err = new Error(e.message || e.reason);
  2522. for (var key in e) {
  2523. if (Object.prototype.hasOwnProperty.call(e, key))
  2524. err[key] = e[key];
  2525. }
  2526. }
  2527. //
  2528. // We're still doing a reconnect attempt, it could be that we failed to
  2529. // connect because the server was down. Failing connect attempts should
  2530. // always emit an `error` event instead of a `open` event.
  2531. //
  2532. //
  2533. if (primus.recovery.reconnecting()) return primus.recovery.reconnected(err);
  2534. if (primus.listeners('error').length) primus.emit('error', err);
  2535. //
  2536. // We received an error while connecting, this most likely the result of an
  2537. // unauthorized access to the server.
  2538. //
  2539. if (connect) {
  2540. if (~primus.options.strategy.indexOf('timeout')) {
  2541. primus.recovery.reconnect();
  2542. } else {
  2543. primus.end();
  2544. }
  2545. }
  2546. });
  2547. primus.on('incoming::data', function message(raw) {
  2548. primus.decoder(raw, function decoding(err, data) {
  2549. //
  2550. // Do a "safe" emit('error') when we fail to parse a message. We don't
  2551. // want to throw here as listening to errors should be optional.
  2552. //
  2553. if (err) return primus.listeners('error').length && primus.emit('error', err);
  2554. //
  2555. // Handle all "primus::" prefixed protocol messages.
  2556. //
  2557. if (primus.protocol(data)) return;
  2558. primus.transforms(primus, primus, 'incoming', data, raw);
  2559. });
  2560. });
  2561. primus.on('incoming::end', function end() {
  2562. var readyState = primus.readyState;
  2563. //
  2564. // This `end` started with the receiving of a primus::server::close packet
  2565. // which indicated that the user/developer on the server closed the
  2566. // connection and it was not a result of a network disruption. So we should
  2567. // kill the connection without doing a reconnect.
  2568. //
  2569. if (primus.disconnect) {
  2570. primus.disconnect = false;
  2571. return primus.end();
  2572. }
  2573. //
  2574. // Always set the readyState to closed, and if we're still connecting, close
  2575. // the connection so we're sure that everything after this if statement block
  2576. // is only executed because our readyState is set to `open`.
  2577. //
  2578. primus.readyState = Primus.CLOSED;
  2579. if (readyState !== primus.readyState) {
  2580. primus.emit('readyStateChange', 'end');
  2581. }
  2582. if (primus.timers.active('connect')) primus.end();
  2583. if (readyState !== Primus.OPEN) {
  2584. return primus.recovery.reconnecting()
  2585. ? primus.recovery.reconnect()
  2586. : false;
  2587. }
  2588. this.writable = false;
  2589. this.readable = false;
  2590. //
  2591. // Clear all timers in case we're not going to reconnect.
  2592. //
  2593. this.timers.clear();
  2594. //
  2595. // Fire the `close` event as an indication of connection disruption.
  2596. // This is also fired by `primus#end` so it is emitted in all cases.
  2597. //
  2598. primus.emit('close');
  2599. //
  2600. // The disconnect was unintentional, probably because the server has
  2601. // shutdown, so if the reconnection is enabled start a reconnect procedure.
  2602. //
  2603. if (~primus.options.strategy.indexOf('disconnect')) {
  2604. return primus.recovery.reconnect();
  2605. }
  2606. primus.emit('outgoing::end');
  2607. primus.emit('end');
  2608. });
  2609. //
  2610. // Setup the real-time client.
  2611. //
  2612. primus.client();
  2613. //
  2614. // Process the potential plugins.
  2615. //
  2616. for (var plugin in primus.ark) {
  2617. primus.ark[plugin].call(primus, primus, options);
  2618. }
  2619. //
  2620. // NOTE: The following code is only required if we're supporting network
  2621. // events as it requires access to browser globals.
  2622. //
  2623. if (!primus.NETWORK_EVENTS) return primus;
  2624. /**
  2625. * Handler for offline notifications.
  2626. *
  2627. * @api private
  2628. */
  2629. primus.offlineHandler = function offline() {
  2630. if (!primus.online) return; // Already or still offline, bailout.
  2631. primus.online = false;
  2632. primus.emit('offline');
  2633. primus.end();
  2634. //
  2635. // It is certainly possible that we're in a reconnection loop and that the
  2636. // user goes offline. In this case we want to kill the existing attempt so
  2637. // when the user goes online, it will attempt to reconnect freshly again.
  2638. //
  2639. primus.recovery.reset();
  2640. };
  2641. /**
  2642. * Handler for online notifications.
  2643. *
  2644. * @api private
  2645. */
  2646. primus.onlineHandler = function online() {
  2647. if (primus.online) return; // Already or still online, bailout.
  2648. primus.online = true;
  2649. primus.emit('online');
  2650. if (~primus.options.strategy.indexOf('online')) {
  2651. primus.recovery.reconnect();
  2652. }
  2653. };
  2654. if (window.addEventListener) {
  2655. window.addEventListener('offline', primus.offlineHandler, false);
  2656. window.addEventListener('online', primus.onlineHandler, false);
  2657. } else if (document.body.attachEvent){
  2658. document.body.attachEvent('onoffline', primus.offlineHandler);
  2659. document.body.attachEvent('ononline', primus.onlineHandler);
  2660. }
  2661. return primus;
  2662. };
  2663. /**
  2664. * Really dead simple protocol parser. We simply assume that every message that
  2665. * is prefixed with `primus::` could be used as some sort of protocol definition
  2666. * for Primus.
  2667. *
  2668. * @param {String} msg The data.
  2669. * @returns {Boolean} Is a protocol message.
  2670. * @api private
  2671. */
  2672. Primus.prototype.protocol = function protocol(msg) {
  2673. if (
  2674. 'string' !== typeof msg
  2675. || msg.indexOf('primus::') !== 0
  2676. ) return false;
  2677. var last = msg.indexOf(':', 8)
  2678. , value = msg.slice(last + 2);
  2679. switch (msg.slice(8, last)) {
  2680. case 'ping':
  2681. this.emit('incoming::ping', +value);
  2682. break;
  2683. case 'server':
  2684. //
  2685. // The server is closing the connection, forcefully disconnect so we don't
  2686. // reconnect again.
  2687. //
  2688. if ('close' === value) {
  2689. this.disconnect = true;
  2690. }
  2691. break;
  2692. case 'id':
  2693. this.emit('incoming::id', value);
  2694. break;
  2695. //
  2696. // Unknown protocol, somebody is probably sending `primus::` prefixed
  2697. // messages.
  2698. //
  2699. default:
  2700. return false;
  2701. }
  2702. return true;
  2703. };
  2704. /**
  2705. * Execute the set of message transformers from Primus on the incoming or
  2706. * outgoing message.
  2707. * This function and it's content should be in sync with Spark#transforms in
  2708. * spark.js.
  2709. *
  2710. * @param {Primus} primus Reference to the Primus instance with message transformers.
  2711. * @param {Spark|Primus} connection Connection that receives or sends data.
  2712. * @param {String} type The type of message, 'incoming' or 'outgoing'.
  2713. * @param {Mixed} data The data to send or that has been received.
  2714. * @param {String} raw The raw encoded data.
  2715. * @returns {Primus}
  2716. * @api public
  2717. */
  2718. Primus.prototype.transforms = function transforms(primus, connection, type, data, raw) {
  2719. var packet = { data: data }
  2720. , fns = primus.transformers[type];
  2721. //
  2722. // Iterate in series over the message transformers so we can allow optional
  2723. // asynchronous execution of message transformers which could for example
  2724. // retrieve additional data from the server, do extra decoding or even
  2725. // message validation.
  2726. //
  2727. (function transform(index, done) {
  2728. var transformer = fns[index++];
  2729. if (!transformer) return done();
  2730. if (1 === transformer.length) {
  2731. if (false === transformer.call(connection, packet)) {
  2732. //
  2733. // When false is returned by an incoming transformer it means that's
  2734. // being handled by the transformer and we should not emit the `data`
  2735. // event.
  2736. //
  2737. return;
  2738. }
  2739. return transform(index, done);
  2740. }
  2741. transformer.call(connection, packet, function finished(err, arg) {
  2742. if (err) return connection.emit('error', err);
  2743. if (false === arg) return;
  2744. transform(index, done);
  2745. });
  2746. }(0, function done() {
  2747. //
  2748. // We always emit 2 arguments for the data event, the first argument is the
  2749. // parsed data and the second argument is the raw string that we received.
  2750. // This allows you, for example, to do some validation on the parsed data
  2751. // and then save the raw string in your database without the stringify
  2752. // overhead.
  2753. //
  2754. if ('incoming' === type) return connection.emit('data', packet.data, raw);
  2755. connection._write(packet.data);
  2756. }));
  2757. return this;
  2758. };
  2759. /**
  2760. * Retrieve the current id from the server.
  2761. *
  2762. * @param {Function} fn Callback function.
  2763. * @returns {Primus}
  2764. * @api public
  2765. */
  2766. Primus.prototype.id = function id(fn) {
  2767. if (this.socket && this.socket.id) return fn(this.socket.id);
  2768. this._write('primus::id::');
  2769. return this.once('incoming::id', fn);
  2770. };
  2771. /**
  2772. * Establish a connection with the server. When this function is called we
  2773. * assume that we don't have any open connections. If you do call it when you
  2774. * have a connection open, it could cause duplicate connections.
  2775. *
  2776. * @returns {Primus}
  2777. * @api public
  2778. */
  2779. Primus.prototype.open = function open() {
  2780. context(this, 'open');
  2781. //
  2782. // Only start a `connection timeout` procedure if we're not reconnecting as
  2783. // that shouldn't count as an initial connection. This should be started
  2784. // before the connection is opened to capture failing connections and kill the
  2785. // timeout.
  2786. //
  2787. if (!this.recovery.reconnecting() && this.options.timeout) this.timeout();
  2788. this.emit('outgoing::open');
  2789. return this;
  2790. };
  2791. /**
  2792. * Send a new message.
  2793. *
  2794. * @param {Mixed} data The data that needs to be written.
  2795. * @returns {Boolean} Always returns true as we don't support back pressure.
  2796. * @api public
  2797. */
  2798. Primus.prototype.write = function write(data) {
  2799. context(this, 'write');
  2800. this.transforms(this, this, 'outgoing', data);
  2801. return true;
  2802. };
  2803. /**
  2804. * The actual message writer.
  2805. *
  2806. * @param {Mixed} data The message that needs to be written.
  2807. * @returns {Boolean} Successful write to the underlaying transport.
  2808. * @api private
  2809. */
  2810. Primus.prototype._write = function write(data) {
  2811. var primus = this;
  2812. //
  2813. // The connection is closed, normally this would already be done in the
  2814. // `spark.write` method, but as `_write` is used internally, we should also
  2815. // add the same check here to prevent potential crashes by writing to a dead
  2816. // socket.
  2817. //
  2818. if (Primus.OPEN !== primus.readyState) {
  2819. //
  2820. // If the buffer is at capacity, remove the first item.
  2821. //
  2822. if (this.buffer.length === this.options.queueSize) {
  2823. this.buffer.splice(0, 1);
  2824. }
  2825. this.buffer.push(data);
  2826. return false;
  2827. }
  2828. primus.encoder(data, function encoded(err, packet) {
  2829. //
  2830. // Do a "safe" emit('error') when we fail to parse a message. We don't
  2831. // want to throw here as listening to errors should be optional.
  2832. //
  2833. if (err) return primus.listeners('error').length && primus.emit('error', err);
  2834. //
  2835. // Hack 1: \u2028 and \u2029 are allowed inside a JSON string, but JavaScript
  2836. // defines them as newline separators. Unescaped control characters are not
  2837. // allowed inside JSON strings, so this causes an error at parse time. We
  2838. // work around this issue by escaping these characters. This can cause
  2839. // errors with JSONP requests or if the string is just evaluated.
  2840. //
  2841. if ('string' === typeof packet) {
  2842. if (~packet.indexOf('\u2028')) packet = packet.replace(u2028, '\\u2028');
  2843. if (~packet.indexOf('\u2029')) packet = packet.replace(u2029, '\\u2029');
  2844. }
  2845. primus.emit('outgoing::data', packet);
  2846. });
  2847. return true;
  2848. };
  2849. /**
  2850. * Set a timer that, upon expiration, closes the client.
  2851. *
  2852. * @returns {Primus}
  2853. * @api private
  2854. */
  2855. Primus.prototype.heartbeat = function heartbeat() {
  2856. if (!this.options.pingTimeout) return this;
  2857. this.timers.clear('heartbeat');
  2858. this.timers.setTimeout('heartbeat', function expired() {
  2859. //
  2860. // The network events already captured the offline event.
  2861. //
  2862. if (!this.online) return;
  2863. this.online = false;
  2864. this.emit('offline');
  2865. this.emit('incoming::end');
  2866. }, this.options.pingTimeout);
  2867. return this;
  2868. };
  2869. /**
  2870. * Start a connection timeout.
  2871. *
  2872. * @returns {Primus}
  2873. * @api private
  2874. */
  2875. Primus.prototype.timeout = function timeout() {
  2876. var primus = this;
  2877. /**
  2878. * Remove all references to the timeout listener as we've received an event
  2879. * that can be used to determine state.
  2880. *
  2881. * @api private
  2882. */
  2883. function remove() {
  2884. primus.removeListener('error', remove)
  2885. .removeListener('open', remove)
  2886. .removeListener('end', remove)
  2887. .timers.clear('connect');
  2888. }
  2889. primus.timers.setTimeout('connect', function expired() {
  2890. remove(); // Clean up old references.
  2891. if (primus.readyState === Primus.OPEN || primus.recovery.reconnecting()) {
  2892. return;
  2893. }
  2894. primus.emit('timeout');
  2895. //
  2896. // We failed to connect to the server.
  2897. //
  2898. if (~primus.options.strategy.indexOf('timeout')) {
  2899. primus.recovery.reconnect();
  2900. } else {
  2901. primus.end();
  2902. }
  2903. }, primus.options.timeout);
  2904. return primus.on('error', remove)
  2905. .on('open', remove)
  2906. .on('end', remove);
  2907. };
  2908. /**
  2909. * Close the connection completely.
  2910. *
  2911. * @param {Mixed} data last packet of data.
  2912. * @returns {Primus}
  2913. * @api public
  2914. */
  2915. Primus.prototype.end = function end(data) {
  2916. context(this, 'end');
  2917. if (
  2918. this.readyState === Primus.CLOSED
  2919. && !this.timers.active('connect')
  2920. && !this.timers.active('open')
  2921. ) {
  2922. //
  2923. // If we are reconnecting stop the reconnection procedure.
  2924. //
  2925. if (this.recovery.reconnecting()) {
  2926. this.recovery.reset();
  2927. this.emit('end');
  2928. }
  2929. return this;
  2930. }
  2931. if (data !== undefined) this.write(data);
  2932. this.writable = false;
  2933. this.readable = false;
  2934. var readyState = this.readyState;
  2935. this.readyState = Primus.CLOSED;
  2936. if (readyState !== this.readyState) {
  2937. this.emit('readyStateChange', 'end');
  2938. }
  2939. this.timers.clear();
  2940. this.emit('outgoing::end');
  2941. this.emit('close');
  2942. this.emit('end');
  2943. return this;
  2944. };
  2945. /**
  2946. * Completely demolish the Primus instance and forcefully nuke all references.
  2947. *
  2948. * @returns {Boolean}
  2949. * @api public
  2950. */
  2951. Primus.prototype.destroy = destroy('url timers options recovery socket transport transformers', {
  2952. before: 'end',
  2953. after: ['removeAllListeners', function detach() {
  2954. if (!this.NETWORK_EVENTS) return;
  2955. if (window.addEventListener) {
  2956. window.removeEventListener('offline', this.offlineHandler);
  2957. window.removeEventListener('online', this.onlineHandler);
  2958. } else if (document.body.attachEvent){
  2959. document.body.detachEvent('onoffline', this.offlineHandler);
  2960. document.body.detachEvent('ononline', this.onlineHandler);
  2961. }
  2962. }]
  2963. });
  2964. /**
  2965. * Create a shallow clone of a given object.
  2966. *
  2967. * @param {Object} obj The object that needs to be cloned.
  2968. * @returns {Object} Copy.
  2969. * @api private
  2970. */
  2971. Primus.prototype.clone = function clone(obj) {
  2972. return this.merge({}, obj);
  2973. };
  2974. /**
  2975. * Merge different objects in to one target object.
  2976. *
  2977. * @param {Object} target The object where everything should be merged in.
  2978. * @returns {Object} Original target with all merged objects.
  2979. * @api private
  2980. */
  2981. Primus.prototype.merge = function merge(target) {
  2982. for (var i = 1, key, obj; i < arguments.length; i++) {
  2983. obj = arguments[i];
  2984. for (key in obj) {
  2985. if (Object.prototype.hasOwnProperty.call(obj, key))
  2986. target[key] = obj[key];
  2987. }
  2988. }
  2989. return target;
  2990. };
  2991. /**
  2992. * Parse the connection string.
  2993. *
  2994. * @type {Function}
  2995. * @param {String} url Connection URL.
  2996. * @returns {Object} Parsed connection.
  2997. * @api private
  2998. */
  2999. Primus.prototype.parse = _dereq_('url-parse');
  3000. /**
  3001. * Parse a query string.
  3002. *
  3003. * @param {String} query The query string that needs to be parsed.
  3004. * @returns {Object} Parsed query string.
  3005. * @api private
  3006. */
  3007. Primus.prototype.querystring = qs.parse;
  3008. /**
  3009. * Transform a query string object back into string equiv.
  3010. *
  3011. * @param {Object} obj The query string object.
  3012. * @returns {String}
  3013. * @api private
  3014. */
  3015. Primus.prototype.querystringify = qs.stringify;
  3016. /**
  3017. * Generates a connection URI.
  3018. *
  3019. * @param {String} protocol The protocol that should used to crate the URI.
  3020. * @returns {String|options} The URL.
  3021. * @api private
  3022. */
  3023. Primus.prototype.uri = function uri(options) {
  3024. var url = this.url
  3025. , server = []
  3026. , qsa = false;
  3027. //
  3028. // Query strings are only allowed when we've received clearance for it.
  3029. //
  3030. if (options.query) qsa = true;
  3031. options = options || {};
  3032. options.protocol = 'protocol' in options
  3033. ? options.protocol
  3034. : 'http:';
  3035. options.query = url.query && qsa
  3036. ? url.query.slice(1)
  3037. : false;
  3038. options.secure = 'secure' in options
  3039. ? options.secure
  3040. : url.protocol === 'https:' || url.protocol === 'wss:';
  3041. options.auth = 'auth' in options
  3042. ? options.auth
  3043. : url.auth;
  3044. options.pathname = 'pathname' in options
  3045. ? options.pathname
  3046. : this.pathname;
  3047. options.port = 'port' in options
  3048. ? +options.port
  3049. : +url.port || (options.secure ? 443 : 80);
  3050. //
  3051. // We need to make sure that we create a unique connection URL every time to
  3052. // prevent back forward cache from becoming an issue. We're doing this by
  3053. // forcing an cache busting query string in to the URL.
  3054. //
  3055. var querystring = this.querystring(options.query || '');
  3056. querystring._primuscb = yeast();
  3057. options.query = this.querystringify(querystring);
  3058. //
  3059. // Allow transformation of the options before we construct a full URL from it.
  3060. //
  3061. this.emit('outgoing::url', options);
  3062. //
  3063. // Automatically suffix the protocol so we can supply `ws:` and `http:` and
  3064. // it gets transformed correctly.
  3065. //
  3066. server.push(options.secure ? options.protocol.replace(':', 's:') : options.protocol, '');
  3067. server.push(options.auth ? options.auth +'@'+ url.host : url.host);
  3068. //
  3069. // Pathnames are optional as some Transformers would just use the pathname
  3070. // directly.
  3071. //
  3072. if (options.pathname) server.push(options.pathname.slice(1));
  3073. //
  3074. // Optionally add a search query.
  3075. //
  3076. if (qsa) server[server.length - 1] += '?'+ options.query;
  3077. else delete options.query;
  3078. if (options.object) return options;
  3079. return server.join('/');
  3080. };
  3081. /**
  3082. * Register a new message transformer. This allows you to easily manipulate incoming
  3083. * and outgoing data which is particularity handy for plugins that want to send
  3084. * meta data together with the messages.
  3085. *
  3086. * @param {String} type Incoming or outgoing
  3087. * @param {Function} fn A new message transformer.
  3088. * @returns {Primus}
  3089. * @api public
  3090. */
  3091. Primus.prototype.transform = function transform(type, fn) {
  3092. context(this, 'transform');
  3093. if (!(type in this.transformers)) {
  3094. return this.critical(new Error('Invalid transformer type'));
  3095. }
  3096. this.transformers[type].push(fn);
  3097. return this;
  3098. };
  3099. /**
  3100. * A critical error has occurred, if we have an `error` listener, emit it there.
  3101. * If not, throw it, so we get a stack trace + proper error message.
  3102. *
  3103. * @param {Error} err The critical error.
  3104. * @returns {Primus}
  3105. * @api private
  3106. */
  3107. Primus.prototype.critical = function critical(err) {
  3108. if (this.emit('error', err)) return this;
  3109. throw err;
  3110. };
  3111. /**
  3112. * Syntax sugar, adopt a Socket.IO like API.
  3113. *
  3114. * @param {String} url The URL we want to connect to.
  3115. * @param {Object} options Connection options.
  3116. * @returns {Primus}
  3117. * @api public
  3118. */
  3119. Primus.connect = function connect(url, options) {
  3120. return new Primus(url, options);
  3121. };
  3122. //
  3123. // Expose the EventEmitter so it can be re-used by wrapping libraries we're also
  3124. // exposing the Stream interface.
  3125. //
  3126. Primus.EventEmitter = EventEmitter;
  3127. //
  3128. // These libraries are automatically inserted at the server-side using the
  3129. // Primus#library method.
  3130. //
  3131. Primus.prototype.client = function client() {
  3132. var onmessage = this.emits('incoming::data')
  3133. , onerror = this.emits('incoming::error')
  3134. , onopen = this.emits('incoming::open')
  3135. , onclose = this.emits('incoming::end')
  3136. , primus = this
  3137. , socket;
  3138. //
  3139. // Select an available Engine.IO factory.
  3140. //
  3141. var factory = (function factory() {
  3142. if ('undefined' !== typeof eio) return eio;
  3143. try {
  3144. var Socket = Primus.requires('engine.io-client').Socket;
  3145. return function eio(options) {
  3146. return new Socket(options);
  3147. }
  3148. } catch (e) {}
  3149. return undefined;
  3150. })();
  3151. if (!factory) return primus.critical(new Error(
  3152. 'Missing required `engine.io-client` module. ' +
  3153. 'Please run `npm install --save engine.io-client`'
  3154. ));
  3155. //
  3156. // Connect to the given URL.
  3157. //
  3158. primus.on('outgoing::open', function opening() {
  3159. primus.emit('outgoing::end');
  3160. primus.socket = socket = factory(primus.merge(primus.transport,
  3161. primus.url,
  3162. primus.uri({ protocol: 'http:', query: true, object: true }), {
  3163. //
  3164. // Never remember upgrades as switching from a WIFI to a 3G connection
  3165. // could still get your connection blocked as 3G connections are usually
  3166. // behind a reverse proxy so ISP's can optimize mobile traffic by
  3167. // caching requests.
  3168. //
  3169. rememberUpgrade: false,
  3170. //
  3171. // Binary support in Engine.IO breaks a shit things. Turn it off for now.
  3172. //
  3173. forceBase64: true,
  3174. //
  3175. // Force timestamps on every single connection. Engine.IO only does this
  3176. // for polling by default, but WebSockets require an explicit `true`
  3177. // boolean.
  3178. //
  3179. timestampRequests: true,
  3180. path: this.pathname,
  3181. transports: !primus.AVOID_WEBSOCKETS
  3182. ? ['polling', 'websocket']
  3183. : ['polling']
  3184. }));
  3185. //
  3186. // Setup the Event handlers.
  3187. //
  3188. socket.on('message', onmessage);
  3189. socket.on('error', onerror);
  3190. socket.on('close', onclose);
  3191. socket.on('open', onopen);
  3192. });
  3193. //
  3194. // We need to write a new message to the socket.
  3195. //
  3196. primus.on('outgoing::data', function write(message) {
  3197. if (socket) socket.send(message);
  3198. });
  3199. //
  3200. // Attempt to reconnect the socket.
  3201. //
  3202. primus.on('outgoing::reconnect', function reconnect() {
  3203. primus.emit('outgoing::open');
  3204. });
  3205. //
  3206. // We need to close the socket.
  3207. //
  3208. primus.on('outgoing::end', function close() {
  3209. if (!socket) return;
  3210. socket.removeListener('message', onmessage);
  3211. socket.removeListener('error', onerror);
  3212. socket.removeListener('close', onclose);
  3213. socket.removeListener('open', onopen);
  3214. socket.close();
  3215. socket = null;
  3216. });
  3217. };
  3218. Primus.prototype.authorization = false;
  3219. Primus.prototype.pathname = "/eureca.io";
  3220. Primus.prototype.encoder = function encoder(data, fn) {
  3221. var err;
  3222. try { data = JSON.stringify(data); }
  3223. catch (e) { err = e; }
  3224. fn(err, data);
  3225. };
  3226. Primus.prototype.decoder = function decoder(data, fn) {
  3227. var err;
  3228. if ('string' !== typeof data) return fn(err, data);
  3229. try { data = JSON.parse(data); }
  3230. catch (e) { err = e; }
  3231. fn(err, data);
  3232. };
  3233. Primus.prototype.version = "8.0.9";
  3234. //
  3235. // Expose the library.
  3236. //
  3237. module.exports = Primus;
  3238. },{"demolish":1,"emits":2,"eventemitter3":3,"inherits":4,"querystringify":8,"recovery":9,"tick-tock":12,"url-parse":14,"yeast":15}]},{},[16])(16)
  3239. ;
  3240. return Primus;
  3241. },
  3242. [
  3243. function (Primus) {
  3244. (function (f) {
  3245. var g;
  3246. if (typeof window !== 'undefined') {
  3247. g = window;
  3248. } else if (typeof self !== 'undefined') {
  3249. g = self;
  3250. }
  3251. g.eio = f();
  3252. })(function () {
  3253. var eio = (function () {
  3254. 'use strict';
  3255. function _typeof(obj) {
  3256. "@babel/helpers - typeof";
  3257. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
  3258. return typeof obj;
  3259. } : function (obj) {
  3260. return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  3261. }, _typeof(obj);
  3262. }
  3263. function _classCallCheck(instance, Constructor) {
  3264. if (!(instance instanceof Constructor)) {
  3265. throw new TypeError("Cannot call a class as a function");
  3266. }
  3267. }
  3268. function _defineProperties(target, props) {
  3269. for (var i = 0; i < props.length; i++) {
  3270. var descriptor = props[i];
  3271. descriptor.enumerable = descriptor.enumerable || false;
  3272. descriptor.configurable = true;
  3273. if ("value" in descriptor) descriptor.writable = true;
  3274. Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  3275. }
  3276. }
  3277. function _createClass(Constructor, protoProps, staticProps) {
  3278. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  3279. if (staticProps) _defineProperties(Constructor, staticProps);
  3280. Object.defineProperty(Constructor, "prototype", {
  3281. writable: false
  3282. });
  3283. return Constructor;
  3284. }
  3285. function _extends() {
  3286. _extends = Object.assign ? Object.assign.bind() : function (target) {
  3287. for (var i = 1; i < arguments.length; i++) {
  3288. var source = arguments[i];
  3289. for (var key in source) {
  3290. if (Object.prototype.hasOwnProperty.call(source, key)) {
  3291. target[key] = source[key];
  3292. }
  3293. }
  3294. }
  3295. return target;
  3296. };
  3297. return _extends.apply(this, arguments);
  3298. }
  3299. function _inherits(subClass, superClass) {
  3300. if (typeof superClass !== "function" && superClass !== null) {
  3301. throw new TypeError("Super expression must either be null or a function");
  3302. }
  3303. subClass.prototype = Object.create(superClass && superClass.prototype, {
  3304. constructor: {
  3305. value: subClass,
  3306. writable: true,
  3307. configurable: true
  3308. }
  3309. });
  3310. Object.defineProperty(subClass, "prototype", {
  3311. writable: false
  3312. });
  3313. if (superClass) _setPrototypeOf(subClass, superClass);
  3314. }
  3315. function _getPrototypeOf(o) {
  3316. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
  3317. return o.__proto__ || Object.getPrototypeOf(o);
  3318. };
  3319. return _getPrototypeOf(o);
  3320. }
  3321. function _setPrototypeOf(o, p) {
  3322. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  3323. o.__proto__ = p;
  3324. return o;
  3325. };
  3326. return _setPrototypeOf(o, p);
  3327. }
  3328. function _isNativeReflectConstruct() {
  3329. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  3330. if (Reflect.construct.sham) return false;
  3331. if (typeof Proxy === "function") return true;
  3332. try {
  3333. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  3334. return true;
  3335. } catch (e) {
  3336. return false;
  3337. }
  3338. }
  3339. function _construct(Parent, args, Class) {
  3340. if (_isNativeReflectConstruct()) {
  3341. _construct = Reflect.construct.bind();
  3342. } else {
  3343. _construct = function _construct(Parent, args, Class) {
  3344. var a = [null];
  3345. a.push.apply(a, args);
  3346. var Constructor = Function.bind.apply(Parent, a);
  3347. var instance = new Constructor();
  3348. if (Class) _setPrototypeOf(instance, Class.prototype);
  3349. return instance;
  3350. };
  3351. }
  3352. return _construct.apply(null, arguments);
  3353. }
  3354. function _isNativeFunction(fn) {
  3355. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  3356. }
  3357. function _wrapNativeSuper(Class) {
  3358. var _cache = typeof Map === "function" ? new Map() : undefined;
  3359. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  3360. if (Class === null || !_isNativeFunction(Class)) return Class;
  3361. if (typeof Class !== "function") {
  3362. throw new TypeError("Super expression must either be null or a function");
  3363. }
  3364. if (typeof _cache !== "undefined") {
  3365. if (_cache.has(Class)) return _cache.get(Class);
  3366. _cache.set(Class, Wrapper);
  3367. }
  3368. function Wrapper() {
  3369. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  3370. }
  3371. Wrapper.prototype = Object.create(Class.prototype, {
  3372. constructor: {
  3373. value: Wrapper,
  3374. enumerable: false,
  3375. writable: true,
  3376. configurable: true
  3377. }
  3378. });
  3379. return _setPrototypeOf(Wrapper, Class);
  3380. };
  3381. return _wrapNativeSuper(Class);
  3382. }
  3383. function _assertThisInitialized(self) {
  3384. if (self === void 0) {
  3385. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  3386. }
  3387. return self;
  3388. }
  3389. function _possibleConstructorReturn(self, call) {
  3390. if (call && (typeof call === "object" || typeof call === "function")) {
  3391. return call;
  3392. } else if (call !== void 0) {
  3393. throw new TypeError("Derived constructors may only return object or undefined");
  3394. }
  3395. return _assertThisInitialized(self);
  3396. }
  3397. function _createSuper(Derived) {
  3398. var hasNativeReflectConstruct = _isNativeReflectConstruct();
  3399. return function _createSuperInternal() {
  3400. var Super = _getPrototypeOf(Derived),
  3401. result;
  3402. if (hasNativeReflectConstruct) {
  3403. var NewTarget = _getPrototypeOf(this).constructor;
  3404. result = Reflect.construct(Super, arguments, NewTarget);
  3405. } else {
  3406. result = Super.apply(this, arguments);
  3407. }
  3408. return _possibleConstructorReturn(this, result);
  3409. };
  3410. }
  3411. function _superPropBase(object, property) {
  3412. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  3413. object = _getPrototypeOf(object);
  3414. if (object === null) break;
  3415. }
  3416. return object;
  3417. }
  3418. function _get() {
  3419. if (typeof Reflect !== "undefined" && Reflect.get) {
  3420. _get = Reflect.get.bind();
  3421. } else {
  3422. _get = function _get(target, property, receiver) {
  3423. var base = _superPropBase(target, property);
  3424. if (!base) return;
  3425. var desc = Object.getOwnPropertyDescriptor(base, property);
  3426. if (desc.get) {
  3427. return desc.get.call(arguments.length < 3 ? target : receiver);
  3428. }
  3429. return desc.value;
  3430. };
  3431. }
  3432. return _get.apply(this, arguments);
  3433. }
  3434. function _toPrimitive(input, hint) {
  3435. if (typeof input !== "object" || input === null) return input;
  3436. var prim = input[Symbol.toPrimitive];
  3437. if (prim !== undefined) {
  3438. var res = prim.call(input, hint || "default");
  3439. if (typeof res !== "object") return res;
  3440. throw new TypeError("@@toPrimitive must return a primitive value.");
  3441. }
  3442. return (hint === "string" ? String : Number)(input);
  3443. }
  3444. function _toPropertyKey(arg) {
  3445. var key = _toPrimitive(arg, "string");
  3446. return typeof key === "symbol" ? key : String(key);
  3447. }
  3448. var PACKET_TYPES = Object.create(null); // no Map = no polyfill
  3449. PACKET_TYPES["open"] = "0";
  3450. PACKET_TYPES["close"] = "1";
  3451. PACKET_TYPES["ping"] = "2";
  3452. PACKET_TYPES["pong"] = "3";
  3453. PACKET_TYPES["message"] = "4";
  3454. PACKET_TYPES["upgrade"] = "5";
  3455. PACKET_TYPES["noop"] = "6";
  3456. var PACKET_TYPES_REVERSE = Object.create(null);
  3457. Object.keys(PACKET_TYPES).forEach(function (key) {
  3458. PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
  3459. });
  3460. var ERROR_PACKET = {
  3461. type: "error",
  3462. data: "parser error"
  3463. };
  3464. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  3465. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  3466. // ArrayBuffer.isView method is not defined in IE10
  3467. var isView = function isView(obj) {
  3468. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
  3469. };
  3470. var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
  3471. var type = _ref.type,
  3472. data = _ref.data;
  3473. if (withNativeBlob && data instanceof Blob) {
  3474. if (supportsBinary) {
  3475. return callback(data);
  3476. } else {
  3477. return encodeBlobAsBase64(data, callback);
  3478. }
  3479. } else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(data))) {
  3480. if (supportsBinary) {
  3481. return callback(data);
  3482. } else {
  3483. return encodeBlobAsBase64(new Blob([data]), callback);
  3484. }
  3485. }
  3486. // plain string
  3487. return callback(PACKET_TYPES[type] + (data || ""));
  3488. };
  3489. var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
  3490. var fileReader = new FileReader();
  3491. fileReader.onload = function () {
  3492. var content = fileReader.result.split(",")[1];
  3493. callback("b" + (content || ""));
  3494. };
  3495. return fileReader.readAsDataURL(data);
  3496. };
  3497. function toArray(data) {
  3498. if (data instanceof Uint8Array) {
  3499. return data;
  3500. } else if (data instanceof ArrayBuffer) {
  3501. return new Uint8Array(data);
  3502. } else {
  3503. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  3504. }
  3505. }
  3506. var TEXT_ENCODER;
  3507. function encodePacketToBinary(packet, callback) {
  3508. if (withNativeBlob && packet.data instanceof Blob) {
  3509. return packet.data.arrayBuffer().then(toArray).then(callback);
  3510. } else if (withNativeArrayBuffer$1 && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
  3511. return callback(toArray(packet.data));
  3512. }
  3513. encodePacket(packet, false, function (encoded) {
  3514. if (!TEXT_ENCODER) {
  3515. TEXT_ENCODER = new TextEncoder();
  3516. }
  3517. callback(TEXT_ENCODER.encode(encoded));
  3518. });
  3519. }
  3520. // imported from https://github.com/socketio/base64-arraybuffer
  3521. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  3522. // Use a lookup table to find the index.
  3523. var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  3524. for (var i$1 = 0; i$1 < chars.length; i$1++) {
  3525. lookup[chars.charCodeAt(i$1)] = i$1;
  3526. }
  3527. var decode$1 = function decode(base64) {
  3528. var bufferLength = base64.length * 0.75,
  3529. len = base64.length,
  3530. i,
  3531. p = 0,
  3532. encoded1,
  3533. encoded2,
  3534. encoded3,
  3535. encoded4;
  3536. if (base64[base64.length - 1] === '=') {
  3537. bufferLength--;
  3538. if (base64[base64.length - 2] === '=') {
  3539. bufferLength--;
  3540. }
  3541. }
  3542. var arraybuffer = new ArrayBuffer(bufferLength),
  3543. bytes = new Uint8Array(arraybuffer);
  3544. for (i = 0; i < len; i += 4) {
  3545. encoded1 = lookup[base64.charCodeAt(i)];
  3546. encoded2 = lookup[base64.charCodeAt(i + 1)];
  3547. encoded3 = lookup[base64.charCodeAt(i + 2)];
  3548. encoded4 = lookup[base64.charCodeAt(i + 3)];
  3549. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  3550. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  3551. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  3552. }
  3553. return arraybuffer;
  3554. };
  3555. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  3556. var decodePacket = function decodePacket(encodedPacket, binaryType) {
  3557. if (typeof encodedPacket !== "string") {
  3558. return {
  3559. type: "message",
  3560. data: mapBinary(encodedPacket, binaryType)
  3561. };
  3562. }
  3563. var type = encodedPacket.charAt(0);
  3564. if (type === "b") {
  3565. return {
  3566. type: "message",
  3567. data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
  3568. };
  3569. }
  3570. var packetType = PACKET_TYPES_REVERSE[type];
  3571. if (!packetType) {
  3572. return ERROR_PACKET;
  3573. }
  3574. return encodedPacket.length > 1 ? {
  3575. type: PACKET_TYPES_REVERSE[type],
  3576. data: encodedPacket.substring(1)
  3577. } : {
  3578. type: PACKET_TYPES_REVERSE[type]
  3579. };
  3580. };
  3581. var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
  3582. if (withNativeArrayBuffer) {
  3583. var decoded = decode$1(data);
  3584. return mapBinary(decoded, binaryType);
  3585. } else {
  3586. return {
  3587. base64: true,
  3588. data: data
  3589. }; // fallback for old browsers
  3590. }
  3591. };
  3592. var mapBinary = function mapBinary(data, binaryType) {
  3593. switch (binaryType) {
  3594. case "blob":
  3595. if (data instanceof Blob) {
  3596. // from WebSocket + binaryType "blob"
  3597. return data;
  3598. } else {
  3599. // from HTTP long-polling or WebTransport
  3600. return new Blob([data]);
  3601. }
  3602. case "arraybuffer":
  3603. default:
  3604. if (data instanceof ArrayBuffer) {
  3605. // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
  3606. return data;
  3607. } else {
  3608. // from WebTransport (Uint8Array)
  3609. return data.buffer;
  3610. }
  3611. }
  3612. };
  3613. var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  3614. var encodePayload = function encodePayload(packets, callback) {
  3615. // some packets may be added to the array while encoding, so the initial length must be saved
  3616. var length = packets.length;
  3617. var encodedPackets = new Array(length);
  3618. var count = 0;
  3619. packets.forEach(function (packet, i) {
  3620. // force base64 encoding for binary packets
  3621. encodePacket(packet, false, function (encodedPacket) {
  3622. encodedPackets[i] = encodedPacket;
  3623. if (++count === length) {
  3624. callback(encodedPackets.join(SEPARATOR));
  3625. }
  3626. });
  3627. });
  3628. };
  3629. var decodePayload = function decodePayload(encodedPayload, binaryType) {
  3630. var encodedPackets = encodedPayload.split(SEPARATOR);
  3631. var packets = [];
  3632. for (var i = 0; i < encodedPackets.length; i++) {
  3633. var decodedPacket = decodePacket(encodedPackets[i], binaryType);
  3634. packets.push(decodedPacket);
  3635. if (decodedPacket.type === "error") {
  3636. break;
  3637. }
  3638. }
  3639. return packets;
  3640. };
  3641. var TEXT_DECODER;
  3642. function decodePacketFromBinary(data, isBinary, binaryType) {
  3643. if (!TEXT_DECODER) {
  3644. // lazily created for compatibility with old browser platforms
  3645. TEXT_DECODER = new TextDecoder();
  3646. }
  3647. // 48 === "0".charCodeAt(0) (OPEN packet type)
  3648. // 54 === "6".charCodeAt(0) (NOOP packet type)
  3649. var isPlainBinary = isBinary || data[0] < 48 || data[0] > 54;
  3650. return decodePacket(isPlainBinary ? data : TEXT_DECODER.decode(data), binaryType);
  3651. }
  3652. var protocol = 4;
  3653. /**
  3654. * Initialize a new `Emitter`.
  3655. *
  3656. * @api public
  3657. */
  3658. function Emitter(obj) {
  3659. if (obj) return mixin(obj);
  3660. }
  3661. /**
  3662. * Mixin the emitter properties.
  3663. *
  3664. * @param {Object} obj
  3665. * @return {Object}
  3666. * @api private
  3667. */
  3668. function mixin(obj) {
  3669. for (var key in Emitter.prototype) {
  3670. obj[key] = Emitter.prototype[key];
  3671. }
  3672. return obj;
  3673. }
  3674. /**
  3675. * Listen on the given `event` with `fn`.
  3676. *
  3677. * @param {String} event
  3678. * @param {Function} fn
  3679. * @return {Emitter}
  3680. * @api public
  3681. */
  3682. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  3683. this._callbacks = this._callbacks || {};
  3684. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  3685. return this;
  3686. };
  3687. /**
  3688. * Adds an `event` listener that will be invoked a single
  3689. * time then automatically removed.
  3690. *
  3691. * @param {String} event
  3692. * @param {Function} fn
  3693. * @return {Emitter}
  3694. * @api public
  3695. */
  3696. Emitter.prototype.once = function (event, fn) {
  3697. function on() {
  3698. this.off(event, on);
  3699. fn.apply(this, arguments);
  3700. }
  3701. on.fn = fn;
  3702. this.on(event, on);
  3703. return this;
  3704. };
  3705. /**
  3706. * Remove the given callback for `event` or all
  3707. * registered callbacks.
  3708. *
  3709. * @param {String} event
  3710. * @param {Function} fn
  3711. * @return {Emitter}
  3712. * @api public
  3713. */
  3714. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  3715. this._callbacks = this._callbacks || {};
  3716. // all
  3717. if (0 == arguments.length) {
  3718. this._callbacks = {};
  3719. return this;
  3720. }
  3721. // specific event
  3722. var callbacks = this._callbacks['$' + event];
  3723. if (!callbacks) return this;
  3724. // remove all handlers
  3725. if (1 == arguments.length) {
  3726. delete this._callbacks['$' + event];
  3727. return this;
  3728. }
  3729. // remove specific handler
  3730. var cb;
  3731. for (var i = 0; i < callbacks.length; i++) {
  3732. cb = callbacks[i];
  3733. if (cb === fn || cb.fn === fn) {
  3734. callbacks.splice(i, 1);
  3735. break;
  3736. }
  3737. }
  3738. // Remove event specific arrays for event types that no
  3739. // one is subscribed for to avoid memory leak.
  3740. if (callbacks.length === 0) {
  3741. delete this._callbacks['$' + event];
  3742. }
  3743. return this;
  3744. };
  3745. /**
  3746. * Emit `event` with the given args.
  3747. *
  3748. * @param {String} event
  3749. * @param {Mixed} ...
  3750. * @return {Emitter}
  3751. */
  3752. Emitter.prototype.emit = function (event) {
  3753. this._callbacks = this._callbacks || {};
  3754. var args = new Array(arguments.length - 1),
  3755. callbacks = this._callbacks['$' + event];
  3756. for (var i = 1; i < arguments.length; i++) {
  3757. args[i - 1] = arguments[i];
  3758. }
  3759. if (callbacks) {
  3760. callbacks = callbacks.slice(0);
  3761. for (var i = 0, len = callbacks.length; i < len; ++i) {
  3762. callbacks[i].apply(this, args);
  3763. }
  3764. }
  3765. return this;
  3766. };
  3767. // alias used for reserved events (protected method)
  3768. Emitter.prototype.emitReserved = Emitter.prototype.emit;
  3769. /**
  3770. * Return array of callbacks for `event`.
  3771. *
  3772. * @param {String} event
  3773. * @return {Array}
  3774. * @api public
  3775. */
  3776. Emitter.prototype.listeners = function (event) {
  3777. this._callbacks = this._callbacks || {};
  3778. return this._callbacks['$' + event] || [];
  3779. };
  3780. /**
  3781. * Check if this emitter has `event` handlers.
  3782. *
  3783. * @param {String} event
  3784. * @return {Boolean}
  3785. * @api public
  3786. */
  3787. Emitter.prototype.hasListeners = function (event) {
  3788. return !!this.listeners(event).length;
  3789. };
  3790. var globalThisShim = function () {
  3791. if (typeof self !== "undefined") {
  3792. return self;
  3793. } else if (typeof window !== "undefined") {
  3794. return window;
  3795. } else {
  3796. return Function("return this")();
  3797. }
  3798. }();
  3799. function pick(obj) {
  3800. for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  3801. attr[_key - 1] = arguments[_key];
  3802. }
  3803. return attr.reduce(function (acc, k) {
  3804. if (obj.hasOwnProperty(k)) {
  3805. acc[k] = obj[k];
  3806. }
  3807. return acc;
  3808. }, {});
  3809. }
  3810. // Keep a reference to the real timeout functions so they can be used when overridden
  3811. var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
  3812. var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
  3813. function installTimerFunctions(obj, opts) {
  3814. if (opts.useNativeTimers) {
  3815. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
  3816. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
  3817. } else {
  3818. obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
  3819. obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
  3820. }
  3821. }
  3822. // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
  3823. var BASE64_OVERHEAD = 1.33;
  3824. // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
  3825. function byteLength(obj) {
  3826. if (typeof obj === "string") {
  3827. return utf8Length(obj);
  3828. }
  3829. // arraybuffer or blob
  3830. return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
  3831. }
  3832. function utf8Length(str) {
  3833. var c = 0,
  3834. length = 0;
  3835. for (var i = 0, l = str.length; i < l; i++) {
  3836. c = str.charCodeAt(i);
  3837. if (c < 0x80) {
  3838. length += 1;
  3839. } else if (c < 0x800) {
  3840. length += 2;
  3841. } else if (c < 0xd800 || c >= 0xe000) {
  3842. length += 3;
  3843. } else {
  3844. i++;
  3845. length += 4;
  3846. }
  3847. }
  3848. return length;
  3849. }
  3850. // imported from https://github.com/galkn/querystring
  3851. /**
  3852. * Compiles a querystring
  3853. * Returns string representation of the object
  3854. *
  3855. * @param {Object}
  3856. * @api private
  3857. */
  3858. function encode$1(obj) {
  3859. var str = '';
  3860. for (var i in obj) {
  3861. if (obj.hasOwnProperty(i)) {
  3862. if (str.length) str += '&';
  3863. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  3864. }
  3865. }
  3866. return str;
  3867. }
  3868. /**
  3869. * Parses a simple querystring into an object
  3870. *
  3871. * @param {String} qs
  3872. * @api private
  3873. */
  3874. function decode(qs) {
  3875. var qry = {};
  3876. var pairs = qs.split('&');
  3877. for (var i = 0, l = pairs.length; i < l; i++) {
  3878. var pair = pairs[i].split('=');
  3879. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  3880. }
  3881. return qry;
  3882. }
  3883. var TransportError = /*#__PURE__*/function (_Error) {
  3884. _inherits(TransportError, _Error);
  3885. var _super = _createSuper(TransportError);
  3886. function TransportError(reason, description, context) {
  3887. var _this;
  3888. _classCallCheck(this, TransportError);
  3889. _this = _super.call(this, reason);
  3890. _this.description = description;
  3891. _this.context = context;
  3892. _this.type = "TransportError";
  3893. return _this;
  3894. }
  3895. return _createClass(TransportError);
  3896. }( /*#__PURE__*/_wrapNativeSuper(Error));
  3897. var Transport = /*#__PURE__*/function (_Emitter) {
  3898. _inherits(Transport, _Emitter);
  3899. var _super2 = _createSuper(Transport);
  3900. /**
  3901. * Transport abstract constructor.
  3902. *
  3903. * @param {Object} opts - options
  3904. * @protected
  3905. */
  3906. function Transport(opts) {
  3907. var _this2;
  3908. _classCallCheck(this, Transport);
  3909. _this2 = _super2.call(this);
  3910. _this2.writable = false;
  3911. installTimerFunctions(_assertThisInitialized(_this2), opts);
  3912. _this2.opts = opts;
  3913. _this2.query = opts.query;
  3914. _this2.socket = opts.socket;
  3915. return _this2;
  3916. }
  3917. /**
  3918. * Emits an error.
  3919. *
  3920. * @param {String} reason
  3921. * @param description
  3922. * @param context - the error context
  3923. * @return {Transport} for chaining
  3924. * @protected
  3925. */
  3926. _createClass(Transport, [{
  3927. key: "onError",
  3928. value: function onError(reason, description, context) {
  3929. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context));
  3930. return this;
  3931. }
  3932. /**
  3933. * Opens the transport.
  3934. */
  3935. }, {
  3936. key: "open",
  3937. value: function open() {
  3938. this.readyState = "opening";
  3939. this.doOpen();
  3940. return this;
  3941. }
  3942. /**
  3943. * Closes the transport.
  3944. */
  3945. }, {
  3946. key: "close",
  3947. value: function close() {
  3948. if (this.readyState === "opening" || this.readyState === "open") {
  3949. this.doClose();
  3950. this.onClose();
  3951. }
  3952. return this;
  3953. }
  3954. /**
  3955. * Sends multiple packets.
  3956. *
  3957. * @param {Array} packets
  3958. */
  3959. }, {
  3960. key: "send",
  3961. value: function send(packets) {
  3962. if (this.readyState === "open") {
  3963. this.write(packets);
  3964. }
  3965. }
  3966. /**
  3967. * Called upon open
  3968. *
  3969. * @protected
  3970. */
  3971. }, {
  3972. key: "onOpen",
  3973. value: function onOpen() {
  3974. this.readyState = "open";
  3975. this.writable = true;
  3976. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open");
  3977. }
  3978. /**
  3979. * Called with data.
  3980. *
  3981. * @param {String} data
  3982. * @protected
  3983. */
  3984. }, {
  3985. key: "onData",
  3986. value: function onData(data) {
  3987. var packet = decodePacket(data, this.socket.binaryType);
  3988. this.onPacket(packet);
  3989. }
  3990. /**
  3991. * Called with a decoded packet.
  3992. *
  3993. * @protected
  3994. */
  3995. }, {
  3996. key: "onPacket",
  3997. value: function onPacket(packet) {
  3998. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet);
  3999. }
  4000. /**
  4001. * Called upon close.
  4002. *
  4003. * @protected
  4004. */
  4005. }, {
  4006. key: "onClose",
  4007. value: function onClose(details) {
  4008. this.readyState = "closed";
  4009. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details);
  4010. }
  4011. /**
  4012. * Pauses the transport, in order not to lose packets during an upgrade.
  4013. *
  4014. * @param onPause
  4015. */
  4016. }, {
  4017. key: "pause",
  4018. value: function pause(onPause) {}
  4019. }, {
  4020. key: "createUri",
  4021. value: function createUri(schema) {
  4022. var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  4023. return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
  4024. }
  4025. }, {
  4026. key: "_hostname",
  4027. value: function _hostname() {
  4028. var hostname = this.opts.hostname;
  4029. return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
  4030. }
  4031. }, {
  4032. key: "_port",
  4033. value: function _port() {
  4034. if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
  4035. return ":" + this.opts.port;
  4036. } else {
  4037. return "";
  4038. }
  4039. }
  4040. }, {
  4041. key: "_query",
  4042. value: function _query(query) {
  4043. var encodedQuery = encode$1(query);
  4044. return encodedQuery.length ? "?" + encodedQuery : "";
  4045. }
  4046. }]);
  4047. return Transport;
  4048. }(Emitter);
  4049. // imported from https://github.com/unshiftio/yeast
  4050. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
  4051. length = 64,
  4052. map = {};
  4053. var seed = 0,
  4054. i = 0,
  4055. prev;
  4056. /**
  4057. * Return a string representing the specified number.
  4058. *
  4059. * @param {Number} num The number to convert.
  4060. * @returns {String} The string representation of the number.
  4061. * @api public
  4062. */
  4063. function encode(num) {
  4064. var encoded = '';
  4065. do {
  4066. encoded = alphabet[num % length] + encoded;
  4067. num = Math.floor(num / length);
  4068. } while (num > 0);
  4069. return encoded;
  4070. }
  4071. /**
  4072. * Yeast: A tiny growing id generator.
  4073. *
  4074. * @returns {String} A unique id.
  4075. * @api public
  4076. */
  4077. function yeast() {
  4078. var now = encode(+new Date());
  4079. if (now !== prev) return seed = 0, prev = now;
  4080. return now + '.' + encode(seed++);
  4081. }
  4082. //
  4083. // Map each character to its index.
  4084. //
  4085. for (; i < length; i++) map[alphabet[i]] = i;
  4086. // imported from https://github.com/component/has-cors
  4087. var value = false;
  4088. try {
  4089. value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  4090. } catch (err) {
  4091. // if XMLHttp support is disabled in IE then it will throw
  4092. // when trying to create
  4093. }
  4094. var hasCORS = value;
  4095. // browser shim for xmlhttprequest module
  4096. function XHR(opts) {
  4097. var xdomain = opts.xdomain;
  4098. // XMLHttpRequest can be disabled on IE
  4099. try {
  4100. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  4101. return new XMLHttpRequest();
  4102. }
  4103. } catch (e) {}
  4104. if (!xdomain) {
  4105. try {
  4106. return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  4107. } catch (e) {}
  4108. }
  4109. }
  4110. function createCookieJar() {}
  4111. function empty() {}
  4112. var hasXHR2 = function () {
  4113. var xhr = new XHR({
  4114. xdomain: false
  4115. });
  4116. return null != xhr.responseType;
  4117. }();
  4118. var Polling = /*#__PURE__*/function (_Transport) {
  4119. _inherits(Polling, _Transport);
  4120. var _super = _createSuper(Polling);
  4121. /**
  4122. * XHR Polling constructor.
  4123. *
  4124. * @param {Object} opts
  4125. * @package
  4126. */
  4127. function Polling(opts) {
  4128. var _this;
  4129. _classCallCheck(this, Polling);
  4130. _this = _super.call(this, opts);
  4131. _this.polling = false;
  4132. if (typeof location !== "undefined") {
  4133. var isSSL = "https:" === location.protocol;
  4134. var port = location.port;
  4135. // some user agents have empty `location.port`
  4136. if (!port) {
  4137. port = isSSL ? "443" : "80";
  4138. }
  4139. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  4140. }
  4141. /**
  4142. * XHR supports binary
  4143. */
  4144. var forceBase64 = opts && opts.forceBase64;
  4145. _this.supportsBinary = hasXHR2 && !forceBase64;
  4146. if (_this.opts.withCredentials) {
  4147. _this.cookieJar = createCookieJar();
  4148. }
  4149. return _this;
  4150. }
  4151. _createClass(Polling, [{
  4152. key: "name",
  4153. get: function get() {
  4154. return "polling";
  4155. }
  4156. /**
  4157. * Opens the socket (triggers polling). We write a PING message to determine
  4158. * when the transport is open.
  4159. *
  4160. * @protected
  4161. */
  4162. }, {
  4163. key: "doOpen",
  4164. value: function doOpen() {
  4165. this.poll();
  4166. }
  4167. /**
  4168. * Pauses polling.
  4169. *
  4170. * @param {Function} onPause - callback upon buffers are flushed and transport is paused
  4171. * @package
  4172. */
  4173. }, {
  4174. key: "pause",
  4175. value: function pause(onPause) {
  4176. var _this2 = this;
  4177. this.readyState = "pausing";
  4178. var pause = function pause() {
  4179. _this2.readyState = "paused";
  4180. onPause();
  4181. };
  4182. if (this.polling || !this.writable) {
  4183. var total = 0;
  4184. if (this.polling) {
  4185. total++;
  4186. this.once("pollComplete", function () {
  4187. --total || pause();
  4188. });
  4189. }
  4190. if (!this.writable) {
  4191. total++;
  4192. this.once("drain", function () {
  4193. --total || pause();
  4194. });
  4195. }
  4196. } else {
  4197. pause();
  4198. }
  4199. }
  4200. /**
  4201. * Starts polling cycle.
  4202. *
  4203. * @private
  4204. */
  4205. }, {
  4206. key: "poll",
  4207. value: function poll() {
  4208. this.polling = true;
  4209. this.doPoll();
  4210. this.emitReserved("poll");
  4211. }
  4212. /**
  4213. * Overloads onData to detect payloads.
  4214. *
  4215. * @protected
  4216. */
  4217. }, {
  4218. key: "onData",
  4219. value: function onData(data) {
  4220. var _this3 = this;
  4221. var callback = function callback(packet) {
  4222. // if its the first message we consider the transport open
  4223. if ("opening" === _this3.readyState && packet.type === "open") {
  4224. _this3.onOpen();
  4225. }
  4226. // if its a close packet, we close the ongoing requests
  4227. if ("close" === packet.type) {
  4228. _this3.onClose({
  4229. description: "transport closed by the server"
  4230. });
  4231. return false;
  4232. }
  4233. // otherwise bypass onData and handle the message
  4234. _this3.onPacket(packet);
  4235. };
  4236. // decode payload
  4237. decodePayload(data, this.socket.binaryType).forEach(callback);
  4238. // if an event did not trigger closing
  4239. if ("closed" !== this.readyState) {
  4240. // if we got data we're not polling
  4241. this.polling = false;
  4242. this.emitReserved("pollComplete");
  4243. if ("open" === this.readyState) {
  4244. this.poll();
  4245. }
  4246. }
  4247. }
  4248. /**
  4249. * For polling, send a close packet.
  4250. *
  4251. * @protected
  4252. */
  4253. }, {
  4254. key: "doClose",
  4255. value: function doClose() {
  4256. var _this4 = this;
  4257. var close = function close() {
  4258. _this4.write([{
  4259. type: "close"
  4260. }]);
  4261. };
  4262. if ("open" === this.readyState) {
  4263. close();
  4264. } else {
  4265. // in case we're trying to close while
  4266. // handshaking is in progress (GH-164)
  4267. this.once("open", close);
  4268. }
  4269. }
  4270. /**
  4271. * Writes a packets payload.
  4272. *
  4273. * @param {Array} packets - data packets
  4274. * @protected
  4275. */
  4276. }, {
  4277. key: "write",
  4278. value: function write(packets) {
  4279. var _this5 = this;
  4280. this.writable = false;
  4281. encodePayload(packets, function (data) {
  4282. _this5.doWrite(data, function () {
  4283. _this5.writable = true;
  4284. _this5.emitReserved("drain");
  4285. });
  4286. });
  4287. }
  4288. /**
  4289. * Generates uri for connection.
  4290. *
  4291. * @private
  4292. */
  4293. }, {
  4294. key: "uri",
  4295. value: function uri() {
  4296. var schema = this.opts.secure ? "https" : "http";
  4297. var query = this.query || {};
  4298. // cache busting is forced
  4299. if (false !== this.opts.timestampRequests) {
  4300. query[this.opts.timestampParam] = yeast();
  4301. }
  4302. if (!this.supportsBinary && !query.sid) {
  4303. query.b64 = 1;
  4304. }
  4305. return this.createUri(schema, query);
  4306. }
  4307. /**
  4308. * Creates a request.
  4309. *
  4310. * @param {String} method
  4311. * @private
  4312. */
  4313. }, {
  4314. key: "request",
  4315. value: function request() {
  4316. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  4317. _extends(opts, {
  4318. xd: this.xd,
  4319. cookieJar: this.cookieJar
  4320. }, this.opts);
  4321. return new Request(this.uri(), opts);
  4322. }
  4323. /**
  4324. * Sends data.
  4325. *
  4326. * @param {String} data to send.
  4327. * @param {Function} called upon flush.
  4328. * @private
  4329. */
  4330. }, {
  4331. key: "doWrite",
  4332. value: function doWrite(data, fn) {
  4333. var _this6 = this;
  4334. var req = this.request({
  4335. method: "POST",
  4336. data: data
  4337. });
  4338. req.on("success", fn);
  4339. req.on("error", function (xhrStatus, context) {
  4340. _this6.onError("xhr post error", xhrStatus, context);
  4341. });
  4342. }
  4343. /**
  4344. * Starts a poll cycle.
  4345. *
  4346. * @private
  4347. */
  4348. }, {
  4349. key: "doPoll",
  4350. value: function doPoll() {
  4351. var _this7 = this;
  4352. var req = this.request();
  4353. req.on("data", this.onData.bind(this));
  4354. req.on("error", function (xhrStatus, context) {
  4355. _this7.onError("xhr poll error", xhrStatus, context);
  4356. });
  4357. this.pollXhr = req;
  4358. }
  4359. }]);
  4360. return Polling;
  4361. }(Transport);
  4362. var Request = /*#__PURE__*/function (_Emitter) {
  4363. _inherits(Request, _Emitter);
  4364. var _super2 = _createSuper(Request);
  4365. /**
  4366. * Request constructor
  4367. *
  4368. * @param {Object} options
  4369. * @package
  4370. */
  4371. function Request(uri, opts) {
  4372. var _this8;
  4373. _classCallCheck(this, Request);
  4374. _this8 = _super2.call(this);
  4375. installTimerFunctions(_assertThisInitialized(_this8), opts);
  4376. _this8.opts = opts;
  4377. _this8.method = opts.method || "GET";
  4378. _this8.uri = uri;
  4379. _this8.data = undefined !== opts.data ? opts.data : null;
  4380. _this8.create();
  4381. return _this8;
  4382. }
  4383. /**
  4384. * Creates the XHR object and sends the request.
  4385. *
  4386. * @private
  4387. */
  4388. _createClass(Request, [{
  4389. key: "create",
  4390. value: function create() {
  4391. var _this9 = this;
  4392. var _a;
  4393. var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  4394. opts.xdomain = !!this.opts.xd;
  4395. var xhr = this.xhr = new XHR(opts);
  4396. try {
  4397. xhr.open(this.method, this.uri, true);
  4398. try {
  4399. if (this.opts.extraHeaders) {
  4400. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  4401. for (var i in this.opts.extraHeaders) {
  4402. if (this.opts.extraHeaders.hasOwnProperty(i)) {
  4403. xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
  4404. }
  4405. }
  4406. }
  4407. } catch (e) {}
  4408. if ("POST" === this.method) {
  4409. try {
  4410. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  4411. } catch (e) {}
  4412. }
  4413. try {
  4414. xhr.setRequestHeader("Accept", "*/*");
  4415. } catch (e) {}
  4416. (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
  4417. // ie6 check
  4418. if ("withCredentials" in xhr) {
  4419. xhr.withCredentials = this.opts.withCredentials;
  4420. }
  4421. if (this.opts.requestTimeout) {
  4422. xhr.timeout = this.opts.requestTimeout;
  4423. }
  4424. xhr.onreadystatechange = function () {
  4425. var _a;
  4426. if (xhr.readyState === 3) {
  4427. (_a = _this9.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(xhr);
  4428. }
  4429. if (4 !== xhr.readyState) return;
  4430. if (200 === xhr.status || 1223 === xhr.status) {
  4431. _this9.onLoad();
  4432. } else {
  4433. // make sure the `error` event handler that's user-set
  4434. // does not throw in the same tick and gets caught here
  4435. _this9.setTimeoutFn(function () {
  4436. _this9.onError(typeof xhr.status === "number" ? xhr.status : 0);
  4437. }, 0);
  4438. }
  4439. };
  4440. xhr.send(this.data);
  4441. } catch (e) {
  4442. // Need to defer since .create() is called directly from the constructor
  4443. // and thus the 'error' event can only be only bound *after* this exception
  4444. // occurs. Therefore, also, we cannot throw here at all.
  4445. this.setTimeoutFn(function () {
  4446. _this9.onError(e);
  4447. }, 0);
  4448. return;
  4449. }
  4450. if (typeof document !== "undefined") {
  4451. this.index = Request.requestsCount++;
  4452. Request.requests[this.index] = this;
  4453. }
  4454. }
  4455. /**
  4456. * Called upon error.
  4457. *
  4458. * @private
  4459. */
  4460. }, {
  4461. key: "onError",
  4462. value: function onError(err) {
  4463. this.emitReserved("error", err, this.xhr);
  4464. this.cleanup(true);
  4465. }
  4466. /**
  4467. * Cleans up house.
  4468. *
  4469. * @private
  4470. */
  4471. }, {
  4472. key: "cleanup",
  4473. value: function cleanup(fromError) {
  4474. if ("undefined" === typeof this.xhr || null === this.xhr) {
  4475. return;
  4476. }
  4477. this.xhr.onreadystatechange = empty;
  4478. if (fromError) {
  4479. try {
  4480. this.xhr.abort();
  4481. } catch (e) {}
  4482. }
  4483. if (typeof document !== "undefined") {
  4484. delete Request.requests[this.index];
  4485. }
  4486. this.xhr = null;
  4487. }
  4488. /**
  4489. * Called upon load.
  4490. *
  4491. * @private
  4492. */
  4493. }, {
  4494. key: "onLoad",
  4495. value: function onLoad() {
  4496. var data = this.xhr.responseText;
  4497. if (data !== null) {
  4498. this.emitReserved("data", data);
  4499. this.emitReserved("success");
  4500. this.cleanup();
  4501. }
  4502. }
  4503. /**
  4504. * Aborts the request.
  4505. *
  4506. * @package
  4507. */
  4508. }, {
  4509. key: "abort",
  4510. value: function abort() {
  4511. this.cleanup();
  4512. }
  4513. }]);
  4514. return Request;
  4515. }(Emitter);
  4516. Request.requestsCount = 0;
  4517. Request.requests = {};
  4518. /**
  4519. * Aborts pending requests when unloading the window. This is needed to prevent
  4520. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  4521. * emitted.
  4522. */
  4523. if (typeof document !== "undefined") {
  4524. // @ts-ignore
  4525. if (typeof attachEvent === "function") {
  4526. // @ts-ignore
  4527. attachEvent("onunload", unloadHandler);
  4528. } else if (typeof addEventListener === "function") {
  4529. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  4530. addEventListener(terminationEvent, unloadHandler, false);
  4531. }
  4532. }
  4533. function unloadHandler() {
  4534. for (var i in Request.requests) {
  4535. if (Request.requests.hasOwnProperty(i)) {
  4536. Request.requests[i].abort();
  4537. }
  4538. }
  4539. }
  4540. var nextTick = function () {
  4541. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  4542. if (isPromiseAvailable) {
  4543. return function (cb) {
  4544. return Promise.resolve().then(cb);
  4545. };
  4546. } else {
  4547. return function (cb, setTimeoutFn) {
  4548. return setTimeoutFn(cb, 0);
  4549. };
  4550. }
  4551. }();
  4552. var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  4553. var usingBrowserWebSocket = true;
  4554. var defaultBinaryType = "arraybuffer";
  4555. // detect ReactNative environment
  4556. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  4557. var WS = /*#__PURE__*/function (_Transport) {
  4558. _inherits(WS, _Transport);
  4559. var _super = _createSuper(WS);
  4560. /**
  4561. * WebSocket transport constructor.
  4562. *
  4563. * @param {Object} opts - connection options
  4564. * @protected
  4565. */
  4566. function WS(opts) {
  4567. var _this;
  4568. _classCallCheck(this, WS);
  4569. _this = _super.call(this, opts);
  4570. _this.supportsBinary = !opts.forceBase64;
  4571. return _this;
  4572. }
  4573. _createClass(WS, [{
  4574. key: "name",
  4575. get: function get() {
  4576. return "websocket";
  4577. }
  4578. }, {
  4579. key: "doOpen",
  4580. value: function doOpen() {
  4581. if (!this.check()) {
  4582. // let probe timeout
  4583. return;
  4584. }
  4585. var uri = this.uri();
  4586. var protocols = this.opts.protocols;
  4587. // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  4588. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  4589. if (this.opts.extraHeaders) {
  4590. opts.headers = this.opts.extraHeaders;
  4591. }
  4592. try {
  4593. this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  4594. } catch (err) {
  4595. return this.emitReserved("error", err);
  4596. }
  4597. this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
  4598. this.addEventListeners();
  4599. }
  4600. /**
  4601. * Adds event listeners to the socket
  4602. *
  4603. * @private
  4604. */
  4605. }, {
  4606. key: "addEventListeners",
  4607. value: function addEventListeners() {
  4608. var _this2 = this;
  4609. this.ws.onopen = function () {
  4610. if (_this2.opts.autoUnref) {
  4611. _this2.ws._socket.unref();
  4612. }
  4613. _this2.onOpen();
  4614. };
  4615. this.ws.onclose = function (closeEvent) {
  4616. return _this2.onClose({
  4617. description: "websocket connection closed",
  4618. context: closeEvent
  4619. });
  4620. };
  4621. this.ws.onmessage = function (ev) {
  4622. return _this2.onData(ev.data);
  4623. };
  4624. this.ws.onerror = function (e) {
  4625. return _this2.onError("websocket error", e);
  4626. };
  4627. }
  4628. }, {
  4629. key: "write",
  4630. value: function write(packets) {
  4631. var _this3 = this;
  4632. this.writable = false;
  4633. // encodePacket efficient as it uses WS framing
  4634. // no need for encodePayload
  4635. var _loop = function _loop() {
  4636. var packet = packets[i];
  4637. var lastPacket = i === packets.length - 1;
  4638. encodePacket(packet, _this3.supportsBinary, function (data) {
  4639. // always create a new object (GH-437)
  4640. var opts = {};
  4641. // Sometimes the websocket has already been closed but the browser didn't
  4642. // have a chance of informing us about it yet, in that case send will
  4643. // throw an error
  4644. try {
  4645. if (usingBrowserWebSocket) {
  4646. // TypeError is thrown when passing the second argument on Safari
  4647. _this3.ws.send(data);
  4648. }
  4649. } catch (e) {}
  4650. if (lastPacket) {
  4651. // fake drain
  4652. // defer to next tick to allow Socket to clear writeBuffer
  4653. nextTick(function () {
  4654. _this3.writable = true;
  4655. _this3.emitReserved("drain");
  4656. }, _this3.setTimeoutFn);
  4657. }
  4658. });
  4659. };
  4660. for (var i = 0; i < packets.length; i++) {
  4661. _loop();
  4662. }
  4663. }
  4664. }, {
  4665. key: "doClose",
  4666. value: function doClose() {
  4667. if (typeof this.ws !== "undefined") {
  4668. this.ws.close();
  4669. this.ws = null;
  4670. }
  4671. }
  4672. /**
  4673. * Generates uri for connection.
  4674. *
  4675. * @private
  4676. */
  4677. }, {
  4678. key: "uri",
  4679. value: function uri() {
  4680. var schema = this.opts.secure ? "wss" : "ws";
  4681. var query = this.query || {};
  4682. // append timestamp to URI
  4683. if (this.opts.timestampRequests) {
  4684. query[this.opts.timestampParam] = yeast();
  4685. }
  4686. // communicate binary support capabilities
  4687. if (!this.supportsBinary) {
  4688. query.b64 = 1;
  4689. }
  4690. return this.createUri(schema, query);
  4691. }
  4692. /**
  4693. * Feature detection for WebSocket.
  4694. *
  4695. * @return {Boolean} whether this transport is available.
  4696. * @private
  4697. */
  4698. }, {
  4699. key: "check",
  4700. value: function check() {
  4701. return !!WebSocket;
  4702. }
  4703. }]);
  4704. return WS;
  4705. }(Transport);
  4706. function shouldIncludeBinaryHeader(packet, encoded) {
  4707. // 48 === "0".charCodeAt(0) (OPEN packet type)
  4708. // 54 === "6".charCodeAt(0) (NOOP packet type)
  4709. return packet.type === "message" && typeof packet.data !== "string" && encoded[0] >= 48 && encoded[0] <= 54;
  4710. }
  4711. var WT = /*#__PURE__*/function (_Transport) {
  4712. _inherits(WT, _Transport);
  4713. var _super = _createSuper(WT);
  4714. function WT() {
  4715. _classCallCheck(this, WT);
  4716. return _super.apply(this, arguments);
  4717. }
  4718. _createClass(WT, [{
  4719. key: "name",
  4720. get: function get() {
  4721. return "webtransport";
  4722. }
  4723. }, {
  4724. key: "doOpen",
  4725. value: function doOpen() {
  4726. var _this = this;
  4727. // @ts-ignore
  4728. if (typeof WebTransport !== "function") {
  4729. return;
  4730. }
  4731. // @ts-ignore
  4732. this.transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
  4733. this.transport.closed.then(function () {
  4734. _this.onClose();
  4735. })["catch"](function (err) {
  4736. _this.onError("webtransport error", err);
  4737. });
  4738. // note: we could have used async/await, but that would require some additional polyfills
  4739. this.transport.ready.then(function () {
  4740. _this.transport.createBidirectionalStream().then(function (stream) {
  4741. var reader = stream.readable.getReader();
  4742. _this.writer = stream.writable.getWriter();
  4743. var binaryFlag;
  4744. var read = function read() {
  4745. reader.read().then(function (_ref) {
  4746. var done = _ref.done,
  4747. value = _ref.value;
  4748. if (done) {
  4749. return;
  4750. }
  4751. if (!binaryFlag && value.byteLength === 1 && value[0] === 54) {
  4752. binaryFlag = true;
  4753. } else {
  4754. // TODO expose binarytype
  4755. _this.onPacket(decodePacketFromBinary(value, binaryFlag, "arraybuffer"));
  4756. binaryFlag = false;
  4757. }
  4758. read();
  4759. })["catch"](function (err) {});
  4760. };
  4761. read();
  4762. var handshake = _this.query.sid ? "0{\"sid\":\"".concat(_this.query.sid, "\"}") : "0";
  4763. _this.writer.write(new TextEncoder().encode(handshake)).then(function () {
  4764. return _this.onOpen();
  4765. });
  4766. });
  4767. });
  4768. }
  4769. }, {
  4770. key: "write",
  4771. value: function write(packets) {
  4772. var _this2 = this;
  4773. this.writable = false;
  4774. var _loop = function _loop() {
  4775. var packet = packets[i];
  4776. var lastPacket = i === packets.length - 1;
  4777. encodePacketToBinary(packet, function (data) {
  4778. if (shouldIncludeBinaryHeader(packet, data)) {
  4779. _this2.writer.write(Uint8Array.of(54));
  4780. }
  4781. _this2.writer.write(data).then(function () {
  4782. if (lastPacket) {
  4783. nextTick(function () {
  4784. _this2.writable = true;
  4785. _this2.emitReserved("drain");
  4786. }, _this2.setTimeoutFn);
  4787. }
  4788. });
  4789. });
  4790. };
  4791. for (var i = 0; i < packets.length; i++) {
  4792. _loop();
  4793. }
  4794. }
  4795. }, {
  4796. key: "doClose",
  4797. value: function doClose() {
  4798. var _a;
  4799. (_a = this.transport) === null || _a === void 0 ? void 0 : _a.close();
  4800. }
  4801. }]);
  4802. return WT;
  4803. }(Transport);
  4804. var transports = {
  4805. websocket: WS,
  4806. webtransport: WT,
  4807. polling: Polling
  4808. };
  4809. // imported from https://github.com/galkn/parseuri
  4810. /**
  4811. * Parses a URI
  4812. *
  4813. * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
  4814. *
  4815. * See:
  4816. * - https://developer.mozilla.org/en-US/docs/Web/API/URL
  4817. * - https://caniuse.com/url
  4818. * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
  4819. *
  4820. * History of the parse() method:
  4821. * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
  4822. * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
  4823. * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
  4824. *
  4825. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  4826. * @api private
  4827. */
  4828. var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  4829. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  4830. function parse(str) {
  4831. var src = str,
  4832. b = str.indexOf('['),
  4833. e = str.indexOf(']');
  4834. if (b != -1 && e != -1) {
  4835. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  4836. }
  4837. var m = re.exec(str || ''),
  4838. uri = {},
  4839. i = 14;
  4840. while (i--) {
  4841. uri[parts[i]] = m[i] || '';
  4842. }
  4843. if (b != -1 && e != -1) {
  4844. uri.source = src;
  4845. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  4846. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  4847. uri.ipv6uri = true;
  4848. }
  4849. uri.pathNames = pathNames(uri, uri['path']);
  4850. uri.queryKey = queryKey(uri, uri['query']);
  4851. return uri;
  4852. }
  4853. function pathNames(obj, path) {
  4854. var regx = /\/{2,9}/g,
  4855. names = path.replace(regx, "/").split("/");
  4856. if (path.slice(0, 1) == '/' || path.length === 0) {
  4857. names.splice(0, 1);
  4858. }
  4859. if (path.slice(-1) == '/') {
  4860. names.splice(names.length - 1, 1);
  4861. }
  4862. return names;
  4863. }
  4864. function queryKey(uri, query) {
  4865. var data = {};
  4866. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  4867. if ($1) {
  4868. data[$1] = $2;
  4869. }
  4870. });
  4871. return data;
  4872. }
  4873. var Socket = /*#__PURE__*/function (_Emitter) {
  4874. _inherits(Socket, _Emitter);
  4875. var _super = _createSuper(Socket);
  4876. /**
  4877. * Socket constructor.
  4878. *
  4879. * @param {String|Object} uri - uri or options
  4880. * @param {Object} opts - options
  4881. */
  4882. function Socket(uri) {
  4883. var _this;
  4884. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  4885. _classCallCheck(this, Socket);
  4886. _this = _super.call(this);
  4887. _this.writeBuffer = [];
  4888. if (uri && "object" === _typeof(uri)) {
  4889. opts = uri;
  4890. uri = null;
  4891. }
  4892. if (uri) {
  4893. uri = parse(uri);
  4894. opts.hostname = uri.host;
  4895. opts.secure = uri.protocol === "https" || uri.protocol === "wss";
  4896. opts.port = uri.port;
  4897. if (uri.query) opts.query = uri.query;
  4898. } else if (opts.host) {
  4899. opts.hostname = parse(opts.host).host;
  4900. }
  4901. installTimerFunctions(_assertThisInitialized(_this), opts);
  4902. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  4903. if (opts.hostname && !opts.port) {
  4904. // if no port is specified manually, use the protocol default
  4905. opts.port = _this.secure ? "443" : "80";
  4906. }
  4907. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  4908. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  4909. _this.transports = opts.transports || ["polling", "websocket", "webtransport"];
  4910. _this.writeBuffer = [];
  4911. _this.prevBufferLen = 0;
  4912. _this.opts = _extends({
  4913. path: "/engine.io",
  4914. agent: false,
  4915. withCredentials: false,
  4916. upgrade: true,
  4917. timestampParam: "t",
  4918. rememberUpgrade: false,
  4919. addTrailingSlash: true,
  4920. rejectUnauthorized: true,
  4921. perMessageDeflate: {
  4922. threshold: 1024
  4923. },
  4924. transportOptions: {},
  4925. closeOnBeforeunload: false
  4926. }, opts);
  4927. _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : "");
  4928. if (typeof _this.opts.query === "string") {
  4929. _this.opts.query = decode(_this.opts.query);
  4930. }
  4931. // set on handshake
  4932. _this.id = null;
  4933. _this.upgrades = null;
  4934. _this.pingInterval = null;
  4935. _this.pingTimeout = null;
  4936. // set on heartbeat
  4937. _this.pingTimeoutTimer = null;
  4938. if (typeof addEventListener === "function") {
  4939. if (_this.opts.closeOnBeforeunload) {
  4940. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  4941. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  4942. // closed/reloaded)
  4943. _this.beforeunloadEventListener = function () {
  4944. if (_this.transport) {
  4945. // silently close the transport
  4946. _this.transport.removeAllListeners();
  4947. _this.transport.close();
  4948. }
  4949. };
  4950. addEventListener("beforeunload", _this.beforeunloadEventListener, false);
  4951. }
  4952. if (_this.hostname !== "localhost") {
  4953. _this.offlineEventListener = function () {
  4954. _this.onClose("transport close", {
  4955. description: "network connection lost"
  4956. });
  4957. };
  4958. addEventListener("offline", _this.offlineEventListener, false);
  4959. }
  4960. }
  4961. _this.open();
  4962. return _this;
  4963. }
  4964. /**
  4965. * Creates transport of the given type.
  4966. *
  4967. * @param {String} name - transport name
  4968. * @return {Transport}
  4969. * @private
  4970. */
  4971. _createClass(Socket, [{
  4972. key: "createTransport",
  4973. value: function createTransport(name) {
  4974. var query = _extends({}, this.opts.query);
  4975. // append engine.io protocol identifier
  4976. query.EIO = protocol;
  4977. // transport name
  4978. query.transport = name;
  4979. // session id if we already have one
  4980. if (this.id) query.sid = this.id;
  4981. var opts = _extends({}, this.opts, {
  4982. query: query,
  4983. socket: this,
  4984. hostname: this.hostname,
  4985. secure: this.secure,
  4986. port: this.port
  4987. }, this.opts.transportOptions[name]);
  4988. return new transports[name](opts);
  4989. }
  4990. /**
  4991. * Initializes transport to use and starts probe.
  4992. *
  4993. * @private
  4994. */
  4995. }, {
  4996. key: "open",
  4997. value: function open() {
  4998. var _this2 = this;
  4999. var transport;
  5000. if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
  5001. transport = "websocket";
  5002. } else if (0 === this.transports.length) {
  5003. // Emit error on next tick so it can be listened to
  5004. this.setTimeoutFn(function () {
  5005. _this2.emitReserved("error", "No transports available");
  5006. }, 0);
  5007. return;
  5008. } else {
  5009. transport = this.transports[0];
  5010. }
  5011. this.readyState = "opening";
  5012. // Retry with the next transport if the transport is disabled (jsonp: false)
  5013. try {
  5014. transport = this.createTransport(transport);
  5015. } catch (e) {
  5016. this.transports.shift();
  5017. this.open();
  5018. return;
  5019. }
  5020. transport.open();
  5021. this.setTransport(transport);
  5022. }
  5023. /**
  5024. * Sets the current transport. Disables the existing one (if any).
  5025. *
  5026. * @private
  5027. */
  5028. }, {
  5029. key: "setTransport",
  5030. value: function setTransport(transport) {
  5031. var _this3 = this;
  5032. if (this.transport) {
  5033. this.transport.removeAllListeners();
  5034. }
  5035. // set up transport
  5036. this.transport = transport;
  5037. // set up transport listeners
  5038. transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) {
  5039. return _this3.onClose("transport close", reason);
  5040. });
  5041. }
  5042. /**
  5043. * Probes a transport.
  5044. *
  5045. * @param {String} name - transport name
  5046. * @private
  5047. */
  5048. }, {
  5049. key: "probe",
  5050. value: function probe(name) {
  5051. var _this4 = this;
  5052. var transport = this.createTransport(name);
  5053. var failed = false;
  5054. Socket.priorWebsocketSuccess = false;
  5055. var onTransportOpen = function onTransportOpen() {
  5056. if (failed) return;
  5057. transport.send([{
  5058. type: "ping",
  5059. data: "probe"
  5060. }]);
  5061. transport.once("packet", function (msg) {
  5062. if (failed) return;
  5063. if ("pong" === msg.type && "probe" === msg.data) {
  5064. _this4.upgrading = true;
  5065. _this4.emitReserved("upgrading", transport);
  5066. if (!transport) return;
  5067. Socket.priorWebsocketSuccess = "websocket" === transport.name;
  5068. _this4.transport.pause(function () {
  5069. if (failed) return;
  5070. if ("closed" === _this4.readyState) return;
  5071. cleanup();
  5072. _this4.setTransport(transport);
  5073. transport.send([{
  5074. type: "upgrade"
  5075. }]);
  5076. _this4.emitReserved("upgrade", transport);
  5077. transport = null;
  5078. _this4.upgrading = false;
  5079. _this4.flush();
  5080. });
  5081. } else {
  5082. var err = new Error("probe error");
  5083. // @ts-ignore
  5084. err.transport = transport.name;
  5085. _this4.emitReserved("upgradeError", err);
  5086. }
  5087. });
  5088. };
  5089. function freezeTransport() {
  5090. if (failed) return;
  5091. // Any callback called by transport should be ignored since now
  5092. failed = true;
  5093. cleanup();
  5094. transport.close();
  5095. transport = null;
  5096. }
  5097. // Handle any error that happens while probing
  5098. var onerror = function onerror(err) {
  5099. var error = new Error("probe error: " + err);
  5100. // @ts-ignore
  5101. error.transport = transport.name;
  5102. freezeTransport();
  5103. _this4.emitReserved("upgradeError", error);
  5104. };
  5105. function onTransportClose() {
  5106. onerror("transport closed");
  5107. }
  5108. // When the socket is closed while we're probing
  5109. function onclose() {
  5110. onerror("socket closed");
  5111. }
  5112. // When the socket is upgraded while we're probing
  5113. function onupgrade(to) {
  5114. if (transport && to.name !== transport.name) {
  5115. freezeTransport();
  5116. }
  5117. }
  5118. // Remove all listeners on the transport and on self
  5119. var cleanup = function cleanup() {
  5120. transport.removeListener("open", onTransportOpen);
  5121. transport.removeListener("error", onerror);
  5122. transport.removeListener("close", onTransportClose);
  5123. _this4.off("close", onclose);
  5124. _this4.off("upgrading", onupgrade);
  5125. };
  5126. transport.once("open", onTransportOpen);
  5127. transport.once("error", onerror);
  5128. transport.once("close", onTransportClose);
  5129. this.once("close", onclose);
  5130. this.once("upgrading", onupgrade);
  5131. if (this.upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
  5132. // favor WebTransport
  5133. this.setTimeoutFn(function () {
  5134. if (!failed) {
  5135. transport.open();
  5136. }
  5137. }, 200);
  5138. } else {
  5139. transport.open();
  5140. }
  5141. }
  5142. /**
  5143. * Called when connection is deemed open.
  5144. *
  5145. * @private
  5146. */
  5147. }, {
  5148. key: "onOpen",
  5149. value: function onOpen() {
  5150. this.readyState = "open";
  5151. Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
  5152. this.emitReserved("open");
  5153. this.flush();
  5154. // we check for `readyState` in case an `open`
  5155. // listener already closed the socket
  5156. if ("open" === this.readyState && this.opts.upgrade) {
  5157. var i = 0;
  5158. var l = this.upgrades.length;
  5159. for (; i < l; i++) {
  5160. this.probe(this.upgrades[i]);
  5161. }
  5162. }
  5163. }
  5164. /**
  5165. * Handles a packet.
  5166. *
  5167. * @private
  5168. */
  5169. }, {
  5170. key: "onPacket",
  5171. value: function onPacket(packet) {
  5172. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  5173. this.emitReserved("packet", packet);
  5174. // Socket is live - any packet counts
  5175. this.emitReserved("heartbeat");
  5176. switch (packet.type) {
  5177. case "open":
  5178. this.onHandshake(JSON.parse(packet.data));
  5179. break;
  5180. case "ping":
  5181. this.resetPingTimeout();
  5182. this.sendPacket("pong");
  5183. this.emitReserved("ping");
  5184. this.emitReserved("pong");
  5185. break;
  5186. case "error":
  5187. var err = new Error("server error");
  5188. // @ts-ignore
  5189. err.code = packet.data;
  5190. this.onError(err);
  5191. break;
  5192. case "message":
  5193. this.emitReserved("data", packet.data);
  5194. this.emitReserved("message", packet.data);
  5195. break;
  5196. }
  5197. }
  5198. }
  5199. /**
  5200. * Called upon handshake completion.
  5201. *
  5202. * @param {Object} data - handshake obj
  5203. * @private
  5204. */
  5205. }, {
  5206. key: "onHandshake",
  5207. value: function onHandshake(data) {
  5208. this.emitReserved("handshake", data);
  5209. this.id = data.sid;
  5210. this.transport.query.sid = data.sid;
  5211. this.upgrades = this.filterUpgrades(data.upgrades);
  5212. this.pingInterval = data.pingInterval;
  5213. this.pingTimeout = data.pingTimeout;
  5214. this.maxPayload = data.maxPayload;
  5215. this.onOpen();
  5216. // In case open handler closes socket
  5217. if ("closed" === this.readyState) return;
  5218. this.resetPingTimeout();
  5219. }
  5220. /**
  5221. * Sets and resets ping timeout timer based on server pings.
  5222. *
  5223. * @private
  5224. */
  5225. }, {
  5226. key: "resetPingTimeout",
  5227. value: function resetPingTimeout() {
  5228. var _this5 = this;
  5229. this.clearTimeoutFn(this.pingTimeoutTimer);
  5230. this.pingTimeoutTimer = this.setTimeoutFn(function () {
  5231. _this5.onClose("ping timeout");
  5232. }, this.pingInterval + this.pingTimeout);
  5233. if (this.opts.autoUnref) {
  5234. this.pingTimeoutTimer.unref();
  5235. }
  5236. }
  5237. /**
  5238. * Called on `drain` event
  5239. *
  5240. * @private
  5241. */
  5242. }, {
  5243. key: "onDrain",
  5244. value: function onDrain() {
  5245. this.writeBuffer.splice(0, this.prevBufferLen);
  5246. // setting prevBufferLen = 0 is very important
  5247. // for example, when upgrading, upgrade packet is sent over,
  5248. // and a nonzero prevBufferLen could cause problems on `drain`
  5249. this.prevBufferLen = 0;
  5250. if (0 === this.writeBuffer.length) {
  5251. this.emitReserved("drain");
  5252. } else {
  5253. this.flush();
  5254. }
  5255. }
  5256. /**
  5257. * Flush write buffers.
  5258. *
  5259. * @private
  5260. */
  5261. }, {
  5262. key: "flush",
  5263. value: function flush() {
  5264. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  5265. var packets = this.getWritablePackets();
  5266. this.transport.send(packets);
  5267. // keep track of current length of writeBuffer
  5268. // splice writeBuffer and callbackBuffer on `drain`
  5269. this.prevBufferLen = packets.length;
  5270. this.emitReserved("flush");
  5271. }
  5272. }
  5273. /**
  5274. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  5275. * long-polling)
  5276. *
  5277. * @private
  5278. */
  5279. }, {
  5280. key: "getWritablePackets",
  5281. value: function getWritablePackets() {
  5282. var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  5283. if (!shouldCheckPayloadSize) {
  5284. return this.writeBuffer;
  5285. }
  5286. var payloadSize = 1; // first packet type
  5287. for (var i = 0; i < this.writeBuffer.length; i++) {
  5288. var data = this.writeBuffer[i].data;
  5289. if (data) {
  5290. payloadSize += byteLength(data);
  5291. }
  5292. if (i > 0 && payloadSize > this.maxPayload) {
  5293. return this.writeBuffer.slice(0, i);
  5294. }
  5295. payloadSize += 2; // separator + packet type
  5296. }
  5297. return this.writeBuffer;
  5298. }
  5299. /**
  5300. * Sends a message.
  5301. *
  5302. * @param {String} msg - message.
  5303. * @param {Object} options.
  5304. * @param {Function} callback function.
  5305. * @return {Socket} for chaining.
  5306. */
  5307. }, {
  5308. key: "write",
  5309. value: function write(msg, options, fn) {
  5310. this.sendPacket("message", msg, options, fn);
  5311. return this;
  5312. }
  5313. }, {
  5314. key: "send",
  5315. value: function send(msg, options, fn) {
  5316. this.sendPacket("message", msg, options, fn);
  5317. return this;
  5318. }
  5319. /**
  5320. * Sends a packet.
  5321. *
  5322. * @param {String} type: packet type.
  5323. * @param {String} data.
  5324. * @param {Object} options.
  5325. * @param {Function} fn - callback function.
  5326. * @private
  5327. */
  5328. }, {
  5329. key: "sendPacket",
  5330. value: function sendPacket(type, data, options, fn) {
  5331. if ("function" === typeof data) {
  5332. fn = data;
  5333. data = undefined;
  5334. }
  5335. if ("function" === typeof options) {
  5336. fn = options;
  5337. options = null;
  5338. }
  5339. if ("closing" === this.readyState || "closed" === this.readyState) {
  5340. return;
  5341. }
  5342. options = options || {};
  5343. options.compress = false !== options.compress;
  5344. var packet = {
  5345. type: type,
  5346. data: data,
  5347. options: options
  5348. };
  5349. this.emitReserved("packetCreate", packet);
  5350. this.writeBuffer.push(packet);
  5351. if (fn) this.once("flush", fn);
  5352. this.flush();
  5353. }
  5354. /**
  5355. * Closes the connection.
  5356. */
  5357. }, {
  5358. key: "close",
  5359. value: function close() {
  5360. var _this6 = this;
  5361. var close = function close() {
  5362. _this6.onClose("forced close");
  5363. _this6.transport.close();
  5364. };
  5365. var cleanupAndClose = function cleanupAndClose() {
  5366. _this6.off("upgrade", cleanupAndClose);
  5367. _this6.off("upgradeError", cleanupAndClose);
  5368. close();
  5369. };
  5370. var waitForUpgrade = function waitForUpgrade() {
  5371. // wait for upgrade to finish since we can't send packets while pausing a transport
  5372. _this6.once("upgrade", cleanupAndClose);
  5373. _this6.once("upgradeError", cleanupAndClose);
  5374. };
  5375. if ("opening" === this.readyState || "open" === this.readyState) {
  5376. this.readyState = "closing";
  5377. if (this.writeBuffer.length) {
  5378. this.once("drain", function () {
  5379. if (_this6.upgrading) {
  5380. waitForUpgrade();
  5381. } else {
  5382. close();
  5383. }
  5384. });
  5385. } else if (this.upgrading) {
  5386. waitForUpgrade();
  5387. } else {
  5388. close();
  5389. }
  5390. }
  5391. return this;
  5392. }
  5393. /**
  5394. * Called upon transport error
  5395. *
  5396. * @private
  5397. */
  5398. }, {
  5399. key: "onError",
  5400. value: function onError(err) {
  5401. Socket.priorWebsocketSuccess = false;
  5402. this.emitReserved("error", err);
  5403. this.onClose("transport error", err);
  5404. }
  5405. /**
  5406. * Called upon transport close.
  5407. *
  5408. * @private
  5409. */
  5410. }, {
  5411. key: "onClose",
  5412. value: function onClose(reason, description) {
  5413. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  5414. // clear timers
  5415. this.clearTimeoutFn(this.pingTimeoutTimer);
  5416. // stop event from firing again for transport
  5417. this.transport.removeAllListeners("close");
  5418. // ensure transport won't stay open
  5419. this.transport.close();
  5420. // ignore further transport communication
  5421. this.transport.removeAllListeners();
  5422. if (typeof removeEventListener === "function") {
  5423. removeEventListener("beforeunload", this.beforeunloadEventListener, false);
  5424. removeEventListener("offline", this.offlineEventListener, false);
  5425. }
  5426. // set ready state
  5427. this.readyState = "closed";
  5428. // clear session id
  5429. this.id = null;
  5430. // emit close event
  5431. this.emitReserved("close", reason, description);
  5432. // clean buffers after, so users can still
  5433. // grab the buffers on `close` event
  5434. this.writeBuffer = [];
  5435. this.prevBufferLen = 0;
  5436. }
  5437. }
  5438. /**
  5439. * Filters upgrades, returning only those matching client transports.
  5440. *
  5441. * @param {Array} upgrades - server upgrades
  5442. * @private
  5443. */
  5444. }, {
  5445. key: "filterUpgrades",
  5446. value: function filterUpgrades(upgrades) {
  5447. var filteredUpgrades = [];
  5448. var i = 0;
  5449. var j = upgrades.length;
  5450. for (; i < j; i++) {
  5451. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  5452. }
  5453. return filteredUpgrades;
  5454. }
  5455. }]);
  5456. return Socket;
  5457. }(Emitter);
  5458. Socket.protocol = protocol;
  5459. var browserEntrypoint = (function (uri, opts) {
  5460. return new Socket(uri, opts);
  5461. });
  5462. return browserEntrypoint;
  5463. })();
  5464. return eio;
  5465. });
  5466. }
  5467. ]);