reloader 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- data/Gemfile +4 -0
- data/LICENSE +20 -0
- data/README.rdoc +31 -0
- data/Rakefile +58 -0
- data/TODO.md +16 -0
- data/VERSION +1 -0
- data/app/controllers/reloader/reloader_controller.rb +14 -0
- data/bin/reloader +2 -0
- data/config/routes.rb +3 -0
- data/lib/config.ru +54 -0
- data/lib/rack/javascript_inject.rb +39 -0
- data/lib/rack/templates/javascript_inject.erb +2 -0
- data/lib/reloader.rb +1 -0
- data/lib/reloader/rails.rb +18 -0
- data/public/javascripts/faye-browser.js +1820 -0
- data/public/javascripts/jquery.js +154 -0
- data/public/javascripts/reloader.js +59 -0
- metadata +149 -0
data/Gemfile
ADDED
data/LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright (c) 2010 Jeroen van Dijk
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
9
|
+
the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.rdoc
ADDED
@@ -0,0 +1,31 @@
|
|
1
|
+
= reloader
|
2
|
+
|
3
|
+
Reloads all your assets with minimal code. Inspired by livereload: http://www.github.com/moccko/livereload . The main difference is and the reason why this project has been started is that it will plugin into your Rails app. So you don't have to think about activating or even installing a browser plugin. In development it will automatically reloads assets when they are changed when you add this gem to your gemfile e.g.
|
4
|
+
|
5
|
+
|
6
|
+
gem "reloader"
|
7
|
+
|
8
|
+
See the TODO file for stuff that is still open. Note that this project is currently complete for my personal usage, but I don't want to give guarantees for others yet.
|
9
|
+
|
10
|
+
|
11
|
+
### Usage
|
12
|
+
|
13
|
+
Start your rails app and in the root directory of your Rails app:
|
14
|
+
|
15
|
+
bundle exec reloader
|
16
|
+
|
17
|
+
Then start editing files and see how things are being reloaded!
|
18
|
+
|
19
|
+
== Note on Patches/Pull Requests
|
20
|
+
|
21
|
+
* Fork the project.
|
22
|
+
* Make your feature addition or bug fix.
|
23
|
+
* Add tests for it. This is important so I don't break it in a
|
24
|
+
future version unintentionally.
|
25
|
+
* Commit, do not mess with rakefile, version, or history.
|
26
|
+
(if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
|
27
|
+
* Send me a pull request. Bonus points for topic branches.
|
28
|
+
|
29
|
+
== Copyright
|
30
|
+
|
31
|
+
Copyright (c) 2010 Jeroen van Dijk. See LICENSE for details.
|
data/Rakefile
ADDED
@@ -0,0 +1,58 @@
|
|
1
|
+
require 'rubygems'
|
2
|
+
require 'rake'
|
3
|
+
|
4
|
+
begin
|
5
|
+
require 'jeweler'
|
6
|
+
Jeweler::Tasks.new do |gem|
|
7
|
+
gem.name = "reloader"
|
8
|
+
gem.summary = %Q{Reloads your pages and assets automatically in your Rails app}
|
9
|
+
gem.description = %Q{Reloads your pages and assets automatically in your Rails app. Heavily inspired by Livereload}
|
10
|
+
gem.email = "jeroen@jeevidee.nl"
|
11
|
+
gem.homepage = "http://github.com/jeroenvandijk/reloader"
|
12
|
+
gem.authors = ["Jeroen van Dijk"]
|
13
|
+
gem.add_dependency "rspactor", "0.7.0.beta.5"
|
14
|
+
gem.add_dependency "faye", "0.5.0"
|
15
|
+
gem.add_dependency "thin", "1.2.7"
|
16
|
+
gem.add_dependency "rev", "0.3.2"
|
17
|
+
gem.files = FileList["[A-Z]*", "{app,bin,config,lib,public}/**/*"]
|
18
|
+
|
19
|
+
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
|
20
|
+
end
|
21
|
+
Jeweler::GemcutterTasks.new
|
22
|
+
rescue LoadError
|
23
|
+
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
|
24
|
+
end
|
25
|
+
|
26
|
+
require 'rake/testtask'
|
27
|
+
Rake::TestTask.new(:test) do |test|
|
28
|
+
test.libs << 'lib' << 'test'
|
29
|
+
test.pattern = 'test/**/test_*.rb'
|
30
|
+
test.verbose = true
|
31
|
+
end
|
32
|
+
|
33
|
+
begin
|
34
|
+
require 'rcov/rcovtask'
|
35
|
+
Rcov::RcovTask.new do |test|
|
36
|
+
test.libs << 'test'
|
37
|
+
test.pattern = 'test/**/test_*.rb'
|
38
|
+
test.verbose = true
|
39
|
+
end
|
40
|
+
rescue LoadError
|
41
|
+
task :rcov do
|
42
|
+
abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
|
43
|
+
end
|
44
|
+
end
|
45
|
+
|
46
|
+
task :test => :check_dependencies
|
47
|
+
|
48
|
+
task :default => :test
|
49
|
+
|
50
|
+
require 'rake/rdoctask'
|
51
|
+
Rake::RDocTask.new do |rdoc|
|
52
|
+
version = File.exist?('VERSION') ? File.read('VERSION') : ""
|
53
|
+
|
54
|
+
rdoc.rdoc_dir = 'rdoc'
|
55
|
+
rdoc.title = "reloader #{version}"
|
56
|
+
rdoc.rdoc_files.include('README*')
|
57
|
+
rdoc.rdoc_files.include('lib/**/*.rb')
|
58
|
+
end
|
data/TODO.md
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
TODO
|
2
|
+
---
|
3
|
+
### (Perceived) Speed improvements
|
4
|
+
* See if Faye is the way the go (Could be slower than direct usage of websockets). Would also
|
5
|
+
remove the dependency on Thin.
|
6
|
+
* Show a spinner or something when something is loading. Especially for Sass files which is
|
7
|
+
currently a bit too slow to be completely satisfying.
|
8
|
+
|
9
|
+
## Usage
|
10
|
+
* Read configuration files so people can easily customize
|
11
|
+
|
12
|
+
### Code cleanup
|
13
|
+
* Make this reloader a real engine when Rails is ready (or the documentation on it)
|
14
|
+
- Remove the controller and route that serve the javascript
|
15
|
+
- If possible remove the Rack middleware that injects the javascript
|
16
|
+
* Remove the Rack reordering hack to fix the loading of Sass files => make sure Sass reloads stylesheets itself or watch stylesheets if thats better.
|
data/VERSION
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
0.1.0
|
@@ -0,0 +1,14 @@
|
|
1
|
+
class Reloader::ReloaderController < ActionController::Base
|
2
|
+
layout false
|
3
|
+
|
4
|
+
def show
|
5
|
+
respond_to do |format|
|
6
|
+
format.js {
|
7
|
+
render :file => File.expand_path("../../../../public/javascripts/#{params[:file]}.js", __FILE__)
|
8
|
+
}
|
9
|
+
end
|
10
|
+
end
|
11
|
+
|
12
|
+
end
|
13
|
+
|
14
|
+
|
data/bin/reloader
ADDED
data/config/routes.rb
ADDED
data/lib/config.ru
ADDED
@@ -0,0 +1,54 @@
|
|
1
|
+
require 'faye'
|
2
|
+
|
3
|
+
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
|
4
|
+
|
5
|
+
Thread.new { run faye_server }
|
6
|
+
|
7
|
+
require 'rspactor'
|
8
|
+
|
9
|
+
# HACK, EXTENSIONS shouldn't need to be redefined
|
10
|
+
RSpactor::Listener::EXTENSIONS = %w[html erb haml sass scss css js rb yml]
|
11
|
+
|
12
|
+
Thread.new do
|
13
|
+
|
14
|
+
client = Faye::Client.new('http://0.0.0.0:9292/faye')
|
15
|
+
|
16
|
+
listener = RSpactor::Listener.new
|
17
|
+
|
18
|
+
listener.watch { |files|
|
19
|
+
for file in files
|
20
|
+
case file
|
21
|
+
when %r{app/.+\.(erb|haml|sass)$}, %r{/app/helpers/.+\.rb$}, # application view code
|
22
|
+
%r{public/.+\.(js|html)$}, # static assets
|
23
|
+
%r{config/locales/.+\.yml$} # translation files
|
24
|
+
|
25
|
+
file_extension = file.split('.').last
|
26
|
+
|
27
|
+
mapping = {
|
28
|
+
"sass" => [ "css", "css" ],
|
29
|
+
"png" => [ "png", "image"],
|
30
|
+
"gif" => [ "gif", "image"],
|
31
|
+
"jpeg" => [ "jpeg", "image"],
|
32
|
+
"jpg" => [ "jpg", "image"] }
|
33
|
+
|
34
|
+
extension, type = mapping[file_extension] || [file_extension, file_extension]
|
35
|
+
|
36
|
+
filename = File.basename(file, ".*") + ".#{extension}"
|
37
|
+
|
38
|
+
client.publish('/files', {
|
39
|
+
'name' => [ filename ],
|
40
|
+
'timestamp' => Time.now.to_i,
|
41
|
+
'type' => type
|
42
|
+
})
|
43
|
+
|
44
|
+
puts "Reloading #{filename}"
|
45
|
+
|
46
|
+
else
|
47
|
+
puts "Unhandled change: #{file}"
|
48
|
+
end
|
49
|
+
end
|
50
|
+
}
|
51
|
+
puts "Listening to files"
|
52
|
+
listener.start
|
53
|
+
end
|
54
|
+
|
@@ -0,0 +1,39 @@
|
|
1
|
+
require 'rack'
|
2
|
+
require 'erb'
|
3
|
+
|
4
|
+
module Rack
|
5
|
+
|
6
|
+
class JavascriptInject
|
7
|
+
|
8
|
+
def initialize(app, options = {})
|
9
|
+
@app, @options = app
|
10
|
+
end
|
11
|
+
|
12
|
+
def call(env); dup._call(env); end
|
13
|
+
|
14
|
+
def _call(env)
|
15
|
+
@status, @headers, @response = @app.call(env)
|
16
|
+
|
17
|
+
if html?
|
18
|
+
response = Rack::Response.new([], @status, @headers)
|
19
|
+
@response.each { |fragment| response.write inject(fragment) }
|
20
|
+
response.finish
|
21
|
+
else
|
22
|
+
[@status, @headers, @response]
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
private
|
27
|
+
|
28
|
+
def html?
|
29
|
+
@headers['Content-Type'] =~ /html/
|
30
|
+
end
|
31
|
+
|
32
|
+
def inject(response)
|
33
|
+
@template ||= ::ERB.new ::File.read ::File.expand_path("../templates/javascript_inject.erb", __FILE__)
|
34
|
+
response.gsub(%r{</body>}, "</body>" + @template.result(binding))
|
35
|
+
end
|
36
|
+
|
37
|
+
end
|
38
|
+
|
39
|
+
end
|
data/lib/reloader.rb
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
require 'reloader/rails'
|
@@ -0,0 +1,18 @@
|
|
1
|
+
require 'rack/javascript_inject'
|
2
|
+
|
3
|
+
module Reloader
|
4
|
+
class Engine < ::Rails::Engine
|
5
|
+
|
6
|
+
if ::Rails.env.development?
|
7
|
+
|
8
|
+
initializer "reloader.sass_rack_reorder" do
|
9
|
+
middleware = Rails.application.config.middleware
|
10
|
+
middleware.insert_before(::ActionDispatch::Static,
|
11
|
+
::Sass::Plugin::Rack)
|
12
|
+
end
|
13
|
+
|
14
|
+
config.app_middleware.use Rack::JavascriptInject
|
15
|
+
end
|
16
|
+
|
17
|
+
end
|
18
|
+
end
|
@@ -0,0 +1,1820 @@
|
|
1
|
+
if (!this.Faye) Faye = {};
|
2
|
+
|
3
|
+
Faye.extend = function(dest, source, overwrite) {
|
4
|
+
if (!source) return dest;
|
5
|
+
for (var key in source) {
|
6
|
+
if (!source.hasOwnProperty(key)) continue;
|
7
|
+
if (dest.hasOwnProperty(key) && overwrite === false) continue;
|
8
|
+
if (dest[key] !== source[key])
|
9
|
+
dest[key] = source[key];
|
10
|
+
}
|
11
|
+
return dest;
|
12
|
+
};
|
13
|
+
|
14
|
+
Faye.extend(Faye, {
|
15
|
+
VERSION: '0.5.0',
|
16
|
+
|
17
|
+
BAYEUX_VERSION: '1.0',
|
18
|
+
ID_LENGTH: 128,
|
19
|
+
JSONP_CALLBACK: 'jsonpcallback',
|
20
|
+
CONNECTION_TYPES: ['long-polling', 'callback-polling', 'websocket'],
|
21
|
+
|
22
|
+
MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'],
|
23
|
+
|
24
|
+
ENV: (function() { return this })(),
|
25
|
+
|
26
|
+
random: function(bitlength) {
|
27
|
+
bitlength = bitlength || this.ID_LENGTH;
|
28
|
+
if (bitlength > 32) {
|
29
|
+
var parts = Math.ceil(bitlength / 32),
|
30
|
+
string = '';
|
31
|
+
while (parts--) string += this.random(32);
|
32
|
+
return string;
|
33
|
+
}
|
34
|
+
var field = Math.pow(2, bitlength);
|
35
|
+
return Math.floor(Math.random() * field).toString(36);
|
36
|
+
},
|
37
|
+
|
38
|
+
commonElement: function(lista, listb) {
|
39
|
+
for (var i = 0, n = lista.length; i < n; i++) {
|
40
|
+
if (this.indexOf(listb, lista[i]) !== -1)
|
41
|
+
return lista[i];
|
42
|
+
}
|
43
|
+
return null;
|
44
|
+
},
|
45
|
+
|
46
|
+
indexOf: function(list, needle) {
|
47
|
+
for (var i = 0, n = list.length; i < n; i++) {
|
48
|
+
if (list[i] === needle) return i;
|
49
|
+
}
|
50
|
+
return -1;
|
51
|
+
},
|
52
|
+
|
53
|
+
each: function(object, callback, scope) {
|
54
|
+
if (object instanceof Array) {
|
55
|
+
for (var i = 0, n = object.length; i < n; i++) {
|
56
|
+
if (object[i] !== undefined)
|
57
|
+
callback.call(scope || null, object[i], i);
|
58
|
+
}
|
59
|
+
} else {
|
60
|
+
for (var key in object) {
|
61
|
+
if (object.hasOwnProperty(key))
|
62
|
+
callback.call(scope || null, key, object[key]);
|
63
|
+
}
|
64
|
+
}
|
65
|
+
},
|
66
|
+
|
67
|
+
map: function(object, callback, scope) {
|
68
|
+
var result = [];
|
69
|
+
this.each(object, function() {
|
70
|
+
result.push(callback.apply(scope || null, arguments));
|
71
|
+
});
|
72
|
+
return result;
|
73
|
+
},
|
74
|
+
|
75
|
+
filter: function(array, callback, scope) {
|
76
|
+
var result = [];
|
77
|
+
this.each(array, function() {
|
78
|
+
if (callback.apply(scope, arguments))
|
79
|
+
result.push(arguments[0]);
|
80
|
+
});
|
81
|
+
return result;
|
82
|
+
},
|
83
|
+
|
84
|
+
size: function(object) {
|
85
|
+
var size = 0;
|
86
|
+
this.each(object, function() { size += 1 });
|
87
|
+
return size;
|
88
|
+
},
|
89
|
+
|
90
|
+
enumEqual: function(actual, expected) {
|
91
|
+
if (expected instanceof Array) {
|
92
|
+
if (!(actual instanceof Array)) return false;
|
93
|
+
var i = actual.length;
|
94
|
+
if (i !== expected.length) return false;
|
95
|
+
while (i--) {
|
96
|
+
if (actual[i] !== expected[i]) return false;
|
97
|
+
}
|
98
|
+
return true;
|
99
|
+
} else {
|
100
|
+
if (!(actual instanceof Object)) return false;
|
101
|
+
if (this.size(expected) !== this.size(actual)) return false;
|
102
|
+
var result = true;
|
103
|
+
this.each(actual, function(key, value) {
|
104
|
+
result = result && (expected[key] === value);
|
105
|
+
});
|
106
|
+
return result;
|
107
|
+
}
|
108
|
+
},
|
109
|
+
|
110
|
+
// http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/
|
111
|
+
toJSON: function(object) {
|
112
|
+
if (this.stringify)
|
113
|
+
return this.stringify(object, function(key, value) {
|
114
|
+
return (this[key] instanceof Array)
|
115
|
+
? this[key]
|
116
|
+
: value;
|
117
|
+
});
|
118
|
+
|
119
|
+
return JSON.stringify(object);
|
120
|
+
},
|
121
|
+
|
122
|
+
timestamp: function() {
|
123
|
+
var date = new Date(),
|
124
|
+
year = date.getFullYear(),
|
125
|
+
month = date.getMonth() + 1,
|
126
|
+
day = date.getDate(),
|
127
|
+
hour = date.getHours(),
|
128
|
+
minute = date.getMinutes(),
|
129
|
+
second = date.getSeconds();
|
130
|
+
|
131
|
+
var pad = function(n) {
|
132
|
+
return n < 10 ? '0' + n : String(n);
|
133
|
+
};
|
134
|
+
|
135
|
+
return pad(year) + '-' + pad(month) + '-' + pad(day) + ' ' +
|
136
|
+
pad(hour) + ':' + pad(minute) + ':' + pad(second);
|
137
|
+
}
|
138
|
+
});
|
139
|
+
|
140
|
+
|
141
|
+
Faye.Class = function(parent, methods) {
|
142
|
+
if (typeof parent !== 'function') {
|
143
|
+
methods = parent;
|
144
|
+
parent = Object;
|
145
|
+
}
|
146
|
+
|
147
|
+
var klass = function() {
|
148
|
+
if (!this.initialize) return this;
|
149
|
+
return this.initialize.apply(this, arguments) || this;
|
150
|
+
};
|
151
|
+
|
152
|
+
var bridge = function() {};
|
153
|
+
bridge.prototype = parent.prototype;
|
154
|
+
|
155
|
+
klass.prototype = new bridge();
|
156
|
+
Faye.extend(klass.prototype, methods);
|
157
|
+
|
158
|
+
return klass;
|
159
|
+
};
|
160
|
+
|
161
|
+
|
162
|
+
Faye.Namespace = Faye.Class({
|
163
|
+
initialize: function() {
|
164
|
+
this._used = {};
|
165
|
+
},
|
166
|
+
|
167
|
+
generate: function() {
|
168
|
+
var name = Faye.random();
|
169
|
+
while (this._used.hasOwnProperty(name))
|
170
|
+
name = Faye.random();
|
171
|
+
return this._used[name] = name;
|
172
|
+
}
|
173
|
+
});
|
174
|
+
|
175
|
+
|
176
|
+
Faye.Deferrable = {
|
177
|
+
callback: function(callback, scope) {
|
178
|
+
if (!callback) return;
|
179
|
+
|
180
|
+
if (this._deferredStatus === 'succeeded')
|
181
|
+
return callback.apply(scope, this._deferredArgs);
|
182
|
+
|
183
|
+
this._callbacks = this._callbacks || [];
|
184
|
+
this._callbacks.push([callback, scope]);
|
185
|
+
},
|
186
|
+
|
187
|
+
setDeferredStatus: function() {
|
188
|
+
var args = Array.prototype.slice.call(arguments),
|
189
|
+
status = args.shift();
|
190
|
+
|
191
|
+
this._deferredStatus = status;
|
192
|
+
this._deferredArgs = args;
|
193
|
+
|
194
|
+
if (status !== 'succeeded') return;
|
195
|
+
if (!this._callbacks) return;
|
196
|
+
|
197
|
+
Faye.each(this._callbacks, function(callback) {
|
198
|
+
callback[0].apply(callback[1], this._deferredArgs);
|
199
|
+
}, this);
|
200
|
+
|
201
|
+
this._callbacks = [];
|
202
|
+
}
|
203
|
+
};
|
204
|
+
|
205
|
+
|
206
|
+
Faye.Publisher = {
|
207
|
+
countSubscribers: function(eventType) {
|
208
|
+
if (!this._subscribers || !this._subscribers[eventType]) return 0;
|
209
|
+
return this._subscribers[eventType].length;
|
210
|
+
},
|
211
|
+
|
212
|
+
addSubscriber: function(eventType, listener, context) {
|
213
|
+
this._subscribers = this._subscribers || {};
|
214
|
+
var list = this._subscribers[eventType] = this._subscribers[eventType] || [];
|
215
|
+
list.push([listener, context]);
|
216
|
+
},
|
217
|
+
|
218
|
+
removeSubscriber: function(eventType, listener, context) {
|
219
|
+
if (!this._subscribers || !this._subscribers[eventType]) return;
|
220
|
+
|
221
|
+
var list = this._subscribers[eventType],
|
222
|
+
i = list.length;
|
223
|
+
|
224
|
+
while (i--) {
|
225
|
+
if (listener && list[i][0] !== listener) continue;
|
226
|
+
if (context && list[i][1] !== context) continue;
|
227
|
+
list.splice(i,1);
|
228
|
+
}
|
229
|
+
},
|
230
|
+
|
231
|
+
publishEvent: function() {
|
232
|
+
var args = Array.prototype.slice.call(arguments),
|
233
|
+
eventType = args.shift();
|
234
|
+
|
235
|
+
if (!this._subscribers || !this._subscribers[eventType]) return;
|
236
|
+
|
237
|
+
Faye.each(this._subscribers[eventType], function(listener) {
|
238
|
+
listener[0].apply(listener[1], args);
|
239
|
+
});
|
240
|
+
}
|
241
|
+
};
|
242
|
+
|
243
|
+
|
244
|
+
Faye.Timeouts = {
|
245
|
+
addTimeout: function(name, delay, callback, scope) {
|
246
|
+
this._timeouts = this._timeouts || {};
|
247
|
+
if (this._timeouts.hasOwnProperty(name)) return;
|
248
|
+
var self = this;
|
249
|
+
this._timeouts[name] = setTimeout(function() {
|
250
|
+
delete self._timeouts[name];
|
251
|
+
callback.call(scope);
|
252
|
+
}, 1000 * delay);
|
253
|
+
},
|
254
|
+
|
255
|
+
removeTimeout: function(name) {
|
256
|
+
this._timeouts = this._timeouts || {};
|
257
|
+
var timeout = this._timeouts[name];
|
258
|
+
if (!timeout) return;
|
259
|
+
clearTimeout(timeout);
|
260
|
+
delete this._timeouts[name];
|
261
|
+
}
|
262
|
+
};
|
263
|
+
|
264
|
+
|
265
|
+
Faye.Logging = {
|
266
|
+
LOG_LEVELS: {
|
267
|
+
error: 3,
|
268
|
+
warn: 2,
|
269
|
+
info: 1,
|
270
|
+
debug: 0
|
271
|
+
},
|
272
|
+
|
273
|
+
logLevel: 'error',
|
274
|
+
|
275
|
+
log: function(messageArgs, level) {
|
276
|
+
if (!Faye.logger) return;
|
277
|
+
|
278
|
+
var levels = Faye.Logging.LOG_LEVELS;
|
279
|
+
if (levels[Faye.Logging.logLevel] > levels[level]) return;
|
280
|
+
|
281
|
+
var messageArgs = Array.prototype.slice.apply(messageArgs),
|
282
|
+
banner = ' [' + level.toUpperCase() + '] [Faye',
|
283
|
+
klass = null,
|
284
|
+
|
285
|
+
message = messageArgs.shift().replace(/\?/g, function() {
|
286
|
+
try {
|
287
|
+
return Faye.toJSON(messageArgs.shift());
|
288
|
+
} catch (e) {
|
289
|
+
return '[Object]';
|
290
|
+
}
|
291
|
+
});
|
292
|
+
|
293
|
+
for (var key in Faye) {
|
294
|
+
if (klass) continue;
|
295
|
+
if (typeof Faye[key] !== 'function') continue;
|
296
|
+
if (this instanceof Faye[key]) klass = key;
|
297
|
+
}
|
298
|
+
if (klass) banner += '.' + klass;
|
299
|
+
banner += '] ';
|
300
|
+
|
301
|
+
Faye.logger(Faye.timestamp() + banner + message);
|
302
|
+
}
|
303
|
+
};
|
304
|
+
|
305
|
+
Faye.each(Faye.Logging.LOG_LEVELS, function(level, value) {
|
306
|
+
Faye.Logging[level] = function() {
|
307
|
+
this.log(arguments, level);
|
308
|
+
};
|
309
|
+
});
|
310
|
+
|
311
|
+
|
312
|
+
Faye.Grammar = {
|
313
|
+
|
314
|
+
LOWALPHA: /^[a-z]$/,
|
315
|
+
|
316
|
+
UPALPHA: /^[A-Z]$/,
|
317
|
+
|
318
|
+
ALPHA: /^([a-z]|[A-Z])$/,
|
319
|
+
|
320
|
+
DIGIT: /^[0-9]$/,
|
321
|
+
|
322
|
+
ALPHANUM: /^(([a-z]|[A-Z])|[0-9])$/,
|
323
|
+
|
324
|
+
MARK: /^(\-|\_|\!|\~|\(|\)|\$|\@)$/,
|
325
|
+
|
326
|
+
STRING: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,
|
327
|
+
|
328
|
+
TOKEN: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,
|
329
|
+
|
330
|
+
INTEGER: /^([0-9])+$/,
|
331
|
+
|
332
|
+
CHANNEL_SEGMENT: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,
|
333
|
+
|
334
|
+
CHANNEL_SEGMENTS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
|
335
|
+
|
336
|
+
CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
|
337
|
+
|
338
|
+
WILD_CARD: /^\*{1,2}$/,
|
339
|
+
|
340
|
+
CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,
|
341
|
+
|
342
|
+
VERSION_ELEMENT: /^(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*$/,
|
343
|
+
|
344
|
+
VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/,
|
345
|
+
|
346
|
+
CLIENT_ID: /^((([a-z]|[A-Z])|[0-9]))+$/,
|
347
|
+
|
348
|
+
ID: /^((([a-z]|[A-Z])|[0-9]))+$/,
|
349
|
+
|
350
|
+
ERROR_MESSAGE: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,
|
351
|
+
|
352
|
+
ERROR_ARGS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*$/,
|
353
|
+
|
354
|
+
ERROR_CODE: /^[0-9][0-9][0-9]$/,
|
355
|
+
|
356
|
+
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])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/
|
357
|
+
|
358
|
+
};
|
359
|
+
|
360
|
+
|
361
|
+
Faye.Extensible = {
|
362
|
+
addExtension: function(extension) {
|
363
|
+
this._extensions = this._extensions || [];
|
364
|
+
this._extensions.push(extension);
|
365
|
+
if (extension.added) extension.added();
|
366
|
+
},
|
367
|
+
|
368
|
+
removeExtension: function(extension) {
|
369
|
+
if (!this._extensions) return;
|
370
|
+
var i = this._extensions.length;
|
371
|
+
while (i--) {
|
372
|
+
if (this._extensions[i] !== extension) continue;
|
373
|
+
this._extensions.splice(i,1);
|
374
|
+
if (extension.removed) extension.removed();
|
375
|
+
}
|
376
|
+
},
|
377
|
+
|
378
|
+
pipeThroughExtensions: function(stage, message, callback, scope) {
|
379
|
+
if (!this._extensions) return callback.call(scope, message);
|
380
|
+
var extensions = this._extensions.slice();
|
381
|
+
|
382
|
+
var pipe = function(message) {
|
383
|
+
if (!message) return callback.call(scope, message);
|
384
|
+
|
385
|
+
var extension = extensions.shift();
|
386
|
+
if (!extension) return callback.call(scope, message);
|
387
|
+
|
388
|
+
if (extension[stage]) extension[stage](message, pipe);
|
389
|
+
else pipe(message);
|
390
|
+
};
|
391
|
+
pipe(message);
|
392
|
+
}
|
393
|
+
};
|
394
|
+
|
395
|
+
|
396
|
+
Faye.Channel = Faye.Class({
|
397
|
+
initialize: function(name) {
|
398
|
+
this.id = this.name = name;
|
399
|
+
},
|
400
|
+
|
401
|
+
push: function(message) {
|
402
|
+
this.publishEvent('message', message);
|
403
|
+
}
|
404
|
+
});
|
405
|
+
|
406
|
+
Faye.extend(Faye.Channel.prototype, Faye.Publisher);
|
407
|
+
|
408
|
+
Faye.extend(Faye.Channel, {
|
409
|
+
HANDSHAKE: '/meta/handshake',
|
410
|
+
CONNECT: '/meta/connect',
|
411
|
+
SUBSCRIBE: '/meta/subscribe',
|
412
|
+
UNSUBSCRIBE: '/meta/unsubscribe',
|
413
|
+
DISCONNECT: '/meta/disconnect',
|
414
|
+
|
415
|
+
META: 'meta',
|
416
|
+
SERVICE: 'service',
|
417
|
+
|
418
|
+
isValid: function(name) {
|
419
|
+
return Faye.Grammar.CHANNEL_NAME.test(name) ||
|
420
|
+
Faye.Grammar.CHANNEL_PATTERN.test(name);
|
421
|
+
},
|
422
|
+
|
423
|
+
parse: function(name) {
|
424
|
+
if (!this.isValid(name)) return null;
|
425
|
+
return name.split('/').slice(1);
|
426
|
+
},
|
427
|
+
|
428
|
+
isMeta: function(name) {
|
429
|
+
var segments = this.parse(name);
|
430
|
+
return segments ? (segments[0] === this.META) : null;
|
431
|
+
},
|
432
|
+
|
433
|
+
isService: function(name) {
|
434
|
+
var segments = this.parse(name);
|
435
|
+
return segments ? (segments[0] === this.SERVICE) : null;
|
436
|
+
},
|
437
|
+
|
438
|
+
isSubscribable: function(name) {
|
439
|
+
if (!this.isValid(name)) return null;
|
440
|
+
return !this.isMeta(name) && !this.isService(name);
|
441
|
+
},
|
442
|
+
|
443
|
+
Tree: Faye.Class({
|
444
|
+
initialize: function(value) {
|
445
|
+
this._value = value;
|
446
|
+
this._children = {};
|
447
|
+
},
|
448
|
+
|
449
|
+
eachChild: function(block, context) {
|
450
|
+
Faye.each(this._children, function(key, subtree) {
|
451
|
+
block.call(context, key, subtree);
|
452
|
+
});
|
453
|
+
},
|
454
|
+
|
455
|
+
each: function(prefix, block, context) {
|
456
|
+
this.eachChild(function(path, subtree) {
|
457
|
+
path = prefix.concat(path);
|
458
|
+
subtree.each(path, block, context);
|
459
|
+
});
|
460
|
+
if (this._value !== undefined) block.call(context, prefix, this._value);
|
461
|
+
},
|
462
|
+
|
463
|
+
getKeys: function() {
|
464
|
+
return this.map(function(key, value) { return '/' + key.join('/') });
|
465
|
+
},
|
466
|
+
|
467
|
+
map: function(block, context) {
|
468
|
+
var result = [];
|
469
|
+
this.each([], function(path, value) {
|
470
|
+
result.push(block.call(context, path, value));
|
471
|
+
});
|
472
|
+
return result;
|
473
|
+
},
|
474
|
+
|
475
|
+
get: function(name) {
|
476
|
+
var tree = this.traverse(name);
|
477
|
+
return tree ? tree._value : null;
|
478
|
+
},
|
479
|
+
|
480
|
+
set: function(name, value) {
|
481
|
+
var subtree = this.traverse(name, true);
|
482
|
+
if (subtree) subtree._value = value;
|
483
|
+
},
|
484
|
+
|
485
|
+
traverse: function(path, createIfAbsent) {
|
486
|
+
if (typeof path === 'string') path = Faye.Channel.parse(path);
|
487
|
+
|
488
|
+
if (path === null) return null;
|
489
|
+
if (path.length === 0) return this;
|
490
|
+
|
491
|
+
var subtree = this._children[path[0]];
|
492
|
+
if (!subtree && !createIfAbsent) return null;
|
493
|
+
if (!subtree) subtree = this._children[path[0]] = new Faye.Channel.Tree();
|
494
|
+
|
495
|
+
return subtree.traverse(path.slice(1), createIfAbsent);
|
496
|
+
},
|
497
|
+
|
498
|
+
findOrCreate: function(channel) {
|
499
|
+
var existing = this.get(channel);
|
500
|
+
if (existing) return existing;
|
501
|
+
existing = new Faye.Channel(channel);
|
502
|
+
this.set(channel, existing);
|
503
|
+
return existing;
|
504
|
+
},
|
505
|
+
|
506
|
+
glob: function(path) {
|
507
|
+
if (typeof path === 'string') path = Faye.Channel.parse(path);
|
508
|
+
|
509
|
+
if (path === null) return [];
|
510
|
+
if (path.length === 0) return (this._value === undefined) ? [] : [this._value];
|
511
|
+
|
512
|
+
var list = [];
|
513
|
+
|
514
|
+
if (Faye.enumEqual(path, ['*'])) {
|
515
|
+
Faye.each(this._children, function(key, subtree) {
|
516
|
+
if (subtree._value !== undefined) list.push(subtree._value);
|
517
|
+
});
|
518
|
+
return list;
|
519
|
+
}
|
520
|
+
|
521
|
+
if (Faye.enumEqual(path, ['**'])) {
|
522
|
+
list = this.map(function(key, value) { return value });
|
523
|
+
if (this._value !== undefined) list.pop();
|
524
|
+
return list;
|
525
|
+
}
|
526
|
+
|
527
|
+
Faye.each(this._children, function(key, subtree) {
|
528
|
+
if (key !== path[0] && key !== '*') return;
|
529
|
+
var sublist = subtree.glob(path.slice(1));
|
530
|
+
Faye.each(sublist, function(channel) { list.push(channel) });
|
531
|
+
});
|
532
|
+
|
533
|
+
if (this._children['**']) list.push(this._children['**']._value);
|
534
|
+
return list;
|
535
|
+
},
|
536
|
+
|
537
|
+
subscribe: function(names, callback, scope) {
|
538
|
+
if (!callback) return;
|
539
|
+
Faye.each(names, function(name) {
|
540
|
+
var channel = this.findOrCreate(name);
|
541
|
+
channel.addSubscriber('message', callback, scope);
|
542
|
+
}, this);
|
543
|
+
},
|
544
|
+
|
545
|
+
unsubscribe: function(name, callback, scope) {
|
546
|
+
var channel = this.get(name);
|
547
|
+
if (!channel) return false;
|
548
|
+
channel.removeSubscriber('message', callback, scope);
|
549
|
+
return channel.countSubscribers('message') === 0;
|
550
|
+
},
|
551
|
+
|
552
|
+
distributeMessage: function(message) {
|
553
|
+
var channels = this.glob(message.channel);
|
554
|
+
Faye.each(channels, function(channel) {
|
555
|
+
channel.publishEvent('message', message.data);
|
556
|
+
});
|
557
|
+
}
|
558
|
+
})
|
559
|
+
});
|
560
|
+
|
561
|
+
|
562
|
+
Faye.Subscription = Faye.Class({
|
563
|
+
initialize: function(client, channels, callback, scope) {
|
564
|
+
this._client = client;
|
565
|
+
this._channels = channels;
|
566
|
+
this._callback = callback;
|
567
|
+
this._scope = scope;
|
568
|
+
this._cancelled = false;
|
569
|
+
},
|
570
|
+
|
571
|
+
cancel: function() {
|
572
|
+
if (this._cancelled) return;
|
573
|
+
this._client.unsubscribe(this._channels, this._callback, this._scope);
|
574
|
+
this._cancelled = true;
|
575
|
+
},
|
576
|
+
|
577
|
+
unsubscribe: function() {
|
578
|
+
this.cancel();
|
579
|
+
}
|
580
|
+
});
|
581
|
+
|
582
|
+
|
583
|
+
Faye.Client = Faye.Class({
|
584
|
+
UNCONNECTED: 1,
|
585
|
+
CONNECTING: 2,
|
586
|
+
CONNECTED: 3,
|
587
|
+
DISCONNECTED: 4,
|
588
|
+
|
589
|
+
HANDSHAKE: 'handshake',
|
590
|
+
RETRY: 'retry',
|
591
|
+
NONE: 'none',
|
592
|
+
|
593
|
+
CONNECTION_TIMEOUT: 60.0,
|
594
|
+
|
595
|
+
DEFAULT_ENDPOINT: '/bayeux',
|
596
|
+
MAX_DELAY: 0.1,
|
597
|
+
INTERVAL: 0.0,
|
598
|
+
|
599
|
+
initialize: function(endpoint, options) {
|
600
|
+
this.info('New client created for ?', endpoint);
|
601
|
+
|
602
|
+
this._endpoint = endpoint || this.DEFAULT_ENDPOINT;
|
603
|
+
this._options = options || {};
|
604
|
+
|
605
|
+
this._transport = Faye.Transport.get(this, Faye.MANDATORY_CONNECTION_TYPES);
|
606
|
+
this._state = this.UNCONNECTED;
|
607
|
+
this._outbox = [];
|
608
|
+
this._channels = new Faye.Channel.Tree();
|
609
|
+
|
610
|
+
this._namespace = new Faye.Namespace();
|
611
|
+
this._responseCallbacks = {};
|
612
|
+
|
613
|
+
this._advice = {
|
614
|
+
reconnect: this.RETRY,
|
615
|
+
interval: 1000 * (this._options.interval || this.INTERVAL),
|
616
|
+
timeout: 1000 * (this._options.timeout || this.CONNECTION_TIMEOUT)
|
617
|
+
};
|
618
|
+
|
619
|
+
if (Faye.Event) Faye.Event.on(Faye.ENV, 'beforeunload',
|
620
|
+
this.disconnect, this);
|
621
|
+
},
|
622
|
+
|
623
|
+
// Request
|
624
|
+
// MUST include: * channel
|
625
|
+
// * version
|
626
|
+
// * supportedConnectionTypes
|
627
|
+
// MAY include: * minimumVersion
|
628
|
+
// * ext
|
629
|
+
// * id
|
630
|
+
//
|
631
|
+
// Success Response Failed Response
|
632
|
+
// MUST include: * channel MUST include: * channel
|
633
|
+
// * version * successful
|
634
|
+
// * supportedConnectionTypes * error
|
635
|
+
// * clientId MAY include: * supportedConnectionTypes
|
636
|
+
// * successful * advice
|
637
|
+
// MAY include: * minimumVersion * version
|
638
|
+
// * advice * minimumVersion
|
639
|
+
// * ext * ext
|
640
|
+
// * id * id
|
641
|
+
// * authSuccessful
|
642
|
+
handshake: function(callback, scope) {
|
643
|
+
if (this._advice.reconnect === this.NONE) return;
|
644
|
+
if (this._state !== this.UNCONNECTED) return;
|
645
|
+
|
646
|
+
this._state = this.CONNECTING;
|
647
|
+
var self = this;
|
648
|
+
|
649
|
+
this.info('Initiating handshake with ?', this._endpoint);
|
650
|
+
|
651
|
+
this._send({
|
652
|
+
channel: Faye.Channel.HANDSHAKE,
|
653
|
+
version: Faye.BAYEUX_VERSION,
|
654
|
+
supportedConnectionTypes: [this._transport.connectionType]
|
655
|
+
|
656
|
+
}, function(response) {
|
657
|
+
|
658
|
+
if (response.successful) {
|
659
|
+
this._state = this.CONNECTED;
|
660
|
+
this._clientId = response.clientId;
|
661
|
+
this._transport = Faye.Transport.get(this, response.supportedConnectionTypes);
|
662
|
+
|
663
|
+
this.info('Handshake successful: ?', this._clientId);
|
664
|
+
|
665
|
+
this.subscribe(this._channels.getKeys());
|
666
|
+
if (callback) callback.call(scope);
|
667
|
+
|
668
|
+
} else {
|
669
|
+
this.info('Handshake unsuccessful');
|
670
|
+
setTimeout(function() { self.handshake(callback, scope) }, this._advice.interval);
|
671
|
+
this._state = this.UNCONNECTED;
|
672
|
+
}
|
673
|
+
}, this);
|
674
|
+
},
|
675
|
+
|
676
|
+
// Request Response
|
677
|
+
// MUST include: * channel MUST include: * channel
|
678
|
+
// * clientId * successful
|
679
|
+
// * connectionType * clientId
|
680
|
+
// MAY include: * ext MAY include: * error
|
681
|
+
// * id * advice
|
682
|
+
// * ext
|
683
|
+
// * id
|
684
|
+
// * timestamp
|
685
|
+
connect: function(callback, scope) {
|
686
|
+
if (this._advice.reconnect === this.NONE) return;
|
687
|
+
if (this._state === this.DISCONNECTED) return;
|
688
|
+
|
689
|
+
if (this._state === this.UNCONNECTED)
|
690
|
+
return this.handshake(function() { this.connect(callback, scope) }, this);
|
691
|
+
|
692
|
+
this.callback(callback, scope);
|
693
|
+
if (this._state !== this.CONNECTED) return;
|
694
|
+
|
695
|
+
this.info('Calling deferred actions for ?', this._clientId);
|
696
|
+
this.setDeferredStatus('succeeded');
|
697
|
+
this.setDeferredStatus('deferred');
|
698
|
+
|
699
|
+
if (this._connectRequest) return;
|
700
|
+
this._connectRequest = true;
|
701
|
+
|
702
|
+
this.info('Initiating connection for ?', this._clientId);
|
703
|
+
|
704
|
+
this._send({
|
705
|
+
channel: Faye.Channel.CONNECT,
|
706
|
+
clientId: this._clientId,
|
707
|
+
connectionType: this._transport.connectionType
|
708
|
+
|
709
|
+
}, this._cycleConnection, this);
|
710
|
+
},
|
711
|
+
|
712
|
+
// Request Response
|
713
|
+
// MUST include: * channel MUST include: * channel
|
714
|
+
// * clientId * successful
|
715
|
+
// MAY include: * ext * clientId
|
716
|
+
// * id MAY include: * error
|
717
|
+
// * ext
|
718
|
+
// * id
|
719
|
+
disconnect: function() {
|
720
|
+
if (this._state !== this.CONNECTED) return;
|
721
|
+
this._state = this.DISCONNECTED;
|
722
|
+
|
723
|
+
this.info('Disconnecting ?', this._clientId);
|
724
|
+
|
725
|
+
this._send({
|
726
|
+
channel: Faye.Channel.DISCONNECT,
|
727
|
+
clientId: this._clientId
|
728
|
+
});
|
729
|
+
|
730
|
+
this.info('Clearing channel listeners for ?', this._clientId);
|
731
|
+
this._channels = new Faye.Channel.Tree();
|
732
|
+
},
|
733
|
+
|
734
|
+
// Request Response
|
735
|
+
// MUST include: * channel MUST include: * channel
|
736
|
+
// * clientId * successful
|
737
|
+
// * subscription * clientId
|
738
|
+
// MAY include: * ext * subscription
|
739
|
+
// * id MAY include: * error
|
740
|
+
// * advice
|
741
|
+
// * ext
|
742
|
+
// * id
|
743
|
+
// * timestamp
|
744
|
+
subscribe: function(channels, callback, scope) {
|
745
|
+
if (channels instanceof Array)
|
746
|
+
return Faye.each(channels, function(channel) {
|
747
|
+
this.subscribe(channel, callback, scope);
|
748
|
+
}, this);
|
749
|
+
|
750
|
+
this._validateChannel(channels);
|
751
|
+
|
752
|
+
this.connect(function() {
|
753
|
+
this.info('Client ? attempting to subscribe to ?', this._clientId, channels);
|
754
|
+
|
755
|
+
this._send({
|
756
|
+
channel: Faye.Channel.SUBSCRIBE,
|
757
|
+
clientId: this._clientId,
|
758
|
+
subscription: channels
|
759
|
+
|
760
|
+
}, function(response) {
|
761
|
+
if (!response.successful) return;
|
762
|
+
|
763
|
+
var channels = [].concat(response.subscription);
|
764
|
+
this.info('Subscription acknowledged for ? to ?', this._clientId, channels);
|
765
|
+
this._channels.subscribe(channels, callback, scope);
|
766
|
+
}, this);
|
767
|
+
|
768
|
+
}, this);
|
769
|
+
|
770
|
+
return new Faye.Subscription(this, channels, callback, scope);
|
771
|
+
},
|
772
|
+
|
773
|
+
// Request Response
|
774
|
+
// MUST include: * channel MUST include: * channel
|
775
|
+
// * clientId * successful
|
776
|
+
// * subscription * clientId
|
777
|
+
// MAY include: * ext * subscription
|
778
|
+
// * id MAY include: * error
|
779
|
+
// * advice
|
780
|
+
// * ext
|
781
|
+
// * id
|
782
|
+
// * timestamp
|
783
|
+
unsubscribe: function(channels, callback, scope) {
|
784
|
+
if (channels instanceof Array)
|
785
|
+
return Faye.each(channels, function(channel) {
|
786
|
+
this.unsubscribe(channel, callback, scope);
|
787
|
+
}, this);
|
788
|
+
|
789
|
+
this._validateChannel(channels);
|
790
|
+
|
791
|
+
var dead = this._channels.unsubscribe(channels, callback, scope);
|
792
|
+
if (!dead) return;
|
793
|
+
|
794
|
+
this.connect(function() {
|
795
|
+
this.info('Client ? attempting to unsubscribe from ?', this._clientId, channels);
|
796
|
+
|
797
|
+
this._send({
|
798
|
+
channel: Faye.Channel.UNSUBSCRIBE,
|
799
|
+
clientId: this._clientId,
|
800
|
+
subscription: channels
|
801
|
+
|
802
|
+
}, function(response) {
|
803
|
+
if (!response.successful) return;
|
804
|
+
|
805
|
+
var channels = [].concat(response.subscription);
|
806
|
+
this.info('Unsubscription acknowledged for ? from ?', this._clientId, channels);
|
807
|
+
}, this);
|
808
|
+
|
809
|
+
}, this);
|
810
|
+
},
|
811
|
+
|
812
|
+
// Request Response
|
813
|
+
// MUST include: * channel MUST include: * channel
|
814
|
+
// * data * successful
|
815
|
+
// MAY include: * clientId MAY include: * id
|
816
|
+
// * id * error
|
817
|
+
// * ext * ext
|
818
|
+
publish: function(channel, data) {
|
819
|
+
this._validateChannel(channel);
|
820
|
+
|
821
|
+
this.connect(function() {
|
822
|
+
this.info('Client ? queueing published message to ?: ?', this._clientId, channel, data);
|
823
|
+
|
824
|
+
this._send({
|
825
|
+
channel: channel,
|
826
|
+
data: data,
|
827
|
+
clientId: this._clientId
|
828
|
+
});
|
829
|
+
}, this);
|
830
|
+
},
|
831
|
+
|
832
|
+
receiveMessage: function(message) {
|
833
|
+
this.pipeThroughExtensions('incoming', message, function(message) {
|
834
|
+
if (!message) return;
|
835
|
+
|
836
|
+
if (message.advice) this._handleAdvice(message.advice);
|
837
|
+
|
838
|
+
var callback = this._responseCallbacks[message.id];
|
839
|
+
if (callback) {
|
840
|
+
delete this._responseCallbacks[message.id];
|
841
|
+
callback[0].call(callback[1], message);
|
842
|
+
}
|
843
|
+
|
844
|
+
this._deliverMessage(message);
|
845
|
+
}, this);
|
846
|
+
},
|
847
|
+
|
848
|
+
_handleAdvice: function(advice) {
|
849
|
+
Faye.extend(this._advice, advice);
|
850
|
+
|
851
|
+
if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {
|
852
|
+
this._state = this.UNCONNECTED;
|
853
|
+
this._clientId = null;
|
854
|
+
this._cycleConnection();
|
855
|
+
}
|
856
|
+
},
|
857
|
+
|
858
|
+
_deliverMessage: function(message) {
|
859
|
+
if (!message.channel || !message.data) return;
|
860
|
+
this.info('Client ? calling listeners for ? with ?', this._clientId, message.channel, message.data);
|
861
|
+
this._channels.distributeMessage(message);
|
862
|
+
},
|
863
|
+
|
864
|
+
_teardownConnection: function() {
|
865
|
+
if (!this._connectRequest) return;
|
866
|
+
this._connectRequest = null;
|
867
|
+
this.info('Closed connection for ?', this._clientId);
|
868
|
+
},
|
869
|
+
|
870
|
+
_cycleConnection: function() {
|
871
|
+
this._teardownConnection();
|
872
|
+
var self = this;
|
873
|
+
setTimeout(function() { self.connect() }, this._advice.interval);
|
874
|
+
},
|
875
|
+
|
876
|
+
_send: function(message, callback, scope) {
|
877
|
+
message.id = this._namespace.generate();
|
878
|
+
if (callback) this._responseCallbacks[message.id] = [callback, scope];
|
879
|
+
|
880
|
+
this.pipeThroughExtensions('outgoing', message, function(message) {
|
881
|
+
if (!message) return;
|
882
|
+
|
883
|
+
if (message.channel === Faye.Channel.HANDSHAKE)
|
884
|
+
return this._transport.send(message, this._advice.timeout / 1000);
|
885
|
+
|
886
|
+
this._outbox.push(message);
|
887
|
+
|
888
|
+
if (message.channel === Faye.Channel.CONNECT)
|
889
|
+
this._connectMessage = message;
|
890
|
+
|
891
|
+
this.addTimeout('publish', this.MAX_DELAY, this._flush, this);
|
892
|
+
}, this);
|
893
|
+
},
|
894
|
+
|
895
|
+
_flush: function() {
|
896
|
+
this.removeTimeout('publish');
|
897
|
+
|
898
|
+
if (this._outbox.length > 1 && this._connectMessage)
|
899
|
+
this._connectMessage.advice = {timeout: 0};
|
900
|
+
|
901
|
+
this._connectMessage = null;
|
902
|
+
|
903
|
+
this._transport.send(this._outbox, this._advice.timeout / 1000);
|
904
|
+
this._outbox = [];
|
905
|
+
},
|
906
|
+
|
907
|
+
_validateChannel: function(channel) {
|
908
|
+
if (!Faye.Channel.isValid(channel))
|
909
|
+
throw '"' + channel + '" is not a valid channel name';
|
910
|
+
if (!Faye.Channel.isSubscribable(channel))
|
911
|
+
throw 'Clients may not subscribe to channel "' + channel + '"';
|
912
|
+
}
|
913
|
+
});
|
914
|
+
|
915
|
+
Faye.extend(Faye.Client.prototype, Faye.Deferrable);
|
916
|
+
Faye.extend(Faye.Client.prototype, Faye.Timeouts);
|
917
|
+
Faye.extend(Faye.Client.prototype, Faye.Logging);
|
918
|
+
Faye.extend(Faye.Client.prototype, Faye.Extensible);
|
919
|
+
|
920
|
+
|
921
|
+
Faye.Transport = Faye.extend(Faye.Class({
|
922
|
+
initialize: function(client, endpoint) {
|
923
|
+
this.debug('Created new ? transport for ?', this.connectionType, endpoint);
|
924
|
+
this._client = client;
|
925
|
+
this._endpoint = endpoint;
|
926
|
+
},
|
927
|
+
|
928
|
+
send: function(messages, timeout) {
|
929
|
+
messages = [].concat(messages);
|
930
|
+
|
931
|
+
this.debug('Client ? sending message to ?: ?',
|
932
|
+
this._client._clientId, this._endpoint, messages);
|
933
|
+
|
934
|
+
return this.request(messages, timeout);
|
935
|
+
},
|
936
|
+
|
937
|
+
receive: function(responses) {
|
938
|
+
this.debug('Client ? received from ?: ?',
|
939
|
+
this._client._clientId, this._endpoint, responses);
|
940
|
+
|
941
|
+
Faye.each(responses, this._client.receiveMessage, this._client);
|
942
|
+
},
|
943
|
+
|
944
|
+
retry: function(message, timeout) {
|
945
|
+
var self = this;
|
946
|
+
return function() {
|
947
|
+
setTimeout(function() { self.request(message, 2 * timeout) }, 1000 * timeout);
|
948
|
+
};
|
949
|
+
}
|
950
|
+
|
951
|
+
}), {
|
952
|
+
get: function(client, connectionTypes) {
|
953
|
+
var endpoint = client._endpoint;
|
954
|
+
if (connectionTypes === undefined) connectionTypes = this.supportedConnectionTypes();
|
955
|
+
|
956
|
+
var candidateClass = null;
|
957
|
+
Faye.each(this._transports, function(pair) {
|
958
|
+
var connType = pair[0], klass = pair[1];
|
959
|
+
if (Faye.indexOf(connectionTypes, connType) < 0) return;
|
960
|
+
if (candidateClass) return;
|
961
|
+
if (klass.isUsable(endpoint)) candidateClass = klass;
|
962
|
+
});
|
963
|
+
|
964
|
+
if (!candidateClass) throw 'Could not find a usable connection type for ' + endpoint;
|
965
|
+
|
966
|
+
return new candidateClass(client, endpoint);
|
967
|
+
},
|
968
|
+
|
969
|
+
register: function(type, klass) {
|
970
|
+
this._transports.push([type, klass]);
|
971
|
+
klass.prototype.connectionType = type;
|
972
|
+
},
|
973
|
+
|
974
|
+
_transports: [],
|
975
|
+
|
976
|
+
supportedConnectionTypes: function() {
|
977
|
+
return Faye.map(this._transports, function(pair) { return pair[0] });
|
978
|
+
}
|
979
|
+
});
|
980
|
+
|
981
|
+
Faye.extend(Faye.Transport.prototype, Faye.Logging);
|
982
|
+
|
983
|
+
|
984
|
+
Faye.Event = {
|
985
|
+
_registry: [],
|
986
|
+
|
987
|
+
on: function(element, eventName, callback, scope) {
|
988
|
+
var wrapped = function() { callback.call(scope) };
|
989
|
+
|
990
|
+
if (element.addEventListener)
|
991
|
+
element.addEventListener(eventName, wrapped, false);
|
992
|
+
else
|
993
|
+
element.attachEvent('on' + eventName, wrapped);
|
994
|
+
|
995
|
+
this._registry.push({
|
996
|
+
_element: element,
|
997
|
+
_type: eventName,
|
998
|
+
_callback: callback,
|
999
|
+
_scope: scope,
|
1000
|
+
_handler: wrapped
|
1001
|
+
});
|
1002
|
+
},
|
1003
|
+
|
1004
|
+
detach: function(element, eventName, callback, scope) {
|
1005
|
+
var i = this._registry.length, register;
|
1006
|
+
while (i--) {
|
1007
|
+
register = this._registry[i];
|
1008
|
+
|
1009
|
+
if ((element && element !== register._element) ||
|
1010
|
+
(eventName && eventName !== register._type) ||
|
1011
|
+
(callback && callback !== register._callback) ||
|
1012
|
+
(scope && scope !== register._scope))
|
1013
|
+
continue;
|
1014
|
+
|
1015
|
+
if (register._element.removeEventListener)
|
1016
|
+
register._element.removeEventListener(register._type, register._handler, false);
|
1017
|
+
else
|
1018
|
+
register._element.detachEvent('on' + register._type, register._handler);
|
1019
|
+
|
1020
|
+
this._registry.splice(i,1);
|
1021
|
+
register = null;
|
1022
|
+
}
|
1023
|
+
}
|
1024
|
+
};
|
1025
|
+
|
1026
|
+
Faye.Event.on(Faye.ENV, 'unload', Faye.Event.detach, Faye.Event);
|
1027
|
+
|
1028
|
+
|
1029
|
+
Faye.URI = Faye.extend(Faye.Class({
|
1030
|
+
queryString: function() {
|
1031
|
+
var pairs = [], key;
|
1032
|
+
Faye.each(this.params, function(key, value) {
|
1033
|
+
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
|
1034
|
+
});
|
1035
|
+
return pairs.join('&');
|
1036
|
+
},
|
1037
|
+
|
1038
|
+
isLocal: function() {
|
1039
|
+
var host = Faye.URI.parse(Faye.ENV.location.href);
|
1040
|
+
|
1041
|
+
var external = (host.hostname !== this.hostname) ||
|
1042
|
+
(host.port !== this.port) ||
|
1043
|
+
(host.protocol !== this.protocol);
|
1044
|
+
|
1045
|
+
return !external;
|
1046
|
+
},
|
1047
|
+
|
1048
|
+
toURL: function() {
|
1049
|
+
var query = this.queryString();
|
1050
|
+
return this.protocol + this.hostname + ':' + this.port +
|
1051
|
+
this.pathname + (query ? '?' + query : '');
|
1052
|
+
}
|
1053
|
+
}), {
|
1054
|
+
parse: function(url, params) {
|
1055
|
+
if (typeof url !== 'string') return url;
|
1056
|
+
|
1057
|
+
var location = new this();
|
1058
|
+
|
1059
|
+
var consume = function(name, pattern) {
|
1060
|
+
url = url.replace(pattern, function(match) {
|
1061
|
+
if (match) location[name] = match;
|
1062
|
+
return '';
|
1063
|
+
});
|
1064
|
+
};
|
1065
|
+
consume('protocol', /^https?\:\/+/);
|
1066
|
+
consume('hostname', /^[^\/\:]+/);
|
1067
|
+
consume('port', /^:[0-9]+/);
|
1068
|
+
|
1069
|
+
Faye.extend(location, {
|
1070
|
+
protocol: 'http://',
|
1071
|
+
hostname: Faye.ENV.location.hostname,
|
1072
|
+
port: Faye.ENV.location.port
|
1073
|
+
}, false);
|
1074
|
+
|
1075
|
+
if (!location.port) location.port = (location.protocol === 'https://') ? '443' : '80';
|
1076
|
+
location.port = location.port.replace(/\D/g, '');
|
1077
|
+
|
1078
|
+
var parts = url.split('?'),
|
1079
|
+
path = parts.shift(),
|
1080
|
+
query = parts.join('?'),
|
1081
|
+
|
1082
|
+
pairs = query ? query.split('&') : [],
|
1083
|
+
n = pairs.length,
|
1084
|
+
data = {};
|
1085
|
+
|
1086
|
+
while (n--) {
|
1087
|
+
parts = pairs[n].split('=');
|
1088
|
+
data[decodeURIComponent(parts[0] || '')] = decodeURIComponent(parts[1] || '');
|
1089
|
+
}
|
1090
|
+
if (typeof params === 'object') Faye.extend(data, params);
|
1091
|
+
|
1092
|
+
location.pathname = path;
|
1093
|
+
location.params = data;
|
1094
|
+
|
1095
|
+
return location;
|
1096
|
+
}
|
1097
|
+
});
|
1098
|
+
|
1099
|
+
|
1100
|
+
Faye.XHR = {
|
1101
|
+
request: function(method, url, params, callbacks, scope) {
|
1102
|
+
var req = new this.Request(method, url, params, callbacks, scope);
|
1103
|
+
req.send();
|
1104
|
+
return req;
|
1105
|
+
},
|
1106
|
+
|
1107
|
+
getXhrObject: function() {
|
1108
|
+
return Faye.ENV.ActiveXObject
|
1109
|
+
? new ActiveXObject("Microsoft.XMLHTTP")
|
1110
|
+
: new XMLHttpRequest();
|
1111
|
+
},
|
1112
|
+
|
1113
|
+
Request: Faye.Class({
|
1114
|
+
initialize: function(method, url, params, callbacks, scope) {
|
1115
|
+
this._method = method.toUpperCase();
|
1116
|
+
this._endpoint = Faye.URI.parse(url, params);
|
1117
|
+
this._postBody = (typeof params === 'string') ? params : null;
|
1118
|
+
this._callbacks = (typeof callbacks === 'function') ? {success: callbacks} : callbacks;
|
1119
|
+
this._scope = scope || null;
|
1120
|
+
this._xhr = null;
|
1121
|
+
},
|
1122
|
+
|
1123
|
+
send: function() {
|
1124
|
+
if (this._waiting) return;
|
1125
|
+
|
1126
|
+
var path = this._endpoint.pathname, qs = this._endpoint.queryString();
|
1127
|
+
if (this._method === 'GET') path += '?' + qs;
|
1128
|
+
|
1129
|
+
var body = (this._method === 'POST') ? (this._postBody || qs) : '';
|
1130
|
+
|
1131
|
+
this._waiting = true;
|
1132
|
+
this._xhr = Faye.XHR.getXhrObject();
|
1133
|
+
this._xhr.open(this._method, path, true);
|
1134
|
+
|
1135
|
+
if (this._method === 'POST')
|
1136
|
+
this._xhr.setRequestHeader('Content-Type', 'application/json');
|
1137
|
+
|
1138
|
+
var self = this, handleState = function() {
|
1139
|
+
if (self._xhr.readyState !== 4) return;
|
1140
|
+
|
1141
|
+
if (poll) {
|
1142
|
+
clearInterval(poll);
|
1143
|
+
poll = null;
|
1144
|
+
}
|
1145
|
+
|
1146
|
+
Faye.Event.detach(Faye.ENV, 'beforeunload', self.abort, self);
|
1147
|
+
self._waiting = false;
|
1148
|
+
self._handleResponse();
|
1149
|
+
self = null;
|
1150
|
+
};
|
1151
|
+
|
1152
|
+
var poll = setInterval(handleState, 10);
|
1153
|
+
Faye.Event.on(Faye.ENV, 'beforeunload', this.abort, this);
|
1154
|
+
this._xhr.send(body);
|
1155
|
+
},
|
1156
|
+
|
1157
|
+
abort: function() {
|
1158
|
+
this._xhr.abort();
|
1159
|
+
},
|
1160
|
+
|
1161
|
+
_handleResponse: function() {
|
1162
|
+
var cb = this._callbacks;
|
1163
|
+
if (!cb) return;
|
1164
|
+
return this.success()
|
1165
|
+
? cb.success && cb.success.call(this._scope, this)
|
1166
|
+
: cb.failure && cb.failure.call(this._scope, this);
|
1167
|
+
},
|
1168
|
+
|
1169
|
+
waiting: function() {
|
1170
|
+
return !!this._waiting;
|
1171
|
+
},
|
1172
|
+
|
1173
|
+
complete: function() {
|
1174
|
+
return this._xhr && !this.waiting();
|
1175
|
+
},
|
1176
|
+
|
1177
|
+
success: function() {
|
1178
|
+
if (!this.complete()) return false;
|
1179
|
+
var status = this._xhr.status;
|
1180
|
+
return (status >= 200 && status < 300) || status === 304 || status === 1223;
|
1181
|
+
},
|
1182
|
+
|
1183
|
+
failure: function() {
|
1184
|
+
if (!this.complete()) return false;
|
1185
|
+
return !this.success();
|
1186
|
+
},
|
1187
|
+
|
1188
|
+
text: function() {
|
1189
|
+
if (!this.complete()) return null;
|
1190
|
+
return this._xhr.responseText;
|
1191
|
+
},
|
1192
|
+
|
1193
|
+
status: function() {
|
1194
|
+
if (!this.complete()) return null;
|
1195
|
+
return this._xhr.status;
|
1196
|
+
}
|
1197
|
+
})
|
1198
|
+
};
|
1199
|
+
|
1200
|
+
|
1201
|
+
/*
|
1202
|
+
http://www.JSON.org/json2.js
|
1203
|
+
2009-04-16
|
1204
|
+
|
1205
|
+
Public Domain.
|
1206
|
+
|
1207
|
+
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
|
1208
|
+
|
1209
|
+
See http://www.JSON.org/js.html
|
1210
|
+
|
1211
|
+
This file creates a global JSON object containing two methods: stringify
|
1212
|
+
and parse.
|
1213
|
+
|
1214
|
+
JSON.stringify(value, replacer, space)
|
1215
|
+
value any JavaScript value, usually an object or array.
|
1216
|
+
|
1217
|
+
replacer an optional parameter that determines how object
|
1218
|
+
values are stringified for objects. It can be a
|
1219
|
+
function or an array of strings.
|
1220
|
+
|
1221
|
+
space an optional parameter that specifies the indentation
|
1222
|
+
of nested structures. If it is omitted, the text will
|
1223
|
+
be packed without extra whitespace. If it is a number,
|
1224
|
+
it will specify the number of spaces to indent at each
|
1225
|
+
level. If it is a string (such as '\t' or ' '),
|
1226
|
+
it contains the characters used to indent at each level.
|
1227
|
+
|
1228
|
+
This method produces a JSON text from a JavaScript value.
|
1229
|
+
|
1230
|
+
When an object value is found, if the object contains a toJSON
|
1231
|
+
method, its toJSON method will be called and the result will be
|
1232
|
+
stringified. A toJSON method does not serialize: it returns the
|
1233
|
+
value represented by the name/value pair that should be serialized,
|
1234
|
+
or undefined if nothing should be serialized. The toJSON method
|
1235
|
+
will be passed the key associated with the value, and this will be
|
1236
|
+
bound to the object holding the key.
|
1237
|
+
|
1238
|
+
For example, this would serialize Dates as ISO strings.
|
1239
|
+
|
1240
|
+
Date.prototype.toJSON = function (key) {
|
1241
|
+
function f(n) {
|
1242
|
+
// Format integers to have at least two digits.
|
1243
|
+
return n < 10 ? '0' + n : n;
|
1244
|
+
}
|
1245
|
+
|
1246
|
+
return this.getUTCFullYear() + '-' +
|
1247
|
+
f(this.getUTCMonth() + 1) + '-' +
|
1248
|
+
f(this.getUTCDate()) + 'T' +
|
1249
|
+
f(this.getUTCHours()) + ':' +
|
1250
|
+
f(this.getUTCMinutes()) + ':' +
|
1251
|
+
f(this.getUTCSeconds()) + 'Z';
|
1252
|
+
};
|
1253
|
+
|
1254
|
+
You can provide an optional replacer method. It will be passed the
|
1255
|
+
key and value of each member, with this bound to the containing
|
1256
|
+
object. The value that is returned from your method will be
|
1257
|
+
serialized. If your method returns undefined, then the member will
|
1258
|
+
be excluded from the serialization.
|
1259
|
+
|
1260
|
+
If the replacer parameter is an array of strings, then it will be
|
1261
|
+
used to select the members to be serialized. It filters the results
|
1262
|
+
such that only members with keys listed in the replacer array are
|
1263
|
+
stringified.
|
1264
|
+
|
1265
|
+
Values that do not have JSON representations, such as undefined or
|
1266
|
+
functions, will not be serialized. Such values in objects will be
|
1267
|
+
dropped; in arrays they will be replaced with null. You can use
|
1268
|
+
a replacer function to replace those with JSON values.
|
1269
|
+
JSON.stringify(undefined) returns undefined.
|
1270
|
+
|
1271
|
+
The optional space parameter produces a stringification of the
|
1272
|
+
value that is filled with line breaks and indentation to make it
|
1273
|
+
easier to read.
|
1274
|
+
|
1275
|
+
If the space parameter is a non-empty string, then that string will
|
1276
|
+
be used for indentation. If the space parameter is a number, then
|
1277
|
+
the indentation will be that many spaces.
|
1278
|
+
|
1279
|
+
Example:
|
1280
|
+
|
1281
|
+
text = JSON.stringify(['e', {pluribus: 'unum'}]);
|
1282
|
+
// text is '["e",{"pluribus":"unum"}]'
|
1283
|
+
|
1284
|
+
|
1285
|
+
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
|
1286
|
+
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
|
1287
|
+
|
1288
|
+
text = JSON.stringify([new Date()], function (key, value) {
|
1289
|
+
return this[key] instanceof Date ?
|
1290
|
+
'Date(' + this[key] + ')' : value;
|
1291
|
+
});
|
1292
|
+
// text is '["Date(---current time---)"]'
|
1293
|
+
|
1294
|
+
|
1295
|
+
JSON.parse(text, reviver)
|
1296
|
+
This method parses a JSON text to produce an object or array.
|
1297
|
+
It can throw a SyntaxError exception.
|
1298
|
+
|
1299
|
+
The optional reviver parameter is a function that can filter and
|
1300
|
+
transform the results. It receives each of the keys and values,
|
1301
|
+
and its return value is used instead of the original value.
|
1302
|
+
If it returns what it received, then the structure is not modified.
|
1303
|
+
If it returns undefined then the member is deleted.
|
1304
|
+
|
1305
|
+
Example:
|
1306
|
+
|
1307
|
+
// Parse the text. Values that look like ISO date strings will
|
1308
|
+
// be converted to Date objects.
|
1309
|
+
|
1310
|
+
myData = JSON.parse(text, function (key, value) {
|
1311
|
+
var a;
|
1312
|
+
if (typeof value === 'string') {
|
1313
|
+
a =
|
1314
|
+
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
|
1315
|
+
if (a) {
|
1316
|
+
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
|
1317
|
+
+a[5], +a[6]));
|
1318
|
+
}
|
1319
|
+
}
|
1320
|
+
return value;
|
1321
|
+
});
|
1322
|
+
|
1323
|
+
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
|
1324
|
+
var d;
|
1325
|
+
if (typeof value === 'string' &&
|
1326
|
+
value.slice(0, 5) === 'Date(' &&
|
1327
|
+
value.slice(-1) === ')') {
|
1328
|
+
d = new Date(value.slice(5, -1));
|
1329
|
+
if (d) {
|
1330
|
+
return d;
|
1331
|
+
}
|
1332
|
+
}
|
1333
|
+
return value;
|
1334
|
+
});
|
1335
|
+
|
1336
|
+
|
1337
|
+
This is a reference implementation. You are free to copy, modify, or
|
1338
|
+
redistribute.
|
1339
|
+
|
1340
|
+
This code should be minified before deployment.
|
1341
|
+
See http://javascript.crockford.com/jsmin.html
|
1342
|
+
|
1343
|
+
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
|
1344
|
+
NOT CONTROL.
|
1345
|
+
*/
|
1346
|
+
|
1347
|
+
/*jslint evil: true */
|
1348
|
+
|
1349
|
+
/*global JSON */
|
1350
|
+
|
1351
|
+
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
|
1352
|
+
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
|
1353
|
+
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
|
1354
|
+
lastIndex, length, parse, prototype, push, replace, slice, stringify,
|
1355
|
+
test, toJSON, toString, valueOf
|
1356
|
+
*/
|
1357
|
+
|
1358
|
+
// Create a JSON object only if one does not already exist. We create the
|
1359
|
+
// methods in a closure to avoid creating global variables.
|
1360
|
+
|
1361
|
+
if (!this.JSON) {
|
1362
|
+
JSON = {};
|
1363
|
+
}
|
1364
|
+
(function () {
|
1365
|
+
|
1366
|
+
function f(n) {
|
1367
|
+
// Format integers to have at least two digits.
|
1368
|
+
return n < 10 ? '0' + n : n;
|
1369
|
+
}
|
1370
|
+
|
1371
|
+
if (typeof Date.prototype.toJSON !== 'function') {
|
1372
|
+
|
1373
|
+
Date.prototype.toJSON = function (key) {
|
1374
|
+
|
1375
|
+
return this.getUTCFullYear() + '-' +
|
1376
|
+
f(this.getUTCMonth() + 1) + '-' +
|
1377
|
+
f(this.getUTCDate()) + 'T' +
|
1378
|
+
f(this.getUTCHours()) + ':' +
|
1379
|
+
f(this.getUTCMinutes()) + ':' +
|
1380
|
+
f(this.getUTCSeconds()) + 'Z';
|
1381
|
+
};
|
1382
|
+
|
1383
|
+
String.prototype.toJSON =
|
1384
|
+
Number.prototype.toJSON =
|
1385
|
+
Boolean.prototype.toJSON = function (key) {
|
1386
|
+
return this.valueOf();
|
1387
|
+
};
|
1388
|
+
}
|
1389
|
+
|
1390
|
+
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
1391
|
+
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
1392
|
+
gap,
|
1393
|
+
indent,
|
1394
|
+
meta = { // table of character substitutions
|
1395
|
+
'\b': '\\b',
|
1396
|
+
'\t': '\\t',
|
1397
|
+
'\n': '\\n',
|
1398
|
+
'\f': '\\f',
|
1399
|
+
'\r': '\\r',
|
1400
|
+
'"' : '\\"',
|
1401
|
+
'\\': '\\\\'
|
1402
|
+
},
|
1403
|
+
rep;
|
1404
|
+
|
1405
|
+
|
1406
|
+
function quote(string) {
|
1407
|
+
|
1408
|
+
// If the string contains no control characters, no quote characters, and no
|
1409
|
+
// backslash characters, then we can safely slap some quotes around it.
|
1410
|
+
// Otherwise we must also replace the offending characters with safe escape
|
1411
|
+
// sequences.
|
1412
|
+
|
1413
|
+
escapable.lastIndex = 0;
|
1414
|
+
return escapable.test(string) ?
|
1415
|
+
'"' + string.replace(escapable, function (a) {
|
1416
|
+
var c = meta[a];
|
1417
|
+
return typeof c === 'string' ? c :
|
1418
|
+
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
1419
|
+
}) + '"' :
|
1420
|
+
'"' + string + '"';
|
1421
|
+
}
|
1422
|
+
|
1423
|
+
|
1424
|
+
function str(key, holder) {
|
1425
|
+
|
1426
|
+
// Produce a string from holder[key].
|
1427
|
+
|
1428
|
+
var i, // The loop counter.
|
1429
|
+
k, // The member key.
|
1430
|
+
v, // The member value.
|
1431
|
+
length,
|
1432
|
+
mind = gap,
|
1433
|
+
partial,
|
1434
|
+
value = holder[key];
|
1435
|
+
|
1436
|
+
// If the value has a toJSON method, call it to obtain a replacement value.
|
1437
|
+
|
1438
|
+
if (value && typeof value === 'object' &&
|
1439
|
+
typeof value.toJSON === 'function') {
|
1440
|
+
value = value.toJSON(key);
|
1441
|
+
}
|
1442
|
+
|
1443
|
+
// If we were called with a replacer function, then call the replacer to
|
1444
|
+
// obtain a replacement value.
|
1445
|
+
|
1446
|
+
if (typeof rep === 'function') {
|
1447
|
+
value = rep.call(holder, key, value);
|
1448
|
+
}
|
1449
|
+
|
1450
|
+
// What happens next depends on the value's type.
|
1451
|
+
|
1452
|
+
switch (typeof value) {
|
1453
|
+
case 'string':
|
1454
|
+
return quote(value);
|
1455
|
+
|
1456
|
+
case 'number':
|
1457
|
+
|
1458
|
+
// JSON numbers must be finite. Encode non-finite numbers as null.
|
1459
|
+
|
1460
|
+
return isFinite(value) ? String(value) : 'null';
|
1461
|
+
|
1462
|
+
case 'boolean':
|
1463
|
+
case 'null':
|
1464
|
+
|
1465
|
+
// If the value is a boolean or null, convert it to a string. Note:
|
1466
|
+
// typeof null does not produce 'null'. The case is included here in
|
1467
|
+
// the remote chance that this gets fixed someday.
|
1468
|
+
|
1469
|
+
return String(value);
|
1470
|
+
|
1471
|
+
// If the type is 'object', we might be dealing with an object or an array or
|
1472
|
+
// null.
|
1473
|
+
|
1474
|
+
case 'object':
|
1475
|
+
|
1476
|
+
// Due to a specification blunder in ECMAScript, typeof null is 'object',
|
1477
|
+
// so watch out for that case.
|
1478
|
+
|
1479
|
+
if (!value) {
|
1480
|
+
return 'null';
|
1481
|
+
}
|
1482
|
+
|
1483
|
+
// Make an array to hold the partial results of stringifying this object value.
|
1484
|
+
|
1485
|
+
gap += indent;
|
1486
|
+
partial = [];
|
1487
|
+
|
1488
|
+
// Is the value an array?
|
1489
|
+
|
1490
|
+
if (Object.prototype.toString.apply(value) === '[object Array]') {
|
1491
|
+
|
1492
|
+
// The value is an array. Stringify every element. Use null as a placeholder
|
1493
|
+
// for non-JSON values.
|
1494
|
+
|
1495
|
+
length = value.length;
|
1496
|
+
for (i = 0; i < length; i += 1) {
|
1497
|
+
partial[i] = str(i, value) || 'null';
|
1498
|
+
}
|
1499
|
+
|
1500
|
+
// Join all of the elements together, separated with commas, and wrap them in
|
1501
|
+
// brackets.
|
1502
|
+
|
1503
|
+
v = partial.length === 0 ? '[]' :
|
1504
|
+
gap ? '[\n' + gap +
|
1505
|
+
partial.join(',\n' + gap) + '\n' +
|
1506
|
+
mind + ']' :
|
1507
|
+
'[' + partial.join(',') + ']';
|
1508
|
+
gap = mind;
|
1509
|
+
return v;
|
1510
|
+
}
|
1511
|
+
|
1512
|
+
// If the replacer is an array, use it to select the members to be stringified.
|
1513
|
+
|
1514
|
+
if (rep && typeof rep === 'object') {
|
1515
|
+
length = rep.length;
|
1516
|
+
for (i = 0; i < length; i += 1) {
|
1517
|
+
k = rep[i];
|
1518
|
+
if (typeof k === 'string') {
|
1519
|
+
v = str(k, value);
|
1520
|
+
if (v) {
|
1521
|
+
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
1522
|
+
}
|
1523
|
+
}
|
1524
|
+
}
|
1525
|
+
} else {
|
1526
|
+
|
1527
|
+
// Otherwise, iterate through all of the keys in the object.
|
1528
|
+
|
1529
|
+
for (k in value) {
|
1530
|
+
if (Object.hasOwnProperty.call(value, k)) {
|
1531
|
+
v = str(k, value);
|
1532
|
+
if (v) {
|
1533
|
+
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
1534
|
+
}
|
1535
|
+
}
|
1536
|
+
}
|
1537
|
+
}
|
1538
|
+
|
1539
|
+
// Join all of the member texts together, separated with commas,
|
1540
|
+
// and wrap them in braces.
|
1541
|
+
|
1542
|
+
v = partial.length === 0 ? '{}' :
|
1543
|
+
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
|
1544
|
+
mind + '}' : '{' + partial.join(',') + '}';
|
1545
|
+
gap = mind;
|
1546
|
+
return v;
|
1547
|
+
}
|
1548
|
+
}
|
1549
|
+
|
1550
|
+
// If the JSON object does not yet have a stringify method, give it one.
|
1551
|
+
|
1552
|
+
// NOTE we've hacked this to expose this method to Faye. We need to use this
|
1553
|
+
// to avoid problems with buggy Firefox version and bad #toJSON implementations
|
1554
|
+
|
1555
|
+
Faye.stringify = function (value, replacer, space) {
|
1556
|
+
|
1557
|
+
// The stringify method takes a value and an optional replacer, and an optional
|
1558
|
+
// space parameter, and returns a JSON text. The replacer can be a function
|
1559
|
+
// that can replace values, or an array of strings that will select the keys.
|
1560
|
+
// A default replacer method can be provided. Use of the space parameter can
|
1561
|
+
// produce text that is more easily readable.
|
1562
|
+
|
1563
|
+
var i;
|
1564
|
+
gap = '';
|
1565
|
+
indent = '';
|
1566
|
+
|
1567
|
+
// If the space parameter is a number, make an indent string containing that
|
1568
|
+
// many spaces.
|
1569
|
+
|
1570
|
+
if (typeof space === 'number') {
|
1571
|
+
for (i = 0; i < space; i += 1) {
|
1572
|
+
indent += ' ';
|
1573
|
+
}
|
1574
|
+
|
1575
|
+
// If the space parameter is a string, it will be used as the indent string.
|
1576
|
+
|
1577
|
+
} else if (typeof space === 'string') {
|
1578
|
+
indent = space;
|
1579
|
+
}
|
1580
|
+
|
1581
|
+
// If there is a replacer, it must be a function or an array.
|
1582
|
+
// Otherwise, throw an error.
|
1583
|
+
|
1584
|
+
rep = replacer;
|
1585
|
+
if (replacer && typeof replacer !== 'function' &&
|
1586
|
+
(typeof replacer !== 'object' ||
|
1587
|
+
typeof replacer.length !== 'number')) {
|
1588
|
+
throw new Error('JSON.stringify');
|
1589
|
+
}
|
1590
|
+
|
1591
|
+
// Make a fake root object containing our value under the key of ''.
|
1592
|
+
// Return the result of stringifying the value.
|
1593
|
+
|
1594
|
+
return str('', {'': value});
|
1595
|
+
};
|
1596
|
+
|
1597
|
+
if (typeof JSON.stringify !== 'function') {
|
1598
|
+
JSON.stringify = Faye.stringify;
|
1599
|
+
}
|
1600
|
+
|
1601
|
+
|
1602
|
+
// If the JSON object does not yet have a parse method, give it one.
|
1603
|
+
|
1604
|
+
if (typeof JSON.parse !== 'function') {
|
1605
|
+
JSON.parse = function (text, reviver) {
|
1606
|
+
|
1607
|
+
// The parse method takes a text and an optional reviver function, and returns
|
1608
|
+
// a JavaScript value if the text is a valid JSON text.
|
1609
|
+
|
1610
|
+
var j;
|
1611
|
+
|
1612
|
+
function walk(holder, key) {
|
1613
|
+
|
1614
|
+
// The walk method is used to recursively walk the resulting structure so
|
1615
|
+
// that modifications can be made.
|
1616
|
+
|
1617
|
+
var k, v, value = holder[key];
|
1618
|
+
if (value && typeof value === 'object') {
|
1619
|
+
for (k in value) {
|
1620
|
+
if (Object.hasOwnProperty.call(value, k)) {
|
1621
|
+
v = walk(value, k);
|
1622
|
+
if (v !== undefined) {
|
1623
|
+
value[k] = v;
|
1624
|
+
} else {
|
1625
|
+
delete value[k];
|
1626
|
+
}
|
1627
|
+
}
|
1628
|
+
}
|
1629
|
+
}
|
1630
|
+
return reviver.call(holder, key, value);
|
1631
|
+
}
|
1632
|
+
|
1633
|
+
|
1634
|
+
// Parsing happens in four stages. In the first stage, we replace certain
|
1635
|
+
// Unicode characters with escape sequences. JavaScript handles many characters
|
1636
|
+
// incorrectly, either silently deleting them, or treating them as line endings.
|
1637
|
+
|
1638
|
+
cx.lastIndex = 0;
|
1639
|
+
if (cx.test(text)) {
|
1640
|
+
text = text.replace(cx, function (a) {
|
1641
|
+
return '\\u' +
|
1642
|
+
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
1643
|
+
});
|
1644
|
+
}
|
1645
|
+
|
1646
|
+
// In the second stage, we run the text against regular expressions that look
|
1647
|
+
// for non-JSON patterns. We are especially concerned with '()' and 'new'
|
1648
|
+
// because they can cause invocation, and '=' because it can cause mutation.
|
1649
|
+
// But just to be safe, we want to reject all unexpected forms.
|
1650
|
+
|
1651
|
+
// We split the second stage into 4 regexp operations in order to work around
|
1652
|
+
// crippling inefficiencies in IE's and Safari's regexp engines. First we
|
1653
|
+
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
|
1654
|
+
// replace all simple value tokens with ']' characters. Third, we delete all
|
1655
|
+
// open brackets that follow a colon or comma or that begin the text. Finally,
|
1656
|
+
// we look to see that the remaining characters are only whitespace or ']' or
|
1657
|
+
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
|
1658
|
+
|
1659
|
+
if (/^[\],:{}\s]*$/.
|
1660
|
+
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
|
1661
|
+
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
|
1662
|
+
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
|
1663
|
+
|
1664
|
+
// In the third stage we use the eval function to compile the text into a
|
1665
|
+
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
|
1666
|
+
// in JavaScript: it can begin a block or an object literal. We wrap the text
|
1667
|
+
// in parens to eliminate the ambiguity.
|
1668
|
+
|
1669
|
+
j = eval('(' + text + ')');
|
1670
|
+
|
1671
|
+
// In the optional fourth stage, we recursively walk the new structure, passing
|
1672
|
+
// each name/value pair to a reviver function for possible transformation.
|
1673
|
+
|
1674
|
+
return typeof reviver === 'function' ?
|
1675
|
+
walk({'': j}, '') : j;
|
1676
|
+
}
|
1677
|
+
|
1678
|
+
// If the text is not JSON parseable, then a SyntaxError is thrown.
|
1679
|
+
|
1680
|
+
throw new SyntaxError('JSON.parse');
|
1681
|
+
};
|
1682
|
+
}
|
1683
|
+
}());
|
1684
|
+
|
1685
|
+
|
1686
|
+
Faye.WebSocketTransport = Faye.Class(Faye.Transport, {
|
1687
|
+
UNCONNECTED: 1,
|
1688
|
+
CONNECTING: 2,
|
1689
|
+
CONNECTED: 3,
|
1690
|
+
|
1691
|
+
request: function(messages, timeout) {
|
1692
|
+
this._messages = this._messages || {};
|
1693
|
+
Faye.each(messages, function(message) {
|
1694
|
+
this._messages[message.id] = message;
|
1695
|
+
}, this);
|
1696
|
+
this.withSocket(function(socket) { socket.send(Faye.toJSON(messages)) });
|
1697
|
+
},
|
1698
|
+
|
1699
|
+
withSocket: function(callback, scope) {
|
1700
|
+
this.callback(callback, scope);
|
1701
|
+
|
1702
|
+
this._state = this._state || this.UNCONNECTED;
|
1703
|
+
if (this._state !== this.UNCONNECTED) return;
|
1704
|
+
|
1705
|
+
this._state = this.CONNECTING;
|
1706
|
+
|
1707
|
+
var socketUrl = Faye.URI.parse(this._endpoint).toURL().
|
1708
|
+
replace(/^https?/ig, 'ws');
|
1709
|
+
|
1710
|
+
this._socket = new WebSocket(socketUrl);
|
1711
|
+
var self = this;
|
1712
|
+
|
1713
|
+
this._socket.onopen = function() {
|
1714
|
+
self._state = self.CONNECTED;
|
1715
|
+
self.setDeferredStatus('succeeded', self._socket);
|
1716
|
+
};
|
1717
|
+
|
1718
|
+
this._socket.onmessage = function(event) {
|
1719
|
+
var messages = [].concat(JSON.parse(event.data));
|
1720
|
+
Faye.each(messages, function(message) {
|
1721
|
+
delete self._messages[message.id];
|
1722
|
+
});
|
1723
|
+
self.receive(messages);
|
1724
|
+
};
|
1725
|
+
|
1726
|
+
this._socket.onclose = function() {
|
1727
|
+
self.setDeferredStatus('deferred');
|
1728
|
+
self._state = self.UNCONNECTED;
|
1729
|
+
self._socket = null;
|
1730
|
+
self.resend();
|
1731
|
+
};
|
1732
|
+
},
|
1733
|
+
|
1734
|
+
resend: function() {
|
1735
|
+
var messages = Faye.map(this._messages, function(id, msg) { return msg });
|
1736
|
+
this.request(messages);
|
1737
|
+
}
|
1738
|
+
});
|
1739
|
+
|
1740
|
+
Faye.extend(Faye.WebSocketTransport.prototype, Faye.Deferrable);
|
1741
|
+
|
1742
|
+
|
1743
|
+
Faye.WebSocketTransport.isUsable = function(endpoint) {
|
1744
|
+
return !!Faye.ENV.WebSocket;
|
1745
|
+
};
|
1746
|
+
|
1747
|
+
Faye.Transport.register('websocket', Faye.WebSocketTransport);
|
1748
|
+
|
1749
|
+
|
1750
|
+
Faye.XHRTransport = Faye.Class(Faye.Transport, {
|
1751
|
+
request: function(message, timeout) {
|
1752
|
+
var retry = this.retry(message, timeout);
|
1753
|
+
|
1754
|
+
Faye.XHR.request('post', this._endpoint, Faye.toJSON(message), {
|
1755
|
+
success:function(response) {
|
1756
|
+
try {
|
1757
|
+
this.receive(JSON.parse(response.text()));
|
1758
|
+
} catch (e) {
|
1759
|
+
retry();
|
1760
|
+
}
|
1761
|
+
},
|
1762
|
+
failure: retry
|
1763
|
+
}, this);
|
1764
|
+
}
|
1765
|
+
});
|
1766
|
+
|
1767
|
+
Faye.XHRTransport.isUsable = function(endpoint) {
|
1768
|
+
return Faye.URI.parse(endpoint).isLocal();
|
1769
|
+
};
|
1770
|
+
|
1771
|
+
Faye.Transport.register('long-polling', Faye.XHRTransport);
|
1772
|
+
|
1773
|
+
|
1774
|
+
Faye.JSONPTransport = Faye.extend(Faye.Class(Faye.Transport, {
|
1775
|
+
request: function(message, timeout) {
|
1776
|
+
var params = {message: Faye.toJSON(message)},
|
1777
|
+
head = document.getElementsByTagName('head')[0],
|
1778
|
+
script = document.createElement('script'),
|
1779
|
+
callbackName = Faye.JSONPTransport.getCallbackName(),
|
1780
|
+
location = Faye.URI.parse(this._endpoint, params),
|
1781
|
+
self = this;
|
1782
|
+
|
1783
|
+
var removeScript = function() {
|
1784
|
+
if (!script.parentNode) return false;
|
1785
|
+
script.parentNode.removeChild(script);
|
1786
|
+
return true;
|
1787
|
+
};
|
1788
|
+
|
1789
|
+
Faye.ENV[callbackName] = function(data) {
|
1790
|
+
Faye.ENV[callbackName] = undefined;
|
1791
|
+
try { delete Faye.ENV[callbackName] } catch (e) {}
|
1792
|
+
if (!removeScript()) return;
|
1793
|
+
self.receive(data);
|
1794
|
+
};
|
1795
|
+
|
1796
|
+
setTimeout(function() {
|
1797
|
+
if (!Faye.ENV[callbackName]) return;
|
1798
|
+
removeScript();
|
1799
|
+
self.request(message, 2 * timeout);
|
1800
|
+
}, 1000 * timeout);
|
1801
|
+
|
1802
|
+
location.params.jsonp = callbackName;
|
1803
|
+
script.type = 'text/javascript';
|
1804
|
+
script.src = location.toURL();
|
1805
|
+
head.appendChild(script);
|
1806
|
+
}
|
1807
|
+
}), {
|
1808
|
+
_cbCount: 0,
|
1809
|
+
|
1810
|
+
getCallbackName: function() {
|
1811
|
+
this._cbCount += 1;
|
1812
|
+
return '__jsonp' + this._cbCount + '__';
|
1813
|
+
}
|
1814
|
+
});
|
1815
|
+
|
1816
|
+
Faye.JSONPTransport.isUsable = function(endpoint) {
|
1817
|
+
return true;
|
1818
|
+
};
|
1819
|
+
|
1820
|
+
Faye.Transport.register('callback-polling', Faye.JSONPTransport);
|