faye 0.8.5 → 0.8.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/node/faye-node.js CHANGED
@@ -1,29 +1,28 @@
1
- var Faye = (typeof Faye === 'object') ? Faye : {};
2
- if (typeof window !== 'undefined') window.Faye = Faye;
3
-
4
- Faye.extend = function(dest, source, overwrite) {
5
- if (!source) return dest;
6
- for (var key in source) {
7
- if (!source.hasOwnProperty(key)) continue;
8
- if (dest.hasOwnProperty(key) && overwrite === false) continue;
9
- if (dest[key] !== source[key])
10
- dest[key] = source[key];
11
- }
12
- return dest;
13
- };
1
+ 'use strict';
2
+
3
+ var Faye = {
4
+ VERSION: '0.8.11',
14
5
 
15
- Faye.extend(Faye, {
16
- VERSION: '0.8.5',
17
-
18
6
  BAYEUX_VERSION: '1.0',
19
7
  ID_LENGTH: 160,
20
8
  JSONP_CALLBACK: 'jsonpcallback',
21
9
  CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'],
22
-
10
+
23
11
  MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'],
24
-
25
- ENV: (function() { return this })(),
26
-
12
+
13
+ ENV: (typeof global === 'undefined') ? window : global,
14
+
15
+ extend: function(dest, source, overwrite) {
16
+ if (!source) return dest;
17
+ for (var key in source) {
18
+ if (!source.hasOwnProperty(key)) continue;
19
+ if (dest.hasOwnProperty(key) && overwrite === false) continue;
20
+ if (dest[key] !== source[key])
21
+ dest[key] = source[key];
22
+ }
23
+ return dest;
24
+ },
25
+
27
26
  random: function(bitlength) {
28
27
  bitlength = bitlength || this.ID_LENGTH;
29
28
  if (bitlength > 32) {
@@ -37,16 +36,16 @@ Faye.extend(Faye, {
37
36
  var limit = Math.pow(2, bitlength) - 1,
38
37
  maxSize = limit.toString(36).length,
39
38
  string = Math.floor(Math.random() * limit).toString(36);
40
-
39
+
41
40
  while (string.length < maxSize) string = '0' + string;
42
41
  return string;
43
42
  },
44
-
43
+
45
44
  clientIdFromMessages: function(messages) {
46
45
  var first = [].concat(messages)[0];
47
46
  return first && first.clientId;
48
47
  },
49
-
48
+
50
49
  copyObject: function(object) {
51
50
  var clone, i, key;
52
51
  if (object instanceof Array) {
@@ -62,7 +61,7 @@ Faye.extend(Faye, {
62
61
  return object;
63
62
  }
64
63
  },
65
-
64
+
66
65
  commonElement: function(lista, listb) {
67
66
  for (var i = 0, n = lista.length; i < n; i++) {
68
67
  if (this.indexOf(listb, lista[i]) !== -1)
@@ -70,20 +69,20 @@ Faye.extend(Faye, {
70
69
  }
71
70
  return null;
72
71
  },
73
-
72
+
74
73
  indexOf: function(list, needle) {
75
74
  if (list.indexOf) return list.indexOf(needle);
76
-
75
+
77
76
  for (var i = 0, n = list.length; i < n; i++) {
78
77
  if (list[i] === needle) return i;
79
78
  }
80
79
  return -1;
81
80
  },
82
-
81
+
83
82
  map: function(object, callback, context) {
84
83
  if (object.map) return object.map(callback, context);
85
84
  var result = [];
86
-
85
+
87
86
  if (object instanceof Array) {
88
87
  for (var i = 0, n = object.length; i < n; i++) {
89
88
  result.push(callback.call(context || null, object[i], i));
@@ -96,7 +95,7 @@ Faye.extend(Faye, {
96
95
  }
97
96
  return result;
98
97
  },
99
-
98
+
100
99
  filter: function(array, callback, context) {
101
100
  var result = [];
102
101
  for (var i = 0, n = array.length; i < n; i++) {
@@ -105,7 +104,7 @@ Faye.extend(Faye, {
105
104
  }
106
105
  return result;
107
106
  },
108
-
107
+
109
108
  asyncEach: function(list, iterator, callback, context) {
110
109
  var n = list.length,
111
110
  i = -1,
@@ -132,7 +131,7 @@ Faye.extend(Faye, {
132
131
  };
133
132
  resume();
134
133
  },
135
-
134
+
136
135
  // http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/
137
136
  toJSON: function(object) {
138
137
  if (this.stringify)
@@ -141,14 +140,14 @@ Faye.extend(Faye, {
141
140
  ? this[key]
142
141
  : value;
143
142
  });
144
-
143
+
145
144
  return JSON.stringify(object);
146
145
  },
147
-
146
+
148
147
  logger: function(message) {
149
148
  if (typeof console !== 'undefined') console.log(message);
150
149
  },
151
-
150
+
152
151
  timestamp: function() {
153
152
  var date = new Date(),
154
153
  year = date.getFullYear(),
@@ -157,15 +156,18 @@ Faye.extend(Faye, {
157
156
  hour = date.getHours(),
158
157
  minute = date.getMinutes(),
159
158
  second = date.getSeconds();
160
-
159
+
161
160
  var pad = function(n) {
162
161
  return n < 10 ? '0' + n : String(n);
163
162
  };
164
-
163
+
165
164
  return pad(year) + '-' + pad(month) + '-' + pad(day) + ' ' +
166
165
  pad(hour) + ':' + pad(minute) + ':' + pad(second);
167
166
  }
168
- });
167
+ };
168
+
169
+ if (typeof window !== 'undefined')
170
+ window.Faye = Faye;
169
171
 
170
172
 
171
173
  Faye.Class = function(parent, methods) {
@@ -173,18 +175,18 @@ Faye.Class = function(parent, methods) {
173
175
  methods = parent;
174
176
  parent = Object;
175
177
  }
176
-
178
+
177
179
  var klass = function() {
178
180
  if (!this.initialize) return this;
179
181
  return this.initialize.apply(this, arguments) || this;
180
182
  };
181
-
183
+
182
184
  var bridge = function() {};
183
185
  bridge.prototype = parent.prototype;
184
-
186
+
185
187
  klass.prototype = new bridge();
186
188
  Faye.extend(klass.prototype, methods);
187
-
189
+
188
190
  return klass;
189
191
  };
190
192
 
@@ -193,18 +195,18 @@ Faye.Namespace = Faye.Class({
193
195
  initialize: function() {
194
196
  this._used = {};
195
197
  },
196
-
198
+
197
199
  exists: function(id) {
198
200
  return this._used.hasOwnProperty(id);
199
201
  },
200
-
202
+
201
203
  generate: function() {
202
204
  var name = Faye.random();
203
205
  while (this._used.hasOwnProperty(name))
204
206
  name = Faye.random();
205
207
  return this._used[name] = name;
206
208
  },
207
-
209
+
208
210
  release: function(id) {
209
211
  delete this._used[id];
210
212
  }
@@ -217,7 +219,7 @@ Faye.Error = Faye.Class({
217
219
  this.params = Array.prototype.slice.call(params);
218
220
  this.message = message;
219
221
  },
220
-
222
+
221
223
  toString: function() {
222
224
  return this.code + ':' +
223
225
  this.params.join(',') + ':' +
@@ -291,14 +293,14 @@ Faye.Error.serverError = function() {
291
293
  Faye.Deferrable = {
292
294
  callback: function(callback, context) {
293
295
  if (!callback) return;
294
-
296
+
295
297
  if (this._deferredStatus === 'succeeded')
296
298
  return callback.apply(context, this._deferredArgs);
297
-
299
+
298
300
  this._callbacks = this._callbacks || [];
299
301
  this._callbacks.push([callback, context]);
300
302
  },
301
-
303
+
302
304
  timeout: function(seconds, message) {
303
305
  var _this = this;
304
306
  var timer = Faye.ENV.setTimeout(function() {
@@ -306,7 +308,7 @@ Faye.Deferrable = {
306
308
  }, seconds * 1000);
307
309
  this._timer = timer;
308
310
  },
309
-
311
+
310
312
  errback: function(callback, context) {
311
313
  if (!callback) return;
312
314
 
@@ -324,17 +326,17 @@ Faye.Deferrable = {
324
326
  var args = Array.prototype.slice.call(arguments),
325
327
  status = args.shift(),
326
328
  callbacks;
327
-
329
+
328
330
  this._deferredStatus = status;
329
331
  this._deferredArgs = args;
330
-
332
+
331
333
  if (status === 'succeeded')
332
334
  callbacks = this._callbacks;
333
335
  else if (status === 'failed')
334
336
  callbacks = this._errbacks;
335
-
337
+
336
338
  if (!callbacks) return;
337
-
339
+
338
340
  var callback;
339
341
  while (callback = callbacks.shift())
340
342
  callback[0].apply(callback[1], this._deferredArgs);
@@ -347,39 +349,39 @@ Faye.Publisher = {
347
349
  if (!this._subscribers || !this._subscribers[eventType]) return 0;
348
350
  return this._subscribers[eventType].length;
349
351
  },
350
-
352
+
351
353
  bind: function(eventType, listener, context) {
352
354
  this._subscribers = this._subscribers || {};
353
355
  var list = this._subscribers[eventType] = this._subscribers[eventType] || [];
354
356
  list.push([listener, context]);
355
357
  },
356
-
358
+
357
359
  unbind: function(eventType, listener, context) {
358
360
  if (!this._subscribers || !this._subscribers[eventType]) return;
359
-
361
+
360
362
  if (!listener) {
361
363
  delete this._subscribers[eventType];
362
364
  return;
363
365
  }
364
366
  var list = this._subscribers[eventType],
365
367
  i = list.length;
366
-
368
+
367
369
  while (i--) {
368
370
  if (listener !== list[i][0]) continue;
369
371
  if (context && list[i][1] !== context) continue;
370
372
  list.splice(i,1);
371
373
  }
372
374
  },
373
-
375
+
374
376
  trigger: function() {
375
377
  var args = Array.prototype.slice.call(arguments),
376
378
  eventType = args.shift();
377
-
379
+
378
380
  if (!this._subscribers || !this._subscribers[eventType]) return;
379
-
381
+
380
382
  var listeners = this._subscribers[eventType].slice(),
381
383
  listener;
382
-
384
+
383
385
  for (var i = 0, n = listeners.length; i < n; i++) {
384
386
  listener = listeners[i];
385
387
  listener[0].apply(listener[1], args);
@@ -398,7 +400,7 @@ Faye.Timeouts = {
398
400
  callback.call(context);
399
401
  }, 1000 * delay);
400
402
  },
401
-
403
+
402
404
  removeTimeout: function(name) {
403
405
  this._timeouts = this._timeouts || {};
404
406
  var timeout = this._timeouts[name];
@@ -416,19 +418,19 @@ Faye.Logging = {
416
418
  info: 1,
417
419
  debug: 0
418
420
  },
419
-
421
+
420
422
  logLevel: 'error',
421
-
423
+
422
424
  log: function(messageArgs, level) {
423
425
  if (!Faye.logger) return;
424
-
426
+
425
427
  var levels = Faye.Logging.LOG_LEVELS;
426
428
  if (levels[Faye.Logging.logLevel] > levels[level]) return;
427
-
429
+
428
430
  var messageArgs = Array.prototype.slice.apply(messageArgs),
429
431
  banner = ' [' + level.toUpperCase() + '] [Faye',
430
432
  klass = this.className,
431
-
433
+
432
434
  message = messageArgs.shift().replace(/\?/g, function() {
433
435
  try {
434
436
  return Faye.toJSON(messageArgs.shift());
@@ -436,7 +438,7 @@ Faye.Logging = {
436
438
  return '[Object]';
437
439
  }
438
440
  });
439
-
441
+
440
442
  for (var key in Faye) {
441
443
  if (klass) continue;
442
444
  if (typeof Faye[key] !== 'function') continue;
@@ -444,7 +446,7 @@ Faye.Logging = {
444
446
  }
445
447
  if (klass) banner += '.' + klass;
446
448
  banner += '] ';
447
-
449
+
448
450
  Faye.logger(Faye.timestamp() + banner + message);
449
451
  }
450
452
  };
@@ -514,7 +516,7 @@ Faye.Extensible = {
514
516
  this._extensions.push(extension);
515
517
  if (extension.added) extension.added(this);
516
518
  },
517
-
519
+
518
520
  removeExtension: function(extension) {
519
521
  if (!this._extensions) return;
520
522
  var i = this._extensions.length;
@@ -524,19 +526,19 @@ Faye.Extensible = {
524
526
  if (extension.removed) extension.removed(this);
525
527
  }
526
528
  },
527
-
529
+
528
530
  pipeThroughExtensions: function(stage, message, callback, context) {
529
531
  this.debug('Passing through ? extensions: ?', stage, message);
530
532
 
531
533
  if (!this._extensions) return callback.call(context, message);
532
534
  var extensions = this._extensions.slice();
533
-
535
+
534
536
  var pipe = function(message) {
535
537
  if (!message) return callback.call(context, message);
536
-
538
+
537
539
  var extension = extensions.shift();
538
540
  if (!extension) return callback.call(context, message);
539
-
541
+
540
542
  if (extension[stage]) extension[stage](message, pipe);
541
543
  else pipe(message);
542
544
  };
@@ -550,11 +552,11 @@ Faye.Channel = Faye.Class({
550
552
  initialize: function(name) {
551
553
  this.id = this.name = name;
552
554
  },
553
-
555
+
554
556
  push: function(message) {
555
557
  this.trigger('message', message);
556
558
  },
557
-
559
+
558
560
  isUnused: function() {
559
561
  return this.countListeners('message') === 0;
560
562
  }
@@ -568,75 +570,75 @@ Faye.extend(Faye.Channel, {
568
570
  SUBSCRIBE: '/meta/subscribe',
569
571
  UNSUBSCRIBE: '/meta/unsubscribe',
570
572
  DISCONNECT: '/meta/disconnect',
571
-
573
+
572
574
  META: 'meta',
573
575
  SERVICE: 'service',
574
-
576
+
575
577
  expand: function(name) {
576
578
  var segments = this.parse(name),
577
579
  channels = ['/**', name];
578
-
580
+
579
581
  var copy = segments.slice();
580
582
  copy[copy.length - 1] = '*';
581
583
  channels.push(this.unparse(copy));
582
-
584
+
583
585
  for (var i = 1, n = segments.length; i < n; i++) {
584
586
  copy = segments.slice(0, i);
585
587
  copy.push('**');
586
588
  channels.push(this.unparse(copy));
587
589
  }
588
-
590
+
589
591
  return channels;
590
592
  },
591
-
593
+
592
594
  isValid: function(name) {
593
595
  return Faye.Grammar.CHANNEL_NAME.test(name) ||
594
596
  Faye.Grammar.CHANNEL_PATTERN.test(name);
595
597
  },
596
-
598
+
597
599
  parse: function(name) {
598
600
  if (!this.isValid(name)) return null;
599
601
  return name.split('/').slice(1);
600
602
  },
601
-
603
+
602
604
  unparse: function(segments) {
603
605
  return '/' + segments.join('/');
604
606
  },
605
-
607
+
606
608
  isMeta: function(name) {
607
609
  var segments = this.parse(name);
608
610
  return segments ? (segments[0] === this.META) : null;
609
611
  },
610
-
612
+
611
613
  isService: function(name) {
612
614
  var segments = this.parse(name);
613
615
  return segments ? (segments[0] === this.SERVICE) : null;
614
616
  },
615
-
617
+
616
618
  isSubscribable: function(name) {
617
619
  if (!this.isValid(name)) return null;
618
620
  return !this.isMeta(name) && !this.isService(name);
619
621
  },
620
-
622
+
621
623
  Set: Faye.Class({
622
624
  initialize: function() {
623
625
  this._channels = {};
624
626
  },
625
-
627
+
626
628
  getKeys: function() {
627
629
  var keys = [];
628
630
  for (var key in this._channels) keys.push(key);
629
631
  return keys;
630
632
  },
631
-
633
+
632
634
  remove: function(name) {
633
635
  delete this._channels[name];
634
636
  },
635
-
637
+
636
638
  hasSubscription: function(name) {
637
639
  return this._channels.hasOwnProperty(name);
638
640
  },
639
-
641
+
640
642
  subscribe: function(names, callback, context) {
641
643
  if (!callback) return;
642
644
  var name;
@@ -646,12 +648,12 @@ Faye.extend(Faye.Channel, {
646
648
  channel.bind('message', callback, context);
647
649
  }
648
650
  },
649
-
651
+
650
652
  unsubscribe: function(name, callback, context) {
651
653
  var channel = this._channels[name];
652
654
  if (!channel) return false;
653
655
  channel.unbind('message', callback, context);
654
-
656
+
655
657
  if (channel.isUnused()) {
656
658
  this.remove(name);
657
659
  return true;
@@ -659,10 +661,10 @@ Faye.extend(Faye.Channel, {
659
661
  return false;
660
662
  }
661
663
  },
662
-
664
+
663
665
  distributeMessage: function(message) {
664
666
  var channels = Faye.Channel.expand(message.channel);
665
-
667
+
666
668
  for (var i = 0, n = channels.length; i < n; i++) {
667
669
  var channel = this._channels[channels[i]];
668
670
  if (channel) channel.trigger('message', message.data);
@@ -683,13 +685,13 @@ Faye.Subscription = Faye.Class({
683
685
  this._context = context;
684
686
  this._cancelled = false;
685
687
  },
686
-
688
+
687
689
  cancel: function() {
688
690
  if (this._cancelled) return;
689
691
  this._client.unsubscribe(this._channels, this._callback, this._context);
690
692
  this._cancelled = true;
691
693
  },
692
-
694
+
693
695
  unsubscribe: function() {
694
696
  this.cancel();
695
697
  }
@@ -703,20 +705,20 @@ Faye.Client = Faye.Class({
703
705
  CONNECTING: 2,
704
706
  CONNECTED: 3,
705
707
  DISCONNECTED: 4,
706
-
708
+
707
709
  HANDSHAKE: 'handshake',
708
710
  RETRY: 'retry',
709
711
  NONE: 'none',
710
-
712
+
711
713
  CONNECTION_TIMEOUT: 60.0,
712
714
  DEFAULT_RETRY: 5.0,
713
-
715
+
714
716
  DEFAULT_ENDPOINT: '/bayeux',
715
717
  INTERVAL: 0.0,
716
-
718
+
717
719
  initialize: function(endpoint, options) {
718
720
  this.info('New client created for ?', endpoint);
719
-
721
+
720
722
  this._options = options || {};
721
723
  this.endpoint = endpoint || this.DEFAULT_ENDPOINT;
722
724
  this.endpoints = this._options.endpoints || {};
@@ -725,36 +727,34 @@ Faye.Client = Faye.Class({
725
727
  this._headers = {};
726
728
  this._disabled = [];
727
729
  this.retry = this._options.retry || this.DEFAULT_RETRY;
728
-
729
- this._selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
730
-
730
+
731
731
  this._state = this.UNCONNECTED;
732
732
  this._channels = new Faye.Channel.Set();
733
733
  this._messageId = 0;
734
-
734
+
735
735
  this._responseCallbacks = {};
736
-
736
+
737
737
  this._advice = {
738
738
  reconnect: this.RETRY,
739
739
  interval: 1000 * (this._options.interval || this.INTERVAL),
740
740
  timeout: 1000 * (this._options.timeout || this.CONNECTION_TIMEOUT)
741
741
  };
742
-
742
+
743
743
  if (Faye.Event)
744
744
  Faye.Event.on(Faye.ENV, 'beforeunload', function() {
745
745
  if (Faye.indexOf(this._disabled, 'autodisconnect') < 0)
746
746
  this.disconnect();
747
747
  }, this);
748
748
  },
749
-
749
+
750
750
  disable: function(feature) {
751
751
  this._disabled.push(feature);
752
752
  },
753
-
753
+
754
754
  setHeader: function(name, value) {
755
755
  this._headers[name] = value;
756
756
  },
757
-
757
+
758
758
  getClientId: function() {
759
759
  return this._clientId;
760
760
  },
@@ -775,7 +775,7 @@ Faye.Client = Faye.Class({
775
775
  // MAY include: * minimumVersion
776
776
  // * ext
777
777
  // * id
778
- //
778
+ //
779
779
  // Success Response Failed Response
780
780
  // MUST include: * channel MUST include: * channel
781
781
  // * version * successful
@@ -790,33 +790,31 @@ Faye.Client = Faye.Class({
790
790
  handshake: function(callback, context) {
791
791
  if (this._advice.reconnect === this.NONE) return;
792
792
  if (this._state !== this.UNCONNECTED) return;
793
-
793
+
794
794
  this._state = this.CONNECTING;
795
795
  var self = this;
796
-
796
+
797
797
  this.info('Initiating handshake with ?', this.endpoint);
798
-
798
+ this._selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
799
+
799
800
  this._send({
800
801
  channel: Faye.Channel.HANDSHAKE,
801
802
  version: Faye.BAYEUX_VERSION,
802
803
  supportedConnectionTypes: [this._transport.connectionType]
803
-
804
+
804
805
  }, function(response) {
805
-
806
+
806
807
  if (response.successful) {
807
808
  this._state = this.CONNECTED;
808
809
  this._clientId = response.clientId;
809
-
810
- var connectionTypes = Faye.filter(response.supportedConnectionTypes, function(connType) {
811
- return Faye.indexOf(this._disabled, connType) < 0;
812
- }, this);
813
- this._selectTransport(connectionTypes);
814
-
810
+
811
+ this._selectTransport(response.supportedConnectionTypes);
812
+
815
813
  this.info('Handshake successful: ?', this._clientId);
816
-
814
+
817
815
  this.subscribe(this._channels.getKeys(), true);
818
816
  if (callback) callback.call(context);
819
-
817
+
820
818
  } else {
821
819
  this.info('Handshake unsuccessful');
822
820
  Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._advice.interval);
@@ -824,7 +822,7 @@ Faye.Client = Faye.Class({
824
822
  }
825
823
  }, this);
826
824
  },
827
-
825
+
828
826
  // Request Response
829
827
  // MUST include: * channel MUST include: * channel
830
828
  // * clientId * successful
@@ -837,30 +835,30 @@ Faye.Client = Faye.Class({
837
835
  connect: function(callback, context) {
838
836
  if (this._advice.reconnect === this.NONE) return;
839
837
  if (this._state === this.DISCONNECTED) return;
840
-
838
+
841
839
  if (this._state === this.UNCONNECTED)
842
840
  return this.handshake(function() { this.connect(callback, context) }, this);
843
-
841
+
844
842
  this.callback(callback, context);
845
843
  if (this._state !== this.CONNECTED) return;
846
-
844
+
847
845
  this.info('Calling deferred actions for ?', this._clientId);
848
846
  this.setDeferredStatus('succeeded');
849
847
  this.setDeferredStatus('deferred');
850
-
848
+
851
849
  if (this._connectRequest) return;
852
850
  this._connectRequest = true;
853
-
851
+
854
852
  this.info('Initiating connection for ?', this._clientId);
855
-
853
+
856
854
  this._send({
857
855
  channel: Faye.Channel.CONNECT,
858
856
  clientId: this._clientId,
859
857
  connectionType: this._transport.connectionType
860
-
858
+
861
859
  }, this._cycleConnection, this);
862
860
  },
863
-
861
+
864
862
  // Request Response
865
863
  // MUST include: * channel MUST include: * channel
866
864
  // * clientId * successful
@@ -871,21 +869,21 @@ Faye.Client = Faye.Class({
871
869
  disconnect: function() {
872
870
  if (this._state !== this.CONNECTED) return;
873
871
  this._state = this.DISCONNECTED;
874
-
872
+
875
873
  this.info('Disconnecting ?', this._clientId);
876
-
874
+
877
875
  this._send({
878
876
  channel: Faye.Channel.DISCONNECT,
879
877
  clientId: this._clientId
880
-
878
+
881
879
  }, function(response) {
882
880
  if (response.successful) this._transport.close();
883
881
  }, this);
884
-
882
+
885
883
  this.info('Clearing channel listeners for ?', this._clientId);
886
884
  this._channels = new Faye.Channel.Set();
887
885
  },
888
-
886
+
889
887
  // Request Response
890
888
  // MUST include: * channel MUST include: * channel
891
889
  // * clientId * successful
@@ -901,41 +899,41 @@ Faye.Client = Faye.Class({
901
899
  return Faye.map(channel, function(c) {
902
900
  return this.subscribe(c, callback, context);
903
901
  }, this);
904
-
902
+
905
903
  var subscription = new Faye.Subscription(this, channel, callback, context),
906
904
  force = (callback === true),
907
905
  hasSubscribe = this._channels.hasSubscription(channel);
908
-
906
+
909
907
  if (hasSubscribe && !force) {
910
908
  this._channels.subscribe([channel], callback, context);
911
909
  subscription.setDeferredStatus('succeeded');
912
910
  return subscription;
913
911
  }
914
-
912
+
915
913
  this.connect(function() {
916
914
  this.info('Client ? attempting to subscribe to ?', this._clientId, channel);
917
915
  if (!force) this._channels.subscribe([channel], callback, context);
918
-
916
+
919
917
  this._send({
920
918
  channel: Faye.Channel.SUBSCRIBE,
921
919
  clientId: this._clientId,
922
920
  subscription: channel
923
-
921
+
924
922
  }, function(response) {
925
923
  if (!response.successful) {
926
924
  subscription.setDeferredStatus('failed', Faye.Error.parse(response.error));
927
925
  return this._channels.unsubscribe(channel, callback, context);
928
926
  }
929
-
927
+
930
928
  var channels = [].concat(response.subscription);
931
929
  this.info('Subscription acknowledged for ? to ?', this._clientId, channels);
932
930
  subscription.setDeferredStatus('succeeded');
933
931
  }, this);
934
932
  }, this);
935
-
933
+
936
934
  return subscription;
937
935
  },
938
-
936
+
939
937
  // Request Response
940
938
  // MUST include: * channel MUST include: * channel
941
939
  // * clientId * successful
@@ -951,27 +949,27 @@ Faye.Client = Faye.Class({
951
949
  return Faye.map(channel, function(c) {
952
950
  return this.unsubscribe(c, callback, context);
953
951
  }, this);
954
-
952
+
955
953
  var dead = this._channels.unsubscribe(channel, callback, context);
956
954
  if (!dead) return;
957
-
955
+
958
956
  this.connect(function() {
959
957
  this.info('Client ? attempting to unsubscribe from ?', this._clientId, channel);
960
-
958
+
961
959
  this._send({
962
960
  channel: Faye.Channel.UNSUBSCRIBE,
963
961
  clientId: this._clientId,
964
962
  subscription: channel
965
-
963
+
966
964
  }, function(response) {
967
965
  if (!response.successful) return;
968
-
966
+
969
967
  var channels = [].concat(response.subscription);
970
968
  this.info('Unsubscription acknowledged for ? from ?', this._clientId, channels);
971
969
  }, this);
972
970
  }, this);
973
971
  },
974
-
972
+
975
973
  // Request Response
976
974
  // MUST include: * channel MUST include: * channel
977
975
  // * data * successful
@@ -980,10 +978,10 @@ Faye.Client = Faye.Class({
980
978
  // * ext * ext
981
979
  publish: function(channel, data) {
982
980
  var publication = new Faye.Publication();
983
-
981
+
984
982
  this.connect(function() {
985
983
  this.info('Client ? queueing published message to ?: ?', this._clientId, channel, data);
986
-
984
+
987
985
  this._send({
988
986
  channel: channel,
989
987
  data: data,
@@ -995,41 +993,44 @@ Faye.Client = Faye.Class({
995
993
  publication.setDeferredStatus('failed', Faye.Error.parse(response.error));
996
994
  }, this);
997
995
  }, this);
998
-
996
+
999
997
  return publication;
1000
998
  },
1001
-
999
+
1002
1000
  receiveMessage: function(message) {
1003
1001
  this.pipeThroughExtensions('incoming', message, function(message) {
1004
1002
  if (!message) return;
1005
-
1003
+
1006
1004
  if (message.advice) this._handleAdvice(message.advice);
1007
1005
  this._deliverMessage(message);
1008
-
1006
+
1009
1007
  if (message.successful === undefined) return;
1010
-
1008
+
1011
1009
  var callback = this._responseCallbacks[message.id];
1012
1010
  if (!callback) return;
1013
-
1011
+
1014
1012
  delete this._responseCallbacks[message.id];
1015
1013
  callback[0].call(callback[1], message);
1016
1014
  }, this);
1017
1015
  },
1018
-
1016
+
1019
1017
  _selectTransport: function(transportTypes) {
1020
- Faye.Transport.get(this, transportTypes, function(transport) {
1018
+ Faye.Transport.get(this, transportTypes, this._disabled, function(transport) {
1021
1019
  this.debug('Selected ? transport for ?', transport.connectionType, transport.endpoint);
1022
-
1020
+
1021
+ if (transport === this._transport) return;
1022
+ if (this._transport) this._transport.close();
1023
+
1023
1024
  this._transport = transport;
1024
1025
  this._transport.cookies = this._cookies;
1025
1026
  this._transport.headers = this._headers;
1026
-
1027
+
1027
1028
  transport.bind('down', function() {
1028
1029
  if (this._transportUp !== undefined && !this._transportUp) return;
1029
1030
  this._transportUp = false;
1030
1031
  this.trigger('transport:down');
1031
1032
  }, this);
1032
-
1033
+
1033
1034
  transport.bind('up', function() {
1034
1035
  if (this._transportUp !== undefined && this._transportUp) return;
1035
1036
  this._transportUp = true;
@@ -1037,7 +1038,7 @@ Faye.Client = Faye.Class({
1037
1038
  }, this);
1038
1039
  }, this);
1039
1040
  },
1040
-
1041
+
1041
1042
  _send: function(message, callback, context) {
1042
1043
  message.id = this._generateMessageId();
1043
1044
  if (callback) this._responseCallbacks[message.id] = [callback, context];
@@ -1047,7 +1048,7 @@ Faye.Client = Faye.Class({
1047
1048
  this._transport.send(message, this._advice.timeout / 1000);
1048
1049
  }, this);
1049
1050
  },
1050
-
1051
+
1051
1052
  _generateMessageId: function() {
1052
1053
  this._messageId += 1;
1053
1054
  if (this._messageId >= Math.pow(2,32)) this._messageId = 0;
@@ -1056,26 +1057,26 @@ Faye.Client = Faye.Class({
1056
1057
 
1057
1058
  _handleAdvice: function(advice) {
1058
1059
  Faye.extend(this._advice, advice);
1059
-
1060
+
1060
1061
  if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {
1061
1062
  this._state = this.UNCONNECTED;
1062
1063
  this._clientId = null;
1063
1064
  this._cycleConnection();
1064
1065
  }
1065
1066
  },
1066
-
1067
+
1067
1068
  _deliverMessage: function(message) {
1068
1069
  if (!message.channel || message.data === undefined) return;
1069
1070
  this.info('Client ? calling listeners for ? with ?', this._clientId, message.channel, message.data);
1070
1071
  this._channels.distributeMessage(message);
1071
1072
  },
1072
-
1073
+
1073
1074
  _teardownConnection: function() {
1074
1075
  if (!this._connectRequest) return;
1075
1076
  this._connectRequest = null;
1076
1077
  this.info('Closed connection for ?', this._clientId);
1077
1078
  },
1078
-
1079
+
1079
1080
  _cycleConnection: function() {
1080
1081
  this._teardownConnection();
1081
1082
  var self = this;
@@ -1098,9 +1099,9 @@ Faye.Transport = Faye.extend(Faye.Class({
1098
1099
  this.endpoint = endpoint;
1099
1100
  this._outbox = [];
1100
1101
  },
1101
-
1102
+
1102
1103
  close: function() {},
1103
-
1104
+
1104
1105
  send: function(message, timeout) {
1105
1106
  this.debug('Client ? sending message to ?: ?',
1106
1107
  this._client._clientId, this.endpoint, message);
@@ -1129,48 +1130,50 @@ Faye.Transport = Faye.extend(Faye.Class({
1129
1130
  this._connectMessage.advice = {timeout: 0};
1130
1131
 
1131
1132
  this.request(this._outbox, this._timeout);
1132
-
1133
+
1133
1134
  this._connectMessage = null;
1134
1135
  this._outbox = [];
1135
1136
  },
1136
-
1137
+
1137
1138
  receive: function(responses) {
1138
1139
  this.debug('Client ? received from ?: ?',
1139
1140
  this._client._clientId, this.endpoint, responses);
1140
-
1141
+
1141
1142
  for (var i = 0, n = responses.length; i < n; i++) {
1142
1143
  this._client.receiveMessage(responses[i]);
1143
1144
  }
1144
1145
  },
1145
-
1146
+
1146
1147
  retry: function(message, timeout) {
1147
1148
  var called = false,
1148
1149
  retry = this._client.retry * 1000,
1149
1150
  self = this;
1150
-
1151
+
1151
1152
  return function() {
1152
1153
  if (called) return;
1153
1154
  called = true;
1154
1155
  Faye.ENV.setTimeout(function() { self.request(message, timeout) }, retry);
1155
1156
  };
1156
1157
  }
1157
-
1158
+
1158
1159
  }), {
1159
1160
  MAX_URL_LENGTH: 2048,
1160
-
1161
- get: function(client, connectionTypes, callback, context) {
1161
+
1162
+ get: function(client, allowed, disabled, callback, context) {
1162
1163
  var endpoint = client.endpoint;
1163
- if (connectionTypes === undefined) connectionTypes = this.supportedConnectionTypes();
1164
-
1164
+
1165
1165
  Faye.asyncEach(this._transports, function(pair, resume) {
1166
1166
  var connType = pair[0], klass = pair[1],
1167
1167
  connEndpoint = client.endpoints[connType] || endpoint;
1168
-
1169
- if (Faye.indexOf(connectionTypes, connType) < 0) {
1168
+
1169
+ if (Faye.indexOf(disabled, connType) >= 0)
1170
+ return resume();
1171
+
1172
+ if (Faye.indexOf(allowed, connType) < 0) {
1170
1173
  klass.isUsable(client, connEndpoint, function() {});
1171
1174
  return resume();
1172
1175
  }
1173
-
1176
+
1174
1177
  klass.isUsable(client, connEndpoint, function(isUsable) {
1175
1178
  if (!isUsable) return resume();
1176
1179
  var transport = klass.hasOwnProperty('create') ? klass.create(client, connEndpoint) : new klass(client, connEndpoint);
@@ -1180,17 +1183,13 @@ Faye.Transport = Faye.extend(Faye.Class({
1180
1183
  throw new Error('Could not find a usable connection type for ' + endpoint);
1181
1184
  });
1182
1185
  },
1183
-
1186
+
1184
1187
  register: function(type, klass) {
1185
1188
  this._transports.push([type, klass]);
1186
1189
  klass.prototype.connectionType = type;
1187
1190
  },
1188
-
1189
- _transports: [],
1190
-
1191
- supportedConnectionTypes: function() {
1192
- return Faye.map(this._transports, function(pair) { return pair[0] });
1193
- }
1191
+
1192
+ _transports: []
1194
1193
  });
1195
1194
 
1196
1195
  Faye.extend(Faye.Transport.prototype, Faye.Logging);
@@ -1202,42 +1201,42 @@ Faye.Set = Faye.Class({
1202
1201
  initialize: function() {
1203
1202
  this._index = {};
1204
1203
  },
1205
-
1204
+
1206
1205
  add: function(item) {
1207
1206
  var key = (item.id !== undefined) ? item.id : item;
1208
1207
  if (this._index.hasOwnProperty(key)) return false;
1209
1208
  this._index[key] = item;
1210
1209
  return true;
1211
1210
  },
1212
-
1211
+
1213
1212
  forEach: function(block, context) {
1214
1213
  for (var key in this._index) {
1215
1214
  if (this._index.hasOwnProperty(key))
1216
1215
  block.call(context, this._index[key]);
1217
1216
  }
1218
1217
  },
1219
-
1218
+
1220
1219
  isEmpty: function() {
1221
1220
  for (var key in this._index) {
1222
1221
  if (this._index.hasOwnProperty(key)) return false;
1223
1222
  }
1224
1223
  return true;
1225
1224
  },
1226
-
1225
+
1227
1226
  member: function(item) {
1228
1227
  for (var key in this._index) {
1229
1228
  if (this._index[key] === item) return true;
1230
1229
  }
1231
1230
  return false;
1232
1231
  },
1233
-
1232
+
1234
1233
  remove: function(item) {
1235
1234
  var key = (item.id !== undefined) ? item.id : item;
1236
1235
  var removed = this._index.hasOwnProperty(key);
1237
1236
  delete this._index[key];
1238
1237
  return removed;
1239
1238
  },
1240
-
1239
+
1241
1240
  toArray: function() {
1242
1241
  var array = [];
1243
1242
  this.forEach(function(item) { array.push(item) });
@@ -1250,7 +1249,7 @@ Faye.Engine = {
1250
1249
  get: function(options) {
1251
1250
  return new Faye.Engine.Proxy(options);
1252
1251
  },
1253
-
1252
+
1254
1253
  METHODS: ['createClient', 'clientExists', 'destroyClient', 'ping', 'subscribe', 'unsubscribe']
1255
1254
  };
1256
1255
 
@@ -1258,26 +1257,26 @@ Faye.Engine.Proxy = Faye.Class({
1258
1257
  MAX_DELAY: 0.0,
1259
1258
  INTERVAL: 0.0,
1260
1259
  TIMEOUT: 60.0,
1261
-
1260
+
1262
1261
  className: 'Engine',
1263
-
1262
+
1264
1263
  initialize: function(options) {
1265
1264
  this._options = options || {};
1266
1265
  this._connections = {};
1267
1266
  this.interval = this._options.interval || this.INTERVAL;
1268
1267
  this.timeout = this._options.timeout || this.TIMEOUT;
1269
-
1268
+
1270
1269
  var engineClass = this._options.type || Faye.Engine.Memory;
1271
1270
  this._engine = engineClass.create(this, this._options);
1272
-
1271
+
1273
1272
  this.bind('disconnect', function(clientId) {
1274
1273
  var self = this;
1275
1274
  setTimeout(function() { self.closeConnection(clientId) }, 10);
1276
1275
  }, this);
1277
-
1276
+
1278
1277
  this.debug('Created new engine: ?', this._options);
1279
1278
  },
1280
-
1279
+
1281
1280
  connect: function(clientId, options, callback, context) {
1282
1281
  this.debug('Accepting connection from ?', clientId);
1283
1282
  this._engine.ping(clientId);
@@ -1285,11 +1284,11 @@ Faye.Engine.Proxy = Faye.Class({
1285
1284
  conn.connect(options, callback, context);
1286
1285
  this._engine.emptyQueue(clientId);
1287
1286
  },
1288
-
1287
+
1289
1288
  hasConnection: function(clientId) {
1290
1289
  return this._connections.hasOwnProperty(clientId);
1291
1290
  },
1292
-
1291
+
1293
1292
  connection: function(clientId, create) {
1294
1293
  var conn = this._connections[clientId];
1295
1294
  if (conn || !create) return conn;
@@ -1297,7 +1296,7 @@ Faye.Engine.Proxy = Faye.Class({
1297
1296
  this.trigger('connection:open', clientId);
1298
1297
  return this._connections[clientId];
1299
1298
  },
1300
-
1299
+
1301
1300
  closeConnection: function(clientId) {
1302
1301
  this.debug('Closing connection for ?', clientId);
1303
1302
  var conn = this._connections[clientId];
@@ -1306,40 +1305,40 @@ Faye.Engine.Proxy = Faye.Class({
1306
1305
  this.trigger('connection:close', clientId);
1307
1306
  delete this._connections[clientId];
1308
1307
  },
1309
-
1308
+
1310
1309
  openSocket: function(clientId, socket) {
1311
1310
  if (!clientId) return;
1312
1311
  var conn = this.connection(clientId, true);
1313
1312
  conn.socket = socket;
1314
1313
  },
1315
-
1314
+
1316
1315
  deliver: function(clientId, messages) {
1317
1316
  if (!messages || messages.length === 0) return false;
1318
-
1317
+
1319
1318
  var conn = this.connection(clientId, false);
1320
1319
  if (!conn) return false;
1321
-
1320
+
1322
1321
  for (var i = 0, n = messages.length; i < n; i++) {
1323
1322
  conn.deliver(messages[i]);
1324
1323
  }
1325
1324
  return true;
1326
1325
  },
1327
-
1326
+
1328
1327
  generateId: function() {
1329
1328
  return Faye.random();
1330
1329
  },
1331
-
1330
+
1332
1331
  flush: function(clientId) {
1333
1332
  if (!clientId) return;
1334
- this.debug('Flushing connection queue for ?', clientId);
1333
+ this.debug('Flushing connection for ?', clientId);
1335
1334
  var conn = this.connection(clientId, false);
1336
1335
  if (conn) conn.flush(true);
1337
1336
  },
1338
-
1337
+
1339
1338
  disconnect: function() {
1340
1339
  if (this._engine.disconnect) return this._engine.disconnect();
1341
1340
  },
1342
-
1341
+
1343
1342
  publish: function(message) {
1344
1343
  var channels = Faye.Channel.expand(message.channel);
1345
1344
  return this._engine.publish(message, channels);
@@ -1362,41 +1361,41 @@ Faye.Engine.Connection = Faye.Class({
1362
1361
  this._options = options;
1363
1362
  this._inbox = [];
1364
1363
  },
1365
-
1364
+
1366
1365
  deliver: function(message) {
1367
- if (this.socket) return this.socket.send(JSON.stringify([message]));
1366
+ if (this.socket) return this.socket.send(message);
1368
1367
  this._inbox.push(message);
1369
1368
  this._beginDeliveryTimeout();
1370
1369
  },
1371
-
1370
+
1372
1371
  connect: function(options, callback, context) {
1373
1372
  options = options || {};
1374
1373
  var timeout = (options.timeout !== undefined) ? options.timeout / 1000 : this._engine.timeout;
1375
-
1374
+
1376
1375
  this.setDeferredStatus('deferred');
1377
1376
  this.callback(callback, context);
1378
-
1377
+
1379
1378
  this._beginDeliveryTimeout();
1380
1379
  this._beginConnectionTimeout(timeout);
1381
1380
  },
1382
-
1381
+
1383
1382
  flush: function(force) {
1384
1383
  this._releaseConnection(force);
1385
1384
  this.setDeferredStatus('succeeded', this._inbox);
1386
1385
  this._inbox = [];
1387
1386
  },
1388
-
1387
+
1389
1388
  _releaseConnection: function(force) {
1390
1389
  if (force || !this.socket) this._engine.closeConnection(this._id);
1391
1390
  this.removeTimeout('connection');
1392
1391
  this.removeTimeout('delivery');
1393
1392
  },
1394
-
1393
+
1395
1394
  _beginDeliveryTimeout: function() {
1396
1395
  if (this._inbox.length === 0) return;
1397
1396
  this.addTimeout('delivery', this._engine.MAX_DELAY, this.flush, this);
1398
1397
  },
1399
-
1398
+
1400
1399
  _beginConnectionTimeout: function(timeout) {
1401
1400
  this.addTimeout('connection', timeout, this.flush, this);
1402
1401
  }
@@ -1427,14 +1426,14 @@ Faye.Engine.Memory.prototype = {
1427
1426
  this._server.trigger('handshake', clientId);
1428
1427
  callback.call(context, clientId);
1429
1428
  },
1430
-
1429
+
1431
1430
  destroyClient: function(clientId, callback, context) {
1432
1431
  if (!this._namespace.exists(clientId)) return;
1433
1432
  var clients = this._clients;
1434
-
1433
+
1435
1434
  if (clients[clientId])
1436
1435
  clients[clientId].forEach(function(channel) { this.unsubscribe(clientId, channel) }, this);
1437
-
1436
+
1438
1437
  this.removeTimeout(clientId);
1439
1438
  this._namespace.release(clientId);
1440
1439
  delete this._messages[clientId];
@@ -1442,79 +1441,79 @@ Faye.Engine.Memory.prototype = {
1442
1441
  this._server.trigger('disconnect', clientId);
1443
1442
  if (callback) callback.call(context);
1444
1443
  },
1445
-
1444
+
1446
1445
  clientExists: function(clientId, callback, context) {
1447
1446
  callback.call(context, this._namespace.exists(clientId));
1448
1447
  },
1449
-
1448
+
1450
1449
  ping: function(clientId) {
1451
1450
  var timeout = this._server.timeout;
1452
1451
  if (typeof timeout !== 'number') return;
1453
-
1452
+
1454
1453
  this._server.debug('Ping ?, ?', clientId, timeout);
1455
1454
  this.removeTimeout(clientId);
1456
1455
  this.addTimeout(clientId, 2 * timeout, function() {
1457
1456
  this.destroyClient(clientId);
1458
1457
  }, this);
1459
1458
  },
1460
-
1459
+
1461
1460
  subscribe: function(clientId, channel, callback, context) {
1462
1461
  var clients = this._clients, channels = this._channels;
1463
-
1462
+
1464
1463
  clients[clientId] = clients[clientId] || new Faye.Set();
1465
1464
  var trigger = clients[clientId].add(channel);
1466
-
1465
+
1467
1466
  channels[channel] = channels[channel] || new Faye.Set();
1468
1467
  channels[channel].add(clientId);
1469
-
1468
+
1470
1469
  this._server.debug('Subscribed client ? to channel ?', clientId, channel);
1471
1470
  if (trigger) this._server.trigger('subscribe', clientId, channel);
1472
1471
  if (callback) callback.call(context, true);
1473
1472
  },
1474
-
1473
+
1475
1474
  unsubscribe: function(clientId, channel, callback, context) {
1476
1475
  var clients = this._clients,
1477
1476
  channels = this._channels,
1478
1477
  trigger = false;
1479
-
1478
+
1480
1479
  if (clients[clientId]) {
1481
1480
  trigger = clients[clientId].remove(channel);
1482
1481
  if (clients[clientId].isEmpty()) delete clients[clientId];
1483
1482
  }
1484
-
1483
+
1485
1484
  if (channels[channel]) {
1486
1485
  channels[channel].remove(clientId);
1487
1486
  if (channels[channel].isEmpty()) delete channels[channel];
1488
1487
  }
1489
-
1488
+
1490
1489
  this._server.debug('Unsubscribed client ? from channel ?', clientId, channel);
1491
1490
  if (trigger) this._server.trigger('unsubscribe', clientId, channel);
1492
1491
  if (callback) callback.call(context, true);
1493
1492
  },
1494
-
1493
+
1495
1494
  publish: function(message, channels) {
1496
1495
  this._server.debug('Publishing message ?', message);
1497
1496
 
1498
1497
  var messages = this._messages,
1499
1498
  clients = new Faye.Set(),
1500
1499
  subs;
1501
-
1500
+
1502
1501
  for (var i = 0, n = channels.length; i < n; i++) {
1503
1502
  subs = this._channels[channels[i]];
1504
1503
  if (!subs) continue;
1505
1504
  subs.forEach(clients.add, clients);
1506
1505
  }
1507
-
1506
+
1508
1507
  clients.forEach(function(clientId) {
1509
1508
  this._server.debug('Queueing for client ?: ?', clientId, message);
1510
1509
  messages[clientId] = messages[clientId] || [];
1511
1510
  messages[clientId].push(Faye.copyObject(message));
1512
1511
  this.emptyQueue(clientId);
1513
1512
  }, this);
1514
-
1513
+
1515
1514
  this._server.trigger('publish', message.clientId, message.channel, message.data);
1516
1515
  },
1517
-
1516
+
1518
1517
  emptyQueue: function(clientId) {
1519
1518
  if (!this._server.hasConnection(clientId)) return;
1520
1519
  this._server.deliver(clientId, this._messages[clientId]);
@@ -1524,6 +1523,8 @@ Faye.Engine.Memory.prototype = {
1524
1523
  Faye.extend(Faye.Engine.Memory.prototype, Faye.Timeouts);
1525
1524
 
1526
1525
  Faye.Server = Faye.Class({
1526
+ META_METHODS: ["handshake", "connect", "disconnect", "subscribe", "unsubscribe"],
1527
+
1527
1528
  initialize: function(options) {
1528
1529
  this._options = options || {};
1529
1530
  var engineOpts = this._options.engine || {};
@@ -1532,33 +1533,33 @@ Faye.Server = Faye.Class({
1532
1533
 
1533
1534
  this.info('Created new server: ?', this._options);
1534
1535
  },
1535
-
1536
+
1536
1537
  flushConnection: function(messages) {
1537
1538
  var clientId = Faye.clientIdFromMessages(messages);
1538
1539
  this.info('Flushing connection for ?', clientId);
1539
1540
  this._engine.flush(clientId);
1540
1541
  },
1541
-
1542
+
1542
1543
  openSocket: function(clientId, socket) {
1543
- this._engine.openSocket(clientId, socket);
1544
+ this._engine.openSocket(clientId, new Faye.Server.Socket(this, socket));
1544
1545
  },
1545
-
1546
+
1546
1547
  closeSocket: function(clientId) {
1547
1548
  this._engine.flush(clientId);
1548
1549
  },
1549
-
1550
+
1550
1551
  process: function(messages, local, callback, context) {
1551
1552
  messages = [].concat(messages);
1552
1553
  this.info('Processing messages: ? (local: ?)', messages, local);
1553
1554
 
1554
1555
  if (messages.length === 0) return callback.call(context, []);
1555
1556
  var processed = 0, responses = [], self = this;
1556
-
1557
+
1557
1558
  var gatherReplies = function(replies) {
1558
1559
  responses = responses.concat(replies);
1559
1560
  processed += 1;
1560
1561
  if (processed < messages.length) return;
1561
-
1562
+
1562
1563
  var n = responses.length;
1563
1564
  while (n--) {
1564
1565
  if (!responses[n]) responses.splice(n,1);
@@ -1566,77 +1567,87 @@ Faye.Server = Faye.Class({
1566
1567
  self.info('Returning replies: ?', responses);
1567
1568
  callback.call(context, responses);
1568
1569
  };
1569
-
1570
+
1570
1571
  var handleReply = function(replies) {
1571
1572
  var extended = 0, expected = replies.length;
1572
1573
  if (expected === 0) gatherReplies(replies);
1573
-
1574
+
1574
1575
  for (var i = 0, n = replies.length; i < n; i++) {
1575
1576
  this.debug('Processing reply: ?', replies[i]);
1576
- this.pipeThroughExtensions('outgoing', replies[i], function(message) {
1577
- replies[i] = message;
1578
- extended += 1;
1579
- if (extended === expected) gatherReplies(replies);
1580
- });
1577
+ (function(index) {
1578
+ self.pipeThroughExtensions('outgoing', replies[index], function(message) {
1579
+ replies[index] = message;
1580
+ extended += 1;
1581
+ if (extended === expected) gatherReplies(replies);
1582
+ });
1583
+ })(i);
1581
1584
  }
1582
1585
  };
1583
-
1586
+
1584
1587
  for (var i = 0, n = messages.length; i < n; i++) {
1585
1588
  this.pipeThroughExtensions('incoming', messages[i], function(pipedMessage) {
1586
1589
  this._handle(pipedMessage, local, handleReply, this);
1587
1590
  }, this);
1588
1591
  }
1589
1592
  },
1590
-
1593
+
1591
1594
  _makeResponse: function(message) {
1592
1595
  var response = {};
1593
-
1596
+
1594
1597
  if (message.id) response.id = message.id;
1595
1598
  if (message.clientId) response.clientId = message.clientId;
1596
1599
  if (message.channel) response.channel = message.channel;
1597
1600
  if (message.error) response.error = message.error;
1598
-
1601
+
1599
1602
  response.successful = !response.error;
1600
1603
  return response;
1601
1604
  },
1602
-
1605
+
1603
1606
  _handle: function(message, local, callback, context) {
1604
1607
  if (!message) return callback.call(context, []);
1605
1608
  this.info('Handling message: ? (local: ?)', message, local);
1606
-
1609
+
1607
1610
  var channelName = message.channel,
1608
1611
  error = message.error,
1609
1612
  response;
1610
-
1613
+
1611
1614
  if (Faye.Channel.isMeta(channelName))
1612
1615
  return this._handleMeta(message, local, callback, context);
1613
-
1616
+
1614
1617
  if (!Faye.Grammar.CHANNEL_NAME.test(channelName))
1615
1618
  error = Faye.Error.channelInvalid(channelName);
1616
-
1619
+
1617
1620
  if (!error) this._engine.publish(message);
1618
-
1621
+
1619
1622
  response = this._makeResponse(message);
1620
1623
  if (error) response.error = error;
1621
1624
  response.successful = !response.error;
1622
1625
  callback.call(context, [response]);
1623
1626
  },
1624
-
1627
+
1625
1628
  _handleMeta: function(message, local, callback, context) {
1626
1629
  var method = Faye.Channel.parse(message.channel)[1],
1627
- clientId = message.clientId;
1628
-
1630
+ clientId = message.clientId,
1631
+ response;
1632
+
1633
+ if (Faye.indexOf(this.META_METHODS, method) < 0) {
1634
+ response = this._makeResponse(message);
1635
+ response.error = Faye.Error.channelForbidden(message.channel);
1636
+ response.successful = false;
1637
+ return callback.call(context, [response]);
1638
+ }
1639
+
1629
1640
  this[method](message, local, function(responses) {
1630
1641
  responses = [].concat(responses);
1631
1642
  for (var i = 0, n = responses.length; i < n; i++) this._advize(responses[i], message.connectionType);
1632
1643
  callback.call(context, responses);
1633
1644
  }, this);
1634
1645
  },
1635
-
1646
+
1636
1647
  _advize: function(response, connectionType) {
1637
1648
  if (Faye.indexOf([Faye.Channel.HANDSHAKE, Faye.Channel.CONNECT], response.channel) < 0)
1638
1649
  return;
1639
-
1650
+
1640
1651
  var interval, timeout;
1641
1652
  if (connectionType === 'eventsource') {
1642
1653
  interval = Math.floor(this._engine.timeout * 1000);
@@ -1645,7 +1656,7 @@ Faye.Server = Faye.Class({
1645
1656
  interval = Math.floor(this._engine.interval * 1000);
1646
1657
  timeout = Math.floor(this._engine.timeout * 1000);
1647
1658
  }
1648
-
1659
+
1649
1660
  response.advice = response.advice || {};
1650
1661
  if (response.error) {
1651
1662
  Faye.extend(response.advice, {reconnect: 'handshake'}, false);
@@ -1657,7 +1668,7 @@ Faye.Server = Faye.Class({
1657
1668
  }, false);
1658
1669
  }
1659
1670
  },
1660
-
1671
+
1661
1672
  // MUST contain * version
1662
1673
  // * supportedConnectionTypes
1663
1674
  // MAY contain * minimumVersion
@@ -1666,15 +1677,15 @@ Faye.Server = Faye.Class({
1666
1677
  handshake: function(message, local, callback, context) {
1667
1678
  var response = this._makeResponse(message);
1668
1679
  response.version = Faye.BAYEUX_VERSION;
1669
-
1680
+
1670
1681
  if (!message.version)
1671
1682
  response.error = Faye.Error.parameterMissing('version');
1672
-
1683
+
1673
1684
  var clientConns = message.supportedConnectionTypes,
1674
1685
  commonConns;
1675
-
1686
+
1676
1687
  response.supportedConnectionTypes = Faye.CONNECTION_TYPES;
1677
-
1688
+
1678
1689
  if (clientConns) {
1679
1690
  commonConns = Faye.filter(clientConns, function(conn) {
1680
1691
  return Faye.indexOf(Faye.CONNECTION_TYPES, conn) >= 0;
@@ -1684,16 +1695,16 @@ Faye.Server = Faye.Class({
1684
1695
  } else {
1685
1696
  response.error = Faye.Error.parameterMissing('supportedConnectionTypes');
1686
1697
  }
1687
-
1698
+
1688
1699
  response.successful = !response.error;
1689
1700
  if (!response.successful) return callback.call(context, response);
1690
-
1701
+
1691
1702
  this._engine.createClient(function(clientId) {
1692
1703
  response.clientId = clientId;
1693
1704
  callback.call(context, response);
1694
1705
  }, this);
1695
1706
  },
1696
-
1707
+
1697
1708
  // MUST contain * clientId
1698
1709
  // * connectionType
1699
1710
  // MAY contain * ext
@@ -1702,23 +1713,23 @@ Faye.Server = Faye.Class({
1702
1713
  var response = this._makeResponse(message),
1703
1714
  clientId = message.clientId,
1704
1715
  connectionType = message.connectionType;
1705
-
1716
+
1706
1717
  this._engine.clientExists(clientId, function(exists) {
1707
1718
  if (!exists) response.error = Faye.Error.clientUnknown(clientId);
1708
1719
  if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
1709
-
1720
+
1710
1721
  if (Faye.indexOf(Faye.CONNECTION_TYPES, connectionType) < 0)
1711
1722
  response.error = Faye.Error.conntypeMismatch(connectionType);
1712
-
1723
+
1713
1724
  if (!connectionType) response.error = Faye.Error.parameterMissing('connectionType');
1714
-
1725
+
1715
1726
  response.successful = !response.error;
1716
-
1727
+
1717
1728
  if (!response.successful) {
1718
1729
  delete response.clientId;
1719
1730
  return callback.call(context, response);
1720
1731
  }
1721
-
1732
+
1722
1733
  if (message.connectionType === 'eventsource') {
1723
1734
  message.advice = message.advice || {};
1724
1735
  message.advice.timeout = 0;
@@ -1728,26 +1739,26 @@ Faye.Server = Faye.Class({
1728
1739
  });
1729
1740
  }, this);
1730
1741
  },
1731
-
1742
+
1732
1743
  // MUST contain * clientId
1733
1744
  // MAY contain * ext
1734
1745
  // * id
1735
1746
  disconnect: function(message, local, callback, context) {
1736
1747
  var response = this._makeResponse(message),
1737
1748
  clientId = message.clientId;
1738
-
1749
+
1739
1750
  this._engine.clientExists(clientId, function(exists) {
1740
1751
  if (!exists) response.error = Faye.Error.clientUnknown(clientId);
1741
1752
  if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
1742
-
1753
+
1743
1754
  response.successful = !response.error;
1744
1755
  if (!response.successful) delete response.clientId;
1745
-
1756
+
1746
1757
  if (response.successful) this._engine.destroyClient(clientId);
1747
1758
  callback.call(context, response);
1748
1759
  }, this);
1749
1760
  },
1750
-
1761
+
1751
1762
  // MUST contain * clientId
1752
1763
  // * subscription
1753
1764
  // MAY contain * ext
@@ -1757,32 +1768,32 @@ Faye.Server = Faye.Class({
1757
1768
  clientId = message.clientId,
1758
1769
  subscription = message.subscription,
1759
1770
  channel;
1760
-
1771
+
1761
1772
  subscription = subscription ? [].concat(subscription) : [];
1762
-
1773
+
1763
1774
  this._engine.clientExists(clientId, function(exists) {
1764
1775
  if (!exists) response.error = Faye.Error.clientUnknown(clientId);
1765
1776
  if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
1766
1777
  if (!message.subscription) response.error = Faye.Error.parameterMissing('subscription');
1767
-
1778
+
1768
1779
  response.subscription = message.subscription || [];
1769
-
1780
+
1770
1781
  for (var i = 0, n = subscription.length; i < n; i++) {
1771
1782
  channel = subscription[i];
1772
-
1783
+
1773
1784
  if (response.error) break;
1774
1785
  if (!local && !Faye.Channel.isSubscribable(channel)) response.error = Faye.Error.channelForbidden(channel);
1775
1786
  if (!Faye.Channel.isValid(channel)) response.error = Faye.Error.channelInvalid(channel);
1776
-
1787
+
1777
1788
  if (response.error) break;
1778
1789
  this._engine.subscribe(clientId, channel);
1779
1790
  }
1780
-
1791
+
1781
1792
  response.successful = !response.error;
1782
1793
  callback.call(context, response);
1783
1794
  }, this);
1784
1795
  },
1785
-
1796
+
1786
1797
  // MUST contain * clientId
1787
1798
  // * subscription
1788
1799
  // MAY contain * ext
@@ -1792,27 +1803,27 @@ Faye.Server = Faye.Class({
1792
1803
  clientId = message.clientId,
1793
1804
  subscription = message.subscription,
1794
1805
  channel;
1795
-
1806
+
1796
1807
  subscription = subscription ? [].concat(subscription) : [];
1797
-
1808
+
1798
1809
  this._engine.clientExists(clientId, function(exists) {
1799
1810
  if (!exists) response.error = Faye.Error.clientUnknown(clientId);
1800
1811
  if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
1801
1812
  if (!message.subscription) response.error = Faye.Error.parameterMissing('subscription');
1802
-
1813
+
1803
1814
  response.subscription = message.subscription || [];
1804
-
1815
+
1805
1816
  for (var i = 0, n = subscription.length; i < n; i++) {
1806
1817
  channel = subscription[i];
1807
-
1818
+
1808
1819
  if (response.error) break;
1809
1820
  if (!local && !Faye.Channel.isSubscribable(channel)) response.error = Faye.Error.channelForbidden(channel);
1810
1821
  if (!Faye.Channel.isValid(channel)) response.error = Faye.Error.channelInvalid(channel);
1811
-
1822
+
1812
1823
  if (response.error) break;
1813
1824
  this._engine.unsubscribe(clientId, channel);
1814
1825
  }
1815
-
1826
+
1816
1827
  response.successful = !response.error;
1817
1828
  callback.call(context, response);
1818
1829
  }, this);
@@ -1823,9 +1834,27 @@ Faye.extend(Faye.Server.prototype, Faye.Logging);
1823
1834
  Faye.extend(Faye.Server.prototype, Faye.Extensible);
1824
1835
 
1825
1836
 
1837
+ Faye.Server.Socket = Faye.Class({
1838
+ initialize: function(server, socket) {
1839
+ this._server = server;
1840
+ this._socket = socket;
1841
+ },
1842
+
1843
+ send: function(message) {
1844
+ this._server.pipeThroughExtensions('outgoing', message, function(pipedMessage) {
1845
+ this._socket.send(JSON.stringify([pipedMessage]));
1846
+ }, this);
1847
+ },
1848
+
1849
+ close: function() {
1850
+ this._socket.close();
1851
+ }
1852
+ });
1853
+
1854
+
1826
1855
  Faye.Transport.NodeLocal = Faye.extend(Faye.Class(Faye.Transport, {
1827
1856
  batching: false,
1828
-
1857
+
1829
1858
  request: function(message, timeout) {
1830
1859
  message = Faye.copyObject(message);
1831
1860
  this.endpoint.process(message, true, function(responses) {
@@ -1846,75 +1875,81 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
1846
1875
  CONNECTED: 3,
1847
1876
 
1848
1877
  batching: false,
1849
-
1878
+
1850
1879
  isUsable: function(callback, context) {
1851
1880
  this.callback(function() { callback.call(context, true) });
1852
1881
  this.errback(function() { callback.call(context, false) });
1853
1882
  this.connect();
1854
1883
  },
1855
-
1884
+
1856
1885
  request: function(messages, timeout) {
1857
1886
  if (messages.length === 0) return;
1858
1887
  this._messages = this._messages || {};
1859
-
1888
+
1860
1889
  for (var i = 0, n = messages.length; i < n; i++) {
1861
1890
  this._messages[messages[i].id] = messages[i];
1862
1891
  }
1863
1892
  this.callback(function(socket) { socket.send(Faye.toJSON(messages)) });
1864
1893
  this.connect();
1865
1894
  },
1866
-
1895
+
1867
1896
  close: function() {
1868
- if (this._closed) return;
1869
- this._closed = true;
1870
- if (this._socket) this._socket.close();
1897
+ if (!this._socket) return;
1898
+ this._socket.onclose = this._socket.onerror = null;
1899
+ this._socket.close();
1900
+ delete this._socket;
1901
+ this.setDeferredStatus('deferred');
1902
+ this._state = this.UNCONNECTED;
1871
1903
  },
1872
-
1904
+
1873
1905
  connect: function() {
1874
1906
  if (Faye.Transport.WebSocket._unloaded) return;
1875
- if (this._closed) return;
1876
-
1907
+
1877
1908
  this._state = this._state || this.UNCONNECTED;
1878
1909
  if (this._state !== this.UNCONNECTED) return;
1879
-
1910
+
1880
1911
  this._state = this.CONNECTING;
1881
-
1912
+
1882
1913
  var ws = Faye.Transport.WebSocket.getClass();
1883
1914
  if (!ws) return this.setDeferredStatus('failed');
1884
-
1915
+
1885
1916
  this._socket = new ws(Faye.Transport.WebSocket.getSocketUrl(this.endpoint));
1886
1917
  var self = this;
1887
-
1918
+
1888
1919
  this._socket.onopen = function() {
1889
1920
  self._state = self.CONNECTED;
1890
1921
  self._everConnected = true;
1891
1922
  self.setDeferredStatus('succeeded', self._socket);
1892
1923
  self.trigger('up');
1893
1924
  };
1894
-
1925
+
1895
1926
  this._socket.onmessage = function(event) {
1896
- var messages = [].concat(JSON.parse(event.data));
1927
+ var messages = JSON.parse(event.data);
1928
+ if (!messages) return;
1929
+ messages = [].concat(messages);
1930
+
1897
1931
  for (var i = 0, n = messages.length; i < n; i++) {
1898
1932
  delete self._messages[messages[i].id];
1899
1933
  }
1900
1934
  self.receive(messages);
1901
1935
  };
1902
-
1903
- this._socket.onclose = function() {
1936
+
1937
+ this._socket.onclose = this._socket.onerror = function() {
1904
1938
  var wasConnected = (self._state === self.CONNECTED);
1905
1939
  self.setDeferredStatus('deferred');
1906
1940
  self._state = self.UNCONNECTED;
1907
- delete self._socket;
1908
-
1941
+
1942
+ self.close();
1943
+
1909
1944
  if (wasConnected) return self.resend();
1910
1945
  if (!self._everConnected) return self.setDeferredStatus('failed');
1911
-
1946
+
1912
1947
  var retry = self._client.retry * 1000;
1913
1948
  Faye.ENV.setTimeout(function() { self.connect() }, retry);
1914
1949
  self.trigger('down');
1915
1950
  };
1916
1951
  },
1917
-
1952
+
1918
1953
  resend: function() {
1919
1954
  if (!this._messages) return;
1920
1955
  var messages = Faye.map(this._messages, function(id, msg) { return msg });
@@ -1925,17 +1960,17 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
1925
1960
  if (Faye.URI) endpoint = Faye.URI.parse(endpoint).toURL();
1926
1961
  return endpoint.replace(/^http(s?):/ig, 'ws$1:');
1927
1962
  },
1928
-
1963
+
1929
1964
  getClass: function() {
1930
1965
  return (Faye.WebSocket && Faye.WebSocket.Client) ||
1931
1966
  Faye.ENV.WebSocket ||
1932
1967
  Faye.ENV.MozWebSocket;
1933
1968
  },
1934
-
1969
+
1935
1970
  isUsable: function(client, endpoint, callback, context) {
1936
1971
  this.create(client, endpoint).isUsable(callback, context);
1937
1972
  },
1938
-
1973
+
1939
1974
  create: function(client, endpoint) {
1940
1975
  var sockets = client.transports.websocket = client.transports.websocket || {};
1941
1976
  sockets[endpoint] = sockets[endpoint] || new this(client, endpoint);
@@ -1960,16 +1995,16 @@ Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {
1960
1995
  content = new Buffer(JSON.stringify(message), 'utf8'),
1961
1996
  retry = this.retry(message, timeout),
1962
1997
  self = this;
1963
-
1998
+
1964
1999
  var cookies = this.cookies.getCookies({domain: uri.hostname, path: uri.pathname}),
1965
2000
  params = this._buildParams(uri, content, cookies, secure),
1966
2001
  request = client.request(params);
1967
-
2002
+
1968
2003
  request.addListener('response', function(response) {
1969
2004
  self._handleResponse(response, retry);
1970
2005
  self._storeCookies(uri.hostname, response.headers['set-cookie']);
1971
2006
  });
1972
-
2007
+
1973
2008
  request.addListener('error', function() {
1974
2009
  retry();
1975
2010
  self.trigger('down');
@@ -1977,7 +2012,7 @@ Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {
1977
2012
  request.write(content);
1978
2013
  request.end();
1979
2014
  },
1980
-
2015
+
1981
2016
  _buildParams: function(uri, content, cookies, secure) {
1982
2017
  return {
1983
2018
  method: 'POST',
@@ -1992,19 +2027,19 @@ Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {
1992
2027
  }, this.headers)
1993
2028
  };
1994
2029
  },
1995
-
2030
+
1996
2031
  _handleResponse: function(response, retry) {
1997
2032
  var message = null,
1998
2033
  body = '',
1999
2034
  self = this;
2000
-
2035
+
2001
2036
  response.setEncoding('utf8');
2002
2037
  response.addListener('data', function(chunk) { body += chunk });
2003
2038
  response.addListener('end', function() {
2004
2039
  try {
2005
2040
  message = JSON.parse(body);
2006
2041
  } catch (e) {}
2007
-
2042
+
2008
2043
  if (message) {
2009
2044
  self.receive(message);
2010
2045
  self.trigger('up');
@@ -2014,18 +2049,18 @@ Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {
2014
2049
  }
2015
2050
  });
2016
2051
  },
2017
-
2052
+
2018
2053
  _storeCookies: function(hostname, cookies) {
2019
2054
  if (!cookies) return;
2020
2055
  var cookie;
2021
-
2056
+
2022
2057
  for (var i = 0, n = cookies.length; i < n; i++) {
2023
2058
  cookie = this.cookies.setCookie(cookies[i]);
2024
2059
  cookie = cookie[0] || cookie;
2025
2060
  cookie.domain = cookie.domain || hostname;
2026
2061
  }
2027
2062
  }
2028
-
2063
+
2029
2064
  }), {
2030
2065
  isUsable: function(client, endpoint, callback, context) {
2031
2066
  callback.call(context, typeof endpoint === 'string');
@@ -2060,147 +2095,160 @@ Faye.withDataFor = function(transport, callback, context) {
2060
2095
  Faye.NodeAdapter = Faye.Class({
2061
2096
  DEFAULT_ENDPOINT: '/bayeux',
2062
2097
  SCRIPT_PATH: 'faye-browser-min.js',
2063
-
2098
+
2099
+ // https://github.com/joyent/node/issues/2727
2100
+ CIPHER_ORDER: 'ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM',
2101
+ CIPHER_OPTIONS: require('constants').SSL_OP_CIPHER_SERVER_PREFERENCE,
2102
+
2064
2103
  TYPE_JSON: {'Content-Type': 'application/json; charset=utf-8'},
2065
2104
  TYPE_SCRIPT: {'Content-Type': 'text/javascript; charset=utf-8'},
2066
2105
  TYPE_TEXT: {'Content-Type': 'text/plain; charset=utf-8'},
2067
-
2106
+
2107
+ VALID_JSONP_CALLBACK: /^[a-z_\$][a-z0-9_\$]*(\.[a-z_\$][a-z0-9_\$]*)*$/i,
2108
+
2068
2109
  initialize: function(options) {
2069
2110
  this._options = options || {};
2070
2111
  this._endpoint = this._options.mount || this.DEFAULT_ENDPOINT;
2071
- this._endpointRe = new RegExp('^' + this._endpoint + '(/[^/]+)*(\\.[^\\.]+)?$');
2112
+ this._endpointRe = new RegExp('^' + this._endpoint.replace(/\/$/, '') + '(/[^/]+)*(\\.[^\\.]+)?$');
2072
2113
  this._server = new Faye.Server(this._options);
2073
-
2114
+
2074
2115
  this._static = new Faye.StaticServer(path.dirname(__filename) + '/../browser', /\.(?:js|map)$/);
2075
2116
  this._static.map(path.basename(this._endpoint) + '.js', this.SCRIPT_PATH);
2076
2117
  this._static.map('client.js', this.SCRIPT_PATH);
2077
-
2118
+
2078
2119
  var extensions = this._options.extensions;
2079
2120
  if (!extensions) return;
2080
-
2121
+
2081
2122
  extensions = [].concat(extensions);
2082
2123
  for (var i = 0, n = extensions.length; i < n; i++)
2083
2124
  this.addExtension(extensions[i]);
2084
2125
  },
2085
-
2126
+
2086
2127
  addExtension: function(extension) {
2087
2128
  return this._server.addExtension(extension);
2088
2129
  },
2089
-
2130
+
2090
2131
  removeExtension: function(extension) {
2091
2132
  return this._server.removeExtension(extension);
2092
2133
  },
2093
-
2134
+
2094
2135
  bind: function() {
2095
2136
  return this._server._engine.bind.apply(this._server._engine, arguments);
2096
2137
  },
2097
-
2138
+
2098
2139
  unbind: function() {
2099
2140
  return this._server._engine.unbind.apply(this._server._engine, arguments);
2100
2141
  },
2101
-
2142
+
2102
2143
  getClient: function() {
2103
2144
  return this._client = this._client || new Faye.Client(this._server);
2104
2145
  },
2105
-
2146
+
2106
2147
  listen: function(port, sslOptions, callback, context) {
2107
2148
  var ssl = sslOptions && sslOptions.cert
2108
- ? { key: fs.readFileSync(sslOptions.key),
2109
- cert: fs.readFileSync(sslOptions.cert)
2149
+ ? { key: fs.readFileSync(sslOptions.key),
2150
+ cert: fs.readFileSync(sslOptions.cert),
2151
+ ciphers: this.CIPHER_ORDER,
2152
+ secureOptions: this.CIPHER_OPTIONS
2110
2153
  }
2111
2154
  : null;
2112
-
2155
+
2113
2156
  if (ssl && sslOptions.ca)
2114
2157
  ssl.ca = Faye.map(sslOptions.ca, function(ca) { return fs.readFileSync(ca) });
2115
-
2158
+
2116
2159
  var httpServer = ssl
2117
2160
  ? https.createServer(ssl, function() {})
2118
2161
  : http.createServer(function() {});
2119
-
2162
+
2120
2163
  this.attach(httpServer);
2121
2164
  httpServer.listen(port, function() {
2122
2165
  if (callback) callback.call(context);
2123
2166
  });
2124
2167
  this._httpServer = httpServer;
2125
2168
  },
2126
-
2169
+
2127
2170
  stop: function(callback, context) {
2128
2171
  this._httpServer.addListener('close', function() {
2129
2172
  if (callback) callback.call(context);
2130
2173
  });
2131
2174
  this._httpServer.close();
2132
2175
  },
2133
-
2176
+
2134
2177
  attach: function(httpServer) {
2135
2178
  this._overrideListeners(httpServer, 'request', 'handle');
2136
2179
  this._overrideListeners(httpServer, 'upgrade', 'handleUpgrade');
2137
2180
  },
2138
-
2181
+
2139
2182
  _overrideListeners: function(httpServer, event, method) {
2140
2183
  var listeners = httpServer.listeners(event),
2141
2184
  self = this;
2142
-
2185
+
2143
2186
  httpServer.removeAllListeners(event);
2144
-
2187
+
2145
2188
  httpServer.addListener(event, function(request) {
2146
2189
  if (self.check(request)) return self[method].apply(self, arguments);
2147
-
2190
+
2148
2191
  for (var i = 0, n = listeners.length; i < n; i++)
2149
2192
  listeners[i].apply(this, arguments);
2150
2193
  });
2151
2194
  },
2152
-
2195
+
2153
2196
  check: function(request) {
2154
2197
  var path = url.parse(request.url, true).pathname;
2155
2198
  return !!this._endpointRe.test(path);
2156
2199
  },
2157
-
2200
+
2158
2201
  handle: function(request, response) {
2159
2202
  var requestUrl = url.parse(request.url, true),
2160
2203
  requestMethod = request.method,
2161
2204
  self = this;
2162
-
2205
+
2206
+ request.addListener('error', function(error) { self._returnError(response, error) });
2207
+ response.addListener('error', function(error) { self._returnError(null, error) });
2208
+
2163
2209
  if (this._static.test(requestUrl.pathname))
2164
2210
  return this._static.call(request, response);
2165
-
2211
+
2166
2212
  // http://groups.google.com/group/faye-users/browse_thread/thread/4a01bb7d25d3636a
2167
2213
  if (requestMethod === 'OPTIONS' || request.headers['access-control-request-method'] === 'POST')
2168
2214
  return this._handleOptions(request, response);
2169
-
2215
+
2170
2216
  if (Faye.EventSource.isEventSource(request))
2171
2217
  return this.handleEventSource(request, response);
2172
-
2218
+
2173
2219
  if (requestMethod === 'GET')
2174
2220
  return this._callWithParams(request, response, requestUrl.query);
2175
-
2221
+
2176
2222
  if (requestMethod === 'POST')
2177
2223
  return Faye.withDataFor(request, function(data) {
2178
2224
  var type = (request.headers['content-type'] || '').split(';')[0],
2179
2225
  params = (type === 'application/json')
2180
2226
  ? {message: data}
2181
2227
  : querystring.parse(data);
2182
-
2228
+
2183
2229
  request.body = data;
2184
2230
  self._callWithParams(request, response, params);
2185
2231
  });
2186
-
2187
- this._returnError(response);
2232
+
2233
+ this._returnError(response, {message: 'Unrecognized request type'});
2188
2234
  },
2189
-
2235
+
2190
2236
  handleUpgrade: function(request, socket, head) {
2191
2237
  var ws = new Faye.WebSocket(request, socket, head, null, {ping: this._options.ping}),
2192
2238
  clientId = null,
2193
2239
  self = this;
2194
-
2240
+
2195
2241
  ws.onmessage = function(event) {
2196
2242
  try {
2197
2243
  self.debug('Received message via WebSocket[' + ws.version + ']: ?', event.data);
2198
-
2199
- var message = JSON.parse(event.data);
2200
- clientId = Faye.clientIdFromMessages(message);
2201
-
2202
- self._server.openSocket(clientId, ws);
2203
-
2244
+
2245
+ var message = JSON.parse(event.data),
2246
+ cid = Faye.clientIdFromMessages(message);
2247
+
2248
+ if (clientId && cid !== clientId) self._server.closeSocket(clientId);
2249
+ self._server.openSocket(cid, ws);
2250
+ clientId = cid;
2251
+
2204
2252
  self._server.process(message, false, function(replies) {
2205
2253
  if (ws) ws.send(JSON.stringify(replies));
2206
2254
  });
@@ -2208,36 +2256,34 @@ Faye.NodeAdapter = Faye.Class({
2208
2256
  self.error(e.message + '\nBacktrace:\n' + e.stack);
2209
2257
  }
2210
2258
  };
2211
-
2259
+
2212
2260
  ws.onclose = function(event) {
2213
2261
  self._server.closeSocket(clientId);
2214
2262
  ws = null;
2215
2263
  };
2216
2264
  },
2217
-
2265
+
2218
2266
  handleEventSource: function(request, response) {
2219
2267
  var es = new Faye.EventSource(request, response, {ping: this._options.ping}),
2220
2268
  clientId = es.url.split('/').pop(),
2221
2269
  self = this;
2222
-
2270
+
2223
2271
  this.debug('Opened EventSource connection for ?', clientId);
2224
2272
  this._server.openSocket(clientId, es);
2225
-
2273
+
2226
2274
  es.onclose = function(event) {
2227
2275
  self._server.closeSocket(clientId);
2228
2276
  es = null;
2229
2277
  };
2230
2278
  },
2231
-
2279
+
2232
2280
  _callWithParams: function(request, response, params) {
2233
- if (!params.message) {
2234
- this.error('Received request with no message: ?', this._formatRequest(request));
2235
- return this._returnError(response);
2236
- }
2237
-
2281
+ if (!params.message)
2282
+ return this._returnError(response, {message: 'Received request with no message: ' + this._formatRequest(request)});
2283
+
2238
2284
  try {
2239
2285
  this.debug('Received message via HTTP ' + request.method + ': ?', params.message);
2240
-
2286
+
2241
2287
  var message = JSON.parse(params.message),
2242
2288
  jsonp = params.jsonp || Faye.JSONP_CALLBACK,
2243
2289
  isGet = (request.method === 'GET'),
@@ -2245,32 +2291,40 @@ Faye.NodeAdapter = Faye.Class({
2245
2291
  headers = Faye.extend({}, type),
2246
2292
  origin = request.headers.origin;
2247
2293
 
2294
+ if (!this.VALID_JSONP_CALLBACK.test(jsonp))
2295
+ return this._returnError(response, {message: 'Invalid JSON-P callback: ' + jsonp});
2296
+
2248
2297
  if (isGet) this._server.flushConnection(message);
2249
-
2298
+
2250
2299
  if (origin) headers['Access-Control-Allow-Origin'] = origin;
2251
2300
  headers['Cache-Control'] = 'no-cache, no-store';
2252
-
2301
+ headers['X-Content-Type-Options'] = 'nosniff';
2302
+
2253
2303
  this._server.process(message, false, function(replies) {
2254
2304
  var body = JSON.stringify(replies);
2255
- if (isGet) body = jsonp + '(' + body + ');';
2305
+
2306
+ if (isGet) {
2307
+ body = '/**/' + jsonp + '(' + body + ');';
2308
+ headers['Content-Disposition'] = 'attachment; filename=f.txt';
2309
+ }
2310
+
2256
2311
  headers['Content-Length'] = new Buffer(body, 'utf8').length.toString();
2257
2312
  headers['Connection'] = 'close';
2258
-
2313
+
2259
2314
  this.debug('HTTP response: ?', body);
2260
2315
  response.writeHead(200, headers);
2261
2316
  response.write(body);
2262
2317
  response.end();
2263
2318
  }, this);
2264
- } catch (e) {
2265
- this.error(e.message + '\nBacktrace:\n' + e.stack);
2266
- this._returnError(response);
2319
+ } catch (error) {
2320
+ this._returnError(response, error);
2267
2321
  }
2268
2322
  },
2269
-
2323
+
2270
2324
  _formatRequest: function(request) {
2271
2325
  var method = request.method.toUpperCase(),
2272
2326
  string = 'curl -X ' + method;
2273
-
2327
+
2274
2328
  string += " 'http://" + request.headers.host + request.url + "'";
2275
2329
  if (method === 'POST') {
2276
2330
  string += " -H 'Content-Type: " + request.headers['content-type'] + "'";
@@ -2278,7 +2332,7 @@ Faye.NodeAdapter = Faye.Class({
2278
2332
  }
2279
2333
  return string;
2280
2334
  },
2281
-
2335
+
2282
2336
  _handleOptions: function(request, response) {
2283
2337
  var headers = {
2284
2338
  'Access-Control-Allow-Origin': '*',
@@ -2291,8 +2345,14 @@ Faye.NodeAdapter = Faye.Class({
2291
2345
  response.write('');
2292
2346
  response.end();
2293
2347
  },
2294
-
2295
- _returnError: function(response) {
2348
+
2349
+ _returnError: function(response, error) {
2350
+ var message = error.message;
2351
+ if (error.stack) message += '\nBacktrace:\n' + error.stack;
2352
+ this.error(message);
2353
+
2354
+ if (!response) return;
2355
+
2296
2356
  response.writeHead(400, this.TYPE_TEXT);
2297
2357
  response.write('Bad request');
2298
2358
  response.end();
@@ -2311,25 +2371,25 @@ Faye.StaticServer = Faye.Class({
2311
2371
  this._pathMap = {};
2312
2372
  this._index = {};
2313
2373
  },
2314
-
2374
+
2315
2375
  map: function(requestPath, filename) {
2316
2376
  this._pathMap[requestPath] = filename;
2317
2377
  },
2318
-
2378
+
2319
2379
  test: function(pathname) {
2320
2380
  return this._pathRegex.test(pathname);
2321
2381
  },
2322
-
2382
+
2323
2383
  call: function(request, response) {
2324
- var pathname = url.parse(request.url, true).pathname;
2325
- pathname = path.basename(pathname);
2326
- pathname = this._pathMap[pathname] || pathname;
2327
-
2328
- this._index[pathname] = this._index[pathname] || {};
2329
-
2330
- var cache = this._index[pathname],
2331
- fullpath = path.join(this._directory, pathname);
2332
-
2384
+ var pathname = url.parse(request.url, true).pathname,
2385
+ filename = path.basename(pathname);
2386
+
2387
+ filename = this._pathMap[filename] || filename;
2388
+ this._index[filename] = this._index[filename] || {};
2389
+
2390
+ var cache = this._index[filename],
2391
+ fullpath = path.join(this._directory, filename);
2392
+
2333
2393
  try {
2334
2394
  cache.content = cache.content || fs.readFileSync(fullpath);
2335
2395
  cache.digest = cache.digest || crypto.createHash('sha1').update(cache.content).digest('hex');
@@ -2338,15 +2398,15 @@ Faye.StaticServer = Faye.Class({
2338
2398
  response.writeHead(404, {});
2339
2399
  return response.end();
2340
2400
  }
2341
-
2342
- var type = /\.js$/.test(pathname) ? 'TYPE_SCRIPT' : 'TYPE_JSON',
2343
- headers = Faye.extend({}, Faye.NodeAdapter.prototype[type]),
2344
- ims = request.headers['if-modified-since'];
2345
-
2346
- headers['Content-Length'] = '0';
2347
- headers['ETag'] = cache.digest;
2348
- headers['Last-Modified'] = cache.mtime.toGMTString();
2349
-
2401
+
2402
+ var type = /\.js$/.test(pathname) ? 'TYPE_SCRIPT' : 'TYPE_JSON',
2403
+ ims = request.headers['if-modified-since'];
2404
+
2405
+ var headers = {
2406
+ 'ETag': cache.digest,
2407
+ 'Last-Modified': cache.mtime.toGMTString()
2408
+ };
2409
+
2350
2410
  if (request.headers['if-none-match'] === cache.digest) {
2351
2411
  response.writeHead(304, headers);
2352
2412
  response.end();
@@ -2357,6 +2417,7 @@ Faye.StaticServer = Faye.Class({
2357
2417
  }
2358
2418
  else {
2359
2419
  headers['Content-Length'] = cache.content.length;
2420
+ Faye.extend(headers, Faye.NodeAdapter.prototype[type]);
2360
2421
  response.writeHead(200, headers);
2361
2422
  response.write(cache.content);
2362
2423
  response.end();