You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7005 lines
170 KiB

  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;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(_dereq_,module,exports){
  2. module.exports = _dereq_('./lib/');
  3. },{"./lib/":2}],2:[function(_dereq_,module,exports){
  4. /**
  5. * Module dependencies.
  6. */
  7. var url = _dereq_('./url');
  8. var parser = _dereq_('socket.io-parser');
  9. var Manager = _dereq_('./manager');
  10. var debug = _dereq_('debug')('socket.io-client');
  11. /**
  12. * Module exports.
  13. */
  14. module.exports = exports = lookup;
  15. /**
  16. * Managers cache.
  17. */
  18. var cache = exports.managers = {};
  19. /**
  20. * Looks up an existing `Manager` for multiplexing.
  21. * If the user summons:
  22. *
  23. * `io('http://localhost/a');`
  24. * `io('http://localhost/b');`
  25. *
  26. * We reuse the existing instance based on same scheme/port/host,
  27. * and we initialize sockets for each namespace.
  28. *
  29. * @api public
  30. */
  31. function lookup(uri, opts) {
  32. if (typeof uri == 'object') {
  33. opts = uri;
  34. uri = undefined;
  35. }
  36. opts = opts || {};
  37. var parsed = url(uri);
  38. var source = parsed.source;
  39. var id = parsed.id;
  40. var path = parsed.path;
  41. var sameNamespace = (cache[id] && cache[id].nsps[path] &&
  42. path == cache[id].nsps[path].nsp);
  43. var newConnection = opts.forceNew || opts['force new connection'] ||
  44. false === opts.multiplex || sameNamespace;
  45. var io;
  46. if (newConnection) {
  47. debug('ignoring socket cache for %s', source);
  48. io = Manager(source, opts);
  49. } else {
  50. if (!cache[id]) {
  51. debug('new io instance for %s', source);
  52. cache[id] = Manager(source, opts);
  53. }
  54. io = cache[id];
  55. }
  56. return io.socket(parsed.path);
  57. }
  58. /**
  59. * Protocol version.
  60. *
  61. * @api public
  62. */
  63. exports.protocol = parser.protocol;
  64. /**
  65. * `connect`.
  66. *
  67. * @param {String} uri
  68. * @api public
  69. */
  70. exports.connect = lookup;
  71. /**
  72. * Expose constructors for standalone build.
  73. *
  74. * @api public
  75. */
  76. exports.Manager = _dereq_('./manager');
  77. exports.Socket = _dereq_('./socket');
  78. },{"./manager":3,"./socket":5,"./url":6,"debug":10,"socket.io-parser":46}],3:[function(_dereq_,module,exports){
  79. /**
  80. * Module dependencies.
  81. */
  82. var url = _dereq_('./url');
  83. var eio = _dereq_('engine.io-client');
  84. var Socket = _dereq_('./socket');
  85. var Emitter = _dereq_('component-emitter');
  86. var parser = _dereq_('socket.io-parser');
  87. var on = _dereq_('./on');
  88. var bind = _dereq_('component-bind');
  89. var object = _dereq_('object-component');
  90. var debug = _dereq_('debug')('socket.io-client:manager');
  91. var indexOf = _dereq_('indexof');
  92. var Backoff = _dereq_('backo2');
  93. /**
  94. * Module exports
  95. */
  96. module.exports = Manager;
  97. /**
  98. * `Manager` constructor.
  99. *
  100. * @param {String} engine instance or engine uri/opts
  101. * @param {Object} options
  102. * @api public
  103. */
  104. function Manager(uri, opts){
  105. if (!(this instanceof Manager)) return new Manager(uri, opts);
  106. if (uri && ('object' == typeof uri)) {
  107. opts = uri;
  108. uri = undefined;
  109. }
  110. opts = opts || {};
  111. opts.path = opts.path || '/socket.io';
  112. this.nsps = {};
  113. this.subs = [];
  114. this.opts = opts;
  115. this.reconnection(opts.reconnection !== false);
  116. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  117. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  118. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  119. this.randomizationFactor(opts.randomizationFactor || 0.5);
  120. this.backoff = new Backoff({
  121. min: this.reconnectionDelay(),
  122. max: this.reconnectionDelayMax(),
  123. jitter: this.randomizationFactor()
  124. });
  125. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  126. this.readyState = 'closed';
  127. this.uri = uri;
  128. this.connected = [];
  129. this.encoding = false;
  130. this.packetBuffer = [];
  131. this.encoder = new parser.Encoder();
  132. this.decoder = new parser.Decoder();
  133. this.autoConnect = opts.autoConnect !== false;
  134. if (this.autoConnect) this.open();
  135. }
  136. /**
  137. * Propagate given event to sockets and emit on `this`
  138. *
  139. * @api private
  140. */
  141. Manager.prototype.emitAll = function() {
  142. this.emit.apply(this, arguments);
  143. for (var nsp in this.nsps) {
  144. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  145. }
  146. };
  147. /**
  148. * Update `socket.id` of all sockets
  149. *
  150. * @api private
  151. */
  152. Manager.prototype.updateSocketIds = function(){
  153. for (var nsp in this.nsps) {
  154. this.nsps[nsp].id = this.engine.id;
  155. }
  156. };
  157. /**
  158. * Mix in `Emitter`.
  159. */
  160. Emitter(Manager.prototype);
  161. /**
  162. * Sets the `reconnection` config.
  163. *
  164. * @param {Boolean} true/false if it should automatically reconnect
  165. * @return {Manager} self or value
  166. * @api public
  167. */
  168. Manager.prototype.reconnection = function(v){
  169. if (!arguments.length) return this._reconnection;
  170. this._reconnection = !!v;
  171. return this;
  172. };
  173. /**
  174. * Sets the reconnection attempts config.
  175. *
  176. * @param {Number} max reconnection attempts before giving up
  177. * @return {Manager} self or value
  178. * @api public
  179. */
  180. Manager.prototype.reconnectionAttempts = function(v){
  181. if (!arguments.length) return this._reconnectionAttempts;
  182. this._reconnectionAttempts = v;
  183. return this;
  184. };
  185. /**
  186. * Sets the delay between reconnections.
  187. *
  188. * @param {Number} delay
  189. * @return {Manager} self or value
  190. * @api public
  191. */
  192. Manager.prototype.reconnectionDelay = function(v){
  193. if (!arguments.length) return this._reconnectionDelay;
  194. this._reconnectionDelay = v;
  195. this.backoff && this.backoff.setMin(v);
  196. return this;
  197. };
  198. Manager.prototype.randomizationFactor = function(v){
  199. if (!arguments.length) return this._randomizationFactor;
  200. this._randomizationFactor = v;
  201. this.backoff && this.backoff.setJitter(v);
  202. return this;
  203. };
  204. /**
  205. * Sets the maximum delay between reconnections.
  206. *
  207. * @param {Number} delay
  208. * @return {Manager} self or value
  209. * @api public
  210. */
  211. Manager.prototype.reconnectionDelayMax = function(v){
  212. if (!arguments.length) return this._reconnectionDelayMax;
  213. this._reconnectionDelayMax = v;
  214. this.backoff && this.backoff.setMax(v);
  215. return this;
  216. };
  217. /**
  218. * Sets the connection timeout. `false` to disable
  219. *
  220. * @return {Manager} self or value
  221. * @api public
  222. */
  223. Manager.prototype.timeout = function(v){
  224. if (!arguments.length) return this._timeout;
  225. this._timeout = v;
  226. return this;
  227. };
  228. /**
  229. * Starts trying to reconnect if reconnection is enabled and we have not
  230. * started reconnecting yet
  231. *
  232. * @api private
  233. */
  234. Manager.prototype.maybeReconnectOnOpen = function() {
  235. // Only try to reconnect if it's the first time we're connecting
  236. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  237. // keeps reconnection from firing twice for the same reconnection loop
  238. this.reconnect();
  239. }
  240. };
  241. /**
  242. * Sets the current transport `socket`.
  243. *
  244. * @param {Function} optional, callback
  245. * @return {Manager} self
  246. * @api public
  247. */
  248. Manager.prototype.open =
  249. Manager.prototype.connect = function(fn){
  250. debug('readyState %s', this.readyState);
  251. if (~this.readyState.indexOf('open')) return this;
  252. debug('opening %s', this.uri);
  253. this.engine = eio(this.uri, this.opts);
  254. var socket = this.engine;
  255. var self = this;
  256. this.readyState = 'opening';
  257. this.skipReconnect = false;
  258. // emit `open`
  259. var openSub = on(socket, 'open', function() {
  260. self.onopen();
  261. fn && fn();
  262. });
  263. // emit `connect_error`
  264. var errorSub = on(socket, 'error', function(data){
  265. debug('connect_error');
  266. self.cleanup();
  267. self.readyState = 'closed';
  268. self.emitAll('connect_error', data);
  269. if (fn) {
  270. var err = new Error('Connection error');
  271. err.data = data;
  272. fn(err);
  273. } else {
  274. // Only do this if there is no fn to handle the error
  275. self.maybeReconnectOnOpen();
  276. }
  277. });
  278. // emit `connect_timeout`
  279. if (false !== this._timeout) {
  280. var timeout = this._timeout;
  281. debug('connect attempt will timeout after %d', timeout);
  282. // set timer
  283. var timer = setTimeout(function(){
  284. debug('connect attempt timed out after %d', timeout);
  285. openSub.destroy();
  286. socket.close();
  287. socket.emit('error', 'timeout');
  288. self.emitAll('connect_timeout', timeout);
  289. }, timeout);
  290. this.subs.push({
  291. destroy: function(){
  292. clearTimeout(timer);
  293. }
  294. });
  295. }
  296. this.subs.push(openSub);
  297. this.subs.push(errorSub);
  298. return this;
  299. };
  300. /**
  301. * Called upon transport open.
  302. *
  303. * @api private
  304. */
  305. Manager.prototype.onopen = function(){
  306. debug('open');
  307. // clear old subs
  308. this.cleanup();
  309. // mark as open
  310. this.readyState = 'open';
  311. this.emit('open');
  312. // add new subs
  313. var socket = this.engine;
  314. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  315. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  316. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  317. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  318. };
  319. /**
  320. * Called with data.
  321. *
  322. * @api private
  323. */
  324. Manager.prototype.ondata = function(data){
  325. this.decoder.add(data);
  326. };
  327. /**
  328. * Called when parser fully decodes a packet.
  329. *
  330. * @api private
  331. */
  332. Manager.prototype.ondecoded = function(packet) {
  333. this.emit('packet', packet);
  334. };
  335. /**
  336. * Called upon socket error.
  337. *
  338. * @api private
  339. */
  340. Manager.prototype.onerror = function(err){
  341. debug('error', err);
  342. this.emitAll('error', err);
  343. };
  344. /**
  345. * Creates a new socket for the given `nsp`.
  346. *
  347. * @return {Socket}
  348. * @api public
  349. */
  350. Manager.prototype.socket = function(nsp){
  351. var socket = this.nsps[nsp];
  352. if (!socket) {
  353. socket = new Socket(this, nsp);
  354. this.nsps[nsp] = socket;
  355. var self = this;
  356. socket.on('connect', function(){
  357. socket.id = self.engine.id;
  358. if (!~indexOf(self.connected, socket)) {
  359. self.connected.push(socket);
  360. }
  361. });
  362. }
  363. return socket;
  364. };
  365. /**
  366. * Called upon a socket close.
  367. *
  368. * @param {Socket} socket
  369. */
  370. Manager.prototype.destroy = function(socket){
  371. var index = indexOf(this.connected, socket);
  372. if (~index) this.connected.splice(index, 1);
  373. if (this.connected.length) return;
  374. this.close();
  375. };
  376. /**
  377. * Writes a packet.
  378. *
  379. * @param {Object} packet
  380. * @api private
  381. */
  382. Manager.prototype.packet = function(packet){
  383. debug('writing packet %j', packet);
  384. var self = this;
  385. if (!self.encoding) {
  386. // encode, then write to engine with result
  387. self.encoding = true;
  388. this.encoder.encode(packet, function(encodedPackets) {
  389. for (var i = 0; i < encodedPackets.length; i++) {
  390. self.engine.write(encodedPackets[i]);
  391. }
  392. self.encoding = false;
  393. self.processPacketQueue();
  394. });
  395. } else { // add packet to the queue
  396. self.packetBuffer.push(packet);
  397. }
  398. };
  399. /**
  400. * If packet buffer is non-empty, begins encoding the
  401. * next packet in line.
  402. *
  403. * @api private
  404. */
  405. Manager.prototype.processPacketQueue = function() {
  406. if (this.packetBuffer.length > 0 && !this.encoding) {
  407. var pack = this.packetBuffer.shift();
  408. this.packet(pack);
  409. }
  410. };
  411. /**
  412. * Clean up transport subscriptions and packet buffer.
  413. *
  414. * @api private
  415. */
  416. Manager.prototype.cleanup = function(){
  417. var sub;
  418. while (sub = this.subs.shift()) sub.destroy();
  419. this.packetBuffer = [];
  420. this.encoding = false;
  421. this.decoder.destroy();
  422. };
  423. /**
  424. * Close the current socket.
  425. *
  426. * @api private
  427. */
  428. Manager.prototype.close =
  429. Manager.prototype.disconnect = function(){
  430. this.skipReconnect = true;
  431. this.backoff.reset();
  432. this.readyState = 'closed';
  433. this.engine && this.engine.close();
  434. };
  435. /**
  436. * Called upon engine close.
  437. *
  438. * @api private
  439. */
  440. Manager.prototype.onclose = function(reason){
  441. debug('close');
  442. this.cleanup();
  443. this.backoff.reset();
  444. this.readyState = 'closed';
  445. this.emit('close', reason);
  446. if (this._reconnection && !this.skipReconnect) {
  447. this.reconnect();
  448. }
  449. };
  450. /**
  451. * Attempt a reconnection.
  452. *
  453. * @api private
  454. */
  455. Manager.prototype.reconnect = function(){
  456. if (this.reconnecting || this.skipReconnect) return this;
  457. var self = this;
  458. if (this.backoff.attempts >= this._reconnectionAttempts) {
  459. debug('reconnect failed');
  460. this.backoff.reset();
  461. this.emitAll('reconnect_failed');
  462. this.reconnecting = false;
  463. } else {
  464. var delay = this.backoff.duration();
  465. debug('will wait %dms before reconnect attempt', delay);
  466. this.reconnecting = true;
  467. var timer = setTimeout(function(){
  468. if (self.skipReconnect) return;
  469. debug('attempting reconnect');
  470. self.emitAll('reconnect_attempt', self.backoff.attempts);
  471. self.emitAll('reconnecting', self.backoff.attempts);
  472. // check again for the case socket closed in above events
  473. if (self.skipReconnect) return;
  474. self.open(function(err){
  475. if (err) {
  476. debug('reconnect attempt error');
  477. self.reconnecting = false;
  478. self.reconnect();
  479. self.emitAll('reconnect_error', err.data);
  480. } else {
  481. debug('reconnect success');
  482. self.onreconnect();
  483. }
  484. });
  485. }, delay);
  486. this.subs.push({
  487. destroy: function(){
  488. clearTimeout(timer);
  489. }
  490. });
  491. }
  492. };
  493. /**
  494. * Called upon successful reconnect.
  495. *
  496. * @api private
  497. */
  498. Manager.prototype.onreconnect = function(){
  499. var attempt = this.backoff.attempts;
  500. this.reconnecting = false;
  501. this.backoff.reset();
  502. this.updateSocketIds();
  503. this.emitAll('reconnect', attempt);
  504. };
  505. },{"./on":4,"./socket":5,"./url":6,"backo2":7,"component-bind":8,"component-emitter":9,"debug":10,"engine.io-client":11,"indexof":42,"object-component":43,"socket.io-parser":46}],4:[function(_dereq_,module,exports){
  506. /**
  507. * Module exports.
  508. */
  509. module.exports = on;
  510. /**
  511. * Helper for subscriptions.
  512. *
  513. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  514. * @param {String} event name
  515. * @param {Function} callback
  516. * @api public
  517. */
  518. function on(obj, ev, fn) {
  519. obj.on(ev, fn);
  520. return {
  521. destroy: function(){
  522. obj.removeListener(ev, fn);
  523. }
  524. };
  525. }
  526. },{}],5:[function(_dereq_,module,exports){
  527. /**
  528. * Module dependencies.
  529. */
  530. var parser = _dereq_('socket.io-parser');
  531. var Emitter = _dereq_('component-emitter');
  532. var toArray = _dereq_('to-array');
  533. var on = _dereq_('./on');
  534. var bind = _dereq_('component-bind');
  535. var debug = _dereq_('debug')('socket.io-client:socket');
  536. var hasBin = _dereq_('has-binary');
  537. /**
  538. * Module exports.
  539. */
  540. module.exports = exports = Socket;
  541. /**
  542. * Internal events (blacklisted).
  543. * These events can't be emitted by the user.
  544. *
  545. * @api private
  546. */
  547. var events = {
  548. connect: 1,
  549. connect_error: 1,
  550. connect_timeout: 1,
  551. disconnect: 1,
  552. error: 1,
  553. reconnect: 1,
  554. reconnect_attempt: 1,
  555. reconnect_failed: 1,
  556. reconnect_error: 1,
  557. reconnecting: 1
  558. };
  559. /**
  560. * Shortcut to `Emitter#emit`.
  561. */
  562. var emit = Emitter.prototype.emit;
  563. /**
  564. * `Socket` constructor.
  565. *
  566. * @api public
  567. */
  568. function Socket(io, nsp){
  569. this.io = io;
  570. this.nsp = nsp;
  571. this.json = this; // compat
  572. this.ids = 0;
  573. this.acks = {};
  574. if (this.io.autoConnect) this.open();
  575. this.receiveBuffer = [];
  576. this.sendBuffer = [];
  577. this.connected = false;
  578. this.disconnected = true;
  579. }
  580. /**
  581. * Mix in `Emitter`.
  582. */
  583. Emitter(Socket.prototype);
  584. /**
  585. * Subscribe to open, close and packet events
  586. *
  587. * @api private
  588. */
  589. Socket.prototype.subEvents = function() {
  590. if (this.subs) return;
  591. var io = this.io;
  592. this.subs = [
  593. on(io, 'open', bind(this, 'onopen')),
  594. on(io, 'packet', bind(this, 'onpacket')),
  595. on(io, 'close', bind(this, 'onclose'))
  596. ];
  597. };
  598. /**
  599. * "Opens" the socket.
  600. *
  601. * @api public
  602. */
  603. Socket.prototype.open =
  604. Socket.prototype.connect = function(){
  605. if (this.connected) return this;
  606. this.subEvents();
  607. this.io.open(); // ensure open
  608. if ('open' == this.io.readyState) this.onopen();
  609. return this;
  610. };
  611. /**
  612. * Sends a `message` event.
  613. *
  614. * @return {Socket} self
  615. * @api public
  616. */
  617. Socket.prototype.send = function(){
  618. var args = toArray(arguments);
  619. args.unshift('message');
  620. this.emit.apply(this, args);
  621. return this;
  622. };
  623. /**
  624. * Override `emit`.
  625. * If the event is in `events`, it's emitted normally.
  626. *
  627. * @param {String} event name
  628. * @return {Socket} self
  629. * @api public
  630. */
  631. Socket.prototype.emit = function(ev){
  632. if (events.hasOwnProperty(ev)) {
  633. emit.apply(this, arguments);
  634. return this;
  635. }
  636. var args = toArray(arguments);
  637. var parserType = parser.EVENT; // default
  638. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  639. var packet = { type: parserType, data: args };
  640. // event ack callback
  641. if ('function' == typeof args[args.length - 1]) {
  642. debug('emitting packet with ack id %d', this.ids);
  643. this.acks[this.ids] = args.pop();
  644. packet.id = this.ids++;
  645. }
  646. if (this.connected) {
  647. this.packet(packet);
  648. } else {
  649. this.sendBuffer.push(packet);
  650. }
  651. return this;
  652. };
  653. /**
  654. * Sends a packet.
  655. *
  656. * @param {Object} packet
  657. * @api private
  658. */
  659. Socket.prototype.packet = function(packet){
  660. packet.nsp = this.nsp;
  661. this.io.packet(packet);
  662. };
  663. /**
  664. * Called upon engine `open`.
  665. *
  666. * @api private
  667. */
  668. Socket.prototype.onopen = function(){
  669. debug('transport is open - connecting');
  670. // write connect packet if necessary
  671. if ('/' != this.nsp) {
  672. this.packet({ type: parser.CONNECT });
  673. }
  674. };
  675. /**
  676. * Called upon engine `close`.
  677. *
  678. * @param {String} reason
  679. * @api private
  680. */
  681. Socket.prototype.onclose = function(reason){
  682. debug('close (%s)', reason);
  683. this.connected = false;
  684. this.disconnected = true;
  685. delete this.id;
  686. this.emit('disconnect', reason);
  687. };
  688. /**
  689. * Called with socket packet.
  690. *
  691. * @param {Object} packet
  692. * @api private
  693. */
  694. Socket.prototype.onpacket = function(packet){
  695. if (packet.nsp != this.nsp) return;
  696. switch (packet.type) {
  697. case parser.CONNECT:
  698. this.onconnect();
  699. break;
  700. case parser.EVENT:
  701. this.onevent(packet);
  702. break;
  703. case parser.BINARY_EVENT:
  704. this.onevent(packet);
  705. break;
  706. case parser.ACK:
  707. this.onack(packet);
  708. break;
  709. case parser.BINARY_ACK:
  710. this.onack(packet);
  711. break;
  712. case parser.DISCONNECT:
  713. this.ondisconnect();
  714. break;
  715. case parser.ERROR:
  716. this.emit('error', packet.data);
  717. break;
  718. }
  719. };
  720. /**
  721. * Called upon a server event.
  722. *
  723. * @param {Object} packet
  724. * @api private
  725. */
  726. Socket.prototype.onevent = function(packet){
  727. var args = packet.data || [];
  728. debug('emitting event %j', args);
  729. if (null != packet.id) {
  730. debug('attaching ack callback to event');
  731. args.push(this.ack(packet.id));
  732. }
  733. if (this.connected) {
  734. emit.apply(this, args);
  735. } else {
  736. this.receiveBuffer.push(args);
  737. }
  738. };
  739. /**
  740. * Produces an ack callback to emit with an event.
  741. *
  742. * @api private
  743. */
  744. Socket.prototype.ack = function(id){
  745. var self = this;
  746. var sent = false;
  747. return function(){
  748. // prevent double callbacks
  749. if (sent) return;
  750. sent = true;
  751. var args = toArray(arguments);
  752. debug('sending ack %j', args);
  753. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  754. self.packet({
  755. type: type,
  756. id: id,
  757. data: args
  758. });
  759. };
  760. };
  761. /**
  762. * Called upon a server acknowlegement.
  763. *
  764. * @param {Object} packet
  765. * @api private
  766. */
  767. Socket.prototype.onack = function(packet){
  768. debug('calling ack %s with %j', packet.id, packet.data);
  769. var fn = this.acks[packet.id];
  770. fn.apply(this, packet.data);
  771. delete this.acks[packet.id];
  772. };
  773. /**
  774. * Called upon server connect.
  775. *
  776. * @api private
  777. */
  778. Socket.prototype.onconnect = function(){
  779. this.connected = true;
  780. this.disconnected = false;
  781. this.emit('connect');
  782. this.emitBuffered();
  783. };
  784. /**
  785. * Emit buffered events (received and emitted).
  786. *
  787. * @api private
  788. */
  789. Socket.prototype.emitBuffered = function(){
  790. var i;
  791. for (i = 0; i < this.receiveBuffer.length; i++) {
  792. emit.apply(this, this.receiveBuffer[i]);
  793. }
  794. this.receiveBuffer = [];
  795. for (i = 0; i < this.sendBuffer.length; i++) {
  796. this.packet(this.sendBuffer[i]);
  797. }
  798. this.sendBuffer = [];
  799. };
  800. /**
  801. * Called upon server disconnect.
  802. *
  803. * @api private
  804. */
  805. Socket.prototype.ondisconnect = function(){
  806. debug('server disconnect (%s)', this.nsp);
  807. this.destroy();
  808. this.onclose('io server disconnect');
  809. };
  810. /**
  811. * Called upon forced client/server side disconnections,
  812. * this method ensures the manager stops tracking us and
  813. * that reconnections don't get triggered for this.
  814. *
  815. * @api private.
  816. */
  817. Socket.prototype.destroy = function(){
  818. if (this.subs) {
  819. // clean subscriptions to avoid reconnections
  820. for (var i = 0; i < this.subs.length; i++) {
  821. this.subs[i].destroy();
  822. }
  823. this.subs = null;
  824. }
  825. this.io.destroy(this);
  826. };
  827. /**
  828. * Disconnects the socket manually.
  829. *
  830. * @return {Socket} self
  831. * @api public
  832. */
  833. Socket.prototype.close =
  834. Socket.prototype.disconnect = function(){
  835. if (this.connected) {
  836. debug('performing disconnect (%s)', this.nsp);
  837. this.packet({ type: parser.DISCONNECT });
  838. }
  839. // remove socket from pool
  840. this.destroy();
  841. if (this.connected) {
  842. // fire events
  843. this.onclose('io client disconnect');
  844. }
  845. return this;
  846. };
  847. },{"./on":4,"component-bind":8,"component-emitter":9,"debug":10,"has-binary":38,"socket.io-parser":46,"to-array":50}],6:[function(_dereq_,module,exports){
  848. (function (global){
  849. /**
  850. * Module dependencies.
  851. */
  852. var parseuri = _dereq_('parseuri');
  853. var debug = _dereq_('debug')('socket.io-client:url');
  854. /**
  855. * Module exports.
  856. */
  857. module.exports = url;
  858. /**
  859. * URL parser.
  860. *
  861. * @param {String} url
  862. * @param {Object} An object meant to mimic window.location.
  863. * Defaults to window.location.
  864. * @api public
  865. */
  866. function url(uri, loc){
  867. var obj = uri;
  868. // default to window.location
  869. var loc = loc || global.location;
  870. if (null == uri) uri = loc.protocol + '//' + loc.host;
  871. // relative path support
  872. if ('string' == typeof uri) {
  873. if ('/' == uri.charAt(0)) {
  874. if ('/' == uri.charAt(1)) {
  875. uri = loc.protocol + uri;
  876. } else {
  877. uri = loc.hostname + uri;
  878. }
  879. }
  880. if (!/^(https?|wss?):\/\//.test(uri)) {
  881. debug('protocol-less url %s', uri);
  882. if ('undefined' != typeof loc) {
  883. uri = loc.protocol + '//' + uri;
  884. } else {
  885. uri = 'https://' + uri;
  886. }
  887. }
  888. // parse
  889. debug('parse %s', uri);
  890. obj = parseuri(uri);
  891. }
  892. // make sure we treat `localhost:80` and `localhost` equally
  893. if (!obj.port) {
  894. if (/^(http|ws)$/.test(obj.protocol)) {
  895. obj.port = '80';
  896. }
  897. else if (/^(http|ws)s$/.test(obj.protocol)) {
  898. obj.port = '443';
  899. }
  900. }
  901. obj.path = obj.path || '/';
  902. // define unique id
  903. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  904. // define href
  905. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  906. return obj;
  907. }
  908. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  909. },{"debug":10,"parseuri":44}],7:[function(_dereq_,module,exports){
  910. /**
  911. * Expose `Backoff`.
  912. */
  913. module.exports = Backoff;
  914. /**
  915. * Initialize backoff timer with `opts`.
  916. *
  917. * - `min` initial timeout in milliseconds [100]
  918. * - `max` max timeout [10000]
  919. * - `jitter` [0]
  920. * - `factor` [2]
  921. *
  922. * @param {Object} opts
  923. * @api public
  924. */
  925. function Backoff(opts) {
  926. opts = opts || {};
  927. this.ms = opts.min || 100;
  928. this.max = opts.max || 10000;
  929. this.factor = opts.factor || 2;
  930. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  931. this.attempts = 0;
  932. }
  933. /**
  934. * Return the backoff duration.
  935. *
  936. * @return {Number}
  937. * @api public
  938. */
  939. Backoff.prototype.duration = function(){
  940. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  941. if (this.jitter) {
  942. var rand = Math.random();
  943. var deviation = Math.floor(rand * this.jitter * ms);
  944. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  945. }
  946. return Math.min(ms, this.max) | 0;
  947. };
  948. /**
  949. * Reset the number of attempts.
  950. *
  951. * @api public
  952. */
  953. Backoff.prototype.reset = function(){
  954. this.attempts = 0;
  955. };
  956. /**
  957. * Set the minimum duration
  958. *
  959. * @api public
  960. */
  961. Backoff.prototype.setMin = function(min){
  962. this.ms = min;
  963. };
  964. /**
  965. * Set the maximum duration
  966. *
  967. * @api public
  968. */
  969. Backoff.prototype.setMax = function(max){
  970. this.max = max;
  971. };
  972. /**
  973. * Set the jitter
  974. *
  975. * @api public
  976. */
  977. Backoff.prototype.setJitter = function(jitter){
  978. this.jitter = jitter;
  979. };
  980. },{}],8:[function(_dereq_,module,exports){
  981. /**
  982. * Slice reference.
  983. */
  984. var slice = [].slice;
  985. /**
  986. * Bind `obj` to `fn`.
  987. *
  988. * @param {Object} obj
  989. * @param {Function|String} fn or string
  990. * @return {Function}
  991. * @api public
  992. */
  993. module.exports = function(obj, fn){
  994. if ('string' == typeof fn) fn = obj[fn];
  995. if ('function' != typeof fn) throw new Error('bind() requires a function');
  996. var args = slice.call(arguments, 2);
  997. return function(){
  998. return fn.apply(obj, args.concat(slice.call(arguments)));
  999. }
  1000. };
  1001. },{}],9:[function(_dereq_,module,exports){
  1002. /**
  1003. * Expose `Emitter`.
  1004. */
  1005. module.exports = Emitter;
  1006. /**
  1007. * Initialize a new `Emitter`.
  1008. *
  1009. * @api public
  1010. */
  1011. function Emitter(obj) {
  1012. if (obj) return mixin(obj);
  1013. };
  1014. /**
  1015. * Mixin the emitter properties.
  1016. *
  1017. * @param {Object} obj
  1018. * @return {Object}
  1019. * @api private
  1020. */
  1021. function mixin(obj) {
  1022. for (var key in Emitter.prototype) {
  1023. obj[key] = Emitter.prototype[key];
  1024. }
  1025. return obj;
  1026. }
  1027. /**
  1028. * Listen on the given `event` with `fn`.
  1029. *
  1030. * @param {String} event
  1031. * @param {Function} fn
  1032. * @return {Emitter}
  1033. * @api public
  1034. */
  1035. Emitter.prototype.on =
  1036. Emitter.prototype.addEventListener = function(event, fn){
  1037. this._callbacks = this._callbacks || {};
  1038. (this._callbacks[event] = this._callbacks[event] || [])
  1039. .push(fn);
  1040. return this;
  1041. };
  1042. /**
  1043. * Adds an `event` listener that will be invoked a single
  1044. * time then automatically removed.
  1045. *
  1046. * @param {String} event
  1047. * @param {Function} fn
  1048. * @return {Emitter}
  1049. * @api public
  1050. */
  1051. Emitter.prototype.once = function(event, fn){
  1052. var self = this;
  1053. this._callbacks = this._callbacks || {};
  1054. function on() {
  1055. self.off(event, on);
  1056. fn.apply(this, arguments);
  1057. }
  1058. on.fn = fn;
  1059. this.on(event, on);
  1060. return this;
  1061. };
  1062. /**
  1063. * Remove the given callback for `event` or all
  1064. * registered callbacks.
  1065. *
  1066. * @param {String} event
  1067. * @param {Function} fn
  1068. * @return {Emitter}
  1069. * @api public
  1070. */
  1071. Emitter.prototype.off =
  1072. Emitter.prototype.removeListener =
  1073. Emitter.prototype.removeAllListeners =
  1074. Emitter.prototype.removeEventListener = function(event, fn){
  1075. this._callbacks = this._callbacks || {};
  1076. // all
  1077. if (0 == arguments.length) {
  1078. this._callbacks = {};
  1079. return this;
  1080. }
  1081. // specific event
  1082. var callbacks = this._callbacks[event];
  1083. if (!callbacks) return this;
  1084. // remove all handlers
  1085. if (1 == arguments.length) {
  1086. delete this._callbacks[event];
  1087. return this;
  1088. }
  1089. // remove specific handler
  1090. var cb;
  1091. for (var i = 0; i < callbacks.length; i++) {
  1092. cb = callbacks[i];
  1093. if (cb === fn || cb.fn === fn) {
  1094. callbacks.splice(i, 1);
  1095. break;
  1096. }
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Emit `event` with the given args.
  1102. *
  1103. * @param {String} event
  1104. * @param {Mixed} ...
  1105. * @return {Emitter}
  1106. */
  1107. Emitter.prototype.emit = function(event){
  1108. this._callbacks = this._callbacks || {};
  1109. var args = [].slice.call(arguments, 1)
  1110. , callbacks = this._callbacks[event];
  1111. if (callbacks) {
  1112. callbacks = callbacks.slice(0);
  1113. for (var i = 0, len = callbacks.length; i < len; ++i) {
  1114. callbacks[i].apply(this, args);
  1115. }
  1116. }
  1117. return this;
  1118. };
  1119. /**
  1120. * Return array of callbacks for `event`.
  1121. *
  1122. * @param {String} event
  1123. * @return {Array}
  1124. * @api public
  1125. */
  1126. Emitter.prototype.listeners = function(event){
  1127. this._callbacks = this._callbacks || {};
  1128. return this._callbacks[event] || [];
  1129. };
  1130. /**
  1131. * Check if this emitter has `event` handlers.
  1132. *
  1133. * @param {String} event
  1134. * @return {Boolean}
  1135. * @api public
  1136. */
  1137. Emitter.prototype.hasListeners = function(event){
  1138. return !! this.listeners(event).length;
  1139. };
  1140. },{}],10:[function(_dereq_,module,exports){
  1141. /**
  1142. * Expose `debug()` as the module.
  1143. */
  1144. module.exports = debug;
  1145. /**
  1146. * Create a debugger with the given `name`.
  1147. *
  1148. * @param {String} name
  1149. * @return {Type}
  1150. * @api public
  1151. */
  1152. function debug(name) {
  1153. if (!debug.enabled(name)) return function(){};
  1154. return function(fmt){
  1155. fmt = coerce(fmt);
  1156. var curr = new Date;
  1157. var ms = curr - (debug[name] || curr);
  1158. debug[name] = curr;
  1159. fmt = name
  1160. + ' '
  1161. + fmt
  1162. + ' +' + debug.humanize(ms);
  1163. // This hackery is required for IE8
  1164. // where `console.log` doesn't have 'apply'
  1165. window.console
  1166. && console.log
  1167. && Function.prototype.apply.call(console.log, console, arguments);
  1168. }
  1169. }
  1170. /**
  1171. * The currently active debug mode names.
  1172. */
  1173. debug.names = [];
  1174. debug.skips = [];
  1175. /**
  1176. * Enables a debug mode by name. This can include modes
  1177. * separated by a colon and wildcards.
  1178. *
  1179. * @param {String} name
  1180. * @api public
  1181. */
  1182. debug.enable = function(name) {
  1183. try {
  1184. localStorage.debug = name;
  1185. } catch(e){}
  1186. var split = (name || '').split(/[\s,]+/)
  1187. , len = split.length;
  1188. for (var i = 0; i < len; i++) {
  1189. name = split[i].replace('*', '.*?');
  1190. if (name[0] === '-') {
  1191. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  1192. }
  1193. else {
  1194. debug.names.push(new RegExp('^' + name + '$'));
  1195. }
  1196. }
  1197. };
  1198. /**
  1199. * Disable debug output.
  1200. *
  1201. * @api public
  1202. */
  1203. debug.disable = function(){
  1204. debug.enable('');
  1205. };
  1206. /**
  1207. * Humanize the given `ms`.
  1208. *
  1209. * @param {Number} m
  1210. * @return {String}
  1211. * @api private
  1212. */
  1213. debug.humanize = function(ms) {
  1214. var sec = 1000
  1215. , min = 60 * 1000
  1216. , hour = 60 * min;
  1217. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  1218. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  1219. if (ms >= sec) return (ms / sec | 0) + 's';
  1220. return ms + 'ms';
  1221. };
  1222. /**
  1223. * Returns true if the given mode name is enabled, false otherwise.
  1224. *
  1225. * @param {String} name
  1226. * @return {Boolean}
  1227. * @api public
  1228. */
  1229. debug.enabled = function(name) {
  1230. for (var i = 0, len = debug.skips.length; i < len; i++) {
  1231. if (debug.skips[i].test(name)) {
  1232. return false;
  1233. }
  1234. }
  1235. for (var i = 0, len = debug.names.length; i < len; i++) {
  1236. if (debug.names[i].test(name)) {
  1237. return true;
  1238. }
  1239. }
  1240. return false;
  1241. };
  1242. /**
  1243. * Coerce `val`.
  1244. */
  1245. function coerce(val) {
  1246. if (val instanceof Error) return val.stack || val.message;
  1247. return val;
  1248. }
  1249. // persist
  1250. try {
  1251. if (window.localStorage) debug.enable(localStorage.debug);
  1252. } catch(e){}
  1253. },{}],11:[function(_dereq_,module,exports){
  1254. module.exports = _dereq_('./lib/');
  1255. },{"./lib/":12}],12:[function(_dereq_,module,exports){
  1256. module.exports = _dereq_('./socket');
  1257. /**
  1258. * Exports parser
  1259. *
  1260. * @api public
  1261. *
  1262. */
  1263. module.exports.parser = _dereq_('engine.io-parser');
  1264. },{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){
  1265. (function (global){
  1266. /**
  1267. * Module dependencies.
  1268. */
  1269. var transports = _dereq_('./transports');
  1270. var Emitter = _dereq_('component-emitter');
  1271. var debug = _dereq_('debug')('engine.io-client:socket');
  1272. var index = _dereq_('indexof');
  1273. var parser = _dereq_('engine.io-parser');
  1274. var parseuri = _dereq_('parseuri');
  1275. var parsejson = _dereq_('parsejson');
  1276. var parseqs = _dereq_('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) {
  1314. opts.port = pieces.pop();
  1315. } else if (!opts.port) {
  1316. // if no port is specified manually, use the protocol default
  1317. opts.port = this.secure ? '443' : '80';
  1318. }
  1319. }
  1320. this.agent = opts.agent || false;
  1321. this.hostname = opts.hostname ||
  1322. (global.location ? location.hostname : 'localhost');
  1323. this.port = opts.port || (global.location && location.port ?
  1324. location.port :
  1325. (this.secure ? 443 : 80));
  1326. this.query = opts.query || {};
  1327. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  1328. this.upgrade = false !== opts.upgrade;
  1329. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  1330. this.forceJSONP = !!opts.forceJSONP;
  1331. this.jsonp = false !== opts.jsonp;
  1332. this.forceBase64 = !!opts.forceBase64;
  1333. this.enablesXDR = !!opts.enablesXDR;
  1334. this.timestampParam = opts.timestampParam || 't';
  1335. this.timestampRequests = opts.timestampRequests;
  1336. this.transports = opts.transports || ['polling', 'websocket'];
  1337. this.readyState = '';
  1338. this.writeBuffer = [];
  1339. this.callbackBuffer = [];
  1340. this.policyPort = opts.policyPort || 843;
  1341. this.rememberUpgrade = opts.rememberUpgrade || false;
  1342. this.binaryType = null;
  1343. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  1344. // SSL options for Node.js client
  1345. this.pfx = opts.pfx || null;
  1346. this.key = opts.key || null;
  1347. this.passphrase = opts.passphrase || null;
  1348. this.cert = opts.cert || null;
  1349. this.ca = opts.ca || null;
  1350. this.ciphers = opts.ciphers || null;
  1351. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  1352. this.open();
  1353. }
  1354. Socket.priorWebsocketSuccess = false;
  1355. /**
  1356. * Mix in `Emitter`.
  1357. */
  1358. Emitter(Socket.prototype);
  1359. /**
  1360. * Protocol version.
  1361. *
  1362. * @api public
  1363. */
  1364. Socket.protocol = parser.protocol; // this is an int
  1365. /**
  1366. * Expose deps for legacy compatibility
  1367. * and standalone browser access.
  1368. */
  1369. Socket.Socket = Socket;
  1370. Socket.Transport = _dereq_('./transport');
  1371. Socket.transports = _dereq_('./transports');
  1372. Socket.parser = _dereq_('engine.io-parser');
  1373. /**
  1374. * Creates transport of the given type.
  1375. *
  1376. * @param {String} transport name
  1377. * @return {Transport}
  1378. * @api private
  1379. */
  1380. Socket.prototype.createTransport = function (name) {
  1381. debug('creating transport "%s"', name);
  1382. var query = clone(this.query);
  1383. // append engine.io protocol identifier
  1384. query.EIO = parser.protocol;
  1385. // transport name
  1386. query.transport = name;
  1387. // session id if we already have one
  1388. if (this.id) query.sid = this.id;
  1389. var transport = new transports[name]({
  1390. agent: this.agent,
  1391. hostname: this.hostname,
  1392. port: this.port,
  1393. secure: this.secure,
  1394. path: this.path,
  1395. query: query,
  1396. forceJSONP: this.forceJSONP,
  1397. jsonp: this.jsonp,
  1398. forceBase64: this.forceBase64,
  1399. enablesXDR: this.enablesXDR,
  1400. timestampRequests: this.timestampRequests,
  1401. timestampParam: this.timestampParam,
  1402. policyPort: this.policyPort,
  1403. socket: this,
  1404. pfx: this.pfx,
  1405. key: this.key,
  1406. passphrase: this.passphrase,
  1407. cert: this.cert,
  1408. ca: this.ca,
  1409. ciphers: this.ciphers,
  1410. rejectUnauthorized: this.rejectUnauthorized
  1411. });
  1412. return transport;
  1413. };
  1414. function clone (obj) {
  1415. var o = {};
  1416. for (var i in obj) {
  1417. if (obj.hasOwnProperty(i)) {
  1418. o[i] = obj[i];
  1419. }
  1420. }
  1421. return o;
  1422. }
  1423. /**
  1424. * Initializes transport to use and starts probe.
  1425. *
  1426. * @api private
  1427. */
  1428. Socket.prototype.open = function () {
  1429. var transport;
  1430. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  1431. transport = 'websocket';
  1432. } else if (0 == this.transports.length) {
  1433. // Emit error on next tick so it can be listened to
  1434. var self = this;
  1435. setTimeout(function() {
  1436. self.emit('error', 'No transports available');
  1437. }, 0);
  1438. return;
  1439. } else {
  1440. transport = this.transports[0];
  1441. }
  1442. this.readyState = 'opening';
  1443. // Retry with the next transport if the transport is disabled (jsonp: false)
  1444. var transport;
  1445. try {
  1446. transport = this.createTransport(transport);
  1447. } catch (e) {
  1448. this.transports.shift();
  1449. this.open();
  1450. return;
  1451. }
  1452. transport.open();
  1453. this.setTransport(transport);
  1454. };
  1455. /**
  1456. * Sets the current transport. Disables the existing one (if any).
  1457. *
  1458. * @api private
  1459. */
  1460. Socket.prototype.setTransport = function(transport){
  1461. debug('setting transport %s', transport.name);
  1462. var self = this;
  1463. if (this.transport) {
  1464. debug('clearing existing transport %s', this.transport.name);
  1465. this.transport.removeAllListeners();
  1466. }
  1467. // set up transport
  1468. this.transport = transport;
  1469. // set up transport listeners
  1470. transport
  1471. .on('drain', function(){
  1472. self.onDrain();
  1473. })
  1474. .on('packet', function(packet){
  1475. self.onPacket(packet);
  1476. })
  1477. .on('error', function(e){
  1478. self.onError(e);
  1479. })
  1480. .on('close', function(){
  1481. self.onClose('transport close');
  1482. });
  1483. };
  1484. /**
  1485. * Probes a transport.
  1486. *
  1487. * @param {String} transport name
  1488. * @api private
  1489. */
  1490. Socket.prototype.probe = function (name) {
  1491. debug('probing transport "%s"', name);
  1492. var transport = this.createTransport(name, { probe: 1 })
  1493. , failed = false
  1494. , self = this;
  1495. Socket.priorWebsocketSuccess = false;
  1496. function onTransportOpen(){
  1497. if (self.onlyBinaryUpgrades) {
  1498. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  1499. failed = failed || upgradeLosesBinary;
  1500. }
  1501. if (failed) return;
  1502. debug('probe transport "%s" opened', name);
  1503. transport.send([{ type: 'ping', data: 'probe' }]);
  1504. transport.once('packet', function (msg) {
  1505. if (failed) return;
  1506. if ('pong' == msg.type && 'probe' == msg.data) {
  1507. debug('probe transport "%s" pong', name);
  1508. self.upgrading = true;
  1509. self.emit('upgrading', transport);
  1510. if (!transport) return;
  1511. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  1512. debug('pausing current transport "%s"', self.transport.name);
  1513. self.transport.pause(function () {
  1514. if (failed) return;
  1515. if ('closed' == self.readyState) return;
  1516. debug('changing transport and sending upgrade packet');
  1517. cleanup();
  1518. self.setTransport(transport);
  1519. transport.send([{ type: 'upgrade' }]);
  1520. self.emit('upgrade', transport);
  1521. transport = null;
  1522. self.upgrading = false;
  1523. self.flush();
  1524. });
  1525. } else {
  1526. debug('probe transport "%s" failed', name);
  1527. var err = new Error('probe error');
  1528. err.transport = transport.name;
  1529. self.emit('upgradeError', err);
  1530. }
  1531. });
  1532. }
  1533. function freezeTransport() {
  1534. if (failed) return;
  1535. // Any callback called by transport should be ignored since now
  1536. failed = true;
  1537. cleanup();
  1538. transport.close();
  1539. transport = null;
  1540. }
  1541. //Handle any error that happens while probing
  1542. function onerror(err) {
  1543. var error = new Error('probe error: ' + err);
  1544. error.transport = transport.name;
  1545. freezeTransport();
  1546. debug('probe transport "%s" failed because of error: %s', name, err);
  1547. self.emit('upgradeError', error);
  1548. }
  1549. function onTransportClose(){
  1550. onerror("transport closed");
  1551. }
  1552. //When the socket is closed while we're probing
  1553. function onclose(){
  1554. onerror("socket closed");
  1555. }
  1556. //When the socket is upgraded while we're probing
  1557. function onupgrade(to){
  1558. if (transport && to.name != transport.name) {
  1559. debug('"%s" works - aborting "%s"', to.name, transport.name);
  1560. freezeTransport();
  1561. }
  1562. }
  1563. //Remove all listeners on the transport and on self
  1564. function cleanup(){
  1565. transport.removeListener('open', onTransportOpen);
  1566. transport.removeListener('error', onerror);
  1567. transport.removeListener('close', onTransportClose);
  1568. self.removeListener('close', onclose);
  1569. self.removeListener('upgrading', onupgrade);
  1570. }
  1571. transport.once('open', onTransportOpen);
  1572. transport.once('error', onerror);
  1573. transport.once('close', onTransportClose);
  1574. this.once('close', onclose);
  1575. this.once('upgrading', onupgrade);
  1576. transport.open();
  1577. };
  1578. /**
  1579. * Called when connection is deemed open.
  1580. *
  1581. * @api public
  1582. */
  1583. Socket.prototype.onOpen = function () {
  1584. debug('socket open');
  1585. this.readyState = 'open';
  1586. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  1587. this.emit('open');
  1588. this.flush();
  1589. // we check for `readyState` in case an `open`
  1590. // listener already closed the socket
  1591. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  1592. debug('starting upgrade probes');
  1593. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  1594. this.probe(this.upgrades[i]);
  1595. }
  1596. }
  1597. };
  1598. /**
  1599. * Handles a packet.
  1600. *
  1601. * @api private
  1602. */
  1603. Socket.prototype.onPacket = function (packet) {
  1604. if ('opening' == this.readyState || 'open' == this.readyState) {
  1605. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  1606. this.emit('packet', packet);
  1607. // Socket is live - any packet counts
  1608. this.emit('heartbeat');
  1609. switch (packet.type) {
  1610. case 'open':
  1611. this.onHandshake(parsejson(packet.data));
  1612. break;
  1613. case 'pong':
  1614. this.setPing();
  1615. break;
  1616. case 'error':
  1617. var err = new Error('server error');
  1618. err.code = packet.data;
  1619. this.emit('error', err);
  1620. break;
  1621. case 'message':
  1622. this.emit('data', packet.data);
  1623. this.emit('message', packet.data);
  1624. break;
  1625. }
  1626. } else {
  1627. debug('packet received with socket readyState "%s"', this.readyState);
  1628. }
  1629. };
  1630. /**
  1631. * Called upon handshake completion.
  1632. *
  1633. * @param {Object} handshake obj
  1634. * @api private
  1635. */
  1636. Socket.prototype.onHandshake = function (data) {
  1637. this.emit('handshake', data);
  1638. this.id = data.sid;
  1639. this.transport.query.sid = data.sid;
  1640. this.upgrades = this.filterUpgrades(data.upgrades);
  1641. this.pingInterval = data.pingInterval;
  1642. this.pingTimeout = data.pingTimeout;
  1643. this.onOpen();
  1644. // In case open handler closes socket
  1645. if ('closed' == this.readyState) return;
  1646. this.setPing();
  1647. // Prolong liveness of socket on heartbeat
  1648. this.removeListener('heartbeat', this.onHeartbeat);
  1649. this.on('heartbeat', this.onHeartbeat);
  1650. };
  1651. /**
  1652. * Resets ping timeout.
  1653. *
  1654. * @api private
  1655. */
  1656. Socket.prototype.onHeartbeat = function (timeout) {
  1657. clearTimeout(this.pingTimeoutTimer);
  1658. var self = this;
  1659. self.pingTimeoutTimer = setTimeout(function () {
  1660. if ('closed' == self.readyState) return;
  1661. self.onClose('ping timeout');
  1662. }, timeout || (self.pingInterval + self.pingTimeout));
  1663. };
  1664. /**
  1665. * Pings server every `this.pingInterval` and expects response
  1666. * within `this.pingTimeout` or closes connection.
  1667. *
  1668. * @api private
  1669. */
  1670. Socket.prototype.setPing = function () {
  1671. var self = this;
  1672. clearTimeout(self.pingIntervalTimer);
  1673. self.pingIntervalTimer = setTimeout(function () {
  1674. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  1675. self.ping();
  1676. self.onHeartbeat(self.pingTimeout);
  1677. }, self.pingInterval);
  1678. };
  1679. /**
  1680. * Sends a ping packet.
  1681. *
  1682. * @api public
  1683. */
  1684. Socket.prototype.ping = function () {
  1685. this.sendPacket('ping');
  1686. };
  1687. /**
  1688. * Called on `drain` event
  1689. *
  1690. * @api private
  1691. */
  1692. Socket.prototype.onDrain = function() {
  1693. for (var i = 0; i < this.prevBufferLen; i++) {
  1694. if (this.callbackBuffer[i]) {
  1695. this.callbackBuffer[i]();
  1696. }
  1697. }
  1698. this.writeBuffer.splice(0, this.prevBufferLen);
  1699. this.callbackBuffer.splice(0, this.prevBufferLen);
  1700. // setting prevBufferLen = 0 is very important
  1701. // for example, when upgrading, upgrade packet is sent over,
  1702. // and a nonzero prevBufferLen could cause problems on `drain`
  1703. this.prevBufferLen = 0;
  1704. if (this.writeBuffer.length == 0) {
  1705. this.emit('drain');
  1706. } else {
  1707. this.flush();
  1708. }
  1709. };
  1710. /**
  1711. * Flush write buffers.
  1712. *
  1713. * @api private
  1714. */
  1715. Socket.prototype.flush = function () {
  1716. if ('closed' != this.readyState && this.transport.writable &&
  1717. !this.upgrading && this.writeBuffer.length) {
  1718. debug('flushing %d packets in socket', this.writeBuffer.length);
  1719. this.transport.send(this.writeBuffer);
  1720. // keep track of current length of writeBuffer
  1721. // splice writeBuffer and callbackBuffer on `drain`
  1722. this.prevBufferLen = this.writeBuffer.length;
  1723. this.emit('flush');
  1724. }
  1725. };
  1726. /**
  1727. * Sends a message.
  1728. *
  1729. * @param {String} message.
  1730. * @param {Function} callback function.
  1731. * @return {Socket} for chaining.
  1732. * @api public
  1733. */
  1734. Socket.prototype.write =
  1735. Socket.prototype.send = function (msg, fn) {
  1736. this.sendPacket('message', msg, fn);
  1737. return this;
  1738. };
  1739. /**
  1740. * Sends a packet.
  1741. *
  1742. * @param {String} packet type.
  1743. * @param {String} data.
  1744. * @param {Function} callback function.
  1745. * @api private
  1746. */
  1747. Socket.prototype.sendPacket = function (type, data, fn) {
  1748. if ('closing' == this.readyState || 'closed' == this.readyState) {
  1749. return;
  1750. }
  1751. var packet = { type: type, data: data };
  1752. this.emit('packetCreate', packet);
  1753. this.writeBuffer.push(packet);
  1754. this.callbackBuffer.push(fn);
  1755. this.flush();
  1756. };
  1757. /**
  1758. * Closes the connection.
  1759. *
  1760. * @api private
  1761. */
  1762. Socket.prototype.close = function () {
  1763. if ('opening' == this.readyState || 'open' == this.readyState) {
  1764. this.readyState = 'closing';
  1765. var self = this;
  1766. function close() {
  1767. self.onClose('forced close');
  1768. debug('socket closing - telling transport to close');
  1769. self.transport.close();
  1770. }
  1771. function cleanupAndClose() {
  1772. self.removeListener('upgrade', cleanupAndClose);
  1773. self.removeListener('upgradeError', cleanupAndClose);
  1774. close();
  1775. }
  1776. function waitForUpgrade() {
  1777. // wait for upgrade to finish since we can't send packets while pausing a transport
  1778. self.once('upgrade', cleanupAndClose);
  1779. self.once('upgradeError', cleanupAndClose);
  1780. }
  1781. if (this.writeBuffer.length) {
  1782. this.once('drain', function() {
  1783. if (this.upgrading) {
  1784. waitForUpgrade();
  1785. } else {
  1786. close();
  1787. }
  1788. });
  1789. } else if (this.upgrading) {
  1790. waitForUpgrade();
  1791. } else {
  1792. close();
  1793. }
  1794. }
  1795. return this;
  1796. };
  1797. /**
  1798. * Called upon transport error
  1799. *
  1800. * @api private
  1801. */
  1802. Socket.prototype.onError = function (err) {
  1803. debug('socket error %j', err);
  1804. Socket.priorWebsocketSuccess = false;
  1805. this.emit('error', err);
  1806. this.onClose('transport error', err);
  1807. };
  1808. /**
  1809. * Called upon transport close.
  1810. *
  1811. * @api private
  1812. */
  1813. Socket.prototype.onClose = function (reason, desc) {
  1814. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  1815. debug('socket close with reason: "%s"', reason);
  1816. var self = this;
  1817. // clear timers
  1818. clearTimeout(this.pingIntervalTimer);
  1819. clearTimeout(this.pingTimeoutTimer);
  1820. // clean buffers in next tick, so developers can still
  1821. // grab the buffers on `close` event
  1822. setTimeout(function() {
  1823. self.writeBuffer = [];
  1824. self.callbackBuffer = [];
  1825. self.prevBufferLen = 0;
  1826. }, 0);
  1827. // stop event from firing again for transport
  1828. this.transport.removeAllListeners('close');
  1829. // ensure transport won't stay open
  1830. this.transport.close();
  1831. // ignore further transport communication
  1832. this.transport.removeAllListeners();
  1833. // set ready state
  1834. this.readyState = 'closed';
  1835. // clear session id
  1836. this.id = null;
  1837. // emit close event
  1838. this.emit('close', reason, desc);
  1839. }
  1840. };
  1841. /**
  1842. * Filters upgrades, returning only those matching client transports.
  1843. *
  1844. * @param {Array} server upgrades
  1845. * @api private
  1846. *
  1847. */
  1848. Socket.prototype.filterUpgrades = function (upgrades) {
  1849. var filteredUpgrades = [];
  1850. for (var i = 0, j = upgrades.length; i<j; i++) {
  1851. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1852. }
  1853. return filteredUpgrades;
  1854. };
  1855. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1856. },{"./transport":14,"./transports":15,"component-emitter":9,"debug":22,"engine.io-parser":25,"indexof":42,"parsejson":34,"parseqs":35,"parseuri":36}],14:[function(_dereq_,module,exports){
  1857. /**
  1858. * Module dependencies.
  1859. */
  1860. var parser = _dereq_('engine.io-parser');
  1861. var Emitter = _dereq_('component-emitter');
  1862. /**
  1863. * Module exports.
  1864. */
  1865. module.exports = Transport;
  1866. /**
  1867. * Transport abstract constructor.
  1868. *
  1869. * @param {Object} options.
  1870. * @api private
  1871. */
  1872. function Transport (opts) {
  1873. this.path = opts.path;
  1874. this.hostname = opts.hostname;
  1875. this.port = opts.port;
  1876. this.secure = opts.secure;
  1877. this.query = opts.query;
  1878. this.timestampParam = opts.timestampParam;
  1879. this.timestampRequests = opts.timestampRequests;
  1880. this.readyState = '';
  1881. this.agent = opts.agent || false;
  1882. this.socket = opts.socket;
  1883. this.enablesXDR = opts.enablesXDR;
  1884. // SSL options for Node.js client
  1885. this.pfx = opts.pfx;
  1886. this.key = opts.key;
  1887. this.passphrase = opts.passphrase;
  1888. this.cert = opts.cert;
  1889. this.ca = opts.ca;
  1890. this.ciphers = opts.ciphers;
  1891. this.rejectUnauthorized = opts.rejectUnauthorized;
  1892. }
  1893. /**
  1894. * Mix in `Emitter`.
  1895. */
  1896. Emitter(Transport.prototype);
  1897. /**
  1898. * A counter used to prevent collisions in the timestamps used
  1899. * for cache busting.
  1900. */
  1901. Transport.timestamps = 0;
  1902. /**
  1903. * Emits an error.
  1904. *
  1905. * @param {String} str
  1906. * @return {Transport} for chaining
  1907. * @api public
  1908. */
  1909. Transport.prototype.onError = function (msg, desc) {
  1910. var err = new Error(msg);
  1911. err.type = 'TransportError';
  1912. err.description = desc;
  1913. this.emit('error', err);
  1914. return this;
  1915. };
  1916. /**
  1917. * Opens the transport.
  1918. *
  1919. * @api public
  1920. */
  1921. Transport.prototype.open = function () {
  1922. if ('closed' == this.readyState || '' == this.readyState) {
  1923. this.readyState = 'opening';
  1924. this.doOpen();
  1925. }
  1926. return this;
  1927. };
  1928. /**
  1929. * Closes the transport.
  1930. *
  1931. * @api private
  1932. */
  1933. Transport.prototype.close = function () {
  1934. if ('opening' == this.readyState || 'open' == this.readyState) {
  1935. this.doClose();
  1936. this.onClose();
  1937. }
  1938. return this;
  1939. };
  1940. /**
  1941. * Sends multiple packets.
  1942. *
  1943. * @param {Array} packets
  1944. * @api private
  1945. */
  1946. Transport.prototype.send = function(packets){
  1947. if ('open' == this.readyState) {
  1948. this.write(packets);
  1949. } else {
  1950. throw new Error('Transport not open');
  1951. }
  1952. };
  1953. /**
  1954. * Called upon open
  1955. *
  1956. * @api private
  1957. */
  1958. Transport.prototype.onOpen = function () {
  1959. this.readyState = 'open';
  1960. this.writable = true;
  1961. this.emit('open');
  1962. };
  1963. /**
  1964. * Called with data.
  1965. *
  1966. * @param {String} data
  1967. * @api private
  1968. */
  1969. Transport.prototype.onData = function(data){
  1970. var packet = parser.decodePacket(data, this.socket.binaryType);
  1971. this.onPacket(packet);
  1972. };
  1973. /**
  1974. * Called with a decoded packet.
  1975. */
  1976. Transport.prototype.onPacket = function (packet) {
  1977. this.emit('packet', packet);
  1978. };
  1979. /**
  1980. * Called upon close.
  1981. *
  1982. * @api private
  1983. */
  1984. Transport.prototype.onClose = function () {
  1985. this.readyState = 'closed';
  1986. this.emit('close');
  1987. };
  1988. },{"component-emitter":9,"engine.io-parser":25}],15:[function(_dereq_,module,exports){
  1989. (function (global){
  1990. /**
  1991. * Module dependencies
  1992. */
  1993. var XMLHttpRequest = _dereq_('xmlhttprequest');
  1994. var XHR = _dereq_('./polling-xhr');
  1995. var JSONP = _dereq_('./polling-jsonp');
  1996. var websocket = _dereq_('./websocket');
  1997. /**
  1998. * Export transports.
  1999. */
  2000. exports.polling = polling;
  2001. exports.websocket = websocket;
  2002. /**
  2003. * Polling transport polymorphic constructor.
  2004. * Decides on xhr vs jsonp based on feature detection.
  2005. *
  2006. * @api private
  2007. */
  2008. function polling(opts){
  2009. var xhr;
  2010. var xd = false;
  2011. var xs = false;
  2012. var jsonp = false !== opts.jsonp;
  2013. if (global.location) {
  2014. var isSSL = 'https:' == location.protocol;
  2015. var port = location.port;
  2016. // some user agents have empty `location.port`
  2017. if (!port) {
  2018. port = isSSL ? 443 : 80;
  2019. }
  2020. xd = opts.hostname != location.hostname || port != opts.port;
  2021. xs = opts.secure != isSSL;
  2022. }
  2023. opts.xdomain = xd;
  2024. opts.xscheme = xs;
  2025. xhr = new XMLHttpRequest(opts);
  2026. if ('open' in xhr && !opts.forceJSONP) {
  2027. return new XHR(opts);
  2028. } else {
  2029. if (!jsonp) throw new Error('JSONP disabled');
  2030. return new JSONP(opts);
  2031. }
  2032. }
  2033. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2034. },{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,"xmlhttprequest":20}],16:[function(_dereq_,module,exports){
  2035. (function (global){
  2036. /**
  2037. * Module requirements.
  2038. */
  2039. var Polling = _dereq_('./polling');
  2040. var inherit = _dereq_('component-inherit');
  2041. /**
  2042. * Module exports.
  2043. */
  2044. module.exports = JSONPPolling;
  2045. /**
  2046. * Cached regular expressions.
  2047. */
  2048. var rNewline = /\n/g;
  2049. var rEscapedNewline = /\\n/g;
  2050. /**
  2051. * Global JSONP callbacks.
  2052. */
  2053. var callbacks;
  2054. /**
  2055. * Callbacks count.
  2056. */
  2057. var index = 0;
  2058. /**
  2059. * Noop.
  2060. */
  2061. function empty () { }
  2062. /**
  2063. * JSONP Polling constructor.
  2064. *
  2065. * @param {Object} opts.
  2066. * @api public
  2067. */
  2068. function JSONPPolling (opts) {
  2069. Polling.call(this, opts);
  2070. this.query = this.query || {};
  2071. // define global callbacks array if not present
  2072. // we do this here (lazily) to avoid unneeded global pollution
  2073. if (!callbacks) {
  2074. // we need to consider multiple engines in the same page
  2075. if (!global.___eio) global.___eio = [];
  2076. callbacks = global.___eio;
  2077. }
  2078. // callback identifier
  2079. this.index = callbacks.length;
  2080. // add callback to jsonp global
  2081. var self = this;
  2082. callbacks.push(function (msg) {
  2083. self.onData(msg);
  2084. });
  2085. // append to query string
  2086. this.query.j = this.index;
  2087. // prevent spurious errors from being emitted when the window is unloaded
  2088. if (global.document && global.addEventListener) {
  2089. global.addEventListener('beforeunload', function () {
  2090. if (self.script) self.script.onerror = empty;
  2091. }, false);
  2092. }
  2093. }
  2094. /**
  2095. * Inherits from Polling.
  2096. */
  2097. inherit(JSONPPolling, Polling);
  2098. /*
  2099. * JSONP only supports binary as base64 encoded strings
  2100. */
  2101. JSONPPolling.prototype.supportsBinary = false;
  2102. /**
  2103. * Closes the socket.
  2104. *
  2105. * @api private
  2106. */
  2107. JSONPPolling.prototype.doClose = function () {
  2108. if (this.script) {
  2109. this.script.parentNode.removeChild(this.script);
  2110. this.script = null;
  2111. }
  2112. if (this.form) {
  2113. this.form.parentNode.removeChild(this.form);
  2114. this.form = null;
  2115. this.iframe = null;
  2116. }
  2117. Polling.prototype.doClose.call(this);
  2118. };
  2119. /**
  2120. * Starts a poll cycle.
  2121. *
  2122. * @api private
  2123. */
  2124. JSONPPolling.prototype.doPoll = function () {
  2125. var self = this;
  2126. var script = document.createElement('script');
  2127. if (this.script) {
  2128. this.script.parentNode.removeChild(this.script);
  2129. this.script = null;
  2130. }
  2131. script.async = true;
  2132. script.src = this.uri();
  2133. script.onerror = function(e){
  2134. self.onError('jsonp poll error',e);
  2135. };
  2136. var insertAt = document.getElementsByTagName('script')[0];
  2137. insertAt.parentNode.insertBefore(script, insertAt);
  2138. this.script = script;
  2139. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  2140. if (isUAgecko) {
  2141. setTimeout(function () {
  2142. var iframe = document.createElement('iframe');
  2143. document.body.appendChild(iframe);
  2144. document.body.removeChild(iframe);
  2145. }, 100);
  2146. }
  2147. };
  2148. /**
  2149. * Writes with a hidden iframe.
  2150. *
  2151. * @param {String} data to send
  2152. * @param {Function} called upon flush.
  2153. * @api private
  2154. */
  2155. JSONPPolling.prototype.doWrite = function (data, fn) {
  2156. var self = this;
  2157. if (!this.form) {
  2158. var form = document.createElement('form');
  2159. var area = document.createElement('textarea');
  2160. var id = this.iframeId = 'eio_iframe_' + this.index;
  2161. var iframe;
  2162. form.className = 'socketio';
  2163. form.style.position = 'absolute';
  2164. form.style.top = '-1000px';
  2165. form.style.left = '-1000px';
  2166. form.target = id;
  2167. form.method = 'POST';
  2168. form.setAttribute('accept-charset', 'utf-8');
  2169. area.name = 'd';
  2170. form.appendChild(area);
  2171. document.body.appendChild(form);
  2172. this.form = form;
  2173. this.area = area;
  2174. }
  2175. this.form.action = this.uri();
  2176. function complete () {
  2177. initIframe();
  2178. fn();
  2179. }
  2180. function initIframe () {
  2181. if (self.iframe) {
  2182. try {
  2183. self.form.removeChild(self.iframe);
  2184. } catch (e) {
  2185. self.onError('jsonp polling iframe removal error', e);
  2186. }
  2187. }
  2188. try {
  2189. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2190. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  2191. iframe = document.createElement(html);
  2192. } catch (e) {
  2193. iframe = document.createElement('iframe');
  2194. iframe.name = self.iframeId;
  2195. iframe.src = 'javascript:0';
  2196. }
  2197. iframe.id = self.iframeId;
  2198. self.form.appendChild(iframe);
  2199. self.iframe = iframe;
  2200. }
  2201. initIframe();
  2202. // escape \n to prevent it from being converted into \r\n by some UAs
  2203. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  2204. data = data.replace(rEscapedNewline, '\\\n');
  2205. this.area.value = data.replace(rNewline, '\\n');
  2206. try {
  2207. this.form.submit();
  2208. } catch(e) {}
  2209. if (this.iframe.attachEvent) {
  2210. this.iframe.onreadystatechange = function(){
  2211. if (self.iframe.readyState == 'complete') {
  2212. complete();
  2213. }
  2214. };
  2215. } else {
  2216. this.iframe.onload = complete;
  2217. }
  2218. };
  2219. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2220. },{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){
  2221. (function (global){
  2222. /**
  2223. * Module requirements.
  2224. */
  2225. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2226. var Polling = _dereq_('./polling');
  2227. var Emitter = _dereq_('component-emitter');
  2228. var inherit = _dereq_('component-inherit');
  2229. var debug = _dereq_('debug')('engine.io-client:polling-xhr');
  2230. /**
  2231. * Module exports.
  2232. */
  2233. module.exports = XHR;
  2234. module.exports.Request = Request;
  2235. /**
  2236. * Empty function
  2237. */
  2238. function empty(){}
  2239. /**
  2240. * XHR Polling constructor.
  2241. *
  2242. * @param {Object} opts
  2243. * @api public
  2244. */
  2245. function XHR(opts){
  2246. Polling.call(this, opts);
  2247. if (global.location) {
  2248. var isSSL = 'https:' == location.protocol;
  2249. var port = location.port;
  2250. // some user agents have empty `location.port`
  2251. if (!port) {
  2252. port = isSSL ? 443 : 80;
  2253. }
  2254. this.xd = opts.hostname != global.location.hostname ||
  2255. port != opts.port;
  2256. this.xs = opts.secure != isSSL;
  2257. }
  2258. }
  2259. /**
  2260. * Inherits from Polling.
  2261. */
  2262. inherit(XHR, Polling);
  2263. /**
  2264. * XHR supports binary
  2265. */
  2266. XHR.prototype.supportsBinary = true;
  2267. /**
  2268. * Creates a request.
  2269. *
  2270. * @param {String} method
  2271. * @api private
  2272. */
  2273. XHR.prototype.request = function(opts){
  2274. opts = opts || {};
  2275. opts.uri = this.uri();
  2276. opts.xd = this.xd;
  2277. opts.xs = this.xs;
  2278. opts.agent = this.agent || false;
  2279. opts.supportsBinary = this.supportsBinary;
  2280. opts.enablesXDR = this.enablesXDR;
  2281. // SSL options for Node.js client
  2282. opts.pfx = this.pfx;
  2283. opts.key = this.key;
  2284. opts.passphrase = this.passphrase;
  2285. opts.cert = this.cert;
  2286. opts.ca = this.ca;
  2287. opts.ciphers = this.ciphers;
  2288. opts.rejectUnauthorized = this.rejectUnauthorized;
  2289. return new Request(opts);
  2290. };
  2291. /**
  2292. * Sends data.
  2293. *
  2294. * @param {String} data to send.
  2295. * @param {Function} called upon flush.
  2296. * @api private
  2297. */
  2298. XHR.prototype.doWrite = function(data, fn){
  2299. var isBinary = typeof data !== 'string' && data !== undefined;
  2300. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  2301. var self = this;
  2302. req.on('success', fn);
  2303. req.on('error', function(err){
  2304. self.onError('xhr post error', err);
  2305. });
  2306. this.sendXhr = req;
  2307. };
  2308. /**
  2309. * Starts a poll cycle.
  2310. *
  2311. * @api private
  2312. */
  2313. XHR.prototype.doPoll = function(){
  2314. debug('xhr poll');
  2315. var req = this.request();
  2316. var self = this;
  2317. req.on('data', function(data){
  2318. self.onData(data);
  2319. });
  2320. req.on('error', function(err){
  2321. self.onError('xhr poll error', err);
  2322. });
  2323. this.pollXhr = req;
  2324. };
  2325. /**
  2326. * Request constructor
  2327. *
  2328. * @param {Object} options
  2329. * @api public
  2330. */
  2331. function Request(opts){
  2332. this.method = opts.method || 'GET';
  2333. this.uri = opts.uri;
  2334. this.xd = !!opts.xd;
  2335. this.xs = !!opts.xs;
  2336. this.async = false !== opts.async;
  2337. this.data = undefined != opts.data ? opts.data : null;
  2338. this.agent = opts.agent;
  2339. this.isBinary = opts.isBinary;
  2340. this.supportsBinary = opts.supportsBinary;
  2341. this.enablesXDR = opts.enablesXDR;
  2342. // SSL options for Node.js client
  2343. this.pfx = opts.pfx;
  2344. this.key = opts.key;
  2345. this.passphrase = opts.passphrase;
  2346. this.cert = opts.cert;
  2347. this.ca = opts.ca;
  2348. this.ciphers = opts.ciphers;
  2349. this.rejectUnauthorized = opts.rejectUnauthorized;
  2350. this.create();
  2351. }
  2352. /**
  2353. * Mix in `Emitter`.
  2354. */
  2355. Emitter(Request.prototype);
  2356. /**
  2357. * Creates the XHR object and sends the request.
  2358. *
  2359. * @api private
  2360. */
  2361. Request.prototype.create = function(){
  2362. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  2363. // SSL options for Node.js client
  2364. opts.pfx = this.pfx;
  2365. opts.key = this.key;
  2366. opts.passphrase = this.passphrase;
  2367. opts.cert = this.cert;
  2368. opts.ca = this.ca;
  2369. opts.ciphers = this.ciphers;
  2370. opts.rejectUnauthorized = this.rejectUnauthorized;
  2371. var xhr = this.xhr = new XMLHttpRequest(opts);
  2372. var self = this;
  2373. try {
  2374. debug('xhr open %s: %s', this.method, this.uri);
  2375. xhr.open(this.method, this.uri, this.async);
  2376. if (this.supportsBinary) {
  2377. // This has to be done after open because Firefox is stupid
  2378. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  2379. xhr.responseType = 'arraybuffer';
  2380. }
  2381. if ('POST' == this.method) {
  2382. try {
  2383. if (this.isBinary) {
  2384. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  2385. } else {
  2386. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  2387. }
  2388. } catch (e) {}
  2389. }
  2390. // ie6 check
  2391. if ('withCredentials' in xhr) {
  2392. xhr.withCredentials = true;
  2393. }
  2394. if (this.hasXDR()) {
  2395. xhr.onload = function(){
  2396. self.onLoad();
  2397. };
  2398. xhr.onerror = function(){
  2399. self.onError(xhr.responseText);
  2400. };
  2401. } else {
  2402. xhr.onreadystatechange = function(){
  2403. if (4 != xhr.readyState) return;
  2404. if (200 == xhr.status || 1223 == xhr.status) {
  2405. self.onLoad();
  2406. } else {
  2407. // make sure the `error` event handler that's user-set
  2408. // does not throw in the same tick and gets caught here
  2409. setTimeout(function(){
  2410. self.onError(xhr.status);
  2411. }, 0);
  2412. }
  2413. };
  2414. }
  2415. debug('xhr data %s', this.data);
  2416. xhr.send(this.data);
  2417. } catch (e) {
  2418. // Need to defer since .create() is called directly fhrom the constructor
  2419. // and thus the 'error' event can only be only bound *after* this exception
  2420. // occurs. Therefore, also, we cannot throw here at all.
  2421. setTimeout(function() {
  2422. self.onError(e);
  2423. }, 0);
  2424. return;
  2425. }
  2426. if (global.document) {
  2427. this.index = Request.requestsCount++;
  2428. Request.requests[this.index] = this;
  2429. }
  2430. };
  2431. /**
  2432. * Called upon successful response.
  2433. *
  2434. * @api private
  2435. */
  2436. Request.prototype.onSuccess = function(){
  2437. this.emit('success');
  2438. this.cleanup();
  2439. };
  2440. /**
  2441. * Called if we have data.
  2442. *
  2443. * @api private
  2444. */
  2445. Request.prototype.onData = function(data){
  2446. this.emit('data', data);
  2447. this.onSuccess();
  2448. };
  2449. /**
  2450. * Called upon error.
  2451. *
  2452. * @api private
  2453. */
  2454. Request.prototype.onError = function(err){
  2455. this.emit('error', err);
  2456. this.cleanup(true);
  2457. };
  2458. /**
  2459. * Cleans up house.
  2460. *
  2461. * @api private
  2462. */
  2463. Request.prototype.cleanup = function(fromError){
  2464. if ('undefined' == typeof this.xhr || null === this.xhr) {
  2465. return;
  2466. }
  2467. // xmlhttprequest
  2468. if (this.hasXDR()) {
  2469. this.xhr.onload = this.xhr.onerror = empty;
  2470. } else {
  2471. this.xhr.onreadystatechange = empty;
  2472. }
  2473. if (fromError) {
  2474. try {
  2475. this.xhr.abort();
  2476. } catch(e) {}
  2477. }
  2478. if (global.document) {
  2479. delete Request.requests[this.index];
  2480. }
  2481. this.xhr = null;
  2482. };
  2483. /**
  2484. * Called upon load.
  2485. *
  2486. * @api private
  2487. */
  2488. Request.prototype.onLoad = function(){
  2489. var data;
  2490. try {
  2491. var contentType;
  2492. try {
  2493. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  2494. } catch (e) {}
  2495. if (contentType === 'application/octet-stream') {
  2496. data = this.xhr.response;
  2497. } else {
  2498. if (!this.supportsBinary) {
  2499. data = this.xhr.responseText;
  2500. } else {
  2501. data = 'ok';
  2502. }
  2503. }
  2504. } catch (e) {
  2505. this.onError(e);
  2506. }
  2507. if (null != data) {
  2508. this.onData(data);
  2509. }
  2510. };
  2511. /**
  2512. * Check if it has XDomainRequest.
  2513. *
  2514. * @api private
  2515. */
  2516. Request.prototype.hasXDR = function(){
  2517. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  2518. };
  2519. /**
  2520. * Aborts the request.
  2521. *
  2522. * @api public
  2523. */
  2524. Request.prototype.abort = function(){
  2525. this.cleanup();
  2526. };
  2527. /**
  2528. * Aborts pending requests when unloading the window. This is needed to prevent
  2529. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  2530. * emitted.
  2531. */
  2532. if (global.document) {
  2533. Request.requestsCount = 0;
  2534. Request.requests = {};
  2535. if (global.attachEvent) {
  2536. global.attachEvent('onunload', unloadHandler);
  2537. } else if (global.addEventListener) {
  2538. global.addEventListener('beforeunload', unloadHandler, false);
  2539. }
  2540. }
  2541. function unloadHandler() {
  2542. for (var i in Request.requests) {
  2543. if (Request.requests.hasOwnProperty(i)) {
  2544. Request.requests[i].abort();
  2545. }
  2546. }
  2547. }
  2548. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2549. },{"./polling":18,"component-emitter":9,"component-inherit":21,"debug":22,"xmlhttprequest":20}],18:[function(_dereq_,module,exports){
  2550. /**
  2551. * Module dependencies.
  2552. */
  2553. var Transport = _dereq_('../transport');
  2554. var parseqs = _dereq_('parseqs');
  2555. var parser = _dereq_('engine.io-parser');
  2556. var inherit = _dereq_('component-inherit');
  2557. var debug = _dereq_('debug')('engine.io-client:polling');
  2558. /**
  2559. * Module exports.
  2560. */
  2561. module.exports = Polling;
  2562. /**
  2563. * Is XHR2 supported?
  2564. */
  2565. var hasXHR2 = (function() {
  2566. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2567. var xhr = new XMLHttpRequest({ xdomain: false });
  2568. return null != xhr.responseType;
  2569. })();
  2570. /**
  2571. * Polling interface.
  2572. *
  2573. * @param {Object} opts
  2574. * @api private
  2575. */
  2576. function Polling(opts){
  2577. var forceBase64 = (opts && opts.forceBase64);
  2578. if (!hasXHR2 || forceBase64) {
  2579. this.supportsBinary = false;
  2580. }
  2581. Transport.call(this, opts);
  2582. }
  2583. /**
  2584. * Inherits from Transport.
  2585. */
  2586. inherit(Polling, Transport);
  2587. /**
  2588. * Transport name.
  2589. */
  2590. Polling.prototype.name = 'polling';
  2591. /**
  2592. * Opens the socket (triggers polling). We write a PING message to determine
  2593. * when the transport is open.
  2594. *
  2595. * @api private
  2596. */
  2597. Polling.prototype.doOpen = function(){
  2598. this.poll();
  2599. };
  2600. /**
  2601. * Pauses polling.
  2602. *
  2603. * @param {Function} callback upon buffers are flushed and transport is paused
  2604. * @api private
  2605. */
  2606. Polling.prototype.pause = function(onPause){
  2607. var pending = 0;
  2608. var self = this;
  2609. this.readyState = 'pausing';
  2610. function pause(){
  2611. debug('paused');
  2612. self.readyState = 'paused';
  2613. onPause();
  2614. }
  2615. if (this.polling || !this.writable) {
  2616. var total = 0;
  2617. if (this.polling) {
  2618. debug('we are currently polling - waiting to pause');
  2619. total++;
  2620. this.once('pollComplete', function(){
  2621. debug('pre-pause polling complete');
  2622. --total || pause();
  2623. });
  2624. }
  2625. if (!this.writable) {
  2626. debug('we are currently writing - waiting to pause');
  2627. total++;
  2628. this.once('drain', function(){
  2629. debug('pre-pause writing complete');
  2630. --total || pause();
  2631. });
  2632. }
  2633. } else {
  2634. pause();
  2635. }
  2636. };
  2637. /**
  2638. * Starts polling cycle.
  2639. *
  2640. * @api public
  2641. */
  2642. Polling.prototype.poll = function(){
  2643. debug('polling');
  2644. this.polling = true;
  2645. this.doPoll();
  2646. this.emit('poll');
  2647. };
  2648. /**
  2649. * Overloads onData to detect payloads.
  2650. *
  2651. * @api private
  2652. */
  2653. Polling.prototype.onData = function(data){
  2654. var self = this;
  2655. debug('polling got data %s', data);
  2656. var callback = function(packet, index, total) {
  2657. // if its the first message we consider the transport open
  2658. if ('opening' == self.readyState) {
  2659. self.onOpen();
  2660. }
  2661. // if its a close packet, we close the ongoing requests
  2662. if ('close' == packet.type) {
  2663. self.onClose();
  2664. return false;
  2665. }
  2666. // otherwise bypass onData and handle the message
  2667. self.onPacket(packet);
  2668. };
  2669. // decode payload
  2670. parser.decodePayload(data, this.socket.binaryType, callback);
  2671. // if an event did not trigger closing
  2672. if ('closed' != this.readyState) {
  2673. // if we got data we're not polling
  2674. this.polling = false;
  2675. this.emit('pollComplete');
  2676. if ('open' == this.readyState) {
  2677. this.poll();
  2678. } else {
  2679. debug('ignoring poll - transport state "%s"', this.readyState);
  2680. }
  2681. }
  2682. };
  2683. /**
  2684. * For polling, send a close packet.
  2685. *
  2686. * @api private
  2687. */
  2688. Polling.prototype.doClose = function(){
  2689. var self = this;
  2690. function close(){
  2691. debug('writing close packet');
  2692. self.write([{ type: 'close' }]);
  2693. }
  2694. if ('open' == this.readyState) {
  2695. debug('transport open - closing');
  2696. close();
  2697. } else {
  2698. // in case we're trying to close while
  2699. // handshaking is in progress (GH-164)
  2700. debug('transport not open - deferring close');
  2701. this.once('open', close);
  2702. }
  2703. };
  2704. /**
  2705. * Writes a packets payload.
  2706. *
  2707. * @param {Array} data packets
  2708. * @param {Function} drain callback
  2709. * @api private
  2710. */
  2711. Polling.prototype.write = function(packets){
  2712. var self = this;
  2713. this.writable = false;
  2714. var callbackfn = function() {
  2715. self.writable = true;
  2716. self.emit('drain');
  2717. };
  2718. var self = this;
  2719. parser.encodePayload(packets, this.supportsBinary, function(data) {
  2720. self.doWrite(data, callbackfn);
  2721. });
  2722. };
  2723. /**
  2724. * Generates uri for connection.
  2725. *
  2726. * @api private
  2727. */
  2728. Polling.prototype.uri = function(){
  2729. var query = this.query || {};
  2730. var schema = this.secure ? 'https' : 'http';
  2731. var port = '';
  2732. // cache busting is forced
  2733. if (false !== this.timestampRequests) {
  2734. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  2735. }
  2736. if (!this.supportsBinary && !query.sid) {
  2737. query.b64 = 1;
  2738. }
  2739. query = parseqs.encode(query);
  2740. // avoid port if default for schema
  2741. if (this.port && (('https' == schema && this.port != 443) ||
  2742. ('http' == schema && this.port != 80))) {
  2743. port = ':' + this.port;
  2744. }
  2745. // prepend ? to query
  2746. if (query.length) {
  2747. query = '?' + query;
  2748. }
  2749. return schema + '://' + this.hostname + port + this.path + query;
  2750. };
  2751. },{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":35,"xmlhttprequest":20}],19:[function(_dereq_,module,exports){
  2752. /**
  2753. * Module dependencies.
  2754. */
  2755. var Transport = _dereq_('../transport');
  2756. var parser = _dereq_('engine.io-parser');
  2757. var parseqs = _dereq_('parseqs');
  2758. var inherit = _dereq_('component-inherit');
  2759. var debug = _dereq_('debug')('engine.io-client:websocket');
  2760. /**
  2761. * `ws` exposes a WebSocket-compatible interface in
  2762. * Node, or the `WebSocket` or `MozWebSocket` globals
  2763. * in the browser.
  2764. */
  2765. var WebSocket = _dereq_('ws');
  2766. /**
  2767. * Module exports.
  2768. */
  2769. module.exports = WS;
  2770. /**
  2771. * WebSocket transport constructor.
  2772. *
  2773. * @api {Object} connection options
  2774. * @api public
  2775. */
  2776. function WS(opts){
  2777. var forceBase64 = (opts && opts.forceBase64);
  2778. if (forceBase64) {
  2779. this.supportsBinary = false;
  2780. }
  2781. Transport.call(this, opts);
  2782. }
  2783. /**
  2784. * Inherits from Transport.
  2785. */
  2786. inherit(WS, Transport);
  2787. /**
  2788. * Transport name.
  2789. *
  2790. * @api public
  2791. */
  2792. WS.prototype.name = 'websocket';
  2793. /*
  2794. * WebSockets support binary
  2795. */
  2796. WS.prototype.supportsBinary = true;
  2797. /**
  2798. * Opens socket.
  2799. *
  2800. * @api private
  2801. */
  2802. WS.prototype.doOpen = function(){
  2803. if (!this.check()) {
  2804. // let probe timeout
  2805. return;
  2806. }
  2807. var self = this;
  2808. var uri = this.uri();
  2809. var protocols = void(0);
  2810. var opts = { agent: this.agent };
  2811. // SSL options for Node.js client
  2812. opts.pfx = this.pfx;
  2813. opts.key = this.key;
  2814. opts.passphrase = this.passphrase;
  2815. opts.cert = this.cert;
  2816. opts.ca = this.ca;
  2817. opts.ciphers = this.ciphers;
  2818. opts.rejectUnauthorized = this.rejectUnauthorized;
  2819. this.ws = new WebSocket(uri, protocols, opts);
  2820. if (this.ws.binaryType === undefined) {
  2821. this.supportsBinary = false;
  2822. }
  2823. this.ws.binaryType = 'arraybuffer';
  2824. this.addEventListeners();
  2825. };
  2826. /**
  2827. * Adds event listeners to the socket
  2828. *
  2829. * @api private
  2830. */
  2831. WS.prototype.addEventListeners = function(){
  2832. var self = this;
  2833. this.ws.onopen = function(){
  2834. self.onOpen();
  2835. };
  2836. this.ws.onclose = function(){
  2837. self.onClose();
  2838. };
  2839. this.ws.onmessage = function(ev){
  2840. self.onData(ev.data);
  2841. };
  2842. this.ws.onerror = function(e){
  2843. self.onError('websocket error', e);
  2844. };
  2845. };
  2846. /**
  2847. * Override `onData` to use a timer on iOS.
  2848. * See: https://gist.github.com/mloughran/2052006
  2849. *
  2850. * @api private
  2851. */
  2852. if ('undefined' != typeof navigator
  2853. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  2854. WS.prototype.onData = function(data){
  2855. var self = this;
  2856. setTimeout(function(){
  2857. Transport.prototype.onData.call(self, data);
  2858. }, 0);
  2859. };
  2860. }
  2861. /**
  2862. * Writes data to socket.
  2863. *
  2864. * @param {Array} array of packets.
  2865. * @api private
  2866. */
  2867. WS.prototype.write = function(packets){
  2868. var self = this;
  2869. this.writable = false;
  2870. // encodePacket efficient as it uses WS framing
  2871. // no need for encodePayload
  2872. for (var i = 0, l = packets.length; i < l; i++) {
  2873. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  2874. //Sometimes the websocket has already been closed but the browser didn't
  2875. //have a chance of informing us about it yet, in that case send will
  2876. //throw an error
  2877. try {
  2878. self.ws.send(data);
  2879. } catch (e){
  2880. debug('websocket closed before onclose event');
  2881. }
  2882. });
  2883. }
  2884. function ondrain() {
  2885. self.writable = true;
  2886. self.emit('drain');
  2887. }
  2888. // fake drain
  2889. // defer to next tick to allow Socket to clear writeBuffer
  2890. setTimeout(ondrain, 0);
  2891. };
  2892. /**
  2893. * Called upon close
  2894. *
  2895. * @api private
  2896. */
  2897. WS.prototype.onClose = function(){
  2898. Transport.prototype.onClose.call(this);
  2899. };
  2900. /**
  2901. * Closes socket.
  2902. *
  2903. * @api private
  2904. */
  2905. WS.prototype.doClose = function(){
  2906. if (typeof this.ws !== 'undefined') {
  2907. this.ws.close();
  2908. }
  2909. };
  2910. /**
  2911. * Generates uri for connection.
  2912. *
  2913. * @api private
  2914. */
  2915. WS.prototype.uri = function(){
  2916. var query = this.query || {};
  2917. var schema = this.secure ? 'wss' : 'ws';
  2918. var port = '';
  2919. // avoid port if default for schema
  2920. if (this.port && (('wss' == schema && this.port != 443)
  2921. || ('ws' == schema && this.port != 80))) {
  2922. port = ':' + this.port;
  2923. }
  2924. // append timestamp to URI
  2925. if (this.timestampRequests) {
  2926. query[this.timestampParam] = +new Date;
  2927. }
  2928. // communicate binary support capabilities
  2929. if (!this.supportsBinary) {
  2930. query.b64 = 1;
  2931. }
  2932. query = parseqs.encode(query);
  2933. // prepend ? to query
  2934. if (query.length) {
  2935. query = '?' + query;
  2936. }
  2937. return schema + '://' + this.hostname + port + this.path + query;
  2938. };
  2939. /**
  2940. * Feature detection for WebSocket.
  2941. *
  2942. * @return {Boolean} whether this transport is available.
  2943. * @api public
  2944. */
  2945. WS.prototype.check = function(){
  2946. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  2947. };
  2948. },{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":35,"ws":37}],20:[function(_dereq_,module,exports){
  2949. // browser shim for xmlhttprequest module
  2950. var hasCORS = _dereq_('has-cors');
  2951. module.exports = function(opts) {
  2952. var xdomain = opts.xdomain;
  2953. // scheme must be same when usign XDomainRequest
  2954. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  2955. var xscheme = opts.xscheme;
  2956. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  2957. // https://github.com/Automattic/engine.io-client/pull/217
  2958. var enablesXDR = opts.enablesXDR;
  2959. // XMLHttpRequest can be disabled on IE
  2960. try {
  2961. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  2962. return new XMLHttpRequest();
  2963. }
  2964. } catch (e) { }
  2965. // Use XDomainRequest for IE8 if enablesXDR is true
  2966. // because loading bar keeps flashing when using jsonp-polling
  2967. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  2968. try {
  2969. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  2970. return new XDomainRequest();
  2971. }
  2972. } catch (e) { }
  2973. if (!xdomain) {
  2974. try {
  2975. return new ActiveXObject('Microsoft.XMLHTTP');
  2976. } catch(e) { }
  2977. }
  2978. }
  2979. },{"has-cors":40}],21:[function(_dereq_,module,exports){
  2980. module.exports = function(a, b){
  2981. var fn = function(){};
  2982. fn.prototype = b.prototype;
  2983. a.prototype = new fn;
  2984. a.prototype.constructor = a;
  2985. };
  2986. },{}],22:[function(_dereq_,module,exports){
  2987. /**
  2988. * This is the web browser implementation of `debug()`.
  2989. *
  2990. * Expose `debug()` as the module.
  2991. */
  2992. exports = module.exports = _dereq_('./debug');
  2993. exports.log = log;
  2994. exports.formatArgs = formatArgs;
  2995. exports.save = save;
  2996. exports.load = load;
  2997. exports.useColors = useColors;
  2998. /**
  2999. * Colors.
  3000. */
  3001. exports.colors = [
  3002. 'lightseagreen',
  3003. 'forestgreen',
  3004. 'goldenrod',
  3005. 'dodgerblue',
  3006. 'darkorchid',
  3007. 'crimson'
  3008. ];
  3009. /**
  3010. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  3011. * and the Firebug extension (any Firefox version) are known
  3012. * to support "%c" CSS customizations.
  3013. *
  3014. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  3015. */
  3016. function useColors() {
  3017. // is webkit? http://stackoverflow.com/a/16459606/376773
  3018. return ('WebkitAppearance' in document.documentElement.style) ||
  3019. // is firebug? http://stackoverflow.com/a/398120/376773
  3020. (window.console && (console.firebug || (console.exception && console.table))) ||
  3021. // is firefox >= v31?
  3022. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  3023. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  3024. }
  3025. /**
  3026. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  3027. */
  3028. exports.formatters.j = function(v) {
  3029. return JSON.stringify(v);
  3030. };
  3031. /**
  3032. * Colorize log arguments if enabled.
  3033. *
  3034. * @api public
  3035. */
  3036. function formatArgs() {
  3037. var args = arguments;
  3038. var useColors = this.useColors;
  3039. args[0] = (useColors ? '%c' : '')
  3040. + this.namespace
  3041. + (useColors ? ' %c' : ' ')
  3042. + args[0]
  3043. + (useColors ? '%c ' : ' ')
  3044. + '+' + exports.humanize(this.diff);
  3045. if (!useColors) return args;
  3046. var c = 'color: ' + this.color;
  3047. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  3048. // the final "%c" is somewhat tricky, because there could be other
  3049. // arguments passed either before or after the %c, so we need to
  3050. // figure out the correct index to insert the CSS into
  3051. var index = 0;
  3052. var lastC = 0;
  3053. args[0].replace(/%[a-z%]/g, function(match) {
  3054. if ('%' === match) return;
  3055. index++;
  3056. if ('%c' === match) {
  3057. // we only are interested in the *last* %c
  3058. // (the user may have provided their own)
  3059. lastC = index;
  3060. }
  3061. });
  3062. args.splice(lastC, 0, c);
  3063. return args;
  3064. }
  3065. /**
  3066. * Invokes `console.log()` when available.
  3067. * No-op when `console.log` is not a "function".
  3068. *
  3069. * @api public
  3070. */
  3071. function log() {
  3072. // This hackery is required for IE8,
  3073. // where the `console.log` function doesn't have 'apply'
  3074. return 'object' == typeof console
  3075. && 'function' == typeof console.log
  3076. && Function.prototype.apply.call(console.log, console, arguments);
  3077. }
  3078. /**
  3079. * Save `namespaces`.
  3080. *
  3081. * @param {String} namespaces
  3082. * @api private
  3083. */
  3084. function save(namespaces) {
  3085. try {
  3086. if (null == namespaces) {
  3087. localStorage.removeItem('debug');
  3088. } else {
  3089. localStorage.debug = namespaces;
  3090. }
  3091. } catch(e) {}
  3092. }
  3093. /**
  3094. * Load `namespaces`.
  3095. *
  3096. * @return {String} returns the previously persisted debug modes
  3097. * @api private
  3098. */
  3099. function load() {
  3100. var r;
  3101. try {
  3102. r = localStorage.debug;
  3103. } catch(e) {}
  3104. return r;
  3105. }
  3106. /**
  3107. * Enable namespaces listed in `localStorage.debug` initially.
  3108. */
  3109. exports.enable(load());
  3110. },{"./debug":23}],23:[function(_dereq_,module,exports){
  3111. /**
  3112. * This is the common logic for both the Node.js and web browser
  3113. * implementations of `debug()`.
  3114. *
  3115. * Expose `debug()` as the module.
  3116. */
  3117. exports = module.exports = debug;
  3118. exports.coerce = coerce;
  3119. exports.disable = disable;
  3120. exports.enable = enable;
  3121. exports.enabled = enabled;
  3122. exports.humanize = _dereq_('ms');
  3123. /**
  3124. * The currently active debug mode names, and names to skip.
  3125. */
  3126. exports.names = [];
  3127. exports.skips = [];
  3128. /**
  3129. * Map of special "%n" handling functions, for the debug "format" argument.
  3130. *
  3131. * Valid key names are a single, lowercased letter, i.e. "n".
  3132. */
  3133. exports.formatters = {};
  3134. /**
  3135. * Previously assigned color.
  3136. */
  3137. var prevColor = 0;
  3138. /**
  3139. * Previous log timestamp.
  3140. */
  3141. var prevTime;
  3142. /**
  3143. * Select a color.
  3144. *
  3145. * @return {Number}
  3146. * @api private
  3147. */
  3148. function selectColor() {
  3149. return exports.colors[prevColor++ % exports.colors.length];
  3150. }
  3151. /**
  3152. * Create a debugger with the given `namespace`.
  3153. *
  3154. * @param {String} namespace
  3155. * @return {Function}
  3156. * @api public
  3157. */
  3158. function debug(namespace) {
  3159. // define the `disabled` version
  3160. function disabled() {
  3161. }
  3162. disabled.enabled = false;
  3163. // define the `enabled` version
  3164. function enabled() {
  3165. var self = enabled;
  3166. // set `diff` timestamp
  3167. var curr = +new Date();
  3168. var ms = curr - (prevTime || curr);
  3169. self.diff = ms;
  3170. self.prev = prevTime;
  3171. self.curr = curr;
  3172. prevTime = curr;
  3173. // add the `color` if not set
  3174. if (null == self.useColors) self.useColors = exports.useColors();
  3175. if (null == self.color && self.useColors) self.color = selectColor();
  3176. var args = Array.prototype.slice.call(arguments);
  3177. args[0] = exports.coerce(args[0]);
  3178. if ('string' !== typeof args[0]) {
  3179. // anything else let's inspect with %o
  3180. args = ['%o'].concat(args);
  3181. }
  3182. // apply any `formatters` transformations
  3183. var index = 0;
  3184. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  3185. // if we encounter an escaped % then don't increase the array index
  3186. if (match === '%') return match;
  3187. index++;
  3188. var formatter = exports.formatters[format];
  3189. if ('function' === typeof formatter) {
  3190. var val = args[index];
  3191. match = formatter.call(self, val);
  3192. // now we need to remove `args[index]` since it's inlined in the `format`
  3193. args.splice(index, 1);
  3194. index--;
  3195. }
  3196. return match;
  3197. });
  3198. if ('function' === typeof exports.formatArgs) {
  3199. args = exports.formatArgs.apply(self, args);
  3200. }
  3201. var logFn = enabled.log || exports.log || console.log.bind(console);
  3202. logFn.apply(self, args);
  3203. }
  3204. enabled.enabled = true;
  3205. var fn = exports.enabled(namespace) ? enabled : disabled;
  3206. fn.namespace = namespace;
  3207. return fn;
  3208. }
  3209. /**
  3210. * Enables a debug mode by namespaces. This can include modes
  3211. * separated by a colon and wildcards.
  3212. *
  3213. * @param {String} namespaces
  3214. * @api public
  3215. */
  3216. function enable(namespaces) {
  3217. exports.save(namespaces);
  3218. var split = (namespaces || '').split(/[\s,]+/);
  3219. var len = split.length;
  3220. for (var i = 0; i < len; i++) {
  3221. if (!split[i]) continue; // ignore empty strings
  3222. namespaces = split[i].replace(/\*/g, '.*?');
  3223. if (namespaces[0] === '-') {
  3224. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  3225. } else {
  3226. exports.names.push(new RegExp('^' + namespaces + '$'));
  3227. }
  3228. }
  3229. }
  3230. /**
  3231. * Disable debug output.
  3232. *
  3233. * @api public
  3234. */
  3235. function disable() {
  3236. exports.enable('');
  3237. }
  3238. /**
  3239. * Returns true if the given mode name is enabled, false otherwise.
  3240. *
  3241. * @param {String} name
  3242. * @return {Boolean}
  3243. * @api public
  3244. */
  3245. function enabled(name) {
  3246. var i, len;
  3247. for (i = 0, len = exports.skips.length; i < len; i++) {
  3248. if (exports.skips[i].test(name)) {
  3249. return false;
  3250. }
  3251. }
  3252. for (i = 0, len = exports.names.length; i < len; i++) {
  3253. if (exports.names[i].test(name)) {
  3254. return true;
  3255. }
  3256. }
  3257. return false;
  3258. }
  3259. /**
  3260. * Coerce `val`.
  3261. *
  3262. * @param {Mixed} val
  3263. * @return {Mixed}
  3264. * @api private
  3265. */
  3266. function coerce(val) {
  3267. if (val instanceof Error) return val.stack || val.message;
  3268. return val;
  3269. }
  3270. },{"ms":24}],24:[function(_dereq_,module,exports){
  3271. /**
  3272. * Helpers.
  3273. */
  3274. var s = 1000;
  3275. var m = s * 60;
  3276. var h = m * 60;
  3277. var d = h * 24;
  3278. var y = d * 365.25;
  3279. /**
  3280. * Parse or format the given `val`.
  3281. *
  3282. * Options:
  3283. *
  3284. * - `long` verbose formatting [false]
  3285. *
  3286. * @param {String|Number} val
  3287. * @param {Object} options
  3288. * @return {String|Number}
  3289. * @api public
  3290. */
  3291. module.exports = function(val, options){
  3292. options = options || {};
  3293. if ('string' == typeof val) return parse(val);
  3294. return options.long
  3295. ? long(val)
  3296. : short(val);
  3297. };
  3298. /**
  3299. * Parse the given `str` and return milliseconds.
  3300. *
  3301. * @param {String} str
  3302. * @return {Number}
  3303. * @api private
  3304. */
  3305. function parse(str) {
  3306. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  3307. if (!match) return;
  3308. var n = parseFloat(match[1]);
  3309. var type = (match[2] || 'ms').toLowerCase();
  3310. switch (type) {
  3311. case 'years':
  3312. case 'year':
  3313. case 'y':
  3314. return n * y;
  3315. case 'days':
  3316. case 'day':
  3317. case 'd':
  3318. return n * d;
  3319. case 'hours':
  3320. case 'hour':
  3321. case 'h':
  3322. return n * h;
  3323. case 'minutes':
  3324. case 'minute':
  3325. case 'm':
  3326. return n * m;
  3327. case 'seconds':
  3328. case 'second':
  3329. case 's':
  3330. return n * s;
  3331. case 'ms':
  3332. return n;
  3333. }
  3334. }
  3335. /**
  3336. * Short format for `ms`.
  3337. *
  3338. * @param {Number} ms
  3339. * @return {String}
  3340. * @api private
  3341. */
  3342. function short(ms) {
  3343. if (ms >= d) return Math.round(ms / d) + 'd';
  3344. if (ms >= h) return Math.round(ms / h) + 'h';
  3345. if (ms >= m) return Math.round(ms / m) + 'm';
  3346. if (ms >= s) return Math.round(ms / s) + 's';
  3347. return ms + 'ms';
  3348. }
  3349. /**
  3350. * Long format for `ms`.
  3351. *
  3352. * @param {Number} ms
  3353. * @return {String}
  3354. * @api private
  3355. */
  3356. function long(ms) {
  3357. return plural(ms, d, 'day')
  3358. || plural(ms, h, 'hour')
  3359. || plural(ms, m, 'minute')
  3360. || plural(ms, s, 'second')
  3361. || ms + ' ms';
  3362. }
  3363. /**
  3364. * Pluralization helper.
  3365. */
  3366. function plural(ms, n, name) {
  3367. if (ms < n) return;
  3368. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  3369. return Math.ceil(ms / n) + ' ' + name + 's';
  3370. }
  3371. },{}],25:[function(_dereq_,module,exports){
  3372. (function (global){
  3373. /**
  3374. * Module dependencies.
  3375. */
  3376. var keys = _dereq_('./keys');
  3377. var hasBinary = _dereq_('has-binary');
  3378. var sliceBuffer = _dereq_('arraybuffer.slice');
  3379. var base64encoder = _dereq_('base64-arraybuffer');
  3380. var after = _dereq_('after');
  3381. var utf8 = _dereq_('utf8');
  3382. /**
  3383. * Check if we are running an android browser. That requires us to use
  3384. * ArrayBuffer with polling transports...
  3385. *
  3386. * http://ghinda.net/jpeg-blob-ajax-android/
  3387. */
  3388. var isAndroid = navigator.userAgent.match(/Android/i);
  3389. /**
  3390. * Check if we are running in PhantomJS.
  3391. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  3392. * https://github.com/ariya/phantomjs/issues/11395
  3393. * @type boolean
  3394. */
  3395. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  3396. /**
  3397. * When true, avoids using Blobs to encode payloads.
  3398. * @type boolean
  3399. */
  3400. var dontSendBlobs = isAndroid || isPhantomJS;
  3401. /**
  3402. * Current protocol version.
  3403. */
  3404. exports.protocol = 3;
  3405. /**
  3406. * Packet types.
  3407. */
  3408. var packets = exports.packets = {
  3409. open: 0 // non-ws
  3410. , close: 1 // non-ws
  3411. , ping: 2
  3412. , pong: 3
  3413. , message: 4
  3414. , upgrade: 5
  3415. , noop: 6
  3416. };
  3417. var packetslist = keys(packets);
  3418. /**
  3419. * Premade error packet.
  3420. */
  3421. var err = { type: 'error', data: 'parser error' };
  3422. /**
  3423. * Create a blob api even for blob builder when vendor prefixes exist
  3424. */
  3425. var Blob = _dereq_('blob');
  3426. /**
  3427. * Encodes a packet.
  3428. *
  3429. * <packet type id> [ <data> ]
  3430. *
  3431. * Example:
  3432. *
  3433. * 5hello world
  3434. * 3
  3435. * 4
  3436. *
  3437. * Binary is encoded in an identical principle
  3438. *
  3439. * @api private
  3440. */
  3441. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  3442. if ('function' == typeof supportsBinary) {
  3443. callback = supportsBinary;
  3444. supportsBinary = false;
  3445. }
  3446. if ('function' == typeof utf8encode) {
  3447. callback = utf8encode;
  3448. utf8encode = null;
  3449. }
  3450. var data = (packet.data === undefined)
  3451. ? undefined
  3452. : packet.data.buffer || packet.data;
  3453. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  3454. return encodeArrayBuffer(packet, supportsBinary, callback);
  3455. } else if (Blob && data instanceof global.Blob) {
  3456. return encodeBlob(packet, supportsBinary, callback);
  3457. }
  3458. // might be an object with { base64: true, data: dataAsBase64String }
  3459. if (data && data.base64) {
  3460. return encodeBase64Object(packet, callback);
  3461. }
  3462. // Sending data as a utf-8 string
  3463. var encoded = packets[packet.type];
  3464. // data fragment is optional
  3465. if (undefined !== packet.data) {
  3466. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  3467. }
  3468. return callback('' + encoded);
  3469. };
  3470. function encodeBase64Object(packet, callback) {
  3471. // packet data is an object { base64: true, data: dataAsBase64String }
  3472. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  3473. return callback(message);
  3474. }
  3475. /**
  3476. * Encode packet helpers for binary types
  3477. */
  3478. function encodeArrayBuffer(packet, supportsBinary, callback) {
  3479. if (!supportsBinary) {
  3480. return exports.encodeBase64Packet(packet, callback);
  3481. }
  3482. var data = packet.data;
  3483. var contentArray = new Uint8Array(data);
  3484. var resultBuffer = new Uint8Array(1 + data.byteLength);
  3485. resultBuffer[0] = packets[packet.type];
  3486. for (var i = 0; i < contentArray.length; i++) {
  3487. resultBuffer[i+1] = contentArray[i];
  3488. }
  3489. return callback(resultBuffer.buffer);
  3490. }
  3491. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  3492. if (!supportsBinary) {
  3493. return exports.encodeBase64Packet(packet, callback);
  3494. }
  3495. var fr = new FileReader();
  3496. fr.onload = function() {
  3497. packet.data = fr.result;
  3498. exports.encodePacket(packet, supportsBinary, true, callback);
  3499. };
  3500. return fr.readAsArrayBuffer(packet.data);
  3501. }
  3502. function encodeBlob(packet, supportsBinary, callback) {
  3503. if (!supportsBinary) {
  3504. return exports.encodeBase64Packet(packet, callback);
  3505. }
  3506. if (dontSendBlobs) {
  3507. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  3508. }
  3509. var length = new Uint8Array(1);
  3510. length[0] = packets[packet.type];
  3511. var blob = new Blob([length.buffer, packet.data]);
  3512. return callback(blob);
  3513. }
  3514. /**
  3515. * Encodes a packet with binary data in a base64 string
  3516. *
  3517. * @param {Object} packet, has `type` and `data`
  3518. * @return {String} base64 encoded message
  3519. */
  3520. exports.encodeBase64Packet = function(packet, callback) {
  3521. var message = 'b' + exports.packets[packet.type];
  3522. if (Blob && packet.data instanceof Blob) {
  3523. var fr = new FileReader();
  3524. fr.onload = function() {
  3525. var b64 = fr.result.split(',')[1];
  3526. callback(message + b64);
  3527. };
  3528. return fr.readAsDataURL(packet.data);
  3529. }
  3530. var b64data;
  3531. try {
  3532. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  3533. } catch (e) {
  3534. // iPhone Safari doesn't let you apply with typed arrays
  3535. var typed = new Uint8Array(packet.data);
  3536. var basic = new Array(typed.length);
  3537. for (var i = 0; i < typed.length; i++) {
  3538. basic[i] = typed[i];
  3539. }
  3540. b64data = String.fromCharCode.apply(null, basic);
  3541. }
  3542. message += global.btoa(b64data);
  3543. return callback(message);
  3544. };
  3545. /**
  3546. * Decodes a packet. Changes format to Blob if requested.
  3547. *
  3548. * @return {Object} with `type` and `data` (if any)
  3549. * @api private
  3550. */
  3551. exports.decodePacket = function (data, binaryType, utf8decode) {
  3552. // String data
  3553. if (typeof data == 'string' || data === undefined) {
  3554. if (data.charAt(0) == 'b') {
  3555. return exports.decodeBase64Packet(data.substr(1), binaryType);
  3556. }
  3557. if (utf8decode) {
  3558. try {
  3559. data = utf8.decode(data);
  3560. } catch (e) {
  3561. return err;
  3562. }
  3563. }
  3564. var type = data.charAt(0);
  3565. if (Number(type) != type || !packetslist[type]) {
  3566. return err;
  3567. }
  3568. if (data.length > 1) {
  3569. return { type: packetslist[type], data: data.substring(1) };
  3570. } else {
  3571. return { type: packetslist[type] };
  3572. }
  3573. }
  3574. var asArray = new Uint8Array(data);
  3575. var type = asArray[0];
  3576. var rest = sliceBuffer(data, 1);
  3577. if (Blob && binaryType === 'blob') {
  3578. rest = new Blob([rest]);
  3579. }
  3580. return { type: packetslist[type], data: rest };
  3581. };
  3582. /**
  3583. * Decodes a packet encoded in a base64 string
  3584. *
  3585. * @param {String} base64 encoded message
  3586. * @return {Object} with `type` and `data` (if any)
  3587. */
  3588. exports.decodeBase64Packet = function(msg, binaryType) {
  3589. var type = packetslist[msg.charAt(0)];
  3590. if (!global.ArrayBuffer) {
  3591. return { type: type, data: { base64: true, data: msg.substr(1) } };
  3592. }
  3593. var data = base64encoder.decode(msg.substr(1));
  3594. if (binaryType === 'blob' && Blob) {
  3595. data = new Blob([data]);
  3596. }
  3597. return { type: type, data: data };
  3598. };
  3599. /**
  3600. * Encodes multiple messages (payload).
  3601. *
  3602. * <length>:data
  3603. *
  3604. * Example:
  3605. *
  3606. * 11:hello world2:hi
  3607. *
  3608. * If any contents are binary, they will be encoded as base64 strings. Base64
  3609. * encoded strings are marked with a b before the length specifier
  3610. *
  3611. * @param {Array} packets
  3612. * @api private
  3613. */
  3614. exports.encodePayload = function (packets, supportsBinary, callback) {
  3615. if (typeof supportsBinary == 'function') {
  3616. callback = supportsBinary;
  3617. supportsBinary = null;
  3618. }
  3619. var isBinary = hasBinary(packets);
  3620. if (supportsBinary && isBinary) {
  3621. if (Blob && !dontSendBlobs) {
  3622. return exports.encodePayloadAsBlob(packets, callback);
  3623. }
  3624. return exports.encodePayloadAsArrayBuffer(packets, callback);
  3625. }
  3626. if (!packets.length) {
  3627. return callback('0:');
  3628. }
  3629. function setLengthHeader(message) {
  3630. return message.length + ':' + message;
  3631. }
  3632. function encodeOne(packet, doneCallback) {
  3633. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  3634. doneCallback(null, setLengthHeader(message));
  3635. });
  3636. }
  3637. map(packets, encodeOne, function(err, results) {
  3638. return callback(results.join(''));
  3639. });
  3640. };
  3641. /**
  3642. * Async array map using after
  3643. */
  3644. function map(ary, each, done) {
  3645. var result = new Array(ary.length);
  3646. var next = after(ary.length, done);
  3647. var eachWithIndex = function(i, el, cb) {
  3648. each(el, function(error, msg) {
  3649. result[i] = msg;
  3650. cb(error, result);
  3651. });
  3652. };
  3653. for (var i = 0; i < ary.length; i++) {
  3654. eachWithIndex(i, ary[i], next);
  3655. }
  3656. }
  3657. /*
  3658. * Decodes data when a payload is maybe expected. Possible binary contents are
  3659. * decoded from their base64 representation
  3660. *
  3661. * @param {String} data, callback method
  3662. * @api public
  3663. */
  3664. exports.decodePayload = function (data, binaryType, callback) {
  3665. if (typeof data != 'string') {
  3666. return exports.decodePayloadAsBinary(data, binaryType, callback);
  3667. }
  3668. if (typeof binaryType === 'function') {
  3669. callback = binaryType;
  3670. binaryType = null;
  3671. }
  3672. var packet;
  3673. if (data == '') {
  3674. // parser error - ignoring payload
  3675. return callback(err, 0, 1);
  3676. }
  3677. var length = ''
  3678. , n, msg;
  3679. for (var i = 0, l = data.length; i < l; i++) {
  3680. var chr = data.charAt(i);
  3681. if (':' != chr) {
  3682. length += chr;
  3683. } else {
  3684. if ('' == length || (length != (n = Number(length)))) {
  3685. // parser error - ignoring payload
  3686. return callback(err, 0, 1);
  3687. }
  3688. msg = data.substr(i + 1, n);
  3689. if (length != msg.length) {
  3690. // parser error - ignoring payload
  3691. return callback(err, 0, 1);
  3692. }
  3693. if (msg.length) {
  3694. packet = exports.decodePacket(msg, binaryType, true);
  3695. if (err.type == packet.type && err.data == packet.data) {
  3696. // parser error in individual packet - ignoring payload
  3697. return callback(err, 0, 1);
  3698. }
  3699. var ret = callback(packet, i + n, l);
  3700. if (false === ret) return;
  3701. }
  3702. // advance cursor
  3703. i += n;
  3704. length = '';
  3705. }
  3706. }
  3707. if (length != '') {
  3708. // parser error - ignoring payload
  3709. return callback(err, 0, 1);
  3710. }
  3711. };
  3712. /**
  3713. * Encodes multiple messages (payload) as binary.
  3714. *
  3715. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  3716. * 255><data>
  3717. *
  3718. * Example:
  3719. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  3720. *
  3721. * @param {Array} packets
  3722. * @return {ArrayBuffer} encoded payload
  3723. * @api private
  3724. */
  3725. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  3726. if (!packets.length) {
  3727. return callback(new ArrayBuffer(0));
  3728. }
  3729. function encodeOne(packet, doneCallback) {
  3730. exports.encodePacket(packet, true, true, function(data) {
  3731. return doneCallback(null, data);
  3732. });
  3733. }
  3734. map(packets, encodeOne, function(err, encodedPackets) {
  3735. var totalLength = encodedPackets.reduce(function(acc, p) {
  3736. var len;
  3737. if (typeof p === 'string'){
  3738. len = p.length;
  3739. } else {
  3740. len = p.byteLength;
  3741. }
  3742. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  3743. }, 0);
  3744. var resultArray = new Uint8Array(totalLength);
  3745. var bufferIndex = 0;
  3746. encodedPackets.forEach(function(p) {
  3747. var isString = typeof p === 'string';
  3748. var ab = p;
  3749. if (isString) {
  3750. var view = new Uint8Array(p.length);
  3751. for (var i = 0; i < p.length; i++) {
  3752. view[i] = p.charCodeAt(i);
  3753. }
  3754. ab = view.buffer;
  3755. }
  3756. if (isString) { // not true binary
  3757. resultArray[bufferIndex++] = 0;
  3758. } else { // true binary
  3759. resultArray[bufferIndex++] = 1;
  3760. }
  3761. var lenStr = ab.byteLength.toString();
  3762. for (var i = 0; i < lenStr.length; i++) {
  3763. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  3764. }
  3765. resultArray[bufferIndex++] = 255;
  3766. var view = new Uint8Array(ab);
  3767. for (var i = 0; i < view.length; i++) {
  3768. resultArray[bufferIndex++] = view[i];
  3769. }
  3770. });
  3771. return callback(resultArray.buffer);
  3772. });
  3773. };
  3774. /**
  3775. * Encode as Blob
  3776. */
  3777. exports.encodePayloadAsBlob = function(packets, callback) {
  3778. function encodeOne(packet, doneCallback) {
  3779. exports.encodePacket(packet, true, true, function(encoded) {
  3780. var binaryIdentifier = new Uint8Array(1);
  3781. binaryIdentifier[0] = 1;
  3782. if (typeof encoded === 'string') {
  3783. var view = new Uint8Array(encoded.length);
  3784. for (var i = 0; i < encoded.length; i++) {
  3785. view[i] = encoded.charCodeAt(i);
  3786. }
  3787. encoded = view.buffer;
  3788. binaryIdentifier[0] = 0;
  3789. }
  3790. var len = (encoded instanceof ArrayBuffer)
  3791. ? encoded.byteLength
  3792. : encoded.size;
  3793. var lenStr = len.toString();
  3794. var lengthAry = new Uint8Array(lenStr.length + 1);
  3795. for (var i = 0; i < lenStr.length; i++) {
  3796. lengthAry[i] = parseInt(lenStr[i]);
  3797. }
  3798. lengthAry[lenStr.length] = 255;
  3799. if (Blob) {
  3800. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  3801. doneCallback(null, blob);
  3802. }
  3803. });
  3804. }
  3805. map(packets, encodeOne, function(err, results) {
  3806. return callback(new Blob(results));
  3807. });
  3808. };
  3809. /*
  3810. * Decodes data when a payload is maybe expected. Strings are decoded by
  3811. * interpreting each byte as a key code for entries marked to start with 0. See
  3812. * description of encodePayloadAsBinary
  3813. *
  3814. * @param {ArrayBuffer} data, callback method
  3815. * @api public
  3816. */
  3817. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  3818. if (typeof binaryType === 'function') {
  3819. callback = binaryType;
  3820. binaryType = null;
  3821. }
  3822. var bufferTail = data;
  3823. var buffers = [];
  3824. var numberTooLong = false;
  3825. while (bufferTail.byteLength > 0) {
  3826. var tailArray = new Uint8Array(bufferTail);
  3827. var isString = tailArray[0] === 0;
  3828. var msgLength = '';
  3829. for (var i = 1; ; i++) {
  3830. if (tailArray[i] == 255) break;
  3831. if (msgLength.length > 310) {
  3832. numberTooLong = true;
  3833. break;
  3834. }
  3835. msgLength += tailArray[i];
  3836. }
  3837. if(numberTooLong) return callback(err, 0, 1);
  3838. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  3839. msgLength = parseInt(msgLength);
  3840. var msg = sliceBuffer(bufferTail, 0, msgLength);
  3841. if (isString) {
  3842. try {
  3843. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  3844. } catch (e) {
  3845. // iPhone Safari doesn't let you apply to typed arrays
  3846. var typed = new Uint8Array(msg);
  3847. msg = '';
  3848. for (var i = 0; i < typed.length; i++) {
  3849. msg += String.fromCharCode(typed[i]);
  3850. }
  3851. }
  3852. }
  3853. buffers.push(msg);
  3854. bufferTail = sliceBuffer(bufferTail, msgLength);
  3855. }
  3856. var total = buffers.length;
  3857. buffers.forEach(function(buffer, i) {
  3858. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  3859. });
  3860. };
  3861. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3862. },{"./keys":26,"after":27,"arraybuffer.slice":28,"base64-arraybuffer":29,"blob":30,"has-binary":31,"utf8":33}],26:[function(_dereq_,module,exports){
  3863. /**
  3864. * Gets the keys for an object.
  3865. *
  3866. * @return {Array} keys
  3867. * @api private
  3868. */
  3869. module.exports = Object.keys || function keys (obj){
  3870. var arr = [];
  3871. var has = Object.prototype.hasOwnProperty;
  3872. for (var i in obj) {
  3873. if (has.call(obj, i)) {
  3874. arr.push(i);
  3875. }
  3876. }
  3877. return arr;
  3878. };
  3879. },{}],27:[function(_dereq_,module,exports){
  3880. module.exports = after
  3881. function after(count, callback, err_cb) {
  3882. var bail = false
  3883. err_cb = err_cb || noop
  3884. proxy.count = count
  3885. return (count === 0) ? callback() : proxy
  3886. function proxy(err, result) {
  3887. if (proxy.count <= 0) {
  3888. throw new Error('after called too many times')
  3889. }
  3890. --proxy.count
  3891. // after first error, rest are passed to err_cb
  3892. if (err) {
  3893. bail = true
  3894. callback(err)
  3895. // future error callbacks will go to error handler
  3896. callback = err_cb
  3897. } else if (proxy.count === 0 && !bail) {
  3898. callback(null, result)
  3899. }
  3900. }
  3901. }
  3902. function noop() {}
  3903. },{}],28:[function(_dereq_,module,exports){
  3904. /**
  3905. * An abstraction for slicing an arraybuffer even when
  3906. * ArrayBuffer.prototype.slice is not supported
  3907. *
  3908. * @api public
  3909. */
  3910. module.exports = function(arraybuffer, start, end) {
  3911. var bytes = arraybuffer.byteLength;
  3912. start = start || 0;
  3913. end = end || bytes;
  3914. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  3915. if (start < 0) { start += bytes; }
  3916. if (end < 0) { end += bytes; }
  3917. if (end > bytes) { end = bytes; }
  3918. if (start >= bytes || start >= end || bytes === 0) {
  3919. return new ArrayBuffer(0);
  3920. }
  3921. var abv = new Uint8Array(arraybuffer);
  3922. var result = new Uint8Array(end - start);
  3923. for (var i = start, ii = 0; i < end; i++, ii++) {
  3924. result[ii] = abv[i];
  3925. }
  3926. return result.buffer;
  3927. };
  3928. },{}],29:[function(_dereq_,module,exports){
  3929. /*
  3930. * base64-arraybuffer
  3931. * https://github.com/niklasvh/base64-arraybuffer
  3932. *
  3933. * Copyright (c) 2012 Niklas von Hertzen
  3934. * Licensed under the MIT license.
  3935. */
  3936. (function(chars){
  3937. "use strict";
  3938. exports.encode = function(arraybuffer) {
  3939. var bytes = new Uint8Array(arraybuffer),
  3940. i, len = bytes.length, base64 = "";
  3941. for (i = 0; i < len; i+=3) {
  3942. base64 += chars[bytes[i] >> 2];
  3943. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  3944. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  3945. base64 += chars[bytes[i + 2] & 63];
  3946. }
  3947. if ((len % 3) === 2) {
  3948. base64 = base64.substring(0, base64.length - 1) + "=";
  3949. } else if (len % 3 === 1) {
  3950. base64 = base64.substring(0, base64.length - 2) + "==";
  3951. }
  3952. return base64;
  3953. };
  3954. exports.decode = function(base64) {
  3955. var bufferLength = base64.length * 0.75,
  3956. len = base64.length, i, p = 0,
  3957. encoded1, encoded2, encoded3, encoded4;
  3958. if (base64[base64.length - 1] === "=") {
  3959. bufferLength--;
  3960. if (base64[base64.length - 2] === "=") {
  3961. bufferLength--;
  3962. }
  3963. }
  3964. var arraybuffer = new ArrayBuffer(bufferLength),
  3965. bytes = new Uint8Array(arraybuffer);
  3966. for (i = 0; i < len; i+=4) {
  3967. encoded1 = chars.indexOf(base64[i]);
  3968. encoded2 = chars.indexOf(base64[i+1]);
  3969. encoded3 = chars.indexOf(base64[i+2]);
  3970. encoded4 = chars.indexOf(base64[i+3]);
  3971. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  3972. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  3973. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  3974. }
  3975. return arraybuffer;
  3976. };
  3977. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  3978. },{}],30:[function(_dereq_,module,exports){
  3979. (function (global){
  3980. /**
  3981. * Create a blob builder even when vendor prefixes exist
  3982. */
  3983. var BlobBuilder = global.BlobBuilder
  3984. || global.WebKitBlobBuilder
  3985. || global.MSBlobBuilder
  3986. || global.MozBlobBuilder;
  3987. /**
  3988. * Check if Blob constructor is supported
  3989. */
  3990. var blobSupported = (function() {
  3991. try {
  3992. var b = new Blob(['hi']);
  3993. return b.size == 2;
  3994. } catch(e) {
  3995. return false;
  3996. }
  3997. })();
  3998. /**
  3999. * Check if BlobBuilder is supported
  4000. */
  4001. var blobBuilderSupported = BlobBuilder
  4002. && BlobBuilder.prototype.append
  4003. && BlobBuilder.prototype.getBlob;
  4004. function BlobBuilderConstructor(ary, options) {
  4005. options = options || {};
  4006. var bb = new BlobBuilder();
  4007. for (var i = 0; i < ary.length; i++) {
  4008. bb.append(ary[i]);
  4009. }
  4010. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  4011. };
  4012. module.exports = (function() {
  4013. if (blobSupported) {
  4014. return global.Blob;
  4015. } else if (blobBuilderSupported) {
  4016. return BlobBuilderConstructor;
  4017. } else {
  4018. return undefined;
  4019. }
  4020. })();
  4021. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4022. },{}],31:[function(_dereq_,module,exports){
  4023. (function (global){
  4024. /*
  4025. * Module requirements.
  4026. */
  4027. var isArray = _dereq_('isarray');
  4028. /**
  4029. * Module exports.
  4030. */
  4031. module.exports = hasBinary;
  4032. /**
  4033. * Checks for binary data.
  4034. *
  4035. * Right now only Buffer and ArrayBuffer are supported..
  4036. *
  4037. * @param {Object} anything
  4038. * @api public
  4039. */
  4040. function hasBinary(data) {
  4041. function _hasBinary(obj) {
  4042. if (!obj) return false;
  4043. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  4044. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  4045. (global.Blob && obj instanceof Blob) ||
  4046. (global.File && obj instanceof File)
  4047. ) {
  4048. return true;
  4049. }
  4050. if (isArray(obj)) {
  4051. for (var i = 0; i < obj.length; i++) {
  4052. if (_hasBinary(obj[i])) {
  4053. return true;
  4054. }
  4055. }
  4056. } else if (obj && 'object' == typeof obj) {
  4057. if (obj.toJSON) {
  4058. obj = obj.toJSON();
  4059. }
  4060. for (var key in obj) {
  4061. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  4062. return true;
  4063. }
  4064. }
  4065. }
  4066. return false;
  4067. }
  4068. return _hasBinary(data);
  4069. }
  4070. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4071. },{"isarray":32}],32:[function(_dereq_,module,exports){
  4072. module.exports = Array.isArray || function (arr) {
  4073. return Object.prototype.toString.call(arr) == '[object Array]';
  4074. };
  4075. },{}],33:[function(_dereq_,module,exports){
  4076. (function (global){
  4077. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  4078. ;(function(root) {
  4079. // Detect free variables `exports`
  4080. var freeExports = typeof exports == 'object' && exports;
  4081. // Detect free variable `module`
  4082. var freeModule = typeof module == 'object' && module &&
  4083. module.exports == freeExports && module;
  4084. // Detect free variable `global`, from Node.js or Browserified code,
  4085. // and use it as `root`
  4086. var freeGlobal = typeof global == 'object' && global;
  4087. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  4088. root = freeGlobal;
  4089. }
  4090. /*--------------------------------------------------------------------------*/
  4091. var stringFromCharCode = String.fromCharCode;
  4092. // Taken from http://mths.be/punycode
  4093. function ucs2decode(string) {
  4094. var output = [];
  4095. var counter = 0;
  4096. var length = string.length;
  4097. var value;
  4098. var extra;
  4099. while (counter < length) {
  4100. value = string.charCodeAt(counter++);
  4101. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  4102. // high surrogate, and there is a next character
  4103. extra = string.charCodeAt(counter++);
  4104. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  4105. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  4106. } else {
  4107. // unmatched surrogate; only append this code unit, in case the next
  4108. // code unit is the high surrogate of a surrogate pair
  4109. output.push(value);
  4110. counter--;
  4111. }
  4112. } else {
  4113. output.push(value);
  4114. }
  4115. }
  4116. return output;
  4117. }
  4118. // Taken from http://mths.be/punycode
  4119. function ucs2encode(array) {
  4120. var length = array.length;
  4121. var index = -1;
  4122. var value;
  4123. var output = '';
  4124. while (++index < length) {
  4125. value = array[index];
  4126. if (value > 0xFFFF) {
  4127. value -= 0x10000;
  4128. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  4129. value = 0xDC00 | value & 0x3FF;
  4130. }
  4131. output += stringFromCharCode(value);
  4132. }
  4133. return output;
  4134. }
  4135. /*--------------------------------------------------------------------------*/
  4136. function createByte(codePoint, shift) {
  4137. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  4138. }
  4139. function encodeCodePoint(codePoint) {
  4140. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  4141. return stringFromCharCode(codePoint);
  4142. }
  4143. var symbol = '';
  4144. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  4145. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  4146. }
  4147. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  4148. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  4149. symbol += createByte(codePoint, 6);
  4150. }
  4151. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  4152. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  4153. symbol += createByte(codePoint, 12);
  4154. symbol += createByte(codePoint, 6);
  4155. }
  4156. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  4157. return symbol;
  4158. }
  4159. function utf8encode(string) {
  4160. var codePoints = ucs2decode(string);
  4161. // console.log(JSON.stringify(codePoints.map(function(x) {
  4162. // return 'U+' + x.toString(16).toUpperCase();
  4163. // })));
  4164. var length = codePoints.length;
  4165. var index = -1;
  4166. var codePoint;
  4167. var byteString = '';
  4168. while (++index < length) {
  4169. codePoint = codePoints[index];
  4170. byteString += encodeCodePoint(codePoint);
  4171. }
  4172. return byteString;
  4173. }
  4174. /*--------------------------------------------------------------------------*/
  4175. function readContinuationByte() {
  4176. if (byteIndex >= byteCount) {
  4177. throw Error('Invalid byte index');
  4178. }
  4179. var continuationByte = byteArray[byteIndex] & 0xFF;
  4180. byteIndex++;
  4181. if ((continuationByte & 0xC0) == 0x80) {
  4182. return continuationByte & 0x3F;
  4183. }
  4184. // If we end up here, it’s not a continuation byte
  4185. throw Error('Invalid continuation byte');
  4186. }
  4187. function decodeSymbol() {
  4188. var byte1;
  4189. var byte2;
  4190. var byte3;
  4191. var byte4;
  4192. var codePoint;
  4193. if (byteIndex > byteCount) {
  4194. throw Error('Invalid byte index');
  4195. }
  4196. if (byteIndex == byteCount) {
  4197. return false;
  4198. }
  4199. // Read first byte
  4200. byte1 = byteArray[byteIndex] & 0xFF;
  4201. byteIndex++;
  4202. // 1-byte sequence (no continuation bytes)
  4203. if ((byte1 & 0x80) == 0) {
  4204. return byte1;
  4205. }
  4206. // 2-byte sequence
  4207. if ((byte1 & 0xE0) == 0xC0) {
  4208. var byte2 = readContinuationByte();
  4209. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  4210. if (codePoint >= 0x80) {
  4211. return codePoint;
  4212. } else {
  4213. throw Error('Invalid continuation byte');
  4214. }
  4215. }
  4216. // 3-byte sequence (may include unpaired surrogates)
  4217. if ((byte1 & 0xF0) == 0xE0) {
  4218. byte2 = readContinuationByte();
  4219. byte3 = readContinuationByte();
  4220. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  4221. if (codePoint >= 0x0800) {
  4222. return codePoint;
  4223. } else {
  4224. throw Error('Invalid continuation byte');
  4225. }
  4226. }
  4227. // 4-byte sequence
  4228. if ((byte1 & 0xF8) == 0xF0) {
  4229. byte2 = readContinuationByte();
  4230. byte3 = readContinuationByte();
  4231. byte4 = readContinuationByte();
  4232. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  4233. (byte3 << 0x06) | byte4;
  4234. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  4235. return codePoint;
  4236. }
  4237. }
  4238. throw Error('Invalid UTF-8 detected');
  4239. }
  4240. var byteArray;
  4241. var byteCount;
  4242. var byteIndex;
  4243. function utf8decode(byteString) {
  4244. byteArray = ucs2decode(byteString);
  4245. byteCount = byteArray.length;
  4246. byteIndex = 0;
  4247. var codePoints = [];
  4248. var tmp;
  4249. while ((tmp = decodeSymbol()) !== false) {
  4250. codePoints.push(tmp);
  4251. }
  4252. return ucs2encode(codePoints);
  4253. }
  4254. /*--------------------------------------------------------------------------*/
  4255. var utf8 = {
  4256. 'version': '2.0.0',
  4257. 'encode': utf8encode,
  4258. 'decode': utf8decode
  4259. };
  4260. // Some AMD build optimizers, like r.js, check for specific condition patterns
  4261. // like the following:
  4262. if (
  4263. typeof define == 'function' &&
  4264. typeof define.amd == 'object' &&
  4265. define.amd
  4266. ) {
  4267. define(function() {
  4268. return utf8;
  4269. });
  4270. } else if (freeExports && !freeExports.nodeType) {
  4271. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  4272. freeModule.exports = utf8;
  4273. } else { // in Narwhal or RingoJS v0.7.0-
  4274. var object = {};
  4275. var hasOwnProperty = object.hasOwnProperty;
  4276. for (var key in utf8) {
  4277. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  4278. }
  4279. }
  4280. } else { // in Rhino or a web browser
  4281. root.utf8 = utf8;
  4282. }
  4283. }(this));
  4284. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4285. },{}],34:[function(_dereq_,module,exports){
  4286. (function (global){
  4287. /**
  4288. * JSON parse.
  4289. *
  4290. * @see Based on jQuery#parseJSON (MIT) and JSON2
  4291. * @api private
  4292. */
  4293. var rvalidchars = /^[\],:{}\s]*$/;
  4294. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  4295. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  4296. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  4297. var rtrimLeft = /^\s+/;
  4298. var rtrimRight = /\s+$/;
  4299. module.exports = function parsejson(data) {
  4300. if ('string' != typeof data || !data) {
  4301. return null;
  4302. }
  4303. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  4304. // Attempt to parse using the native JSON parser first
  4305. if (global.JSON && JSON.parse) {
  4306. return JSON.parse(data);
  4307. }
  4308. if (rvalidchars.test(data.replace(rvalidescape, '@')
  4309. .replace(rvalidtokens, ']')
  4310. .replace(rvalidbraces, ''))) {
  4311. return (new Function('return ' + data))();
  4312. }
  4313. };
  4314. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4315. },{}],35:[function(_dereq_,module,exports){
  4316. /**
  4317. * Compiles a querystring
  4318. * Returns string representation of the object
  4319. *
  4320. * @param {Object}
  4321. * @api private
  4322. */
  4323. exports.encode = function (obj) {
  4324. var str = '';
  4325. for (var i in obj) {
  4326. if (obj.hasOwnProperty(i)) {
  4327. if (str.length) str += '&';
  4328. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  4329. }
  4330. }
  4331. return str;
  4332. };
  4333. /**
  4334. * Parses a simple querystring into an object
  4335. *
  4336. * @param {String} qs
  4337. * @api private
  4338. */
  4339. exports.decode = function(qs){
  4340. var qry = {};
  4341. var pairs = qs.split('&');
  4342. for (var i = 0, l = pairs.length; i < l; i++) {
  4343. var pair = pairs[i].split('=');
  4344. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  4345. }
  4346. return qry;
  4347. };
  4348. },{}],36:[function(_dereq_,module,exports){
  4349. /**
  4350. * Parses an URI
  4351. *
  4352. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  4353. * @api private
  4354. */
  4355. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  4356. var parts = [
  4357. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  4358. ];
  4359. module.exports = function parseuri(str) {
  4360. var src = str,
  4361. b = str.indexOf('['),
  4362. e = str.indexOf(']');
  4363. if (b != -1 && e != -1) {
  4364. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  4365. }
  4366. var m = re.exec(str || ''),
  4367. uri = {},
  4368. i = 14;
  4369. while (i--) {
  4370. uri[parts[i]] = m[i] || '';
  4371. }
  4372. if (b != -1 && e != -1) {
  4373. uri.source = src;
  4374. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  4375. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  4376. uri.ipv6uri = true;
  4377. }
  4378. return uri;
  4379. };
  4380. },{}],37:[function(_dereq_,module,exports){
  4381. /**
  4382. * Module dependencies.
  4383. */
  4384. var global = (function() { return this; })();
  4385. /**
  4386. * WebSocket constructor.
  4387. */
  4388. var WebSocket = global.WebSocket || global.MozWebSocket;
  4389. /**
  4390. * Module exports.
  4391. */
  4392. module.exports = WebSocket ? ws : null;
  4393. /**
  4394. * WebSocket constructor.
  4395. *
  4396. * The third `opts` options object gets ignored in web browsers, since it's
  4397. * non-standard, and throws a TypeError if passed to the constructor.
  4398. * See: https://github.com/einaros/ws/issues/227
  4399. *
  4400. * @param {String} uri
  4401. * @param {Array} protocols (optional)
  4402. * @param {Object) opts (optional)
  4403. * @api public
  4404. */
  4405. function ws(uri, protocols, opts) {
  4406. var instance;
  4407. if (protocols) {
  4408. instance = new WebSocket(uri, protocols);
  4409. } else {
  4410. instance = new WebSocket(uri);
  4411. }
  4412. return instance;
  4413. }
  4414. if (WebSocket) ws.prototype = WebSocket.prototype;
  4415. },{}],38:[function(_dereq_,module,exports){
  4416. (function (global){
  4417. /*
  4418. * Module requirements.
  4419. */
  4420. var isArray = _dereq_('isarray');
  4421. /**
  4422. * Module exports.
  4423. */
  4424. module.exports = hasBinary;
  4425. /**
  4426. * Checks for binary data.
  4427. *
  4428. * Right now only Buffer and ArrayBuffer are supported..
  4429. *
  4430. * @param {Object} anything
  4431. * @api public
  4432. */
  4433. function hasBinary(data) {
  4434. function _hasBinary(obj) {
  4435. if (!obj) return false;
  4436. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  4437. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  4438. (global.Blob && obj instanceof Blob) ||
  4439. (global.File && obj instanceof File)
  4440. ) {
  4441. return true;
  4442. }
  4443. if (isArray(obj)) {
  4444. for (var i = 0; i < obj.length; i++) {
  4445. if (_hasBinary(obj[i])) {
  4446. return true;
  4447. }
  4448. }
  4449. } else if (obj && 'object' == typeof obj) {
  4450. if (obj.toJSON) {
  4451. obj = obj.toJSON();
  4452. }
  4453. for (var key in obj) {
  4454. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  4455. return true;
  4456. }
  4457. }
  4458. }
  4459. return false;
  4460. }
  4461. return _hasBinary(data);
  4462. }
  4463. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4464. },{"isarray":39}],39:[function(_dereq_,module,exports){
  4465. module.exports=_dereq_(32)
  4466. },{}],40:[function(_dereq_,module,exports){
  4467. /**
  4468. * Module dependencies.
  4469. */
  4470. var global = _dereq_('global');
  4471. /**
  4472. * Module exports.
  4473. *
  4474. * Logic borrowed from Modernizr:
  4475. *
  4476. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  4477. */
  4478. try {
  4479. module.exports = 'XMLHttpRequest' in global &&
  4480. 'withCredentials' in new global.XMLHttpRequest();
  4481. } catch (err) {
  4482. // if XMLHttp support is disabled in IE then it will throw
  4483. // when trying to create
  4484. module.exports = false;
  4485. }
  4486. },{"global":41}],41:[function(_dereq_,module,exports){
  4487. /**
  4488. * Returns `this`. Execute this without a "context" (i.e. without it being
  4489. * attached to an object of the left-hand side), and `this` points to the
  4490. * "global" scope of the current JS execution.
  4491. */
  4492. module.exports = (function () { return this; })();
  4493. },{}],42:[function(_dereq_,module,exports){
  4494. var indexOf = [].indexOf;
  4495. module.exports = function(arr, obj){
  4496. if (indexOf) return arr.indexOf(obj);
  4497. for (var i = 0; i < arr.length; ++i) {
  4498. if (arr[i] === obj) return i;
  4499. }
  4500. return -1;
  4501. };
  4502. },{}],43:[function(_dereq_,module,exports){
  4503. /**
  4504. * HOP ref.
  4505. */
  4506. var has = Object.prototype.hasOwnProperty;
  4507. /**
  4508. * Return own keys in `obj`.
  4509. *
  4510. * @param {Object} obj
  4511. * @return {Array}
  4512. * @api public
  4513. */
  4514. exports.keys = Object.keys || function(obj){
  4515. var keys = [];
  4516. for (var key in obj) {
  4517. if (has.call(obj, key)) {
  4518. keys.push(key);
  4519. }
  4520. }
  4521. return keys;
  4522. };
  4523. /**
  4524. * Return own values in `obj`.
  4525. *
  4526. * @param {Object} obj
  4527. * @return {Array}
  4528. * @api public
  4529. */
  4530. exports.values = function(obj){
  4531. var vals = [];
  4532. for (var key in obj) {
  4533. if (has.call(obj, key)) {
  4534. vals.push(obj[key]);
  4535. }
  4536. }
  4537. return vals;
  4538. };
  4539. /**
  4540. * Merge `b` into `a`.
  4541. *
  4542. * @param {Object} a
  4543. * @param {Object} b
  4544. * @return {Object} a
  4545. * @api public
  4546. */
  4547. exports.merge = function(a, b){
  4548. for (var key in b) {
  4549. if (has.call(b, key)) {
  4550. a[key] = b[key];
  4551. }
  4552. }
  4553. return a;
  4554. };
  4555. /**
  4556. * Return length of `obj`.
  4557. *
  4558. * @param {Object} obj
  4559. * @return {Number}
  4560. * @api public
  4561. */
  4562. exports.length = function(obj){
  4563. return exports.keys(obj).length;
  4564. };
  4565. /**
  4566. * Check if `obj` is empty.
  4567. *
  4568. * @param {Object} obj
  4569. * @return {Boolean}
  4570. * @api public
  4571. */
  4572. exports.isEmpty = function(obj){
  4573. return 0 == exports.length(obj);
  4574. };
  4575. },{}],44:[function(_dereq_,module,exports){
  4576. /**
  4577. * Parses an URI
  4578. *
  4579. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  4580. * @api private
  4581. */
  4582. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  4583. var parts = [
  4584. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  4585. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  4586. ];
  4587. module.exports = function parseuri(str) {
  4588. var m = re.exec(str || '')
  4589. , uri = {}
  4590. , i = 14;
  4591. while (i--) {
  4592. uri[parts[i]] = m[i] || '';
  4593. }
  4594. return uri;
  4595. };
  4596. },{}],45:[function(_dereq_,module,exports){
  4597. (function (global){
  4598. /*global Blob,File*/
  4599. /**
  4600. * Module requirements
  4601. */
  4602. var isArray = _dereq_('isarray');
  4603. var isBuf = _dereq_('./is-buffer');
  4604. /**
  4605. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  4606. * Anything with blobs or files should be fed through removeBlobs before coming
  4607. * here.
  4608. *
  4609. * @param {Object} packet - socket.io event packet
  4610. * @return {Object} with deconstructed packet and list of buffers
  4611. * @api public
  4612. */
  4613. exports.deconstructPacket = function(packet){
  4614. var buffers = [];
  4615. var packetData = packet.data;
  4616. function _deconstructPacket(data) {
  4617. if (!data) return data;
  4618. if (isBuf(data)) {
  4619. var placeholder = { _placeholder: true, num: buffers.length };
  4620. buffers.push(data);
  4621. return placeholder;
  4622. } else if (isArray(data)) {
  4623. var newData = new Array(data.length);
  4624. for (var i = 0; i < data.length; i++) {
  4625. newData[i] = _deconstructPacket(data[i]);
  4626. }
  4627. return newData;
  4628. } else if ('object' == typeof data && !(data instanceof Date)) {
  4629. var newData = {};
  4630. for (var key in data) {
  4631. newData[key] = _deconstructPacket(data[key]);
  4632. }
  4633. return newData;
  4634. }
  4635. return data;
  4636. }
  4637. var pack = packet;
  4638. pack.data = _deconstructPacket(packetData);
  4639. pack.attachments = buffers.length; // number of binary 'attachments'
  4640. return {packet: pack, buffers: buffers};
  4641. };
  4642. /**
  4643. * Reconstructs a binary packet from its placeholder packet and buffers
  4644. *
  4645. * @param {Object} packet - event packet with placeholders
  4646. * @param {Array} buffers - binary buffers to put in placeholder positions
  4647. * @return {Object} reconstructed packet
  4648. * @api public
  4649. */
  4650. exports.reconstructPacket = function(packet, buffers) {
  4651. var curPlaceHolder = 0;
  4652. function _reconstructPacket(data) {
  4653. if (data && data._placeholder) {
  4654. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  4655. return buf;
  4656. } else if (isArray(data)) {
  4657. for (var i = 0; i < data.length; i++) {
  4658. data[i] = _reconstructPacket(data[i]);
  4659. }
  4660. return data;
  4661. } else if (data && 'object' == typeof data) {
  4662. for (var key in data) {
  4663. data[key] = _reconstructPacket(data[key]);
  4664. }
  4665. return data;
  4666. }
  4667. return data;
  4668. }
  4669. packet.data = _reconstructPacket(packet.data);
  4670. packet.attachments = undefined; // no longer useful
  4671. return packet;
  4672. };
  4673. /**
  4674. * Asynchronously removes Blobs or Files from data via
  4675. * FileReader's readAsArrayBuffer method. Used before encoding
  4676. * data as msgpack. Calls callback with the blobless data.
  4677. *
  4678. * @param {Object} data
  4679. * @param {Function} callback
  4680. * @api private
  4681. */
  4682. exports.removeBlobs = function(data, callback) {
  4683. function _removeBlobs(obj, curKey, containingObject) {
  4684. if (!obj) return obj;
  4685. // convert any blob
  4686. if ((global.Blob && obj instanceof Blob) ||
  4687. (global.File && obj instanceof File)) {
  4688. pendingBlobs++;
  4689. // async filereader
  4690. var fileReader = new FileReader();
  4691. fileReader.onload = function() { // this.result == arraybuffer
  4692. if (containingObject) {
  4693. containingObject[curKey] = this.result;
  4694. }
  4695. else {
  4696. bloblessData = this.result;
  4697. }
  4698. // if nothing pending its callback time
  4699. if(! --pendingBlobs) {
  4700. callback(bloblessData);
  4701. }
  4702. };
  4703. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  4704. } else if (isArray(obj)) { // handle array
  4705. for (var i = 0; i < obj.length; i++) {
  4706. _removeBlobs(obj[i], i, obj);
  4707. }
  4708. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  4709. for (var key in obj) {
  4710. _removeBlobs(obj[key], key, obj);
  4711. }
  4712. }
  4713. }
  4714. var pendingBlobs = 0;
  4715. var bloblessData = data;
  4716. _removeBlobs(bloblessData);
  4717. if (!pendingBlobs) {
  4718. callback(bloblessData);
  4719. }
  4720. };
  4721. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4722. },{"./is-buffer":47,"isarray":48}],46:[function(_dereq_,module,exports){
  4723. /**
  4724. * Module dependencies.
  4725. */
  4726. var debug = _dereq_('debug')('socket.io-parser');
  4727. var json = _dereq_('json3');
  4728. var isArray = _dereq_('isarray');
  4729. var Emitter = _dereq_('component-emitter');
  4730. var binary = _dereq_('./binary');
  4731. var isBuf = _dereq_('./is-buffer');
  4732. /**
  4733. * Protocol version.
  4734. *
  4735. * @api public
  4736. */
  4737. exports.protocol = 4;
  4738. /**
  4739. * Packet types.
  4740. *
  4741. * @api public
  4742. */
  4743. exports.types = [
  4744. 'CONNECT',
  4745. 'DISCONNECT',
  4746. 'EVENT',
  4747. 'BINARY_EVENT',
  4748. 'ACK',
  4749. 'BINARY_ACK',
  4750. 'ERROR'
  4751. ];
  4752. /**
  4753. * Packet type `connect`.
  4754. *
  4755. * @api public
  4756. */
  4757. exports.CONNECT = 0;
  4758. /**
  4759. * Packet type `disconnect`.
  4760. *
  4761. * @api public
  4762. */
  4763. exports.DISCONNECT = 1;
  4764. /**
  4765. * Packet type `event`.
  4766. *
  4767. * @api public
  4768. */
  4769. exports.EVENT = 2;
  4770. /**
  4771. * Packet type `ack`.
  4772. *
  4773. * @api public
  4774. */
  4775. exports.ACK = 3;
  4776. /**
  4777. * Packet type `error`.
  4778. *
  4779. * @api public
  4780. */
  4781. exports.ERROR = 4;
  4782. /**
  4783. * Packet type 'binary event'
  4784. *
  4785. * @api public
  4786. */
  4787. exports.BINARY_EVENT = 5;
  4788. /**
  4789. * Packet type `binary ack`. For acks with binary arguments.
  4790. *
  4791. * @api public
  4792. */
  4793. exports.BINARY_ACK = 6;
  4794. /**
  4795. * Encoder constructor.
  4796. *
  4797. * @api public
  4798. */
  4799. exports.Encoder = Encoder;
  4800. /**
  4801. * Decoder constructor.
  4802. *
  4803. * @api public
  4804. */
  4805. exports.Decoder = Decoder;
  4806. /**
  4807. * A socket.io Encoder instance
  4808. *
  4809. * @api public
  4810. */
  4811. function Encoder() {}
  4812. /**
  4813. * Encode a packet as a single string if non-binary, or as a
  4814. * buffer sequence, depending on packet type.
  4815. *
  4816. * @param {Object} obj - packet object
  4817. * @param {Function} callback - function to handle encodings (likely engine.write)
  4818. * @return Calls callback with Array of encodings
  4819. * @api public
  4820. */
  4821. Encoder.prototype.encode = function(obj, callback){
  4822. debug('encoding packet %j', obj);
  4823. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  4824. encodeAsBinary(obj, callback);
  4825. }
  4826. else {
  4827. var encoding = encodeAsString(obj);
  4828. callback([encoding]);
  4829. }
  4830. };
  4831. /**
  4832. * Encode packet as string.
  4833. *
  4834. * @param {Object} packet
  4835. * @return {String} encoded
  4836. * @api private
  4837. */
  4838. function encodeAsString(obj) {
  4839. var str = '';
  4840. var nsp = false;
  4841. // first is type
  4842. str += obj.type;
  4843. // attachments if we have them
  4844. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  4845. str += obj.attachments;
  4846. str += '-';
  4847. }
  4848. // if we have a namespace other than `/`
  4849. // we append it followed by a comma `,`
  4850. if (obj.nsp && '/' != obj.nsp) {
  4851. nsp = true;
  4852. str += obj.nsp;
  4853. }
  4854. // immediately followed by the id
  4855. if (null != obj.id) {
  4856. if (nsp) {
  4857. str += ',';
  4858. nsp = false;
  4859. }
  4860. str += obj.id;
  4861. }
  4862. // json data
  4863. if (null != obj.data) {
  4864. if (nsp) str += ',';
  4865. str += json.stringify(obj.data);
  4866. }
  4867. debug('encoded %j as %s', obj, str);
  4868. return str;
  4869. }
  4870. /**
  4871. * Encode packet as 'buffer sequence' by removing blobs, and
  4872. * deconstructing packet into object with placeholders and
  4873. * a list of buffers.
  4874. *
  4875. * @param {Object} packet
  4876. * @return {Buffer} encoded
  4877. * @api private
  4878. */
  4879. function encodeAsBinary(obj, callback) {
  4880. function writeEncoding(bloblessData) {
  4881. var deconstruction = binary.deconstructPacket(bloblessData);
  4882. var pack = encodeAsString(deconstruction.packet);
  4883. var buffers = deconstruction.buffers;
  4884. buffers.unshift(pack); // add packet info to beginning of data list
  4885. callback(buffers); // write all the buffers
  4886. }
  4887. binary.removeBlobs(obj, writeEncoding);
  4888. }
  4889. /**
  4890. * A socket.io Decoder instance
  4891. *
  4892. * @return {Object} decoder
  4893. * @api public
  4894. */
  4895. function Decoder() {
  4896. this.reconstructor = null;
  4897. }
  4898. /**
  4899. * Mix in `Emitter` with Decoder.
  4900. */
  4901. Emitter(Decoder.prototype);
  4902. /**
  4903. * Decodes an ecoded packet string into packet JSON.
  4904. *
  4905. * @param {String} obj - encoded packet
  4906. * @return {Object} packet
  4907. * @api public
  4908. */
  4909. Decoder.prototype.add = function(obj) {
  4910. var packet;
  4911. if ('string' == typeof obj) {
  4912. packet = decodeString(obj);
  4913. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  4914. this.reconstructor = new BinaryReconstructor(packet);
  4915. // no attachments, labeled binary but no binary data to follow
  4916. if (this.reconstructor.reconPack.attachments === 0) {
  4917. this.emit('decoded', packet);
  4918. }
  4919. } else { // non-binary full packet
  4920. this.emit('decoded', packet);
  4921. }
  4922. }
  4923. else if (isBuf(obj) || obj.base64) { // raw binary data
  4924. if (!this.reconstructor) {
  4925. throw new Error('got binary data when not reconstructing a packet');
  4926. } else {
  4927. packet = this.reconstructor.takeBinaryData(obj);
  4928. if (packet) { // received final buffer
  4929. this.reconstructor = null;
  4930. this.emit('decoded', packet);
  4931. }
  4932. }
  4933. }
  4934. else {
  4935. throw new Error('Unknown type: ' + obj);
  4936. }
  4937. };
  4938. /**
  4939. * Decode a packet String (JSON data)
  4940. *
  4941. * @param {String} str
  4942. * @return {Object} packet
  4943. * @api private
  4944. */
  4945. function decodeString(str) {
  4946. var p = {};
  4947. var i = 0;
  4948. // look up type
  4949. p.type = Number(str.charAt(0));
  4950. if (null == exports.types[p.type]) return error();
  4951. // look up attachments if type binary
  4952. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  4953. var buf = '';
  4954. while (str.charAt(++i) != '-') {
  4955. buf += str.charAt(i);
  4956. if (i == str.length) break;
  4957. }
  4958. if (buf != Number(buf) || str.charAt(i) != '-') {
  4959. throw new Error('Illegal attachments');
  4960. }
  4961. p.attachments = Number(buf);
  4962. }
  4963. // look up namespace (if any)
  4964. if ('/' == str.charAt(i + 1)) {
  4965. p.nsp = '';
  4966. while (++i) {
  4967. var c = str.charAt(i);
  4968. if (',' == c) break;
  4969. p.nsp += c;
  4970. if (i == str.length) break;
  4971. }
  4972. } else {
  4973. p.nsp = '/';
  4974. }
  4975. // look up id
  4976. var next = str.charAt(i + 1);
  4977. if ('' !== next && Number(next) == next) {
  4978. p.id = '';
  4979. while (++i) {
  4980. var c = str.charAt(i);
  4981. if (null == c || Number(c) != c) {
  4982. --i;
  4983. break;
  4984. }
  4985. p.id += str.charAt(i);
  4986. if (i == str.length) break;
  4987. }
  4988. p.id = Number(p.id);
  4989. }
  4990. // look up json data
  4991. if (str.charAt(++i)) {
  4992. try {
  4993. p.data = json.parse(str.substr(i));
  4994. } catch(e){
  4995. return error();
  4996. }
  4997. }
  4998. debug('decoded %s as %j', str, p);
  4999. return p;
  5000. }
  5001. /**
  5002. * Deallocates a parser's resources
  5003. *
  5004. * @api public
  5005. */
  5006. Decoder.prototype.destroy = function() {
  5007. if (this.reconstructor) {
  5008. this.reconstructor.finishedReconstruction();
  5009. }
  5010. };
  5011. /**
  5012. * A manager of a binary event's 'buffer sequence'. Should
  5013. * be constructed whenever a packet of type BINARY_EVENT is
  5014. * decoded.
  5015. *
  5016. * @param {Object} packet
  5017. * @return {BinaryReconstructor} initialized reconstructor
  5018. * @api private
  5019. */
  5020. function BinaryReconstructor(packet) {
  5021. this.reconPack = packet;
  5022. this.buffers = [];
  5023. }
  5024. /**
  5025. * Method to be called when binary data received from connection
  5026. * after a BINARY_EVENT packet.
  5027. *
  5028. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  5029. * @return {null | Object} returns null if more binary data is expected or
  5030. * a reconstructed packet object if all buffers have been received.
  5031. * @api private
  5032. */
  5033. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  5034. this.buffers.push(binData);
  5035. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  5036. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  5037. this.finishedReconstruction();
  5038. return packet;
  5039. }
  5040. return null;
  5041. };
  5042. /**
  5043. * Cleans up binary packet reconstruction variables.
  5044. *
  5045. * @api private
  5046. */
  5047. BinaryReconstructor.prototype.finishedReconstruction = function() {
  5048. this.reconPack = null;
  5049. this.buffers = [];
  5050. };
  5051. function error(data){
  5052. return {
  5053. type: exports.ERROR,
  5054. data: 'parser error'
  5055. };
  5056. }
  5057. },{"./binary":45,"./is-buffer":47,"component-emitter":9,"debug":10,"isarray":48,"json3":49}],47:[function(_dereq_,module,exports){
  5058. (function (global){
  5059. module.exports = isBuf;
  5060. /**
  5061. * Returns true if obj is a buffer or an arraybuffer.
  5062. *
  5063. * @api private
  5064. */
  5065. function isBuf(obj) {
  5066. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  5067. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  5068. }
  5069. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5070. },{}],48:[function(_dereq_,module,exports){
  5071. module.exports=_dereq_(32)
  5072. },{}],49:[function(_dereq_,module,exports){
  5073. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  5074. ;(function (window) {
  5075. // Convenience aliases.
  5076. var getClass = {}.toString, isProperty, forEach, undef;
  5077. // Detect the `define` function exposed by asynchronous module loaders. The
  5078. // strict `define` check is necessary for compatibility with `r.js`.
  5079. var isLoader = typeof define === "function" && define.amd;
  5080. // Detect native implementations.
  5081. var nativeJSON = typeof JSON == "object" && JSON;
  5082. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  5083. // available.
  5084. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  5085. if (JSON3 && nativeJSON) {
  5086. // Explicitly delegate to the native `stringify` and `parse`
  5087. // implementations in CommonJS environments.
  5088. JSON3.stringify = nativeJSON.stringify;
  5089. JSON3.parse = nativeJSON.parse;
  5090. } else {
  5091. // Export for web browsers, JavaScript engines, and asynchronous module
  5092. // loaders, using the global `JSON` object if available.
  5093. JSON3 = window.JSON = nativeJSON || {};
  5094. }
  5095. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  5096. var isExtended = new Date(-3509827334573292);
  5097. try {
  5098. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  5099. // results for certain dates in Opera >= 10.53.
  5100. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  5101. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  5102. // but clips the values returned by the date methods to the range of
  5103. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  5104. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  5105. } catch (exception) {}
  5106. // Internal: Determines whether the native `JSON.stringify` and `parse`
  5107. // implementations are spec-compliant. Based on work by Ken Snyder.
  5108. function has(name) {
  5109. if (has[name] !== undef) {
  5110. // Return cached feature test result.
  5111. return has[name];
  5112. }
  5113. var isSupported;
  5114. if (name == "bug-string-char-index") {
  5115. // IE <= 7 doesn't support accessing string characters using square
  5116. // bracket notation. IE 8 only supports this for primitives.
  5117. isSupported = "a"[0] != "a";
  5118. } else if (name == "json") {
  5119. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  5120. // supported.
  5121. isSupported = has("json-stringify") && has("json-parse");
  5122. } else {
  5123. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  5124. // Test `JSON.stringify`.
  5125. if (name == "json-stringify") {
  5126. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  5127. if (stringifySupported) {
  5128. // A test function object with a custom `toJSON` method.
  5129. (value = function () {
  5130. return 1;
  5131. }).toJSON = value;
  5132. try {
  5133. stringifySupported =
  5134. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  5135. // primitives as object literals.
  5136. stringify(0) === "0" &&
  5137. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  5138. // literals.
  5139. stringify(new Number()) === "0" &&
  5140. stringify(new String()) == '""' &&
  5141. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  5142. // does not define a canonical JSON representation (this applies to
  5143. // objects with `toJSON` properties as well, *unless* they are nested
  5144. // within an object or array).
  5145. stringify(getClass) === undef &&
  5146. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  5147. // FF 3.1b3 pass this test.
  5148. stringify(undef) === undef &&
  5149. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  5150. // respectively, if the value is omitted entirely.
  5151. stringify() === undef &&
  5152. // FF 3.1b1, 2 throw an error if the given value is not a number,
  5153. // string, array, object, Boolean, or `null` literal. This applies to
  5154. // objects with custom `toJSON` methods as well, unless they are nested
  5155. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  5156. // methods entirely.
  5157. stringify(value) === "1" &&
  5158. stringify([value]) == "[1]" &&
  5159. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  5160. // `"[null]"`.
  5161. stringify([undef]) == "[null]" &&
  5162. // YUI 3.0.0b1 fails to serialize `null` literals.
  5163. stringify(null) == "null" &&
  5164. // FF 3.1b1, 2 halts serialization if an array contains a function:
  5165. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  5166. // elides non-JSON values from objects and arrays, unless they
  5167. // define custom `toJSON` methods.
  5168. stringify([undef, getClass, null]) == "[null,null,null]" &&
  5169. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  5170. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  5171. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  5172. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  5173. stringify(null, value) === "1" &&
  5174. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  5175. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  5176. // serialize extended years.
  5177. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  5178. // The milliseconds are optional in ES 5, but required in 5.1.
  5179. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  5180. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  5181. // four-digit years instead of six-digit years. Credits: @Yaffle.
  5182. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  5183. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  5184. // values less than 1000. Credits: @Yaffle.
  5185. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  5186. } catch (exception) {
  5187. stringifySupported = false;
  5188. }
  5189. }
  5190. isSupported = stringifySupported;
  5191. }
  5192. // Test `JSON.parse`.
  5193. if (name == "json-parse") {
  5194. var parse = JSON3.parse;
  5195. if (typeof parse == "function") {
  5196. try {
  5197. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  5198. // Conforming implementations should also coerce the initial argument to
  5199. // a string prior to parsing.
  5200. if (parse("0") === 0 && !parse(false)) {
  5201. // Simple parsing test.
  5202. value = parse(serialized);
  5203. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  5204. if (parseSupported) {
  5205. try {
  5206. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  5207. parseSupported = !parse('"\t"');
  5208. } catch (exception) {}
  5209. if (parseSupported) {
  5210. try {
  5211. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  5212. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  5213. // certain octal literals.
  5214. parseSupported = parse("01") !== 1;
  5215. } catch (exception) {}
  5216. }
  5217. if (parseSupported) {
  5218. try {
  5219. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  5220. // points. These environments, along with FF 3.1b1 and 2,
  5221. // also allow trailing commas in JSON objects and arrays.
  5222. parseSupported = parse("1.") !== 1;
  5223. } catch (exception) {}
  5224. }
  5225. }
  5226. }
  5227. } catch (exception) {
  5228. parseSupported = false;
  5229. }
  5230. }
  5231. isSupported = parseSupported;
  5232. }
  5233. }
  5234. return has[name] = !!isSupported;
  5235. }
  5236. if (!has("json")) {
  5237. // Common `[[Class]]` name aliases.
  5238. var functionClass = "[object Function]";
  5239. var dateClass = "[object Date]";
  5240. var numberClass = "[object Number]";
  5241. var stringClass = "[object String]";
  5242. var arrayClass = "[object Array]";
  5243. var booleanClass = "[object Boolean]";
  5244. // Detect incomplete support for accessing string characters by index.
  5245. var charIndexBuggy = has("bug-string-char-index");
  5246. // Define additional utility methods if the `Date` methods are buggy.
  5247. if (!isExtended) {
  5248. var floor = Math.floor;
  5249. // A mapping between the months of the year and the number of days between
  5250. // January 1st and the first of the respective month.
  5251. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  5252. // Internal: Calculates the number of days between the Unix epoch and the
  5253. // first day of the given month.
  5254. var getDay = function (year, month) {
  5255. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  5256. };
  5257. }
  5258. // Internal: Determines if a property is a direct property of the given
  5259. // object. Delegates to the native `Object#hasOwnProperty` method.
  5260. if (!(isProperty = {}.hasOwnProperty)) {
  5261. isProperty = function (property) {
  5262. var members = {}, constructor;
  5263. if ((members.__proto__ = null, members.__proto__ = {
  5264. // The *proto* property cannot be set multiple times in recent
  5265. // versions of Firefox and SeaMonkey.
  5266. "toString": 1
  5267. }, members).toString != getClass) {
  5268. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  5269. // supports the mutable *proto* property.
  5270. isProperty = function (property) {
  5271. // Capture and break the object's prototype chain (see section 8.6.2
  5272. // of the ES 5.1 spec). The parenthesized expression prevents an
  5273. // unsafe transformation by the Closure Compiler.
  5274. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  5275. // Restore the original prototype chain.
  5276. this.__proto__ = original;
  5277. return result;
  5278. };
  5279. } else {
  5280. // Capture a reference to the top-level `Object` constructor.
  5281. constructor = members.constructor;
  5282. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  5283. // other environments.
  5284. isProperty = function (property) {
  5285. var parent = (this.constructor || constructor).prototype;
  5286. return property in this && !(property in parent && this[property] === parent[property]);
  5287. };
  5288. }
  5289. members = null;
  5290. return isProperty.call(this, property);
  5291. };
  5292. }
  5293. // Internal: A set of primitive types used by `isHostType`.
  5294. var PrimitiveTypes = {
  5295. 'boolean': 1,
  5296. 'number': 1,
  5297. 'string': 1,
  5298. 'undefined': 1
  5299. };
  5300. // Internal: Determines if the given object `property` value is a
  5301. // non-primitive.
  5302. var isHostType = function (object, property) {
  5303. var type = typeof object[property];
  5304. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  5305. };
  5306. // Internal: Normalizes the `for...in` iteration algorithm across
  5307. // environments. Each enumerated key is yielded to a `callback` function.
  5308. forEach = function (object, callback) {
  5309. var size = 0, Properties, members, property;
  5310. // Tests for bugs in the current environment's `for...in` algorithm. The
  5311. // `valueOf` property inherits the non-enumerable flag from
  5312. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  5313. (Properties = function () {
  5314. this.valueOf = 0;
  5315. }).prototype.valueOf = 0;
  5316. // Iterate over a new instance of the `Properties` class.
  5317. members = new Properties();
  5318. for (property in members) {
  5319. // Ignore all properties inherited from `Object.prototype`.
  5320. if (isProperty.call(members, property)) {
  5321. size++;
  5322. }
  5323. }
  5324. Properties = members = null;
  5325. // Normalize the iteration algorithm.
  5326. if (!size) {
  5327. // A list of non-enumerable properties inherited from `Object.prototype`.
  5328. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  5329. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  5330. // properties.
  5331. forEach = function (object, callback) {
  5332. var isFunction = getClass.call(object) == functionClass, property, length;
  5333. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  5334. for (property in object) {
  5335. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  5336. // certain conditions; IE does not.
  5337. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  5338. callback(property);
  5339. }
  5340. }
  5341. // Manually invoke the callback for each non-enumerable property.
  5342. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  5343. };
  5344. } else if (size == 2) {
  5345. // Safari <= 2.0.4 enumerates shadowed properties twice.
  5346. forEach = function (object, callback) {
  5347. // Create a set of iterated properties.
  5348. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  5349. for (property in object) {
  5350. // Store each property name to prevent double enumeration. The
  5351. // `prototype` property of functions is not enumerated due to cross-
  5352. // environment inconsistencies.
  5353. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  5354. callback(property);
  5355. }
  5356. }
  5357. };
  5358. } else {
  5359. // No bugs detected; use the standard `for...in` algorithm.
  5360. forEach = function (object, callback) {
  5361. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  5362. for (property in object) {
  5363. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  5364. callback(property);
  5365. }
  5366. }
  5367. // Manually invoke the callback for the `constructor` property due to
  5368. // cross-environment inconsistencies.
  5369. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  5370. callback(property);
  5371. }
  5372. };
  5373. }
  5374. return forEach(object, callback);
  5375. };
  5376. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  5377. // `filter` argument may specify either a function that alters how object and
  5378. // array members are serialized, or an array of strings and numbers that
  5379. // indicates which properties should be serialized. The optional `width`
  5380. // argument may be either a string or number that specifies the indentation
  5381. // level of the output.
  5382. if (!has("json-stringify")) {
  5383. // Internal: A map of control characters and their escaped equivalents.
  5384. var Escapes = {
  5385. 92: "\\\\",
  5386. 34: '\\"',
  5387. 8: "\\b",
  5388. 12: "\\f",
  5389. 10: "\\n",
  5390. 13: "\\r",
  5391. 9: "\\t"
  5392. };
  5393. // Internal: Converts `value` into a zero-padded string such that its
  5394. // length is at least equal to `width`. The `width` must be <= 6.
  5395. var leadingZeroes = "000000";
  5396. var toPaddedString = function (width, value) {
  5397. // The `|| 0` expression is necessary to work around a bug in
  5398. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  5399. return (leadingZeroes + (value || 0)).slice(-width);
  5400. };
  5401. // Internal: Double-quotes a string `value`, replacing all ASCII control
  5402. // characters (characters with code unit values between 0 and 31) with
  5403. // their escaped equivalents. This is an implementation of the
  5404. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  5405. var unicodePrefix = "\\u00";
  5406. var quote = function (value) {
  5407. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  5408. if (isLarge) {
  5409. symbols = value.split("");
  5410. }
  5411. for (; index < length; index++) {
  5412. var charCode = value.charCodeAt(index);
  5413. // If the character is a control character, append its Unicode or
  5414. // shorthand escape sequence; otherwise, append the character as-is.
  5415. switch (charCode) {
  5416. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  5417. result += Escapes[charCode];
  5418. break;
  5419. default:
  5420. if (charCode < 32) {
  5421. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  5422. break;
  5423. }
  5424. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  5425. }
  5426. }
  5427. return result + '"';
  5428. };
  5429. // Internal: Recursively serializes an object. Implements the
  5430. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  5431. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  5432. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  5433. try {
  5434. // Necessary for host object support.
  5435. value = object[property];
  5436. } catch (exception) {}
  5437. if (typeof value == "object" && value) {
  5438. className = getClass.call(value);
  5439. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  5440. if (value > -1 / 0 && value < 1 / 0) {
  5441. // Dates are serialized according to the `Date#toJSON` method
  5442. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  5443. // for the ISO 8601 date time string format.
  5444. if (getDay) {
  5445. // Manually compute the year, month, date, hours, minutes,
  5446. // seconds, and milliseconds if the `getUTC*` methods are
  5447. // buggy. Adapted from @Yaffle's `date-shim` project.
  5448. date = floor(value / 864e5);
  5449. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  5450. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  5451. date = 1 + date - getDay(year, month);
  5452. // The `time` value specifies the time within the day (see ES
  5453. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  5454. // to compute `A modulo B`, as the `%` operator does not
  5455. // correspond to the `modulo` operation for negative numbers.
  5456. time = (value % 864e5 + 864e5) % 864e5;
  5457. // The hours, minutes, seconds, and milliseconds are obtained by
  5458. // decomposing the time within the day. See section 15.9.1.10.
  5459. hours = floor(time / 36e5) % 24;
  5460. minutes = floor(time / 6e4) % 60;
  5461. seconds = floor(time / 1e3) % 60;
  5462. milliseconds = time % 1e3;
  5463. } else {
  5464. year = value.getUTCFullYear();
  5465. month = value.getUTCMonth();
  5466. date = value.getUTCDate();
  5467. hours = value.getUTCHours();
  5468. minutes = value.getUTCMinutes();
  5469. seconds = value.getUTCSeconds();
  5470. milliseconds = value.getUTCMilliseconds();
  5471. }
  5472. // Serialize extended years correctly.
  5473. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  5474. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  5475. // Months, dates, hours, minutes, and seconds should have two
  5476. // digits; milliseconds should have three.
  5477. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  5478. // Milliseconds are optional in ES 5.0, but required in 5.1.
  5479. "." + toPaddedString(3, milliseconds) + "Z";
  5480. } else {
  5481. value = null;
  5482. }
  5483. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  5484. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  5485. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  5486. // ignores all `toJSON` methods on these objects unless they are
  5487. // defined directly on an instance.
  5488. value = value.toJSON(property);
  5489. }
  5490. }
  5491. if (callback) {
  5492. // If a replacement function was provided, call it to obtain the value
  5493. // for serialization.
  5494. value = callback.call(object, property, value);
  5495. }
  5496. if (value === null) {
  5497. return "null";
  5498. }
  5499. className = getClass.call(value);
  5500. if (className == booleanClass) {
  5501. // Booleans are represented literally.
  5502. return "" + value;
  5503. } else if (className == numberClass) {
  5504. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  5505. // `"null"`.
  5506. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  5507. } else if (className == stringClass) {
  5508. // Strings are double-quoted and escaped.
  5509. return quote("" + value);
  5510. }
  5511. // Recursively serialize objects and arrays.
  5512. if (typeof value == "object") {
  5513. // Check for cyclic structures. This is a linear search; performance
  5514. // is inversely proportional to the number of unique nested objects.
  5515. for (length = stack.length; length--;) {
  5516. if (stack[length] === value) {
  5517. // Cyclic structures cannot be serialized by `JSON.stringify`.
  5518. throw TypeError();
  5519. }
  5520. }
  5521. // Add the object to the stack of traversed objects.
  5522. stack.push(value);
  5523. results = [];
  5524. // Save the current indentation level and indent one additional level.
  5525. prefix = indentation;
  5526. indentation += whitespace;
  5527. if (className == arrayClass) {
  5528. // Recursively serialize array elements.
  5529. for (index = 0, length = value.length; index < length; index++) {
  5530. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  5531. results.push(element === undef ? "null" : element);
  5532. }
  5533. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  5534. } else {
  5535. // Recursively serialize object members. Members are selected from
  5536. // either a user-specified list of property names, or the object
  5537. // itself.
  5538. forEach(properties || value, function (property) {
  5539. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  5540. if (element !== undef) {
  5541. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  5542. // is not the empty string, let `member` {quote(property) + ":"}
  5543. // be the concatenation of `member` and the `space` character."
  5544. // The "`space` character" refers to the literal space
  5545. // character, not the `space` {width} argument provided to
  5546. // `JSON.stringify`.
  5547. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  5548. }
  5549. });
  5550. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  5551. }
  5552. // Remove the object from the traversed object stack.
  5553. stack.pop();
  5554. return result;
  5555. }
  5556. };
  5557. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  5558. JSON3.stringify = function (source, filter, width) {
  5559. var whitespace, callback, properties, className;
  5560. if (typeof filter == "function" || typeof filter == "object" && filter) {
  5561. if ((className = getClass.call(filter)) == functionClass) {
  5562. callback = filter;
  5563. } else if (className == arrayClass) {
  5564. // Convert the property names array into a makeshift set.
  5565. properties = {};
  5566. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  5567. }
  5568. }
  5569. if (width) {
  5570. if ((className = getClass.call(width)) == numberClass) {
  5571. // Convert the `width` to an integer and create a string containing
  5572. // `width` number of space characters.
  5573. if ((width -= width % 1) > 0) {
  5574. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  5575. }
  5576. } else if (className == stringClass) {
  5577. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  5578. }
  5579. }
  5580. // Opera <= 7.54u2 discards the values associated with empty string keys
  5581. // (`""`) only if they are used directly within an object member list
  5582. // (e.g., `!("" in { "": 1})`).
  5583. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  5584. };
  5585. }
  5586. // Public: Parses a JSON source string.
  5587. if (!has("json-parse")) {
  5588. var fromCharCode = String.fromCharCode;
  5589. // Internal: A map of escaped control characters and their unescaped
  5590. // equivalents.
  5591. var Unescapes = {
  5592. 92: "\\",
  5593. 34: '"',
  5594. 47: "/",
  5595. 98: "\b",
  5596. 116: "\t",
  5597. 110: "\n",
  5598. 102: "\f",
  5599. 114: "\r"
  5600. };
  5601. // Internal: Stores the parser state.
  5602. var Index, Source;
  5603. // Internal: Resets the parser state and throws a `SyntaxError`.
  5604. var abort = function() {
  5605. Index = Source = null;
  5606. throw SyntaxError();
  5607. };
  5608. // Internal: Returns the next token, or `"$"` if the parser has reached
  5609. // the end of the source string. A token may be a string, number, `null`
  5610. // literal, or Boolean literal.
  5611. var lex = function () {
  5612. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  5613. while (Index < length) {
  5614. charCode = source.charCodeAt(Index);
  5615. switch (charCode) {
  5616. case 9: case 10: case 13: case 32:
  5617. // Skip whitespace tokens, including tabs, carriage returns, line
  5618. // feeds, and space characters.
  5619. Index++;
  5620. break;
  5621. case 123: case 125: case 91: case 93: case 58: case 44:
  5622. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  5623. // the current position.
  5624. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  5625. Index++;
  5626. return value;
  5627. case 34:
  5628. // `"` delimits a JSON string; advance to the next character and
  5629. // begin parsing the string. String tokens are prefixed with the
  5630. // sentinel `@` character to distinguish them from punctuators and
  5631. // end-of-string tokens.
  5632. for (value = "@", Index++; Index < length;) {
  5633. charCode = source.charCodeAt(Index);
  5634. if (charCode < 32) {
  5635. // Unescaped ASCII control characters (those with a code unit
  5636. // less than the space character) are not permitted.
  5637. abort();
  5638. } else if (charCode == 92) {
  5639. // A reverse solidus (`\`) marks the beginning of an escaped
  5640. // control character (including `"`, `\`, and `/`) or Unicode
  5641. // escape sequence.
  5642. charCode = source.charCodeAt(++Index);
  5643. switch (charCode) {
  5644. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  5645. // Revive escaped control characters.
  5646. value += Unescapes[charCode];
  5647. Index++;
  5648. break;
  5649. case 117:
  5650. // `\u` marks the beginning of a Unicode escape sequence.
  5651. // Advance to the first character and validate the
  5652. // four-digit code point.
  5653. begin = ++Index;
  5654. for (position = Index + 4; Index < position; Index++) {
  5655. charCode = source.charCodeAt(Index);
  5656. // A valid sequence comprises four hexdigits (case-
  5657. // insensitive) that form a single hexadecimal value.
  5658. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  5659. // Invalid Unicode escape sequence.
  5660. abort();
  5661. }
  5662. }
  5663. // Revive the escaped character.
  5664. value += fromCharCode("0x" + source.slice(begin, Index));
  5665. break;
  5666. default:
  5667. // Invalid escape sequence.
  5668. abort();
  5669. }
  5670. } else {
  5671. if (charCode == 34) {
  5672. // An unescaped double-quote character marks the end of the
  5673. // string.
  5674. break;
  5675. }
  5676. charCode = source.charCodeAt(Index);
  5677. begin = Index;
  5678. // Optimize for the common case where a string is valid.
  5679. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  5680. charCode = source.charCodeAt(++Index);
  5681. }
  5682. // Append the string as-is.
  5683. value += source.slice(begin, Index);
  5684. }
  5685. }
  5686. if (source.charCodeAt(Index) == 34) {
  5687. // Advance to the next character and return the revived string.
  5688. Index++;
  5689. return value;
  5690. }
  5691. // Unterminated string.
  5692. abort();
  5693. default:
  5694. // Parse numbers and literals.
  5695. begin = Index;
  5696. // Advance past the negative sign, if one is specified.
  5697. if (charCode == 45) {
  5698. isSigned = true;
  5699. charCode = source.charCodeAt(++Index);
  5700. }
  5701. // Parse an integer or floating-point value.
  5702. if (charCode >= 48 && charCode <= 57) {
  5703. // Leading zeroes are interpreted as octal literals.
  5704. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  5705. // Illegal octal literal.
  5706. abort();
  5707. }
  5708. isSigned = false;
  5709. // Parse the integer component.
  5710. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  5711. // Floats cannot contain a leading decimal point; however, this
  5712. // case is already accounted for by the parser.
  5713. if (source.charCodeAt(Index) == 46) {
  5714. position = ++Index;
  5715. // Parse the decimal component.
  5716. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  5717. if (position == Index) {
  5718. // Illegal trailing decimal.
  5719. abort();
  5720. }
  5721. Index = position;
  5722. }
  5723. // Parse exponents. The `e` denoting the exponent is
  5724. // case-insensitive.
  5725. charCode = source.charCodeAt(Index);
  5726. if (charCode == 101 || charCode == 69) {
  5727. charCode = source.charCodeAt(++Index);
  5728. // Skip past the sign following the exponent, if one is
  5729. // specified.
  5730. if (charCode == 43 || charCode == 45) {
  5731. Index++;
  5732. }
  5733. // Parse the exponential component.
  5734. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  5735. if (position == Index) {
  5736. // Illegal empty exponent.
  5737. abort();
  5738. }
  5739. Index = position;
  5740. }
  5741. // Coerce the parsed value to a JavaScript number.
  5742. return +source.slice(begin, Index);
  5743. }
  5744. // A negative sign may only precede numbers.
  5745. if (isSigned) {
  5746. abort();
  5747. }
  5748. // `true`, `false`, and `null` literals.
  5749. if (source.slice(Index, Index + 4) == "true") {
  5750. Index += 4;
  5751. return true;
  5752. } else if (source.slice(Index, Index + 5) == "false") {
  5753. Index += 5;
  5754. return false;
  5755. } else if (source.slice(Index, Index + 4) == "null") {
  5756. Index += 4;
  5757. return null;
  5758. }
  5759. // Unrecognized token.
  5760. abort();
  5761. }
  5762. }
  5763. // Return the sentinel `$` character if the parser has reached the end
  5764. // of the source string.
  5765. return "$";
  5766. };
  5767. // Internal: Parses a JSON `value` token.
  5768. var get = function (value) {
  5769. var results, hasMembers;
  5770. if (value == "$") {
  5771. // Unexpected end of input.
  5772. abort();
  5773. }
  5774. if (typeof value == "string") {
  5775. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  5776. // Remove the sentinel `@` character.
  5777. return value.slice(1);
  5778. }
  5779. // Parse object and array literals.
  5780. if (value == "[") {
  5781. // Parses a JSON array, returning a new JavaScript array.
  5782. results = [];
  5783. for (;; hasMembers || (hasMembers = true)) {
  5784. value = lex();
  5785. // A closing square bracket marks the end of the array literal.
  5786. if (value == "]") {
  5787. break;
  5788. }
  5789. // If the array literal contains elements, the current token
  5790. // should be a comma separating the previous element from the
  5791. // next.
  5792. if (hasMembers) {
  5793. if (value == ",") {
  5794. value = lex();
  5795. if (value == "]") {
  5796. // Unexpected trailing `,` in array literal.
  5797. abort();
  5798. }
  5799. } else {
  5800. // A `,` must separate each array element.
  5801. abort();
  5802. }
  5803. }
  5804. // Elisions and leading commas are not permitted.
  5805. if (value == ",") {
  5806. abort();
  5807. }
  5808. results.push(get(value));
  5809. }
  5810. return results;
  5811. } else if (value == "{") {
  5812. // Parses a JSON object, returning a new JavaScript object.
  5813. results = {};
  5814. for (;; hasMembers || (hasMembers = true)) {
  5815. value = lex();
  5816. // A closing curly brace marks the end of the object literal.
  5817. if (value == "}") {
  5818. break;
  5819. }
  5820. // If the object literal contains members, the current token
  5821. // should be a comma separator.
  5822. if (hasMembers) {
  5823. if (value == ",") {
  5824. value = lex();
  5825. if (value == "}") {
  5826. // Unexpected trailing `,` in object literal.
  5827. abort();
  5828. }
  5829. } else {
  5830. // A `,` must separate each object member.
  5831. abort();
  5832. }
  5833. }
  5834. // Leading commas are not permitted, object property names must be
  5835. // double-quoted strings, and a `:` must separate each property
  5836. // name and value.
  5837. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  5838. abort();
  5839. }
  5840. results[value.slice(1)] = get(lex());
  5841. }
  5842. return results;
  5843. }
  5844. // Unexpected token encountered.
  5845. abort();
  5846. }
  5847. return value;
  5848. };
  5849. // Internal: Updates a traversed object member.
  5850. var update = function(source, property, callback) {
  5851. var element = walk(source, property, callback);
  5852. if (element === undef) {
  5853. delete source[property];
  5854. } else {
  5855. source[property] = element;
  5856. }
  5857. };
  5858. // Internal: Recursively traverses a parsed JSON object, invoking the
  5859. // `callback` function for each value. This is an implementation of the
  5860. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  5861. var walk = function (source, property, callback) {
  5862. var value = source[property], length;
  5863. if (typeof value == "object" && value) {
  5864. // `forEach` can't be used to traverse an array in Opera <= 8.54
  5865. // because its `Object#hasOwnProperty` implementation returns `false`
  5866. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  5867. if (getClass.call(value) == arrayClass) {
  5868. for (length = value.length; length--;) {
  5869. update(value, length, callback);
  5870. }
  5871. } else {
  5872. forEach(value, function (property) {
  5873. update(value, property, callback);
  5874. });
  5875. }
  5876. }
  5877. return callback.call(source, property, value);
  5878. };
  5879. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  5880. JSON3.parse = function (source, callback) {
  5881. var result, value;
  5882. Index = 0;
  5883. Source = "" + source;
  5884. result = get(lex());
  5885. // If a JSON string contains multiple tokens, it is invalid.
  5886. if (lex() != "$") {
  5887. abort();
  5888. }
  5889. // Reset the parser state.
  5890. Index = Source = null;
  5891. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  5892. };
  5893. }
  5894. }
  5895. // Export for asynchronous module loaders.
  5896. if (isLoader) {
  5897. define(function () {
  5898. return JSON3;
  5899. });
  5900. }
  5901. }(this));
  5902. },{}],50:[function(_dereq_,module,exports){
  5903. module.exports = toArray
  5904. function toArray(list, index) {
  5905. var array = []
  5906. index = index || 0
  5907. for (var i = index || 0; i < list.length; i++) {
  5908. array[i - index] = list[i]
  5909. }
  5910. return array
  5911. }
  5912. },{}]},{},[1])
  5913. (1)
  5914. });