vendor/assets/javascripts/faye-browser.js in faye-rails-1.0.10 vs vendor/assets/javascripts/faye-browser.js in faye-rails-2.0.0
- old
+ new
@@ -1,19 +1,20 @@
(function() {
+(function() {
'use strict';
var Faye = {
- VERSION: '0.8.9',
+ VERSION: '1.0.1',
BAYEUX_VERSION: '1.0',
ID_LENGTH: 160,
JSONP_CALLBACK: 'jsonpcallback',
CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'],
MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'],
- ENV: (typeof global === 'undefined') ? window : global,
+ ENV: (typeof window !== 'undefined') ? window : global,
extend: function(dest, source, overwrite) {
if (!source) return dest;
for (var key in source) {
if (!source.hasOwnProperty(key)) continue;
@@ -24,29 +25,18 @@
return dest;
},
random: function(bitlength) {
bitlength = bitlength || this.ID_LENGTH;
- if (bitlength > 32) {
- var parts = Math.ceil(bitlength / 32),
- string = '';
- while (parts--) string += this.random(32);
- var chars = string.split(''), result = '';
- while (chars.length > 0) result += chars.pop();
- return result;
- }
- var limit = Math.pow(2, bitlength) - 1,
- maxSize = limit.toString(36).length,
- string = Math.floor(Math.random() * limit).toString(36);
-
- while (string.length < maxSize) string = '0' + string;
- return string;
+ return csprng(bitlength, 36);
},
clientIdFromMessages: function(messages) {
- var first = [].concat(messages)[0];
- return first && first.clientId;
+ var connect = this.filter([].concat(messages), function(message) {
+ return message.channel === '/meta/connect';
+ });
+ return connect[0] && connect[0].clientId;
},
copyObject: function(object) {
var clone, i, key;
if (object instanceof Array) {
@@ -96,10 +86,11 @@
}
return result;
},
filter: function(array, callback, context) {
+ if (array.filter) return array.filter(callback, context);
var result = [];
for (var i = 0, n = array.length; i < n; i++) {
if (callback.call(context || null, array[i], i))
result.push(array[i]);
}
@@ -133,46 +124,23 @@
resume();
},
// http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/
toJSON: function(object) {
- if (this.stringify)
- return this.stringify(object, function(key, value) {
- return (this[key] instanceof Array)
- ? this[key]
- : value;
- });
+ if (!this.stringify) return JSON.stringify(object);
- return JSON.stringify(object);
- },
-
- logger: function(message) {
- if (typeof console !== 'undefined') console.log(message);
- },
-
- timestamp: function() {
- var date = new Date(),
- year = date.getFullYear(),
- month = date.getMonth() + 1,
- day = date.getDate(),
- hour = date.getHours(),
- minute = date.getMinutes(),
- second = date.getSeconds();
-
- var pad = function(n) {
- return n < 10 ? '0' + n : String(n);
- };
-
- return pad(year) + '-' + pad(month) + '-' + pad(day) + ' ' +
- pad(hour) + ':' + pad(minute) + ':' + pad(second);
+ return this.stringify(object, function(key, value) {
+ return (this[key] instanceof Array) ? this[key] : value;
+ });
}
};
-if (typeof window !== 'undefined')
+if (typeof module !== 'undefined')
+ module.exports = Faye;
+else if (typeof window !== 'undefined')
window.Faye = Faye;
-
Faye.Class = function(parent, methods) {
if (typeof parent !== 'function') {
methods = parent;
parent = Object;
}
@@ -189,11 +157,185 @@
Faye.extend(klass.prototype, methods);
return klass;
};
+(function() {
+var EventEmitter = Faye.EventEmitter = function() {};
+/*
+Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+var isArray = typeof Array.isArray === 'function'
+ ? Array.isArray
+ : function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]'
+ }
+;
+function indexOf (xs, x) {
+ if (xs.indexOf) return xs.indexOf(x);
+ for (var i = 0; i < xs.length; i++) {
+ if (x === xs[i]) return i;
+ }
+ return -1;
+}
+
+
+EventEmitter.prototype.emit = function(type) {
+ // If there is no 'error' event listener then throw.
+ if (type === 'error') {
+ if (!this._events || !this._events.error ||
+ (isArray(this._events.error) && !this._events.error.length))
+ {
+ if (arguments[1] instanceof Error) {
+ throw arguments[1]; // Unhandled 'error' event
+ } else {
+ throw new Error("Uncaught, unspecified 'error' event.");
+ }
+ return false;
+ }
+ }
+
+ if (!this._events) return false;
+ var handler = this._events[type];
+ if (!handler) return false;
+
+ if (typeof handler == 'function') {
+ switch (arguments.length) {
+ // fast cases
+ case 1:
+ handler.call(this);
+ break;
+ case 2:
+ handler.call(this, arguments[1]);
+ break;
+ case 3:
+ handler.call(this, arguments[1], arguments[2]);
+ break;
+ // slower
+ default:
+ var args = Array.prototype.slice.call(arguments, 1);
+ handler.apply(this, args);
+ }
+ return true;
+
+ } else if (isArray(handler)) {
+ var args = Array.prototype.slice.call(arguments, 1);
+
+ var listeners = handler.slice();
+ for (var i = 0, l = listeners.length; i < l; i++) {
+ listeners[i].apply(this, args);
+ }
+ return true;
+
+ } else {
+ return false;
+ }
+};
+
+// EventEmitter is defined in src/node_events.cc
+// EventEmitter.prototype.emit() is also defined there.
+EventEmitter.prototype.addListener = function(type, listener) {
+ if ('function' !== typeof listener) {
+ throw new Error('addListener only takes instances of Function');
+ }
+
+ if (!this._events) this._events = {};
+
+ // To avoid recursion in the case that type == "newListeners"! Before
+ // adding it to the listeners, first emit "newListeners".
+ this.emit('newListener', type, listener);
+
+ if (!this._events[type]) {
+ // Optimize the case of one listener. Don't need the extra array object.
+ this._events[type] = listener;
+ } else if (isArray(this._events[type])) {
+ // If we've already got an array, just append.
+ this._events[type].push(listener);
+ } else {
+ // Adding the second element, need to change to array.
+ this._events[type] = [this._events[type], listener];
+ }
+
+ return this;
+};
+
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;
+
+EventEmitter.prototype.once = function(type, listener) {
+ var self = this;
+ self.on(type, function g() {
+ self.removeListener(type, g);
+ listener.apply(this, arguments);
+ });
+
+ return this;
+};
+
+EventEmitter.prototype.removeListener = function(type, listener) {
+ if ('function' !== typeof listener) {
+ throw new Error('removeListener only takes instances of Function');
+ }
+
+ // does not use listeners(), so no side effect of creating _events[type]
+ if (!this._events || !this._events[type]) return this;
+
+ var list = this._events[type];
+
+ if (isArray(list)) {
+ var i = indexOf(list, listener);
+ if (i < 0) return this;
+ list.splice(i, 1);
+ if (list.length == 0)
+ delete this._events[type];
+ } else if (this._events[type] === listener) {
+ delete this._events[type];
+ }
+
+ return this;
+};
+
+EventEmitter.prototype.removeAllListeners = function(type) {
+ if (arguments.length === 0) {
+ this._events = {};
+ return this;
+ }
+
+ // does not use listeners(), so no side effect of creating _events[type]
+ if (type && this._events && this._events[type]) this._events[type] = null;
+ return this;
+};
+
+EventEmitter.prototype.listeners = function(type) {
+ if (!this._events) this._events = {};
+ if (!this._events[type]) this._events[type] = [];
+ if (!isArray(this._events[type])) {
+ this._events[type] = [this._events[type]];
+ }
+ return this._events[type];
+};
+
+})();
+
Faye.Namespace = Faye.Class({
initialize: function() {
this._used = {};
},
@@ -211,11 +353,288 @@
release: function(id) {
delete this._used[id];
}
});
+(function() {
+'use strict';
+var timeout = setTimeout;
+
+var defer;
+if (typeof setImmediate === 'function')
+ defer = function(fn) { setImmediate(fn) };
+else if (typeof process === 'object' && process.nextTick)
+ defer = function(fn) { process.nextTick(fn) };
+else
+ defer = function(fn) { timeout(fn, 0) };
+
+var PENDING = 0,
+ FULFILLED = 1,
+ REJECTED = 2;
+
+var RETURN = function(x) { return x },
+ THROW = function(x) { throw x };
+
+var Promise = function(task) {
+ this._state = PENDING;
+ this._callbacks = [];
+ this._errbacks = [];
+
+ if (typeof task !== 'function') return;
+ var self = this;
+
+ task(function(value) { fulfill(self, value) },
+ function(reason) { reject(self, reason) });
+};
+
+Promise.prototype.then = function(callback, errback) {
+ var next = {}, self = this;
+
+ next.promise = new Promise(function(fulfill, reject) {
+ next.fulfill = fulfill;
+ next.reject = reject;
+
+ registerCallback(self, callback, next);
+ registerErrback(self, errback, next);
+ });
+ return next.promise;
+};
+
+var registerCallback = function(promise, callback, next) {
+ if (typeof callback !== 'function') callback = RETURN;
+ var handler = function(value) { invoke(callback, value, next) };
+ if (promise._state === PENDING) {
+ promise._callbacks.push(handler);
+ } else if (promise._state === FULFILLED) {
+ handler(promise._value);
+ }
+};
+
+var registerErrback = function(promise, errback, next) {
+ if (typeof errback !== 'function') errback = THROW;
+ var handler = function(reason) { invoke(errback, reason, next) };
+ if (promise._state === PENDING) {
+ promise._errbacks.push(handler);
+ } else if (promise._state === REJECTED) {
+ handler(promise._reason);
+ }
+};
+
+var invoke = function(fn, value, next) {
+ defer(function() { _invoke(fn, value, next) });
+};
+
+var _invoke = function(fn, value, next) {
+ var called = false, outcome, type, then;
+
+ try {
+ outcome = fn(value);
+ type = typeof outcome;
+ then = outcome !== null && (type === 'function' || type === 'object') && outcome.then;
+
+ if (outcome === next.promise)
+ return next.reject(new TypeError('Recursive promise chain detected'));
+
+ if (typeof then !== 'function') return next.fulfill(outcome);
+
+ then.call(outcome, function(v) {
+ if (called) return;
+ called = true;
+ _invoke(RETURN, v, next);
+ }, function(r) {
+ if (called) return;
+ called = true;
+ next.reject(r);
+ });
+
+ } catch (error) {
+ if (called) return;
+ called = true;
+ next.reject(error);
+ }
+};
+
+var fulfill = Promise.fulfill = Promise.resolve = function(promise, value) {
+ if (promise._state !== PENDING) return;
+
+ promise._state = FULFILLED;
+ promise._value = value;
+ promise._errbacks = [];
+
+ var callbacks = promise._callbacks, cb;
+ while (cb = callbacks.shift()) cb(value);
+};
+
+var reject = Promise.reject = function(promise, reason) {
+ if (promise._state !== PENDING) return;
+
+ promise._state = REJECTED;
+ promise._reason = reason;
+ promise._callbacks = [];
+
+ var errbacks = promise._errbacks, eb;
+ while (eb = errbacks.shift()) eb(reason);
+};
+
+Promise.defer = defer;
+
+Promise.deferred = Promise.pending = function() {
+ var tuple = {};
+
+ tuple.promise = new Promise(function(fulfill, reject) {
+ tuple.fulfill = tuple.resolve = fulfill;
+ tuple.reject = reject;
+ });
+ return tuple;
+};
+
+Promise.fulfilled = Promise.resolved = function(value) {
+ return new Promise(function(fulfill, reject) { fulfill(value) });
+};
+
+Promise.rejected = function(reason) {
+ return new Promise(function(fulfill, reject) { reject(reason) });
+};
+
+if (typeof Faye === 'undefined')
+ module.exports = Promise;
+else
+ Faye.Promise = Promise;
+
+})();
+
+Faye.Set = Faye.Class({
+ initialize: function() {
+ this._index = {};
+ },
+
+ add: function(item) {
+ var key = (item.id !== undefined) ? item.id : item;
+ if (this._index.hasOwnProperty(key)) return false;
+ this._index[key] = item;
+ return true;
+ },
+
+ forEach: function(block, context) {
+ for (var key in this._index) {
+ if (this._index.hasOwnProperty(key))
+ block.call(context, this._index[key]);
+ }
+ },
+
+ isEmpty: function() {
+ for (var key in this._index) {
+ if (this._index.hasOwnProperty(key)) return false;
+ }
+ return true;
+ },
+
+ member: function(item) {
+ for (var key in this._index) {
+ if (this._index[key] === item) return true;
+ }
+ return false;
+ },
+
+ remove: function(item) {
+ var key = (item.id !== undefined) ? item.id : item;
+ var removed = this._index[key];
+ delete this._index[key];
+ return removed;
+ },
+
+ toArray: function() {
+ var array = [];
+ this.forEach(function(item) { array.push(item) });
+ return array;
+ }
+});
+
+Faye.URI = {
+ isURI: function(uri) {
+ return uri && uri.protocol && uri.host && uri.path;
+ },
+
+ isSameOrigin: function(uri) {
+ var location = Faye.ENV.location;
+ return uri.protocol === location.protocol &&
+ uri.hostname === location.hostname &&
+ uri.port === location.port;
+ },
+
+ parse: function(url) {
+ if (typeof url !== 'string') return url;
+ var uri = {}, parts, query, pairs, i, n, data;
+
+ var consume = function(name, pattern) {
+ url = url.replace(pattern, function(match) {
+ uri[name] = match;
+ return '';
+ });
+ uri[name] = uri[name] || '';
+ };
+
+ consume('protocol', /^[a-z]+\:/i);
+ consume('host', /^\/\/[^\/\?#]+/);
+
+ if (!/^\//.test(url) && !uri.host)
+ url = Faye.ENV.location.pathname.replace(/[^\/]*$/, '') + url;
+
+ consume('pathname', /^[^\?#]*/);
+ consume('search', /^\?[^#]*/);
+ consume('hash', /^#.*/);
+
+ uri.protocol = uri.protocol || Faye.ENV.location.protocol;
+
+ if (uri.host) {
+ uri.host = uri.host.substr(2);
+ parts = uri.host.split(':');
+ uri.hostname = parts[0];
+ uri.port = parts[1] || '';
+ } else {
+ uri.host = Faye.ENV.location.host;
+ uri.hostname = Faye.ENV.location.hostname;
+ uri.port = Faye.ENV.location.port;
+ }
+
+ uri.pathname = uri.pathname || '/';
+ uri.path = uri.pathname + uri.search;
+
+ query = uri.search.replace(/^\?/, '');
+ pairs = query ? query.split('&') : [];
+ data = {};
+
+ for (i = 0, n = pairs.length; i < n; i++) {
+ parts = pairs[i].split('=');
+ data[decodeURIComponent(parts[0] || '')] = decodeURIComponent(parts[1] || '');
+ }
+
+ uri.query = data;
+
+ uri.href = this.stringify(uri);
+ return uri;
+ },
+
+ stringify: function(uri) {
+ var string = uri.protocol + '//' + uri.hostname;
+ if (uri.port) string += ':' + uri.port;
+ string += uri.pathname + this.queryString(uri.query) + (uri.hash || '');
+ return string;
+ },
+
+ queryString: function(query) {
+ var pairs = [];
+ for (var key in query) {
+ if (!query.hasOwnProperty(key)) continue;
+ pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key]));
+ }
+ if (pairs.length === 0) return '';
+ return '?' + pairs.join('&');
+ }
+};
+
Faye.Error = Faye.Class({
initialize: function(code, params, message) {
this.code = code;
this.params = Array.prototype.slice.call(params);
this.message = message;
@@ -238,147 +657,137 @@
message = parts[2];
return new this(code, params, message);
};
+
+
+
Faye.Error.versionMismatch = function() {
- return new this(300, arguments, "Version mismatch").toString();
+ return new this(300, arguments, 'Version mismatch').toString();
};
+
Faye.Error.conntypeMismatch = function() {
- return new this(301, arguments, "Connection types not supported").toString();
+ return new this(301, arguments, 'Connection types not supported').toString();
};
+
Faye.Error.extMismatch = function() {
- return new this(302, arguments, "Extension mismatch").toString();
+ return new this(302, arguments, 'Extension mismatch').toString();
};
+
Faye.Error.badRequest = function() {
- return new this(400, arguments, "Bad request").toString();
+ return new this(400, arguments, 'Bad request').toString();
};
+
Faye.Error.clientUnknown = function() {
- return new this(401, arguments, "Unknown client").toString();
+ return new this(401, arguments, 'Unknown client').toString();
};
+
Faye.Error.parameterMissing = function() {
- return new this(402, arguments, "Missing required parameter").toString();
+ return new this(402, arguments, 'Missing required parameter').toString();
};
+
Faye.Error.channelForbidden = function() {
- return new this(403, arguments, "Forbidden channel").toString();
+ return new this(403, arguments, 'Forbidden channel').toString();
};
+
Faye.Error.channelUnknown = function() {
- return new this(404, arguments, "Unknown channel").toString();
+ return new this(404, arguments, 'Unknown channel').toString();
};
+
Faye.Error.channelInvalid = function() {
- return new this(405, arguments, "Invalid channel").toString();
+ return new this(405, arguments, 'Invalid channel').toString();
};
+
Faye.Error.extUnknown = function() {
- return new this(406, arguments, "Unknown extension").toString();
+ return new this(406, arguments, 'Unknown extension').toString();
};
+
Faye.Error.publishFailed = function() {
- return new this(407, arguments, "Failed to publish").toString();
+ return new this(407, arguments, 'Failed to publish').toString();
};
+
Faye.Error.serverError = function() {
- return new this(500, arguments, "Internal server error").toString();
+ return new this(500, arguments, 'Internal server error').toString();
};
Faye.Deferrable = {
- callback: function(callback, context) {
- if (!callback) return;
+ then: function(callback, errback) {
+ var self = this;
+ if (!this._promise)
+ this._promise = new Faye.Promise(function(fulfill, reject) {
+ self._fulfill = fulfill;
+ self._reject = reject;
+ });
- if (this._deferredStatus === 'succeeded')
- return callback.apply(context, this._deferredArgs);
-
- this._callbacks = this._callbacks || [];
- this._callbacks.push([callback, context]);
+ if (arguments.length === 0)
+ return this._promise;
+ else
+ return this._promise.then(callback, errback);
},
- timeout: function(seconds, message) {
- var _this = this;
- var timer = Faye.ENV.setTimeout(function() {
- _this.setDeferredStatus('failed', message);
- }, seconds * 1000);
- this._timer = timer;
+ callback: function(callback, context) {
+ return this.then(function(value) { callback.call(context, value) });
},
errback: function(callback, context) {
- if (!callback) return;
+ return this.then(null, function(reason) { callback.call(context, reason) });
+ },
- if (this._deferredStatus === 'failed')
- return callback.apply(context, this._deferredArgs);
-
- this._errbacks = this._errbacks || [];
- this._errbacks.push([callback, context]);
+ timeout: function(seconds, message) {
+ this.then();
+ var self = this;
+ this._timer = Faye.ENV.setTimeout(function() {
+ self._reject(message);
+ }, seconds * 1000);
},
- setDeferredStatus: function() {
- if (this._timer)
- Faye.ENV.clearTimeout(this._timer);
+ setDeferredStatus: function(status, value) {
+ if (this._timer) Faye.ENV.clearTimeout(this._timer);
- var args = Array.prototype.slice.call(arguments),
- status = args.shift(),
- callbacks;
+ var promise = this.then();
- this._deferredStatus = status;
- this._deferredArgs = args;
-
if (status === 'succeeded')
- callbacks = this._callbacks;
+ this._fulfill(value);
else if (status === 'failed')
- callbacks = this._errbacks;
-
- if (!callbacks) return;
-
- var callback;
- while (callback = callbacks.shift())
- callback[0].apply(callback[1], this._deferredArgs);
+ this._reject(value);
+ else
+ delete this._promise;
}
};
-
Faye.Publisher = {
countListeners: function(eventType) {
- if (!this._subscribers || !this._subscribers[eventType]) return 0;
- return this._subscribers[eventType].length;
+ return this.listeners(eventType).length;
},
bind: function(eventType, listener, context) {
- this._subscribers = this._subscribers || {};
- var list = this._subscribers[eventType] = this._subscribers[eventType] || [];
- list.push([listener, context]);
+ var slice = Array.prototype.slice,
+ handler = function() { listener.apply(context, slice.call(arguments)) };
+
+ this._listeners = this._listeners || [];
+ this._listeners.push([eventType, listener, context, handler]);
+ return this.on(eventType, handler);
},
unbind: function(eventType, listener, context) {
- if (!this._subscribers || !this._subscribers[eventType]) return;
+ this._listeners = this._listeners || [];
+ var n = this._listeners.length, tuple;
- if (!listener) {
- delete this._subscribers[eventType];
- return;
+ while (n--) {
+ tuple = this._listeners[n];
+ if (tuple[0] !== eventType) continue;
+ if (listener && (tuple[1] !== listener || tuple[2] !== context)) continue;
+ this._listeners.splice(n, 1);
+ this.removeListener(eventType, tuple[3]);
}
- var list = this._subscribers[eventType],
- i = list.length;
-
- while (i--) {
- if (listener !== list[i][0]) continue;
- if (context && list[i][1] !== context) continue;
- list.splice(i,1);
- }
- },
-
- trigger: function() {
- var args = Array.prototype.slice.call(arguments),
- eventType = args.shift();
-
- if (!this._subscribers || !this._subscribers[eventType]) return;
-
- var listeners = this._subscribers[eventType].slice(),
- listener;
-
- for (var i = 0, n = listeners.length; i < n; i++) {
- listener = listeners[i];
- listener[0].apply(listener[1], args);
- }
}
};
+Faye.extend(Faye.Publisher, Faye.EventEmitter.prototype);
+Faye.Publisher.trigger = Faye.Publisher.emit;
Faye.Timeouts = {
addTimeout: function(name, delay, callback, context) {
this._timeouts = this._timeouts || {};
if (this._timeouts.hasOwnProperty(name)) return;
@@ -393,33 +802,33 @@
this._timeouts = this._timeouts || {};
var timeout = this._timeouts[name];
if (!timeout) return;
clearTimeout(timeout);
delete this._timeouts[name];
+ },
+
+ removeAllTimeouts: function() {
+ this._timeouts = this._timeouts || {};
+ for (var name in this._timeouts) this.removeTimeout(name);
}
};
-
Faye.Logging = {
LOG_LEVELS: {
+ fatal: 4,
error: 3,
warn: 2,
info: 1,
debug: 0
},
- logLevel: 'error',
-
- log: function(messageArgs, level) {
+ writeLog: function(messageArgs, level) {
if (!Faye.logger) return;
- var levels = Faye.Logging.LOG_LEVELS;
- if (levels[Faye.Logging.logLevel] > levels[level]) return;
-
var messageArgs = Array.prototype.slice.apply(messageArgs),
- banner = ' [' + level.toUpperCase() + '] [Faye',
- klass = this.className,
+ banner = '[Faye',
+ klass = this.className,
message = messageArgs.shift().replace(/\?/g, function() {
try {
return Faye.toJSON(messageArgs.shift());
} catch (e) {
@@ -433,50 +842,33 @@
if (this instanceof Faye[key]) klass = key;
}
if (klass) banner += '.' + klass;
banner += '] ';
- Faye.logger(Faye.timestamp() + banner + message);
+ if (typeof Faye.logger[level] === 'function')
+ Faye.logger[level](banner + message);
+ else if (typeof Faye.logger === 'function')
+ Faye.logger(banner + message);
}
};
(function() {
for (var key in Faye.Logging.LOG_LEVELS)
(function(level, value) {
Faye.Logging[level] = function() {
- this.log(arguments, level);
+ this.writeLog(arguments, level);
};
})(key, Faye.Logging.LOG_LEVELS[key]);
})();
-
Faye.Grammar = {
- LOWALPHA: /^[a-z]$/,
- UPALPHA: /^[A-Z]$/,
- ALPHA: /^([a-z]|[A-Z])$/,
- DIGIT: /^[0-9]$/,
- ALPHANUM: /^(([a-z]|[A-Z])|[0-9])$/,
- MARK: /^(\-|\_|\!|\~|\(|\)|\$|\@)$/,
- STRING: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,
- TOKEN: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,
- INTEGER: /^([0-9])+$/,
- CHANNEL_SEGMENT: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,
- CHANNEL_SEGMENTS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
- WILD_CARD: /^\*{1,2}$/,
- CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,
- VERSION_ELEMENT: /^(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*$/,
- VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/,
- CLIENT_ID: /^((([a-z]|[A-Z])|[0-9]))+$/,
- ID: /^((([a-z]|[A-Z])|[0-9]))+$/,
- ERROR_MESSAGE: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,
- ERROR_ARGS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*$/,
- ERROR_CODE: /^[0-9][0-9][0-9]$/,
- ERROR: /^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/
+ CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,
+ ERROR: /^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/,
+ VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/
};
-
Faye.Extensible = {
addExtension: function(extension) {
this._extensions = this._extensions || [];
this._extensions.push(extension);
if (extension.added) extension.added(this);
@@ -490,11 +882,11 @@
this._extensions.splice(i,1);
if (extension.removed) extension.removed(this);
}
},
- pipeThroughExtensions: function(stage, message, callback, context) {
+ pipeThroughExtensions: function(stage, message, request, callback, context) {
this.debug('Passing through ? extensions: ?', stage, message);
if (!this._extensions) return callback.call(context, message);
var extensions = this._extensions.slice();
@@ -502,12 +894,15 @@
if (!message) return callback.call(context, message);
var extension = extensions.shift();
if (!extension) return callback.call(context, message);
- if (extension[stage]) extension[stage](message, pipe);
- else pipe(message);
+ var fn = extension[stage];
+ if (!fn) return pipe(message);
+
+ if (fn.length >= 3) extension[stage](message, request, pipe);
+ else extension[stage](message, pipe);
};
pipe(message);
}
};
@@ -636,14 +1031,23 @@
}
}
})
});
+Faye.Envelope = Faye.Class({
+ initialize: function(message, timeout) {
+ this.id = message.id;
+ this.message = message;
-Faye.Publication = Faye.Class(Faye.Deferrable);
+ if (timeout !== undefined) this.timeout(timeout / 1000, false);
+ }
+});
+Faye.extend(Faye.Envelope.prototype, Faye.Deferrable);
+Faye.Publication = Faye.Class(Faye.Deferrable);
+
Faye.Subscription = Faye.Class({
initialize: function(client, channels, callback, context) {
this._client = client;
this._channels = channels;
this._callback = callback;
@@ -662,39 +1066,45 @@
}
});
Faye.extend(Faye.Subscription.prototype, Faye.Deferrable);
-
Faye.Client = Faye.Class({
UNCONNECTED: 1,
CONNECTING: 2,
CONNECTED: 3,
DISCONNECTED: 4,
HANDSHAKE: 'handshake',
RETRY: 'retry',
NONE: 'none',
- CONNECTION_TIMEOUT: 60.0,
- DEFAULT_RETRY: 5.0,
+ CONNECTION_TIMEOUT: 60,
+ DEFAULT_RETRY: 5,
+ MAX_REQUEST_SIZE: 2048,
DEFAULT_ENDPOINT: '/bayeux',
- INTERVAL: 0.0,
+ INTERVAL: 0,
initialize: function(endpoint, options) {
this.info('New client created for ?', endpoint);
this._options = options || {};
- this.endpoint = endpoint || this.DEFAULT_ENDPOINT;
+ this.endpoint = Faye.URI.parse(endpoint || this.DEFAULT_ENDPOINT);
this.endpoints = this._options.endpoints || {};
this.transports = {};
- this._cookies = Faye.CookieJar && new Faye.CookieJar();
- this._headers = {};
+ this.cookies = Faye.CookieJar && new Faye.CookieJar();
+ this.headers = {};
+ this.ca = this._options.ca;
this._disabled = [];
- this.retry = this._options.retry || this.DEFAULT_RETRY;
+ this._retry = this._options.retry || this.DEFAULT_RETRY;
+ for (var key in this.endpoints)
+ this.endpoints[key] = Faye.URI.parse(this.endpoints[key]);
+
+ this.maxRequestSize = this.MAX_REQUEST_SIZE;
+
this._state = this.UNCONNECTED;
this._channels = new Faye.Channel.Set();
this._messageId = 0;
this._responseCallbacks = {};
@@ -703,11 +1113,11 @@
reconnect: this.RETRY,
interval: 1000 * (this._options.interval || this.INTERVAL),
timeout: 1000 * (this._options.timeout || this.CONNECTION_TIMEOUT)
};
- if (Faye.Event)
+ if (Faye.Event && Faye.ENV.onbeforeunload !== undefined)
Faye.Event.on(Faye.ENV, 'beforeunload', function() {
if (Faye.indexOf(this._disabled, 'autodisconnect') < 0)
this.disconnect();
}, this);
},
@@ -715,26 +1125,13 @@
disable: function(feature) {
this._disabled.push(feature);
},
setHeader: function(name, value) {
- this._headers[name] = value;
+ this.headers[name] = value;
},
- getClientId: function() {
- return this._clientId;
- },
-
- getState: function() {
- switch (this._state) {
- case this.UNCONNECTED: return 'UNCONNECTED';
- case this.CONNECTING: return 'CONNECTING';
- case this.CONNECTED: return 'CONNECTED';
- case this.DISCONNECTED: return 'DISCONNECTED';
- }
- },
-
// Request
// MUST include: * channel
// * version
// * supportedConnectionTypes
// MAY include: * minimumVersion
@@ -757,16 +1154,16 @@
if (this._state !== this.UNCONNECTED) return;
this._state = this.CONNECTING;
var self = this;
- this.info('Initiating handshake with ?', this.endpoint);
+ this.info('Initiating handshake with ?', Faye.URI.stringify(this.endpoint));
this._selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
this._send({
- channel: Faye.Channel.HANDSHAKE,
- version: Faye.BAYEUX_VERSION,
+ channel: Faye.Channel.HANDSHAKE,
+ version: Faye.BAYEUX_VERSION,
supportedConnectionTypes: [this._transport.connectionType]
}, function(response) {
if (response.successful) {
@@ -776,11 +1173,11 @@
this._selectTransport(response.supportedConnectionTypes);
this.info('Handshake successful: ?', this._clientId);
this.subscribe(this._channels.getKeys(), true);
- if (callback) callback.call(context);
+ if (callback) Faye.Promise.defer(function() { callback.call(context) });
} else {
this.info('Handshake unsuccessful');
Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._advice.interval);
this._state = this.UNCONNECTED;
@@ -807,11 +1204,11 @@
this.callback(callback, context);
if (this._state !== this.CONNECTED) return;
this.info('Calling deferred actions for ?', this._clientId);
this.setDeferredStatus('succeeded');
- this.setDeferredStatus('deferred');
+ this.setDeferredStatus('unknown');
if (this._connectRequest) return;
this._connectRequest = true;
this.info('Initiating connection for ?', this._clientId);
@@ -836,15 +1233,17 @@
this._state = this.DISCONNECTED;
this.info('Disconnecting ?', this._clientId);
this._send({
- channel: Faye.Channel.DISCONNECT,
- clientId: this._clientId
+ channel: Faye.Channel.DISCONNECT,
+ clientId: this._clientId
}, function(response) {
- if (response.successful) this._transport.close();
+ if (!response.successful) return;
+ this._transport.close();
+ delete this._transport;
}, this);
this.info('Clearing channel listeners for ?', this._clientId);
this._channels = new Faye.Channel.Set();
},
@@ -946,13 +1345,14 @@
this.connect(function() {
this.info('Client ? queueing published message to ?: ?', this._clientId, channel, data);
this._send({
- channel: channel,
- data: data,
- clientId: this._clientId
+ channel: channel,
+ data: data,
+ clientId: this._clientId
+
}, function(response) {
if (response.successful)
publication.setDeferredStatus('succeeded');
else
publication.setDeferredStatus('failed', Faye.Error.parse(response.error));
@@ -961,61 +1361,86 @@
return publication;
},
receiveMessage: function(message) {
- this.pipeThroughExtensions('incoming', message, function(message) {
+ var id = message.id, timeout, callback;
+
+ if (message.successful !== undefined) {
+ callback = this._responseCallbacks[id];
+ delete this._responseCallbacks[id];
+ }
+
+ this.pipeThroughExtensions('incoming', message, null, function(message) {
if (!message) return;
if (message.advice) this._handleAdvice(message.advice);
this._deliverMessage(message);
- if (message.successful === undefined) return;
+ if (callback) callback[0].call(callback[1], message);
+ }, this);
- var callback = this._responseCallbacks[message.id];
- if (!callback) return;
+ if (this._transportUp === true) return;
+ this._transportUp = true;
+ this.trigger('transport:up');
+ },
- delete this._responseCallbacks[message.id];
- callback[0].call(callback[1], message);
- }, this);
+ messageError: function(messages, immediate) {
+ var retry = this._retry,
+ self = this,
+ id, message, timeout;
+
+ for (var i = 0, n = messages.length; i < n; i++) {
+ message = messages[i];
+ id = message.id;
+
+ if (immediate)
+ this._transportSend(message);
+ else
+ Faye.ENV.setTimeout(function() { self._transportSend(message) }, retry * 1000);
+ }
+
+ if (immediate || this._transportUp === false) return;
+ this._transportUp = false;
+ this.trigger('transport:down');
},
_selectTransport: function(transportTypes) {
Faye.Transport.get(this, transportTypes, this._disabled, function(transport) {
- this.debug('Selected ? transport for ?', transport.connectionType, transport.endpoint);
+ this.debug('Selected ? transport for ?', transport.connectionType, Faye.URI.stringify(transport.endpoint));
if (transport === this._transport) return;
if (this._transport) this._transport.close();
this._transport = transport;
- this._transport.cookies = this._cookies;
- this._transport.headers = this._headers;
-
- transport.bind('down', function() {
- if (this._transportUp !== undefined && !this._transportUp) return;
- this._transportUp = false;
- this.trigger('transport:down');
- }, this);
-
- transport.bind('up', function() {
- if (this._transportUp !== undefined && this._transportUp) return;
- this._transportUp = true;
- this.trigger('transport:up');
- }, this);
}, this);
},
_send: function(message, callback, context) {
- message.id = this._generateMessageId();
- if (callback) this._responseCallbacks[message.id] = [callback, context];
+ if (!this._transport) return;
+ message.id = message.id || this._generateMessageId();
- this.pipeThroughExtensions('outgoing', message, function(message) {
+ this.pipeThroughExtensions('outgoing', message, null, function(message) {
if (!message) return;
- this._transport.send(message, this._advice.timeout / 1000);
+ if (callback) this._responseCallbacks[message.id] = [callback, context];
+ this._transportSend(message);
}, this);
},
+ _transportSend: function(message) {
+ if (!this._transport) return;
+
+ var timeout = 1.2 * (this._advice.timeout || this._retry * 1000),
+ envelope = new Faye.Envelope(message, timeout);
+
+ envelope.errback(function(immediate) {
+ this.messageError([message], immediate);
+ }, this);
+
+ this._transport.send(envelope);
+ },
+
_generateMessageId: function() {
this._messageId += 1;
if (this._messageId >= Math.pow(2,32)) this._messageId = 0;
return this._messageId.toString(36);
},
@@ -1034,98 +1459,123 @@
if (!message.channel || message.data === undefined) return;
this.info('Client ? calling listeners for ? with ?', this._clientId, message.channel, message.data);
this._channels.distributeMessage(message);
},
- _teardownConnection: function() {
- if (!this._connectRequest) return;
- this._connectRequest = null;
- this.info('Closed connection for ?', this._clientId);
- },
-
_cycleConnection: function() {
- this._teardownConnection();
+ if (this._connectRequest) {
+ this._connectRequest = null;
+ this.info('Closed connection for ?', this._clientId);
+ }
var self = this;
Faye.ENV.setTimeout(function() { self.connect() }, this._advice.interval);
}
});
Faye.extend(Faye.Client.prototype, Faye.Deferrable);
Faye.extend(Faye.Client.prototype, Faye.Publisher);
Faye.extend(Faye.Client.prototype, Faye.Logging);
Faye.extend(Faye.Client.prototype, Faye.Extensible);
-
Faye.Transport = Faye.extend(Faye.Class({
- MAX_DELAY: 0.0,
+ MAX_DELAY: 0,
batching: true,
initialize: function(client, endpoint) {
this._client = client;
this.endpoint = endpoint;
this._outbox = [];
},
close: function() {},
- send: function(message, timeout) {
+ encode: function(envelopes) {
+ return '';
+ },
+
+ send: function(envelope) {
+ var message = envelope.message;
+
this.debug('Client ? sending message to ?: ?',
- this._client._clientId, this.endpoint, message);
+ this._client._clientId, Faye.URI.stringify(this.endpoint), message);
- if (!this.batching) return this.request([message], timeout);
+ if (!this.batching) return this.request([envelope]);
- this._outbox.push(message);
- this._timeout = timeout;
+ this._outbox.push(envelope);
if (message.channel === Faye.Channel.HANDSHAKE)
return this.addTimeout('publish', 0.01, this.flush, this);
if (message.channel === Faye.Channel.CONNECT)
this._connectMessage = message;
- if (this.shouldFlush && this.shouldFlush(this._outbox))
- return this.flush();
-
+ this.flushLargeBatch();
this.addTimeout('publish', this.MAX_DELAY, this.flush, this);
},
flush: function() {
this.removeTimeout('publish');
if (this._outbox.length > 1 && this._connectMessage)
this._connectMessage.advice = {timeout: 0};
- this.request(this._outbox, this._timeout);
+ this.request(this._outbox);
this._connectMessage = null;
this._outbox = [];
},
- receive: function(responses) {
+ flushLargeBatch: function() {
+ var string = this.encode(this._outbox);
+ if (string.length < this._client.maxRequestSize) return;
+ var last = this._outbox.pop();
+ this.flush();
+ if (last) this._outbox.push(last);
+ },
+
+ receive: function(envelopes, responses) {
+ var n = envelopes.length;
+ while (n--) envelopes[n].setDeferredStatus('succeeded');
+
+ responses = [].concat(responses);
+
this.debug('Client ? received from ?: ?',
- this._client._clientId, this.endpoint, responses);
+ this._client._clientId, Faye.URI.stringify(this.endpoint), responses);
- for (var i = 0, n = responses.length; i < n; i++) {
+ for (var i = 0, n = responses.length; i < n; i++)
this._client.receiveMessage(responses[i]);
- }
},
- retry: function(message, timeout) {
- var called = false,
- retry = this._client.retry * 1000,
- self = this;
+ handleError: function(envelopes, immediate) {
+ var n = envelopes.length;
+ while (n--) envelopes[n].setDeferredStatus('failed', immediate);
+ },
- return function() {
- if (called) return;
- called = true;
- Faye.ENV.setTimeout(function() { self.request(message, timeout) }, retry);
- };
+ _getCookies: function() {
+ var cookies = this._client.cookies;
+ if (!cookies) return '';
+
+ return cookies.getCookies({
+ domain: this.endpoint.hostname,
+ path: this.endpoint.path,
+ secure: this.endpoint.protocol === 'https:'
+ }).toValueString();
+ },
+
+ _storeCookies: function(setCookie) {
+ if (!setCookie || !this._client.cookies) return;
+ setCookie = [].concat(setCookie);
+ var cookie;
+
+ for (var i = 0, n = setCookie.length; i < n; i++) {
+ cookie = this._client.cookies.setCookie(setCookie[i]);
+ cookie = cookie[0] || cookie;
+ cookie.domain = cookie.domain || this.endpoint.hostname;
+ }
}
}), {
- MAX_URL_LENGTH: 2048,
-
get: function(client, allowed, disabled, callback, context) {
var endpoint = client.endpoint;
Faye.asyncEach(this._transports, function(pair, resume) {
var connType = pair[0], klass = pair[1],
@@ -1143,11 +1593,11 @@
if (!isUsable) return resume();
var transport = klass.hasOwnProperty('create') ? klass.create(client, connEndpoint) : new klass(client, connEndpoint);
callback.call(context, transport);
});
}, function() {
- throw new Error('Could not find a usable connection type for ' + endpoint);
+ throw new Error('Could not find a usable connection type for ' + Faye.URI.stringify(endpoint));
});
},
register: function(type, klass) {
this._transports.push([type, klass]);
@@ -1156,14 +1606,12 @@
_transports: []
});
Faye.extend(Faye.Transport.prototype, Faye.Logging);
-Faye.extend(Faye.Transport.prototype, Faye.Publisher);
Faye.extend(Faye.Transport.prototype, Faye.Timeouts);
-
Faye.Event = {
_registry: [],
on: function(element, eventName, callback, context) {
var wrapped = function() { callback.call(context) };
@@ -1202,102 +1650,30 @@
register = null;
}
}
};
-Faye.Event.on(Faye.ENV, 'unload', Faye.Event.detach, Faye.Event);
+if (Faye.ENV.onunload !== undefined) Faye.Event.on(Faye.ENV, 'unload', Faye.Event.detach, Faye.Event);
-
-Faye.URI = Faye.extend(Faye.Class({
- queryString: function() {
- var pairs = [];
- for (var key in this.params) {
- if (!this.params.hasOwnProperty(key)) continue;
- pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(this.params[key]));
- }
- return pairs.join('&');
- },
-
- isSameOrigin: function() {
- var host = Faye.URI.parse(Faye.ENV.location.href, false);
-
- var external = (host.hostname !== this.hostname) ||
- (host.port !== this.port) ||
- (host.protocol !== this.protocol);
-
- return !external;
- },
-
- toURL: function() {
- var query = this.queryString();
- return this.protocol + '//' + this.hostname + (this.port ? ':' + this.port : '') +
- this.pathname + (query ? '?' + query : '') + this.hash;
- }
-}), {
- parse: function(url, params) {
- if (typeof url !== 'string') return url;
- var uri = new this(), parts;
-
- var consume = function(name, pattern, infer) {
- url = url.replace(pattern, function(match) {
- uri[name] = match;
- return '';
- });
- if (uri[name] === undefined)
- uri[name] = infer ? Faye.ENV.location[name] : '';
- };
-
- consume('protocol', /^https?\:/, true);
- consume('host', /^\/\/[^\/]+/, true);
-
- if (!/^\//.test(url)) url = Faye.ENV.location.pathname.replace(/[^\/]*$/, '') + url;
- consume('pathname', /^\/[^\?#]*/);
- consume('search', /^\?[^#]*/);
- consume('hash', /^#.*/);
-
- if (/^\/\//.test(uri.host)) {
- uri.host = uri.host.substr(2);
- parts = uri.host.split(':');
- uri.hostname = parts[0];
- uri.port = parts[1] || '';
- } else {
- uri.hostname = Faye.ENV.location.hostname;
- uri.port = Faye.ENV.location.port;
- }
-
- if (params === false) {
- uri.params = {};
- } else {
- var query = uri.search.replace(/^\?/, ''),
- pairs = query ? query.split('&') : [],
- n = pairs.length,
- data = {};
-
- while (n--) {
- parts = pairs[n].split('=');
- data[decodeURIComponent(parts[0] || '')] = decodeURIComponent(parts[1] || '');
- }
- if (typeof params === 'object') Faye.extend(data, params);
-
- uri.params = data;
- }
-
- return uri;
- }
-});
-
-
/*
- http://www.JSON.org/json2.js
- 2009-04-16
+ json2.js
+ 2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
@@ -1319,11 +1695,11 @@
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
- bound to the object holding the key.
+ bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
@@ -1422,59 +1798,56 @@
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
-
- This code should be minified before deployment.
- See http://javascript.crockford.com/jsmin.html
-
- USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
- NOT CONTROL.
*/
-/*jslint evil: true */
+/*jslint evil: true, regexp: true */
-/*global JSON */
-
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
+
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
-if (!this.JSON) {
+if (typeof JSON !== 'object') {
JSON = {};
}
+
(function () {
+ 'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
- Date.prototype.toJSON = function (key) {
+ Date.prototype.toJSON = function () {
- return this.getUTCFullYear() + '-' +
- f(this.getUTCMonth() + 1) + '-' +
- f(this.getUTCDate()) + 'T' +
- f(this.getUTCHours()) + ':' +
- f(this.getUTCMinutes()) + ':' +
- f(this.getUTCSeconds()) + 'Z';
+ return isFinite(this.valueOf())
+ ? this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z'
+ : null;
};
- String.prototype.toJSON =
- Number.prototype.toJSON =
- Boolean.prototype.toJSON = function (key) {
- return this.valueOf();
- };
+ String.prototype.toJSON =
+ Number.prototype.toJSON =
+ Boolean.prototype.toJSON = function () {
+ return this.valueOf();
+ };
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
@@ -1497,17 +1870,16 @@
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
- return escapable.test(string) ?
- '"' + string.replace(escapable, function (a) {
- var c = meta[a];
- return typeof c === 'string' ? c :
- '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- }) + '"' :
- '"' + string + '"';
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
+ var c = meta[a];
+ return typeof c === 'string'
+ ? c
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+ }) + '"' : '"' + string + '"';
}
function str(key, holder) {
@@ -1586,26 +1958,26 @@
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
- v = partial.length === 0 ? '[]' :
- gap ? '[\n' + gap +
- partial.join(',\n' + gap) + '\n' +
- mind + ']' :
- '[' + partial.join(',') + ']';
+ v = partial.length === 0
+ ? '[]'
+ : gap
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
+ : '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
- k = rep[i];
- if (typeof k === 'string') {
+ if (typeof rep[i] === 'string') {
+ k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
@@ -1613,11 +1985,11 @@
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
- if (Object.hasOwnProperty.call(value, k)) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
@@ -1625,70 +1997,68 @@
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
- v = partial.length === 0 ? '{}' :
- gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
- mind + '}' : '{' + partial.join(',') + '}';
+ v = partial.length === 0
+ ? '{}'
+ : gap
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
+ : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
-// NOTE we've hacked this to expose this method to Faye. We need to use this
-// to avoid problems with buggy Firefox version and bad #toJSON implementations
+ Faye.stringify = function (value, replacer, space) {
- Faye.stringify = function (value, replacer, space) {
-
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
- var i;
- gap = '';
- indent = '';
+ var i;
+ gap = '';
+ indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
- if (typeof space === 'number') {
- for (i = 0; i < space; i += 1) {
- indent += ' ';
- }
+ if (typeof space === 'number') {
+ for (i = 0; i < space; i += 1) {
+ indent += ' ';
+ }
// If the space parameter is a string, it will be used as the indent string.
- } else if (typeof space === 'string') {
- indent = space;
- }
+ } else if (typeof space === 'string') {
+ indent = space;
+ }
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
- rep = replacer;
- if (replacer && typeof replacer !== 'function' &&
- (typeof replacer !== 'object' ||
- typeof replacer.length !== 'number')) {
- throw new Error('JSON.stringify');
- }
+ rep = replacer;
+ if (replacer && typeof replacer !== 'function' &&
+ (typeof replacer !== 'object' ||
+ typeof replacer.length !== 'number')) {
+ throw new Error('JSON.stringify');
+ }
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
- return str('', {'': value});
- };
+ return str('', {'': value});
+ };
if (typeof JSON.stringify !== 'function') {
JSON.stringify = Faye.stringify;
}
-
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
@@ -1703,11 +2073,11 @@
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
- if (Object.hasOwnProperty.call(value, k)) {
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
@@ -1721,10 +2091,11 @@
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
+ text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
@@ -1742,14 +2113,14 @@
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
- if (/^[\],:{}\s]*$/.
-test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
-replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
-replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
+ if (/^[\],:{}\s]*$/
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
@@ -1757,22 +2128,22 @@
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
- return typeof reviver === 'function' ?
- walk({'': j}, '') : j;
+ return typeof reviver === 'function'
+ ? walk({'': j}, '')
+ : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
-
Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
UNCONNECTED: 1,
CONNECTING: 2,
CONNECTED: 3,
@@ -1782,103 +2153,127 @@
this.callback(function() { callback.call(context, true) });
this.errback(function() { callback.call(context, false) });
this.connect();
},
- request: function(messages, timeout) {
- if (messages.length === 0) return;
- this._messages = this._messages || {};
+ request: function(envelopes) {
+ this._pending = this._pending || new Faye.Set();
+ for (var i = 0, n = envelopes.length; i < n; i++) this._pending.add(envelopes[i]);
- for (var i = 0, n = messages.length; i < n; i++) {
- this._messages[messages[i].id] = messages[i];
- }
- this.callback(function(socket) { socket.send(Faye.toJSON(messages)) });
+ this.callback(function(socket) {
+ if (!socket) return;
+ var messages = Faye.map(envelopes, function(e) { return e.message });
+ socket.send(Faye.toJSON(messages));
+ }, this);
this.connect();
},
- close: function() {
- if (!this._socket) return;
- this._socket.onclose = this._socket.onerror = null;
- this._socket.close();
- delete this._socket;
- this.setDeferredStatus('deferred');
- this._state = this.UNCONNECTED;
- },
-
connect: function() {
if (Faye.Transport.WebSocket._unloaded) return;
this._state = this._state || this.UNCONNECTED;
if (this._state !== this.UNCONNECTED) return;
-
this._state = this.CONNECTING;
- var ws = Faye.Transport.WebSocket.getClass();
- if (!ws) return this.setDeferredStatus('failed');
+ var socket = this._createSocket();
+ if (!socket) return this.setDeferredStatus('failed');
- this._socket = new ws(Faye.Transport.WebSocket.getSocketUrl(this.endpoint));
var self = this;
- this._socket.onopen = function() {
+ socket.onopen = function() {
+ if (socket.headers) self._storeCookies(socket.headers['set-cookie']);
+ self._socket = socket;
self._state = self.CONNECTED;
self._everConnected = true;
- self.setDeferredStatus('succeeded', self._socket);
- self.trigger('up');
+ self._ping();
+ self.setDeferredStatus('succeeded', socket);
};
- this._socket.onmessage = function(event) {
- var messages = JSON.parse(event.data);
+ var closed = false;
+ socket.onclose = socket.onerror = function() {
+ if (closed) return;
+ closed = true;
+
+ var wasConnected = (self._state === self.CONNECTED);
+ socket.onopen = socket.onclose = socket.onerror = socket.onmessage = null;
+
+ delete self._socket;
+ self._state = self.UNCONNECTED;
+ self.removeTimeout('ping');
+ self.setDeferredStatus('unknown');
+
+ var pending = self._pending ? self._pending.toArray() : [];
+ delete self._pending;
+
+ if (wasConnected) {
+ self.handleError(pending, true);
+ } else if (self._everConnected) {
+ self.handleError(pending);
+ } else {
+ self.setDeferredStatus('failed');
+ }
+ };
+
+ socket.onmessage = function(event) {
+ var messages = JSON.parse(event.data),
+ envelopes = [],
+ envelope;
+
if (!messages) return;
messages = [].concat(messages);
for (var i = 0, n = messages.length; i < n; i++) {
- delete self._messages[messages[i].id];
+ if (messages[i].successful === undefined) continue;
+ envelope = self._pending.remove(messages[i]);
+ if (envelope) envelopes.push(envelope);
}
- self.receive(messages);
+ self.receive(envelopes, messages);
};
+ },
- this._socket.onclose = this._socket.onerror = function() {
- var wasConnected = (self._state === self.CONNECTED);
- self.setDeferredStatus('deferred');
- self._state = self.UNCONNECTED;
+ close: function() {
+ if (!this._socket) return;
+ this._socket.close();
+ },
- self.close();
+ _createSocket: function() {
+ var url = Faye.Transport.WebSocket.getSocketUrl(this.endpoint),
+ options = {headers: Faye.copyObject(this._client.headers), ca: this._client.ca};
- if (wasConnected) return self.resend();
- if (!self._everConnected) return self.setDeferredStatus('failed');
+ options.headers['Cookie'] = this._getCookies();
- var retry = self._client.retry * 1000;
- Faye.ENV.setTimeout(function() { self.connect() }, retry);
- self.trigger('down');
- };
+ if (Faye.WebSocket) return new Faye.WebSocket.Client(url, [], options);
+ if (Faye.ENV.MozWebSocket) return new MozWebSocket(url);
+ if (Faye.ENV.WebSocket) return new WebSocket(url);
},
- resend: function() {
- if (!this._messages) return;
- var messages = Faye.map(this._messages, function(id, msg) { return msg });
- this.request(messages);
+ _ping: function() {
+ if (!this._socket) return;
+ this._socket.send('[]');
+ this.addTimeout('ping', this._client._advice.timeout/2000, this._ping, this);
}
+
}), {
- getSocketUrl: function(endpoint) {
- if (Faye.URI) endpoint = Faye.URI.parse(endpoint).toURL();
- return endpoint.replace(/^http(s?):/ig, 'ws$1:');
+ PROTOCOLS: {
+ 'http:': 'ws:',
+ 'https:': 'wss:'
},
- getClass: function() {
- return (Faye.WebSocket && Faye.WebSocket.Client) ||
- Faye.ENV.WebSocket ||
- Faye.ENV.MozWebSocket;
+ create: function(client, endpoint) {
+ var sockets = client.transports.websocket = client.transports.websocket || {};
+ sockets[endpoint.href] = sockets[endpoint.href] || new this(client, endpoint);
+ return sockets[endpoint.href];
},
- isUsable: function(client, endpoint, callback, context) {
- this.create(client, endpoint).isUsable(callback, context);
+ getSocketUrl: function(endpoint) {
+ endpoint = Faye.copyObject(endpoint);
+ endpoint.protocol = this.PROTOCOLS[endpoint.protocol];
+ return Faye.URI.stringify(endpoint);
},
- create: function(client, endpoint) {
- var sockets = client.transports.websocket = client.transports.websocket || {};
- sockets[endpoint] = sockets[endpoint] || new this(client, endpoint);
- return sockets[endpoint];
+ isUsable: function(client, endpoint, callback, context) {
+ this.create(client, endpoint).isUsable(callback, context);
}
});
Faye.extend(Faye.Transport.WebSocket.prototype, Faye.Deferrable);
Faye.Transport.register('websocket', Faye.Transport.WebSocket);
@@ -1886,208 +2281,208 @@
if (Faye.Event)
Faye.Event.on(Faye.ENV, 'beforeunload', function() {
Faye.Transport.WebSocket._unloaded = true;
});
-
Faye.Transport.EventSource = Faye.extend(Faye.Class(Faye.Transport, {
initialize: function(client, endpoint) {
Faye.Transport.prototype.initialize.call(this, client, endpoint);
if (!Faye.ENV.EventSource) return this.setDeferredStatus('failed');
this._xhr = new Faye.Transport.XHR(client, endpoint);
- var socket = new EventSource(endpoint + '/' + client.getClientId()),
+ endpoint = Faye.copyObject(endpoint);
+ endpoint.pathname += '/' + client._clientId;
+
+ var socket = new EventSource(Faye.URI.stringify(endpoint)),
self = this;
socket.onopen = function() {
self._everConnected = true;
self.setDeferredStatus('succeeded');
- self.trigger('up');
};
socket.onerror = function() {
if (self._everConnected) {
- self.trigger('down');
+ self._client.messageError([]);
} else {
self.setDeferredStatus('failed');
socket.close();
}
};
socket.onmessage = function(event) {
- self.receive(JSON.parse(event.data));
- self.trigger('up');
+ self.receive([], JSON.parse(event.data));
};
this._socket = socket;
},
+ close: function() {
+ if (!this._socket) return;
+ this._socket.onopen = this._socket.onerror = this._socket.onmessage = null;
+ this._socket.close();
+ delete this._socket;
+ },
+
isUsable: function(callback, context) {
this.callback(function() { callback.call(context, true) });
this.errback(function() { callback.call(context, false) });
},
- request: function(message, timeout) {
- this._xhr.request(message, timeout);
+ encode: function(envelopes) {
+ return this._xhr.encode(envelopes);
},
- close: function() {
- if (!this._socket) return;
- this._socket.onerror = null;
- this._socket.close();
- delete this._socket;
+ request: function(envelopes) {
+ this._xhr.request(envelopes);
}
+
}), {
isUsable: function(client, endpoint, callback, context) {
- var id = client.getClientId();
+ var id = client._clientId;
if (!id) return callback.call(context, false);
Faye.Transport.XHR.isUsable(client, endpoint, function(usable) {
if (!usable) return callback.call(context, false);
this.create(client, endpoint).isUsable(callback, context);
}, this);
},
create: function(client, endpoint) {
- var sockets = client.transports.eventsource = client.transports.eventsource || {},
- id = client.getClientId(),
- endpoint = endpoint + '/' + (id || '');
+ var sockets = client.transports.eventsource = client.transports.eventsource || {},
+ id = client._clientId;
- sockets[endpoint] = sockets[endpoint] || new this(client, endpoint);
- return sockets[endpoint];
+ endpoint = Faye.copyObject(endpoint);
+ endpoint.pathname += '/' + (id || '');
+ var url = Faye.URI.stringify(endpoint);
+
+ sockets[url] = sockets[url] || new this(client, endpoint);
+ return sockets[url];
}
});
Faye.extend(Faye.Transport.EventSource.prototype, Faye.Deferrable);
Faye.Transport.register('eventsource', Faye.Transport.EventSource);
-
Faye.Transport.XHR = Faye.extend(Faye.Class(Faye.Transport, {
- request: function(message, timeout) {
- var retry = this.retry(message, timeout),
- path = Faye.URI.parse(this.endpoint).pathname,
- self = this,
- xhr = Faye.ENV.ActiveXObject
- ? new ActiveXObject("Microsoft.XMLHTTP")
- : new XMLHttpRequest();
+ encode: function(envelopes) {
+ var messages = Faye.map(envelopes, function(e) { return e.message });
+ return Faye.toJSON(messages);
+ },
+ request: function(envelopes) {
+ var path = this.endpoint.path,
+ xhr = Faye.ENV.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(),
+ self = this;
+
xhr.open('POST', path, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
- var headers = this.headers;
+ var headers = this._client.headers;
for (var key in headers) {
if (!headers.hasOwnProperty(key)) continue;
xhr.setRequestHeader(key, headers[key]);
}
var abort = function() { xhr.abort() };
Faye.Event.on(Faye.ENV, 'beforeunload', abort);
- var cleanUp = function() {
- Faye.Event.detach(Faye.ENV, 'beforeunload', abort);
- xhr.onreadystatechange = function() {};
- xhr = null;
- };
-
xhr.onreadystatechange = function() {
- if (xhr.readyState !== 4) return;
+ if (!xhr || xhr.readyState !== 4) return;
var parsedMessage = null,
status = xhr.status,
- successful = ((status >= 200 && status < 300) ||
- status === 304 ||
- status === 1223);
+ text = xhr.responseText,
+ successful = (status >= 200 && status < 300) || status === 304 || status === 1223;
- if (!successful) {
- cleanUp();
- retry();
- return self.trigger('down');
- }
+ Faye.Event.detach(Faye.ENV, 'beforeunload', abort);
+ xhr.onreadystatechange = function() {};
+ xhr = null;
+ if (!successful) return self.handleError(envelopes);
+
try {
- parsedMessage = JSON.parse(xhr.responseText);
+ parsedMessage = JSON.parse(text);
} catch (e) {}
- cleanUp();
-
- if (parsedMessage) {
- self.receive(parsedMessage);
- self.trigger('up');
- } else {
- retry();
- self.trigger('down');
- }
+ if (parsedMessage)
+ self.receive(envelopes, parsedMessage);
+ else
+ self.handleError(envelopes);
};
- xhr.send(Faye.toJSON(message));
+ xhr.send(this.encode(envelopes));
}
}), {
isUsable: function(client, endpoint, callback, context) {
- callback.call(context, Faye.URI.parse(endpoint).isSameOrigin());
+ callback.call(context, Faye.URI.isSameOrigin(endpoint));
}
});
Faye.Transport.register('long-polling', Faye.Transport.XHR);
Faye.Transport.CORS = Faye.extend(Faye.Class(Faye.Transport, {
- request: function(message, timeout) {
+ encode: function(envelopes) {
+ var messages = Faye.map(envelopes, function(e) { return e.message });
+ return 'message=' + encodeURIComponent(Faye.toJSON(messages));
+ },
+
+ request: function(envelopes) {
var xhrClass = Faye.ENV.XDomainRequest ? XDomainRequest : XMLHttpRequest,
xhr = new xhrClass(),
- retry = this.retry(message, timeout),
- self = this;
+ headers = this._client.headers,
+ self = this,
+ key;
- xhr.open('POST', this.endpoint, true);
- if (xhr.setRequestHeader) xhr.setRequestHeader('Pragma', 'no-cache');
+ xhr.open('POST', Faye.URI.stringify(this.endpoint), true);
+ if (xhr.setRequestHeader) {
+ xhr.setRequestHeader('Pragma', 'no-cache');
+ for (key in headers) {
+ if (!headers.hasOwnProperty(key)) continue;
+ xhr.setRequestHeader(key, headers[key]);
+ }
+ }
+
var cleanUp = function() {
if (!xhr) return false;
xhr.onload = xhr.onerror = xhr.ontimeout = xhr.onprogress = null;
xhr = null;
- Faye.ENV.clearTimeout(timer);
- return true;
};
xhr.onload = function() {
var parsedMessage = null;
try {
parsedMessage = JSON.parse(xhr.responseText);
} catch (e) {}
cleanUp();
- if (parsedMessage) {
- self.receive(parsedMessage);
- self.trigger('up');
- } else {
- retry();
- self.trigger('down');
- }
+ if (parsedMessage)
+ self.receive(envelopes, parsedMessage);
+ else
+ self.handleError(envelopes);
};
- var onerror = function() {
+ xhr.onerror = xhr.ontimeout = function() {
cleanUp();
- retry();
- self.trigger('down');
+ self.handleError(envelopes);
};
- var timer = Faye.ENV.setTimeout(onerror, 1.5 * 1000 * timeout);
- xhr.onerror = onerror;
- xhr.ontimeout = onerror;
xhr.onprogress = function() {};
- xhr.send('message=' + encodeURIComponent(Faye.toJSON(message)));
+ xhr.send(this.encode(envelopes));
}
}), {
isUsable: function(client, endpoint, callback, context) {
- if (Faye.URI.parse(endpoint).isSameOrigin())
+ if (Faye.URI.isSameOrigin(endpoint))
return callback.call(context, false);
if (Faye.ENV.XDomainRequest)
- return callback.call(context, Faye.URI.parse(endpoint).protocol ===
- Faye.URI.parse(Faye.ENV.location).protocol);
+ return callback.call(context, endpoint.protocol === Faye.ENV.location.protocol);
if (Faye.ENV.XMLHttpRequest) {
var xhr = new Faye.ENV.XMLHttpRequest();
return callback.call(context, xhr.withCredentials !== undefined);
}
@@ -2095,54 +2490,40 @@
}
});
Faye.Transport.register('cross-origin-long-polling', Faye.Transport.CORS);
-
Faye.Transport.JSONP = Faye.extend(Faye.Class(Faye.Transport, {
- shouldFlush: function(messages) {
- var params = {
- message: Faye.toJSON(messages),
- jsonp: '__jsonp' + Faye.Transport.JSONP._cbCount + '__'
- };
- var location = Faye.URI.parse(this.endpoint, params).toURL();
- return location.length >= Faye.Transport.MAX_URL_LENGTH;
+ encode: function(envelopes) {
+ var messages = Faye.map(envelopes, function(e) { return e.message });
+ var url = Faye.copyObject(this.endpoint);
+ url.query.message = Faye.toJSON(messages);
+ url.query.jsonp = '__jsonp' + Faye.Transport.JSONP._cbCount + '__';
+ return Faye.URI.stringify(url);
},
- request: function(messages, timeout) {
- var params = {message: Faye.toJSON(messages)},
+ request: function(envelopes) {
+ var messages = Faye.map(envelopes, function(e) { return e.message }),
head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
callbackName = Faye.Transport.JSONP.getCallbackName(),
- location = Faye.URI.parse(this.endpoint, params),
- retry = this.retry(messages, timeout),
+ endpoint = Faye.copyObject(this.endpoint),
self = this;
- Faye.ENV[callbackName] = function(data) {
- cleanUp();
- self.receive(data);
- self.trigger('up');
- };
+ endpoint.query.message = Faye.toJSON(messages);
+ endpoint.query.jsonp = callbackName;
- var timer = Faye.ENV.setTimeout(function() {
- cleanUp();
- retry();
- self.trigger('down');
- }, 1.5 * 1000 * timeout);
-
- var cleanUp = function() {
+ Faye.ENV[callbackName] = function(data) {
if (!Faye.ENV[callbackName]) return false;
Faye.ENV[callbackName] = undefined;
try { delete Faye.ENV[callbackName] } catch (e) {}
- Faye.ENV.clearTimeout(timer);
script.parentNode.removeChild(script);
- return true;
+ self.receive(envelopes, data);
};
- location.params.jsonp = callbackName;
script.type = 'text/javascript';
- script.src = location.toURL();
+ script.src = Faye.URI.stringify(endpoint);
head.appendChild(script);
}
}), {
_cbCount: 0,
@@ -2156,6 +2537,7 @@
}
});
Faye.Transport.register('callback-polling', Faye.Transport.JSONP);
-})();
+})();
+})(this);
\ No newline at end of file