PageRenderTime 91ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

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