PageRenderTime 86ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/socket.io.js

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