PageRenderTime 53ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 1ms

/socket.io.js

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

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