faye-huboard 1.0.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 65217423f8c2b3af79413bda593460e639791480
4
+ data.tar.gz: 3bbfe262d9011ca6887dd8f9f73edeb2e6014078
5
+ SHA512:
6
+ metadata.gz: 8462466d1c0ae16b54393fab8fcbc6d3fe4c0f44100a52d67b3ab6a39924427749b2757af4eb0ae845836719589052ce04e123d9c93e81e277f5739084cd2321
7
+ data.tar.gz: b6d2f174f9982e49b26315b2c2ac6aef29fb8d2ff45a86a89c27f187dbd405dd9fa0007d7a2b081b88c1c7c4fda0963b5b941e02533271d7d06d4969bd22c3fa
@@ -0,0 +1,351 @@
1
+ ### 1.0.3 / 2014-07-08
2
+
3
+ * Make some changes to JSON-P responses to mitigate the Rosetta Flash attack
4
+ * http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
5
+
6
+
7
+ ### 1.0.2 -- removed due to error while publishing
8
+
9
+
10
+ ### 1.0.1 / 2013-12-10
11
+
12
+ * Add `Adapter#close()` method for gracefully shutting down the server
13
+ * Fix error recover bug in WebSocket that made transport cycle through `up`/`down` state
14
+ * Update Promise implementation to pass `promises-aplus-tests 2.0`
15
+ * Correct some incorrect variable names in the Ruby transports
16
+ * Make logging methods public to fix a problem on Ruby 2.1
17
+
18
+
19
+ ### 1.0.0 / 2013-10-01
20
+
21
+ * Client changes:
22
+ * Allow clients to be instantiated with URI objects rather than strings
23
+ * Add a `ca` option to the Node `Client` class for passing in trusted server certificates
24
+ * Objects supporting the `callback()` method in JavaScript are now Promises
25
+ * Fix protocol-relative URI parsing in the client
26
+ * Remove the `getClientId()` and `getState()` methods from the `Client` class
27
+ * Transport changes:
28
+ * Add request-size limiting to all batching transports
29
+ * Make the WebSocket transport more robust against quiet network periods and clients going to sleep
30
+ * Support cookies across all transports when using the client on Node.js or Ruby
31
+ * Support custom headers in the `cross-origin-long-polling` and server-side `websocket` transports
32
+ * Adapter changes:
33
+ * Support the `rack.hijack` streaming API
34
+ * Migrate to MultiJson for JSON handling on Ruby, allowing use of JRuby
35
+ * Escape U+2028 and U+2029 in JSON-P output
36
+ * Fix a bug stopping requests being routed when the mount point is `/`
37
+ * Fix various bugs that cause errors to be thrown if we try to send a message over a closed socket
38
+ * Remove the `listen()` method from `Adapter` in favour of using server-specific APIs
39
+ * Server changes:
40
+ * Use cryptographically secure random number generators to create client IDs
41
+ * Allow extensions to access request properties by using 3-ary methods
42
+ * Objects supporting the `bind()` method now implement the full `EventEmitter` API
43
+ * Stop the server from forwarding the `clientId` property of published messages
44
+ * Miscellaneous:
45
+ * Support Browserify by returning the client module
46
+ * `Faye.logger` can now be a logger object rather than a function
47
+
48
+
49
+ ### 0.8.9 / 2013-02-26
50
+
51
+ * Specify ciphers for SSL on Node to mitigate the BEAST attack
52
+ * Mitigate increased risk of socket hang-up errors in Node v0.8.20
53
+ * Fix race condition when processing outgoing extensions in the Node server
54
+ * Fix problem loading the client script when using `{mount: '/'}`
55
+ * Clean up connection objects when a WebSocket is re-used with a new clientId
56
+ * All JavaScript code now runs in strict mode
57
+ * Select transport on handshake, instead of on client creation to allow time for `disable()` calls
58
+ * Do not speculatively open WebSocket/EventSource connections if they are disabled
59
+ * Gracefully handle WebSocket messages with no data on the client side
60
+ * Close and reconnect WebSocket when onerror is fired, not just when onclose is fired
61
+ * Fix problem with caching of EventSource connections with stale clientIds
62
+ * Don't parse query strings when checking if a URL is same-origin or not
63
+
64
+
65
+ ### 0.8.8 / 2013-01-10
66
+
67
+ * Patch security hole allowing remote execution of arbitrary Server methods
68
+
69
+
70
+ ### 0.8.7 -- removed due to error while publishing
71
+
72
+
73
+ ### 0.8.6 / 2012-10-07
74
+
75
+ * Make sure messages pushed to the client over a socket pass through outgoing extensions
76
+
77
+
78
+ ### 0.8.5 / 2012-09-30
79
+
80
+ * Fix a bug in `URI.parse()` that caused Faye endpoints to inherit search and hash from `window.location`
81
+
82
+
83
+ ### 0.8.4 / 2012-09-29
84
+
85
+ * Optimise upgrade process so that WebSocket is tested earlier and the connection is cached
86
+ * Check that EventSource actually works to work around broken Opera implementation
87
+ * Emit `connection:open` and `connection:close` events from the Engine proxy
88
+ * Increase size of client IDs from 128 to 160 bits
89
+ * Fix bug with relative URL resolution in IE
90
+ * Limit the JSON-P transport's message buffer so it doesn't create over-long URLs
91
+ * Send `Pragma: no-cache` with XHR requests to guard against iOS 6 POST caching
92
+ * Add `charset=utf-8` to response Content-Type headers
93
+
94
+
95
+ ### 0.8.3 / 2012-07-15
96
+
97
+ * `Client#subscribe` returns an array of Subscriptions if given an array of channels
98
+ * Allow different endpoints to be specified per-transport
99
+ * Only use IE's `XDomainRequest` for same-protocol requests
100
+ * Replace URL parser with one that treats relative URLs the same as the browser
101
+ * Improve logging of malformed requests and detect problems earlier
102
+ * Make sure socket connections are closed when a client session is timed out
103
+ * Stop WebSocket reconnecting after `window.onbeforeunload`
104
+
105
+
106
+ ### 0.8.2 / 2012-04-12
107
+
108
+ * Fix replacement of `null` with `{}` in `copyObject()`
109
+ * Make EventSource transport trigger `transport:up/down` events
110
+ * Supply source map for minified JavaScript client, and include source in gem
111
+ * Return `Content-Length: 0` for 304 responses
112
+ * Handle pre-flight CORS requests from old versions of Safari
113
+
114
+
115
+ ### 0.8.1 / 2012-03-15
116
+
117
+ * Make `Publisher#trigger` safe for event listeners that modify the listener list
118
+ * Make `Server#subscribe` return a response if the incoming message has an error
119
+ * Fix edge case in code that identifies the `clientId` of socket connections
120
+ * Return `Content-Length` headers for HTTP responses
121
+ * Don't send empty lists of messages from the WebSocket transport
122
+ * Stop client sending multiple `/meta/subscribe` messages for subscriptions made before handshaking
123
+ * Stop client treating incoming published messages as responses to `/meta/*` messages
124
+
125
+
126
+ ### 0.8.0 / 2012-02-26
127
+
128
+ * Extract the Redis engine into a separate library, `faye-redis`
129
+ * Stabilize and document the Engine API so others can write backends
130
+ * Extract WebSocket and EventSource tools into a separate library, `faye-websocket`
131
+ * Improve use of WebSocket so messages are immediately pushed rather than polling
132
+ * Introduce new EventSource-based transport, for proxies that block WebSocket
133
+ * Support the Rainbows and Goliath web servers for Ruby, same as `faye-websocket`
134
+ * Improve detection of network errors and switch to fixed-interval for reconnecting
135
+ * Add `setHeader()` method to Client (e.g. for connecting to Salesforce API)
136
+ * Add `timeout()` method to `Faye.Deferrable` to match `EventMachine::Deferrable`
137
+ * Fix some bugs in client-side message handlers created with `subscribe()`
138
+ * Improve speed and memory consumption of `copyObject()`
139
+ * Switch from JSON to Yajl for JSON parsing in Ruby
140
+
141
+
142
+ ### 0.7.1 / 2011-12-22
143
+
144
+ * Extension `added()` and `removed()` methods now receive the extended object
145
+ * Detection of WebSockets in RackAdapter is more strict
146
+
147
+
148
+ ### 0.7.0 / 2011-11-22
149
+
150
+ * Provide an event API for monitoring engine events on the server side
151
+ * Implement server-side WebSocket connections for improved latency
152
+ * Fix WebSocket protocol bugs and expose APIs for developers to use
153
+ * Make server-side HTTP transports support SSL and cookies
154
+ * Allow clients to disable selected transports and autodisconnection
155
+ * Add callback/errback API to `Client#publish()` interface
156
+ * Add `socket` setting for the Redis engine for connecting through a Unix socket
157
+
158
+
159
+ ### 0.6.7 / 2011-10-20
160
+
161
+ * Cache client script in memory and add `ETag` and `Last-Modified` headers
162
+ * Fix bug in Node Redis engine where `undefined` was used if no namespace given
163
+ * Flush Redis message queues using a transaction to avoid re-delivery of messages
164
+ * Fix race condition and timing errors present in Redis locking code
165
+ * Use `Cache-Control: no-cache, no-store` on JSON-P responses
166
+ * Improvements to the CORS and JSON-P transports
167
+ * Prevent retry handlers in transports from being invoked multiple times
168
+ * Use the current page protocol by default when parsing relative URIs
169
+
170
+
171
+ ### 0.6.6 / 2011-09-12
172
+
173
+ * Add `:key` and `:cert` options to the `Adapter#listen` methods for setting up SSL
174
+ * Fix error detection of CORS transport in IE9 running IE8 compatibility mode
175
+ * Fix dependency versions so that Rubygems lets Faye install
176
+
177
+
178
+ ### 0.6.5 / 2011-08-29
179
+
180
+ * Fix UTF-8 encoding bugs in draft-75/76 and protocol-8 WebSocket parsers
181
+ * Switch to streaming parser for WebSocket protocol-8
182
+ * Remove an `SREM` operation that shouldn't have been in the Redis engine
183
+ * Move `thin_extensions.rb` so it's not on the Rubygems load path
184
+
185
+
186
+ ### 0.6.4 / 2011-08-18
187
+
188
+ * Support WebSocket protocol used by Chrome 14 and Firefox 6
189
+ * Fix handling of multibyte characters in WebSocket messages on Node
190
+ * Improve message routing in Node memory engine to avoid false duplicates
191
+
192
+
193
+ ### 0.6.3 / 2011-07-10
194
+
195
+ * Use sequential message IDs to reduce memory usage on the client side
196
+ * Only send advice with handshake and connect responses
197
+ * Stop trying to publish `/meta/*` messages - no-one is listening and it breaks `/**`
198
+ * Fix bug causing invalid listeners to appear after a client reconnection
199
+ * Stop loading `rubygems` within our library code
200
+ * Make sure we only queue a message for each client once in the Redis engine
201
+ * Use lists instead of sets for message queues in Redis
202
+ * Improve clean-up of expired clients in Redis engine
203
+
204
+
205
+ ### 0.6.2 / 2011-06-19
206
+
207
+ * Add authentication, database selection and namespacing to Redis engine
208
+ * Clean up all client data when removing clients from Redis
209
+ * Fix `cross-origin-long-polling` for `OPTIONS`-aware browsers
210
+ * Update secure WebSocket detection for recent Node versions
211
+ * Reinstate `faye.client` field in Rack environment
212
+
213
+
214
+ ### 0.6.1 / 2011-06-06
215
+
216
+ * Fix `cross-origin-long-polling` support in `RackAdapter`
217
+ * Plug some potential memory leaks in `Memory` engine
218
+
219
+
220
+ ### 0.6.0 / 2011-05-21
221
+
222
+ * Extract core logic into the `Engine` class to support swappable backends
223
+ * Introduce a Redis-backed engine to support clustered web front-ends
224
+ * Use CORS for `cross-domain long-polling`
225
+ * Make server more resilient against bad requests, including empty message lists
226
+ * Perform subscription validation on the server and use errbacks to signal errors
227
+ * Prohibit publishing to wildcard channels
228
+ * Unsubscribing from a channel is now O(1) instead of O(N)
229
+ * Much more thorough and consistent unit test coverage of both versions
230
+ * Automatic integration tests using Terminus and TestSwarm
231
+
232
+
233
+ ### 0.5.5 / 2011-01-16
234
+
235
+ * Open a real socket to check for WebSocket usability, not just object detection
236
+ * Catch server-side errors when handshaking with WebSockets
237
+
238
+
239
+ ### 0.5.4 / 2010-12-19
240
+
241
+ * Add a `#callback` method to `Subscriptions` to detect when they become active
242
+ * Add `:extensions` option to `RackAdapter` to make it easier to extend middleware
243
+ * Detect secure WebSocket requests through the `HTTP_X_FORWARDED_PROTO` header
244
+ * Handle socket errors when sending WebSocket messages from `NodeAdapter`
245
+ * Use exponential backoff to reconnect client-side WebSockets to reduce CPU load
246
+
247
+
248
+ ### 0.5.3 / 2010-10-21
249
+
250
+ * Improve detection of `wss:` requirement for secure WebSocket connections
251
+ * Correctly use default ports (80,443) for server-side HTTP connections
252
+ * Support legacy `application/x-www-form-urlencoded` POST requests
253
+ * Delete unused Channel objects that have all their subscribers removed
254
+ * Fix resend/reconnect logic in WebSocket transport
255
+ * Keep client script in memory rather than reading it from disk every time
256
+ * Prevent error-adding extensions from breaking the core protocol
257
+
258
+
259
+ ### 0.5.2 / 2010-08-12
260
+
261
+ * Support draft-76 of the WebSocket protocol (FF4, Chrome 6)
262
+ * Reduce `Connection::MAX_DELAY` to improve latency
263
+
264
+
265
+ ### 0.5.1 / 2010-07-21
266
+
267
+ * Fix a publishing problem in Ruby `LocalTransport`
268
+
269
+
270
+ ### 0.5.0 / 2010-07-17
271
+
272
+ * Handle multiple event listeners bound to a channel
273
+ * Add extension system for adding domain-specific logic to the protocol
274
+ * Improve handling of client reconnections if the server goes down
275
+ * Change default polling interval to 0 (immediate reconnect)
276
+ * Add support for WebSockets (draft75 only) as a network transport
277
+ * Remove support for Ruby servers other than Thin
278
+ * Make client and server compatible with CometD (1.x and 2.0) components
279
+ * Improve clean-up of unused server-side connections
280
+ * Change Node API for adding Faye service to an HTTP server
281
+
282
+
283
+ ### 0.3.4 / 2010-06-20
284
+
285
+ * Stop local clients going into an infinite loop if a subscription block causes a reconnect
286
+
287
+
288
+ ### 0.3.3 / 2010-06-07
289
+
290
+ * Bring Node APIs up to date with 0.1.97
291
+ * Catch `ECONNREFUSED` errors in Node clients to withstand server outages
292
+ * Refactor the `Server` internals
293
+
294
+
295
+ ### 0.3.2 / 2010-04-04
296
+
297
+ * Fix problems with JSON serialization when Prototype, MooTools present
298
+ * Make the client reconnect if it doesn't hear from the server after a timeout
299
+ * Stop JavaScript server returning `NaN` for `advice.interval`
300
+ * Make Ruby server return an integer for `advice.interval`
301
+ * Ensure EventMachine is running before handling messages
302
+ * Handle `data` and `end` events properly in Node HTTP API
303
+ * Switch to `application/json` for content types and stop using querystring format in POST bodies
304
+ * Respond to any URL path under the mount point, not just the exact match
305
+
306
+
307
+ ### 0.3.1 / 2010-03-09
308
+
309
+ * Pass client down through Rack stack as `env['faye.client']`
310
+ * Refactor some JavaScript internals to mirror Ruby codebase
311
+
312
+
313
+ ### 0.3.0 / 2010-03-01
314
+
315
+ * Add server-side clients for Node.js and Ruby environments
316
+ * Clients support both HTTP and in-process transports
317
+ * Fix ID generation in JavaScript version to 128-bit IDs
318
+ * Fix bug in interpretation of `**` channel wildcard
319
+ * Users don't have to call `#connect()` on clients any more
320
+ * Fix timeout race conditions that were killing active connections
321
+ * Support new Node APIs from 0.1.29.
322
+
323
+
324
+ ### 0.2.2 / 2010-02-10
325
+
326
+ * Kick out requests with malformed JSON as 400s
327
+
328
+
329
+ ### 0.2.1 / 2010-02-04
330
+
331
+ * Fix server-side flushing of callback-polling connections
332
+ * Backend can be used cross-domain if running on Node or Thin
333
+
334
+
335
+ ### 0.2.0 / 2010-02-02
336
+
337
+ * Port server to JavaScript with an adapter for Node.js
338
+ * Support Thin's async responses in the Ruby version for complete non-blocking
339
+ * Fix some minor client-side bugs in transport choice
340
+
341
+
342
+ ### 0.1.1 / 2009-07-26
343
+
344
+ * Fix a broken client build
345
+
346
+
347
+ ### 0.1.0 / 2009-06-15
348
+
349
+ * Ruby Bayeux server and Rack adapter
350
+ * Internally evented using EventMachine, web frontend blocks
351
+ * JavaScript client with `long-polling` and `callback-polling`
@@ -0,0 +1,35 @@
1
+ # Faye
2
+
3
+ Faye is a set of tools for simple publish-subscribe messaging between web
4
+ clients. It ships with easy-to-use message routing servers for Node.js and Rack
5
+ applications, and clients that can be used on the server and in the browser.
6
+
7
+ * Documentation: http://faye.jcoglan.com
8
+ * Mailing list: http://groups.google.com/group/faye-users
9
+ * Bug tracker: http://github.com/faye/faye/issues
10
+ * Source code: http://github.com/faye/faye
11
+
12
+
13
+ ## License
14
+
15
+ (The MIT License)
16
+
17
+ Copyright (c) 2009-2014 James Coglan and contributors
18
+
19
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
20
+ this software and associated documentation files (the 'Software'), to deal in
21
+ the Software without restriction, including without limitation the rights to
22
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
23
+ of the Software, and to permit persons to whom the Software is furnished to do
24
+ so, subject to the following conditions:
25
+
26
+ The above copyright notice and this permission notice shall be included in all
27
+ copies or substantial portions of the Software.
28
+
29
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ !function(){"use strict";var Faye={VERSION:"1.0.3",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:"undefined"!=typeof window?window:global,extend:function(e,t,n){if(!t)return e;for(var i in t)t.hasOwnProperty(i)&&(e.hasOwnProperty(i)&&n===!1||e[i]!==t[i]&&(e[i]=t[i]));return e},random:function(e){e=e||this.ID_LENGTH;for(var t=Math.ceil(e*Math.log(2)/Math.log(36)),n=csprng(e,36);n.length<t;)n="0"+n;return n},clientIdFromMessages:function(e){var t=this.filter([].concat(e),function(e){return"/meta/connect"===e.channel});return t[0]&&t[0].clientId},copyObject:function(e){var t,n,i;if(e instanceof Array){for(t=[],n=e.length;n--;)t[n]=Faye.copyObject(e[n]);return t}if("object"==typeof e){t=null===e?null:{};for(i in e)t[i]=Faye.copyObject(e[i]);return t}return e},commonElement:function(e,t){for(var n=0,i=e.length;i>n;n++)if(-1!==this.indexOf(t,e[n]))return e[n];return null},indexOf:function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,i=e.length;i>n;n++)if(e[n]===t)return n;return-1},map:function(e,t,n){if(e.map)return e.map(t,n);var i=[];if(e instanceof Array)for(var s=0,r=e.length;r>s;s++)i.push(t.call(n||null,e[s],s));else for(var o in e)e.hasOwnProperty(o)&&i.push(t.call(n||null,o,e[o]));return i},filter:function(e,t,n){if(e.filter)return e.filter(t,n);for(var i=[],s=0,r=e.length;r>s;s++)t.call(n||null,e[s],s)&&i.push(e[s]);return i},asyncEach:function(e,t,n,i){var s=e.length,r=-1,o=0,a=!1,c=function(){return o-=1,r+=1,r===s?n&&n.call(i):void t(e[r],u)},h=function(){if(!a){for(a=!0;o>0;)c();a=!1}},u=function(){o+=1,h()};u()},toJSON:function(e){return this.stringify?this.stringify(e,function(e,t){return this[e]instanceof Array?this[e]:t}):JSON.stringify(e)}};"undefined"!=typeof module?module.exports=Faye:"undefined"!=typeof window&&(window.Faye=Faye),Faye.Class=function(e,t){"function"!=typeof e&&(t=e,e=Object);var n=function(){return this.initialize?this.initialize.apply(this,arguments)||this:this},i=function(){};return i.prototype=e.prototype,n.prototype=new i,Faye.extend(n.prototype,t),n},function(){function e(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;n++)if(t===e[n])return n;return-1}var t=Faye.EventEmitter=function(){},n="function"==typeof Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};t.prototype.emit=function(e){if("error"===e&&(!this._events||!this._events.error||n(this._events.error)&&!this._events.error.length))throw arguments[1]instanceof Error?arguments[1]:Error("Uncaught, unspecified 'error' event.");if(!this._events)return!1;var t=this._events[e];if(!t)return!1;if("function"==typeof t){switch(arguments.length){case 1:t.call(this);break;case 2:t.call(this,arguments[1]);break;case 3:t.call(this,arguments[1],arguments[2]);break;default:var i=Array.prototype.slice.call(arguments,1);t.apply(this,i)}return!0}if(n(t)){for(var i=Array.prototype.slice.call(arguments,1),s=t.slice(),r=0,o=s.length;o>r;r++)s[r].apply(this,i);return!0}return!1},t.prototype.addListener=function(e,t){if("function"!=typeof t)throw Error("addListener only takes instances of Function");return this._events||(this._events={}),this.emit("newListener",e,t),this._events[e]?n(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,this},t.prototype.on=t.prototype.addListener,t.prototype.once=function(e,t){var n=this;return n.on(e,function i(){n.removeListener(e,i),t.apply(this,arguments)}),this},t.prototype.removeListener=function(t,i){if("function"!=typeof i)throw Error("removeListener only takes instances of Function");if(!this._events||!this._events[t])return this;var s=this._events[t];if(n(s)){var r=e(s,i);if(0>r)return this;s.splice(r,1),0==s.length&&delete this._events[t]}else this._events[t]===i&&delete this._events[t];return this},t.prototype.removeAllListeners=function(e){return 0===arguments.length?(this._events={},this):(e&&this._events&&this._events[e]&&(this._events[e]=null),this)},t.prototype.listeners=function(e){return this._events||(this._events={}),this._events[e]||(this._events[e]=[]),n(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]}}(),Faye.Namespace=Faye.Class({initialize:function(){this._used={}},exists:function(e){return this._used.hasOwnProperty(e)},generate:function(){for(var e=Faye.random();this._used.hasOwnProperty(e);)e=Faye.random();return this._used[e]=e},release:function(e){delete this._used[e]}}),function(){var e,t=setTimeout;e="function"==typeof setImmediate?function(e){setImmediate(e)}:"object"==typeof process&&process.nextTick?function(e){process.nextTick(e)}:function(e){t(e,0)};var n=0,i=1,s=2,r=function(e){return e},o=function(e){throw e},a=function(e){if(this._state=n,this._onFulfilled=[],this._onRejected=[],"function"==typeof e){var t=this;e(function(e){f(t,e)},function(e){d(t,e)})}};a.prototype.then=function(e,t){var n=new a;return c(this,e,n),h(this,t,n),n};var c=function(e,t,s){"function"!=typeof t&&(t=r);var o=function(e){u(t,e,s)};e._state===n?e._onFulfilled.push(o):e._state===i&&o(e._value)},h=function(e,t,i){"function"!=typeof t&&(t=o);var r=function(e){u(t,e,i)};e._state===n?e._onRejected.push(r):e._state===s&&r(e._reason)},u=function(t,n,i){e(function(){l(t,n,i)})},l=function(e,t,n){var i;try{i=e(t)}catch(s){return d(n,s)}i===n?d(n,new TypeError("Recursive promise chain detected")):f(n,i)},f=a.fulfill=a.resolve=function(e,t){var n,i,s=!1;try{if(n=typeof t,i=null!==t&&("function"===n||"object"===n)&&t.then,"function"!=typeof i)return p(e,t);i.call(t,function(t){s^(s=!0)&&f(e,t)},function(t){s^(s=!0)&&d(e,t)})}catch(r){if(!(s^(s=!0)))return;d(e,r)}},p=function(e,t){if(e._state===n){e._state=i,e._value=t,e._onRejected=[];for(var s,r=e._onFulfilled;s=r.shift();)s(t)}},d=a.reject=function(e,t){if(e._state===n){e._state=s,e._reason=t,e._onFulfilled=[];for(var i,r=e._onRejected;i=r.shift();)i(t)}};a.all=function(e){return new a(function(t,n){var i,s=[],r=e.length;if(0===r)return t(s);for(i=0;r>i;i++)(function(e,i){a.fulfilled(e).then(function(e){s[i]=e,0===--r&&t(s)},n)})(e[i],i)})},a.defer=e,a.deferred=a.pending=function(){var e={};return e.promise=new a(function(t,n){e.fulfill=e.resolve=t,e.reject=n}),e},a.fulfilled=a.resolved=function(e){return new a(function(t){t(e)})},a.rejected=function(e){return new a(function(t,n){n(e)})},void 0===Faye?module.exports=a:Faye.Promise=a}(),Faye.Set=Faye.Class({initialize:function(){this._index={}},add:function(e){var t=void 0!==e.id?e.id:e;return this._index.hasOwnProperty(t)?!1:(this._index[t]=e,!0)},forEach:function(e,t){for(var n in this._index)this._index.hasOwnProperty(n)&&e.call(t,this._index[n])},isEmpty:function(){for(var e in this._index)if(this._index.hasOwnProperty(e))return!1;return!0},member:function(e){for(var t in this._index)if(this._index[t]===e)return!0;return!1},remove:function(e){var t=void 0!==e.id?e.id:e,n=this._index[t];return delete this._index[t],n},toArray:function(){var e=[];return this.forEach(function(t){e.push(t)}),e}}),Faye.URI={isURI:function(e){return e&&e.protocol&&e.host&&e.path},isSameOrigin:function(e){var t=Faye.ENV.location;return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port},parse:function(e){if("string"!=typeof e)return e;var t,n,i,s,r,o,a={},c=function(t,n){e=e.replace(n,function(e){return a[t]=e,""}),a[t]=a[t]||""};for(c("protocol",/^[a-z]+\:/i),c("host",/^\/\/[^\/\?#]+/),/^\//.test(e)||a.host||(e=Faye.ENV.location.pathname.replace(/[^\/]*$/,"")+e),c("pathname",/^[^\?#]*/),c("search",/^\?[^#]*/),c("hash",/^#.*/),a.protocol=a.protocol||Faye.ENV.location.protocol,a.host?(a.host=a.host.substr(2),t=a.host.split(":"),a.hostname=t[0],a.port=t[1]||""):(a.host=Faye.ENV.location.host,a.hostname=Faye.ENV.location.hostname,a.port=Faye.ENV.location.port),a.pathname=a.pathname||"/",a.path=a.pathname+a.search,n=a.search.replace(/^\?/,""),i=n?n.split("&"):[],o={},s=0,r=i.length;r>s;s++)t=i[s].split("="),o[decodeURIComponent(t[0]||"")]=decodeURIComponent(t[1]||"");return a.query=o,a.href=this.stringify(a),a},stringify:function(e){var t=e.protocol+"//"+e.hostname;return e.port&&(t+=":"+e.port),t+=e.pathname+this.queryString(e.query)+(e.hash||"")},queryString:function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return 0===t.length?"":"?"+t.join("&")}},Faye.Error=Faye.Class({initialize:function(e,t,n){this.code=e,this.params=Array.prototype.slice.call(t),this.message=n},toString:function(){return this.code+":"+this.params.join(",")+":"+this.message}}),Faye.Error.parse=function(e){if(e=e||"",!Faye.Grammar.ERROR.test(e))return new this(null,[],e);var t=e.split(":"),n=parseInt(t[0]),i=t[1].split(","),e=t[2];return new this(n,i,e)},Faye.Error.versionMismatch=function(){return""+new this(300,arguments,"Version mismatch")},Faye.Error.conntypeMismatch=function(){return""+new this(301,arguments,"Connection types not supported")},Faye.Error.extMismatch=function(){return""+new this(302,arguments,"Extension mismatch")},Faye.Error.badRequest=function(){return""+new this(400,arguments,"Bad request")},Faye.Error.clientUnknown=function(){return""+new this(401,arguments,"Unknown client")},Faye.Error.parameterMissing=function(){return""+new this(402,arguments,"Missing required parameter")},Faye.Error.channelForbidden=function(){return""+new this(403,arguments,"Forbidden channel")},Faye.Error.channelUnknown=function(){return""+new this(404,arguments,"Unknown channel")},Faye.Error.channelInvalid=function(){return""+new this(405,arguments,"Invalid channel")},Faye.Error.extUnknown=function(){return""+new this(406,arguments,"Unknown extension")},Faye.Error.publishFailed=function(){return""+new this(407,arguments,"Failed to publish")},Faye.Error.serverError=function(){return""+new this(500,arguments,"Internal server error")},Faye.Deferrable={then:function(e,t){var n=this;return this._promise||(this._promise=new Faye.Promise(function(e,t){n._fulfill=e,n._reject=t})),0===arguments.length?this._promise:this._promise.then(e,t)},callback:function(e,t){return this.then(function(n){e.call(t,n)})},errback:function(e,t){return this.then(null,function(n){e.call(t,n)})},timeout:function(e,t){this.then();var n=this;this._timer=Faye.ENV.setTimeout(function(){n._reject(t)},1e3*e)},setDeferredStatus:function(e,t){this._timer&&Faye.ENV.clearTimeout(this._timer),this.then(),"succeeded"===e?this._fulfill(t):"failed"===e?this._reject(t):delete this._promise}},Faye.Publisher={countListeners:function(e){return this.listeners(e).length},bind:function(e,t,n){var i=Array.prototype.slice,s=function(){t.apply(n,i.call(arguments))};return this._listeners=this._listeners||[],this._listeners.push([e,t,n,s]),this.on(e,s)},unbind:function(e,t,n){this._listeners=this._listeners||[];for(var i,s=this._listeners.length;s--;)i=this._listeners[s],i[0]===e&&(!t||i[1]===t&&i[2]===n)&&(this._listeners.splice(s,1),this.removeListener(e,i[3]))}},Faye.extend(Faye.Publisher,Faye.EventEmitter.prototype),Faye.Publisher.trigger=Faye.Publisher.emit,Faye.Timeouts={addTimeout:function(e,t,n,i){if(this._timeouts=this._timeouts||{},!this._timeouts.hasOwnProperty(e)){var s=this;this._timeouts[e]=Faye.ENV.setTimeout(function(){delete s._timeouts[e],n.call(i)},1e3*t)}},removeTimeout:function(e){this._timeouts=this._timeouts||{};var t=this._timeouts[e];t&&(Faye.ENV.clearTimeout(t),delete this._timeouts[e])},removeAllTimeouts:function(){this._timeouts=this._timeouts||{};for(var e in this._timeouts)this.removeTimeout(e)}},Faye.Logging={LOG_LEVELS:{fatal:4,error:3,warn:2,info:1,debug:0},writeLog:function(e,t){if(Faye.logger){var n=Array.prototype.slice.apply(e),i="[Faye",s=this.className,r=n.shift().replace(/\?/g,function(){try{return Faye.toJSON(n.shift())}catch(e){return"[Object]"}});for(var o in Faye)s||"function"==typeof Faye[o]&&this instanceof Faye[o]&&(s=o);s&&(i+="."+s),i+="] ","function"==typeof Faye.logger[t]?Faye.logger[t](i+r):"function"==typeof Faye.logger&&Faye.logger(i+r)}}},function(){for(var e in Faye.Logging.LOG_LEVELS)(function(e){Faye.Logging[e]=function(){this.writeLog(arguments,e)}})(e)}(),Faye.Grammar={CHANNEL_NAME:/^\/(((([a-z]|[A-Z])|[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(e){this._extensions=this._extensions||[],this._extensions.push(e),e.added&&e.added(this)},removeExtension:function(e){if(this._extensions)for(var t=this._extensions.length;t--;)this._extensions[t]===e&&(this._extensions.splice(t,1),e.removed&&e.removed(this))},pipeThroughExtensions:function(e,t,n,i,s){if(this.debug("Passing through ? extensions: ?",e,t),!this._extensions)return i.call(s,t);var r=this._extensions.slice(),o=function(t){if(!t)return i.call(s,t);var a=r.shift();if(!a)return i.call(s,t);var c=a[e];return c?void(c.length>=3?a[e](t,n,o):a[e](t,o)):o(t)};o(t)}},Faye.extend(Faye.Extensible,Faye.Logging),Faye.Channel=Faye.Class({initialize:function(e){this.id=this.name=e},push:function(e){this.trigger("message",e)},isUnused:function(){return 0===this.countListeners("message")}}),Faye.extend(Faye.Channel.prototype,Faye.Publisher),Faye.extend(Faye.Channel,{HANDSHAKE:"/meta/handshake",CONNECT:"/meta/connect",SUBSCRIBE:"/meta/subscribe",UNSUBSCRIBE:"/meta/unsubscribe",DISCONNECT:"/meta/disconnect",META:"meta",SERVICE:"service",expand:function(e){var t=this.parse(e),n=["/**",e],i=t.slice();i[i.length-1]="*",n.push(this.unparse(i));for(var s=1,r=t.length;r>s;s++)i=t.slice(0,s),i.push("**"),n.push(this.unparse(i));return n},isValid:function(e){return Faye.Grammar.CHANNEL_NAME.test(e)||Faye.Grammar.CHANNEL_PATTERN.test(e)},parse:function(e){return this.isValid(e)?e.split("/").slice(1):null},unparse:function(e){return"/"+e.join("/")},isMeta:function(e){var t=this.parse(e);return t?t[0]===this.META:null},isService:function(e){var t=this.parse(e);return t?t[0]===this.SERVICE:null},isSubscribable:function(e){return this.isValid(e)?!this.isMeta(e)&&!this.isService(e):null},Set:Faye.Class({initialize:function(){this._channels={}},getKeys:function(){var e=[];for(var t in this._channels)e.push(t);return e},remove:function(e){delete this._channels[e]},hasSubscription:function(e){return this._channels.hasOwnProperty(e)},subscribe:function(e,t,n){for(var i,s=0,r=e.length;r>s;s++){i=e[s];var o=this._channels[i]=this._channels[i]||new Faye.Channel(i);t&&o.bind("message",t,n)}},unsubscribe:function(e,t,n){var i=this._channels[e];return i?(i.unbind("message",t,n),i.isUnused()?(this.remove(e),!0):!1):!1},distributeMessage:function(e){for(var t=Faye.Channel.expand(e.channel),n=0,i=t.length;i>n;n++){var s=this._channels[t[n]];s&&s.trigger("message",e.data)}}})}),Faye.Publication=Faye.Class(Faye.Deferrable),Faye.Subscription=Faye.Class({initialize:function(e,t,n,i){this._client=e,this._channels=t,this._callback=n,this._context=i,this._cancelled=!1},cancel:function(){this._cancelled||(this._client.unsubscribe(this._channels,this._callback,this._context),this._cancelled=!0)},unsubscribe:function(){this.cancel()}}),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,DEFAULT_ENDPOINT:"/bayeux",INTERVAL:0,initialize:function(e,t){this.info("New client created for ?",e),t=t||{},this._endpoint=e||this.DEFAULT_ENDPOINT,this._channels=new Faye.Channel.Set,this._dispatcher=new Faye.Dispatcher(this,this._endpoint,t),this._messageId=0,this._state=this.UNCONNECTED,this._responseCallbacks={},this._advice={reconnect:this.RETRY,interval:1e3*(t.interval||this.INTERVAL),timeout:1e3*(t.timeout||this.CONNECTION_TIMEOUT)},this._dispatcher.timeout=this._advice.timeout/1e3,this._dispatcher.bind("message",this._receiveMessage,this),Faye.Event&&void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",function(){Faye.indexOf(this._dispatcher._disabled,"autodisconnect")<0&&this.disconnect()},this)},disable:function(e){return this._dispatcher.disable(e)},setHeader:function(e,t){return this._dispatcher.setHeader(e,t)},handshake:function(e,t){if(this._advice.reconnect!==this.NONE&&this._state===this.UNCONNECTED){this._state=this.CONNECTING;var n=this;this.info("Initiating handshake with ?",Faye.URI.stringify(this._endpoint)),this._dispatcher.selectTransport(Faye.MANDATORY_CONNECTION_TYPES),this._sendMessage({channel:Faye.Channel.HANDSHAKE,version:Faye.BAYEUX_VERSION,supportedConnectionTypes:[this._dispatcher.connectionType]},{},function(i){i.successful?(this._state=this.CONNECTED,this._dispatcher.clientId=i.clientId,this._dispatcher.selectTransport(i.supportedConnectionTypes),this.info("Handshake successful: ?",this._dispatcher.clientId),this.subscribe(this._channels.getKeys(),!0),e&&Faye.Promise.defer(function(){e.call(t)})):(this.info("Handshake unsuccessful"),Faye.ENV.setTimeout(function(){n.handshake(e,t)},1e3*this._dispatcher.retry),this._state=this.UNCONNECTED)},this)}},connect:function(e,t){if(this._advice.reconnect!==this.NONE&&this._state!==this.DISCONNECTED){if(this._state===this.UNCONNECTED)return this.handshake(function(){this.connect(e,t)},this);this.callback(e,t),this._state===this.CONNECTED&&(this.info("Calling deferred actions for ?",this._dispatcher.clientId),this.setDeferredStatus("succeeded"),this.setDeferredStatus("unknown"),this._connectRequest||(this._connectRequest=!0,this.info("Initiating connection for ?",this._dispatcher.clientId),this._sendMessage({channel:Faye.Channel.CONNECT,clientId:this._dispatcher.clientId,connectionType:this._dispatcher.connectionType},{},this._cycleConnection,this)))}},disconnect:function(){this._state===this.CONNECTED&&(this._state=this.DISCONNECTED,this.info("Disconnecting ?",this._dispatcher.clientId),this._sendMessage({channel:Faye.Channel.DISCONNECT,clientId:this._dispatcher.clientId},{},function(e){e.successful&&this._dispatcher.close()},this),this.info("Clearing channel listeners for ?",this._dispatcher.clientId),this._channels=new Faye.Channel.Set)},subscribe:function(e,t,n){if(e instanceof Array)return Faye.map(e,function(e){return this.subscribe(e,t,n)},this);var i=new Faye.Subscription(this,e,t,n),s=t===!0,r=this._channels.hasSubscription(e);return r&&!s?(this._channels.subscribe([e],t,n),i.setDeferredStatus("succeeded"),i):(this.connect(function(){this.info("Client ? attempting to subscribe to ?",this._dispatcher.clientId,e),s||this._channels.subscribe([e],t,n),this._sendMessage({channel:Faye.Channel.SUBSCRIBE,clientId:this._dispatcher.clientId,subscription:e},{},function(s){if(!s.successful)return i.setDeferredStatus("failed",Faye.Error.parse(s.error)),this._channels.unsubscribe(e,t,n);var r=[].concat(s.subscription);this.info("Subscription acknowledged for ? to ?",this._dispatcher.clientId,r),i.setDeferredStatus("succeeded")},this)},this),i)},unsubscribe:function(e,t,n){if(e instanceof Array)return Faye.map(e,function(e){return this.unsubscribe(e,t,n)},this);var i=this._channels.unsubscribe(e,t,n);i&&this.connect(function(){this.info("Client ? attempting to unsubscribe from ?",this._dispatcher.clientId,e),this._sendMessage({channel:Faye.Channel.UNSUBSCRIBE,clientId:this._dispatcher.clientId,subscription:e},{},function(e){if(e.successful){var t=[].concat(e.subscription);this.info("Unsubscription acknowledged for ? from ?",this._dispatcher.clientId,t)}},this)},this)},publish:function(e,t,n){var i=new Faye.Publication;return this.connect(function(){this.info("Client ? queueing published message to ?: ?",this._dispatcher.clientId,e,t),this._sendMessage({channel:e,data:t,clientId:this._dispatcher.clientId},n,function(e){e.successful?i.setDeferredStatus("succeeded"):i.setDeferredStatus("failed",Faye.Error.parse(e.error))},this)},this),i},_sendMessage:function(e,t,n,i){e.id=this._generateMessageId();var s=this._advice.timeout?1.2*this._advice.timeout/1e3:1.2*this._dispatcher.retry;this.pipeThroughExtensions("outgoing",e,null,function(e){e&&(n&&(this._responseCallbacks[e.id]=[n,i]),this._dispatcher.sendMessage(e,s,t||{}))},this)},_generateMessageId:function(){return this._messageId+=1,this._messageId>=Math.pow(2,32)&&(this._messageId=0),this._messageId.toString(36)},_receiveMessage:function(e){var t,n=e.id;void 0!==e.successful&&(t=this._responseCallbacks[n],delete this._responseCallbacks[n]),this.pipeThroughExtensions("incoming",e,null,function(e){e&&(e.advice&&this._handleAdvice(e.advice),this._deliverMessage(e),t&&t[0].call(t[1],e))},this)},_handleAdvice:function(e){Faye.extend(this._advice,e),this._dispatcher.timeout=this._advice.timeout/1e3,this._advice.reconnect===this.HANDSHAKE&&this._state!==this.DISCONNECTED&&(this._state=this.UNCONNECTED,this._dispatcher.clientId=null,this._cycleConnection())},_deliverMessage:function(e){e.channel&&void 0!==e.data&&(this.info("Client ? calling listeners for ? with ?",this._dispatcher.clientId,e.channel,e.data),this._channels.distributeMessage(e))},_cycleConnection:function(){this._connectRequest&&(this._connectRequest=null,this.info("Closed connection for ?",this._dispatcher.clientId));var e=this;Faye.ENV.setTimeout(function(){e.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.Dispatcher=Faye.Class({MAX_REQUEST_SIZE:2048,DEFAULT_RETRY:5,UP:1,DOWN:2,initialize:function(e,t,n){this._client=e,this.endpoint=Faye.URI.parse(t),this._alternates=n.endpoints||{},this.ca=n.ca,this.cookies=Faye.Cookies&&new Faye.Cookies.CookieJar,this._disabled=[],this._envelopes={},this.headers={},this.retry=n.retry||this.DEFAULT_RETRY,this._state=0,this.transports={};for(var i in this._alternates)this._alternates[i]=Faye.URI.parse(this._alternates[i]);this.maxRequestSize=this.MAX_REQUEST_SIZE},endpointFor:function(e){return this._alternates[e]||this.endpoint},disable:function(e){this._disabled.push(e)},setHeader:function(e,t){this.headers[e]=t},close:function(){var e=this._transport;delete this._transport,e&&e.close()},selectTransport:function(e){Faye.Transport.get(this,e,this._disabled,function(e){this.debug("Selected ? transport for ?",e.connectionType,Faye.URI.stringify(e.endpoint)),e!==this._transport&&(this._transport&&this._transport.close(),this._transport=e,this.connectionType=e.connectionType)},this)},sendMessage:function(e,t,n){if(this._transport){n=n||{};var i=this,s=e.id,r=n.attempts,o=n.deadline&&(new Date).getTime()+1e3*n.deadline,a=this._envelopes[s]=this._envelopes[s]||{message:e,timeout:t,attempts:r,deadline:o};if(!a.request&&!a.timer){if(this._attemptsExhausted(a)||this._deadlinePassed(a))return void delete this._envelopes[s];a.timer=Faye.ENV.setTimeout(function(){i.handleError(e)},1e3*t),a.request=this._transport.sendMessage(e)}}},handleResponse:function(e){var t=this._envelopes[e.id];void 0!==e.successful&&t&&(delete this._envelopes[e.id],Faye.ENV.clearTimeout(t.timer)),this.trigger("message",e),this._state!==this.UP&&(this._state=this.UP,this._client.trigger("transport:up"))},handleError:function(e,t){var n=this._envelopes[e.id],i=n&&n.request,s=this;i&&(i.then(function(e){e&&e.abort&&e.abort()}),Faye.ENV.clearTimeout(n.timer),n.request=n.timer=null,t?this.sendMessage(n.message,n.timeout):n.timer=Faye.ENV.setTimeout(function(){n.timer=null,s.sendMessage(n.message,n.timeout)},1e3*this.retry),this._state!==this.DOWN&&(this._state=this.DOWN,this._client.trigger("transport:down")))},_attemptsExhausted:function(e){return void 0===e.attempts?!1:(e.attempts-=1,e.attempts>=0?!1:!0)},_deadlinePassed:function(e){var t=e.deadline;return void 0===t?!1:(new Date).getTime()<=t?!1:!0}}),Faye.extend(Faye.Dispatcher.prototype,Faye.Publisher),Faye.extend(Faye.Dispatcher.prototype,Faye.Logging),Faye.Transport=Faye.extend(Faye.Class({MAX_DELAY:0,batching:!0,initialize:function(e,t){this._dispatcher=e,this.endpoint=t,this._outbox=[]},close:function(){},encode:function(){return""},sendMessage:function(e){return this.debug("Client ? sending message to ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),e),this.batching?(this._outbox.push(e),this._flushLargeBatch(),this._promise=this._promise||new Faye.Promise,e.channel===Faye.Channel.HANDSHAKE?(this.addTimeout("publish",.01,this._flush,this),this._promise):(e.channel===Faye.Channel.CONNECT&&(this._connectMessage=e),this.addTimeout("publish",this.MAX_DELAY,this._flush,this),this._promise)):Faye.Promise.fulfilled(this.request([e]))},_flush:function(){this.removeTimeout("publish"),this._outbox.length>1&&this._connectMessage&&(this._connectMessage.advice={timeout:0}),Faye.Promise.fulfill(this._promise,this.request(this._outbox)),delete this._promise,this._connectMessage=null,this._outbox=[]},_flushLargeBatch:function(){var e=this.encode(this._outbox);if(!(e.length<this._dispatcher.maxRequestSize)){var t=this._outbox.pop();this._flush(),t&&this._outbox.push(t)}},_receive:function(e){e=[].concat(e),this.debug("Client ? received from ? via ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),this.connectionType,e);for(var t=0,n=e.length;n>t;t++)this._dispatcher.handleResponse(e[t])},_handleError:function(e){e=[].concat(e),this.debug("Client ? failed to send to ? via ?: ?",this._dispatcher.clientId,Faye.URI.stringify(this.endpoint),this.connectionType,e);for(var t=0,n=e.length;n>t;t++)this._dispatcher.handleError(e[t])},_getCookies:function(){var e=this._dispatcher.cookies,t=Faye.URI.stringify(this.endpoint);return e?Faye.map(e.getCookiesSync(t),function(e){return e.cookieString()}).join("; "):""},_storeCookies:function(e){var t,n=this._dispatcher.cookies,i=Faye.URI.stringify(this.endpoint);if(e&&n){e=[].concat(e);for(var s=0,r=e.length;r>s;s++)t=Faye.Cookies.Cookie.parse(e[s]),n.setCookieSync(t,i)}}}),{get:function(e,t,n,i,s){var r=e.endpoint;Faye.asyncEach(this._transports,function(r,o){var a=r[0],c=r[1],h=e.endpointFor(a);return Faye.indexOf(n,a)>=0?o():Faye.indexOf(t,a)<0?(c.isUsable(e,h,function(){}),o()):void c.isUsable(e,h,function(t){if(!t)return o();var n=c.hasOwnProperty("create")?c.create(e,h):new c(e,h);i.call(s,n)})},function(){throw Error("Could not find a usable connection type for "+Faye.URI.stringify(r))})},register:function(e,t){this._transports.push([e,t]),t.prototype.connectionType=e},_transports:[]}),Faye.extend(Faye.Transport.prototype,Faye.Logging),Faye.extend(Faye.Transport.prototype,Faye.Timeouts),Faye.Event={_registry:[],on:function(e,t,n,i){var s=function(){n.call(i)};e.addEventListener?e.addEventListener(t,s,!1):e.attachEvent("on"+t,s),this._registry.push({_element:e,_type:t,_callback:n,_context:i,_handler:s})},detach:function(e,t,n,i){for(var s,r=this._registry.length;r--;)s=this._registry[r],e&&e!==s._element||t&&t!==s._type||n&&n!==s._callback||i&&i!==s._context||(s._element.removeEventListener?s._element.removeEventListener(s._type,s._handler,!1):s._element.detachEvent("on"+s._type,s._handler),this._registry.splice(r,1),s=null)}},void 0!==Faye.ENV.onunload&&Faye.Event.on(Faye.ENV,"unload",Faye.Event.detach,Faye.Event),"object"!=typeof JSON&&(JSON={}),function(){function f(e){return 10>e?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,i,s,r,o,a=gap,c=t[e];switch(c&&"object"==typeof c&&"function"==typeof c.toJSON&&(c=c.toJSON(e)),"function"==typeof rep&&(c=rep.call(t,e,c)),typeof c){case"string":return quote(c);case"number":return isFinite(c)?c+"":"null";case"boolean":case"null":return c+"";case"object":if(!c)return"null";if(gap+=indent,o=[],"[object Array]"===Object.prototype.toString.apply(c)){for(r=c.length,n=0;r>n;n+=1)o[n]=str(n,c)||"null";return s=0===o.length?"[]":gap?"[\n"+gap+o.join(",\n"+gap)+"\n"+a+"]":"["+o.join(",")+"]",gap=a,s}if(rep&&"object"==typeof rep)for(r=rep.length,n=0;r>n;n+=1)"string"==typeof rep[n]&&(i=rep[n],s=str(i,c),s&&o.push(quote(i)+(gap?": ":":")+s));else for(i in c)Object.prototype.hasOwnProperty.call(c,i)&&(s=str(i,c),s&&o.push(quote(i)+(gap?": ":":")+s));return s=0===o.length?"{}":gap?"{\n"+gap+o.join(",\n"+gap)+"\n"+a+"}":"{"+o.join(",")+"}",gap=a,s}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){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(){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,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;Faye.stringify=function(e,t,n){var i;if(gap="",indent="","number"==typeof n)for(i=0;n>i;i+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw Error("JSON.stringify");return str("",{"":e})},"function"!=typeof JSON.stringify&&(JSON.stringify=Faye.stringify),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(e,t){var n,i,s=e[t];if(s&&"object"==typeof s)for(n in s)Object.prototype.hasOwnProperty.call(s,n)&&(i=walk(s,n),void 0!==i?s[n]=i:delete s[n]);return reviver.call(e,t,s)}var j;if(text+="",cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\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,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),Faye.Transport.WebSocket=Faye.extend(Faye.Class(Faye.Transport,{UNCONNECTED:1,CONNECTING:2,CONNECTED:3,batching:!1,isUsable:function(e,t){this.callback(function(){e.call(t,!0)}),this.errback(function(){e.call(t,!1)}),this.connect()},request:function(e){this._pending=this._pending||new Faye.Set;for(var t=0,n=e.length;n>t;t++)this._pending.add(e[t]);var i=new Faye.Promise;return this.callback(function(t){t&&(t.send(Faye.toJSON(e)),Faye.Promise.fulfill(i,t))},this),this.connect(),{abort:function(){i.then(function(e){e.close()})}}},connect:function(){if(!Faye.Transport.WebSocket._unloaded&&(this._state=this._state||this.UNCONNECTED,this._state===this.UNCONNECTED)){this._state=this.CONNECTING;var e=this._createSocket();if(!e)return this.setDeferredStatus("failed");var t=this;e.onopen=function(){e.headers&&t._storeCookies(e.headers["set-cookie"]),t._socket=e,t._state=t.CONNECTED,t._everConnected=!0,t._ping(),t.setDeferredStatus("succeeded",e)};var n=!1;e.onclose=e.onerror=function(){if(!n){n=!0;var i=t._state===t.CONNECTED;e.onopen=e.onclose=e.onerror=e.onmessage=null,delete t._socket,t._state=t.UNCONNECTED,t.removeTimeout("ping"),t.setDeferredStatus("unknown");var s=t._pending?t._pending.toArray():[];delete t._pending,i?t._handleError(s,!0):t._everConnected?t._handleError(s):t.setDeferredStatus("failed")}},e.onmessage=function(e){var n=JSON.parse(e.data);
2
+ if(n){n=[].concat(n);for(var i=0,s=n.length;s>i;i++)void 0!==n[i].successful&&t._pending.remove(n[i]);t._receive(n)}}}},close:function(){this._socket&&this._socket.close()},_createSocket:function(){var e=Faye.Transport.WebSocket.getSocketUrl(this.endpoint),t=Faye.copyObject(this._dispatcher.headers),n={headers:t,ca:this._dispatcher.ca};return n.headers.Cookie=this._getCookies(),Faye.WebSocket?new Faye.WebSocket.Client(e,[],n):Faye.ENV.MozWebSocket?new MozWebSocket(e):Faye.ENV.WebSocket?new WebSocket(e):void 0},_ping:function(){this._socket&&(this._socket.send("[]"),this.addTimeout("ping",this._dispatcher.timeout/2,this._ping,this))}}),{PROTOCOLS:{"http:":"ws:","https:":"wss:"},create:function(e,t){var n=e.transports.websocket=e.transports.websocket||{};return n[t.href]=n[t.href]||new this(e,t),n[t.href]},getSocketUrl:function(e){return e=Faye.copyObject(e),e.protocol=this.PROTOCOLS[e.protocol],Faye.URI.stringify(e)},isUsable:function(e,t,n,i){this.create(e,t).isUsable(n,i)}}),Faye.extend(Faye.Transport.WebSocket.prototype,Faye.Deferrable),Faye.Transport.register("websocket",Faye.Transport.WebSocket),Faye.Event&&void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",function(){Faye.Transport.WebSocket._unloaded=!0}),Faye.Transport.EventSource=Faye.extend(Faye.Class(Faye.Transport,{initialize:function(e,t){if(Faye.Transport.prototype.initialize.call(this,e,t),!Faye.ENV.EventSource)return this.setDeferredStatus("failed");this._xhr=new Faye.Transport.XHR(e,t),t=Faye.copyObject(t),t.pathname+="/"+e.clientId;var n=new EventSource(Faye.URI.stringify(t)),i=this;n.onopen=function(){i._everConnected=!0,i.setDeferredStatus("succeeded")},n.onerror=function(){i._everConnected?i._handleError([]):(i.setDeferredStatus("failed"),n.close())},n.onmessage=function(e){i._receive(JSON.parse(e.data))},this._socket=n},close:function(){this._socket&&(this._socket.onopen=this._socket.onerror=this._socket.onmessage=null,this._socket.close(),delete this._socket)},isUsable:function(e,t){this.callback(function(){e.call(t,!0)}),this.errback(function(){e.call(t,!1)})},encode:function(e){return this._xhr.encode(e)},request:function(e){return this._xhr.request(e)}}),{isUsable:function(e,t,n,i){var s=e.clientId;return s?void Faye.Transport.XHR.isUsable(e,t,function(s){return s?void this.create(e,t).isUsable(n,i):n.call(i,!1)},this):n.call(i,!1)},create:function(e,t){var n=e.transports.eventsource=e.transports.eventsource||{},i=e.clientId;t=Faye.copyObject(t),t.pathname+="/"+(i||"");var s=Faye.URI.stringify(t);return n[s]=n[s]||new this(e,t),n[s]}}),Faye.extend(Faye.Transport.EventSource.prototype,Faye.Deferrable),Faye.Transport.register("eventsource",Faye.Transport.EventSource),Faye.Transport.XHR=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){return Faye.toJSON(e)},request:function(e){var t=this.endpoint.href,n=Faye.ENV.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest,i=this;n.open("POST",t,!0),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("Pragma","no-cache"),n.setRequestHeader("X-Requested-With","XMLHttpRequest");var s=this._dispatcher.headers;for(var r in s)s.hasOwnProperty(r)&&n.setRequestHeader(r,s[r]);var o=function(){n.abort()};return void 0!==Faye.ENV.onbeforeunload&&Faye.Event.on(Faye.ENV,"beforeunload",o),n.onreadystatechange=function(){if(n&&4===n.readyState){var t=null,s=n.status,r=n.responseText,a=s>=200&&300>s||304===s||1223===s;if(void 0!==Faye.ENV.onbeforeunload&&Faye.Event.detach(Faye.ENV,"beforeunload",o),n.onreadystatechange=function(){},n=null,!a)return i._handleError(e);try{t=JSON.parse(r)}catch(c){}t?i._receive(t):i._handleError(e)}},n.send(this.encode(e)),n}}),{isUsable:function(e,t,n,i){n.call(i,Faye.URI.isSameOrigin(t))}}),Faye.Transport.register("long-polling",Faye.Transport.XHR),Faye.Transport.CORS=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){return"message="+encodeURIComponent(Faye.toJSON(e))},request:function(e){var t,n=Faye.ENV.XDomainRequest?XDomainRequest:XMLHttpRequest,i=new n,s=this._dispatcher.headers,r=this;if(i.open("POST",Faye.URI.stringify(this.endpoint),!0),i.setRequestHeader){i.setRequestHeader("Pragma","no-cache");for(t in s)s.hasOwnProperty(t)&&i.setRequestHeader(t,s[t])}var o=function(){return i?(i.onload=i.onerror=i.ontimeout=i.onprogress=null,void(i=null)):!1};return i.onload=function(){var t=null;try{t=JSON.parse(i.responseText)}catch(n){}o(),t?r._receive(t):r._handleError(e)},i.onerror=i.ontimeout=function(){o(),r._handleError(e)},i.onprogress=function(){},i.send(this.encode(e)),i}}),{isUsable:function(e,t,n,i){if(Faye.URI.isSameOrigin(t))return n.call(i,!1);if(Faye.ENV.XDomainRequest)return n.call(i,t.protocol===Faye.ENV.location.protocol);if(Faye.ENV.XMLHttpRequest){var s=new Faye.ENV.XMLHttpRequest;return n.call(i,void 0!==s.withCredentials)}return n.call(i,!1)}}),Faye.Transport.register("cross-origin-long-polling",Faye.Transport.CORS),Faye.Transport.JSONP=Faye.extend(Faye.Class(Faye.Transport,{encode:function(e){var t=Faye.copyObject(this.endpoint);return t.query.message=Faye.toJSON(e),t.query.jsonp="__jsonp"+Faye.Transport.JSONP._cbCount+"__",Faye.URI.stringify(t)},request:function(e){var t=document.getElementsByTagName("head")[0],n=document.createElement("script"),i=Faye.Transport.JSONP.getCallbackName(),s=Faye.copyObject(this.endpoint),r=this;s.query.message=Faye.toJSON(e),s.query.jsonp=i;var o=function(){if(!Faye.ENV[i])return!1;Faye.ENV[i]=void 0;try{delete Faye.ENV[i]}catch(e){}n.parentNode.removeChild(n)};return Faye.ENV[i]=function(e){o(),r._receive(e)},n.type="text/javascript",n.src=Faye.URI.stringify(s),t.appendChild(n),n.onerror=function(){o(),r._handleError(e)},{abort:o}}}),{_cbCount:0,getCallbackName:function(){return this._cbCount+=1,"__jsonp"+this._cbCount+"__"},isUsable:function(e,t,n,i){n.call(i,!0)}}),Faye.Transport.register("callback-polling",Faye.Transport.JSONP)}();
3
+ //# sourceMappingURL=faye-browser-min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"faye-browser-min.js","sources":["faye-browser.js"],"names":["Faye","VERSION","BAYEUX_VERSION","ID_LENGTH","JSONP_CALLBACK","CONNECTION_TYPES","MANDATORY_CONNECTION_TYPES","ENV","window","global","extend","dest","source","overwrite","key","hasOwnProperty","random","bitlength","this","maxLength","Math","ceil","log","string","csprng","length","clientIdFromMessages","messages","connect","filter","concat","message","channel","clientId","copyObject","object","clone","i","Array","commonElement","lista","listb","n","indexOf","list","needle","map","callback","context","result","push","call","array","asyncEach","iterator","calls","looping","iterate","resume","loop","toJSON","stringify","value","JSON","module","exports","Class","parent","methods","Object","klass","initialize","apply","arguments","bridge","prototype","xs","x","EventEmitter","isArray","toString","emit","type","_events","error","Error","handler","args","slice","listeners","l","addListener","listener","on","once","self","g","removeListener","splice","removeAllListeners","Namespace","_used","exists","id","generate","name","release","defer","timeout","setTimeout","setImmediate","fn","process","nextTick","PENDING","FULFILLED","REJECTED","RETURN","THROW","Promise","task","_state","_onFulfilled","_onRejected","fulfill","reason","reject","then","onFulfilled","onRejected","next","registerOnFulfilled","registerOnRejected","promise","invoke","_value","_reason","_invoke","outcome","TypeError","resolve","called","_fulfill","v","r","shift","all","promises","fulfilled","deferred","pending","tuple","resolved","rejected","Set","_index","add","item","undefined","forEach","block","isEmpty","member","remove","removed","toArray","URI","isURI","uri","protocol","host","path","isSameOrigin","location","hostname","port","parse","url","parts","query","pairs","data","consume","pattern","replace","match","test","pathname","substr","split","search","decodeURIComponent","href","queryString","hash","encodeURIComponent","join","code","params","Grammar","ERROR","parseInt","versionMismatch","conntypeMismatch","extMismatch","badRequest","clientUnknown","parameterMissing","channelForbidden","channelUnknown","channelInvalid","extUnknown","publishFailed","serverError","Deferrable","errback","_promise","_reject","seconds","_timer","setDeferredStatus","status","clearTimeout","Publisher","countListeners","eventType","bind","_listeners","unbind","trigger","Timeouts","addTimeout","delay","_timeouts","removeTimeout","removeAllTimeouts","Logging","LOG_LEVELS","fatal","warn","info","debug","writeLog","messageArgs","level","logger","banner","className","e","CHANNEL_NAME","CHANNEL_PATTERN","Extensible","addExtension","extension","_extensions","added","removeExtension","pipeThroughExtensions","stage","request","extensions","pipe","Channel","isUnused","HANDSHAKE","CONNECT","SUBSCRIBE","UNSUBSCRIBE","DISCONNECT","META","SERVICE","expand","segments","channels","copy","unparse","isValid","isMeta","isService","isSubscribable","_channels","getKeys","keys","hasSubscription","subscribe","names","unsubscribe","distributeMessage","Publication","Subscription","client","_client","_callback","_context","_cancelled","cancel","Client","UNCONNECTED","CONNECTING","CONNECTED","DISCONNECTED","RETRY","NONE","CONNECTION_TIMEOUT","DEFAULT_ENDPOINT","INTERVAL","endpoint","options","_endpoint","_dispatcher","Dispatcher","_messageId","_responseCallbacks","_advice","reconnect","interval","_receiveMessage","Event","onbeforeunload","_disabled","disconnect","disable","feature","setHeader","handshake","selectTransport","_sendMessage","version","supportedConnectionTypes","connectionType","response","successful","retry","_connectRequest","_cycleConnection","close","c","subscription","force","hasSubscribe","dead","publish","publication","_generateMessageId","sendMessage","pow","advice","_handleAdvice","_deliverMessage","MAX_REQUEST_SIZE","DEFAULT_RETRY","UP","DOWN","_alternates","endpoints","ca","cookies","Cookies","CookieJar","_envelopes","headers","transports","maxRequestSize","endpointFor","transport","_transport","transportTypes","Transport","get","attempts","deadline","Date","getTime","envelope","timer","_attemptsExhausted","_deadlinePassed","handleError","handleResponse","reply","immediate","req","abort","MAX_DELAY","batching","dispatcher","_outbox","encode","_flushLargeBatch","_flush","_connectMessage","last","pop","_receive","replies","_handleError","_getCookies","getCookiesSync","cookie","cookieString","_storeCookies","setCookie","Cookie","setCookieSync","allowed","disabled","_transports","pair","connType","connEndpoint","isUsable","create","register","_registry","element","eventName","wrapped","addEventListener","attachEvent","_element","_type","_handler","detach","removeEventListener","detachEvent","onunload","f","quote","escapable","lastIndex","a","meta","charCodeAt","str","holder","k","partial","mind","gap","rep","isFinite","String","indent","valueOf","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","Number","Boolean","cx","\b","\t","\n","\f","\r","\"","\\","replacer","space","text","reviver","walk","j","eval","SyntaxError","WebSocket","_pending","socket","send","ws","_unloaded","_createSocket","onopen","_socket","_everConnected","_ping","closed","onclose","onerror","wasConnected","onmessage","event","getSocketUrl","MozWebSocket","PROTOCOLS","http:","https:","sockets","websocket","EventSource","_xhr","XHR","usable","eventsource","xhr","ActiveXObject","XMLHttpRequest","open","setRequestHeader","onreadystatechange","readyState","responseText","CORS","xhrClass","XDomainRequest","cleanUp","onload","ontimeout","onprogress","withCredentials","JSONP","jsonp","_cbCount","head","document","getElementsByTagName","script","createElement","callbackName","getCallbackName","cleanup","parentNode","removeChild","src","appendChild"],"mappings":"CAAA,WACA,YAEA,IAAIA,OACFC,QAAkB,QAElBC,eAAkB,MAClBC,UAAkB,IAClBC,eAAkB,gBAClBC,kBAAmB,eAAgB,4BAA6B,mBAAoB,YAAa,cAAe,cAEhHC,4BAA6B,eAAgB,mBAAoB,cAEjEC,IAAwB,mBAAXC,QAA0BA,OAASC,OAEhDC,OAAQ,SAASC,EAAMC,EAAQC,GAC7B,IAAKD,EAAQ,MAAOD,EACpB,KAAK,GAAIG,KAAOF,GACTA,EAAOG,eAAeD,KACvBH,EAAKI,eAAeD,IAAQD,KAAc,GAC1CF,EAAKG,KAASF,EAAOE,KACvBH,EAAKG,GAAOF,EAAOE,IAEvB,OAAOH,IAGTK,OAAQ,SAASC,GACfA,EAAYA,GAAaC,KAAKf,SAG9B,KAFA,GAAIgB,GAAYC,KAAKC,KAAKJ,EAAYG,KAAKE,IAAI,GAAKF,KAAKE,IAAI,KACzDC,EAASC,OAAOP,EAAW,IACxBM,EAAOE,OAASN,GAAWI,EAAS,IAAMA,CACjD,OAAOA,IAGTG,qBAAsB,SAASC,GAC7B,GAAIC,GAAUV,KAAKW,UAAUC,OAAOH,GAAW,SAASI,GACtD,MAA2B,kBAApBA,EAAQC,SAEjB,OAAOJ,GAAQ,IAAMA,EAAQ,GAAGK,UAGlCC,WAAY,SAASC,GACnB,GAAIC,GAAOC,EAAGvB,CACd,IAAIqB,YAAkBG,OAAO,CAG3B,IAFAF,KACAC,EAAI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GACjCkN,EAAKW,YAAYR,GAEjBA,EAAOtC,QAAU,WACf0C,IACA5a,EAAK4S,aAAahX,KAGZmW,MAAO6I,OAGjBR,SAAU,EAEVO,gBAAiB,WAEf,MADAxf,MAAKif,UAAY,EACV,UAAYjf,KAAKif,SAAW,MAGrCzG,SAAU,SAASzB,EAAY/E,EAAUnQ,EAAUC,GACjDD,EAASI,KAAKH,GAAS,MAI3BhD,KAAK+W,UAAU6C,SAAS,mBAAoB5Z,KAAK+W,UAAUkJ"}
@@ -0,0 +1,2659 @@
1
+ (function() {
2
+ 'use strict';
3
+
4
+ var Faye = {
5
+ VERSION: '1.0.3',
6
+
7
+ BAYEUX_VERSION: '1.0',
8
+ ID_LENGTH: 160,
9
+ JSONP_CALLBACK: 'jsonpcallback',
10
+ CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'],
11
+
12
+ MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'],
13
+
14
+ ENV: (typeof window !== 'undefined') ? window : global,
15
+
16
+ extend: function(dest, source, overwrite) {
17
+ if (!source) return dest;
18
+ for (var key in source) {
19
+ if (!source.hasOwnProperty(key)) continue;
20
+ if (dest.hasOwnProperty(key) && overwrite === false) continue;
21
+ if (dest[key] !== source[key])
22
+ dest[key] = source[key];
23
+ }
24
+ return dest;
25
+ },
26
+
27
+ random: function(bitlength) {
28
+ bitlength = bitlength || this.ID_LENGTH;
29
+ var maxLength = Math.ceil(bitlength * Math.log(2) / Math.log(36));
30
+ var string = csprng(bitlength, 36);
31
+ while (string.length < maxLength) string = '0' + string;
32
+ return string;
33
+ },
34
+
35
+ clientIdFromMessages: function(messages) {
36
+ var connect = this.filter([].concat(messages), function(message) {
37
+ return message.channel === '/meta/connect';
38
+ });
39
+ return connect[0] && connect[0].clientId;
40
+ },
41
+
42
+ copyObject: function(object) {
43
+ var clone, i, key;
44
+ if (object instanceof Array) {
45
+ clone = [];
46
+ i = object.length;
47
+ while (i--) clone[i] = Faye.copyObject(object[i]);
48
+ return clone;
49
+ } else if (typeof object === 'object') {
50
+ clone = (object === null) ? null : {};
51
+ for (key in object) clone[key] = Faye.copyObject(object[key]);
52
+ return clone;
53
+ } else {
54
+ return object;
55
+ }
56
+ },
57
+
58
+ commonElement: function(lista, listb) {
59
+ for (var i = 0, n = lista.length; i < n; i++) {
60
+ if (this.indexOf(listb, lista[i]) !== -1)
61
+ return lista[i];
62
+ }
63
+ return null;
64
+ },
65
+
66
+ indexOf: function(list, needle) {
67
+ if (list.indexOf) return list.indexOf(needle);
68
+
69
+ for (var i = 0, n = list.length; i < n; i++) {
70
+ if (list[i] === needle) return i;
71
+ }
72
+ return -1;
73
+ },
74
+
75
+ map: function(object, callback, context) {
76
+ if (object.map) return object.map(callback, context);
77
+ var result = [];
78
+
79
+ if (object instanceof Array) {
80
+ for (var i = 0, n = object.length; i < n; i++) {
81
+ result.push(callback.call(context || null, object[i], i));
82
+ }
83
+ } else {
84
+ for (var key in object) {
85
+ if (!object.hasOwnProperty(key)) continue;
86
+ result.push(callback.call(context || null, key, object[key]));
87
+ }
88
+ }
89
+ return result;
90
+ },
91
+
92
+ filter: function(array, callback, context) {
93
+ if (array.filter) return array.filter(callback, context);
94
+ var result = [];
95
+ for (var i = 0, n = array.length; i < n; i++) {
96
+ if (callback.call(context || null, array[i], i))
97
+ result.push(array[i]);
98
+ }
99
+ return result;
100
+ },
101
+
102
+ asyncEach: function(list, iterator, callback, context) {
103
+ var n = list.length,
104
+ i = -1,
105
+ calls = 0,
106
+ looping = false;
107
+
108
+ var iterate = function() {
109
+ calls -= 1;
110
+ i += 1;
111
+ if (i === n) return callback && callback.call(context);
112
+ iterator(list[i], resume);
113
+ };
114
+
115
+ var loop = function() {
116
+ if (looping) return;
117
+ looping = true;
118
+ while (calls > 0) iterate();
119
+ looping = false;
120
+ };
121
+
122
+ var resume = function() {
123
+ calls += 1;
124
+ loop();
125
+ };
126
+ resume();
127
+ },
128
+
129
+ // http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/
130
+ toJSON: function(object) {
131
+ if (!this.stringify) return JSON.stringify(object);
132
+
133
+ return this.stringify(object, function(key, value) {
134
+ return (this[key] instanceof Array) ? this[key] : value;
135
+ });
136
+ }
137
+ };
138
+
139
+ if (typeof module !== 'undefined')
140
+ module.exports = Faye;
141
+ else if (typeof window !== 'undefined')
142
+ window.Faye = Faye;
143
+
144
+ Faye.Class = function(parent, methods) {
145
+ if (typeof parent !== 'function') {
146
+ methods = parent;
147
+ parent = Object;
148
+ }
149
+
150
+ var klass = function() {
151
+ if (!this.initialize) return this;
152
+ return this.initialize.apply(this, arguments) || this;
153
+ };
154
+
155
+ var bridge = function() {};
156
+ bridge.prototype = parent.prototype;
157
+
158
+ klass.prototype = new bridge();
159
+ Faye.extend(klass.prototype, methods);
160
+
161
+ return klass;
162
+ };
163
+
164
+ (function() {
165
+ var EventEmitter = Faye.EventEmitter = function() {};
166
+
167
+ /*
168
+ Copyright Joyent, Inc. and other Node contributors. All rights reserved.
169
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
170
+ this software and associated documentation files (the "Software"), to deal in
171
+ the Software without restriction, including without limitation the rights to
172
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
173
+ of the Software, and to permit persons to whom the Software is furnished to do
174
+ so, subject to the following conditions:
175
+
176
+ The above copyright notice and this permission notice shall be included in all
177
+ copies or substantial portions of the Software.
178
+
179
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
180
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
181
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
182
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
183
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
184
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
185
+ SOFTWARE.
186
+ */
187
+
188
+ var isArray = typeof Array.isArray === 'function'
189
+ ? Array.isArray
190
+ : function (xs) {
191
+ return Object.prototype.toString.call(xs) === '[object Array]'
192
+ }
193
+ ;
194
+ function indexOf (xs, x) {
195
+ if (xs.indexOf) return xs.indexOf(x);
196
+ for (var i = 0; i < xs.length; i++) {
197
+ if (x === xs[i]) return i;
198
+ }
199
+ return -1;
200
+ }
201
+
202
+
203
+ EventEmitter.prototype.emit = function(type) {
204
+ // If there is no 'error' event listener then throw.
205
+ if (type === 'error') {
206
+ if (!this._events || !this._events.error ||
207
+ (isArray(this._events.error) && !this._events.error.length))
208
+ {
209
+ if (arguments[1] instanceof Error) {
210
+ throw arguments[1]; // Unhandled 'error' event
211
+ } else {
212
+ throw new Error("Uncaught, unspecified 'error' event.");
213
+ }
214
+ return false;
215
+ }
216
+ }
217
+
218
+ if (!this._events) return false;
219
+ var handler = this._events[type];
220
+ if (!handler) return false;
221
+
222
+ if (typeof handler == 'function') {
223
+ switch (arguments.length) {
224
+ // fast cases
225
+ case 1:
226
+ handler.call(this);
227
+ break;
228
+ case 2:
229
+ handler.call(this, arguments[1]);
230
+ break;
231
+ case 3:
232
+ handler.call(this, arguments[1], arguments[2]);
233
+ break;
234
+ // slower
235
+ default:
236
+ var args = Array.prototype.slice.call(arguments, 1);
237
+ handler.apply(this, args);
238
+ }
239
+ return true;
240
+
241
+ } else if (isArray(handler)) {
242
+ var args = Array.prototype.slice.call(arguments, 1);
243
+
244
+ var listeners = handler.slice();
245
+ for (var i = 0, l = listeners.length; i < l; i++) {
246
+ listeners[i].apply(this, args);
247
+ }
248
+ return true;
249
+
250
+ } else {
251
+ return false;
252
+ }
253
+ };
254
+
255
+ // EventEmitter is defined in src/node_events.cc
256
+ // EventEmitter.prototype.emit() is also defined there.
257
+ EventEmitter.prototype.addListener = function(type, listener) {
258
+ if ('function' !== typeof listener) {
259
+ throw new Error('addListener only takes instances of Function');
260
+ }
261
+
262
+ if (!this._events) this._events = {};
263
+
264
+ // To avoid recursion in the case that type == "newListeners"! Before
265
+ // adding it to the listeners, first emit "newListeners".
266
+ this.emit('newListener', type, listener);
267
+
268
+ if (!this._events[type]) {
269
+ // Optimize the case of one listener. Don't need the extra array object.
270
+ this._events[type] = listener;
271
+ } else if (isArray(this._events[type])) {
272
+ // If we've already got an array, just append.
273
+ this._events[type].push(listener);
274
+ } else {
275
+ // Adding the second element, need to change to array.
276
+ this._events[type] = [this._events[type], listener];
277
+ }
278
+
279
+ return this;
280
+ };
281
+
282
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
283
+
284
+ EventEmitter.prototype.once = function(type, listener) {
285
+ var self = this;
286
+ self.on(type, function g() {
287
+ self.removeListener(type, g);
288
+ listener.apply(this, arguments);
289
+ });
290
+
291
+ return this;
292
+ };
293
+
294
+ EventEmitter.prototype.removeListener = function(type, listener) {
295
+ if ('function' !== typeof listener) {
296
+ throw new Error('removeListener only takes instances of Function');
297
+ }
298
+
299
+ // does not use listeners(), so no side effect of creating _events[type]
300
+ if (!this._events || !this._events[type]) return this;
301
+
302
+ var list = this._events[type];
303
+
304
+ if (isArray(list)) {
305
+ var i = indexOf(list, listener);
306
+ if (i < 0) return this;
307
+ list.splice(i, 1);
308
+ if (list.length == 0)
309
+ delete this._events[type];
310
+ } else if (this._events[type] === listener) {
311
+ delete this._events[type];
312
+ }
313
+
314
+ return this;
315
+ };
316
+
317
+ EventEmitter.prototype.removeAllListeners = function(type) {
318
+ if (arguments.length === 0) {
319
+ this._events = {};
320
+ return this;
321
+ }
322
+
323
+ // does not use listeners(), so no side effect of creating _events[type]
324
+ if (type && this._events && this._events[type]) this._events[type] = null;
325
+ return this;
326
+ };
327
+
328
+ EventEmitter.prototype.listeners = function(type) {
329
+ if (!this._events) this._events = {};
330
+ if (!this._events[type]) this._events[type] = [];
331
+ if (!isArray(this._events[type])) {
332
+ this._events[type] = [this._events[type]];
333
+ }
334
+ return this._events[type];
335
+ };
336
+
337
+ })();
338
+
339
+ Faye.Namespace = Faye.Class({
340
+ initialize: function() {
341
+ this._used = {};
342
+ },
343
+
344
+ exists: function(id) {
345
+ return this._used.hasOwnProperty(id);
346
+ },
347
+
348
+ generate: function() {
349
+ var name = Faye.random();
350
+ while (this._used.hasOwnProperty(name))
351
+ name = Faye.random();
352
+ return this._used[name] = name;
353
+ },
354
+
355
+ release: function(id) {
356
+ delete this._used[id];
357
+ }
358
+ });
359
+
360
+ (function() {
361
+ 'use strict';
362
+
363
+ var timeout = setTimeout, defer;
364
+
365
+ if (typeof setImmediate === 'function')
366
+ defer = function(fn) { setImmediate(fn) };
367
+ else if (typeof process === 'object' && process.nextTick)
368
+ defer = function(fn) { process.nextTick(fn) };
369
+ else
370
+ defer = function(fn) { timeout(fn, 0) };
371
+
372
+ var PENDING = 0,
373
+ FULFILLED = 1,
374
+ REJECTED = 2;
375
+
376
+ var RETURN = function(x) { return x },
377
+ THROW = function(x) { throw x };
378
+
379
+ var Promise = function(task) {
380
+ this._state = PENDING;
381
+ this._onFulfilled = [];
382
+ this._onRejected = [];
383
+
384
+ if (typeof task !== 'function') return;
385
+ var self = this;
386
+
387
+ task(function(value) { fulfill(self, value) },
388
+ function(reason) { reject(self, reason) });
389
+ };
390
+
391
+ Promise.prototype.then = function(onFulfilled, onRejected) {
392
+ var next = new Promise();
393
+ registerOnFulfilled(this, onFulfilled, next);
394
+ registerOnRejected(this, onRejected, next);
395
+ return next;
396
+ };
397
+
398
+ var registerOnFulfilled = function(promise, onFulfilled, next) {
399
+ if (typeof onFulfilled !== 'function') onFulfilled = RETURN;
400
+ var handler = function(value) { invoke(onFulfilled, value, next) };
401
+
402
+ if (promise._state === PENDING) {
403
+ promise._onFulfilled.push(handler);
404
+ } else if (promise._state === FULFILLED) {
405
+ handler(promise._value);
406
+ }
407
+ };
408
+
409
+ var registerOnRejected = function(promise, onRejected, next) {
410
+ if (typeof onRejected !== 'function') onRejected = THROW;
411
+ var handler = function(reason) { invoke(onRejected, reason, next) };
412
+
413
+ if (promise._state === PENDING) {
414
+ promise._onRejected.push(handler);
415
+ } else if (promise._state === REJECTED) {
416
+ handler(promise._reason);
417
+ }
418
+ };
419
+
420
+ var invoke = function(fn, value, next) {
421
+ defer(function() { _invoke(fn, value, next) });
422
+ };
423
+
424
+ var _invoke = function(fn, value, next) {
425
+ var outcome;
426
+
427
+ try {
428
+ outcome = fn(value);
429
+ } catch (error) {
430
+ return reject(next, error);
431
+ }
432
+
433
+ if (outcome === next) {
434
+ reject(next, new TypeError('Recursive promise chain detected'));
435
+ } else {
436
+ fulfill(next, outcome);
437
+ }
438
+ };
439
+
440
+ var fulfill = Promise.fulfill = Promise.resolve = function(promise, value) {
441
+ var called = false, type, then;
442
+
443
+ try {
444
+ type = typeof value;
445
+ then = value !== null && (type === 'function' || type === 'object') && value.then;
446
+
447
+ if (typeof then !== 'function') return _fulfill(promise, value);
448
+
449
+ then.call(value, function(v) {
450
+ if (!(called ^ (called = true))) return;
451
+ fulfill(promise, v);
452
+ }, function(r) {
453
+ if (!(called ^ (called = true))) return;
454
+ reject(promise, r);
455
+ });
456
+ } catch (error) {
457
+ if (!(called ^ (called = true))) return;
458
+ reject(promise, error);
459
+ }
460
+ };
461
+
462
+ var _fulfill = function(promise, value) {
463
+ if (promise._state !== PENDING) return;
464
+
465
+ promise._state = FULFILLED;
466
+ promise._value = value;
467
+ promise._onRejected = [];
468
+
469
+ var onFulfilled = promise._onFulfilled, fn;
470
+ while (fn = onFulfilled.shift()) fn(value);
471
+ };
472
+
473
+ var reject = Promise.reject = function(promise, reason) {
474
+ if (promise._state !== PENDING) return;
475
+
476
+ promise._state = REJECTED;
477
+ promise._reason = reason;
478
+ promise._onFulfilled = [];
479
+
480
+ var onRejected = promise._onRejected, fn;
481
+ while (fn = onRejected.shift()) fn(reason);
482
+ };
483
+
484
+ Promise.all = function(promises) {
485
+ return new Promise(function(fulfill, reject) {
486
+ var list = [],
487
+ n = promises.length,
488
+ i;
489
+
490
+ if (n === 0) return fulfill(list);
491
+
492
+ for (i = 0; i < n; i++) (function(promise, i) {
493
+ Promise.fulfilled(promise).then(function(value) {
494
+ list[i] = value;
495
+ if (--n === 0) fulfill(list);
496
+ }, reject);
497
+ })(promises[i], i);
498
+ });
499
+ };
500
+
501
+ Promise.defer = defer;
502
+
503
+ Promise.deferred = Promise.pending = function() {
504
+ var tuple = {};
505
+
506
+ tuple.promise = new Promise(function(fulfill, reject) {
507
+ tuple.fulfill = tuple.resolve = fulfill;
508
+ tuple.reject = reject;
509
+ });
510
+ return tuple;
511
+ };
512
+
513
+ Promise.fulfilled = Promise.resolved = function(value) {
514
+ return new Promise(function(fulfill, reject) { fulfill(value) });
515
+ };
516
+
517
+ Promise.rejected = function(reason) {
518
+ return new Promise(function(fulfill, reject) { reject(reason) });
519
+ };
520
+
521
+ if (typeof Faye === 'undefined')
522
+ module.exports = Promise;
523
+ else
524
+ Faye.Promise = Promise;
525
+
526
+ })();
527
+
528
+ Faye.Set = Faye.Class({
529
+ initialize: function() {
530
+ this._index = {};
531
+ },
532
+
533
+ add: function(item) {
534
+ var key = (item.id !== undefined) ? item.id : item;
535
+ if (this._index.hasOwnProperty(key)) return false;
536
+ this._index[key] = item;
537
+ return true;
538
+ },
539
+
540
+ forEach: function(block, context) {
541
+ for (var key in this._index) {
542
+ if (this._index.hasOwnProperty(key))
543
+ block.call(context, this._index[key]);
544
+ }
545
+ },
546
+
547
+ isEmpty: function() {
548
+ for (var key in this._index) {
549
+ if (this._index.hasOwnProperty(key)) return false;
550
+ }
551
+ return true;
552
+ },
553
+
554
+ member: function(item) {
555
+ for (var key in this._index) {
556
+ if (this._index[key] === item) return true;
557
+ }
558
+ return false;
559
+ },
560
+
561
+ remove: function(item) {
562
+ var key = (item.id !== undefined) ? item.id : item;
563
+ var removed = this._index[key];
564
+ delete this._index[key];
565
+ return removed;
566
+ },
567
+
568
+ toArray: function() {
569
+ var array = [];
570
+ this.forEach(function(item) { array.push(item) });
571
+ return array;
572
+ }
573
+ });
574
+
575
+ Faye.URI = {
576
+ isURI: function(uri) {
577
+ return uri && uri.protocol && uri.host && uri.path;
578
+ },
579
+
580
+ isSameOrigin: function(uri) {
581
+ var location = Faye.ENV.location;
582
+ return uri.protocol === location.protocol &&
583
+ uri.hostname === location.hostname &&
584
+ uri.port === location.port;
585
+ },
586
+
587
+ parse: function(url) {
588
+ if (typeof url !== 'string') return url;
589
+ var uri = {}, parts, query, pairs, i, n, data;
590
+
591
+ var consume = function(name, pattern) {
592
+ url = url.replace(pattern, function(match) {
593
+ uri[name] = match;
594
+ return '';
595
+ });
596
+ uri[name] = uri[name] || '';
597
+ };
598
+
599
+ consume('protocol', /^[a-z]+\:/i);
600
+ consume('host', /^\/\/[^\/\?#]+/);
601
+
602
+ if (!/^\//.test(url) && !uri.host)
603
+ url = Faye.ENV.location.pathname.replace(/[^\/]*$/, '') + url;
604
+
605
+ consume('pathname', /^[^\?#]*/);
606
+ consume('search', /^\?[^#]*/);
607
+ consume('hash', /^#.*/);
608
+
609
+ uri.protocol = uri.protocol || Faye.ENV.location.protocol;
610
+
611
+ if (uri.host) {
612
+ uri.host = uri.host.substr(2);
613
+ parts = uri.host.split(':');
614
+ uri.hostname = parts[0];
615
+ uri.port = parts[1] || '';
616
+ } else {
617
+ uri.host = Faye.ENV.location.host;
618
+ uri.hostname = Faye.ENV.location.hostname;
619
+ uri.port = Faye.ENV.location.port;
620
+ }
621
+
622
+ uri.pathname = uri.pathname || '/';
623
+ uri.path = uri.pathname + uri.search;
624
+
625
+ query = uri.search.replace(/^\?/, '');
626
+ pairs = query ? query.split('&') : [];
627
+ data = {};
628
+
629
+ for (i = 0, n = pairs.length; i < n; i++) {
630
+ parts = pairs[i].split('=');
631
+ data[decodeURIComponent(parts[0] || '')] = decodeURIComponent(parts[1] || '');
632
+ }
633
+
634
+ uri.query = data;
635
+
636
+ uri.href = this.stringify(uri);
637
+ return uri;
638
+ },
639
+
640
+ stringify: function(uri) {
641
+ var string = uri.protocol + '//' + uri.hostname;
642
+ if (uri.port) string += ':' + uri.port;
643
+ string += uri.pathname + this.queryString(uri.query) + (uri.hash || '');
644
+ return string;
645
+ },
646
+
647
+ queryString: function(query) {
648
+ var pairs = [];
649
+ for (var key in query) {
650
+ if (!query.hasOwnProperty(key)) continue;
651
+ pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key]));
652
+ }
653
+ if (pairs.length === 0) return '';
654
+ return '?' + pairs.join('&');
655
+ }
656
+ };
657
+
658
+ Faye.Error = Faye.Class({
659
+ initialize: function(code, params, message) {
660
+ this.code = code;
661
+ this.params = Array.prototype.slice.call(params);
662
+ this.message = message;
663
+ },
664
+
665
+ toString: function() {
666
+ return this.code + ':' +
667
+ this.params.join(',') + ':' +
668
+ this.message;
669
+ }
670
+ });
671
+
672
+ Faye.Error.parse = function(message) {
673
+ message = message || '';
674
+ if (!Faye.Grammar.ERROR.test(message)) return new this(null, [], message);
675
+
676
+ var parts = message.split(':'),
677
+ code = parseInt(parts[0]),
678
+ params = parts[1].split(','),
679
+ message = parts[2];
680
+
681
+ return new this(code, params, message);
682
+ };
683
+
684
+
685
+
686
+
687
+ Faye.Error.versionMismatch = function() {
688
+ return new this(300, arguments, 'Version mismatch').toString();
689
+ };
690
+
691
+ Faye.Error.conntypeMismatch = function() {
692
+ return new this(301, arguments, 'Connection types not supported').toString();
693
+ };
694
+
695
+ Faye.Error.extMismatch = function() {
696
+ return new this(302, arguments, 'Extension mismatch').toString();
697
+ };
698
+
699
+ Faye.Error.badRequest = function() {
700
+ return new this(400, arguments, 'Bad request').toString();
701
+ };
702
+
703
+ Faye.Error.clientUnknown = function() {
704
+ return new this(401, arguments, 'Unknown client').toString();
705
+ };
706
+
707
+ Faye.Error.parameterMissing = function() {
708
+ return new this(402, arguments, 'Missing required parameter').toString();
709
+ };
710
+
711
+ Faye.Error.channelForbidden = function() {
712
+ return new this(403, arguments, 'Forbidden channel').toString();
713
+ };
714
+
715
+ Faye.Error.channelUnknown = function() {
716
+ return new this(404, arguments, 'Unknown channel').toString();
717
+ };
718
+
719
+ Faye.Error.channelInvalid = function() {
720
+ return new this(405, arguments, 'Invalid channel').toString();
721
+ };
722
+
723
+ Faye.Error.extUnknown = function() {
724
+ return new this(406, arguments, 'Unknown extension').toString();
725
+ };
726
+
727
+ Faye.Error.publishFailed = function() {
728
+ return new this(407, arguments, 'Failed to publish').toString();
729
+ };
730
+
731
+ Faye.Error.serverError = function() {
732
+ return new this(500, arguments, 'Internal server error').toString();
733
+ };
734
+
735
+
736
+ Faye.Deferrable = {
737
+ then: function(callback, errback) {
738
+ var self = this;
739
+ if (!this._promise)
740
+ this._promise = new Faye.Promise(function(fulfill, reject) {
741
+ self._fulfill = fulfill;
742
+ self._reject = reject;
743
+ });
744
+
745
+ if (arguments.length === 0)
746
+ return this._promise;
747
+ else
748
+ return this._promise.then(callback, errback);
749
+ },
750
+
751
+ callback: function(callback, context) {
752
+ return this.then(function(value) { callback.call(context, value) });
753
+ },
754
+
755
+ errback: function(callback, context) {
756
+ return this.then(null, function(reason) { callback.call(context, reason) });
757
+ },
758
+
759
+ timeout: function(seconds, message) {
760
+ this.then();
761
+ var self = this;
762
+ this._timer = Faye.ENV.setTimeout(function() {
763
+ self._reject(message);
764
+ }, seconds * 1000);
765
+ },
766
+
767
+ setDeferredStatus: function(status, value) {
768
+ if (this._timer) Faye.ENV.clearTimeout(this._timer);
769
+
770
+ this.then();
771
+
772
+ if (status === 'succeeded')
773
+ this._fulfill(value);
774
+ else if (status === 'failed')
775
+ this._reject(value);
776
+ else
777
+ delete this._promise;
778
+ }
779
+ };
780
+
781
+ Faye.Publisher = {
782
+ countListeners: function(eventType) {
783
+ return this.listeners(eventType).length;
784
+ },
785
+
786
+ bind: function(eventType, listener, context) {
787
+ var slice = Array.prototype.slice,
788
+ handler = function() { listener.apply(context, slice.call(arguments)) };
789
+
790
+ this._listeners = this._listeners || [];
791
+ this._listeners.push([eventType, listener, context, handler]);
792
+ return this.on(eventType, handler);
793
+ },
794
+
795
+ unbind: function(eventType, listener, context) {
796
+ this._listeners = this._listeners || [];
797
+ var n = this._listeners.length, tuple;
798
+
799
+ while (n--) {
800
+ tuple = this._listeners[n];
801
+ if (tuple[0] !== eventType) continue;
802
+ if (listener && (tuple[1] !== listener || tuple[2] !== context)) continue;
803
+ this._listeners.splice(n, 1);
804
+ this.removeListener(eventType, tuple[3]);
805
+ }
806
+ }
807
+ };
808
+
809
+ Faye.extend(Faye.Publisher, Faye.EventEmitter.prototype);
810
+ Faye.Publisher.trigger = Faye.Publisher.emit;
811
+
812
+ Faye.Timeouts = {
813
+ addTimeout: function(name, delay, callback, context) {
814
+ this._timeouts = this._timeouts || {};
815
+ if (this._timeouts.hasOwnProperty(name)) return;
816
+ var self = this;
817
+ this._timeouts[name] = Faye.ENV.setTimeout(function() {
818
+ delete self._timeouts[name];
819
+ callback.call(context);
820
+ }, 1000 * delay);
821
+ },
822
+
823
+ removeTimeout: function(name) {
824
+ this._timeouts = this._timeouts || {};
825
+ var timeout = this._timeouts[name];
826
+ if (!timeout) return;
827
+ Faye.ENV.clearTimeout(timeout);
828
+ delete this._timeouts[name];
829
+ },
830
+
831
+ removeAllTimeouts: function() {
832
+ this._timeouts = this._timeouts || {};
833
+ for (var name in this._timeouts) this.removeTimeout(name);
834
+ }
835
+ };
836
+
837
+ Faye.Logging = {
838
+ LOG_LEVELS: {
839
+ fatal: 4,
840
+ error: 3,
841
+ warn: 2,
842
+ info: 1,
843
+ debug: 0
844
+ },
845
+
846
+ writeLog: function(messageArgs, level) {
847
+ if (!Faye.logger) return;
848
+
849
+ var args = Array.prototype.slice.apply(messageArgs),
850
+ banner = '[Faye',
851
+ klass = this.className,
852
+
853
+ message = args.shift().replace(/\?/g, function() {
854
+ try {
855
+ return Faye.toJSON(args.shift());
856
+ } catch (e) {
857
+ return '[Object]';
858
+ }
859
+ });
860
+
861
+ for (var key in Faye) {
862
+ if (klass) continue;
863
+ if (typeof Faye[key] !== 'function') continue;
864
+ if (this instanceof Faye[key]) klass = key;
865
+ }
866
+ if (klass) banner += '.' + klass;
867
+ banner += '] ';
868
+
869
+ if (typeof Faye.logger[level] === 'function')
870
+ Faye.logger[level](banner + message);
871
+ else if (typeof Faye.logger === 'function')
872
+ Faye.logger(banner + message);
873
+ }
874
+ };
875
+
876
+ (function() {
877
+ for (var key in Faye.Logging.LOG_LEVELS)
878
+ (function(level) {
879
+ Faye.Logging[level] = function() {
880
+ this.writeLog(arguments, level);
881
+ };
882
+ })(key);
883
+ })();
884
+
885
+ Faye.Grammar = {
886
+ CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
887
+ CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,
888
+ 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])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/,
889
+ VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/
890
+ };
891
+
892
+ Faye.Extensible = {
893
+ addExtension: function(extension) {
894
+ this._extensions = this._extensions || [];
895
+ this._extensions.push(extension);
896
+ if (extension.added) extension.added(this);
897
+ },
898
+
899
+ removeExtension: function(extension) {
900
+ if (!this._extensions) return;
901
+ var i = this._extensions.length;
902
+ while (i--) {
903
+ if (this._extensions[i] !== extension) continue;
904
+ this._extensions.splice(i,1);
905
+ if (extension.removed) extension.removed(this);
906
+ }
907
+ },
908
+
909
+ pipeThroughExtensions: function(stage, message, request, callback, context) {
910
+ this.debug('Passing through ? extensions: ?', stage, message);
911
+
912
+ if (!this._extensions) return callback.call(context, message);
913
+ var extensions = this._extensions.slice();
914
+
915
+ var pipe = function(message) {
916
+ if (!message) return callback.call(context, message);
917
+
918
+ var extension = extensions.shift();
919
+ if (!extension) return callback.call(context, message);
920
+
921
+ var fn = extension[stage];
922
+ if (!fn) return pipe(message);
923
+
924
+ if (fn.length >= 3) extension[stage](message, request, pipe);
925
+ else extension[stage](message, pipe);
926
+ };
927
+ pipe(message);
928
+ }
929
+ };
930
+
931
+ Faye.extend(Faye.Extensible, Faye.Logging);
932
+
933
+ Faye.Channel = Faye.Class({
934
+ initialize: function(name) {
935
+ this.id = this.name = name;
936
+ },
937
+
938
+ push: function(message) {
939
+ this.trigger('message', message);
940
+ },
941
+
942
+ isUnused: function() {
943
+ return this.countListeners('message') === 0;
944
+ }
945
+ });
946
+
947
+ Faye.extend(Faye.Channel.prototype, Faye.Publisher);
948
+
949
+ Faye.extend(Faye.Channel, {
950
+ HANDSHAKE: '/meta/handshake',
951
+ CONNECT: '/meta/connect',
952
+ SUBSCRIBE: '/meta/subscribe',
953
+ UNSUBSCRIBE: '/meta/unsubscribe',
954
+ DISCONNECT: '/meta/disconnect',
955
+
956
+ META: 'meta',
957
+ SERVICE: 'service',
958
+
959
+ expand: function(name) {
960
+ var segments = this.parse(name),
961
+ channels = ['/**', name];
962
+
963
+ var copy = segments.slice();
964
+ copy[copy.length - 1] = '*';
965
+ channels.push(this.unparse(copy));
966
+
967
+ for (var i = 1, n = segments.length; i < n; i++) {
968
+ copy = segments.slice(0, i);
969
+ copy.push('**');
970
+ channels.push(this.unparse(copy));
971
+ }
972
+
973
+ return channels;
974
+ },
975
+
976
+ isValid: function(name) {
977
+ return Faye.Grammar.CHANNEL_NAME.test(name) ||
978
+ Faye.Grammar.CHANNEL_PATTERN.test(name);
979
+ },
980
+
981
+ parse: function(name) {
982
+ if (!this.isValid(name)) return null;
983
+ return name.split('/').slice(1);
984
+ },
985
+
986
+ unparse: function(segments) {
987
+ return '/' + segments.join('/');
988
+ },
989
+
990
+ isMeta: function(name) {
991
+ var segments = this.parse(name);
992
+ return segments ? (segments[0] === this.META) : null;
993
+ },
994
+
995
+ isService: function(name) {
996
+ var segments = this.parse(name);
997
+ return segments ? (segments[0] === this.SERVICE) : null;
998
+ },
999
+
1000
+ isSubscribable: function(name) {
1001
+ if (!this.isValid(name)) return null;
1002
+ return !this.isMeta(name) && !this.isService(name);
1003
+ },
1004
+
1005
+ Set: Faye.Class({
1006
+ initialize: function() {
1007
+ this._channels = {};
1008
+ },
1009
+
1010
+ getKeys: function() {
1011
+ var keys = [];
1012
+ for (var key in this._channels) keys.push(key);
1013
+ return keys;
1014
+ },
1015
+
1016
+ remove: function(name) {
1017
+ delete this._channels[name];
1018
+ },
1019
+
1020
+ hasSubscription: function(name) {
1021
+ return this._channels.hasOwnProperty(name);
1022
+ },
1023
+
1024
+ subscribe: function(names, callback, context) {
1025
+ var name;
1026
+ for (var i = 0, n = names.length; i < n; i++) {
1027
+ name = names[i];
1028
+ var channel = this._channels[name] = this._channels[name] || new Faye.Channel(name);
1029
+ if (callback) channel.bind('message', callback, context);
1030
+ }
1031
+ },
1032
+
1033
+ unsubscribe: function(name, callback, context) {
1034
+ var channel = this._channels[name];
1035
+ if (!channel) return false;
1036
+ channel.unbind('message', callback, context);
1037
+
1038
+ if (channel.isUnused()) {
1039
+ this.remove(name);
1040
+ return true;
1041
+ } else {
1042
+ return false;
1043
+ }
1044
+ },
1045
+
1046
+ distributeMessage: function(message) {
1047
+ var channels = Faye.Channel.expand(message.channel);
1048
+
1049
+ for (var i = 0, n = channels.length; i < n; i++) {
1050
+ var channel = this._channels[channels[i]];
1051
+ if (channel) channel.trigger('message', message.data);
1052
+ }
1053
+ }
1054
+ })
1055
+ });
1056
+
1057
+ Faye.Publication = Faye.Class(Faye.Deferrable);
1058
+
1059
+ Faye.Subscription = Faye.Class({
1060
+ initialize: function(client, channels, callback, context) {
1061
+ this._client = client;
1062
+ this._channels = channels;
1063
+ this._callback = callback;
1064
+ this._context = context;
1065
+ this._cancelled = false;
1066
+ },
1067
+
1068
+ cancel: function() {
1069
+ if (this._cancelled) return;
1070
+ this._client.unsubscribe(this._channels, this._callback, this._context);
1071
+ this._cancelled = true;
1072
+ },
1073
+
1074
+ unsubscribe: function() {
1075
+ this.cancel();
1076
+ }
1077
+ });
1078
+
1079
+ Faye.extend(Faye.Subscription.prototype, Faye.Deferrable);
1080
+
1081
+ Faye.Client = Faye.Class({
1082
+ UNCONNECTED: 1,
1083
+ CONNECTING: 2,
1084
+ CONNECTED: 3,
1085
+ DISCONNECTED: 4,
1086
+
1087
+ HANDSHAKE: 'handshake',
1088
+ RETRY: 'retry',
1089
+ NONE: 'none',
1090
+
1091
+ CONNECTION_TIMEOUT: 60,
1092
+
1093
+ DEFAULT_ENDPOINT: '/bayeux',
1094
+ INTERVAL: 0,
1095
+
1096
+ initialize: function(endpoint, options) {
1097
+ this.info('New client created for ?', endpoint);
1098
+ options = options || {};
1099
+
1100
+ this._endpoint = endpoint || this.DEFAULT_ENDPOINT;
1101
+ this._channels = new Faye.Channel.Set();
1102
+ this._dispatcher = new Faye.Dispatcher(this, this._endpoint, options);
1103
+
1104
+ this._messageId = 0;
1105
+ this._state = this.UNCONNECTED;
1106
+
1107
+ this._responseCallbacks = {};
1108
+
1109
+ this._advice = {
1110
+ reconnect: this.RETRY,
1111
+ interval: 1000 * (options.interval || this.INTERVAL),
1112
+ timeout: 1000 * (options.timeout || this.CONNECTION_TIMEOUT)
1113
+ };
1114
+ this._dispatcher.timeout = this._advice.timeout / 1000;
1115
+
1116
+ this._dispatcher.bind('message', this._receiveMessage, this);
1117
+
1118
+ if (Faye.Event && Faye.ENV.onbeforeunload !== undefined)
1119
+ Faye.Event.on(Faye.ENV, 'beforeunload', function() {
1120
+ if (Faye.indexOf(this._dispatcher._disabled, 'autodisconnect') < 0)
1121
+ this.disconnect();
1122
+ }, this);
1123
+ },
1124
+
1125
+ disable: function(feature) {
1126
+ return this._dispatcher.disable(feature);
1127
+ },
1128
+
1129
+ setHeader: function(name, value) {
1130
+ return this._dispatcher.setHeader(name, value);
1131
+ },
1132
+
1133
+ // Request
1134
+ // MUST include: * channel
1135
+ // * version
1136
+ // * supportedConnectionTypes
1137
+ // MAY include: * minimumVersion
1138
+ // * ext
1139
+ // * id
1140
+ //
1141
+ // Success Response Failed Response
1142
+ // MUST include: * channel MUST include: * channel
1143
+ // * version * successful
1144
+ // * supportedConnectionTypes * error
1145
+ // * clientId MAY include: * supportedConnectionTypes
1146
+ // * successful * advice
1147
+ // MAY include: * minimumVersion * version
1148
+ // * advice * minimumVersion
1149
+ // * ext * ext
1150
+ // * id * id
1151
+ // * authSuccessful
1152
+ handshake: function(callback, context) {
1153
+ if (this._advice.reconnect === this.NONE) return;
1154
+ if (this._state !== this.UNCONNECTED) return;
1155
+
1156
+ this._state = this.CONNECTING;
1157
+ var self = this;
1158
+
1159
+ this.info('Initiating handshake with ?', Faye.URI.stringify(this._endpoint));
1160
+ this._dispatcher.selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
1161
+
1162
+ this._sendMessage({
1163
+ channel: Faye.Channel.HANDSHAKE,
1164
+ version: Faye.BAYEUX_VERSION,
1165
+ supportedConnectionTypes: [this._dispatcher.connectionType]
1166
+
1167
+ }, {}, function(response) {
1168
+
1169
+ if (response.successful) {
1170
+ this._state = this.CONNECTED;
1171
+ this._dispatcher.clientId = response.clientId;
1172
+
1173
+ this._dispatcher.selectTransport(response.supportedConnectionTypes);
1174
+
1175
+ this.info('Handshake successful: ?', this._dispatcher.clientId);
1176
+
1177
+ this.subscribe(this._channels.getKeys(), true);
1178
+ if (callback) Faye.Promise.defer(function() { callback.call(context) });
1179
+
1180
+ } else {
1181
+ this.info('Handshake unsuccessful');
1182
+ Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._dispatcher.retry * 1000);
1183
+ this._state = this.UNCONNECTED;
1184
+ }
1185
+ }, this);
1186
+ },
1187
+
1188
+ // Request Response
1189
+ // MUST include: * channel MUST include: * channel
1190
+ // * clientId * successful
1191
+ // * connectionType * clientId
1192
+ // MAY include: * ext MAY include: * error
1193
+ // * id * advice
1194
+ // * ext
1195
+ // * id
1196
+ // * timestamp
1197
+ connect: function(callback, context) {
1198
+ if (this._advice.reconnect === this.NONE) return;
1199
+ if (this._state === this.DISCONNECTED) return;
1200
+
1201
+ if (this._state === this.UNCONNECTED)
1202
+ return this.handshake(function() { this.connect(callback, context) }, this);
1203
+
1204
+ this.callback(callback, context);
1205
+ if (this._state !== this.CONNECTED) return;
1206
+
1207
+ this.info('Calling deferred actions for ?', this._dispatcher.clientId);
1208
+ this.setDeferredStatus('succeeded');
1209
+ this.setDeferredStatus('unknown');
1210
+
1211
+ if (this._connectRequest) return;
1212
+ this._connectRequest = true;
1213
+
1214
+ this.info('Initiating connection for ?', this._dispatcher.clientId);
1215
+
1216
+ this._sendMessage({
1217
+ channel: Faye.Channel.CONNECT,
1218
+ clientId: this._dispatcher.clientId,
1219
+ connectionType: this._dispatcher.connectionType
1220
+
1221
+ }, {}, this._cycleConnection, this);
1222
+ },
1223
+
1224
+ // Request Response
1225
+ // MUST include: * channel MUST include: * channel
1226
+ // * clientId * successful
1227
+ // MAY include: * ext * clientId
1228
+ // * id MAY include: * error
1229
+ // * ext
1230
+ // * id
1231
+ disconnect: function() {
1232
+ if (this._state !== this.CONNECTED) return;
1233
+ this._state = this.DISCONNECTED;
1234
+
1235
+ this.info('Disconnecting ?', this._dispatcher.clientId);
1236
+
1237
+ this._sendMessage({
1238
+ channel: Faye.Channel.DISCONNECT,
1239
+ clientId: this._dispatcher.clientId
1240
+
1241
+ }, {}, function(response) {
1242
+ if (response.successful) this._dispatcher.close();
1243
+ }, this);
1244
+
1245
+ this.info('Clearing channel listeners for ?', this._dispatcher.clientId);
1246
+ this._channels = new Faye.Channel.Set();
1247
+ },
1248
+
1249
+ // Request Response
1250
+ // MUST include: * channel MUST include: * channel
1251
+ // * clientId * successful
1252
+ // * subscription * clientId
1253
+ // MAY include: * ext * subscription
1254
+ // * id MAY include: * error
1255
+ // * advice
1256
+ // * ext
1257
+ // * id
1258
+ // * timestamp
1259
+ subscribe: function(channel, callback, context) {
1260
+ if (channel instanceof Array)
1261
+ return Faye.map(channel, function(c) {
1262
+ return this.subscribe(c, callback, context);
1263
+ }, this);
1264
+
1265
+ var subscription = new Faye.Subscription(this, channel, callback, context),
1266
+ force = (callback === true),
1267
+ hasSubscribe = this._channels.hasSubscription(channel);
1268
+
1269
+ if (hasSubscribe && !force) {
1270
+ this._channels.subscribe([channel], callback, context);
1271
+ subscription.setDeferredStatus('succeeded');
1272
+ return subscription;
1273
+ }
1274
+
1275
+ this.connect(function() {
1276
+ this.info('Client ? attempting to subscribe to ?', this._dispatcher.clientId, channel);
1277
+ if (!force) this._channels.subscribe([channel], callback, context);
1278
+
1279
+ this._sendMessage({
1280
+ channel: Faye.Channel.SUBSCRIBE,
1281
+ clientId: this._dispatcher.clientId,
1282
+ subscription: channel
1283
+
1284
+ }, {}, function(response) {
1285
+ if (!response.successful) {
1286
+ subscription.setDeferredStatus('failed', Faye.Error.parse(response.error));
1287
+ return this._channels.unsubscribe(channel, callback, context);
1288
+ }
1289
+
1290
+ var channels = [].concat(response.subscription);
1291
+ this.info('Subscription acknowledged for ? to ?', this._dispatcher.clientId, channels);
1292
+ subscription.setDeferredStatus('succeeded');
1293
+ }, this);
1294
+ }, this);
1295
+
1296
+ return subscription;
1297
+ },
1298
+
1299
+ // Request Response
1300
+ // MUST include: * channel MUST include: * channel
1301
+ // * clientId * successful
1302
+ // * subscription * clientId
1303
+ // MAY include: * ext * subscription
1304
+ // * id MAY include: * error
1305
+ // * advice
1306
+ // * ext
1307
+ // * id
1308
+ // * timestamp
1309
+ unsubscribe: function(channel, callback, context) {
1310
+ if (channel instanceof Array)
1311
+ return Faye.map(channel, function(c) {
1312
+ return this.unsubscribe(c, callback, context);
1313
+ }, this);
1314
+
1315
+ var dead = this._channels.unsubscribe(channel, callback, context);
1316
+ if (!dead) return;
1317
+
1318
+ this.connect(function() {
1319
+ this.info('Client ? attempting to unsubscribe from ?', this._dispatcher.clientId, channel);
1320
+
1321
+ this._sendMessage({
1322
+ channel: Faye.Channel.UNSUBSCRIBE,
1323
+ clientId: this._dispatcher.clientId,
1324
+ subscription: channel
1325
+
1326
+ }, {}, function(response) {
1327
+ if (!response.successful) return;
1328
+
1329
+ var channels = [].concat(response.subscription);
1330
+ this.info('Unsubscription acknowledged for ? from ?', this._dispatcher.clientId, channels);
1331
+ }, this);
1332
+ }, this);
1333
+ },
1334
+
1335
+ // Request Response
1336
+ // MUST include: * channel MUST include: * channel
1337
+ // * data * successful
1338
+ // MAY include: * clientId MAY include: * id
1339
+ // * id * error
1340
+ // * ext * ext
1341
+ publish: function(channel, data, options) {
1342
+ var publication = new Faye.Publication();
1343
+
1344
+ this.connect(function() {
1345
+ this.info('Client ? queueing published message to ?: ?', this._dispatcher.clientId, channel, data);
1346
+
1347
+ this._sendMessage({
1348
+ channel: channel,
1349
+ data: data,
1350
+ clientId: this._dispatcher.clientId
1351
+
1352
+ }, options, function(response) {
1353
+ if (response.successful)
1354
+ publication.setDeferredStatus('succeeded');
1355
+ else
1356
+ publication.setDeferredStatus('failed', Faye.Error.parse(response.error));
1357
+ }, this);
1358
+ }, this);
1359
+
1360
+ return publication;
1361
+ },
1362
+
1363
+ _sendMessage: function(message, options, callback, context) {
1364
+ message.id = this._generateMessageId();
1365
+
1366
+ var timeout = this._advice.timeout
1367
+ ? 1.2 * this._advice.timeout / 1000
1368
+ : 1.2 * this._dispatcher.retry;
1369
+
1370
+ this.pipeThroughExtensions('outgoing', message, null, function(message) {
1371
+ if (!message) return;
1372
+ if (callback) this._responseCallbacks[message.id] = [callback, context];
1373
+ this._dispatcher.sendMessage(message, timeout, options || {});
1374
+ }, this);
1375
+ },
1376
+
1377
+ _generateMessageId: function() {
1378
+ this._messageId += 1;
1379
+ if (this._messageId >= Math.pow(2,32)) this._messageId = 0;
1380
+ return this._messageId.toString(36);
1381
+ },
1382
+
1383
+ _receiveMessage: function(message) {
1384
+ var id = message.id, callback;
1385
+
1386
+ if (message.successful !== undefined) {
1387
+ callback = this._responseCallbacks[id];
1388
+ delete this._responseCallbacks[id];
1389
+ }
1390
+
1391
+ this.pipeThroughExtensions('incoming', message, null, function(message) {
1392
+ if (!message) return;
1393
+ if (message.advice) this._handleAdvice(message.advice);
1394
+ this._deliverMessage(message);
1395
+ if (callback) callback[0].call(callback[1], message);
1396
+ }, this);
1397
+ },
1398
+
1399
+ _handleAdvice: function(advice) {
1400
+ Faye.extend(this._advice, advice);
1401
+ this._dispatcher.timeout = this._advice.timeout / 1000;
1402
+
1403
+ if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {
1404
+ this._state = this.UNCONNECTED;
1405
+ this._dispatcher.clientId = null;
1406
+ this._cycleConnection();
1407
+ }
1408
+ },
1409
+
1410
+ _deliverMessage: function(message) {
1411
+ if (!message.channel || message.data === undefined) return;
1412
+ this.info('Client ? calling listeners for ? with ?', this._dispatcher.clientId, message.channel, message.data);
1413
+ this._channels.distributeMessage(message);
1414
+ },
1415
+
1416
+ _cycleConnection: function() {
1417
+ if (this._connectRequest) {
1418
+ this._connectRequest = null;
1419
+ this.info('Closed connection for ?', this._dispatcher.clientId);
1420
+ }
1421
+ var self = this;
1422
+ Faye.ENV.setTimeout(function() { self.connect() }, this._advice.interval);
1423
+ }
1424
+ });
1425
+
1426
+ Faye.extend(Faye.Client.prototype, Faye.Deferrable);
1427
+ Faye.extend(Faye.Client.prototype, Faye.Publisher);
1428
+ Faye.extend(Faye.Client.prototype, Faye.Logging);
1429
+ Faye.extend(Faye.Client.prototype, Faye.Extensible);
1430
+
1431
+ Faye.Dispatcher = Faye.Class({
1432
+ MAX_REQUEST_SIZE: 2048,
1433
+ DEFAULT_RETRY: 5,
1434
+
1435
+ UP: 1,
1436
+ DOWN: 2,
1437
+
1438
+ initialize: function(client, endpoint, options) {
1439
+ this._client = client;
1440
+ this.endpoint = Faye.URI.parse(endpoint);
1441
+ this._alternates = options.endpoints || {};
1442
+
1443
+ this.ca = options.ca;
1444
+ this.cookies = Faye.Cookies && new Faye.Cookies.CookieJar();
1445
+ this._disabled = [];
1446
+ this._envelopes = {};
1447
+ this.headers = {};
1448
+ this.retry = options.retry || this.DEFAULT_RETRY;
1449
+ this._state = 0;
1450
+ this.transports = {};
1451
+
1452
+ for (var type in this._alternates)
1453
+ this._alternates[type] = Faye.URI.parse(this._alternates[type]);
1454
+
1455
+ this.maxRequestSize = this.MAX_REQUEST_SIZE;
1456
+ },
1457
+
1458
+ endpointFor: function(connectionType) {
1459
+ return this._alternates[connectionType] || this.endpoint;
1460
+ },
1461
+
1462
+ disable: function(feature) {
1463
+ this._disabled.push(feature);
1464
+ },
1465
+
1466
+ setHeader: function(name, value) {
1467
+ this.headers[name] = value;
1468
+ },
1469
+
1470
+ close: function() {
1471
+ var transport = this._transport;
1472
+ delete this._transport;
1473
+ if (transport) transport.close();
1474
+ },
1475
+
1476
+ selectTransport: function(transportTypes) {
1477
+ Faye.Transport.get(this, transportTypes, this._disabled, function(transport) {
1478
+ this.debug('Selected ? transport for ?', transport.connectionType, Faye.URI.stringify(transport.endpoint));
1479
+
1480
+ if (transport === this._transport) return;
1481
+ if (this._transport) this._transport.close();
1482
+
1483
+ this._transport = transport;
1484
+ this.connectionType = transport.connectionType;
1485
+ }, this);
1486
+ },
1487
+
1488
+ sendMessage: function(message, timeout, options) {
1489
+ if (!this._transport) return;
1490
+ options = options || {};
1491
+
1492
+ var self = this,
1493
+ id = message.id,
1494
+ attempts = options.attempts,
1495
+ deadline = options.deadline && new Date().getTime() + (options.deadline * 1000),
1496
+
1497
+ envelope = this._envelopes[id] = this._envelopes[id] ||
1498
+ {message: message, timeout: timeout, attempts: attempts, deadline: deadline};
1499
+
1500
+ if (envelope.request || envelope.timer) return;
1501
+
1502
+ if (this._attemptsExhausted(envelope) || this._deadlinePassed(envelope)) {
1503
+ delete this._envelopes[id];
1504
+ return;
1505
+ }
1506
+
1507
+ envelope.timer = Faye.ENV.setTimeout(function() {
1508
+ self.handleError(message);
1509
+ }, timeout * 1000);
1510
+
1511
+ envelope.request = this._transport.sendMessage(message);
1512
+ },
1513
+
1514
+ handleResponse: function(reply) {
1515
+ var envelope = this._envelopes[reply.id];
1516
+
1517
+ if (reply.successful !== undefined && envelope) {
1518
+ delete this._envelopes[reply.id];
1519
+ Faye.ENV.clearTimeout(envelope.timer);
1520
+ }
1521
+
1522
+ this.trigger('message', reply);
1523
+
1524
+ if (this._state === this.UP) return;
1525
+ this._state = this.UP;
1526
+ this._client.trigger('transport:up');
1527
+ },
1528
+
1529
+ handleError: function(message, immediate) {
1530
+ var envelope = this._envelopes[message.id],
1531
+ request = envelope && envelope.request,
1532
+ self = this;
1533
+
1534
+ if (!request) return;
1535
+
1536
+ request.then(function(req) {
1537
+ if (req && req.abort) req.abort();
1538
+ });
1539
+
1540
+ Faye.ENV.clearTimeout(envelope.timer);
1541
+ envelope.request = envelope.timer = null;
1542
+
1543
+ if (immediate) {
1544
+ this.sendMessage(envelope.message, envelope.timeout);
1545
+ } else {
1546
+ envelope.timer = Faye.ENV.setTimeout(function() {
1547
+ envelope.timer = null;
1548
+ self.sendMessage(envelope.message, envelope.timeout);
1549
+ }, this.retry * 1000);
1550
+ }
1551
+
1552
+ if (this._state === this.DOWN) return;
1553
+ this._state = this.DOWN;
1554
+ this._client.trigger('transport:down');
1555
+ },
1556
+
1557
+ _attemptsExhausted: function(envelope) {
1558
+ if (envelope.attempts === undefined) return false;
1559
+ envelope.attempts -= 1;
1560
+ if (envelope.attempts >= 0) return false;
1561
+ return true;
1562
+ },
1563
+
1564
+ _deadlinePassed: function(envelope) {
1565
+ var deadline = envelope.deadline;
1566
+ if (deadline === undefined) return false;
1567
+ if (new Date().getTime() <= deadline) return false;
1568
+ return true;
1569
+ }
1570
+ });
1571
+
1572
+ Faye.extend(Faye.Dispatcher.prototype, Faye.Publisher);
1573
+ Faye.extend(Faye.Dispatcher.prototype, Faye.Logging);
1574
+
1575
+ Faye.Transport = Faye.extend(Faye.Class({
1576
+ MAX_DELAY: 0,
1577
+ batching: true,
1578
+
1579
+ initialize: function(dispatcher, endpoint) {
1580
+ this._dispatcher = dispatcher;
1581
+ this.endpoint = endpoint;
1582
+ this._outbox = [];
1583
+ },
1584
+
1585
+ close: function() {},
1586
+
1587
+ encode: function(messages) {
1588
+ return '';
1589
+ },
1590
+
1591
+ sendMessage: function(message) {
1592
+ this.debug('Client ? sending message to ?: ?',
1593
+ this._dispatcher.clientId, Faye.URI.stringify(this.endpoint), message);
1594
+
1595
+ if (!this.batching) return Faye.Promise.fulfilled(this.request([message]));
1596
+
1597
+ this._outbox.push(message);
1598
+ this._flushLargeBatch();
1599
+ this._promise = this._promise || new Faye.Promise();
1600
+
1601
+ if (message.channel === Faye.Channel.HANDSHAKE) {
1602
+ this.addTimeout('publish', 0.01, this._flush, this);
1603
+ return this._promise;
1604
+ }
1605
+
1606
+ if (message.channel === Faye.Channel.CONNECT)
1607
+ this._connectMessage = message;
1608
+
1609
+ this.addTimeout('publish', this.MAX_DELAY, this._flush, this);
1610
+ return this._promise;
1611
+ },
1612
+
1613
+ _flush: function() {
1614
+ this.removeTimeout('publish');
1615
+
1616
+ if (this._outbox.length > 1 && this._connectMessage)
1617
+ this._connectMessage.advice = {timeout: 0};
1618
+
1619
+ Faye.Promise.fulfill(this._promise, this.request(this._outbox));
1620
+ delete this._promise;
1621
+
1622
+ this._connectMessage = null;
1623
+ this._outbox = [];
1624
+ },
1625
+
1626
+ _flushLargeBatch: function() {
1627
+ var string = this.encode(this._outbox);
1628
+ if (string.length < this._dispatcher.maxRequestSize) return;
1629
+ var last = this._outbox.pop();
1630
+ this._flush();
1631
+ if (last) this._outbox.push(last);
1632
+ },
1633
+
1634
+ _receive: function(replies) {
1635
+ replies = [].concat(replies);
1636
+
1637
+ this.debug('Client ? received from ? via ?: ?',
1638
+ this._dispatcher.clientId, Faye.URI.stringify(this.endpoint), this.connectionType, replies);
1639
+
1640
+ for (var i = 0, n = replies.length; i < n; i++)
1641
+ this._dispatcher.handleResponse(replies[i]);
1642
+ },
1643
+
1644
+ _handleError: function(messages, immediate) {
1645
+ messages = [].concat(messages);
1646
+
1647
+ this.debug('Client ? failed to send to ? via ?: ?',
1648
+ this._dispatcher.clientId, Faye.URI.stringify(this.endpoint), this.connectionType, messages);
1649
+
1650
+ for (var i = 0, n = messages.length; i < n; i++)
1651
+ this._dispatcher.handleError(messages[i]);
1652
+ },
1653
+
1654
+ _getCookies: function() {
1655
+ var cookies = this._dispatcher.cookies,
1656
+ url = Faye.URI.stringify(this.endpoint);
1657
+
1658
+ if (!cookies) return '';
1659
+
1660
+ return Faye.map(cookies.getCookiesSync(url), function(cookie) {
1661
+ return cookie.cookieString();
1662
+ }).join('; ');
1663
+ },
1664
+
1665
+ _storeCookies: function(setCookie) {
1666
+ var cookies = this._dispatcher.cookies,
1667
+ url = Faye.URI.stringify(this.endpoint),
1668
+ cookie;
1669
+
1670
+ if (!setCookie || !cookies) return;
1671
+ setCookie = [].concat(setCookie);
1672
+
1673
+ for (var i = 0, n = setCookie.length; i < n; i++) {
1674
+ cookie = Faye.Cookies.Cookie.parse(setCookie[i]);
1675
+ cookies.setCookieSync(cookie, url);
1676
+ }
1677
+ }
1678
+
1679
+ }), {
1680
+ get: function(dispatcher, allowed, disabled, callback, context) {
1681
+ var endpoint = dispatcher.endpoint;
1682
+
1683
+ Faye.asyncEach(this._transports, function(pair, resume) {
1684
+ var connType = pair[0], klass = pair[1],
1685
+ connEndpoint = dispatcher.endpointFor(connType);
1686
+
1687
+ if (Faye.indexOf(disabled, connType) >= 0)
1688
+ return resume();
1689
+
1690
+ if (Faye.indexOf(allowed, connType) < 0) {
1691
+ klass.isUsable(dispatcher, connEndpoint, function() {});
1692
+ return resume();
1693
+ }
1694
+
1695
+ klass.isUsable(dispatcher, connEndpoint, function(isUsable) {
1696
+ if (!isUsable) return resume();
1697
+ var transport = klass.hasOwnProperty('create') ? klass.create(dispatcher, connEndpoint) : new klass(dispatcher, connEndpoint);
1698
+ callback.call(context, transport);
1699
+ });
1700
+ }, function() {
1701
+ throw new Error('Could not find a usable connection type for ' + Faye.URI.stringify(endpoint));
1702
+ });
1703
+ },
1704
+
1705
+ register: function(type, klass) {
1706
+ this._transports.push([type, klass]);
1707
+ klass.prototype.connectionType = type;
1708
+ },
1709
+
1710
+ _transports: []
1711
+ });
1712
+
1713
+ Faye.extend(Faye.Transport.prototype, Faye.Logging);
1714
+ Faye.extend(Faye.Transport.prototype, Faye.Timeouts);
1715
+
1716
+ Faye.Event = {
1717
+ _registry: [],
1718
+
1719
+ on: function(element, eventName, callback, context) {
1720
+ var wrapped = function() { callback.call(context) };
1721
+
1722
+ if (element.addEventListener)
1723
+ element.addEventListener(eventName, wrapped, false);
1724
+ else
1725
+ element.attachEvent('on' + eventName, wrapped);
1726
+
1727
+ this._registry.push({
1728
+ _element: element,
1729
+ _type: eventName,
1730
+ _callback: callback,
1731
+ _context: context,
1732
+ _handler: wrapped
1733
+ });
1734
+ },
1735
+
1736
+ detach: function(element, eventName, callback, context) {
1737
+ var i = this._registry.length, register;
1738
+ while (i--) {
1739
+ register = this._registry[i];
1740
+
1741
+ if ((element && element !== register._element) ||
1742
+ (eventName && eventName !== register._type) ||
1743
+ (callback && callback !== register._callback) ||
1744
+ (context && context !== register._context))
1745
+ continue;
1746
+
1747
+ if (register._element.removeEventListener)
1748
+ register._element.removeEventListener(register._type, register._handler, false);
1749
+ else
1750
+ register._element.detachEvent('on' + register._type, register._handler);
1751
+
1752
+ this._registry.splice(i,1);
1753
+ register = null;
1754
+ }
1755
+ }
1756
+ };
1757
+
1758
+ if (Faye.ENV.onunload !== undefined) Faye.Event.on(Faye.ENV, 'unload', Faye.Event.detach, Faye.Event);
1759
+
1760
+ /*
1761
+ json2.js
1762
+ 2013-05-26
1763
+
1764
+ Public Domain.
1765
+
1766
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
1767
+
1768
+ See http://www.JSON.org/js.html
1769
+
1770
+
1771
+ This code should be minified before deployment.
1772
+ See http://javascript.crockford.com/jsmin.html
1773
+
1774
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
1775
+ NOT CONTROL.
1776
+
1777
+
1778
+ This file creates a global JSON object containing two methods: stringify
1779
+ and parse.
1780
+
1781
+ JSON.stringify(value, replacer, space)
1782
+ value any JavaScript value, usually an object or array.
1783
+
1784
+ replacer an optional parameter that determines how object
1785
+ values are stringified for objects. It can be a
1786
+ function or an array of strings.
1787
+
1788
+ space an optional parameter that specifies the indentation
1789
+ of nested structures. If it is omitted, the text will
1790
+ be packed without extra whitespace. If it is a number,
1791
+ it will specify the number of spaces to indent at each
1792
+ level. If it is a string (such as '\t' or '&nbsp;'),
1793
+ it contains the characters used to indent at each level.
1794
+
1795
+ This method produces a JSON text from a JavaScript value.
1796
+
1797
+ When an object value is found, if the object contains a toJSON
1798
+ method, its toJSON method will be called and the result will be
1799
+ stringified. A toJSON method does not serialize: it returns the
1800
+ value represented by the name/value pair that should be serialized,
1801
+ or undefined if nothing should be serialized. The toJSON method
1802
+ will be passed the key associated with the value, and this will be
1803
+ bound to the value
1804
+
1805
+ For example, this would serialize Dates as ISO strings.
1806
+
1807
+ Date.prototype.toJSON = function (key) {
1808
+ function f(n) {
1809
+ // Format integers to have at least two digits.
1810
+ return n < 10 ? '0' + n : n;
1811
+ }
1812
+
1813
+ return this.getUTCFullYear() + '-' +
1814
+ f(this.getUTCMonth() + 1) + '-' +
1815
+ f(this.getUTCDate()) + 'T' +
1816
+ f(this.getUTCHours()) + ':' +
1817
+ f(this.getUTCMinutes()) + ':' +
1818
+ f(this.getUTCSeconds()) + 'Z';
1819
+ };
1820
+
1821
+ You can provide an optional replacer method. It will be passed the
1822
+ key and value of each member, with this bound to the containing
1823
+ object. The value that is returned from your method will be
1824
+ serialized. If your method returns undefined, then the member will
1825
+ be excluded from the serialization.
1826
+
1827
+ If the replacer parameter is an array of strings, then it will be
1828
+ used to select the members to be serialized. It filters the results
1829
+ such that only members with keys listed in the replacer array are
1830
+ stringified.
1831
+
1832
+ Values that do not have JSON representations, such as undefined or
1833
+ functions, will not be serialized. Such values in objects will be
1834
+ dropped; in arrays they will be replaced with null. You can use
1835
+ a replacer function to replace those with JSON values.
1836
+ JSON.stringify(undefined) returns undefined.
1837
+
1838
+ The optional space parameter produces a stringification of the
1839
+ value that is filled with line breaks and indentation to make it
1840
+ easier to read.
1841
+
1842
+ If the space parameter is a non-empty string, then that string will
1843
+ be used for indentation. If the space parameter is a number, then
1844
+ the indentation will be that many spaces.
1845
+
1846
+ Example:
1847
+
1848
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
1849
+ // text is '["e",{"pluribus":"unum"}]'
1850
+
1851
+
1852
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
1853
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
1854
+
1855
+ text = JSON.stringify([new Date()], function (key, value) {
1856
+ return this[key] instanceof Date ?
1857
+ 'Date(' + this[key] + ')' : value;
1858
+ });
1859
+ // text is '["Date(---current time---)"]'
1860
+
1861
+
1862
+ JSON.parse(text, reviver)
1863
+ This method parses a JSON text to produce an object or array.
1864
+ It can throw a SyntaxError exception.
1865
+
1866
+ The optional reviver parameter is a function that can filter and
1867
+ transform the results. It receives each of the keys and values,
1868
+ and its return value is used instead of the original value.
1869
+ If it returns what it received, then the structure is not modified.
1870
+ If it returns undefined then the member is deleted.
1871
+
1872
+ Example:
1873
+
1874
+ // Parse the text. Values that look like ISO date strings will
1875
+ // be converted to Date objects.
1876
+
1877
+ myData = JSON.parse(text, function (key, value) {
1878
+ var a;
1879
+ if (typeof value === 'string') {
1880
+ a =
1881
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
1882
+ if (a) {
1883
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
1884
+ +a[5], +a[6]));
1885
+ }
1886
+ }
1887
+ return value;
1888
+ });
1889
+
1890
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
1891
+ var d;
1892
+ if (typeof value === 'string' &&
1893
+ value.slice(0, 5) === 'Date(' &&
1894
+ value.slice(-1) === ')') {
1895
+ d = new Date(value.slice(5, -1));
1896
+ if (d) {
1897
+ return d;
1898
+ }
1899
+ }
1900
+ return value;
1901
+ });
1902
+
1903
+
1904
+ This is a reference implementation. You are free to copy, modify, or
1905
+ redistribute.
1906
+ */
1907
+
1908
+ /*jslint evil: true, regexp: true */
1909
+
1910
+ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
1911
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
1912
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
1913
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
1914
+ test, toJSON, toString, valueOf
1915
+ */
1916
+
1917
+
1918
+ // Create a JSON object only if one does not already exist. We create the
1919
+ // methods in a closure to avoid creating global variables.
1920
+
1921
+ if (typeof JSON !== 'object') {
1922
+ JSON = {};
1923
+ }
1924
+
1925
+ (function () {
1926
+ 'use strict';
1927
+
1928
+ function f(n) {
1929
+ // Format integers to have at least two digits.
1930
+ return n < 10 ? '0' + n : n;
1931
+ }
1932
+
1933
+ if (typeof Date.prototype.toJSON !== 'function') {
1934
+
1935
+ Date.prototype.toJSON = function () {
1936
+
1937
+ return isFinite(this.valueOf())
1938
+ ? this.getUTCFullYear() + '-' +
1939
+ f(this.getUTCMonth() + 1) + '-' +
1940
+ f(this.getUTCDate()) + 'T' +
1941
+ f(this.getUTCHours()) + ':' +
1942
+ f(this.getUTCMinutes()) + ':' +
1943
+ f(this.getUTCSeconds()) + 'Z'
1944
+ : null;
1945
+ };
1946
+
1947
+ String.prototype.toJSON =
1948
+ Number.prototype.toJSON =
1949
+ Boolean.prototype.toJSON = function () {
1950
+ return this.valueOf();
1951
+ };
1952
+ }
1953
+
1954
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
1955
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
1956
+ gap,
1957
+ indent,
1958
+ meta = { // table of character substitutions
1959
+ '\b': '\\b',
1960
+ '\t': '\\t',
1961
+ '\n': '\\n',
1962
+ '\f': '\\f',
1963
+ '\r': '\\r',
1964
+ '"' : '\\"',
1965
+ '\\': '\\\\'
1966
+ },
1967
+ rep;
1968
+
1969
+
1970
+ function quote(string) {
1971
+
1972
+ // If the string contains no control characters, no quote characters, and no
1973
+ // backslash characters, then we can safely slap some quotes around it.
1974
+ // Otherwise we must also replace the offending characters with safe escape
1975
+ // sequences.
1976
+
1977
+ escapable.lastIndex = 0;
1978
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
1979
+ var c = meta[a];
1980
+ return typeof c === 'string'
1981
+ ? c
1982
+ : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
1983
+ }) + '"' : '"' + string + '"';
1984
+ }
1985
+
1986
+
1987
+ function str(key, holder) {
1988
+
1989
+ // Produce a string from holder[key].
1990
+
1991
+ var i, // The loop counter.
1992
+ k, // The member key.
1993
+ v, // The member value.
1994
+ length,
1995
+ mind = gap,
1996
+ partial,
1997
+ value = holder[key];
1998
+
1999
+ // If the value has a toJSON method, call it to obtain a replacement value.
2000
+
2001
+ if (value && typeof value === 'object' &&
2002
+ typeof value.toJSON === 'function') {
2003
+ value = value.toJSON(key);
2004
+ }
2005
+
2006
+ // If we were called with a replacer function, then call the replacer to
2007
+ // obtain a replacement value.
2008
+
2009
+ if (typeof rep === 'function') {
2010
+ value = rep.call(holder, key, value);
2011
+ }
2012
+
2013
+ // What happens next depends on the value's type.
2014
+
2015
+ switch (typeof value) {
2016
+ case 'string':
2017
+ return quote(value);
2018
+
2019
+ case 'number':
2020
+
2021
+ // JSON numbers must be finite. Encode non-finite numbers as null.
2022
+
2023
+ return isFinite(value) ? String(value) : 'null';
2024
+
2025
+ case 'boolean':
2026
+ case 'null':
2027
+
2028
+ // If the value is a boolean or null, convert it to a string. Note:
2029
+ // typeof null does not produce 'null'. The case is included here in
2030
+ // the remote chance that this gets fixed someday.
2031
+
2032
+ return String(value);
2033
+
2034
+ // If the type is 'object', we might be dealing with an object or an array or
2035
+ // null.
2036
+
2037
+ case 'object':
2038
+
2039
+ // Due to a specification blunder in ECMAScript, typeof null is 'object',
2040
+ // so watch out for that case.
2041
+
2042
+ if (!value) {
2043
+ return 'null';
2044
+ }
2045
+
2046
+ // Make an array to hold the partial results of stringifying this object value.
2047
+
2048
+ gap += indent;
2049
+ partial = [];
2050
+
2051
+ // Is the value an array?
2052
+
2053
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
2054
+
2055
+ // The value is an array. Stringify every element. Use null as a placeholder
2056
+ // for non-JSON values.
2057
+
2058
+ length = value.length;
2059
+ for (i = 0; i < length; i += 1) {
2060
+ partial[i] = str(i, value) || 'null';
2061
+ }
2062
+
2063
+ // Join all of the elements together, separated with commas, and wrap them in
2064
+ // brackets.
2065
+
2066
+ v = partial.length === 0
2067
+ ? '[]'
2068
+ : gap
2069
+ ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
2070
+ : '[' + partial.join(',') + ']';
2071
+ gap = mind;
2072
+ return v;
2073
+ }
2074
+
2075
+ // If the replacer is an array, use it to select the members to be stringified.
2076
+
2077
+ if (rep && typeof rep === 'object') {
2078
+ length = rep.length;
2079
+ for (i = 0; i < length; i += 1) {
2080
+ if (typeof rep[i] === 'string') {
2081
+ k = rep[i];
2082
+ v = str(k, value);
2083
+ if (v) {
2084
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
2085
+ }
2086
+ }
2087
+ }
2088
+ } else {
2089
+
2090
+ // Otherwise, iterate through all of the keys in the object.
2091
+
2092
+ for (k in value) {
2093
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
2094
+ v = str(k, value);
2095
+ if (v) {
2096
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
2097
+ }
2098
+ }
2099
+ }
2100
+ }
2101
+
2102
+ // Join all of the member texts together, separated with commas,
2103
+ // and wrap them in braces.
2104
+
2105
+ v = partial.length === 0
2106
+ ? '{}'
2107
+ : gap
2108
+ ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
2109
+ : '{' + partial.join(',') + '}';
2110
+ gap = mind;
2111
+ return v;
2112
+ }
2113
+ }
2114
+
2115
+ // If the JSON object does not yet have a stringify method, give it one.
2116
+
2117
+ Faye.stringify = function (value, replacer, space) {
2118
+
2119
+ // The stringify method takes a value and an optional replacer, and an optional
2120
+ // space parameter, and returns a JSON text. The replacer can be a function
2121
+ // that can replace values, or an array of strings that will select the keys.
2122
+ // A default replacer method can be provided. Use of the space parameter can
2123
+ // produce text that is more easily readable.
2124
+
2125
+ var i;
2126
+ gap = '';
2127
+ indent = '';
2128
+
2129
+ // If the space parameter is a number, make an indent string containing that
2130
+ // many spaces.
2131
+
2132
+ if (typeof space === 'number') {
2133
+ for (i = 0; i < space; i += 1) {
2134
+ indent += ' ';
2135
+ }
2136
+
2137
+ // If the space parameter is a string, it will be used as the indent string.
2138
+
2139
+ } else if (typeof space === 'string') {
2140
+ indent = space;
2141
+ }
2142
+
2143
+ // If there is a replacer, it must be a function or an array.
2144
+ // Otherwise, throw an error.
2145
+
2146
+ rep = replacer;
2147
+ if (replacer && typeof replacer !== 'function' &&
2148
+ (typeof replacer !== 'object' ||
2149
+ typeof replacer.length !== 'number')) {
2150
+ throw new Error('JSON.stringify');
2151
+ }
2152
+
2153
+ // Make a fake root object containing our value under the key of ''.
2154
+ // Return the result of stringifying the value.
2155
+
2156
+ return str('', {'': value});
2157
+ };
2158
+
2159
+ if (typeof JSON.stringify !== 'function') {
2160
+ JSON.stringify = Faye.stringify;
2161
+ }
2162
+
2163
+ // If the JSON object does not yet have a parse method, give it one.
2164
+
2165
+ if (typeof JSON.parse !== 'function') {
2166
+ JSON.parse = function (text, reviver) {
2167
+
2168
+ // The parse method takes a text and an optional reviver function, and returns
2169
+ // a JavaScript value if the text is a valid JSON text.
2170
+
2171
+ var j;
2172
+
2173
+ function walk(holder, key) {
2174
+
2175
+ // The walk method is used to recursively walk the resulting structure so
2176
+ // that modifications can be made.
2177
+
2178
+ var k, v, value = holder[key];
2179
+ if (value && typeof value === 'object') {
2180
+ for (k in value) {
2181
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
2182
+ v = walk(value, k);
2183
+ if (v !== undefined) {
2184
+ value[k] = v;
2185
+ } else {
2186
+ delete value[k];
2187
+ }
2188
+ }
2189
+ }
2190
+ }
2191
+ return reviver.call(holder, key, value);
2192
+ }
2193
+
2194
+
2195
+ // Parsing happens in four stages. In the first stage, we replace certain
2196
+ // Unicode characters with escape sequences. JavaScript handles many characters
2197
+ // incorrectly, either silently deleting them, or treating them as line endings.
2198
+
2199
+ text = String(text);
2200
+ cx.lastIndex = 0;
2201
+ if (cx.test(text)) {
2202
+ text = text.replace(cx, function (a) {
2203
+ return '\\u' +
2204
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
2205
+ });
2206
+ }
2207
+
2208
+ // In the second stage, we run the text against regular expressions that look
2209
+ // for non-JSON patterns. We are especially concerned with '()' and 'new'
2210
+ // because they can cause invocation, and '=' because it can cause mutation.
2211
+ // But just to be safe, we want to reject all unexpected forms.
2212
+
2213
+ // We split the second stage into 4 regexp operations in order to work around
2214
+ // crippling inefficiencies in IE's and Safari's regexp engines. First we
2215
+ // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
2216
+ // replace all simple value tokens with ']' characters. Third, we delete all
2217
+ // open brackets that follow a colon or comma or that begin the text. Finally,
2218
+ // we look to see that the remaining characters are only whitespace or ']' or
2219
+ // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
2220
+
2221
+ if (/^[\],:{}\s]*$/
2222
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
2223
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
2224
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
2225
+
2226
+ // In the third stage we use the eval function to compile the text into a
2227
+ // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
2228
+ // in JavaScript: it can begin a block or an object literal. We wrap the text
2229
+ // in parens to eliminate the ambiguity.
2230
+
2231
+ j = eval('(' + text + ')');
2232
+
2233
+ // In the optional fourth stage, we recursively walk the new structure, passing
2234
+ // each name/value pair to a reviver function for possible transformation.
2235
+
2236
+ return typeof reviver === 'function'
2237
+ ? walk({'': j}, '')
2238
+ : j;
2239
+ }
2240
+
2241
+ // If the text is not JSON parseable, then a SyntaxError is thrown.
2242
+
2243
+ throw new SyntaxError('JSON.parse');
2244
+ };
2245
+ }
2246
+ }());
2247
+
2248
+ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2249
+ UNCONNECTED: 1,
2250
+ CONNECTING: 2,
2251
+ CONNECTED: 3,
2252
+
2253
+ batching: false,
2254
+
2255
+ isUsable: function(callback, context) {
2256
+ this.callback(function() { callback.call(context, true) });
2257
+ this.errback(function() { callback.call(context, false) });
2258
+ this.connect();
2259
+ },
2260
+
2261
+ request: function(messages) {
2262
+ this._pending = this._pending || new Faye.Set();
2263
+ for (var i = 0, n = messages.length; i < n; i++) this._pending.add(messages[i]);
2264
+
2265
+ var promise = new Faye.Promise();
2266
+
2267
+ this.callback(function(socket) {
2268
+ if (!socket) return;
2269
+ socket.send(Faye.toJSON(messages));
2270
+ Faye.Promise.fulfill(promise, socket);
2271
+ }, this);
2272
+
2273
+ this.connect();
2274
+
2275
+ return {
2276
+ abort: function() { promise.then(function(ws) { ws.close() }) }
2277
+ };
2278
+ },
2279
+
2280
+ connect: function() {
2281
+ if (Faye.Transport.WebSocket._unloaded) return;
2282
+
2283
+ this._state = this._state || this.UNCONNECTED;
2284
+ if (this._state !== this.UNCONNECTED) return;
2285
+ this._state = this.CONNECTING;
2286
+
2287
+ var socket = this._createSocket();
2288
+ if (!socket) return this.setDeferredStatus('failed');
2289
+
2290
+ var self = this;
2291
+
2292
+ socket.onopen = function() {
2293
+ if (socket.headers) self._storeCookies(socket.headers['set-cookie']);
2294
+ self._socket = socket;
2295
+ self._state = self.CONNECTED;
2296
+ self._everConnected = true;
2297
+ self._ping();
2298
+ self.setDeferredStatus('succeeded', socket);
2299
+ };
2300
+
2301
+ var closed = false;
2302
+ socket.onclose = socket.onerror = function() {
2303
+ if (closed) return;
2304
+ closed = true;
2305
+
2306
+ var wasConnected = (self._state === self.CONNECTED);
2307
+ socket.onopen = socket.onclose = socket.onerror = socket.onmessage = null;
2308
+
2309
+ delete self._socket;
2310
+ self._state = self.UNCONNECTED;
2311
+ self.removeTimeout('ping');
2312
+ self.setDeferredStatus('unknown');
2313
+
2314
+ var pending = self._pending ? self._pending.toArray() : [];
2315
+ delete self._pending;
2316
+
2317
+ if (wasConnected) {
2318
+ self._handleError(pending, true);
2319
+ } else if (self._everConnected) {
2320
+ self._handleError(pending);
2321
+ } else {
2322
+ self.setDeferredStatus('failed');
2323
+ }
2324
+ };
2325
+
2326
+ socket.onmessage = function(event) {
2327
+ var replies = JSON.parse(event.data);
2328
+ if (!replies) return;
2329
+
2330
+ replies = [].concat(replies);
2331
+
2332
+ for (var i = 0, n = replies.length; i < n; i++) {
2333
+ if (replies[i].successful === undefined) continue;
2334
+ self._pending.remove(replies[i]);
2335
+ }
2336
+ self._receive(replies);
2337
+ };
2338
+ },
2339
+
2340
+ close: function() {
2341
+ if (!this._socket) return;
2342
+ this._socket.close();
2343
+ },
2344
+
2345
+ _createSocket: function() {
2346
+ var url = Faye.Transport.WebSocket.getSocketUrl(this.endpoint),
2347
+ headers = Faye.copyObject(this._dispatcher.headers),
2348
+ options = {headers: headers, ca: this._dispatcher.ca};
2349
+
2350
+ options.headers['Cookie'] = this._getCookies();
2351
+
2352
+ if (Faye.WebSocket) return new Faye.WebSocket.Client(url, [], options);
2353
+ if (Faye.ENV.MozWebSocket) return new MozWebSocket(url);
2354
+ if (Faye.ENV.WebSocket) return new WebSocket(url);
2355
+ },
2356
+
2357
+ _ping: function() {
2358
+ if (!this._socket) return;
2359
+ this._socket.send('[]');
2360
+ this.addTimeout('ping', this._dispatcher.timeout / 2, this._ping, this);
2361
+ }
2362
+
2363
+ }), {
2364
+ PROTOCOLS: {
2365
+ 'http:': 'ws:',
2366
+ 'https:': 'wss:'
2367
+ },
2368
+
2369
+ create: function(dispatcher, endpoint) {
2370
+ var sockets = dispatcher.transports.websocket = dispatcher.transports.websocket || {};
2371
+ sockets[endpoint.href] = sockets[endpoint.href] || new this(dispatcher, endpoint);
2372
+ return sockets[endpoint.href];
2373
+ },
2374
+
2375
+ getSocketUrl: function(endpoint) {
2376
+ endpoint = Faye.copyObject(endpoint);
2377
+ endpoint.protocol = this.PROTOCOLS[endpoint.protocol];
2378
+ return Faye.URI.stringify(endpoint);
2379
+ },
2380
+
2381
+ isUsable: function(dispatcher, endpoint, callback, context) {
2382
+ this.create(dispatcher, endpoint).isUsable(callback, context);
2383
+ }
2384
+ });
2385
+
2386
+ Faye.extend(Faye.Transport.WebSocket.prototype, Faye.Deferrable);
2387
+ Faye.Transport.register('websocket', Faye.Transport.WebSocket);
2388
+
2389
+ if (Faye.Event && Faye.ENV.onbeforeunload !== undefined)
2390
+ Faye.Event.on(Faye.ENV, 'beforeunload', function() {
2391
+ Faye.Transport.WebSocket._unloaded = true;
2392
+ });
2393
+
2394
+ Faye.Transport.EventSource = Faye.extend(Faye.Class(Faye.Transport, {
2395
+ initialize: function(dispatcher, endpoint) {
2396
+ Faye.Transport.prototype.initialize.call(this, dispatcher, endpoint);
2397
+ if (!Faye.ENV.EventSource) return this.setDeferredStatus('failed');
2398
+
2399
+ this._xhr = new Faye.Transport.XHR(dispatcher, endpoint);
2400
+
2401
+ endpoint = Faye.copyObject(endpoint);
2402
+ endpoint.pathname += '/' + dispatcher.clientId;
2403
+
2404
+ var socket = new EventSource(Faye.URI.stringify(endpoint)),
2405
+ self = this;
2406
+
2407
+ socket.onopen = function() {
2408
+ self._everConnected = true;
2409
+ self.setDeferredStatus('succeeded');
2410
+ };
2411
+
2412
+ socket.onerror = function() {
2413
+ if (self._everConnected) {
2414
+ self._handleError([]);
2415
+ } else {
2416
+ self.setDeferredStatus('failed');
2417
+ socket.close();
2418
+ }
2419
+ };
2420
+
2421
+ socket.onmessage = function(event) {
2422
+ self._receive(JSON.parse(event.data));
2423
+ };
2424
+
2425
+ this._socket = socket;
2426
+ },
2427
+
2428
+ close: function() {
2429
+ if (!this._socket) return;
2430
+ this._socket.onopen = this._socket.onerror = this._socket.onmessage = null;
2431
+ this._socket.close();
2432
+ delete this._socket;
2433
+ },
2434
+
2435
+ isUsable: function(callback, context) {
2436
+ this.callback(function() { callback.call(context, true) });
2437
+ this.errback(function() { callback.call(context, false) });
2438
+ },
2439
+
2440
+ encode: function(messages) {
2441
+ return this._xhr.encode(messages);
2442
+ },
2443
+
2444
+ request: function(messages) {
2445
+ return this._xhr.request(messages);
2446
+ }
2447
+
2448
+ }), {
2449
+ isUsable: function(dispatcher, endpoint, callback, context) {
2450
+ var id = dispatcher.clientId;
2451
+ if (!id) return callback.call(context, false);
2452
+
2453
+ Faye.Transport.XHR.isUsable(dispatcher, endpoint, function(usable) {
2454
+ if (!usable) return callback.call(context, false);
2455
+ this.create(dispatcher, endpoint).isUsable(callback, context);
2456
+ }, this);
2457
+ },
2458
+
2459
+ create: function(dispatcher, endpoint) {
2460
+ var sockets = dispatcher.transports.eventsource = dispatcher.transports.eventsource || {},
2461
+ id = dispatcher.clientId;
2462
+
2463
+ endpoint = Faye.copyObject(endpoint);
2464
+ endpoint.pathname += '/' + (id || '');
2465
+ var url = Faye.URI.stringify(endpoint);
2466
+
2467
+ sockets[url] = sockets[url] || new this(dispatcher, endpoint);
2468
+ return sockets[url];
2469
+ }
2470
+ });
2471
+
2472
+ Faye.extend(Faye.Transport.EventSource.prototype, Faye.Deferrable);
2473
+ Faye.Transport.register('eventsource', Faye.Transport.EventSource);
2474
+
2475
+ Faye.Transport.XHR = Faye.extend(Faye.Class(Faye.Transport, {
2476
+ encode: function(messages) {
2477
+ return Faye.toJSON(messages);
2478
+ },
2479
+
2480
+ request: function(messages) {
2481
+ var href = this.endpoint.href,
2482
+ xhr = Faye.ENV.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(),
2483
+ self = this;
2484
+
2485
+ xhr.open('POST', href, true);
2486
+ xhr.setRequestHeader('Content-Type', 'application/json');
2487
+ xhr.setRequestHeader('Pragma', 'no-cache');
2488
+ xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
2489
+
2490
+ var headers = this._dispatcher.headers;
2491
+ for (var key in headers) {
2492
+ if (!headers.hasOwnProperty(key)) continue;
2493
+ xhr.setRequestHeader(key, headers[key]);
2494
+ }
2495
+
2496
+ var abort = function() { xhr.abort() };
2497
+ if (Faye.ENV.onbeforeunload !== undefined) Faye.Event.on(Faye.ENV, 'beforeunload', abort);
2498
+
2499
+ xhr.onreadystatechange = function() {
2500
+ if (!xhr || xhr.readyState !== 4) return;
2501
+
2502
+ var replies = null,
2503
+ status = xhr.status,
2504
+ text = xhr.responseText,
2505
+ successful = (status >= 200 && status < 300) || status === 304 || status === 1223;
2506
+
2507
+ if (Faye.ENV.onbeforeunload !== undefined) Faye.Event.detach(Faye.ENV, 'beforeunload', abort);
2508
+ xhr.onreadystatechange = function() {};
2509
+ xhr = null;
2510
+
2511
+ if (!successful) return self._handleError(messages);
2512
+
2513
+ try {
2514
+ replies = JSON.parse(text);
2515
+ } catch (e) {}
2516
+
2517
+ if (replies)
2518
+ self._receive(replies);
2519
+ else
2520
+ self._handleError(messages);
2521
+ };
2522
+
2523
+ xhr.send(this.encode(messages));
2524
+ return xhr;
2525
+ }
2526
+ }), {
2527
+ isUsable: function(dispatcher, endpoint, callback, context) {
2528
+ callback.call(context, Faye.URI.isSameOrigin(endpoint));
2529
+ }
2530
+ });
2531
+
2532
+ Faye.Transport.register('long-polling', Faye.Transport.XHR);
2533
+
2534
+ Faye.Transport.CORS = Faye.extend(Faye.Class(Faye.Transport, {
2535
+ encode: function(messages) {
2536
+ return 'message=' + encodeURIComponent(Faye.toJSON(messages));
2537
+ },
2538
+
2539
+ request: function(messages) {
2540
+ var xhrClass = Faye.ENV.XDomainRequest ? XDomainRequest : XMLHttpRequest,
2541
+ xhr = new xhrClass(),
2542
+ headers = this._dispatcher.headers,
2543
+ self = this,
2544
+ key;
2545
+
2546
+ xhr.open('POST', Faye.URI.stringify(this.endpoint), true);
2547
+
2548
+ if (xhr.setRequestHeader) {
2549
+ xhr.setRequestHeader('Pragma', 'no-cache');
2550
+ for (key in headers) {
2551
+ if (!headers.hasOwnProperty(key)) continue;
2552
+ xhr.setRequestHeader(key, headers[key]);
2553
+ }
2554
+ }
2555
+
2556
+ var cleanUp = function() {
2557
+ if (!xhr) return false;
2558
+ xhr.onload = xhr.onerror = xhr.ontimeout = xhr.onprogress = null;
2559
+ xhr = null;
2560
+ };
2561
+
2562
+ xhr.onload = function() {
2563
+ var replies = null;
2564
+ try {
2565
+ replies = JSON.parse(xhr.responseText);
2566
+ } catch (e) {}
2567
+
2568
+ cleanUp();
2569
+
2570
+ if (replies)
2571
+ self._receive(replies);
2572
+ else
2573
+ self._handleError(messages);
2574
+ };
2575
+
2576
+ xhr.onerror = xhr.ontimeout = function() {
2577
+ cleanUp();
2578
+ self._handleError(messages);
2579
+ };
2580
+
2581
+ xhr.onprogress = function() {};
2582
+ xhr.send(this.encode(messages));
2583
+ return xhr;
2584
+ }
2585
+ }), {
2586
+ isUsable: function(dispatcher, endpoint, callback, context) {
2587
+ if (Faye.URI.isSameOrigin(endpoint))
2588
+ return callback.call(context, false);
2589
+
2590
+ if (Faye.ENV.XDomainRequest)
2591
+ return callback.call(context, endpoint.protocol === Faye.ENV.location.protocol);
2592
+
2593
+ if (Faye.ENV.XMLHttpRequest) {
2594
+ var xhr = new Faye.ENV.XMLHttpRequest();
2595
+ return callback.call(context, xhr.withCredentials !== undefined);
2596
+ }
2597
+ return callback.call(context, false);
2598
+ }
2599
+ });
2600
+
2601
+ Faye.Transport.register('cross-origin-long-polling', Faye.Transport.CORS);
2602
+
2603
+ Faye.Transport.JSONP = Faye.extend(Faye.Class(Faye.Transport, {
2604
+ encode: function(messages) {
2605
+ var url = Faye.copyObject(this.endpoint);
2606
+ url.query.message = Faye.toJSON(messages);
2607
+ url.query.jsonp = '__jsonp' + Faye.Transport.JSONP._cbCount + '__';
2608
+ return Faye.URI.stringify(url);
2609
+ },
2610
+
2611
+ request: function(messages) {
2612
+ var head = document.getElementsByTagName('head')[0],
2613
+ script = document.createElement('script'),
2614
+ callbackName = Faye.Transport.JSONP.getCallbackName(),
2615
+ endpoint = Faye.copyObject(this.endpoint),
2616
+ self = this;
2617
+
2618
+ endpoint.query.message = Faye.toJSON(messages);
2619
+ endpoint.query.jsonp = callbackName;
2620
+
2621
+ var cleanup = function() {
2622
+ if (!Faye.ENV[callbackName]) return false;
2623
+ Faye.ENV[callbackName] = undefined;
2624
+ try { delete Faye.ENV[callbackName] } catch (e) {}
2625
+ script.parentNode.removeChild(script);
2626
+ };
2627
+
2628
+ Faye.ENV[callbackName] = function(replies) {
2629
+ cleanup();
2630
+ self._receive(replies);
2631
+ };
2632
+
2633
+ script.type = 'text/javascript';
2634
+ script.src = Faye.URI.stringify(endpoint);
2635
+ head.appendChild(script);
2636
+
2637
+ script.onerror = function() {
2638
+ cleanup();
2639
+ self._handleError(messages);
2640
+ };
2641
+
2642
+ return {abort: cleanup};
2643
+ }
2644
+ }), {
2645
+ _cbCount: 0,
2646
+
2647
+ getCallbackName: function() {
2648
+ this._cbCount += 1;
2649
+ return '__jsonp' + this._cbCount + '__';
2650
+ },
2651
+
2652
+ isUsable: function(dispatcher, endpoint, callback, context) {
2653
+ callback.call(context, true);
2654
+ }
2655
+ });
2656
+
2657
+ Faye.Transport.register('callback-polling', Faye.Transport.JSONP);
2658
+
2659
+ })();