PageRenderTime 78ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/assets/js/socket.io.js

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