PageRenderTime 75ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/socket.io/node_modules/socket.io-client/socket.io.js

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