PageRenderTime 1118ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/client/www/js/lib/socket.io.js

https://github.com/Panoptico/NetSense
JavaScript | 6172 lines | 3458 code | 953 blank | 1761 comment | 975 complexity | b7f1f9f5bf365f2b451e737440125134 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.io=e():"undefined"!=typeof global?global.io=e():"undefined"!=typeof self&&(self.io=e())}(function(){var define,module,exports;
  2. return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  3. module.exports = require('./lib/');
  4. },{"./lib/":2}],2:[function(require,module,exports){
  5. /**
  6. * Module dependencies.
  7. */
  8. var url = require('./url');
  9. var parser = require('socket.io-parser');
  10. var Manager = require('./manager');
  11. var debug = require('debug')('socket.io-client');
  12. /**
  13. * Module exports.
  14. */
  15. module.exports = exports = lookup;
  16. /**
  17. * Managers cache.
  18. */
  19. var cache = exports.managers = {};
  20. /**
  21. * Looks up an existing `Manager` for multiplexing.
  22. * If the user summons:
  23. *
  24. * `io('http://localhost/a');`
  25. * `io('http://localhost/b');`
  26. *
  27. * We reuse the existing instance based on same scheme/port/host,
  28. * and we initialize sockets for each namespace.
  29. *
  30. * @api public
  31. */
  32. function lookup(uri, opts) {
  33. if (typeof uri == 'object') {
  34. opts = uri;
  35. uri = undefined;
  36. }
  37. opts = opts || {};
  38. var parsed = url(uri);
  39. var source = parsed.source;
  40. var id = parsed.id;
  41. var io;
  42. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  43. debug('ignoring socket cache for %s', source);
  44. io = Manager(source, opts);
  45. } else {
  46. if (!cache[id]) {
  47. debug('new io instance for %s', source);
  48. cache[id] = Manager(source, opts);
  49. }
  50. io = cache[id];
  51. }
  52. return io.socket(parsed.path);
  53. }
  54. /**
  55. * Protocol version.
  56. *
  57. * @api public
  58. */
  59. exports.protocol = parser.protocol;
  60. /**
  61. * `connect`.
  62. *
  63. * @param {String} uri
  64. * @api public
  65. */
  66. exports.connect = lookup;
  67. /**
  68. * Expose constructors for standalone build.
  69. *
  70. * @api public
  71. */
  72. exports.Manager = require('./manager');
  73. exports.Socket = require('./socket');
  74. },{"./manager":3,"./socket":5,"./url":6,"debug":9,"socket.io-parser":40}],3:[function(require,module,exports){
  75. /**
  76. * Module dependencies.
  77. */
  78. var url = require('./url');
  79. var eio = require('engine.io-client');
  80. var Socket = require('./socket');
  81. var Emitter = require('component-emitter');
  82. var parser = require('socket.io-parser');
  83. var on = require('./on');
  84. var bind = require('component-bind');
  85. var object = require('object-component');
  86. var debug = require('debug')('socket.io-client:manager');
  87. /**
  88. * Module exports
  89. */
  90. module.exports = Manager;
  91. /**
  92. * `Manager` constructor.
  93. *
  94. * @param {String} engine instance or engine uri/opts
  95. * @param {Object} options
  96. * @api public
  97. */
  98. function Manager(uri, opts){
  99. if (!(this instanceof Manager)) return new Manager(uri, opts);
  100. if (uri && ('object' == typeof uri)) {
  101. opts = uri;
  102. uri = undefined;
  103. }
  104. opts = opts || {};
  105. opts.path = opts.path || '/socket.io';
  106. this.nsps = {};
  107. this.subs = [];
  108. this.opts = opts;
  109. this.reconnection(opts.reconnection !== false);
  110. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  111. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  112. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  113. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  114. this.readyState = 'closed';
  115. this.uri = uri;
  116. this.connected = 0;
  117. this.attempts = 0;
  118. this.encoding = false;
  119. this.packetBuffer = [];
  120. this.encoder = new parser.Encoder();
  121. this.decoder = new parser.Decoder();
  122. this.open();
  123. }
  124. /**
  125. * Propagate given event to sockets and emit on `this`
  126. *
  127. * @api private
  128. */
  129. Manager.prototype.emitAll = function() {
  130. this.emit.apply(this, arguments);
  131. for (var nsp in this.nsps) {
  132. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  133. }
  134. };
  135. /**
  136. * Mix in `Emitter`.
  137. */
  138. Emitter(Manager.prototype);
  139. /**
  140. * Sets the `reconnection` config.
  141. *
  142. * @param {Boolean} true/false if it should automatically reconnect
  143. * @return {Manager} self or value
  144. * @api public
  145. */
  146. Manager.prototype.reconnection = function(v){
  147. if (!arguments.length) return this._reconnection;
  148. this._reconnection = !!v;
  149. return this;
  150. };
  151. /**
  152. * Sets the reconnection attempts config.
  153. *
  154. * @param {Number} max reconnection attempts before giving up
  155. * @return {Manager} self or value
  156. * @api public
  157. */
  158. Manager.prototype.reconnectionAttempts = function(v){
  159. if (!arguments.length) return this._reconnectionAttempts;
  160. this._reconnectionAttempts = v;
  161. return this;
  162. };
  163. /**
  164. * Sets the delay between reconnections.
  165. *
  166. * @param {Number} delay
  167. * @return {Manager} self or value
  168. * @api public
  169. */
  170. Manager.prototype.reconnectionDelay = function(v){
  171. if (!arguments.length) return this._reconnectionDelay;
  172. this._reconnectionDelay = v;
  173. return this;
  174. };
  175. /**
  176. * Sets the maximum delay between reconnections.
  177. *
  178. * @param {Number} delay
  179. * @return {Manager} self or value
  180. * @api public
  181. */
  182. Manager.prototype.reconnectionDelayMax = function(v){
  183. if (!arguments.length) return this._reconnectionDelayMax;
  184. this._reconnectionDelayMax = v;
  185. return this;
  186. };
  187. /**
  188. * Sets the connection timeout. `false` to disable
  189. *
  190. * @return {Manager} self or value
  191. * @api public
  192. */
  193. Manager.prototype.timeout = function(v){
  194. if (!arguments.length) return this._timeout;
  195. this._timeout = v;
  196. return this;
  197. };
  198. /**
  199. * Starts trying to reconnect if reconnection is enabled and we have not
  200. * started reconnecting yet
  201. *
  202. * @api private
  203. */
  204. Manager.prototype.maybeReconnectOnOpen = function() {
  205. if (!this.openReconnect && !this.reconnecting && this._reconnection) {
  206. // keeps reconnection from firing twice for the same reconnection loop
  207. this.openReconnect = true;
  208. this.reconnect();
  209. }
  210. };
  211. /**
  212. * Sets the current transport `socket`.
  213. *
  214. * @param {Function} optional, callback
  215. * @return {Manager} self
  216. * @api public
  217. */
  218. Manager.prototype.open =
  219. Manager.prototype.connect = function(fn){
  220. debug('readyState %s', this.readyState);
  221. if (~this.readyState.indexOf('open')) return this;
  222. debug('opening %s', this.uri);
  223. this.engine = eio(this.uri, this.opts);
  224. var socket = this.engine;
  225. var self = this;
  226. this.readyState = 'opening';
  227. // emit `open`
  228. var openSub = on(socket, 'open', function() {
  229. self.onopen();
  230. fn && fn();
  231. });
  232. // emit `connect_error`
  233. var errorSub = on(socket, 'error', function(data){
  234. debug('connect_error');
  235. self.cleanup();
  236. self.readyState = 'closed';
  237. self.emitAll('connect_error', data);
  238. if (fn) {
  239. var err = new Error('Connection error');
  240. err.data = data;
  241. fn(err);
  242. }
  243. self.maybeReconnectOnOpen();
  244. });
  245. // emit `connect_timeout`
  246. if (false !== this._timeout) {
  247. var timeout = this._timeout;
  248. debug('connect attempt will timeout after %d', timeout);
  249. // set timer
  250. var timer = setTimeout(function(){
  251. debug('connect attempt timed out after %d', timeout);
  252. openSub.destroy();
  253. socket.close();
  254. socket.emit('error', 'timeout');
  255. self.emitAll('connect_timeout', timeout);
  256. }, timeout);
  257. this.subs.push({
  258. destroy: function(){
  259. clearTimeout(timer);
  260. }
  261. });
  262. }
  263. this.subs.push(openSub);
  264. this.subs.push(errorSub);
  265. return this;
  266. };
  267. /**
  268. * Called upon transport open.
  269. *
  270. * @api private
  271. */
  272. Manager.prototype.onopen = function(){
  273. debug('open');
  274. // clear old subs
  275. this.cleanup();
  276. // mark as open
  277. this.readyState = 'open';
  278. this.emit('open');
  279. // add new subs
  280. var socket = this.engine;
  281. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  282. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  283. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  284. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  285. };
  286. /**
  287. * Called with data.
  288. *
  289. * @api private
  290. */
  291. Manager.prototype.ondata = function(data){
  292. this.decoder.add(data);
  293. };
  294. /**
  295. * Called when parser fully decodes a packet.
  296. *
  297. * @api private
  298. */
  299. Manager.prototype.ondecoded = function(packet) {
  300. this.emit('packet', packet);
  301. };
  302. /**
  303. * Called upon socket error.
  304. *
  305. * @api private
  306. */
  307. Manager.prototype.onerror = function(err){
  308. debug('error', err);
  309. this.emitAll('error', err);
  310. };
  311. /**
  312. * Creates a new socket for the given `nsp`.
  313. *
  314. * @return {Socket}
  315. * @api public
  316. */
  317. Manager.prototype.socket = function(nsp){
  318. var socket = this.nsps[nsp];
  319. if (!socket) {
  320. socket = new Socket(this, nsp);
  321. this.nsps[nsp] = socket;
  322. var self = this;
  323. socket.on('connect', function(){
  324. self.connected++;
  325. });
  326. }
  327. return socket;
  328. };
  329. /**
  330. * Called upon a socket close.
  331. *
  332. * @param {Socket} socket
  333. */
  334. Manager.prototype.destroy = function(socket){
  335. --this.connected || this.close();
  336. };
  337. /**
  338. * Writes a packet.
  339. *
  340. * @param {Object} packet
  341. * @api private
  342. */
  343. Manager.prototype.packet = function(packet){
  344. debug('writing packet %j', packet);
  345. var self = this;
  346. if (!self.encoding) {
  347. // encode, then write to engine with result
  348. self.encoding = true;
  349. this.encoder.encode(packet, function(encodedPackets) {
  350. for (var i = 0; i < encodedPackets.length; i++) {
  351. self.engine.write(encodedPackets[i]);
  352. }
  353. self.encoding = false;
  354. self.processPacketQueue();
  355. });
  356. } else { // add packet to the queue
  357. self.packetBuffer.push(packet);
  358. }
  359. };
  360. /**
  361. * If packet buffer is non-empty, begins encoding the
  362. * next packet in line.
  363. *
  364. * @api private
  365. */
  366. Manager.prototype.processPacketQueue = function() {
  367. if (this.packetBuffer.length > 0 && !this.encoding) {
  368. var pack = this.packetBuffer.shift();
  369. this.packet(pack);
  370. }
  371. };
  372. /**
  373. * Clean up transport subscriptions and packet buffer.
  374. *
  375. * @api private
  376. */
  377. Manager.prototype.cleanup = function(){
  378. var sub;
  379. while (sub = this.subs.shift()) sub.destroy();
  380. this.packetBuffer = [];
  381. this.encoding = false;
  382. this.decoder.destroy();
  383. };
  384. /**
  385. * Close the current socket.
  386. *
  387. * @api private
  388. */
  389. Manager.prototype.close =
  390. Manager.prototype.disconnect = function(){
  391. this.skipReconnect = true;
  392. this.engine.close();
  393. };
  394. /**
  395. * Called upon engine close.
  396. *
  397. * @api private
  398. */
  399. Manager.prototype.onclose = function(reason){
  400. debug('close');
  401. this.cleanup();
  402. this.readyState = 'closed';
  403. this.emit('close', reason);
  404. if (this._reconnection && !this.skipReconnect) {
  405. this.reconnect();
  406. }
  407. };
  408. /**
  409. * Attempt a reconnection.
  410. *
  411. * @api private
  412. */
  413. Manager.prototype.reconnect = function(){
  414. if (this.reconnecting) return this;
  415. var self = this;
  416. this.attempts++;
  417. if (this.attempts > this._reconnectionAttempts) {
  418. debug('reconnect failed');
  419. this.emitAll('reconnect_failed');
  420. this.reconnecting = false;
  421. } else {
  422. var delay = this.attempts * this.reconnectionDelay();
  423. delay = Math.min(delay, this.reconnectionDelayMax());
  424. debug('will wait %dms before reconnect attempt', delay);
  425. this.reconnecting = true;
  426. var timer = setTimeout(function(){
  427. debug('attempting reconnect');
  428. self.emitAll('reconnect_attempt', self.attempts);
  429. self.emitAll('reconnecting', self.attempts);
  430. self.open(function(err){
  431. if (err) {
  432. debug('reconnect attempt error');
  433. self.reconnecting = false;
  434. self.reconnect();
  435. self.emitAll('reconnect_error', err.data);
  436. } else {
  437. debug('reconnect success');
  438. self.onreconnect();
  439. }
  440. });
  441. }, delay);
  442. this.subs.push({
  443. destroy: function(){
  444. clearTimeout(timer);
  445. }
  446. });
  447. }
  448. };
  449. /**
  450. * Called upon successful reconnect.
  451. *
  452. * @api private
  453. */
  454. Manager.prototype.onreconnect = function(){
  455. var attempt = this.attempts;
  456. this.attempts = 0;
  457. this.reconnecting = false;
  458. this.emitAll('reconnect', attempt);
  459. };
  460. },{"./on":4,"./socket":5,"./url":6,"component-bind":7,"component-emitter":8,"debug":9,"engine.io-client":11,"object-component":37,"socket.io-parser":40}],4:[function(require,module,exports){
  461. /**
  462. * Module exports.
  463. */
  464. module.exports = on;
  465. /**
  466. * Helper for subscriptions.
  467. *
  468. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  469. * @param {String} event name
  470. * @param {Function} callback
  471. * @api public
  472. */
  473. function on(obj, ev, fn) {
  474. obj.on(ev, fn);
  475. return {
  476. destroy: function(){
  477. obj.removeListener(ev, fn);
  478. }
  479. };
  480. }
  481. },{}],5:[function(require,module,exports){
  482. /**
  483. * Module dependencies.
  484. */
  485. var parser = require('socket.io-parser');
  486. var Emitter = require('component-emitter');
  487. var toArray = require('to-array');
  488. var on = require('./on');
  489. var bind = require('component-bind');
  490. var debug = require('debug')('socket.io-client:socket');
  491. var hasBin = require('has-binary-data');
  492. var indexOf = require('indexof');
  493. /**
  494. * Module exports.
  495. */
  496. module.exports = exports = Socket;
  497. /**
  498. * Internal events (blacklisted).
  499. * These events can't be emitted by the user.
  500. *
  501. * @api private
  502. */
  503. var events = {
  504. connect: 1,
  505. connect_error: 1,
  506. connect_timeout: 1,
  507. disconnect: 1,
  508. error: 1,
  509. reconnect: 1,
  510. reconnect_attempt: 1,
  511. reconnect_failed: 1,
  512. reconnect_error: 1,
  513. reconnecting: 1
  514. };
  515. /**
  516. * Shortcut to `Emitter#emit`.
  517. */
  518. var emit = Emitter.prototype.emit;
  519. /**
  520. * `Socket` constructor.
  521. *
  522. * @api public
  523. */
  524. function Socket(io, nsp){
  525. this.io = io;
  526. this.nsp = nsp;
  527. this.json = this; // compat
  528. this.ids = 0;
  529. this.acks = {};
  530. this.open();
  531. this.receiveBuffer = [];
  532. this.sendBuffer = [];
  533. this.connected = false;
  534. this.disconnected = true;
  535. this.subEvents();
  536. }
  537. /**
  538. * Mix in `Emitter`.
  539. */
  540. Emitter(Socket.prototype);
  541. /**
  542. * Subscribe to open, close and packet events
  543. *
  544. * @api private
  545. */
  546. Socket.prototype.subEvents = function() {
  547. var io = this.io;
  548. this.subs = [
  549. on(io, 'open', bind(this, 'onopen')),
  550. on(io, 'packet', bind(this, 'onpacket')),
  551. on(io, 'close', bind(this, 'onclose'))
  552. ];
  553. };
  554. /**
  555. * Called upon engine `open`.
  556. *
  557. * @api private
  558. */
  559. Socket.prototype.open =
  560. Socket.prototype.connect = function(){
  561. if (this.connected) return this;
  562. this.io.open(); // ensure open
  563. if ('open' == this.io.readyState) this.onopen();
  564. return this;
  565. };
  566. /**
  567. * Sends a `message` event.
  568. *
  569. * @return {Socket} self
  570. * @api public
  571. */
  572. Socket.prototype.send = function(){
  573. var args = toArray(arguments);
  574. args.unshift('message');
  575. this.emit.apply(this, args);
  576. return this;
  577. };
  578. /**
  579. * Override `emit`.
  580. * If the event is in `events`, it's emitted normally.
  581. *
  582. * @param {String} event name
  583. * @return {Socket} self
  584. * @api public
  585. */
  586. Socket.prototype.emit = function(ev){
  587. if (events.hasOwnProperty(ev)) {
  588. emit.apply(this, arguments);
  589. return this;
  590. }
  591. var args = toArray(arguments);
  592. var parserType = parser.EVENT; // default
  593. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  594. var packet = { type: parserType, data: args };
  595. // event ack callback
  596. if ('function' == typeof args[args.length - 1]) {
  597. debug('emitting packet with ack id %d', this.ids);
  598. this.acks[this.ids] = args.pop();
  599. packet.id = this.ids++;
  600. }
  601. if (this.connected) {
  602. this.packet(packet);
  603. } else {
  604. this.sendBuffer.push(packet);
  605. }
  606. return this;
  607. };
  608. /**
  609. * Sends a packet.
  610. *
  611. * @param {Object} packet
  612. * @api private
  613. */
  614. Socket.prototype.packet = function(packet){
  615. packet.nsp = this.nsp;
  616. this.io.packet(packet);
  617. };
  618. /**
  619. * "Opens" the socket.
  620. *
  621. * @api private
  622. */
  623. Socket.prototype.onopen = function(){
  624. debug('transport is open - connecting');
  625. // write connect packet if necessary
  626. if ('/' != this.nsp) {
  627. this.packet({ type: parser.CONNECT });
  628. }
  629. };
  630. /**
  631. * Called upon engine `close`.
  632. *
  633. * @param {String} reason
  634. * @api private
  635. */
  636. Socket.prototype.onclose = function(reason){
  637. debug('close (%s)', reason);
  638. this.connected = false;
  639. this.disconnected = true;
  640. this.emit('disconnect', reason);
  641. };
  642. /**
  643. * Called with socket packet.
  644. *
  645. * @param {Object} packet
  646. * @api private
  647. */
  648. Socket.prototype.onpacket = function(packet){
  649. if (packet.nsp != this.nsp) return;
  650. switch (packet.type) {
  651. case parser.CONNECT:
  652. this.onconnect();
  653. break;
  654. case parser.EVENT:
  655. this.onevent(packet);
  656. break;
  657. case parser.BINARY_EVENT:
  658. this.onevent(packet);
  659. break;
  660. case parser.ACK:
  661. this.onack(packet);
  662. break;
  663. case parser.BINARY_ACK:
  664. this.onack(packet);
  665. break;
  666. case parser.DISCONNECT:
  667. this.ondisconnect();
  668. break;
  669. case parser.ERROR:
  670. this.emit('error', packet.data);
  671. break;
  672. }
  673. };
  674. /**
  675. * Called upon a server event.
  676. *
  677. * @param {Object} packet
  678. * @api private
  679. */
  680. Socket.prototype.onevent = function(packet){
  681. var args = packet.data || [];
  682. debug('emitting event %j', args);
  683. if (null != packet.id) {
  684. debug('attaching ack callback to event');
  685. args.push(this.ack(packet.id));
  686. }
  687. if (this.connected) {
  688. emit.apply(this, args);
  689. } else {
  690. this.receiveBuffer.push(args);
  691. }
  692. };
  693. /**
  694. * Produces an ack callback to emit with an event.
  695. *
  696. * @api private
  697. */
  698. Socket.prototype.ack = function(id){
  699. var self = this;
  700. var sent = false;
  701. return function(){
  702. // prevent double callbacks
  703. if (sent) return;
  704. sent = true;
  705. var args = toArray(arguments);
  706. debug('sending ack %j', args);
  707. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  708. self.packet({
  709. type: type,
  710. id: id,
  711. data: args
  712. });
  713. };
  714. };
  715. /**
  716. * Called upon a server acknowlegement.
  717. *
  718. * @param {Object} packet
  719. * @api private
  720. */
  721. Socket.prototype.onack = function(packet){
  722. debug('calling ack %s with %j', packet.id, packet.data);
  723. var fn = this.acks[packet.id];
  724. fn.apply(this, packet.data);
  725. delete this.acks[packet.id];
  726. };
  727. /**
  728. * Called upon server connect.
  729. *
  730. * @api private
  731. */
  732. Socket.prototype.onconnect = function(){
  733. this.connected = true;
  734. this.disconnected = false;
  735. this.emit('connect');
  736. this.emitBuffered();
  737. };
  738. /**
  739. * Emit buffered events (received and emitted).
  740. *
  741. * @api private
  742. */
  743. Socket.prototype.emitBuffered = function(){
  744. var i;
  745. for (i = 0; i < this.receiveBuffer.length; i++) {
  746. emit.apply(this, this.receiveBuffer[i]);
  747. }
  748. this.receiveBuffer = [];
  749. for (i = 0; i < this.sendBuffer.length; i++) {
  750. this.packet(this.sendBuffer[i]);
  751. }
  752. this.sendBuffer = [];
  753. };
  754. /**
  755. * Called upon server disconnect.
  756. *
  757. * @api private
  758. */
  759. Socket.prototype.ondisconnect = function(){
  760. debug('server disconnect (%s)', this.nsp);
  761. this.destroy();
  762. this.onclose('io server disconnect');
  763. };
  764. /**
  765. * Called upon forced client/server side disconnections,
  766. * this method ensures the manager stops tracking us and
  767. * that reconnections don't get triggered for this.
  768. *
  769. * @api private.
  770. */
  771. Socket.prototype.destroy = function(){
  772. // clean subscriptions to avoid reconnections
  773. for (var i = 0; i < this.subs.length; i++) {
  774. this.subs[i].destroy();
  775. }
  776. this.io.destroy(this);
  777. };
  778. /**
  779. * Disconnects the socket manually.
  780. *
  781. * @return {Socket} self
  782. * @api public
  783. */
  784. Socket.prototype.close =
  785. Socket.prototype.disconnect = function(){
  786. if (!this.connected) return this;
  787. debug('performing disconnect (%s)', this.nsp);
  788. this.packet({ type: parser.DISCONNECT });
  789. // remove socket from pool
  790. this.destroy();
  791. // fire events
  792. this.onclose('io client disconnect');
  793. return this;
  794. };
  795. },{"./on":4,"component-bind":7,"component-emitter":8,"debug":9,"has-binary-data":32,"indexof":36,"socket.io-parser":40,"to-array":43}],6:[function(require,module,exports){
  796. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
  797. /**
  798. * Module dependencies.
  799. */
  800. var parseuri = require('parseuri');
  801. var debug = require('debug')('socket.io-client:url');
  802. /**
  803. * Module exports.
  804. */
  805. module.exports = url;
  806. /**
  807. * URL parser.
  808. *
  809. * @param {String} url
  810. * @param {Object} An object meant to mimic window.location.
  811. * Defaults to window.location.
  812. * @api public
  813. */
  814. function url(uri, loc){
  815. var obj = uri;
  816. // default to window.location
  817. var loc = loc || global.location;
  818. if (null == uri) uri = loc.protocol + '//' + loc.hostname;
  819. // relative path support
  820. if ('string' == typeof uri) {
  821. if ('/' == uri.charAt(0)) {
  822. if ('undefined' != typeof loc) {
  823. uri = loc.hostname + uri;
  824. }
  825. }
  826. if (!/^(https?|wss?):\/\//.test(uri)) {
  827. debug('protocol-less url %s', uri);
  828. if ('undefined' != typeof loc) {
  829. uri = loc.protocol + '//' + uri;
  830. } else {
  831. uri = 'https://' + uri;
  832. }
  833. }
  834. // parse
  835. debug('parse %s', uri);
  836. obj = parseuri(uri);
  837. }
  838. // make sure we treat `localhost:80` and `localhost` equally
  839. if (!obj.port) {
  840. if (/^(http|ws)$/.test(obj.protocol)) {
  841. obj.port = '80';
  842. }
  843. else if (/^(http|ws)s$/.test(obj.protocol)) {
  844. obj.port = '443';
  845. }
  846. }
  847. obj.path = obj.path || '/';
  848. // define unique id
  849. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  850. // define href
  851. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  852. return obj;
  853. }
  854. },{"debug":9,"parseuri":38}],7:[function(require,module,exports){
  855. /**
  856. * Slice reference.
  857. */
  858. var slice = [].slice;
  859. /**
  860. * Bind `obj` to `fn`.
  861. *
  862. * @param {Object} obj
  863. * @param {Function|String} fn or string
  864. * @return {Function}
  865. * @api public
  866. */
  867. module.exports = function(obj, fn){
  868. if ('string' == typeof fn) fn = obj[fn];
  869. if ('function' != typeof fn) throw new Error('bind() requires a function');
  870. var args = slice.call(arguments, 2);
  871. return function(){
  872. return fn.apply(obj, args.concat(slice.call(arguments)));
  873. }
  874. };
  875. },{}],8:[function(require,module,exports){
  876. /**
  877. * Expose `Emitter`.
  878. */
  879. module.exports = Emitter;
  880. /**
  881. * Initialize a new `Emitter`.
  882. *
  883. * @api public
  884. */
  885. function Emitter(obj) {
  886. if (obj) return mixin(obj);
  887. };
  888. /**
  889. * Mixin the emitter properties.
  890. *
  891. * @param {Object} obj
  892. * @return {Object}
  893. * @api private
  894. */
  895. function mixin(obj) {
  896. for (var key in Emitter.prototype) {
  897. obj[key] = Emitter.prototype[key];
  898. }
  899. return obj;
  900. }
  901. /**
  902. * Listen on the given `event` with `fn`.
  903. *
  904. * @param {String} event
  905. * @param {Function} fn
  906. * @return {Emitter}
  907. * @api public
  908. */
  909. Emitter.prototype.on =
  910. Emitter.prototype.addEventListener = function(event, fn){
  911. this._callbacks = this._callbacks || {};
  912. (this._callbacks[event] = this._callbacks[event] || [])
  913. .push(fn);
  914. return this;
  915. };
  916. /**
  917. * Adds an `event` listener that will be invoked a single
  918. * time then automatically removed.
  919. *
  920. * @param {String} event
  921. * @param {Function} fn
  922. * @return {Emitter}
  923. * @api public
  924. */
  925. Emitter.prototype.once = function(event, fn){
  926. var self = this;
  927. this._callbacks = this._callbacks || {};
  928. function on() {
  929. self.off(event, on);
  930. fn.apply(this, arguments);
  931. }
  932. on.fn = fn;
  933. this.on(event, on);
  934. return this;
  935. };
  936. /**
  937. * Remove the given callback for `event` or all
  938. * registered callbacks.
  939. *
  940. * @param {String} event
  941. * @param {Function} fn
  942. * @return {Emitter}
  943. * @api public
  944. */
  945. Emitter.prototype.off =
  946. Emitter.prototype.removeListener =
  947. Emitter.prototype.removeAllListeners =
  948. Emitter.prototype.removeEventListener = function(event, fn){
  949. this._callbacks = this._callbacks || {};
  950. // all
  951. if (0 == arguments.length) {
  952. this._callbacks = {};
  953. return this;
  954. }
  955. // specific event
  956. var callbacks = this._callbacks[event];
  957. if (!callbacks) return this;
  958. // remove all handlers
  959. if (1 == arguments.length) {
  960. delete this._callbacks[event];
  961. return this;
  962. }
  963. // remove specific handler
  964. var cb;
  965. for (var i = 0; i < callbacks.length; i++) {
  966. cb = callbacks[i];
  967. if (cb === fn || cb.fn === fn) {
  968. callbacks.splice(i, 1);
  969. break;
  970. }
  971. }
  972. return this;
  973. };
  974. /**
  975. * Emit `event` with the given args.
  976. *
  977. * @param {String} event
  978. * @param {Mixed} ...
  979. * @return {Emitter}
  980. */
  981. Emitter.prototype.emit = function(event){
  982. this._callbacks = this._callbacks || {};
  983. var args = [].slice.call(arguments, 1)
  984. , callbacks = this._callbacks[event];
  985. if (callbacks) {
  986. callbacks = callbacks.slice(0);
  987. for (var i = 0, len = callbacks.length; i < len; ++i) {
  988. callbacks[i].apply(this, args);
  989. }
  990. }
  991. return this;
  992. };
  993. /**
  994. * Return array of callbacks for `event`.
  995. *
  996. * @param {String} event
  997. * @return {Array}
  998. * @api public
  999. */
  1000. Emitter.prototype.listeners = function(event){
  1001. this._callbacks = this._callbacks || {};
  1002. return this._callbacks[event] || [];
  1003. };
  1004. /**
  1005. * Check if this emitter has `event` handlers.
  1006. *
  1007. * @param {String} event
  1008. * @return {Boolean}
  1009. * @api public
  1010. */
  1011. Emitter.prototype.hasListeners = function(event){
  1012. return !! this.listeners(event).length;
  1013. };
  1014. },{}],9:[function(require,module,exports){
  1015. /**
  1016. * Expose `debug()` as the module.
  1017. */
  1018. module.exports = debug;
  1019. /**
  1020. * Create a debugger with the given `name`.
  1021. *
  1022. * @param {String} name
  1023. * @return {Type}
  1024. * @api public
  1025. */
  1026. function debug(name) {
  1027. if (!debug.enabled(name)) return function(){};
  1028. return function(fmt){
  1029. fmt = coerce(fmt);
  1030. var curr = new Date;
  1031. var ms = curr - (debug[name] || curr);
  1032. debug[name] = curr;
  1033. fmt = name
  1034. + ' '
  1035. + fmt
  1036. + ' +' + debug.humanize(ms);
  1037. // This hackery is required for IE8
  1038. // where `console.log` doesn't have 'apply'
  1039. window.console
  1040. && console.log
  1041. && Function.prototype.apply.call(console.log, console, arguments);
  1042. }
  1043. }
  1044. /**
  1045. * The currently active debug mode names.
  1046. */
  1047. debug.names = [];
  1048. debug.skips = [];
  1049. /**
  1050. * Enables a debug mode by name. This can include modes
  1051. * separated by a colon and wildcards.
  1052. *
  1053. * @param {String} name
  1054. * @api public
  1055. */
  1056. debug.enable = function(name) {
  1057. try {
  1058. localStorage.debug = name;
  1059. } catch(e){}
  1060. var split = (name || '').split(/[\s,]+/)
  1061. , len = split.length;
  1062. for (var i = 0; i < len; i++) {
  1063. name = split[i].replace('*', '.*?');
  1064. if (name[0] === '-') {
  1065. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  1066. }
  1067. else {
  1068. debug.names.push(new RegExp('^' + name + '$'));
  1069. }
  1070. }
  1071. };
  1072. /**
  1073. * Disable debug output.
  1074. *
  1075. * @api public
  1076. */
  1077. debug.disable = function(){
  1078. debug.enable('');
  1079. };
  1080. /**
  1081. * Humanize the given `ms`.
  1082. *
  1083. * @param {Number} m
  1084. * @return {String}
  1085. * @api private
  1086. */
  1087. debug.humanize = function(ms) {
  1088. var sec = 1000
  1089. , min = 60 * 1000
  1090. , hour = 60 * min;
  1091. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  1092. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  1093. if (ms >= sec) return (ms / sec | 0) + 's';
  1094. return ms + 'ms';
  1095. };
  1096. /**
  1097. * Returns true if the given mode name is enabled, false otherwise.
  1098. *
  1099. * @param {String} name
  1100. * @return {Boolean}
  1101. * @api public
  1102. */
  1103. debug.enabled = function(name) {
  1104. for (var i = 0, len = debug.skips.length; i < len; i++) {
  1105. if (debug.skips[i].test(name)) {
  1106. return false;
  1107. }
  1108. }
  1109. for (var i = 0, len = debug.names.length; i < len; i++) {
  1110. if (debug.names[i].test(name)) {
  1111. return true;
  1112. }
  1113. }
  1114. return false;
  1115. };
  1116. /**
  1117. * Coerce `val`.
  1118. */
  1119. function coerce(val) {
  1120. if (val instanceof Error) return val.stack || val.message;
  1121. return val;
  1122. }
  1123. // persist
  1124. try {
  1125. if (window.localStorage) debug.enable(localStorage.debug);
  1126. } catch(e){}
  1127. },{}],10:[function(require,module,exports){
  1128. /**
  1129. * Module dependencies.
  1130. */
  1131. var index = require('indexof');
  1132. /**
  1133. * Expose `Emitter`.
  1134. */
  1135. module.exports = Emitter;
  1136. /**
  1137. * Initialize a new `Emitter`.
  1138. *
  1139. * @api public
  1140. */
  1141. function Emitter(obj) {
  1142. if (obj) return mixin(obj);
  1143. };
  1144. /**
  1145. * Mixin the emitter properties.
  1146. *
  1147. * @param {Object} obj
  1148. * @return {Object}
  1149. * @api private
  1150. */
  1151. function mixin(obj) {
  1152. for (var key in Emitter.prototype) {
  1153. obj[key] = Emitter.prototype[key];
  1154. }
  1155. return obj;
  1156. }
  1157. /**
  1158. * Listen on the given `event` with `fn`.
  1159. *
  1160. * @param {String} event
  1161. * @param {Function} fn
  1162. * @return {Emitter}
  1163. * @api public
  1164. */
  1165. Emitter.prototype.on = function(event, fn){
  1166. this._callbacks = this._callbacks || {};
  1167. (this._callbacks[event] = this._callbacks[event] || [])
  1168. .push(fn);
  1169. return this;
  1170. };
  1171. /**
  1172. * Adds an `event` listener that will be invoked a single
  1173. * time then automatically removed.
  1174. *
  1175. * @param {String} event
  1176. * @param {Function} fn
  1177. * @return {Emitter}
  1178. * @api public
  1179. */
  1180. Emitter.prototype.once = function(event, fn){
  1181. var self = this;
  1182. this._callbacks = this._callbacks || {};
  1183. function on() {
  1184. self.off(event, on);
  1185. fn.apply(this, arguments);
  1186. }
  1187. fn._off = on;
  1188. this.on(event, on);
  1189. return this;
  1190. };
  1191. /**
  1192. * Remove the given callback for `event` or all
  1193. * registered callbacks.
  1194. *
  1195. * @param {String} event
  1196. * @param {Function} fn
  1197. * @return {Emitter}
  1198. * @api public
  1199. */
  1200. Emitter.prototype.off =
  1201. Emitter.prototype.removeListener =
  1202. Emitter.prototype.removeAllListeners = function(event, fn){
  1203. this._callbacks = this._callbacks || {};
  1204. // all
  1205. if (0 == arguments.length) {
  1206. this._callbacks = {};
  1207. return this;
  1208. }
  1209. // specific event
  1210. var callbacks = this._callbacks[event];
  1211. if (!callbacks) return this;
  1212. // remove all handlers
  1213. if (1 == arguments.length) {
  1214. delete this._callbacks[event];
  1215. return this;
  1216. }
  1217. // remove specific handler
  1218. var i = index(callbacks, fn._off || fn);
  1219. if (~i) callbacks.splice(i, 1);
  1220. return this;
  1221. };
  1222. /**
  1223. * Emit `event` with the given args.
  1224. *
  1225. * @param {String} event
  1226. * @param {Mixed} ...
  1227. * @return {Emitter}
  1228. */
  1229. Emitter.prototype.emit = function(event){
  1230. this._callbacks = this._callbacks || {};
  1231. var args = [].slice.call(arguments, 1)
  1232. , callbacks = this._callbacks[event];
  1233. if (callbacks) {
  1234. callbacks = callbacks.slice(0);
  1235. for (var i = 0, len = callbacks.length; i < len; ++i) {
  1236. callbacks[i].apply(this, args);
  1237. }
  1238. }
  1239. return this;
  1240. };
  1241. /**
  1242. * Return array of callbacks for `event`.
  1243. *
  1244. * @param {String} event
  1245. * @return {Array}
  1246. * @api public
  1247. */
  1248. Emitter.prototype.listeners = function(event){
  1249. this._callbacks = this._callbacks || {};
  1250. return this._callbacks[event] || [];
  1251. };
  1252. /**
  1253. * Check if this emitter has `event` handlers.
  1254. *
  1255. * @param {String} event
  1256. * @return {Boolean}
  1257. * @api public
  1258. */
  1259. Emitter.prototype.hasListeners = function(event){
  1260. return !! this.listeners(event).length;
  1261. };
  1262. },{"indexof":36}],11:[function(require,module,exports){
  1263. module.exports = require('./lib/');
  1264. },{"./lib/":12}],12:[function(require,module,exports){
  1265. module.exports = require('./socket');
  1266. /**
  1267. * Exports parser
  1268. *
  1269. * @api public
  1270. *
  1271. */
  1272. module.exports.parser = require('engine.io-parser');
  1273. },{"./socket":13,"engine.io-parser":22}],13:[function(require,module,exports){
  1274. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
  1275. * Module dependencies.
  1276. */
  1277. var transports = require('./transports');
  1278. var Emitter = require('component-emitter');
  1279. var debug = require('debug')('engine.io-client:socket');
  1280. var index = require('indexof');
  1281. var parser = require('engine.io-parser');
  1282. var parseuri = require('parseuri');
  1283. var parsejson = require('parsejson');
  1284. var parseqs = require('parseqs');
  1285. /**
  1286. * Module exports.
  1287. */
  1288. module.exports = Socket;
  1289. /**
  1290. * Noop function.
  1291. *
  1292. * @api private
  1293. */
  1294. function noop(){}
  1295. /**
  1296. * Socket constructor.
  1297. *
  1298. * @param {String|Object} uri or options
  1299. * @param {Object} options
  1300. * @api public
  1301. */
  1302. function Socket(uri, opts){
  1303. if (!(this instanceof Socket)) return new Socket(uri, opts);
  1304. opts = opts || {};
  1305. if (uri && 'object' == typeof uri) {
  1306. opts = uri;
  1307. uri = null;
  1308. }
  1309. if (uri) {
  1310. uri = parseuri(uri);
  1311. opts.host = uri.host;
  1312. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  1313. opts.port = uri.port;
  1314. if (uri.query) opts.query = uri.query;
  1315. }
  1316. this.secure = null != opts.secure ? opts.secure :
  1317. (global.location && 'https:' == location.protocol);
  1318. if (opts.host) {
  1319. var pieces = opts.host.split(':');
  1320. opts.hostname = pieces.shift();
  1321. if (pieces.length) opts.port = pieces.pop();
  1322. }
  1323. this.agent = opts.agent || false;
  1324. this.hostname = opts.hostname ||
  1325. (global.location ? location.hostname : 'localhost');
  1326. this.port = opts.port || (global.location && location.port ?
  1327. location.port :
  1328. (this.secure ? 443 : 80));
  1329. this.query = opts.query || {};
  1330. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  1331. this.upgrade = false !== opts.upgrade;
  1332. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  1333. this.forceJSONP = !!opts.forceJSONP;
  1334. this.forceBase64 = !!opts.forceBase64;
  1335. this.timestampParam = opts.timestampParam || 't';
  1336. this.timestampRequests = opts.timestampRequests;
  1337. this.transports = opts.transports || ['polling', 'websocket'];
  1338. this.readyState = '';
  1339. this.writeBuffer = [];
  1340. this.callbackBuffer = [];
  1341. this.policyPort = opts.policyPort || 843;
  1342. this.rememberUpgrade = opts.rememberUpgrade || false;
  1343. this.open();
  1344. this.binaryType = null;
  1345. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  1346. }
  1347. Socket.priorWebsocketSuccess = false;
  1348. /**
  1349. * Mix in `Emitter`.
  1350. */
  1351. Emitter(Socket.prototype);
  1352. /**
  1353. * Protocol version.
  1354. *
  1355. * @api public
  1356. */
  1357. Socket.protocol = parser.protocol; // this is an int
  1358. /**
  1359. * Expose deps for legacy compatibility
  1360. * and standalone browser access.
  1361. */
  1362. Socket.Socket = Socket;
  1363. Socket.Transport = require('./transport');
  1364. Socket.transports = require('./transports');
  1365. Socket.parser = require('engine.io-parser');
  1366. /**
  1367. * Creates transport of the given type.
  1368. *
  1369. * @param {String} transport name
  1370. * @return {Transport}
  1371. * @api private
  1372. */
  1373. Socket.prototype.createTransport = function (name) {
  1374. debug('creating transport "%s"', name);
  1375. var query = clone(this.query);
  1376. // append engine.io protocol identifier
  1377. query.EIO = parser.protocol;
  1378. // transport name
  1379. query.transport = name;
  1380. // session id if we already have one
  1381. if (this.id) query.sid = this.id;
  1382. var transport = new transports[name]({
  1383. agent: this.agent,
  1384. hostname: this.hostname,
  1385. port: this.port,
  1386. secure: this.secure,
  1387. path: this.path,
  1388. query: query,
  1389. forceJSONP: this.forceJSONP,
  1390. forceBase64: this.forceBase64,
  1391. timestampRequests: this.timestampRequests,
  1392. timestampParam: this.timestampParam,
  1393. policyPort: this.policyPort,
  1394. socket: this
  1395. });
  1396. return transport;
  1397. };
  1398. function clone (obj) {
  1399. var o = {};
  1400. for (var i in obj) {
  1401. if (obj.hasOwnProperty(i)) {
  1402. o[i] = obj[i];
  1403. }
  1404. }
  1405. return o;
  1406. }
  1407. /**
  1408. * Initializes transport to use and starts probe.
  1409. *
  1410. * @api private
  1411. */
  1412. Socket.prototype.open = function () {
  1413. var transport;
  1414. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  1415. transport = 'websocket';
  1416. } else {
  1417. transport = this.transports[0];
  1418. }
  1419. this.readyState = 'opening';
  1420. var transport = this.createTransport(transport);
  1421. transport.open();
  1422. this.setTransport(transport);
  1423. };
  1424. /**
  1425. * Sets the current transport. Disables the existing one (if any).
  1426. *
  1427. * @api private
  1428. */
  1429. Socket.prototype.setTransport = function(transport){
  1430. debug('setting transport %s', transport.name);
  1431. var self = this;
  1432. if (this.transport) {
  1433. debug('clearing existing transport %s', this.transport.name);
  1434. this.transport.removeAllListeners();
  1435. }
  1436. // set up transport
  1437. this.transport = transport;
  1438. // set up transport listeners
  1439. transport
  1440. .on('drain', function(){
  1441. self.onDrain();
  1442. })
  1443. .on('packet', function(packet){
  1444. self.onPacket(packet);
  1445. })
  1446. .on('error', function(e){
  1447. self.onError(e);
  1448. })
  1449. .on('close', function(){
  1450. self.onClose('transport close');
  1451. });
  1452. };
  1453. /**
  1454. * Probes a transport.
  1455. *
  1456. * @param {String} transport name
  1457. * @api private
  1458. */
  1459. Socket.prototype.probe = function (name) {
  1460. debug('probing transport "%s"', name);
  1461. var transport = this.createTransport(name, { probe: 1 })
  1462. , failed = false
  1463. , self = this;
  1464. Socket.priorWebsocketSuccess = false;
  1465. function onTransportOpen(){
  1466. if (self.onlyBinaryUpgrades) {
  1467. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  1468. failed = failed || upgradeLosesBinary;
  1469. }
  1470. if (failed) return;
  1471. debug('probe transport "%s" opened', name);
  1472. transport.send([{ type: 'ping', data: 'probe' }]);
  1473. transport.once('packet', function (msg) {
  1474. if (failed) return;
  1475. if ('pong' == msg.type && 'probe' == msg.data) {
  1476. debug('probe transport "%s" pong', name);
  1477. self.upgrading = true;
  1478. self.emit('upgrading', transport);
  1479. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  1480. debug('pausing current transport "%s"', self.transport.name);
  1481. self.transport.pause(function () {
  1482. if (failed) return;
  1483. if ('closed' == self.readyState || 'closing' == self.readyState) {
  1484. return;
  1485. }
  1486. debug('changing transport and sending upgrade packet');
  1487. cleanup();
  1488. self.setTransport(transport);
  1489. transport.send([{ type: 'upgrade' }]);
  1490. self.emit('upgrade', transport);
  1491. transport = null;
  1492. self.upgrading = false;
  1493. self.flush();
  1494. });
  1495. } else {
  1496. debug('probe transport "%s" failed', name);
  1497. var err = new Error('probe error');
  1498. err.transport = transport.name;
  1499. self.emit('upgradeError', err);
  1500. }
  1501. });
  1502. }
  1503. function freezeTransport() {
  1504. if (failed) return;
  1505. // Any callback called by transport should be ignored since now
  1506. failed = true;
  1507. cleanup();
  1508. transport.close();
  1509. transport = null;
  1510. }
  1511. //Handle any error that happens while probing
  1512. function onerror(err) {
  1513. var error = new Error('probe error: ' + err);
  1514. error.transport = transport.name;
  1515. freezeTransport();
  1516. debug('probe transport "%s" failed because of error: %s', name, err);
  1517. self.emit('upgradeError', error);
  1518. }
  1519. function onTransportClose(){
  1520. onerror("transport closed");
  1521. }
  1522. //When the socket is closed while we're probing
  1523. function onclose(){
  1524. onerror("socket closed");
  1525. }
  1526. //When the socket is upgraded while we're probing
  1527. function onupgrade(to){
  1528. if (transport && to.name != transport.name) {
  1529. debug('"%s" works - aborting "%s"', to.name, transport.name);
  1530. freezeTransport();
  1531. }
  1532. }
  1533. //Remove all listeners on the transport and on self
  1534. function cleanup(){
  1535. transport.removeListener('open', onTransportOpen);
  1536. transport.removeListener('error', onerror);
  1537. transport.removeListener('close', onTransportClose);
  1538. self.removeListener('close', onclose);
  1539. self.removeListener('upgrading', onupgrade);
  1540. }
  1541. transport.once('open', onTransportOpen);
  1542. transport.once('error', onerror);
  1543. transport.once('close', onTransportClose);
  1544. this.once('close', onclose);
  1545. this.once('upgrading', onupgrade);
  1546. transport.open();
  1547. };
  1548. /**
  1549. * Called when connection is deemed open.
  1550. *
  1551. * @api public
  1552. */
  1553. Socket.prototype.onOpen = function () {
  1554. debug('socket open');
  1555. this.readyState = 'open';
  1556. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  1557. this.emit('open');
  1558. this.flush();
  1559. // we check for `readyState` in case an `open`
  1560. // listener already closed the socket
  1561. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  1562. debug('starting upgrade probes');
  1563. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  1564. this.probe(this.upgrades[i]);
  1565. }
  1566. }
  1567. };
  1568. /**
  1569. * Handles a packet.
  1570. *
  1571. * @api private
  1572. */
  1573. Socket.prototype.onPacket = function (packet) {
  1574. if ('opening' == this.readyState || 'open' == this.readyState) {
  1575. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  1576. this.emit('packet', packet);
  1577. // Socket is live - any packet counts
  1578. this.emit('heartbeat');
  1579. switch (packet.type) {
  1580. case 'open':
  1581. this.onHandshake(parsejson(packet.data));
  1582. break;
  1583. case 'pong':
  1584. this.setPing();
  1585. break;
  1586. case 'error':
  1587. var err = new Error('server error');
  1588. err.code = packet.data;
  1589. this.emit('error', err);
  1590. break;
  1591. case 'message':
  1592. this.emit('data', packet.data);
  1593. this.emit('message', packet.data);
  1594. break;
  1595. }
  1596. } else {
  1597. debug('packet received with socket readyState "%s"', this.readyState);
  1598. }
  1599. };
  1600. /**
  1601. * Called upon handshake completion.
  1602. *
  1603. * @param {Object} handshake obj
  1604. * @api private
  1605. */
  1606. Socket.prototype.onHandshake = function (data) {
  1607. this.emit('handshake', data);
  1608. this.id = data.sid;
  1609. this.transport.query.sid = data.sid;
  1610. this.upgrades = this.filterUpgrades(data.upgrades);
  1611. this.pingInterval = data.pingInterval;
  1612. this.pingTimeout = data.pingTimeout;
  1613. this.onOpen();
  1614. // In case open handler closes socket
  1615. if ('closed' == this.readyState) return;
  1616. this.setPing();
  1617. // Prolong liveness of socket on heartbeat
  1618. this.removeListener('heartbeat', this.onHeartbeat);
  1619. this.on('heartbeat', this.onHeartbeat);
  1620. };
  1621. /**
  1622. * Resets ping timeout.
  1623. *
  1624. * @api private
  1625. */
  1626. Socket.prototype.onHeartbeat = function (timeout) {
  1627. clearTimeout(this.pingTimeoutTimer);
  1628. var self = this;
  1629. self.pingTimeoutTimer = setTimeout(function () {
  1630. if ('closed' == self.readyState) return;
  1631. self.onClose('ping timeout');
  1632. }, timeout || (self.pingInterval + self.pingTimeout));
  1633. };
  1634. /**
  1635. * Pings server every `this.pingInterval` and expects response
  1636. * within `this.pingTimeout` or closes connection.
  1637. *
  1638. * @api private
  1639. */
  1640. Socket.prototype.setPing = function () {
  1641. var self = this;
  1642. clearTimeout(self.pingIntervalTimer);
  1643. self.pingIntervalTimer = setTimeout(function () {
  1644. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  1645. self.ping();
  1646. self.onHeartbeat(self.pingTimeout);
  1647. }, self.pingInterval);
  1648. };
  1649. /**
  1650. * Sends a ping packet.
  1651. *
  1652. * @api public
  1653. */
  1654. Socket.prototype.ping = function () {
  1655. this.sendPacket('ping');
  1656. };
  1657. /**
  1658. * Called on `drain` event
  1659. *
  1660. * @api private
  1661. */
  1662. Socket.prototype.onDrain = function() {
  1663. for (var i = 0; i < this.prevBufferLen; i++) {
  1664. if (this.callbackBuffer[i]) {
  1665. this.callbackBuffer[i]();
  1666. }
  1667. }
  1668. this.writeBuffer.splice(0, this.prevBufferLen);
  1669. this.callbackBuffer.splice(0, this.prevBufferLen);
  1670. // setting prevBufferLen = 0 is very important
  1671. // for example, when upgrading, upgrade packet is sent over,
  1672. // and a nonzero prevBufferLen could cause problems on `drain`
  1673. this.prevBufferLen = 0;
  1674. if (this.writeBuffer.length == 0) {
  1675. this.emit('drain');
  1676. } else {
  1677. this.flush();
  1678. }
  1679. };
  1680. /**
  1681. * Flush write buffers.
  1682. *
  1683. * @api private
  1684. */
  1685. Socket.prototype.flush = function () {
  1686. if ('closed' != this.readyState && this.transport.writable &&
  1687. !this.upgrading && this.writeBuffer.length) {
  1688. debug('flushing %d packets in socket', this.writeBuffer.length);
  1689. this.transport.send(this.writeBuffer);
  1690. // keep track of current length of writeBuffer
  1691. // splice writeBuffer and callbackBuffer on `drain`
  1692. this.prevBufferLen = this.writeBuffer.length;
  1693. this.emit('flush');
  1694. }
  1695. };
  1696. /**
  1697. * Sends a message.
  1698. *
  1699. * @param {String} message.
  1700. * @param {Function} callback function.
  1701. * @return {Socket} for chaining.
  1702. * @api public
  1703. */
  1704. Socket.prototype.write =
  1705. Socket.prototype.send = function (msg, fn) {
  1706. this.sendPacket('message', msg, fn);
  1707. return this;
  1708. };
  1709. /**
  1710. * Sends a packet.
  1711. *
  1712. * @param {String} packet type.
  1713. * @param {String} data.
  1714. * @param {Function} callback function.
  1715. * @api private
  1716. */
  1717. Socket.prototype.sendPacket = function (type, data, fn) {
  1718. var packet = { type: type, data: data };
  1719. this.emit('packetCreate', packet);
  1720. this.writeBuffer.push(packet);
  1721. this.callbackBuffer.push(fn);
  1722. this.flush();
  1723. };
  1724. /**
  1725. * Closes the connection.
  1726. *
  1727. * @api private
  1728. */
  1729. Socket.prototype.close = function () {
  1730. if ('opening' == this.readyState || 'open' == this.readyState) {
  1731. this.onClose('forced close');
  1732. debug('socket closing - telling transport to close');
  1733. this.transport.close();
  1734. }
  1735. return this;
  1736. };
  1737. /**
  1738. * Called upon transport error
  1739. *
  1740. * @api private
  1741. */
  1742. Socket.prototype.onError = function (err) {
  1743. debug('socket error %j', err);
  1744. Socket.priorWebsocketSuccess = false;
  1745. this.emit('error', err);
  1746. this.onClose('transport error', err);
  1747. };
  1748. /**
  1749. * Called upon transport close.
  1750. *
  1751. * @api private
  1752. */
  1753. Socket.prototype.onClose = function (reason, desc) {
  1754. if ('opening' == this.readyState || 'open' == this.readyState) {
  1755. debug('socket close with reason: "%s"', reason);
  1756. var self = this;
  1757. // clear timers
  1758. clearTimeout(this.pingIntervalTimer);
  1759. clearTimeout(this.pingTimeoutTimer);
  1760. // clean buffers in next tick, so developers can still
  1761. // grab the buffers on `close` event
  1762. setTimeout(function() {
  1763. self.writeBuffer = [];
  1764. self.callbackBuffer = [];
  1765. self.prevBufferLen = 0;
  1766. }, 0);
  1767. // stop event from firing again for transport
  1768. this.transport.removeAllListeners('close');
  1769. // ensure transport won't stay open
  1770. this.transport.close();
  1771. // ignore further transport communication
  1772. this.transport.removeAllListeners();
  1773. // set ready state
  1774. this.readyState = 'closed';
  1775. // clear session id
  1776. this.id = null;
  1777. // emit close event
  1778. this.emit('close', reason, desc);
  1779. }
  1780. };
  1781. /**
  1782. * Filters upgrades, returning only those matching client transports.
  1783. *
  1784. * @param {Array} server upgrades
  1785. * @api private
  1786. *
  1787. */
  1788. Socket.prototype.filterUpgrades = function (upgrades) {
  1789. var filteredUpgrades = [];
  1790. for (var i = 0, j = upgrades.length; i<j; i++) {
  1791. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1792. }
  1793. return filteredUpgrades;
  1794. };
  1795. },{"./transport":14,"./transports":15,"component-emitter":8,"debug":9,"engine.io-parser":22,"indexof":36,"parsejson":29,"parseqs":30,"parseuri":38}],14:[function(require,module,exports){
  1796. /**
  1797. * Module dependencies.
  1798. */
  1799. var parser = require('engine.io-parser');
  1800. var Emitter = require('component-emitter');
  1801. /**
  1802. * Module exports.
  1803. */
  1804. module.exports = Transport;
  1805. /**
  1806. * Transport abstract constructor.
  1807. *
  1808. * @param {Object} options.
  1809. * @api private
  1810. */
  1811. function Transport (opts) {
  1812. this.path = opts.path;
  1813. this.hostname = opts.hostname;
  1814. this.port = opts.port;
  1815. this.secure = opts.secure;
  1816. this.query = opts.query;
  1817. this.timestampParam = opts.timestampParam;
  1818. this.timestampRequests = opts.timestampRequests;
  1819. this.readyState = '';
  1820. this.agent = opts.agent || false;
  1821. this.socket = opts.socket;
  1822. }
  1823. /**
  1824. * Mix in `Emitter`.
  1825. */
  1826. Emitter(Transport.prototype);
  1827. /**
  1828. * A counter used to prevent collisions in the timestamps used
  1829. * for cache busting.
  1830. */
  1831. Transport.timestamps = 0;
  1832. /**
  1833. * Emits an error.
  1834. *
  1835. * @param {String} str
  1836. * @return {Transport} for chaining
  1837. * @api public
  1838. */
  1839. Transport.prototype.onError = function (msg, desc) {
  1840. var err = new Error(msg);
  1841. err.type = 'TransportError';
  1842. err.description = desc;
  1843. this.emit('error', err);
  1844. return this;
  1845. };
  1846. /**
  1847. * Opens the transport.
  1848. *
  1849. * @api public
  1850. */
  1851. Transport.prototype.open = function () {
  1852. if ('closed' == this.readyState || '' == this.readyState) {
  1853. this.readyState = 'opening';
  1854. this.doOpen();
  1855. }
  1856. return this;
  1857. };
  1858. /**
  1859. * Closes the transport.
  1860. *
  1861. * @api private
  1862. */
  1863. Transport.prototype.close = function () {
  1864. if ('opening' == this.readyState || 'open' == this.readyState) {
  1865. this.doClose();
  1866. this.onClose();
  1867. }
  1868. return this;
  1869. };
  1870. /**
  1871. * Sends multiple packets.
  1872. *
  1873. * @param {Array} packets
  1874. * @api private
  1875. */
  1876. Transport.prototype.send = function(packets){
  1877. if ('open' == this.readyState) {
  1878. this.write(packets);
  1879. } else {
  1880. throw new Error('Transport not open');
  1881. }
  1882. };
  1883. /**
  1884. * Called upon open
  1885. *
  1886. * @api private
  1887. */
  1888. Transport.prototype.onOpen = function () {
  1889. this.readyState = 'open';
  1890. this.writable = true;
  1891. this.emit('open');
  1892. };
  1893. /**
  1894. * Called with data.
  1895. *
  1896. * @param {String} data
  1897. * @api private
  1898. */
  1899. Transport.prototype.onData = function(data){
  1900. try {
  1901. var packet = parser.decodePacket(data, this.socket.binaryType);
  1902. this.onPacket(packet);
  1903. } catch(e){
  1904. e.data = data;
  1905. this.onError('parser decode error', e);
  1906. }
  1907. };
  1908. /**
  1909. * Called with a decoded packet.
  1910. */
  1911. Transport.prototype.onPacket = function (packet) {
  1912. this.emit('packet', packet);
  1913. };
  1914. /**
  1915. * Called upon close.
  1916. *
  1917. * @api private
  1918. */
  1919. Transport.prototype.onClose = function () {
  1920. this.readyState = 'closed';
  1921. this.emit('close');
  1922. };
  1923. },{"component-emitter":8,"engine.io-parser":22}],15:[function(require,module,exports){
  1924. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
  1925. * Module dependencies
  1926. */
  1927. var XMLHttpRequest = require('xmlhttprequest');
  1928. var XHR = require('./polling-xhr');
  1929. var JSONP = require('./polling-jsonp');
  1930. var websocket = require('./websocket');
  1931. /**
  1932. * Export transports.
  1933. */
  1934. exports.polling = polling;
  1935. exports.websocket = websocket;
  1936. /**
  1937. * Polling transport polymorphic constructor.
  1938. * Decides on xhr vs jsonp based on feature detection.
  1939. *
  1940. * @api private
  1941. */
  1942. function polling(opts){
  1943. var xhr;
  1944. var xd = false;
  1945. if (global.location) {
  1946. var isSSL = 'https:' == location.protocol;
  1947. var port = location.port;
  1948. // some user agents have empty `location.port`
  1949. if (!port) {
  1950. port = isSSL ? 443 : 80;
  1951. }
  1952. xd = opts.hostname != location.hostname || port != opts.port;
  1953. }
  1954. opts.xdomain = xd;
  1955. xhr = new XMLHttpRequest(opts);
  1956. if ('open' in xhr && !opts.forceJSONP) {
  1957. return new XHR(opts);
  1958. } else {
  1959. return new JSONP(opts);
  1960. }
  1961. }
  1962. },{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,"xmlhttprequest":20}],16:[function(require,module,exports){
  1963. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
  1964. /**
  1965. * Module requirements.
  1966. */
  1967. var Polling = require('./polling');
  1968. var inherit = require('component-inherit');
  1969. /**
  1970. * Module exports.
  1971. */
  1972. module.exports = JSONPPolling;
  1973. /**
  1974. * Cached regular expressions.
  1975. */
  1976. var rNewline = /\n/g;
  1977. var rEscapedNewline = /\\n/g;
  1978. /**
  1979. * Global JSONP callbacks.
  1980. */
  1981. var callbacks;
  1982. /**
  1983. * Callbacks count.
  1984. */
  1985. var index = 0;
  1986. /**
  1987. * N…

Large files files are truncated, but you can click here to view the full file