-!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.eio=e():"undefined"!=typeof global?global.eio=e():"undefined"!=typeof self&&(self.eio=e())}(function(){var define,module,exports;
-return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
-
-module.exports = require('./lib/');
-
-},{"./lib/":3}],2:[function(require,module,exports){
+;(function(){
/**
- * Module dependencies.
+ * Require the given path.
+ *
+ * @param {String} path
+ * @return {Object} exports
+ * @api public
*/
-var Emitter = require('emitter');
+function require(path, parent, orig) {
+ var resolved = require.resolve(path);
-/**
- * Module exports.
- */
+ // lookup failed
+ if (null == resolved) {
+ orig = orig || path;
+ parent = parent || 'root';
+ var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
+ err.path = orig;
+ err.parent = parent;
+ err.require = true;
+ throw err;
+ }
-module.exports = Emitter;
+ var module = require.modules[resolved];
+
+ // perform real require()
+ // by invoking the module's
+ // registered function
+ if (!module.exports) {
+ module.exports = {};
+ module.client = module.component = true;
+ module.call(this, module.exports, require.relative(resolved), module);
+ }
+
+ return module.exports;
+}
/**
- * Compatibility with `WebSocket#addEventListener`.
- *
- * @api public
+ * Registered modules.
*/
-Emitter.prototype.addEventListener = Emitter.prototype.on;
+require.modules = {};
/**
- * Compatibility with `WebSocket#removeEventListener`.
- *
- * @api public
+ * Registered aliases.
*/
-Emitter.prototype.removeEventListener = Emitter.prototype.off;
+require.aliases = {};
/**
- * Node-compatible `EventEmitter#removeListener`
+ * Resolve `path`.
*
- * @api public
+ * Lookup:
+ *
+ * - PATH/index.js
+ * - PATH.js
+ * - PATH
+ *
+ * @param {String} path
+ * @return {String} path or null
+ * @api private
*/
-Emitter.prototype.removeListener = Emitter.prototype.off;
+require.resolve = function(path) {
+ if (path.charAt(0) === '/') path = path.slice(1);
+ var index = path + '/index.js';
-},{"emitter":15}],3:[function(require,module,exports){
+ var paths = [
+ path,
+ path + '.js',
+ path + '.json',
+ path + '/index.js',
+ path + '/index.json'
+ ];
-module.exports = require('./socket');
+ for (var i = 0; i < paths.length; i++) {
+ var path = paths[i];
+ if (require.modules.hasOwnProperty(path)) return path;
+ }
+
+ if (require.aliases.hasOwnProperty(index)) {
+ return require.aliases[index];
+ }
+};
/**
- * Exports parser
- *
- * @api public
+ * Normalize `path` relative to the current path.
*
+ * @param {String} curr
+ * @param {String} path
+ * @return {String}
+ * @api private
*/
-module.exports.parser = require('engine.io-parser');
-},{"./socket":4,"engine.io-parser":16}],4:[function(require,module,exports){
-/**
- * Module dependencies.
- */
+require.normalize = function(curr, path) {
+ var segs = [];
-var util = require('./util');
-var transports = require('./transports');
-var Emitter = require('./emitter');
-var debug = require('debug')('engine.io-client:socket');
-var index = require('indexof');
-var parser = require('engine.io-parser');
+ if ('.' != path.charAt(0)) return path;
-/**
- * Module exports.
- */
+ curr = curr.split('/');
+ path = path.split('/');
-module.exports = Socket;
+ for (var i = 0; i < path.length; ++i) {
+ if ('..' == path[i]) {
+ curr.pop();
+ } else if ('.' != path[i] && '' != path[i]) {
+ segs.push(path[i]);
+ }
+ }
+
+ return curr.concat(segs).join('/');
+};
/**
- * Global reference.
+ * Register module at `path` with callback `definition`.
+ *
+ * @param {String} path
+ * @param {Function} definition
+ * @api private
*/
-var global = require('global');
+require.register = function(path, definition) {
+ require.modules[path] = definition;
+};
/**
- * Noop function.
+ * Alias a module definition.
*
+ * @param {String} from
+ * @param {String} to
* @api private
*/
-function noop(){}
+require.alias = function(from, to) {
+ if (!require.modules.hasOwnProperty(from)) {
+ throw new Error('Failed to alias "' + from + '", it does not exist');
+ }
+ require.aliases[to] = from;
+};
/**
- * Socket constructor.
+ * Return a require function relative to the `parent` path.
*
- * @param {String|Object} uri or options
- * @param {Object} options
- * @api public
+ * @param {String} parent
+ * @return {Function}
+ * @api private
*/
-function Socket(uri, opts){
- if (!(this instanceof Socket)) return new Socket(uri, opts);
+require.relative = function(parent) {
+ var p = require.normalize(parent, '..');
- opts = opts || {};
+ /**
+ * lastIndexOf helper.
+ */
- if (uri && 'object' == typeof uri) {
- opts = uri;
- uri = null;
+ function lastIndexOf(arr, obj) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === obj) return i;
+ }
+ return -1;
}
- if (uri) {
- uri = util.parseUri(uri);
- opts.host = uri.host;
- opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
- opts.port = uri.port;
- if (uri.query) opts.query = uri.query;
+ /**
+ * The relative require() itself.
+ */
+
+ function localRequire(path) {
+ var resolved = localRequire.resolve(path);
+ return require(resolved, parent, path);
}
- this.secure = null != opts.secure ? opts.secure :
- (global.location && 'https:' == location.protocol);
+ /**
+ * Resolve relative to the parent.
+ */
- if (opts.host) {
- var pieces = opts.host.split(':');
- opts.hostname = pieces.shift();
- if (pieces.length) opts.port = pieces.pop();
- }
+ localRequire.resolve = function(path) {
+ var c = path.charAt(0);
+ if ('/' == c) return path.slice(1);
+ if ('.' == c) return require.normalize(p, path);
- this.agent = opts.agent || false;
- this.hostname = opts.hostname ||
- (global.location ? location.hostname : 'localhost');
- this.port = opts.port || (global.location && location.port ?
- location.port :
- (this.secure ? 443 : 80));
- this.query = opts.query || {};
- if ('string' == typeof this.query) this.query = util.qsParse(this.query);
- this.upgrade = false !== opts.upgrade;
- this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
- this.forceJSONP = !!opts.forceJSONP;
- this.timestampParam = opts.timestampParam || 't';
- this.timestampRequests = opts.timestampRequests;
- this.flashPath = opts.flashPath || '';
- this.transports = opts.transports || ['polling', 'websocket', 'flashsocket'];
- this.readyState = '';
- this.writeBuffer = [];
- this.callbackBuffer = [];
- this.policyPort = opts.policyPort || 843;
- this.open();
-}
+ // resolve deps by returning
+ // the dep in the nearest "deps"
+ // directory
+ var segs = parent.split('/');
+ var i = lastIndexOf(segs, 'deps') + 1;
+ if (!i) i = 0;
+ path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
+ return path;
+ };
-/**
- * Mix in `Emitter`.
- */
+ /**
+ * Check if module is defined at `path`.
+ */
-Emitter(Socket.prototype);
+ localRequire.exists = function(path) {
+ return require.modules.hasOwnProperty(localRequire.resolve(path));
+ };
+
+ return localRequire;
+};
+require.register("component-emitter/index.js", function(exports, require, module){
/**
- * Protocol version.
- *
- * @api public
+ * Expose `Emitter`.
*/
-Socket.protocol = parser.protocol; // this is an int
+module.exports = Emitter;
/**
- * Expose deps for legacy compatibility
- * and standalone browser access.
+ * Initialize a new `Emitter`.
+ *
+ * @api public
*/
-Socket.Socket = Socket;
-Socket.Transport = require('./transport');
-Socket.Emitter = require('./emitter');
-Socket.transports = require('./transports');
-Socket.util = require('./util');
-Socket.parser = require('engine.io-parser');
+function Emitter(obj) {
+ if (obj) return mixin(obj);
+};
/**
- * Creates transport of the given type.
+ * Mixin the emitter properties.
*
- * @param {String} transport name
- * @return {Transport}
+ * @param {Object} obj
+ * @return {Object}
* @api private
*/
-Socket.prototype.createTransport = function (name) {
- debug('creating transport "%s"', name);
- var query = clone(this.query);
-
- // append engine.io protocol identifier
- query.EIO = parser.protocol;
-
- // transport name
- query.transport = name;
-
- // session id if we already have one
- if (this.id) query.sid = this.id;
-
- var transport = new transports[name]({
- agent: this.agent,
- hostname: this.hostname,
- port: this.port,
- secure: this.secure,
- path: this.path,
- query: query,
- forceJSONP: this.forceJSONP,
- timestampRequests: this.timestampRequests,
- timestampParam: this.timestampParam,
- flashPath: this.flashPath,
- policyPort: this.policyPort
- });
-
- return transport;
-};
-
-function clone (obj) {
- var o = {};
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- o[i] = obj[i];
- }
+function mixin(obj) {
+ for (var key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
}
- return o;
+ return obj;
}
/**
- * Initializes transport to use and starts probe.
+ * Listen on the given `event` with `fn`.
*
- * @api private
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
*/
-Socket.prototype.open = function () {
- var transport = this.transports[0];
- this.readyState = 'opening';
- var transport = this.createTransport(transport);
- transport.open();
- this.setTransport(transport);
+Emitter.prototype.on = function(event, fn){
+ this._callbacks = this._callbacks || {};
+ (this._callbacks[event] = this._callbacks[event] || [])
+ .push(fn);
+ return this;
};
/**
- * Sets the current transport. Disables the existing one (if any).
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
*
- * @api private
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
*/
-Socket.prototype.setTransport = function(transport){
- debug('setting transport %s', transport.name);
+Emitter.prototype.once = function(event, fn){
var self = this;
+ this._callbacks = this._callbacks || {};
- if (this.transport) {
- debug('clearing existing transport %s', this.transport.name);
- this.transport.removeAllListeners();
+ function on() {
+ self.off(event, on);
+ fn.apply(this, arguments);
}
- // set up transport
- this.transport = transport;
-
- // set up transport listeners
- transport
- .on('drain', function(){
- self.onDrain();
- })
- .on('packet', function(packet){
- self.onPacket(packet);
- })
- .on('error', function(e){
- self.onError(e);
- })
- .on('close', function(){
- self.onClose('transport close');
- });
+ fn._off = on;
+ this.on(event, on);
+ return this;
};
/**
- * Probes a transport.
+ * Remove the given callback for `event` or all
+ * registered callbacks.
*
- * @param {String} transport name
- * @api private
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
*/
-Socket.prototype.probe = function (name) {
- debug('probing transport "%s"', name);
- var transport = this.createTransport(name, { probe: 1 })
- , failed = false
- , self = this;
-
- transport.once('open', function () {
- if (failed) return;
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners = function(event, fn){
+ this._callbacks = this._callbacks || {};
- debug('probe transport "%s" opened', name);
- transport.send([{ type: 'ping', data: 'probe' }]);
- transport.once('packet', function (msg) {
- if (failed) return;
- if ('pong' == msg.type && 'probe' == msg.data) {
- debug('probe transport "%s" pong', name);
- self.upgrading = true;
- self.emit('upgrading', transport);
+ // all
+ if (0 == arguments.length) {
+ this._callbacks = {};
+ return this;
+ }
- debug('pausing current transport "%s"', self.transport.name);
- self.transport.pause(function () {
- if (failed) return;
- if ('closed' == self.readyState || 'closing' == self.readyState) {
- return;
- }
- debug('changing transport and sending upgrade packet');
- transport.removeListener('error', onerror);
- self.emit('upgrade', transport);
- self.setTransport(transport);
- transport.send([{ type: 'upgrade' }]);
- transport = null;
- self.upgrading = false;
- self.flush();
- });
- } else {
- debug('probe transport "%s" failed', name);
- var err = new Error('probe error');
- err.transport = transport.name;
- self.emit('upgradeError', err);
- }
- });
- });
-
- transport.once('error', onerror);
- function onerror(err) {
- if (failed) return;
+ // specific event
+ var callbacks = this._callbacks[event];
+ if (!callbacks) return this;
- // Any callback called by transport should be ignored since now
- failed = true;
+ // remove all handlers
+ if (1 == arguments.length) {
+ delete this._callbacks[event];
+ return this;
+ }
- var error = new Error('probe error: ' + err);
- error.transport = transport.name;
+ // remove specific handler
+ var i = callbacks.indexOf(fn._off || fn);
+ if (~i) callbacks.splice(i, 1);
+ return this;
+};
- transport.close();
- transport = null;
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
- debug('probe transport "%s" failed because of error: %s', name, err);
+Emitter.prototype.emit = function(event){
+ this._callbacks = this._callbacks || {};
+ var args = [].slice.call(arguments, 1)
+ , callbacks = this._callbacks[event];
- self.emit('upgradeError', error);
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
}
- transport.open();
+ return this;
+};
- this.once('close', function () {
- if (transport) {
- debug('socket closed prematurely - aborting probe');
- failed = true;
- transport.close();
- transport = null;
- }
- });
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
- this.once('upgrading', function (to) {
- if (transport && to.name != transport.name) {
- debug('"%s" works - aborting "%s"', to.name, transport.name);
- transport.close();
- transport = null;
- }
- });
+Emitter.prototype.listeners = function(event){
+ this._callbacks = this._callbacks || {};
+ return this._callbacks[event] || [];
};
/**
- * Called when connection is deemed open.
+ * Check if this emitter has `event` handlers.
*
+ * @param {String} event
+ * @return {Boolean}
* @api public
*/
-Socket.prototype.onOpen = function () {
- debug('socket open');
- this.readyState = 'open';
- this.emit('open');
- this.onopen && this.onopen.call(this);
- this.flush();
+Emitter.prototype.hasListeners = function(event){
+ return !! this.listeners(event).length;
+};
- // we check for `readyState` in case an `open`
- // listener already closed the socket
- if ('open' == this.readyState && this.upgrade && this.transport.pause) {
- debug('starting upgrade probes');
- for (var i = 0, l = this.upgrades.length; i < l; i++) {
- this.probe(this.upgrades[i]);
- }
+});
+require.register("component-indexof/index.js", function(exports, require, module){
+
+var indexOf = [].indexOf;
+
+module.exports = function(arr, obj){
+ if (indexOf) return arr.indexOf(obj);
+ for (var i = 0; i < arr.length; ++i) {
+ if (arr[i] === obj) return i;
}
+ return -1;
};
-
+});
+require.register("LearnBoost-engine.io-protocol/lib/index.js", function(exports, require, module){
/**
- * Handles a packet.
- *
- * @api private
+ * Module dependencies.
*/
-Socket.prototype.onPacket = function (packet) {
- if ('opening' == this.readyState || 'open' == this.readyState) {
- debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
+var keys = require('./keys');
- this.emit('packet', packet);
+/**
+ * Current protocol version.
+ */
+exports.protocol = 2;
- // Socket is live - any packet counts
- this.emit('heartbeat');
+/**
+ * Packet types.
+ */
- switch (packet.type) {
- case 'open':
- this.onHandshake(util.parseJSON(packet.data));
- break;
+var packets = exports.packets = {
+ open: 0 // non-ws
+ , close: 1 // non-ws
+ , ping: 2
+ , pong: 3
+ , message: 4
+ , upgrade: 5
+ , noop: 6
+};
- case 'pong':
- this.setPing();
- break;
+var packetslist = keys(packets);
- case 'error':
- var err = new Error('server error');
- err.code = packet.data;
- this.emit('error', err);
- break;
+/**
+ * Premade error packet.
+ */
- case 'message':
- this.emit('data', packet.data);
- this.emit('message', packet.data);
- var event = { data: packet.data };
- event.toString = function () {
- return packet.data;
- };
- this.onmessage && this.onmessage.call(this, event);
- break;
- }
- } else {
- debug('packet received with socket readyState "%s"', this.readyState);
- }
-};
+var err = { type: 'error', data: 'parser error' };
/**
- * Called upon handshake completion.
+ * Encodes a packet.
+ *
+ * <packet type id> [ `:` <data> ]
+ *
+ * Example:
+ *
+ * 5:hello world
+ * 3
+ * 4
*
- * @param {Object} handshake obj
* @api private
*/
-Socket.prototype.onHandshake = function (data) {
- this.emit('handshake', data);
- this.id = data.sid;
- this.transport.query.sid = data.sid;
- this.upgrades = this.filterUpgrades(data.upgrades);
- this.pingInterval = data.pingInterval;
- this.pingTimeout = data.pingTimeout;
- this.onOpen();
- this.setPing();
+exports.encodePacket = function (packet) {
+ var encoded = packets[packet.type];
- // Prolong liveness of socket on heartbeat
- this.removeListener('heartbeat', this.onHeartbeat);
- this.on('heartbeat', this.onHeartbeat);
+ // data fragment is optional
+ if (undefined !== packet.data) {
+ encoded += String(packet.data);
+ }
+
+ return '' + encoded;
};
/**
- * Resets ping timeout.
+ * Decodes a packet.
*
+ * @return {Object} with `type` and `data` (if any)
* @api private
*/
-Socket.prototype.onHeartbeat = function (timeout) {
- clearTimeout(this.pingTimeoutTimer);
- var self = this;
- self.pingTimeoutTimer = setTimeout(function () {
- if ('closed' == self.readyState) return;
- self.onClose('ping timeout');
- }, timeout || (self.pingInterval + self.pingTimeout));
+exports.decodePacket = function (data) {
+ var type = data.charAt(0);
+
+ if (Number(type) != type || !packetslist[type]) {
+ return err;
+ }
+
+ if (data.length > 1) {
+ return { type: packetslist[type], data: data.substring(1) };
+ } else {
+ return { type: packetslist[type] };
+ }
};
/**
- * Pings server every `this.pingInterval` and expects response
- * within `this.pingTimeout` or closes connection.
+ * Encodes multiple messages (payload).
+ *
+ * <length>:data
*
+ * Example:
+ *
+ * 11:hello world2:hi
+ *
+ * @param {Array} packets
* @api private
*/
-Socket.prototype.setPing = function () {
- var self = this;
- clearTimeout(self.pingIntervalTimer);
- self.pingIntervalTimer = setTimeout(function () {
- debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
- self.ping();
- self.onHeartbeat(self.pingTimeout);
- }, self.pingInterval);
+exports.encodePayload = function (packets) {
+ if (!packets.length) {
+ return '0:';
+ }
+
+ var encoded = '';
+ var message;
+
+ for (var i = 0, l = packets.length; i < l; i++) {
+ message = exports.encodePacket(packets[i]);
+ encoded += message.length + ':' + message;
+ }
+
+ return encoded;
};
-/**
-* Sends a ping packet.
-*
-* @api public
-*/
+/*
+ * Decodes data when a payload is maybe expected.
+ *
+ * @param {String} data, callback method
+ * @api public
+ */
+
+exports.decodePayload = function (data, callback) {
+ var packet;
+ if (data == '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ var length = ''
+ , n, msg;
+
+ for (var i = 0, l = data.length; i < l; i++) {
+ var chr = data.charAt(i);
+
+ if (':' != chr) {
+ length += chr;
+ } else {
+ if ('' == length || (length != (n = Number(length)))) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ msg = data.substr(i + 1, n);
+
+ if (length != msg.length) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ if (msg.length) {
+ packet = exports.decodePacket(msg);
+
+ if (err.type == packet.type && err.data == packet.data) {
+ // parser error in individual packet - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ var ret = callback(packet, i + n, l);
+ if (false === ret) return;
+ }
+
+ // advance cursor
+ i += n;
+ length = '';
+ }
+ }
+
+ if (length != '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
-Socket.prototype.ping = function () {
- this.sendPacket('ping');
};
+});
+require.register("LearnBoost-engine.io-protocol/lib/keys.js", function(exports, require, module){
+
/**
- * Called on `drain` event
+ * Gets the keys for an object.
*
+ * @return {Array} keys
* @api private
*/
- Socket.prototype.onDrain = function() {
- for (var i = 0; i < this.prevBufferLen; i++) {
- if (this.callbackBuffer[i]) {
- this.callbackBuffer[i]();
+module.exports = Object.keys || function keys (obj){
+ var arr = [];
+ var has = Object.prototype.hasOwnProperty;
+
+ for (var i in obj) {
+ if (has.call(obj, i)) {
+ arr.push(i);
}
}
+ return arr;
+};
- this.writeBuffer.splice(0, this.prevBufferLen);
- this.callbackBuffer.splice(0, this.prevBufferLen);
+});
+require.register("visionmedia-debug/index.js", function(exports, require, module){
+if ('undefined' == typeof window) {
+ module.exports = require('./lib/debug');
+} else {
+ module.exports = require('./debug');
+}
- // setting prevBufferLen = 0 is very important
- // for example, when upgrading, upgrade packet is sent over,
- // and a nonzero prevBufferLen could cause problems on `drain`
- this.prevBufferLen = 0;
+});
+require.register("visionmedia-debug/debug.js", function(exports, require, module){
- if (this.writeBuffer.length == 0) {
- this.emit('drain');
- } else {
- this.flush();
- }
-};
+/**
+ * Expose `debug()` as the module.
+ */
+
+module.exports = debug;
/**
- * Flush write buffers.
+ * Create a debugger with the given `name`.
*
- * @api private
+ * @param {String} name
+ * @return {Type}
+ * @api public
*/
-Socket.prototype.flush = function () {
- if ('closed' != this.readyState && this.transport.writable &&
- !this.upgrading && this.writeBuffer.length) {
- debug('flushing %d packets in socket', this.writeBuffer.length);
- this.transport.send(this.writeBuffer);
- // keep track of current length of writeBuffer
- // splice writeBuffer and callbackBuffer on `drain`
- this.prevBufferLen = this.writeBuffer.length;
- this.emit('flush');
+function debug(name) {
+ if (!debug.enabled(name)) return function(){};
+
+ return function(fmt){
+ fmt = coerce(fmt);
+
+ var curr = new Date;
+ var ms = curr - (debug[name] || curr);
+ debug[name] = curr;
+
+ fmt = name
+ + ' '
+ + fmt
+ + ' +' + debug.humanize(ms);
+
+ // This hackery is required for IE8
+ // where `console.log` doesn't have 'apply'
+ window.console
+ && console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
}
-};
+}
/**
- * Sends a message.
+ * The currently active debug mode names.
+ */
+
+debug.names = [];
+debug.skips = [];
+
+/**
+ * Enables a debug mode by name. This can include modes
+ * separated by a colon and wildcards.
*
- * @param {String} message.
- * @param {Function} callback function.
- * @return {Socket} for chaining.
+ * @param {String} name
* @api public
*/
-Socket.prototype.write =
-Socket.prototype.send = function (msg, fn) {
- this.sendPacket('message', msg, fn);
- return this;
+debug.enable = function(name) {
+ try {
+ localStorage.debug = name;
+ } catch(e){}
+
+ var split = (name || '').split(/[\s,]+/)
+ , len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ name = split[i].replace('*', '.*?');
+ if (name[0] === '-') {
+ debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
+ }
+ else {
+ debug.names.push(new RegExp('^' + name + '$'));
+ }
+ }
};
/**
- * Sends a packet.
+ * Disable debug output.
*
- * @param {String} packet type.
- * @param {String} data.
- * @param {Function} callback function.
- * @api private
+ * @api public
*/
-Socket.prototype.sendPacket = function (type, data, fn) {
- var packet = { type: type, data: data };
- this.emit('packetCreate', packet);
- this.writeBuffer.push(packet);
- this.callbackBuffer.push(fn);
- this.flush();
+debug.disable = function(){
+ debug.enable('');
};
/**
- * Closes the connection.
+ * Humanize the given `ms`.
*
+ * @param {Number} m
+ * @return {String}
* @api private
*/
-Socket.prototype.close = function () {
- if ('opening' == this.readyState || 'open' == this.readyState) {
- this.onClose('forced close');
- debug('socket closing - telling transport to close');
- this.transport.close();
- }
+debug.humanize = function(ms) {
+ var sec = 1000
+ , min = 60 * 1000
+ , hour = 60 * min;
- return this;
+ if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
+ if (ms >= min) return (ms / min).toFixed(1) + 'm';
+ if (ms >= sec) return (ms / sec | 0) + 's';
+ return ms + 'ms';
};
/**
- * Called upon transport error
+ * Returns true if the given mode name is enabled, false otherwise.
*
- * @api private
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
*/
-Socket.prototype.onError = function (err) {
- debug('socket error %j', err);
- this.emit('error', err);
- this.onerror && this.onerror.call(this, err);
- this.onClose('transport error', err);
+debug.enabled = function(name) {
+ for (var i = 0, len = debug.skips.length; i < len; i++) {
+ if (debug.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (var i = 0, len = debug.names.length; i < len; i++) {
+ if (debug.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
};
/**
- * Called upon transport close.
- *
- * @api private
+ * Coerce `val`.
*/
-Socket.prototype.onClose = function (reason, desc) {
- if ('opening' == this.readyState || 'open' == this.readyState) {
- debug('socket close with reason: "%s"', reason);
- var self = this;
-
- // clear timers
- clearTimeout(this.pingIntervalTimer);
- clearTimeout(this.pingTimeoutTimer);
-
- // clean buffers in next tick, so developers can still
- // grab the buffers on `close` event
- setTimeout(function() {
- self.writeBuffer = [];
- self.callbackBuffer = [];
- self.prevBufferLen = 0;
- }, 0);
+function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+}
- // ignore further transport communication
- this.transport.removeAllListeners();
+// persist
- // set ready state
- this.readyState = 'closed';
+if (window.localStorage) debug.enable(localStorage.debug);
- // clear session id
- this.id = null;
+});
+require.register("engine.io/lib/index.js", function(exports, require, module){
- // emit close event
- this.emit('close', reason, desc);
- this.onclose && this.onclose.call(this);
- }
-};
+module.exports = require('./socket');
/**
- * Filters upgrades, returning only those matching client transports.
+ * Exports parser
*
- * @param {Array} server upgrades
- * @api private
+ * @api public
*
*/
+module.exports.parser = require('engine.io-parser');
-Socket.prototype.filterUpgrades = function (upgrades) {
- var filteredUpgrades = [];
- for (var i = 0, j = upgrades.length; i<j; i++) {
- if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
- }
- return filteredUpgrades;
-};
-
-},{"./emitter":2,"./transport":5,"./transports":7,"./util":12,"debug":14,"engine.io-parser":16,"global":19,"indexof":21}],5:[function(require,module,exports){
-
+});
+require.register("engine.io/lib/socket.js", function(exports, require, module){
/**
* Module dependencies.
*/
-var util = require('./util');
-var parser = require('engine.io-parser');
-var Emitter = require('./emitter');
+var util = require('./util')
+ , transports = require('./transports')
+ , Emitter = require('./emitter')
+ , debug = require('debug')('engine-client:socket')
+ , index = require('indexof')
+ , parser = require('engine.io-parser');
/**
* Module exports.
*/
-module.exports = Transport;
+module.exports = Socket;
/**
- * Transport abstract constructor.
- *
- * @param {Object} options.
- * @api private
+ * Global reference.
*/
-function Transport (opts) {
- this.path = opts.path;
- this.hostname = opts.hostname;
- this.port = opts.port;
- this.secure = opts.secure;
- this.query = opts.query;
- this.timestampParam = opts.timestampParam;
- this.timestampRequests = opts.timestampRequests;
- this.readyState = '';
- this.agent = opts.agent || false;
-}
+var global = util.global();
/**
- * Mix in `Emitter`.
+ * Noop function.
+ *
+ * @api private
*/
-Emitter(Transport.prototype);
+function noop () {};
/**
- * Emits an error.
+ * Socket constructor.
*
- * @param {String} str
- * @return {Transport} for chaining
+ * @param {String|Object} uri or options
+ * @param {Object} options
* @api public
*/
-Transport.prototype.onError = function (msg, desc) {
- var err = new Error(msg);
- err.type = 'TransportError';
- err.description = desc;
- this.emit('error', err);
- return this;
+function Socket(uri, opts){
+ if (!(this instanceof Socket)) return new Socket(uri, opts);
+
+ opts = opts || {};
+
+ if ('object' == typeof uri) {
+ opts = uri;
+ uri = null;
+ }
+
+ if (uri) {
+ uri = util.parseUri(uri);
+ opts.host = uri.host;
+ opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
+ opts.port = uri.port;
+ if (uri.query) opts.query = uri.query;
+ }
+
+ this.secure = null != opts.secure ? opts.secure :
+ (global.location && 'https:' == location.protocol);
+
+ if (opts.host) {
+ var pieces = opts.host.split(':');
+ opts.hostname = pieces.shift();
+ if (pieces.length) opts.port = pieces.pop();
+ }
+
+ this.hostname = opts.hostname ||
+ (global.location ? location.hostname : 'localhost');
+ this.port = opts.port || (global.location && location.port ?
+ location.port :
+ (this.secure ? 443 : 80));
+ this.query = opts.query || {};
+ if ('string' == typeof this.query) this.query = util.qsParse(this.query);
+ this.upgrade = false !== opts.upgrade;
+ this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
+ this.forceJSONP = !!opts.forceJSONP;
+ this.timestampParam = opts.timestampParam || 't';
+ this.timestampRequests = !!opts.timestampRequests;
+ this.flashPath = opts.flashPath || '';
+ this.transports = opts.transports || ['polling', 'websocket', 'flashsocket'];
+ this.readyState = '';
+ this.writeBuffer = [];
+ this.callbackBuffer = [];
+ this.policyPort = opts.policyPort || 843;
+ this.open();
+
+ Socket.sockets.push(this);
+ Socket.sockets.evs.emit('add', this);
};
/**
- * Opens the transport.
+ * Mix in `Emitter`.
+ */
+
+Emitter(Socket.prototype);
+
+/**
+ * Protocol version.
*
* @api public
*/
-Transport.prototype.open = function () {
- if ('closed' == this.readyState || '' == this.readyState) {
- this.readyState = 'opening';
- this.doOpen();
- }
-
- return this;
-};
+Socket.protocol = parser.protocol; // this is an int
/**
- * Closes the transport.
- *
- * @api private
+ * Static EventEmitter.
*/
-Transport.prototype.close = function () {
- if ('opening' == this.readyState || 'open' == this.readyState) {
- this.doClose();
- this.onClose();
- }
+Socket.sockets = [];
+Socket.sockets.evs = new Emitter;
- return this;
-};
+/**
+ * Expose deps for legacy compatibility
+ * and standalone browser access.
+ */
+
+Socket.Socket = Socket;
+Socket.Transport = require('./transport');
+Socket.Emitter = require('./emitter');
+Socket.transports = require('./transports');
+Socket.util = require('./util');
+Socket.parser = require('engine.io-parser');
/**
- * Sends multiple packets.
+ * Creates transport of the given type.
*
- * @param {Array} packets
+ * @param {String} transport name
+ * @return {Transport}
* @api private
*/
-Transport.prototype.send = function(packets){
- if ('open' == this.readyState) {
- this.write(packets);
- } else {
- throw new Error('Transport not open');
- }
+Socket.prototype.createTransport = function (name) {
+ debug('creating transport "%s"', name);
+ var query = clone(this.query);
+
+ // append engine.io protocol identifier
+ query.EIO = parser.protocol;
+
+ // transport name
+ query.transport = name;
+
+ // session id if we already have one
+ if (this.id) query.sid = this.id;
+
+ var transport = new transports[name]({
+ hostname: this.hostname,
+ port: this.port,
+ secure: this.secure,
+ path: this.path,
+ query: query,
+ forceJSONP: this.forceJSONP,
+ timestampRequests: this.timestampRequests,
+ timestampParam: this.timestampParam,
+ flashPath: this.flashPath,
+ policyPort: this.policyPort
+ });
+
+ return transport;
};
+function clone (obj) {
+ var o = {};
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ o[i] = obj[i];
+ }
+ }
+ return o;
+}
+
/**
- * Called upon open
+ * Initializes transport to use and starts probe.
*
* @api private
*/
-Transport.prototype.onOpen = function () {
- this.readyState = 'open';
- this.writable = true;
- this.emit('open');
+Socket.prototype.open = function () {
+ this.readyState = 'opening';
+ var transport = this.createTransport(this.transports[0]);
+ transport.open();
+ this.setTransport(transport);
};
/**
- * Called with data.
+ * Sets the current transport. Disables the existing one (if any).
*
- * @param {String} data
* @api private
*/
-Transport.prototype.onData = function (data) {
- this.onPacket(parser.decodePacket(data));
-};
+Socket.prototype.setTransport = function (transport) {
+ var self = this;
-/**
- * Called with a decoded packet.
- */
+ if (this.transport) {
+ debug('clearing existing transport');
+ this.transport.removeAllListeners();
+ }
-Transport.prototype.onPacket = function (packet) {
- this.emit('packet', packet);
+ // set up transport
+ this.transport = transport;
+
+ // set up transport listeners
+ transport
+ .on('drain', function () {
+ self.onDrain();
+ })
+ .on('packet', function (packet) {
+ self.onPacket(packet);
+ })
+ .on('error', function (e) {
+ self.onError(e);
+ })
+ .on('close', function () {
+ self.onClose('transport close');
+ });
};
/**
- * Called upon close.
+ * Probes a transport.
*
+ * @param {String} transport name
* @api private
*/
-Transport.prototype.onClose = function () {
- this.readyState = 'closed';
- this.emit('close');
-};
-
-},{"./emitter":2,"./util":12,"engine.io-parser":16}],6:[function(require,module,exports){
+Socket.prototype.probe = function (name) {
+ debug('probing transport "%s"', name);
+ var transport = this.createTransport(name, { probe: 1 })
+ , failed = false
+ , self = this;
-/**
- * Module dependencies.
- */
+ transport.once('open', function () {
+ if (failed) return;
-var WS = require('./websocket');
-var util = require('../util');
-var debug = require('debug')('engine.io-client:flashsocket');
+ debug('probe transport "%s" opened', name);
+ transport.send([{ type: 'ping', data: 'probe' }]);
+ transport.once('packet', function (msg) {
+ if (failed) return;
+ if ('pong' == msg.type && 'probe' == msg.data) {
+ debug('probe transport "%s" pong', name);
+ self.upgrading = true;
+ self.emit('upgrading', transport);
-/**
- * Module exports.
- */
+ debug('pausing current transport "%s"', self.transport.name);
+ self.transport.pause(function () {
+ if (failed) return;
+ if ('closed' == self.readyState || 'closing' == self.readyState) {
+ return;
+ }
+ debug('changing transport and sending upgrade packet');
+ transport.removeListener('error', onerror);
+ self.emit('upgrade', transport);
+ self.setTransport(transport);
+ transport.send([{ type: 'upgrade' }]);
+ transport = null;
+ self.upgrading = false;
+ self.flush();
+ });
+ } else {
+ debug('probe transport "%s" failed', name);
+ var err = new Error('probe error');
+ err.transport = transport.name;
+ self.emit('error', err);
+ }
+ });
+ });
-module.exports = FlashWS;
+ transport.once('error', onerror);
+ function onerror(err) {
+ if (failed) return;
-/**
- * Global reference.
- */
+ // Any callback called by transport should be ignored since now
+ failed = true;
-var global = require('global');
+ var error = new Error('probe error: ' + err);
+ error.transport = transport.name;
-/**
- * Obfuscated key for Blue Coat.
- */
+ transport.close();
+ transport = null;
-var xobject = global[['Active'].concat('Object').join('X')];
+ debug('probe transport "%s" failed because of error: %s', name, err);
-/**
- * FlashWS constructor.
- *
- * @api public
- */
+ self.emit('error', error);
+ };
-function FlashWS(options){
- WS.call(this, options);
- this.flashPath = options.flashPath;
- this.policyPort = options.policyPort;
-}
+ transport.open();
-/**
- * Inherits from WebSocket.
- */
+ this.once('close', function () {
+ if (transport) {
+ debug('socket closed prematurely - aborting probe');
+ failed = true;
+ transport.close();
+ transport = null;
+ }
+ });
-util.inherits(FlashWS, WS);
+ this.once('upgrading', function (to) {
+ if (transport && to.name != transport.name) {
+ debug('"%s" works - aborting "%s"', to.name, transport.name);
+ transport.close();
+ transport = null;
+ }
+ });
+};
/**
- * Transport name.
+ * Called when connection is deemed open.
*
* @api public
*/
-FlashWS.prototype.name = 'flashsocket';
+Socket.prototype.onOpen = function () {
+ debug('socket open');
+ this.readyState = 'open';
+ this.emit('open');
+ this.onopen && this.onopen.call(this);
+ this.flush();
+
+ // we check for `readyState` in case an `open`
+ // listener alreay closed the socket
+ if ('open' == this.readyState && this.upgrade && this.transport.pause) {
+ debug('starting upgrade probes');
+ for (var i = 0, l = this.upgrades.length; i < l; i++) {
+ this.probe(this.upgrades[i]);
+ }
+ }
+};
/**
- * Opens the transport.
+ * Handles a packet.
*
- * @api public
+ * @api private
*/
-FlashWS.prototype.doOpen = function(){
- if (!this.check()) {
- // let the probe timeout
- return;
- }
-
- // instrument websocketjs logging
- function log(type){
- return function(){
- var str = Array.prototype.join.call(arguments, ' ');
- debug('[websocketjs %s] %s', type, str);
- };
- }
+Socket.prototype.onPacket = function (packet) {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
- global.WEB_SOCKET_LOGGER = { log: log('debug'), error: log('error') };
- global.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;
- global.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true;
+ this.emit('packet', packet);
- if (!global.WEB_SOCKET_SWF_LOCATION) {
- global.WEB_SOCKET_SWF_LOCATION = this.flashPath + 'WebSocketMainInsecure.swf';
- }
+ // Socket is live - any packet counts
+ this.emit('heartbeat');
- // dependencies
- var deps = [this.flashPath + 'web_socket.js'];
+ switch (packet.type) {
+ case 'open':
+ this.onHandshake(util.parseJSON(packet.data));
+ break;
- if (!global.swfobject) {
- deps.unshift(this.flashPath + 'swfobject.js');
- }
+ case 'pong':
+ this.setPing();
+ break;
- var self = this;
+ case 'error':
+ var err = new Error('server error');
+ err.code = packet.data;
+ this.emit('error', err);
+ break;
- load(deps, function(){
- self.ready(function(){
- WebSocket.__addTask(function () {
- self.socket = new WebSocket(self.uri());
- self.addEventListeners();
- });
- });
- });
+ case 'message':
+ this.emit('data', packet.data);
+ this.emit('message', packet.data);
+ var event = { data: packet.data };
+ event.toString = function () {
+ return packet.data;
+ };
+ this.onmessage && this.onmessage.call(this, event);
+ break;
+ }
+ } else {
+ debug('packet received with socket readyState "%s"', this.readyState);
+ }
};
/**
- * Override to prevent closing uninitialized flashsocket.
+ * Called upon handshake completion.
*
+ * @param {Object} handshake obj
* @api private
*/
-FlashWS.prototype.doClose = function(){
- if (!this.socket) return;
- var self = this;
- WebSocket.__addTask(function(){
- WS.prototype.doClose.call(self);
- });
+Socket.prototype.onHandshake = function (data) {
+ this.emit('handshake', data);
+ this.id = data.sid;
+ this.transport.query.sid = data.sid;
+ this.upgrades = this.filterUpgrades(data.upgrades);
+ this.pingInterval = data.pingInterval;
+ this.pingTimeout = data.pingTimeout;
+ this.onOpen();
+ this.setPing();
+
+ // Prolong liveness of socket on heartbeat
+ this.removeListener('heartbeat', this.onHeartbeat);
+ this.on('heartbeat', this.onHeartbeat);
};
/**
- * Writes to the Flash socket.
+ * Resets ping timeout.
*
* @api private
*/
-FlashWS.prototype.write = function(){
- var self = this, args = arguments;
- WebSocket.__addTask(function(){
- WS.prototype.write.apply(self, args);
- });
+Socket.prototype.onHeartbeat = function (timeout) {
+ clearTimeout(this.pingTimeoutTimer);
+ var self = this;
+ self.pingTimeoutTimer = setTimeout(function () {
+ if ('closed' == self.readyState) return;
+ self.onClose('ping timeout');
+ }, timeout || (self.pingInterval + self.pingTimeout));
};
/**
- * Called upon dependencies are loaded.
+ * Pings server every `this.pingInterval` and expects response
+ * within `this.pingTimeout` or closes connection.
*
* @api private
*/
-FlashWS.prototype.ready = function(fn){
- if (typeof WebSocket == 'undefined' ||
- !('__initialize' in WebSocket) || !global.swfobject) {
- return;
- }
-
- if (global.swfobject.getFlashPlayerVersion().major < 10) {
- return;
- }
-
- function init () {
- // only start downloading the swf file when
- // we checked that this browser actually supports it
- if (!FlashWS.loaded) {
- if (843 != self.policyPort) {
- var policy = 'xmlsocket://' + self.hostname + ':' + self.policyPort;
- WebSocket.loadFlashPolicyFile(policy);
- }
-
- WebSocket.__initialize();
- FlashWS.loaded = true;
- }
-
- fn.call(self);
- }
-
+Socket.prototype.setPing = function () {
var self = this;
- if (document.body) {
- return init();
- }
+ clearTimeout(self.pingIntervalTimer);
+ self.pingIntervalTimer = setTimeout(function () {
+ debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
+ self.ping();
+ self.onHeartbeat(self.pingTimeout);
+ }, self.pingInterval);
+};
- util.load(init);
+/**
+* Sends a ping packet.
+*
+* @api public
+*/
+
+Socket.prototype.ping = function () {
+ this.sendPacket('ping');
};
/**
- * Feature detection for flashsocket.
+ * Called on `drain` event
*
- * @return {Boolean} whether this transport is available.
- * @api public
+ * @api private
*/
-FlashWS.prototype.check = function(){
- if ('undefined' == typeof window) {
- return false;
+ Socket.prototype.onDrain = function() {
+ for (var i = 0; i < this.prevBufferLen; i++) {
+ if (this.callbackBuffer[i]) {
+ this.callbackBuffer[i]();
+ }
}
- if (typeof WebSocket != 'undefined' && !('__initialize' in WebSocket)) {
- return false;
- }
+ this.writeBuffer.splice(0, this.prevBufferLen);
+ this.callbackBuffer.splice(0, this.prevBufferLen);
- if (xobject) {
- var control = null;
- try {
- control = new xobject('ShockwaveFlash.ShockwaveFlash');
- } catch (e) { }
- if (control) {
- return true;
- }
+ // setting prevBufferLen = 0 is very important
+ // for example, when upgrading, upgrade packet is sent over,
+ // and a nonzero prevBufferLen could cause problems on `drain`
+ this.prevBufferLen = 0;
+
+ if (this.writeBuffer.length == 0) {
+ this.emit('drain');
} else {
- for (var i = 0, l = navigator.plugins.length; i < l; i++) {
- for (var j = 0, m = navigator.plugins[i].length; j < m; j++) {
- if (navigator.plugins[i][j].description == 'Shockwave Flash') {
- return true;
- }
- }
- }
+ this.flush();
}
-
- return false;
};
/**
- * Lazy loading of scripts.
- * Based on $script by Dustin Diaz - MIT
- */
-
-var scripts = {};
-
-/**
- * Injects a script. Keeps tracked of injected ones.
+ * Flush write buffers.
*
- * @param {String} path
- * @param {Function} callback
* @api private
*/
-function create(path, fn){
- if (scripts[path]) return fn();
-
- var el = document.createElement('script');
- var loaded = false;
-
- debug('loading "%s"', path);
- el.onload = el.onreadystatechange = function(){
- if (loaded || scripts[path]) return;
- var rs = el.readyState;
- if (!rs || 'loaded' == rs || 'complete' == rs) {
- debug('loaded "%s"', path);
- el.onload = el.onreadystatechange = null;
- loaded = true;
- scripts[path] = true;
- fn();
- }
- };
-
- el.async = 1;
- el.src = path;
-
- var head = document.getElementsByTagName('head')[0];
- head.insertBefore(el, head.firstChild);
-}
+Socket.prototype.flush = function () {
+ if ('closed' != this.readyState && this.transport.writable &&
+ !this.upgrading && this.writeBuffer.length) {
+ debug('flushing %d packets in socket', this.writeBuffer.length);
+ this.transport.send(this.writeBuffer);
+ // keep track of current length of writeBuffer
+ // splice writeBuffer and callbackBuffer on `drain`
+ this.prevBufferLen = this.writeBuffer.length;
+ this.emit('flush');
+ }
+};
/**
- * Loads scripts and fires a callback.
+ * Sends a message.
*
- * @param {Array} paths
- * @param {Function} callback
+ * @param {String} message.
+ * @param {Function} callback function.
+ * @return {Socket} for chaining.
+ * @api public
*/
-function load(arr, fn){
- function process(i){
- if (!arr[i]) return fn();
- create(arr[i], function () {
- process(++i);
- });
- }
-
- process(0);
-}
-
-},{"../util":12,"./websocket":11,"debug":14,"global":19}],7:[function(require,module,exports){
+Socket.prototype.write =
+Socket.prototype.send = function (msg, fn) {
+ this.sendPacket('message', msg, fn);
+ return this;
+};
/**
- * Module dependencies
+ * Sends a packet.
+ *
+ * @param {String} packet type.
+ * @param {String} data.
+ * @param {Function} callback function.
+ * @api private
*/
-var XMLHttpRequest = require('xmlhttprequest')
- , XHR = require('./polling-xhr')
- , JSONP = require('./polling-jsonp')
- , websocket = require('./websocket')
- , flashsocket = require('./flashsocket')
+Socket.prototype.sendPacket = function (type, data, fn) {
+ var packet = { type: type, data: data };
+ this.emit('packetCreate', packet);
+ this.writeBuffer.push(packet);
+ this.callbackBuffer.push(fn);
+ this.flush();
+};
/**
- * Export transports.
+ * Closes the connection.
+ *
+ * @api private
*/
-exports.polling = polling;
-exports.websocket = websocket;
-exports.flashsocket = flashsocket;
+Socket.prototype.close = function () {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ this.onClose('forced close');
+ debug('socket closing - telling transport to close');
+ this.transport.close();
+ }
+
+ return this;
+};
/**
- * Global reference.
+ * Called upon transport error
+ *
+ * @api private
*/
-var global = require('global');
+Socket.prototype.onError = function (err) {
+ debug('socket error %j', err);
+ this.emit('error', err);
+ this.onerror && this.onerror.call(this, err);
+ this.onClose('transport error', err);
+};
/**
- * Polling transport polymorphic constructor.
- * Decides on xhr vs jsonp based on feature detection.
+ * Called upon transport close.
*
* @api private
*/
-function polling (opts) {
- var xhr
- , xd = false;
+Socket.prototype.onClose = function (reason, desc) {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ debug('socket close with reason: "%s"', reason);
+ var self = this;
- if (global.location) {
- var isSSL = 'https:' == location.protocol;
- var port = location.port;
+ // clear timers
+ clearTimeout(this.pingIntervalTimer);
+ clearTimeout(this.pingTimeoutTimer);
- // some user agents have empty `location.port`
- if (!port) {
- port = isSSL ? 443 : 80;
- }
+ // clean buffers in next tick, so developers can still
+ // grab the buffers on `close` event
+ setTimeout(function() {
+ self.writeBuffer = [];
+ self.callbackBuffer = [];
+ }, 0);
+
+ // ignore further transport communication
+ this.transport.removeAllListeners();
- xd = opts.hostname != location.hostname || port != opts.port;
- }
+ // set ready state
+ var prev = this.readyState;
+ this.readyState = 'closed';
- opts.xdomain = xd;
- xhr = new XMLHttpRequest(opts);
+ // clear session id
+ this.id = null;
- if (xhr && !opts.forceJSONP) {
- return new XHR(opts);
- } else {
- return new JSONP(opts);
+ // emit events
+ if (prev == 'open') {
+ this.emit('close', reason, desc);
+ this.onclose && this.onclose.call(this);
+ }
}
};
-},{"./flashsocket":6,"./polling-jsonp":8,"./polling-xhr":9,"./websocket":11,"global":19,"xmlhttprequest":13}],8:[function(require,module,exports){
-
/**
- * Module requirements.
+ * Filters upgrades, returning only those matching client transports.
+ *
+ * @param {Array} server upgrades
+ * @api private
+ *
*/
-var Polling = require('./polling');
-var util = require('../util');
-
-/**
- * Module exports.
- */
+Socket.prototype.filterUpgrades = function (upgrades) {
+ var filteredUpgrades = [];
+ for (var i = 0, j = upgrades.length; i<j; i++) {
+ if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
+ }
+ return filteredUpgrades;
+};
-module.exports = JSONPPolling;
+});
+require.register("engine.io/lib/transport.js", function(exports, require, module){
/**
- * Global reference.
+ * Module dependencies.
*/
-var global = require('global');
+var util = require('./util')
+ , parser = require('engine.io-parser')
+ , Emitter = require('./emitter');
/**
- * Cached regular expressions.
+ * Module exports.
*/
-var rNewline = /\n/g;
+module.exports = Transport;
/**
- * Global JSONP callbacks.
+ * Transport abstract constructor.
+ *
+ * @param {Object} options.
+ * @api private
*/
-var callbacks;
+function Transport (opts) {
+ this.path = opts.path;
+ this.hostname = opts.hostname;
+ this.port = opts.port;
+ this.secure = opts.secure;
+ this.query = opts.query;
+ this.timestampParam = opts.timestampParam;
+ this.timestampRequests = opts.timestampRequests;
+ this.readyState = '';
+};
/**
- * Callbacks count.
+ * Mix in `Emitter`.
*/
-var index = 0;
+Emitter(Transport.prototype);
/**
- * Noop.
+ * Emits an error.
+ *
+ * @param {String} str
+ * @return {Transport} for chaining
+ * @api public
*/
-function empty () { }
+Transport.prototype.onError = function (msg, desc) {
+ var err = new Error(msg);
+ err.type = 'TransportError';
+ err.description = desc;
+ this.emit('error', err);
+ return this;
+};
/**
- * JSONP Polling constructor.
+ * Opens the transport.
*
- * @param {Object} opts.
* @api public
*/
-function JSONPPolling (opts) {
- Polling.call(this, opts);
-
- // define global callbacks array if not present
- // we do this here (lazily) to avoid unneeded global pollution
- if (!callbacks) {
- // we need to consider multiple engines in the same page
- if (!global.___eio) global.___eio = [];
- callbacks = global.___eio;
+Transport.prototype.open = function () {
+ if ('closed' == this.readyState || '' == this.readyState) {
+ this.readyState = 'opening';
+ this.doOpen();
}
- // callback identifier
- this.index = callbacks.length;
-
- // add callback to jsonp global
- var self = this;
- callbacks.push(function (msg) {
- self.onData(msg);
- });
-
- // append to query string
- this.query.j = this.index;
-}
-
-/**
- * Inherits from Polling.
- */
-
-util.inherits(JSONPPolling, Polling);
+ return this;
+};
/**
- * Closes the socket
+ * Closes the transport.
*
* @api private
*/
-JSONPPolling.prototype.doClose = function () {
- if (this.script) {
- this.script.parentNode.removeChild(this.script);
- this.script = null;
- }
-
- if (this.form) {
- this.form.parentNode.removeChild(this.form);
- this.form = null;
+Transport.prototype.close = function () {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ this.doClose();
+ this.onClose();
}
- Polling.prototype.doClose.call(this);
+ return this;
};
/**
- * Starts a poll cycle.
+ * Sends multiple packets.
*
+ * @param {Array} packets
* @api private
*/
-JSONPPolling.prototype.doPoll = function () {
- var self = this;
- var script = document.createElement('script');
-
- if (this.script) {
- this.script.parentNode.removeChild(this.script);
- this.script = null;
- }
-
- script.async = true;
- script.src = this.uri();
- script.onerror = function(e){
- self.onError('jsonp poll error',e);
- };
-
- var insertAt = document.getElementsByTagName('script')[0];
- insertAt.parentNode.insertBefore(script, insertAt);
- this.script = script;
-
-
- if (util.ua.gecko) {
- setTimeout(function () {
- var iframe = document.createElement('iframe');
- document.body.appendChild(iframe);
- document.body.removeChild(iframe);
- }, 100);
+Transport.prototype.send = function(packets){
+ if ('open' == this.readyState) {
+ this.write(packets);
+ } else {
+ throw new Error('Transport not open');
}
};
/**
- * Writes with a hidden iframe.
+ * Called upon open
*
- * @param {String} data to send
- * @param {Function} called upon flush.
* @api private
*/
-JSONPPolling.prototype.doWrite = function (data, fn) {
- var self = this;
-
- if (!this.form) {
- var form = document.createElement('form');
- var area = document.createElement('textarea');
- var id = this.iframeId = 'eio_iframe_' + this.index;
- var iframe;
-
- form.className = 'socketio';
- form.style.position = 'absolute';
- form.style.top = '-1000px';
- form.style.left = '-1000px';
- form.target = id;
- form.method = 'POST';
- form.setAttribute('accept-charset', 'utf-8');
- area.name = 'd';
- form.appendChild(area);
- document.body.appendChild(form);
-
- this.form = form;
- this.area = area;
- }
-
- this.form.action = this.uri();
-
- function complete () {
- initIframe();
- fn();
- }
-
- function initIframe () {
- if (self.iframe) {
- try {
- self.form.removeChild(self.iframe);
- } catch (e) {
- self.onError('jsonp polling iframe removal error', e);
- }
- }
-
- try {
- // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
- var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
- iframe = document.createElement(html);
- } catch (e) {
- iframe = document.createElement('iframe');
- iframe.name = self.iframeId;
- iframe.src = 'javascript:0';
- }
+Transport.prototype.onOpen = function () {
+ this.readyState = 'open';
+ this.writable = true;
+ this.emit('open');
+};
- iframe.id = self.iframeId;
+/**
+ * Called with data.
+ *
+ * @param {String} data
+ * @api private
+ */
- self.form.appendChild(iframe);
- self.iframe = iframe;
- }
+Transport.prototype.onData = function (data) {
+ this.onPacket(parser.decodePacket(data));
+};
- initIframe();
+/**
+ * Called with a decoded packet.
+ */
- // escape \n to prevent it from being converted into \r\n by some UAs
- this.area.value = data.replace(rNewline, '\\n');
+Transport.prototype.onPacket = function (packet) {
+ this.emit('packet', packet);
+};
- try {
- this.form.submit();
- } catch(e) {}
+/**
+ * Called upon close.
+ *
+ * @api private
+ */
- if (this.iframe.attachEvent) {
- this.iframe.onreadystatechange = function(){
- if (self.iframe.readyState == 'complete') {
- complete();
- }
- };
- } else {
- this.iframe.onload = complete;
- }
+Transport.prototype.onClose = function () {
+ this.readyState = 'closed';
+ this.emit('close');
};
-},{"../util":12,"./polling":10,"global":19}],9:[function(require,module,exports){
+});
+require.register("engine.io/lib/emitter.js", function(exports, require, module){
+
/**
- * Module requirements.
+ * Module dependencies.
*/
-var XMLHttpRequest = require('xmlhttprequest');
-var Polling = require('./polling');
-var util = require('../util');
-var Emitter = require('../emitter');
-var debug = require('debug')('engine.io-client:polling-xhr');
+var Emitter = require('emitter');
/**
* Module exports.
*/
-module.exports = XHR;
-module.exports.Request = Request;
+module.exports = Emitter;
/**
- * Global reference.
+ * Compatibility with `WebSocket#addEventListener`.
+ *
+ * @api public
*/
-var global = require('global');
+Emitter.prototype.addEventListener = Emitter.prototype.on;
/**
- * Obfuscated key for Blue Coat.
+ * Compatibility with `WebSocket#removeEventListener`.
+ *
+ * @api public
*/
-var hasAttachEvent = global.document && global.document.attachEvent;
+Emitter.prototype.removeEventListener = Emitter.prototype.off;
/**
- * Empty function
+ * Node-compatible `EventEmitter#removeListener`
+ *
+ * @api public
*/
-function empty(){}
+Emitter.prototype.removeListener = Emitter.prototype.off;
+
+});
+require.register("engine.io/lib/util.js", function(exports, require, module){
+/**
+ * Status of page load.
+ */
+
+var pageLoaded = false;
/**
- * XHR Polling constructor.
+ * Returns the global object
*
- * @param {Object} opts
- * @api public
+ * @api private
*/
-function XHR(opts){
- Polling.call(this, opts);
+exports.global = function () {
+ return 'undefined' != typeof window ? window : global;
+};
- if (global.location) {
- var isSSL = 'https:' == location.protocol;
- var port = location.port;
+/**
+ * Inheritance.
+ *
+ * @param {Function} ctor a
+ * @param {Function} ctor b
+ * @api private
+ */
- // some user agents have empty `location.port`
- if (!port) {
- port = isSSL ? 443 : 80;
- }
+exports.inherits = function inherits (a, b) {
+ function c () { }
+ c.prototype = b.prototype;
+ a.prototype = new c;
+};
- this.xd = opts.hostname != global.location.hostname ||
- port != opts.port;
+/**
+ * Object.keys
+ */
+
+exports.keys = Object.keys || function (obj) {
+ var ret = [];
+ var has = Object.prototype.hasOwnProperty;
+
+ for (var i in obj) {
+ if (has.call(obj, i)) {
+ ret.push(i);
+ }
}
-}
+
+ return ret;
+};
/**
- * Inherits from Polling.
+ * Adds an event.
+ *
+ * @api private
*/
-util.inherits(XHR, Polling);
+exports.on = function (element, event, fn, capture) {
+ if (element.attachEvent) {
+ element.attachEvent('on' + event, fn);
+ } else if (element.addEventListener) {
+ element.addEventListener(event, fn, capture);
+ }
+};
/**
- * Creates a request.
+ * Load utility.
*
- * @param {String} method
* @api private
*/
-XHR.prototype.request = function(opts){
- opts = opts || {};
- opts.uri = this.uri();
- opts.xd = this.xd;
- opts.agent = this.agent || false;
- return new Request(opts);
+exports.load = function (fn) {
+ var global = exports.global();
+ if (global.document && document.readyState === 'complete' || pageLoaded) {
+ return fn();
+ }
+
+ exports.on(global, 'load', fn, false);
};
/**
- * Sends data.
+ * Change the internal pageLoaded value.
+ */
+
+if ('undefined' != typeof window) {
+ exports.load(function () {
+ pageLoaded = true;
+ });
+}
+
+/**
+ * Defers a function to ensure a spinner is not displayed by the browser.
*
- * @param {String} data to send.
- * @param {Function} called upon flush.
+ * @param {Function} fn
* @api private
*/
-XHR.prototype.doWrite = function(data, fn){
- var req = this.request({ method: 'POST', data: data });
- var self = this;
- req.on('success', fn);
- req.on('error', function(err){
- self.onError('xhr post error', err);
+exports.defer = function (fn) {
+ if (!exports.ua.webkit || 'undefined' != typeof importScripts) {
+ return fn();
+ }
+
+ exports.load(function () {
+ setTimeout(fn, 100);
});
- this.sendXhr = req;
};
/**
- * Starts a poll cycle.
+ * JSON parse.
*
+ * @see Based on jQuery#parseJSON (MIT) and JSON2
* @api private
*/
-XHR.prototype.doPoll = function(){
- debug('xhr poll');
- var req = this.request();
- var self = this;
- req.on('data', function(data){
- self.onData(data);
- });
- req.on('error', function(err){
- self.onError('xhr poll error', err);
- });
- this.pollXhr = req;
+var rvalidchars = /^[\],:{}\s]*$/;
+var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
+var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
+var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
+var rtrimLeft = /^\s+/;
+var rtrimRight = /\s+$/;
+
+exports.parseJSON = function (data) {
+ var global = exports.global();
+
+ if ('string' != typeof data || !data) {
+ return null;
+ }
+
+ data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
+
+ // Attempt to parse using the native JSON parser first
+ if (global.JSON && JSON.parse) {
+ return JSON.parse(data);
+ }
+
+ if (rvalidchars.test(data.replace(rvalidescape, '@')
+ .replace(rvalidtokens, ']')
+ .replace(rvalidbraces, ''))) {
+ return (new Function('return ' + data))();
+ }
};
/**
- * Request constructor
+ * UA / engines detection namespace.
*
- * @param {Object} options
- * @api public
+ * @namespace
*/
-function Request(opts){
- this.method = opts.method || 'GET';
- this.uri = opts.uri;
- this.xd = !!opts.xd;
- this.async = false !== opts.async;
- this.data = undefined != opts.data ? opts.data : null;
- this.agent = opts.agent;
- this.create();
-}
+exports.ua = {};
/**
- * Mix in `Emitter`.
+ * Whether the UA supports CORS for XHR.
+ *
+ * @api private
*/
-Emitter(Request.prototype);
+exports.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
+ var a;
+ try {
+ a = new XMLHttpRequest();
+ } catch (e) {
+ return false;
+ }
+
+ return a.withCredentials != undefined;
+})();
/**
- * Creates the XHR object and sends the request.
+ * Detect webkit.
*
* @api private
*/
-Request.prototype.create = function(){
- var xhr = this.xhr = new XMLHttpRequest({ agent: this.agent, xdomain: this.xd });
- var self = this;
+exports.ua.webkit = 'undefined' != typeof navigator &&
+ /webkit/i.test(navigator.userAgent);
- try {
- debug('xhr open %s: %s', this.method, this.uri);
- xhr.open(this.method, this.uri, this.async);
+/**
+ * Detect gecko.
+ *
+ * @api private
+ */
- if ('POST' == this.method) {
- try {
- xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
- } catch (e) {}
- }
+exports.ua.gecko = 'undefined' != typeof navigator &&
+ /gecko/i.test(navigator.userAgent);
- // ie6 check
- if ('withCredentials' in xhr) {
- xhr.withCredentials = true;
- }
+/**
+ * Detect android;
+ */
- xhr.onreadystatechange = function(){
- var data;
+exports.ua.android = 'undefined' != typeof navigator &&
+ /android/i.test(navigator.userAgent);
- try {
- if (4 != xhr.readyState) return;
- if (200 == xhr.status || 1223 == xhr.status) {
- data = xhr.responseText;
- } else {
- // make sure the `error` event handler that's user-set
- // does not throw in the same tick and gets caught here
- setTimeout(function(){
- self.onError(xhr.status);
- }, 0);
- }
- } catch (e) {
- self.onError(e);
- }
+/**
+ * Detect iOS.
+ */
- if (null != data) {
- self.onData(data);
- }
- };
+exports.ua.ios = 'undefined' != typeof navigator &&
+ /^(iPad|iPhone|iPod)$/.test(navigator.platform);
+exports.ua.ios6 = exports.ua.ios && /OS 6_/.test(navigator.userAgent);
- debug('xhr data %s', this.data);
- xhr.send(this.data);
- } catch (e) {
- // Need to defer since .create() is called directly from the constructor
- // and thus the 'error' event can only be only bound *after* this exception
- // occurs. Therefore, also, we cannot throw here at all.
- setTimeout(function() {
- self.onError(e);
- }, 0);
- return;
+/**
+ * XHR request helper.
+ *
+ * @param {Boolean} whether we need xdomain
+ * @api private
+ */
+
+exports.request = function request (xdomain) {
+ try {
+ var _XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
+ return new _XMLHttpRequest();
+ } catch (e) {}
+
+ if (xdomain && 'undefined' != typeof XDomainRequest && !exports.ua.hasCORS) {
+ return new XDomainRequest();
}
- if (hasAttachEvent) {
- this.index = Request.requestsCount++;
- Request.requests[this.index] = this;
+ // XMLHttpRequest can be disabled on IE
+ try {
+ if ('undefined' != typeof XMLHttpRequest && (!xdomain || exports.ua.hasCORS)) {
+ return new XMLHttpRequest();
+ }
+ } catch (e) { }
+
+ if (!xdomain) {
+ try {
+ return new ActiveXObject('Microsoft.XMLHTTP');
+ } catch(e) { }
}
};
/**
- * Called upon successful response.
+ * Parses an URI
*
+ * @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
-Request.prototype.onSuccess = function(){
- this.emit('success');
- this.cleanup();
+var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
+
+var parts = [
+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
+ , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
+];
+
+exports.parseUri = function (str) {
+ var m = re.exec(str || '')
+ , uri = {}
+ , i = 14;
+
+ while (i--) {
+ uri[parts[i]] = m[i] || '';
+ }
+
+ return uri;
};
/**
- * Called if we have data.
+ * Compiles a querystring
*
+ * @param {Object}
* @api private
*/
-Request.prototype.onData = function(data){
- this.emit('data', data);
- this.onSuccess();
+exports.qs = function (obj) {
+ var str = '';
+
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if (str.length) str += '&';
+ str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
+ }
+ }
+
+ return str;
};
/**
- * Called upon error.
+ * Parses a simple querystring.
*
+ * @param {String} qs
* @api private
*/
-Request.prototype.onError = function(err){
- this.emit('error', err);
- this.cleanup();
+exports.qsParse = function(qs){
+ var qry = {};
+ var pairs = qs.split('&');
+ for (var i = 0, l = pairs.length; i < l; i++) {
+ var pair = pairs[i].split('=');
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
+ }
+ return qry;
};
+});
+require.register("engine.io/lib/transports/index.js", function(exports, require, module){
+
/**
- * Cleans up house.
- *
- * @api private
+ * Module dependencies
*/
-Request.prototype.cleanup = function(){
- if ('undefined' == typeof this.xhr ) {
- return;
- }
- // xmlhttprequest
- this.xhr.onreadystatechange = empty;
-
- try {
- this.xhr.abort();
- } catch(e) {}
+var XHR = require('./polling-xhr')
+ , JSONP = require('./polling-jsonp')
+ , websocket = require('./websocket')
+ , flashsocket = require('./flashsocket')
+ , util = require('../util');
- if (hasAttachEvent) {
- delete Request.requests[this.index];
- }
+/**
+ * Export transports.
+ */
- this.xhr = null;
-};
+exports.polling = polling;
+exports.websocket = websocket;
+exports.flashsocket = flashsocket;
/**
- * Aborts the request.
- *
- * @api public
+ * Global reference.
*/
-Request.prototype.abort = function(){
- this.cleanup();
-};
+var global = util.global()
/**
- * Cleanup is needed for old versions of IE
- * that leak memory unless we abort request before unload.
+ * Polling transport polymorphic constructor.
+ * Decides on xhr vs jsonp based on feature detection.
+ *
+ * @api private
*/
-if (hasAttachEvent) {
- Request.requestsCount = 0;
- Request.requests = {};
+function polling (opts) {
+ var xhr
+ , xd = false
+ , isXProtocol = false;
- global.attachEvent('onunload', function(){
- for (var i in Request.requests) {
- if (Request.requests.hasOwnProperty(i)) {
- Request.requests[i].abort();
- }
+ if (global.location) {
+ var isSSL = 'https:' == location.protocol;
+ var port = location.port;
+
+ // some user agents have empty `location.port`
+ if (Number(port) !== port) {
+ port = isSSL ? 443 : 80;
}
- });
-}
-},{"../emitter":2,"../util":12,"./polling":10,"debug":14,"global":19,"xmlhttprequest":13}],10:[function(require,module,exports){
+ xd = opts.hostname != location.hostname || port != opts.port;
+ isXProtocol = opts.secure != isSSL;
+ }
+
+ xhr = util.request(xd);
+ /* See #7 at http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx */
+ if (isXProtocol && global.XDomainRequest && xhr instanceof global.XDomainRequest) {
+ return new JSONP(opts);
+ }
+
+ if (xhr && !opts.forceJSONP) {
+ return new XHR(opts);
+ } else {
+ return new JSONP(opts);
+ }
+};
+
+});
+require.register("engine.io/lib/transports/polling.js", function(exports, require, module){
/**
* Module dependencies.
*/
-var Transport = require('../transport');
-var util = require('../util');
-var parser = require('engine.io-parser');
-var debug = require('debug')('engine.io-client:polling');
+var Transport = require('../transport')
+ , util = require('../util')
+ , parser = require('engine.io-parser')
+ , debug = require('debug')('engine.io-client:polling');
/**
* Module exports.
* Global reference.
*/
-var global = require('global');
+var global = util.global();
/**
* Polling interface.
self.write([{ type: 'close' }]);
}
- if ('open' == this.readyState) {
+ if (this.open) {
debug('transport open - closing');
close();
} else {
// in case we're trying to close while
// handshaking is in progress (GH-164)
- debug('transport not open - deferring close');
+ debug('transport not open - defering close');
this.once('open', close);
}
};
var port = '';
// cache busting is forced for IE / android / iOS6 ಠ_à²
- if ('ActiveXObject' in global
- || util.ua.chromeframe
- || util.ua.android
- || util.ua.ios6
- || this.timestampRequests) {
- if (false !== this.timestampRequests) {
- query[this.timestampParam] = +new Date;
- }
+ if (global.ActiveXObject || util.ua.android || util.ua.ios6 ||
+ this.timestampRequests) {
+ query[this.timestampParam] = +new Date;
}
query = util.qs(query);
return schema + '://' + this.hostname + port + this.path + query;
};
-},{"../transport":5,"../util":12,"debug":14,"engine.io-parser":16,"global":19}],11:[function(require,module,exports){
-/**
- * Module dependencies.
- */
-
-var Transport = require('../transport');
-var parser = require('engine.io-parser');
-var util = require('../util');
-var debug = require('debug')('engine.io-client:websocket');
-
+});
+require.register("engine.io/lib/transports/polling-xhr.js", function(exports, require, module){
/**
- * `ws` exposes a WebSocket-compatible interface in
- * Node, or the `WebSocket` or `MozWebSocket` globals
- * in the browser.
+ * Module requirements.
*/
-var WebSocket = require('ws');
+var Polling = require('./polling')
+ , util = require('../util')
+ , Emitter = require('../emitter')
+ , debug = require('debug')('engine.io-client:polling-xhr');
/**
* Module exports.
*/
-module.exports = WS;
+module.exports = XHR;
+module.exports.Request = Request;
/**
* Global reference.
*/
-var global = require('global');
+var global = util.global();
+
/**
- * WebSocket transport constructor.
- *
- * @api {Object} connection options
- * @api public
+ * Obfuscated key for Blue Coat.
*/
-function WS(opts){
- Transport.call(this, opts);
-}
+var xobject = global[['Active'].concat('Object').join('X')];
/**
- * Inherits from Transport.
+ * Empty function
*/
-util.inherits(WS, Transport);
+function empty(){}
/**
- * Transport name.
+ * XHR Polling constructor.
*
+ * @param {Object} opts
* @api public
*/
-WS.prototype.name = 'websocket';
+function XHR(opts){
+ Polling.call(this, opts);
+
+ if (global.location) {
+ var isSSL = 'https:' == location.protocol;
+ var port = location.port;
+
+ // some user agents have empty `location.port`
+ if (Number(port) !== port) {
+ port = isSSL ? 443 : 80;
+ }
+
+ this.xd = opts.hostname != global.location.hostname ||
+ port != opts.port;
+ }
+};
/**
- * Opens socket.
+ * Inherits from Polling.
+ */
+
+util.inherits(XHR, Polling);
+
+/**
+ * Opens the socket
*
* @api private
*/
-WS.prototype.doOpen = function(){
- if (!this.check()) {
- // let probe timeout
- return;
- }
-
+XHR.prototype.doOpen = function(){
var self = this;
- var uri = this.uri();
- var protocols = void(0);
- var opts = { agent: this.agent };
-
- this.socket = new WebSocket(uri, protocols, opts);
- this.addEventListeners();
+ util.defer(function(){
+ Polling.prototype.doOpen.call(self);
+ });
};
/**
- * Adds event listeners to the socket
+ * Creates a request.
*
+ * @param {String} method
* @api private
*/
-WS.prototype.addEventListeners = function(){
- var self = this;
-
- this.socket.onopen = function(){
- self.onOpen();
- };
- this.socket.onclose = function(){
- self.onClose();
- };
- this.socket.onmessage = function(ev){
- self.onData(ev.data);
- };
- this.socket.onerror = function(e){
- self.onError('websocket error', e);
- };
+XHR.prototype.request = function(opts){
+ opts = opts || {};
+ opts.uri = this.uri();
+ opts.xd = this.xd;
+ return new Request(opts);
};
/**
- * Override `onData` to use a timer on iOS.
- * See: https://gist.github.com/mloughran/2052006
+ * Sends data.
*
+ * @param {String} data to send.
+ * @param {Function} called upon flush.
* @api private
*/
-if ('undefined' != typeof navigator
- && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
- WS.prototype.onData = function(data){
- var self = this;
- setTimeout(function(){
- Transport.prototype.onData.call(self, data);
- }, 0);
- };
-}
+XHR.prototype.doWrite = function(data, fn){
+ var req = this.request({ method: 'POST', data: data });
+ var self = this;
+ req.on('success', fn);
+ req.on('error', function(err){
+ self.onError('xhr post error', err);
+ });
+ this.sendXhr = req;
+};
/**
- * Writes data to socket.
+ * Starts a poll cycle.
*
- * @param {Array} array of packets.
* @api private
*/
-WS.prototype.write = function(packets){
+XHR.prototype.doPoll = function(){
+ debug('xhr poll');
+ var req = this.request();
var self = this;
- this.writable = false;
- // encodePacket efficient as it uses WS framing
- // no need for encodePayload
- for (var i = 0, l = packets.length; i < l; i++) {
- this.socket.send(parser.encodePacket(packets[i]));
- }
- function ondrain() {
- self.writable = true;
- self.emit('drain');
- }
- // fake drain
- // defer to next tick to allow Socket to clear writeBuffer
- setTimeout(ondrain, 0);
+ req.on('data', function(data){
+ self.onData(data);
+ });
+ req.on('error', function(err){
+ self.onError('xhr poll error', err);
+ });
+ this.pollXhr = req;
};
/**
- * Called upon close
+ * Request constructor
*
- * @api private
+ * @param {Object} options
+ * @api public
*/
-WS.prototype.onClose = function(){
- Transport.prototype.onClose.call(this);
-};
+function Request(opts){
+ this.method = opts.method || 'GET';
+ this.uri = opts.uri;
+ this.xd = !!opts.xd;
+ this.async = false !== opts.async;
+ this.data = undefined != opts.data ? opts.data : null;
+ this.create();
+}
/**
- * Closes socket.
- *
- * @api private
+ * Mix in `Emitter`.
*/
-WS.prototype.doClose = function(){
- if (typeof this.socket !== 'undefined') {
- this.socket.close();
- }
-};
+Emitter(Request.prototype);
/**
- * Generates uri for connection.
+ * Creates the XHR object and sends the request.
*
* @api private
*/
-WS.prototype.uri = function(){
- var query = this.query || {};
- var schema = this.secure ? 'wss' : 'ws';
- var port = '';
+Request.prototype.create = function(){
+ var xhr = this.xhr = util.request(this.xd);
+ var self = this;
- // avoid port if default for schema
- if (this.port && (('wss' == schema && this.port != 443)
- || ('ws' == schema && this.port != 80))) {
- port = ':' + this.port;
- }
+ xhr.open(this.method, this.uri, this.async);
- // append timestamp to URI
- if (this.timestampRequests) {
- query[this.timestampParam] = +new Date;
+ if ('POST' == this.method) {
+ try {
+ if (xhr.setRequestHeader) {
+ // xmlhttprequest
+ xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
+ } else {
+ // xdomainrequest
+ xhr.contentType = 'text/plain';
+ }
+ } catch (e) {}
}
- query = util.qs(query);
+ if (this.xd && global.XDomainRequest && xhr instanceof XDomainRequest) {
+ xhr.onerror = function(e){
+ self.onError(e);
+ };
+ xhr.onload = function(){
+ self.onData(xhr.responseText);
+ };
+ xhr.onprogress = empty;
+ } else {
+ // ie6 check
+ if ('withCredentials' in xhr) {
+ xhr.withCredentials = true;
+ }
- // prepend ? to query
- if (query.length) {
- query = '?' + query;
+ xhr.onreadystatechange = function(){
+ var data;
+
+ try {
+ if (4 != xhr.readyState) return;
+ if (200 == xhr.status || 1223 == xhr.status) {
+ data = xhr.responseText;
+ } else {
+ self.onError(xhr.status);
+ }
+ } catch (e) {
+ self.onError(e);
+ }
+
+ if (undefined !== data) {
+ self.onData(data);
+ }
+ };
}
- return schema + '://' + this.hostname + port + this.path + query;
+ debug('sending xhr with url %s | data %s', this.uri, this.data);
+ xhr.send(this.data);
+
+ if (xobject) {
+ this.index = Request.requestsCount++;
+ Request.requests[this.index] = this;
+ }
};
/**
- * Feature detection for WebSocket.
+ * Called upon successful response.
*
- * @return {Boolean} whether this transport is available.
- * @api public
+ * @api private
*/
-WS.prototype.check = function(){
- return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
+Request.prototype.onSuccess = function(){
+ this.emit('success');
+ this.cleanup();
};
-},{"../transport":5,"../util":12,"debug":14,"engine.io-parser":16,"global":19,"ws":22}],12:[function(require,module,exports){
-
-var global = require('global');
-
/**
- * Status of page load.
+ * Called if we have data.
+ *
+ * @api private
*/
-var pageLoaded = false;
+Request.prototype.onData = function(data){
+ this.emit('data', data);
+ this.onSuccess();
+};
/**
- * Inheritance.
+ * Called upon error.
*
- * @param {Function} ctor a
- * @param {Function} ctor b
* @api private
*/
-exports.inherits = function inherits (a, b) {
- function c () { }
- c.prototype = b.prototype;
- a.prototype = new c;
+Request.prototype.onError = function(err){
+ this.emit('error', err);
+ this.cleanup();
};
/**
- * Object.keys
+ * Cleans up house.
+ *
+ * @api private
*/
-exports.keys = Object.keys || function (obj) {
- var ret = [];
- var has = Object.prototype.hasOwnProperty;
-
- for (var i in obj) {
- if (has.call(obj, i)) {
- ret.push(i);
- }
+Request.prototype.cleanup = function(){
+ if ('undefined' == typeof this.xhr ) {
+ return;
}
+ // xmlhttprequest
+ this.xhr.onreadystatechange = empty;
- return ret;
-};
+ // xdomainrequest
+ this.xhr.onload = this.xhr.onerror = empty;
-/**
- * Adds an event.
- *
- * @api private
- */
+ try {
+ this.xhr.abort();
+ } catch(e) {}
-exports.on = function (element, event, fn, capture) {
- if (element.attachEvent) {
- element.attachEvent('on' + event, fn);
- } else if (element.addEventListener) {
- element.addEventListener(event, fn, capture);
+ if (xobject) {
+ delete Request.requests[this.index];
}
+
+ this.xhr = null;
};
/**
- * Load utility.
+ * Aborts the request.
*
- * @api private
+ * @api public
*/
-exports.load = function (fn) {
- if (global.document && document.readyState === 'complete' || pageLoaded) {
- return fn();
- }
-
- exports.on(global, 'load', fn, false);
+Request.prototype.abort = function(){
+ this.cleanup();
};
-/**
- * Change the internal pageLoaded value.
- */
+if (xobject) {
+ Request.requestsCount = 0;
+ Request.requests = {};
-if ('undefined' != typeof window) {
- exports.load(function () {
- pageLoaded = true;
+ global.attachEvent('onunload', function(){
+ for (var i in Request.requests) {
+ if (Request.requests.hasOwnProperty(i)) {
+ Request.requests[i].abort();
+ }
+ }
});
}
+});
+require.register("engine.io/lib/transports/polling-jsonp.js", function(exports, require, module){
+
/**
- * JSON parse.
- *
- * @see Based on jQuery#parseJSON (MIT) and JSON2
- * @api private
+ * Module requirements.
*/
-var rvalidchars = /^[\],:{}\s]*$/;
-var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
-var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
-var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
-var rtrimLeft = /^\s+/;
-var rtrimRight = /\s+$/;
+var Polling = require('./polling')
+ , util = require('../util');
-exports.parseJSON = function (data) {
- if ('string' != typeof data || !data) {
- return null;
- }
+/**
+ * Module exports.
+ */
- data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
+module.exports = JSONPPolling;
- // Attempt to parse using the native JSON parser first
- if (global.JSON && JSON.parse) {
- return JSON.parse(data);
- }
+/**
+ * Global reference.
+ */
- if (rvalidchars.test(data.replace(rvalidescape, '@')
- .replace(rvalidtokens, ']')
- .replace(rvalidbraces, ''))) {
- return (new Function('return ' + data))();
- }
-};
+var global = util.global();
/**
- * UA / engines detection namespace.
- *
- * @namespace
+ * Cached regular expressions.
*/
-exports.ua = {};
+var rNewline = /\n/g;
/**
- * Detect webkit.
- *
- * @api private
+ * Global JSONP callbacks.
*/
-exports.ua.webkit = 'undefined' != typeof navigator &&
- /webkit/i.test(navigator.userAgent);
+var callbacks;
/**
- * Detect gecko.
- *
- * @api private
+ * Callbacks count.
*/
-exports.ua.gecko = 'undefined' != typeof navigator &&
- /gecko/i.test(navigator.userAgent);
+var index = 0;
/**
- * Detect android;
+ * Noop.
*/
-exports.ua.android = 'undefined' != typeof navigator &&
- /android/i.test(navigator.userAgent);
+function empty () { }
/**
- * Detect iOS.
+ * JSONP Polling constructor.
+ *
+ * @param {Object} opts.
+ * @api public
*/
-exports.ua.ios = 'undefined' != typeof navigator &&
- /^(iPad|iPhone|iPod)$/.test(navigator.platform);
-exports.ua.ios6 = exports.ua.ios && /OS 6_/.test(navigator.userAgent);
+function JSONPPolling (opts) {
+ Polling.call(this, opts);
+
+ // define global callbacks array if not present
+ // we do this here (lazily) to avoid unneeded global pollution
+ if (!callbacks) {
+ // we need to consider multiple engines in the same page
+ if (!global.___eio) global.___eio = [];
+ callbacks = global.___eio;
+ }
+
+ // callback identifier
+ this.index = callbacks.length;
+
+ // add callback to jsonp global
+ var self = this;
+ callbacks.push(function (msg) {
+ self.onData(msg);
+ });
+
+ // append to query string
+ this.query.j = this.index;
+};
/**
- * Detect Chrome Frame.
+ * Inherits from Polling.
*/
-exports.ua.chromeframe = Boolean(global.externalHost);
+util.inherits(JSONPPolling, Polling);
/**
- * Parses an URI
+ * Opens the socket.
*
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
-var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
-
-var parts = [
- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
- , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
-];
-
-exports.parseUri = function (str) {
- var m = re.exec(str || '')
- , uri = {}
- , i = 14;
-
- while (i--) {
- uri[parts[i]] = m[i] || '';
- }
-
- return uri;
+JSONPPolling.prototype.doOpen = function () {
+ var self = this;
+ util.defer(function () {
+ Polling.prototype.doOpen.call(self);
+ });
};
/**
- * Compiles a querystring
+ * Closes the socket
*
- * @param {Object}
* @api private
*/
-exports.qs = function (obj) {
- var str = '';
+JSONPPolling.prototype.doClose = function () {
+ if (this.script) {
+ this.script.parentNode.removeChild(this.script);
+ this.script = null;
+ }
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- if (str.length) str += '&';
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
- }
+ if (this.form) {
+ this.form.parentNode.removeChild(this.form);
+ this.form = null;
}
- return str;
+ Polling.prototype.doClose.call(this);
};
/**
- * Parses a simple querystring.
+ * Starts a poll cycle.
*
- * @param {String} qs
* @api private
*/
-exports.qsParse = function(qs){
- var qry = {};
- var pairs = qs.split('&');
- for (var i = 0, l = pairs.length; i < l; i++) {
- var pair = pairs[i].split('=');
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
+JSONPPolling.prototype.doPoll = function () {
+ var self = this;
+ var script = document.createElement('script');
+
+ if (this.script) {
+ this.script.parentNode.removeChild(this.script);
+ this.script = null;
}
- return qry;
-};
-},{"global":19}],13:[function(require,module,exports){
-// browser shim for xmlhttprequest module
-var hasCORS = require('has-cors');
+ script.async = true;
+ script.src = this.uri();
+ script.onerror = function(e){
+ self.onError('jsonp poll error',e);
+ }
-module.exports = function(opts) {
- var xdomain = opts.xdomain;
+ var insertAt = document.getElementsByTagName('script')[0];
+ insertAt.parentNode.insertBefore(script, insertAt);
+ this.script = script;
- // XMLHttpRequest can be disabled on IE
- try {
- if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
- return new XMLHttpRequest();
- }
- } catch (e) { }
- if (!xdomain) {
- try {
- return new ActiveXObject('Microsoft.XMLHTTP');
- } catch(e) { }
+ if (util.ua.gecko) {
+ setTimeout(function () {
+ var iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ document.body.removeChild(iframe);
+ }, 100);
}
-}
-
-},{"has-cors":20}],14:[function(require,module,exports){
-
-/**
- * Expose `debug()` as the module.
- */
-
-module.exports = debug;
+};
/**
- * Create a debugger with the given `name`.
+ * Writes with a hidden iframe.
*
- * @param {String} name
- * @return {Type}
- * @api public
+ * @param {String} data to send
+ * @param {Function} called upon flush.
+ * @api private
*/
-function debug(name) {
- if (!debug.enabled(name)) return function(){};
-
- return function(fmt){
- fmt = coerce(fmt);
+JSONPPolling.prototype.doWrite = function (data, fn) {
+ var self = this;
- var curr = new Date;
- var ms = curr - (debug[name] || curr);
- debug[name] = curr;
+ if (!this.form) {
+ var form = document.createElement('form');
+ var area = document.createElement('textarea');
+ var id = this.iframeId = 'eio_iframe_' + this.index;
+ var iframe;
- fmt = name
- + ' '
- + fmt
- + ' +' + debug.humanize(ms);
+ form.className = 'socketio';
+ form.style.position = 'absolute';
+ form.style.top = '-1000px';
+ form.style.left = '-1000px';
+ form.target = id;
+ form.method = 'POST';
+ form.setAttribute('accept-charset', 'utf-8');
+ area.name = 'd';
+ form.appendChild(area);
+ document.body.appendChild(form);
- // This hackery is required for IE8
- // where `console.log` doesn't have 'apply'
- window.console
- && console.log
- && Function.prototype.apply.call(console.log, console, arguments);
+ this.form = form;
+ this.area = area;
}
-}
-
-/**
- * The currently active debug mode names.
- */
-
-debug.names = [];
-debug.skips = [];
-
-/**
- * Enables a debug mode by name. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} name
- * @api public
- */
-debug.enable = function(name) {
- try {
- localStorage.debug = name;
- } catch(e){}
+ this.form.action = this.uri();
- var split = (name || '').split(/[\s,]+/)
- , len = split.length;
+ function complete () {
+ initIframe();
+ fn();
+ };
- for (var i = 0; i < len; i++) {
- name = split[i].replace('*', '.*?');
- if (name[0] === '-') {
- debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
- }
- else {
- debug.names.push(new RegExp('^' + name + '$'));
+ function initIframe () {
+ if (self.iframe) {
+ try {
+ self.form.removeChild(self.iframe);
+ } catch (e) {
+ self.onError('jsonp polling iframe removal error', e);
+ }
}
- }
-};
-/**
- * Disable debug output.
- *
- * @api public
- */
+ try {
+ // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
+ var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
+ iframe = document.createElement(html);
+ } catch (e) {
+ iframe = document.createElement('iframe');
+ iframe.name = self.iframeId;
+ iframe.src = 'javascript:0';
+ }
-debug.disable = function(){
- debug.enable('');
-};
+ iframe.id = self.iframeId;
-/**
- * Humanize the given `ms`.
- *
- * @param {Number} m
- * @return {String}
- * @api private
- */
+ self.form.appendChild(iframe);
+ self.iframe = iframe;
+ };
-debug.humanize = function(ms) {
- var sec = 1000
- , min = 60 * 1000
- , hour = 60 * min;
+ initIframe();
- if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
- if (ms >= min) return (ms / min).toFixed(1) + 'm';
- if (ms >= sec) return (ms / sec | 0) + 's';
- return ms + 'ms';
-};
+ // escape \n to prevent it from being converted into \r\n by some UAs
+ this.area.value = data.replace(rNewline, '\\n');
-/**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
+ try {
+ this.form.submit();
+ } catch(e) {}
-debug.enabled = function(name) {
- for (var i = 0, len = debug.skips.length; i < len; i++) {
- if (debug.skips[i].test(name)) {
- return false;
- }
- }
- for (var i = 0, len = debug.names.length; i < len; i++) {
- if (debug.names[i].test(name)) {
- return true;
- }
+ if (this.iframe.attachEvent) {
+ this.iframe.onreadystatechange = function(){
+ if (self.iframe.readyState == 'complete') {
+ complete();
+ }
+ };
+ } else {
+ this.iframe.onload = complete;
}
- return false;
};
+});
+require.register("engine.io/lib/transports/websocket.js", function(exports, require, module){
/**
- * Coerce `val`.
+ * Module dependencies.
*/
-function coerce(val) {
- if (val instanceof Error) return val.stack || val.message;
- return val;
-}
+var Transport = require('../transport')
+ , parser = require('engine.io-parser')
+ , util = require('../util')
+ , debug = require('debug')('engine.io-client:websocket');
-// persist
+/**
+ * Module exports.
+ */
-try {
- if (window.localStorage) debug.enable(localStorage.debug);
-} catch(e){}
+module.exports = WS;
+
+/**
+ * Global reference.
+ */
-},{}],15:[function(require,module,exports){
+var global = util.global();
/**
- * Module dependencies.
+ * WebSocket transport constructor.
+ *
+ * @api {Object} connection options
+ * @api public
*/
-var index = require('indexof');
+function WS(opts){
+ Transport.call(this, opts);
+};
/**
- * Expose `Emitter`.
+ * Inherits from Transport.
*/
-module.exports = Emitter;
+util.inherits(WS, Transport);
/**
- * Initialize a new `Emitter`.
+ * Transport name.
*
* @api public
*/
-function Emitter(obj) {
- if (obj) return mixin(obj);
-};
+WS.prototype.name = 'websocket';
/**
- * Mixin the emitter properties.
+ * Opens socket.
*
- * @param {Object} obj
- * @return {Object}
* @api private
*/
-function mixin(obj) {
- for (var key in Emitter.prototype) {
- obj[key] = Emitter.prototype[key];
+WS.prototype.doOpen = function(){
+ if (!this.check()) {
+ // let probe timeout
+ return;
}
- return obj;
-}
+
+ var self = this;
+
+ this.socket = new (ws())(this.uri());
+ this.socket.onopen = function(){
+ self.onOpen();
+ };
+ this.socket.onclose = function(){
+ self.onClose();
+ };
+ this.socket.onmessage = function(ev){
+ self.onData(ev.data);
+ };
+ this.socket.onerror = function(e){
+ self.onError('websocket error', e);
+ };
+};
/**
- * Listen on the given `event` with `fn`.
+ * Override `onData` to use a timer on iOS.
+ * See: https://gist.github.com/mloughran/2052006
*
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
+ * @api private
*/
-Emitter.prototype.on = function(event, fn){
- this._callbacks = this._callbacks || {};
- (this._callbacks[event] = this._callbacks[event] || [])
- .push(fn);
- return this;
-};
+if ('undefined' != typeof navigator
+ && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
+ WS.prototype.onData = function(data){
+ var self = this;
+ setTimeout(function(){
+ Transport.prototype.onData.call(self, data);
+ }, 0);
+ };
+}
/**
- * Adds an `event` listener that will be invoked a single
- * time then automatically removed.
+ * Writes data to socket.
*
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
+ * @param {Array} array of packets.
+ * @api private
*/
-Emitter.prototype.once = function(event, fn){
+WS.prototype.write = function(packets){
var self = this;
- this._callbacks = this._callbacks || {};
-
- function on() {
- self.off(event, on);
- fn.apply(this, arguments);
+ this.writable = false;
+ // encodePacket efficient as it uses WS framing
+ // no need for encodePayload
+ for (var i = 0, l = packets.length; i < l; i++) {
+ this.socket.send(parser.encodePacket(packets[i]));
+ }
+ function ondrain() {
+ self.writable = true;
+ self.emit('drain');
+ }
+ // check periodically if we're done sending
+ if ('bufferedAmount' in this.socket) {
+ this.bufferedAmountId = setInterval(function() {
+ if (self.socket.bufferedAmount == 0) {
+ clearInterval(self.bufferedAmountId);
+ ondrain();
+ }
+ }, 50);
+ } else {
+ // fake drain
+ // defer to next tick to allow Socket to clear writeBuffer
+ setTimeout(ondrain, 0);
}
-
- fn._off = on;
- this.on(event, on);
- return this;
};
/**
- * Remove the given callback for `event` or all
- * registered callbacks.
+ * Called upon close
*
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
+ * @api private
*/
-Emitter.prototype.off =
-Emitter.prototype.removeListener =
-Emitter.prototype.removeAllListeners = function(event, fn){
- this._callbacks = this._callbacks || {};
-
- // all
- if (0 == arguments.length) {
- this._callbacks = {};
- return this;
- }
+WS.prototype.onClose = function(){
+ // stop checking to see if websocket is done sending buffer
+ clearInterval(this.bufferedAmountId);
+ Transport.prototype.onClose.call(this);
+};
- // specific event
- var callbacks = this._callbacks[event];
- if (!callbacks) return this;
+/**
+ * Closes socket.
+ *
+ * @api private
+ */
- // remove all handlers
- if (1 == arguments.length) {
- delete this._callbacks[event];
- return this;
+WS.prototype.doClose = function(){
+ if (typeof this.socket !== 'undefined') {
+ this.socket.close();
}
-
- // remove specific handler
- var i = index(callbacks, fn._off || fn);
- if (~i) callbacks.splice(i, 1);
- return this;
};
/**
- * Emit `event` with the given args.
+ * Generates uri for connection.
*
- * @param {String} event
- * @param {Mixed} ...
- * @return {Emitter}
+ * @api private
*/
-Emitter.prototype.emit = function(event){
- this._callbacks = this._callbacks || {};
- var args = [].slice.call(arguments, 1)
- , callbacks = this._callbacks[event];
+WS.prototype.uri = function(){
+ var query = this.query || {};
+ var schema = this.secure ? 'wss' : 'ws';
+ var port = '';
- if (callbacks) {
- callbacks = callbacks.slice(0);
- for (var i = 0, len = callbacks.length; i < len; ++i) {
- callbacks[i].apply(this, args);
- }
+ // avoid port if default for schema
+ if (this.port && (('wss' == schema && this.port != 443)
+ || ('ws' == schema && this.port != 80))) {
+ port = ':' + this.port;
}
- return this;
+ // append timestamp to URI
+ if (this.timestampRequests) {
+ query[this.timestampParam] = +new Date;
+ }
+
+ query = util.qs(query);
+
+ // prepend ? to query
+ if (query.length) {
+ query = '?' + query;
+ }
+
+ return schema + '://' + this.hostname + port + this.path + query;
};
/**
- * Return array of callbacks for `event`.
+ * Feature detection for WebSocket.
*
- * @param {String} event
- * @return {Array}
+ * @return {Boolean} whether this transport is available.
* @api public
*/
-Emitter.prototype.listeners = function(event){
- this._callbacks = this._callbacks || {};
- return this._callbacks[event] || [];
+WS.prototype.check = function(){
+ var websocket = ws();
+ return !!websocket && !('__initialize' in websocket && this.name === WS.prototype.name);
};
/**
- * Check if this emitter has `event` handlers.
+ * Getter for WS constructor.
*
- * @param {String} event
- * @return {Boolean}
- * @api public
+ * @api private
*/
-Emitter.prototype.hasListeners = function(event){
- return !! this.listeners(event).length;
-};
-
-},{"indexof":21}],16:[function(require,module,exports){
+function ws(){
+ if ('undefined' == typeof window) {
+ return require('ws');
+ }
-module.exports = require('./lib/');
+ return global.WebSocket || global.MozWebSocket;
+}
-},{"./lib/":17}],17:[function(require,module,exports){
+});
+require.register("engine.io/lib/transports/flashsocket.js", function(exports, require, module){
/**
* Module dependencies.
*/
-var keys = require('./keys');
-
-/**
- * Current protocol version.
- */
-exports.protocol = 2;
+var WS = require('./websocket')
+ , util = require('../util')
+ , debug = require('debug')('engine.io-client:flashsocket');
/**
- * Packet types.
+ * Module exports.
*/
-var packets = exports.packets = {
- open: 0 // non-ws
- , close: 1 // non-ws
- , ping: 2
- , pong: 3
- , message: 4
- , upgrade: 5
- , noop: 6
-};
-
-var packetslist = keys(packets);
+module.exports = FlashWS;
/**
- * Premade error packet.
+ * Global reference.
*/
-var err = { type: 'error', data: 'parser error' };
+var global = util.global()
/**
- * Encodes a packet.
- *
- * <packet type id> [ `:` <data> ]
- *
- * Example:
- *
- * 5:hello world
- * 3
- * 4
- *
- * @api private
+ * Obfuscated key for Blue Coat.
*/
-exports.encodePacket = function (packet) {
- var encoded = packets[packet.type];
-
- // data fragment is optional
- if (undefined !== packet.data) {
- encoded += String(packet.data);
- }
-
- return '' + encoded;
-};
+var xobject = global[['Active'].concat('Object').join('X')];
/**
- * Decodes a packet.
+ * FlashWS constructor.
*
- * @return {Object} with `type` and `data` (if any)
- * @api private
+ * @api public
*/
-exports.decodePacket = function (data) {
- var type = data.charAt(0);
-
- if (Number(type) != type || !packetslist[type]) {
- return err;
- }
-
- if (data.length > 1) {
- return { type: packetslist[type], data: data.substring(1) };
- } else {
- return { type: packetslist[type] };
- }
+function FlashWS (options) {
+ WS.call(this, options);
+ this.flashPath = options.flashPath;
+ this.policyPort = options.policyPort;
};
/**
- * Encodes multiple messages (payload).
- *
- * <length>:data
- *
- * Example:
- *
- * 11:hello world2:hi
- *
- * @param {Array} packets
- * @api private
+ * Inherits from WebSocket.
*/
-exports.encodePayload = function (packets) {
- if (!packets.length) {
- return '0:';
- }
-
- var encoded = '';
- var message;
+util.inherits(FlashWS, WS);
- for (var i = 0, l = packets.length; i < l; i++) {
- message = exports.encodePacket(packets[i]);
- encoded += message.length + ':' + message;
- }
+/**
+ * Transport name.
+ *
+ * @api public
+ */
- return encoded;
-};
+FlashWS.prototype.name = 'flashsocket';
-/*
- * Decodes data when a payload is maybe expected.
+/**
+ * Opens the transport.
*
- * @param {String} data, callback method
* @api public
*/
-exports.decodePayload = function (data, callback) {
- var packet;
- if (data == '') {
- // parser error - ignoring payload
- return callback(err, 0, 1);
+FlashWS.prototype.doOpen = function () {
+ if (!this.check()) {
+ // let the probe timeout
+ return;
}
- var length = ''
- , n, msg;
+ // instrument websocketjs logging
+ function log (type) {
+ return function(){
+ var str = Array.prototype.join.call(arguments, ' ');
+ debug('[websocketjs %s] %s', type, str);
+ };
+ };
- for (var i = 0, l = data.length; i < l; i++) {
- var chr = data.charAt(i);
+ WEB_SOCKET_LOGGER = { log: log('debug'), error: log('error') };
+ WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;
+ WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true;
- if (':' != chr) {
- length += chr;
- } else {
- if ('' == length || (length != (n = Number(length)))) {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
+ if ('undefined' == typeof WEB_SOCKET_SWF_LOCATION) {
+ WEB_SOCKET_SWF_LOCATION = this.flashPath + 'WebSocketMainInsecure.swf';
+ }
- msg = data.substr(i + 1, n);
+ // dependencies
+ var deps = [this.flashPath + 'web_socket.js'];
- if (length != msg.length) {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
+ if ('undefined' == typeof swfobject) {
+ deps.unshift(this.flashPath + 'swfobject.js');
+ }
- if (msg.length) {
- packet = exports.decodePacket(msg);
+ var self = this;
- if (err.type == packet.type && err.data == packet.data) {
- // parser error in individual packet - ignoring payload
- return callback(err, 0, 1);
- }
+ load(deps, function () {
+ self.ready(function () {
+ WebSocket.__addTask(function () {
+ WS.prototype.doOpen.call(self);
+ });
+ });
+ });
+};
- var ret = callback(packet, i + n, l);
- if (false === ret) return;
- }
+/**
+ * Override to prevent closing uninitialized flashsocket.
+ *
+ * @api private
+ */
- // advance cursor
- i += n;
- length = '';
- }
- }
+FlashWS.prototype.doClose = function () {
+ if (!this.socket) return;
+ var self = this;
+ WebSocket.__addTask(function() {
+ WS.prototype.doClose.call(self);
+ });
+};
- if (length != '') {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
+/**
+ * Writes to the Flash socket.
+ *
+ * @api private
+ */
+FlashWS.prototype.write = function() {
+ var self = this, args = arguments;
+ WebSocket.__addTask(function () {
+ WS.prototype.write.apply(self, args);
+ });
};
-},{"./keys":18}],18:[function(require,module,exports){
-
/**
- * Gets the keys for an object.
+ * Called upon dependencies are loaded.
*
- * @return {Array} keys
* @api private
*/
-module.exports = Object.keys || function keys (obj){
- var arr = [];
- var has = Object.prototype.hasOwnProperty;
-
- for (var i in obj) {
- if (has.call(obj, i)) {
- arr.push(i);
- }
+FlashWS.prototype.ready = function (fn) {
+ if (typeof WebSocket == 'undefined' ||
+ !('__initialize' in WebSocket) || !swfobject) {
+ return;
}
- return arr;
-};
-},{}],19:[function(require,module,exports){
+ if (swfobject.getFlashPlayerVersion().major < 10) {
+ return;
+ }
-/**
- * Returns `this`. Execute this without a "context" (i.e. without it being
- * attached to an object of the left-hand side), and `this` points to the
- * "global" scope of the current JS execution.
- */
+ function init () {
+ // Only start downloading the swf file when the checked that this browser
+ // actually supports it
+ if (!FlashWS.loaded) {
+ if (843 != self.policyPort) {
+ WebSocket.loadFlashPolicyFile('xmlsocket://' + self.host + ':' + self.policyPort);
+ }
-module.exports = (function () { return this; })();
+ WebSocket.__initialize();
+ FlashWS.loaded = true;
+ }
-},{}],20:[function(require,module,exports){
+ fn.call(self);
+ }
-/**
- * Module dependencies.
- */
+ var self = this;
+ if (document.body) {
+ return init();
+ }
-var global = require('global');
+ util.load(init);
+};
/**
- * Module exports.
- *
- * Logic borrowed from Modernizr:
+ * Feature detection for flashsocket.
*
- * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
+ * @return {Boolean} whether this transport is available.
+ * @api public
*/
-try {
- module.exports = 'XMLHttpRequest' in global &&
- 'withCredentials' in new global.XMLHttpRequest();
-} catch (err) {
- // if XMLHttp support is disabled in IE then it will throw
- // when trying to create
- module.exports = false;
-}
-
-},{"global":19}],21:[function(require,module,exports){
+FlashWS.prototype.check = function () {
+ if ('undefined' == typeof window) {
+ return false;
+ }
-var indexOf = [].indexOf;
+ if (typeof WebSocket != 'undefined' && !('__initialize' in WebSocket)) {
+ return false;
+ }
-module.exports = function(arr, obj){
- if (indexOf) return arr.indexOf(obj);
- for (var i = 0; i < arr.length; ++i) {
- if (arr[i] === obj) return i;
+ if (xobject) {
+ var control = null;
+ try {
+ control = new xobject('ShockwaveFlash.ShockwaveFlash');
+ } catch (e) { }
+ if (control) {
+ return true;
+ }
+ } else {
+ for (var i = 0, l = navigator.plugins.length; i < l; i++) {
+ for (var j = 0, m = navigator.plugins[i].length; j < m; j++) {
+ if (navigator.plugins[i][j].description == 'Shockwave Flash') {
+ return true;
+ }
+ }
+ }
}
- return -1;
+
+ return false;
};
-},{}],22:[function(require,module,exports){
/**
- * Module dependencies.
+ * Lazy loading of scripts.
+ * Based on $script by Dustin Diaz - MIT
*/
-var global = (function() { return this; })();
+var scripts = {};
/**
- * WebSocket constructor.
+ * Injects a script. Keeps tracked of injected ones.
+ *
+ * @param {String} path
+ * @param {Function} callback
+ * @api private
*/
-var WebSocket = global.WebSocket || global.MozWebSocket;
+function create (path, fn) {
+ if (scripts[path]) return fn();
-/**
- * Module exports.
- */
+ var el = document.createElement('script');
+ var loaded = false;
+
+ debug('loading "%s"', path);
+ el.onload = el.onreadystatechange = function () {
+ if (loaded || scripts[path]) return;
+ var rs = el.readyState;
+ if (!rs || 'loaded' == rs || 'complete' == rs) {
+ debug('loaded "%s"', path);
+ el.onload = el.onreadystatechange = null;
+ loaded = true;
+ scripts[path] = true;
+ fn();
+ }
+ };
+
+ el.async = 1;
+ el.src = path;
-module.exports = WebSocket ? ws : null;
+ var head = document.getElementsByTagName('head')[0];
+ head.insertBefore(el, head.firstChild);
+};
/**
- * WebSocket constructor.
- *
- * The third `opts` options object gets ignored in web browsers, since it's
- * non-standard, and throws a TypeError if passed to the constructor.
- * See: https://github.com/einaros/ws/issues/227
+ * Loads scripts and fires a callback.
*
- * @param {String} uri
- * @param {Array} protocols (optional)
- * @param {Object) opts (optional)
- * @api public
+ * @param {Array} paths
+ * @param {Function} callback
*/
-function ws(uri, protocols, opts) {
- var instance;
- if (protocols) {
- instance = new WebSocket(uri, protocols);
- } else {
- instance = new WebSocket(uri);
- }
- return instance;
-}
+function load (arr, fn) {
+ function process (i) {
+ if (!arr[i]) return fn();
+ create(arr[i], function () {
+ process(++i);
+ });
+ };
-if (WebSocket) ws.prototype = WebSocket.prototype;
+ process(0);
+};
-},{}]},{},[1])
-(1)
});
-;
+require.alias("component-emitter/index.js", "engine.io/deps/emitter/index.js");
+require.alias("component-emitter/index.js", "emitter/index.js");
+
+require.alias("component-indexof/index.js", "engine.io/deps/indexof/index.js");
+require.alias("component-indexof/index.js", "indexof/index.js");
+
+require.alias("LearnBoost-engine.io-protocol/lib/index.js", "engine.io/deps/engine.io-parser/lib/index.js");
+require.alias("LearnBoost-engine.io-protocol/lib/keys.js", "engine.io/deps/engine.io-parser/lib/keys.js");
+require.alias("LearnBoost-engine.io-protocol/lib/index.js", "engine.io/deps/engine.io-parser/index.js");
+require.alias("LearnBoost-engine.io-protocol/lib/index.js", "engine.io-parser/index.js");
+require.alias("LearnBoost-engine.io-protocol/lib/index.js", "LearnBoost-engine.io-protocol/index.js");
+
+require.alias("visionmedia-debug/index.js", "engine.io/deps/debug/index.js");
+require.alias("visionmedia-debug/debug.js", "engine.io/deps/debug/debug.js");
+require.alias("visionmedia-debug/index.js", "debug/index.js");
+
+require.alias("engine.io/lib/index.js", "engine.io/index.js");
+
+if (typeof exports == "object") {
+ module.exports = require("engine.io");
+} else if (typeof define == "function" && define.amd) {
+ define(function(){ return require("engine.io"); });
+} else {
+ this["eio"] = require("engine.io");
+}})();
\ No newline at end of file