/app/socket.io.js

https://github.com/tantion/chat · JavaScript · 6155 lines · 3413 code · 950 blank · 1792 comment · 1014 complexity · 6775500dd53a94b9084148d96d818431 MD5 · raw file

Large files are truncated 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');
  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. }
  536. /**
  537. * Mix in `Emitter`.
  538. */
  539. Emitter(Socket.prototype);
  540. /**
  541. * Called upon engine `open`.
  542. *
  543. * @api private
  544. */
  545. Socket.prototype.open =
  546. Socket.prototype.connect = function(){
  547. if (this.connected) return this;
  548. var io = this.io;
  549. io.open(); // ensure open
  550. this.subs = [
  551. on(io, 'open', bind(this, 'onopen')),
  552. on(io, 'packet', bind(this, 'onpacket')),
  553. on(io, 'close', bind(this, 'onclose'))
  554. ];
  555. if ('open' == this.io.readyState) this.onopen();
  556. return this;
  557. };
  558. /**
  559. * Sends a `message` event.
  560. *
  561. * @return {Socket} self
  562. * @api public
  563. */
  564. Socket.prototype.send = function(){
  565. var args = toArray(arguments);
  566. args.unshift('message');
  567. this.emit.apply(this, args);
  568. return this;
  569. };
  570. /**
  571. * Override `emit`.
  572. * If the event is in `events`, it's emitted normally.
  573. *
  574. * @param {String} event name
  575. * @return {Socket} self
  576. * @api public
  577. */
  578. Socket.prototype.emit = function(ev){
  579. if (events.hasOwnProperty(ev)) {
  580. emit.apply(this, arguments);
  581. return this;
  582. }
  583. var args = toArray(arguments);
  584. var parserType = parser.EVENT; // default
  585. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  586. var packet = { type: parserType, data: args };
  587. // event ack callback
  588. if ('function' == typeof args[args.length - 1]) {
  589. debug('emitting packet with ack id %d', this.ids);
  590. this.acks[this.ids] = args.pop();
  591. packet.id = this.ids++;
  592. }
  593. if (this.connected) {
  594. this.packet(packet);
  595. } else {
  596. this.sendBuffer.push(packet);
  597. }
  598. return this;
  599. };
  600. /**
  601. * Sends a packet.
  602. *
  603. * @param {Object} packet
  604. * @api private
  605. */
  606. Socket.prototype.packet = function(packet){
  607. packet.nsp = this.nsp;
  608. this.io.packet(packet);
  609. };
  610. /**
  611. * "Opens" the socket.
  612. *
  613. * @api private
  614. */
  615. Socket.prototype.onopen = function(){
  616. debug('transport is open - connecting');
  617. // write connect packet if necessary
  618. if ('/' != this.nsp) {
  619. this.packet({ type: parser.CONNECT });
  620. }
  621. };
  622. /**
  623. * Called upon engine `close`.
  624. *
  625. * @param {String} reason
  626. * @api private
  627. */
  628. Socket.prototype.onclose = function(reason){
  629. debug('close (%s)', reason);
  630. this.connected = false;
  631. this.disconnected = true;
  632. this.emit('disconnect', reason);
  633. };
  634. /**
  635. * Called with socket packet.
  636. *
  637. * @param {Object} packet
  638. * @api private
  639. */
  640. Socket.prototype.onpacket = function(packet){
  641. if (packet.nsp != this.nsp) return;
  642. switch (packet.type) {
  643. case parser.CONNECT:
  644. this.onconnect();
  645. break;
  646. case parser.EVENT:
  647. this.onevent(packet);
  648. break;
  649. case parser.BINARY_EVENT:
  650. this.onevent(packet);
  651. break;
  652. case parser.ACK:
  653. this.onack(packet);
  654. break;
  655. case parser.BINARY_ACK:
  656. this.onack(packet);
  657. break;
  658. case parser.DISCONNECT:
  659. this.ondisconnect();
  660. break;
  661. case parser.ERROR:
  662. this.emit('error', packet.data);
  663. break;
  664. }
  665. };
  666. /**
  667. * Called upon a server event.
  668. *
  669. * @param {Object} packet
  670. * @api private
  671. */
  672. Socket.prototype.onevent = function(packet){
  673. var args = packet.data || [];
  674. debug('emitting event %j', args);
  675. if (null != packet.id) {
  676. debug('attaching ack callback to event');
  677. args.push(this.ack(packet.id));
  678. }
  679. if (this.connected) {
  680. emit.apply(this, args);
  681. } else {
  682. this.receiveBuffer.push(args);
  683. }
  684. };
  685. /**
  686. * Produces an ack callback to emit with an event.
  687. *
  688. * @api private
  689. */
  690. Socket.prototype.ack = function(id){
  691. var self = this;
  692. var sent = false;
  693. return function(){
  694. // prevent double callbacks
  695. if (sent) return;
  696. sent = true;
  697. var args = toArray(arguments);
  698. debug('sending ack %j', args);
  699. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  700. self.packet({
  701. type: type,
  702. id: id,
  703. data: args
  704. });
  705. };
  706. };
  707. /**
  708. * Called upon a server acknowlegement.
  709. *
  710. * @param {Object} packet
  711. * @api private
  712. */
  713. Socket.prototype.onack = function(packet){
  714. debug('calling ack %s with %j', packet.id, packet.data);
  715. var fn = this.acks[packet.id];
  716. fn.apply(this, packet.data);
  717. delete this.acks[packet.id];
  718. };
  719. /**
  720. * Called upon server connect.
  721. *
  722. * @api private
  723. */
  724. Socket.prototype.onconnect = function(){
  725. this.connected = true;
  726. this.disconnected = false;
  727. this.emit('connect');
  728. this.emitBuffered();
  729. };
  730. /**
  731. * Emit buffered events (received and emitted).
  732. *
  733. * @api private
  734. */
  735. Socket.prototype.emitBuffered = function(){
  736. var i;
  737. for (i = 0; i < this.receiveBuffer.length; i++) {
  738. emit.apply(this, this.receiveBuffer[i]);
  739. }
  740. this.receiveBuffer = [];
  741. for (i = 0; i < this.sendBuffer.length; i++) {
  742. this.packet(this.sendBuffer[i]);
  743. }
  744. this.sendBuffer = [];
  745. };
  746. /**
  747. * Called upon server disconnect.
  748. *
  749. * @api private
  750. */
  751. Socket.prototype.ondisconnect = function(){
  752. debug('server disconnect (%s)', this.nsp);
  753. this.destroy();
  754. this.onclose('io server disconnect');
  755. };
  756. /**
  757. * Called upon forced client/server side disconnections,
  758. * this method ensures the manager stops tracking us and
  759. * that reconnections don't get triggered for this.
  760. *
  761. * @api private.
  762. */
  763. Socket.prototype.destroy = function(){
  764. // clean subscriptions to avoid reconnections
  765. for (var i = 0; i < this.subs.length; i++) {
  766. this.subs[i].destroy();
  767. }
  768. this.io.destroy(this);
  769. };
  770. /**
  771. * Disconnects the socket manually.
  772. *
  773. * @return {Socket} self
  774. * @api public
  775. */
  776. Socket.prototype.close =
  777. Socket.prototype.disconnect = function(){
  778. if (!this.connected) return this;
  779. debug('performing disconnect (%s)', this.nsp);
  780. this.packet({ type: parser.DISCONNECT });
  781. // remove socket from pool
  782. this.destroy();
  783. // fire events
  784. this.onclose('io client disconnect');
  785. return this;
  786. };
  787. },{"./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){
  788. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
  789. /**
  790. * Module dependencies.
  791. */
  792. var parseuri = require('parseuri');
  793. var debug = require('debug')('socket.io-client:url');
  794. /**
  795. * Module exports.
  796. */
  797. module.exports = url;
  798. /**
  799. * URL parser.
  800. *
  801. * @param {String} url
  802. * @param {Object} An object meant to mimic window.location.
  803. * Defaults to window.location.
  804. * @api public
  805. */
  806. function url(uri, loc){
  807. var obj = uri;
  808. // default to window.location
  809. var loc = loc || global.location;
  810. if (null == uri) uri = loc.protocol + '//' + loc.hostname;
  811. // relative path support
  812. if ('string' == typeof uri) {
  813. if ('/' == uri.charAt(0)) {
  814. if ('undefined' != typeof loc) {
  815. uri = loc.hostname + uri;
  816. }
  817. }
  818. if (!/^(https?|wss?):\/\//.test(uri)) {
  819. debug('protocol-less url %s', uri);
  820. if ('undefined' != typeof loc) {
  821. uri = loc.protocol + '//' + uri;
  822. } else {
  823. uri = 'https://' + uri;
  824. }
  825. }
  826. // parse
  827. debug('parse %s', uri);
  828. obj = parseuri(uri);
  829. }
  830. // make sure we treat `localhost:80` and `localhost` equally
  831. if (!obj.port) {
  832. if (/^(http|ws)$/.test(obj.protocol)) {
  833. obj.port = '80';
  834. }
  835. else if (/^(http|ws)s$/.test(obj.protocol)) {
  836. obj.port = '443';
  837. }
  838. }
  839. obj.path = obj.path || '/';
  840. // define unique id
  841. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  842. // define href
  843. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  844. return obj;
  845. }
  846. },{"debug":9,"parseuri":38}],7:[function(require,module,exports){
  847. /**
  848. * Slice reference.
  849. */
  850. var slice = [].slice;
  851. /**
  852. * Bind `obj` to `fn`.
  853. *
  854. * @param {Object} obj
  855. * @param {Function|String} fn or string
  856. * @return {Function}
  857. * @api public
  858. */
  859. module.exports = function(obj, fn){
  860. if ('string' == typeof fn) fn = obj[fn];
  861. if ('function' != typeof fn) throw new Error('bind() requires a function');
  862. var args = slice.call(arguments, 2);
  863. return function(){
  864. return fn.apply(obj, args.concat(slice.call(arguments)));
  865. }
  866. };
  867. },{}],8:[function(require,module,exports){
  868. /**
  869. * Expose `Emitter`.
  870. */
  871. module.exports = Emitter;
  872. /**
  873. * Initialize a new `Emitter`.
  874. *
  875. * @api public
  876. */
  877. function Emitter(obj) {
  878. if (obj) return mixin(obj);
  879. };
  880. /**
  881. * Mixin the emitter properties.
  882. *
  883. * @param {Object} obj
  884. * @return {Object}
  885. * @api private
  886. */
  887. function mixin(obj) {
  888. for (var key in Emitter.prototype) {
  889. obj[key] = Emitter.prototype[key];
  890. }
  891. return obj;
  892. }
  893. /**
  894. * Listen on the given `event` with `fn`.
  895. *
  896. * @param {String} event
  897. * @param {Function} fn
  898. * @return {Emitter}
  899. * @api public
  900. */
  901. Emitter.prototype.on =
  902. Emitter.prototype.addEventListener = function(event, fn){
  903. this._callbacks = this._callbacks || {};
  904. (this._callbacks[event] = this._callbacks[event] || [])
  905. .push(fn);
  906. return this;
  907. };
  908. /**
  909. * Adds an `event` listener that will be invoked a single
  910. * time then automatically removed.
  911. *
  912. * @param {String} event
  913. * @param {Function} fn
  914. * @return {Emitter}
  915. * @api public
  916. */
  917. Emitter.prototype.once = function(event, fn){
  918. var self = this;
  919. this._callbacks = this._callbacks || {};
  920. function on() {
  921. self.off(event, on);
  922. fn.apply(this, arguments);
  923. }
  924. on.fn = fn;
  925. this.on(event, on);
  926. return this;
  927. };
  928. /**
  929. * Remove the given callback for `event` or all
  930. * registered callbacks.
  931. *
  932. * @param {String} event
  933. * @param {Function} fn
  934. * @return {Emitter}
  935. * @api public
  936. */
  937. Emitter.prototype.off =
  938. Emitter.prototype.removeListener =
  939. Emitter.prototype.removeAllListeners =
  940. Emitter.prototype.removeEventListener = function(event, fn){
  941. this._callbacks = this._callbacks || {};
  942. // all
  943. if (0 == arguments.length) {
  944. this._callbacks = {};
  945. return this;
  946. }
  947. // specific event
  948. var callbacks = this._callbacks[event];
  949. if (!callbacks) return this;
  950. // remove all handlers
  951. if (1 == arguments.length) {
  952. delete this._callbacks[event];
  953. return this;
  954. }
  955. // remove specific handler
  956. var cb;
  957. for (var i = 0; i < callbacks.length; i++) {
  958. cb = callbacks[i];
  959. if (cb === fn || cb.fn === fn) {
  960. callbacks.splice(i, 1);
  961. break;
  962. }
  963. }
  964. return this;
  965. };
  966. /**
  967. * Emit `event` with the given args.
  968. *
  969. * @param {String} event
  970. * @param {Mixed} ...
  971. * @return {Emitter}
  972. */
  973. Emitter.prototype.emit = function(event){
  974. this._callbacks = this._callbacks || {};
  975. var args = [].slice.call(arguments, 1)
  976. , callbacks = this._callbacks[event];
  977. if (callbacks) {
  978. callbacks = callbacks.slice(0);
  979. for (var i = 0, len = callbacks.length; i < len; ++i) {
  980. callbacks[i].apply(this, args);
  981. }
  982. }
  983. return this;
  984. };
  985. /**
  986. * Return array of callbacks for `event`.
  987. *
  988. * @param {String} event
  989. * @return {Array}
  990. * @api public
  991. */
  992. Emitter.prototype.listeners = function(event){
  993. this._callbacks = this._callbacks || {};
  994. return this._callbacks[event] || [];
  995. };
  996. /**
  997. * Check if this emitter has `event` handlers.
  998. *
  999. * @param {String} event
  1000. * @return {Boolean}
  1001. * @api public
  1002. */
  1003. Emitter.prototype.hasListeners = function(event){
  1004. return !! this.listeners(event).length;
  1005. };
  1006. },{}],9:[function(require,module,exports){
  1007. /**
  1008. * Expose `debug()` as the module.
  1009. */
  1010. module.exports = debug;
  1011. /**
  1012. * Create a debugger with the given `name`.
  1013. *
  1014. * @param {String} name
  1015. * @return {Type}
  1016. * @api public
  1017. */
  1018. function debug(name) {
  1019. if (!debug.enabled(name)) return function(){};
  1020. return function(fmt){
  1021. fmt = coerce(fmt);
  1022. var curr = new Date;
  1023. var ms = curr - (debug[name] || curr);
  1024. debug[name] = curr;
  1025. fmt = name
  1026. + ' '
  1027. + fmt
  1028. + ' +' + debug.humanize(ms);
  1029. // This hackery is required for IE8
  1030. // where `console.log` doesn't have 'apply'
  1031. window.console
  1032. && console.log
  1033. && Function.prototype.apply.call(console.log, console, arguments);
  1034. }
  1035. }
  1036. /**
  1037. * The currently active debug mode names.
  1038. */
  1039. debug.names = [];
  1040. debug.skips = [];
  1041. /**
  1042. * Enables a debug mode by name. This can include modes
  1043. * separated by a colon and wildcards.
  1044. *
  1045. * @param {String} name
  1046. * @api public
  1047. */
  1048. debug.enable = function(name) {
  1049. try {
  1050. localStorage.debug = name;
  1051. } catch(e){}
  1052. var split = (name || '').split(/[\s,]+/)
  1053. , len = split.length;
  1054. for (var i = 0; i < len; i++) {
  1055. name = split[i].replace('*', '.*?');
  1056. if (name[0] === '-') {
  1057. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  1058. }
  1059. else {
  1060. debug.names.push(new RegExp('^' + name + '$'));
  1061. }
  1062. }
  1063. };
  1064. /**
  1065. * Disable debug output.
  1066. *
  1067. * @api public
  1068. */
  1069. debug.disable = function(){
  1070. debug.enable('');
  1071. };
  1072. /**
  1073. * Humanize the given `ms`.
  1074. *
  1075. * @param {Number} m
  1076. * @return {String}
  1077. * @api private
  1078. */
  1079. debug.humanize = function(ms) {
  1080. var sec = 1000
  1081. , min = 60 * 1000
  1082. , hour = 60 * min;
  1083. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  1084. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  1085. if (ms >= sec) return (ms / sec | 0) + 's';
  1086. return ms + 'ms';
  1087. };
  1088. /**
  1089. * Returns true if the given mode name is enabled, false otherwise.
  1090. *
  1091. * @param {String} name
  1092. * @return {Boolean}
  1093. * @api public
  1094. */
  1095. debug.enabled = function(name) {
  1096. for (var i = 0, len = debug.skips.length; i < len; i++) {
  1097. if (debug.skips[i].test(name)) {
  1098. return false;
  1099. }
  1100. }
  1101. for (var i = 0, len = debug.names.length; i < len; i++) {
  1102. if (debug.names[i].test(name)) {
  1103. return true;
  1104. }
  1105. }
  1106. return false;
  1107. };
  1108. /**
  1109. * Coerce `val`.
  1110. */
  1111. function coerce(val) {
  1112. if (val instanceof Error) return val.stack || val.message;
  1113. return val;
  1114. }
  1115. // persist
  1116. try {
  1117. if (window.localStorage) debug.enable(localStorage.debug);
  1118. } catch(e){}
  1119. },{}],10:[function(require,module,exports){
  1120. /**
  1121. * Module dependencies.
  1122. */
  1123. var index = require('indexof');
  1124. /**
  1125. * Expose `Emitter`.
  1126. */
  1127. module.exports = Emitter;
  1128. /**
  1129. * Initialize a new `Emitter`.
  1130. *
  1131. * @api public
  1132. */
  1133. function Emitter(obj) {
  1134. if (obj) return mixin(obj);
  1135. };
  1136. /**
  1137. * Mixin the emitter properties.
  1138. *
  1139. * @param {Object} obj
  1140. * @return {Object}
  1141. * @api private
  1142. */
  1143. function mixin(obj) {
  1144. for (var key in Emitter.prototype) {
  1145. obj[key] = Emitter.prototype[key];
  1146. }
  1147. return obj;
  1148. }
  1149. /**
  1150. * Listen on the given `event` with `fn`.
  1151. *
  1152. * @param {String} event
  1153. * @param {Function} fn
  1154. * @return {Emitter}
  1155. * @api public
  1156. */
  1157. Emitter.prototype.on = function(event, fn){
  1158. this._callbacks = this._callbacks || {};
  1159. (this._callbacks[event] = this._callbacks[event] || [])
  1160. .push(fn);
  1161. return this;
  1162. };
  1163. /**
  1164. * Adds an `event` listener that will be invoked a single
  1165. * time then automatically removed.
  1166. *
  1167. * @param {String} event
  1168. * @param {Function} fn
  1169. * @return {Emitter}
  1170. * @api public
  1171. */
  1172. Emitter.prototype.once = function(event, fn){
  1173. var self = this;
  1174. this._callbacks = this._callbacks || {};
  1175. function on() {
  1176. self.off(event, on);
  1177. fn.apply(this, arguments);
  1178. }
  1179. fn._off = on;
  1180. this.on(event, on);
  1181. return this;
  1182. };
  1183. /**
  1184. * Remove the given callback for `event` or all
  1185. * registered callbacks.
  1186. *
  1187. * @param {String} event
  1188. * @param {Function} fn
  1189. * @return {Emitter}
  1190. * @api public
  1191. */
  1192. Emitter.prototype.off =
  1193. Emitter.prototype.removeListener =
  1194. Emitter.prototype.removeAllListeners = function(event, fn){
  1195. this._callbacks = this._callbacks || {};
  1196. // all
  1197. if (0 == arguments.length) {
  1198. this._callbacks = {};
  1199. return this;
  1200. }
  1201. // specific event
  1202. var callbacks = this._callbacks[event];
  1203. if (!callbacks) return this;
  1204. // remove all handlers
  1205. if (1 == arguments.length) {
  1206. delete this._callbacks[event];
  1207. return this;
  1208. }
  1209. // remove specific handler
  1210. var i = index(callbacks, fn._off || fn);
  1211. if (~i) callbacks.splice(i, 1);
  1212. return this;
  1213. };
  1214. /**
  1215. * Emit `event` with the given args.
  1216. *
  1217. * @param {String} event
  1218. * @param {Mixed} ...
  1219. * @return {Emitter}
  1220. */
  1221. Emitter.prototype.emit = function(event){
  1222. this._callbacks = this._callbacks || {};
  1223. var args = [].slice.call(arguments, 1)
  1224. , callbacks = this._callbacks[event];
  1225. if (callbacks) {
  1226. callbacks = callbacks.slice(0);
  1227. for (var i = 0, len = callbacks.length; i < len; ++i) {
  1228. callbacks[i].apply(this, args);
  1229. }
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Return array of callbacks for `event`.
  1235. *
  1236. * @param {String} event
  1237. * @return {Array}
  1238. * @api public
  1239. */
  1240. Emitter.prototype.listeners = function(event){
  1241. this._callbacks = this._callbacks || {};
  1242. return this._callbacks[event] || [];
  1243. };
  1244. /**
  1245. * Check if this emitter has `event` handlers.
  1246. *
  1247. * @param {String} event
  1248. * @return {Boolean}
  1249. * @api public
  1250. */
  1251. Emitter.prototype.hasListeners = function(event){
  1252. return !! this.listeners(event).length;
  1253. };
  1254. },{"indexof":36}],11:[function(require,module,exports){
  1255. module.exports = require('./lib/');
  1256. },{"./lib/":12}],12:[function(require,module,exports){
  1257. module.exports = require('./socket');
  1258. /**
  1259. * Exports parser
  1260. *
  1261. * @api public
  1262. *
  1263. */
  1264. module.exports.parser = require('engine.io-parser');
  1265. },{"./socket":13,"engine.io-parser":22}],13:[function(require,module,exports){
  1266. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
  1267. * Module dependencies.
  1268. */
  1269. var transports = require('./transports');
  1270. var Emitter = require('component-emitter');
  1271. var debug = require('debug')('engine.io-client:socket');
  1272. var index = require('indexof');
  1273. var parser = require('engine.io-parser');
  1274. var parseuri = require('parseuri');
  1275. var parsejson = require('parsejson');
  1276. var parseqs = require('parseqs');
  1277. /**
  1278. * Module exports.
  1279. */
  1280. module.exports = Socket;
  1281. /**
  1282. * Noop function.
  1283. *
  1284. * @api private
  1285. */
  1286. function noop(){}
  1287. /**
  1288. * Socket constructor.
  1289. *
  1290. * @param {String|Object} uri or options
  1291. * @param {Object} options
  1292. * @api public
  1293. */
  1294. function Socket(uri, opts){
  1295. if (!(this instanceof Socket)) return new Socket(uri, opts);
  1296. opts = opts || {};
  1297. if (uri && 'object' == typeof uri) {
  1298. opts = uri;
  1299. uri = null;
  1300. }
  1301. if (uri) {
  1302. uri = parseuri(uri);
  1303. opts.host = uri.host;
  1304. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  1305. opts.port = uri.port;
  1306. if (uri.query) opts.query = uri.query;
  1307. }
  1308. this.secure = null != opts.secure ? opts.secure :
  1309. (global.location && 'https:' == location.protocol);
  1310. if (opts.host) {
  1311. var pieces = opts.host.split(':');
  1312. opts.hostname = pieces.shift();
  1313. if (pieces.length) opts.port = pieces.pop();
  1314. }
  1315. this.agent = opts.agent || false;
  1316. this.hostname = opts.hostname ||
  1317. (global.location ? location.hostname : 'localhost');
  1318. this.port = opts.port || (global.location && location.port ?
  1319. location.port :
  1320. (this.secure ? 443 : 80));
  1321. this.query = opts.query || {};
  1322. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  1323. this.upgrade = false !== opts.upgrade;
  1324. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  1325. this.forceJSONP = !!opts.forceJSONP;
  1326. this.forceBase64 = !!opts.forceBase64;
  1327. this.timestampParam = opts.timestampParam || 't';
  1328. this.timestampRequests = opts.timestampRequests;
  1329. this.transports = opts.transports || ['polling', 'websocket'];
  1330. this.readyState = '';
  1331. this.writeBuffer = [];
  1332. this.callbackBuffer = [];
  1333. this.policyPort = opts.policyPort || 843;
  1334. this.rememberUpgrade = opts.rememberUpgrade || false;
  1335. this.open();
  1336. this.binaryType = null;
  1337. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  1338. }
  1339. Socket.priorWebsocketSuccess = false;
  1340. /**
  1341. * Mix in `Emitter`.
  1342. */
  1343. Emitter(Socket.prototype);
  1344. /**
  1345. * Protocol version.
  1346. *
  1347. * @api public
  1348. */
  1349. Socket.protocol = parser.protocol; // this is an int
  1350. /**
  1351. * Expose deps for legacy compatibility
  1352. * and standalone browser access.
  1353. */
  1354. Socket.Socket = Socket;
  1355. Socket.Transport = require('./transport');
  1356. Socket.transports = require('./transports');
  1357. Socket.parser = require('engine.io-parser');
  1358. /**
  1359. * Creates transport of the given type.
  1360. *
  1361. * @param {String} transport name
  1362. * @return {Transport}
  1363. * @api private
  1364. */
  1365. Socket.prototype.createTransport = function (name) {
  1366. debug('creating transport "%s"', name);
  1367. var query = clone(this.query);
  1368. // append engine.io protocol identifier
  1369. query.EIO = parser.protocol;
  1370. // transport name
  1371. query.transport = name;
  1372. // session id if we already have one
  1373. if (this.id) query.sid = this.id;
  1374. var transport = new transports[name]({
  1375. agent: this.agent,
  1376. hostname: this.hostname,
  1377. port: this.port,
  1378. secure: this.secure,
  1379. path: this.path,
  1380. query: query,
  1381. forceJSONP: this.forceJSONP,
  1382. forceBase64: this.forceBase64,
  1383. timestampRequests: this.timestampRequests,
  1384. timestampParam: this.timestampParam,
  1385. policyPort: this.policyPort,
  1386. socket: this
  1387. });
  1388. return transport;
  1389. };
  1390. function clone (obj) {
  1391. var o = {};
  1392. for (var i in obj) {
  1393. if (obj.hasOwnProperty(i)) {
  1394. o[i] = obj[i];
  1395. }
  1396. }
  1397. return o;
  1398. }
  1399. /**
  1400. * Initializes transport to use and starts probe.
  1401. *
  1402. * @api private
  1403. */
  1404. Socket.prototype.open = function () {
  1405. var transport;
  1406. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  1407. transport = 'websocket';
  1408. } else {
  1409. transport = this.transports[0];
  1410. }
  1411. this.readyState = 'opening';
  1412. var transport = this.createTransport(transport);
  1413. transport.open();
  1414. this.setTransport(transport);
  1415. };
  1416. /**
  1417. * Sets the current transport. Disables the existing one (if any).
  1418. *
  1419. * @api private
  1420. */
  1421. Socket.prototype.setTransport = function(transport){
  1422. debug('setting transport %s', transport.name);
  1423. var self = this;
  1424. if (this.transport) {
  1425. debug('clearing existing transport %s', this.transport.name);
  1426. this.transport.removeAllListeners();
  1427. }
  1428. // set up transport
  1429. this.transport = transport;
  1430. // set up transport listeners
  1431. transport
  1432. .on('drain', function(){
  1433. self.onDrain();
  1434. })
  1435. .on('packet', function(packet){
  1436. self.onPacket(packet);
  1437. })
  1438. .on('error', function(e){
  1439. self.onError(e);
  1440. })
  1441. .on('close', function(){
  1442. self.onClose('transport close');
  1443. });
  1444. };
  1445. /**
  1446. * Probes a transport.
  1447. *
  1448. * @param {String} transport name
  1449. * @api private
  1450. */
  1451. Socket.prototype.probe = function (name) {
  1452. debug('probing transport "%s"', name);
  1453. var transport = this.createTransport(name, { probe: 1 })
  1454. , failed = false
  1455. , self = this;
  1456. Socket.priorWebsocketSuccess = false;
  1457. function onTransportOpen(){
  1458. if (self.onlyBinaryUpgrades) {
  1459. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  1460. failed = failed || upgradeLosesBinary;
  1461. }
  1462. if (failed) return;
  1463. debug('probe transport "%s" opened', name);
  1464. transport.send([{ type: 'ping', data: 'probe' }]);
  1465. transport.once('packet', function (msg) {
  1466. if (failed) return;
  1467. if ('pong' == msg.type && 'probe' == msg.data) {
  1468. debug('probe transport "%s" pong', name);
  1469. self.upgrading = true;
  1470. self.emit('upgrading', transport);
  1471. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  1472. debug('pausing current transport "%s"', self.transport.name);
  1473. self.transport.pause(function () {
  1474. if (failed) return;
  1475. if ('closed' == self.readyState || 'closing' == self.readyState) {
  1476. return;
  1477. }
  1478. debug('changing transport and sending upgrade packet');
  1479. cleanup();
  1480. self.setTransport(transport);
  1481. transport.send([{ type: 'upgrade' }]);
  1482. self.emit('upgrade', transport);
  1483. transport = null;
  1484. self.upgrading = false;
  1485. self.flush();
  1486. });
  1487. } else {
  1488. debug('probe transport "%s" failed', name);
  1489. var err = new Error('probe error');
  1490. err.transport = transport.name;
  1491. self.emit('upgradeError', err);
  1492. }
  1493. });
  1494. }
  1495. function freezeTransport() {
  1496. if (failed) return;
  1497. // Any callback called by transport should be ignored since now
  1498. failed = true;
  1499. cleanup();
  1500. transport.close();
  1501. transport = null;
  1502. }
  1503. //Handle any error that happens while probing
  1504. function onerror(err) {
  1505. var error = new Error('probe error: ' + err);
  1506. error.transport = transport.name;
  1507. freezeTransport();
  1508. debug('probe transport "%s" failed because of error: %s', name, err);
  1509. self.emit('upgradeError', error);
  1510. }
  1511. function onTransportClose(){
  1512. onerror("transport closed");
  1513. }
  1514. //When the socket is closed while we're probing
  1515. function onclose(){
  1516. onerror("socket closed");
  1517. }
  1518. //When the socket is upgraded while we're probing
  1519. function onupgrade(to){
  1520. if (transport && to.name != transport.name) {
  1521. debug('"%s" works - aborting "%s"', to.name, transport.name);
  1522. freezeTransport();
  1523. }
  1524. }
  1525. //Remove all listeners on the transport and on self
  1526. function cleanup(){
  1527. transport.removeListener('open', onTransportOpen);
  1528. transport.removeListener('error', onerror);
  1529. transport.removeListener('close', onTransportClose);
  1530. self.removeListener('close', onclose);
  1531. self.removeListener('upgrading', onupgrade);
  1532. }
  1533. transport.once('open', onTransportOpen);
  1534. transport.once('error', onerror);
  1535. transport.once('close', onTransportClose);
  1536. this.once('close', onclose);
  1537. this.once('upgrading', onupgrade);
  1538. transport.open();
  1539. };
  1540. /**
  1541. * Called when connection is deemed open.
  1542. *
  1543. * @api public
  1544. */
  1545. Socket.prototype.onOpen = function () {
  1546. debug('socket open');
  1547. this.readyState = 'open';
  1548. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  1549. this.emit('open');
  1550. this.flush();
  1551. // we check for `readyState` in case an `open`
  1552. // listener already closed the socket
  1553. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  1554. debug('starting upgrade probes');
  1555. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  1556. this.probe(this.upgrades[i]);
  1557. }
  1558. }
  1559. };
  1560. /**
  1561. * Handles a packet.
  1562. *
  1563. * @api private
  1564. */
  1565. Socket.prototype.onPacket = function (packet) {
  1566. if ('opening' == this.readyState || 'open' == this.readyState) {
  1567. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  1568. this.emit('packet', packet);
  1569. // Socket is live - any packet counts
  1570. this.emit('heartbeat');
  1571. switch (packet.type) {
  1572. case 'open':
  1573. this.onHandshake(parsejson(packet.data));
  1574. break;
  1575. case 'pong':
  1576. this.setPing();
  1577. break;
  1578. case 'error':
  1579. var err = new Error('server error');
  1580. err.code = packet.data;
  1581. this.emit('error', err);
  1582. break;
  1583. case 'message':
  1584. this.emit('data', packet.data);
  1585. this.emit('message', packet.data);
  1586. break;
  1587. }
  1588. } else {
  1589. debug('packet received with socket readyState "%s"', this.readyState);
  1590. }
  1591. };
  1592. /**
  1593. * Called upon handshake completion.
  1594. *
  1595. * @param {Object} handshake obj
  1596. * @api private
  1597. */
  1598. Socket.prototype.onHandshake = function (data) {
  1599. this.emit('handshake', data);
  1600. this.id = data.sid;
  1601. this.transport.query.sid = data.sid;
  1602. this.upgrades = this.filterUpgrades(data.upgrades);
  1603. this.pingInterval = data.pingInterval;
  1604. this.pingTimeout = data.pingTimeout;
  1605. this.onOpen();
  1606. // In case open handler closes socket
  1607. if ('closed' == this.readyState) return;
  1608. this.setPing();
  1609. // Prolong liveness of socket on heartbeat
  1610. this.removeListener('heartbeat', this.onHeartbeat);
  1611. this.on('heartbeat', this.onHeartbeat);
  1612. };
  1613. /**
  1614. * Resets ping timeout.
  1615. *
  1616. * @api private
  1617. */
  1618. Socket.prototype.onHeartbeat = function (timeout) {
  1619. clearTimeout(this.pingTimeoutTimer);
  1620. var self = this;
  1621. self.pingTimeoutTimer = setTimeout(function () {
  1622. if ('closed' == self.readyState) return;
  1623. self.onClose('ping timeout');
  1624. }, timeout || (self.pingInterval + self.pingTimeout));
  1625. };
  1626. /**
  1627. * Pings server every `this.pingInterval` and expects response
  1628. * within `this.pingTimeout` or closes connection.
  1629. *
  1630. * @api private
  1631. */
  1632. Socket.prototype.setPing = function () {
  1633. var self = this;
  1634. clearTimeout(self.pingIntervalTimer);
  1635. self.pingIntervalTimer = setTimeout(function () {
  1636. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  1637. self.ping();
  1638. self.onHeartbeat(self.pingTimeout);
  1639. }, self.pingInterval);
  1640. };
  1641. /**
  1642. * Sends a ping packet.
  1643. *
  1644. * @api public
  1645. */
  1646. Socket.prototype.ping = function () {
  1647. this.sendPacket('ping');
  1648. };
  1649. /**
  1650. * Called on `drain` event
  1651. *
  1652. * @api private
  1653. */
  1654. Socket.prototype.onDrain = function() {
  1655. for (var i = 0; i < this.prevBufferLen; i++) {
  1656. if (this.callbackBuffer[i]) {
  1657. this.callbackBuffer[i]();
  1658. }
  1659. }
  1660. this.writeBuffer.splice(0, this.prevBufferLen);
  1661. this.callbackBuffer.splice(0, this.prevBufferLen);
  1662. // setting prevBufferLen = 0 is very important
  1663. // for example, when upgrading, upgrade packet is sent over,
  1664. // and a nonzero prevBufferLen could cause problems on `drain`
  1665. this.prevBufferLen = 0;
  1666. if (this.writeBuffer.length == 0) {
  1667. this.emit('drain');
  1668. } else {
  1669. this.flush();
  1670. }
  1671. };
  1672. /**
  1673. * Flush write buffers.
  1674. *
  1675. * @api private
  1676. */
  1677. Socket.prototype.flush = function () {
  1678. if ('closed' != this.readyState && this.transport.writable &&
  1679. !this.upgrading && this.writeBuffer.length) {
  1680. debug('flushing %d packets in socket', this.writeBuffer.length);
  1681. this.transport.send(this.writeBuffer);
  1682. // keep track of current length of writeBuffer
  1683. // splice writeBuffer and callbackBuffer on `drain`
  1684. this.prevBufferLen = this.writeBuffer.length;
  1685. this.emit('flush');
  1686. }
  1687. };
  1688. /**
  1689. * Sends a message.
  1690. *
  1691. * @param {String} message.
  1692. * @param {Function} callback function.
  1693. * @return {Socket} for chaining.
  1694. * @api public
  1695. */
  1696. Socket.prototype.write =
  1697. Socket.prototype.send = function (msg, fn) {
  1698. this.sendPacket('message', msg, fn);
  1699. return this;
  1700. };
  1701. /**
  1702. * Sends a packet.
  1703. *
  1704. * @param {String} packet type.
  1705. * @param {String} data.
  1706. * @param {Function} callback function.
  1707. * @api private
  1708. */
  1709. Socket.prototype.sendPacket = function (type, data, fn) {
  1710. var packet = { type: type, data: data };
  1711. this.emit('packetCreate', packet);
  1712. this.writeBuffer.push(packet);
  1713. this.callbackBuffer.push(fn);
  1714. this.flush();
  1715. };
  1716. /**
  1717. * Closes the connection.
  1718. *
  1719. * @api private
  1720. */
  1721. Socket.prototype.close = function () {
  1722. if ('opening' == this.readyState || 'open' == this.readyState) {
  1723. this.onClose('forced close');
  1724. debug('socket closing - telling transport to close');
  1725. this.transport.close();
  1726. }
  1727. return this;
  1728. };
  1729. /**
  1730. * Called upon transport error
  1731. *
  1732. * @api private
  1733. */
  1734. Socket.prototype.onError = function (err) {
  1735. debug('socket error %j', err);
  1736. Socket.priorWebsocketSuccess = false;
  1737. this.emit('error', err);
  1738. this.onClose('transport error', err);
  1739. };
  1740. /**
  1741. * Called upon transport close.
  1742. *
  1743. * @api private
  1744. */
  1745. Socket.prototype.onClose = function (reason, desc) {
  1746. if ('opening' == this.readyState || 'open' == this.readyState) {
  1747. debug('socket close with reason: "%s"', reason);
  1748. var self = this;
  1749. // clear timers
  1750. clearTimeout(this.pingIntervalTimer);
  1751. clearTimeout(this.pingTimeoutTimer);
  1752. // clean buffers in next tick, so developers can still
  1753. // grab the buffers on `close` event
  1754. setTimeout(function() {
  1755. self.writeBuffer = [];
  1756. self.callbackBuffer = [];
  1757. self.prevBufferLen = 0;
  1758. }, 0);
  1759. // stop event from firing again for transport
  1760. this.transport.removeAllListeners('close');
  1761. // ensure transport won't stay open
  1762. this.transport.close();
  1763. // ignore further transport communication
  1764. this.transport.removeAllListeners();
  1765. // set ready state
  1766. this.readyState = 'closed';
  1767. // clear session id
  1768. this.id = null;
  1769. // emit close event
  1770. this.emit('close', reason, desc);
  1771. }
  1772. };
  1773. /**
  1774. * Filters upgrades, returning only those matching client transports.
  1775. *
  1776. * @param {Array} server upgrades
  1777. * @api private
  1778. *
  1779. */
  1780. Socket.prototype.filterUpgrades = function (upgrades) {
  1781. var filteredUpgrades = [];
  1782. for (var i = 0, j = upgrades.length; i<j; i++) {
  1783. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1784. }
  1785. return filteredUpgrades;
  1786. };
  1787. },{"./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){
  1788. /**
  1789. * Module dependencies.
  1790. */
  1791. var parser = require('engine.io-parser');
  1792. var Emitter = require('component-emitter');
  1793. /**
  1794. * Module exports.
  1795. */
  1796. module.exports = Transport;
  1797. /**
  1798. * Transport abstract constructor.
  1799. *
  1800. * @param {Object} options.
  1801. * @api private
  1802. */
  1803. function Transport (opts) {
  1804. this.path = opts.path;
  1805. this.hostname = opts.hostname;
  1806. this.port = opts.port;
  1807. this.secure = opts.secure;
  1808. this.query = opts.query;
  1809. this.timestampParam = opts.timestampParam;
  1810. this.timestampRequests = opts.timestampRequests;
  1811. this.readyState = '';
  1812. this.agent = opts.agent || false;
  1813. this.socket = opts.socket;
  1814. }
  1815. /**
  1816. * Mix in `Emitter`.
  1817. */
  1818. Emitter(Transport.prototype);
  1819. /**
  1820. * A counter used to prevent collisions in the timestamps used
  1821. * for cache busting.
  1822. */
  1823. Transport.timestamps = 0;
  1824. /**
  1825. * Emits an error.
  1826. *
  1827. * @param {String} str
  1828. * @return {Transport} for chaining
  1829. * @api public
  1830. */
  1831. Transport.prototype.onError = function (msg, desc) {
  1832. var err = new Error(msg);
  1833. err.type = 'TransportError';
  1834. err.description = desc;
  1835. this.emit('error', err);
  1836. return this;
  1837. };
  1838. /**
  1839. * Opens the transport.
  1840. *
  1841. * @api public
  1842. */
  1843. Transport.prototype.open = function () {
  1844. if ('closed' == this.readyState || '' == this.readyState) {
  1845. this.readyState = 'opening';
  1846. this.doOpen();
  1847. }
  1848. return this;
  1849. };
  1850. /**
  1851. * Closes the transport.
  1852. *
  1853. * @api private
  1854. */
  1855. Transport.prototype.close = function () {
  1856. if ('opening' == this.readyState || 'open' == this.readyState) {
  1857. this.doClose();
  1858. this.onClose();
  1859. }
  1860. return this;
  1861. };
  1862. /**
  1863. * Sends multiple packets.
  1864. *
  1865. * @param {Array} packets
  1866. * @api private
  1867. */
  1868. Transport.prototype.send = function(packets){
  1869. if ('open' == this.readyState) {
  1870. this.write(packets);
  1871. } else {
  1872. throw new Error('Transport not open');
  1873. }
  1874. };
  1875. /**
  1876. * Called upon open
  1877. *
  1878. * @api private
  1879. */
  1880. Transport.prototype.onOpen = function () {
  1881. this.readyState = 'open';
  1882. this.writable = true;
  1883. this.emit('open');
  1884. };
  1885. /**
  1886. * Called with data.
  1887. *
  1888. * @param {String} data
  1889. * @api private
  1890. */
  1891. Transport.prototype.onData = function (data) {
  1892. this.onPacket(parser.decodePacket(data, this.socket.binaryType));
  1893. };
  1894. /**
  1895. * Called with a decoded packet.
  1896. */
  1897. Transport.prototype.onPacket = function (packet) {
  1898. this.emit('packet', packet);
  1899. };
  1900. /**
  1901. * Called upon close.
  1902. *
  1903. * @api private
  1904. */
  1905. Transport.prototype.onClose = function () {
  1906. this.readyState = 'closed';
  1907. this.emit('close');
  1908. };
  1909. },{"component-emitter":8,"engine.io-parser":22}],15:[function(require,module,exports){
  1910. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/**
  1911. * Module dependencies
  1912. */
  1913. var XMLHttpRequest = require('xmlhttprequest');
  1914. var XHR = require('./polling-xhr');
  1915. var JSONP = require('./polling-jsonp');
  1916. var websocket = require('./websocket');
  1917. /**
  1918. * Export transports.
  1919. */
  1920. exports.polling = polling;
  1921. exports.websocket = websocket;
  1922. /**
  1923. * Polling transport polymorphic constructor.
  1924. * Decides on xhr vs jsonp based on feature detection.
  1925. *
  1926. * @api private
  1927. */
  1928. function polling(opts){
  1929. var xhr;
  1930. var xd = false;
  1931. if (global.location) {
  1932. var isSSL = 'https:' == location.protocol;
  1933. var port = location.port;
  1934. // some user agents have empty `location.port`
  1935. if (!port) {
  1936. port = isSSL ? 443 : 80;
  1937. }
  1938. xd = opts.hostname != location.hostname || port != opts.port;
  1939. }
  1940. opts.xdomain = xd;
  1941. xhr = new XMLHttpRequest(opts);
  1942. if ('open' in xhr && !opts.forceJSONP) {
  1943. return new XHR(opts);
  1944. } else {
  1945. return new JSONP(opts);
  1946. }
  1947. }
  1948. },{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,"xmlhttprequest":20}],16:[function(require,module,exports){
  1949. var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
  1950. /**
  1951. * Module requirements.
  1952. */
  1953. var Polling = require('./polling');
  1954. var inherit = require('component-inherit');
  1955. /**
  1956. * Module exports.
  1957. */
  1958. module.exports = JSONPPolling;
  1959. /**
  1960. * Cached regular expressions.
  1961. */
  1962. var rNewline = /\n/g;
  1963. var rEscapedNewline = /\\n/g;
  1964. /**
  1965. * Global JSONP callbacks.
  1966. */
  1967. var callbacks;
  1968. /**
  1969. * Callbacks count.
  1970. */
  1971. var index = 0;
  1972. /**
  1973. * Noop.
  1974. */
  1975. function empty () { }
  1976. /**
  1977. * JSONP Polling constructor.
  1978. *
  1979. * @param {Object} opts.
  1980. * @api public
  1981. */
  1982. function JSONPPolling (opts) {
  1983. Polling.call(this, opts);
  1984. this.query = this.query || {};
  1985. // define global callbacks array if not present
  1986. // we do this…