PageRenderTime 83ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/platforms/ios/www/js/socket.io.js

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