Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
emscripten-core
GitHub Repository: emscripten-core/emscripten
Path: blob/main/third_party/socket.io.js
4129 views
1
/*! Socket.IO.js build:0.9.11, development. Copyright(c) 2011 LearnBoost <[email protected]> MIT Licensed */
2
3
(function(global) {
4
5
var io = ('undefined' === typeof module ? {} : module.exports);
6
7
/**
8
* socket.io
9
* Copyright(c) 2011 LearnBoost <[email protected]>
10
* MIT Licensed
11
*/
12
13
(function (exports) {
14
15
/**
16
* IO namespace.
17
*
18
* @namespace
19
*/
20
21
var io = exports;
22
23
/**
24
* Socket.IO version
25
*
26
* @api public
27
*/
28
29
io.version = '0.9.11';
30
31
/**
32
* Protocol implemented.
33
*
34
* @api public
35
*/
36
37
io.protocol = 1;
38
39
/**
40
* Available transports, these will be populated with the available transports
41
*
42
* @api public
43
*/
44
45
io.transports = [];
46
47
/**
48
* Keep track of jsonp callbacks.
49
*
50
* @api private
51
*/
52
53
io.j = [];
54
55
/**
56
* Keep track of our io.Sockets
57
*
58
* @api private
59
*/
60
io.sockets = {};
61
62
63
/**
64
* Manages connections to hosts.
65
*
66
* @param {String} uri
67
* @Param {Boolean} force creation of new socket (defaults to false)
68
* @api public
69
*/
70
71
io.connect = function (host, details) {
72
var uri = io.util.parseUri(host)
73
, uuri
74
, socket;
75
76
if (global && global.location) {
77
uri.protocol = uri.protocol || global.location.protocol.slice(0, -1);
78
uri.host = uri.host || (global.document
79
? global.document.domain : global.location.hostname);
80
uri.port = uri.port || global.location.port;
81
}
82
83
uuri = io.util.uniqueUri(uri);
84
85
var options = {
86
host: uri.host
87
, secure: 'https' == uri.protocol
88
, port: uri.port || ('https' == uri.protocol ? 443 : 80)
89
, query: uri.query || ''
90
};
91
92
io.util.merge(options, details);
93
94
if (options['force new connection'] || !io.sockets[uuri]) {
95
socket = new io.Socket(options);
96
}
97
98
if (!options['force new connection'] && socket) {
99
io.sockets[uuri] = socket;
100
}
101
102
socket = socket || io.sockets[uuri];
103
104
// if path is different from '' or /
105
return socket.of(uri.path.length > 1 ? uri.path : '');
106
};
107
108
})('object' === typeof module ? module.exports : (io = {}));
109
/**
110
* socket.io
111
* Copyright(c) 2011 LearnBoost <[email protected]>
112
* MIT Licensed
113
*/
114
115
(function (exports) {
116
117
/**
118
* Utilities namespace.
119
*
120
* @namespace
121
*/
122
123
var util = exports.util = {};
124
125
/**
126
* Parses an URI
127
*
128
* @author Steven Levithan <stevenlevithan.com> (MIT license)
129
* @api public
130
*/
131
132
var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
133
134
var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
135
'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
136
'anchor'];
137
138
util.parseUri = function (str) {
139
var m = re.exec(str || '')
140
, uri = {}
141
, i = 14;
142
143
while (i--) {
144
uri[parts[i]] = m[i] || '';
145
}
146
147
return uri;
148
};
149
150
/**
151
* Produces a unique url that identifies a Socket.IO connection.
152
*
153
* @param {Object} uri
154
* @api public
155
*/
156
157
util.uniqueUri = function (uri) {
158
var protocol = uri.protocol
159
, host = uri.host
160
, port = uri.port;
161
162
if ('document' in global) {
163
host = host || document.domain;
164
port = port || (protocol == 'https'
165
&& document.location.protocol !== 'https:' ? 443 : document.location.port);
166
} else {
167
host = host || 'localhost';
168
169
if (!port && protocol == 'https') {
170
port = 443;
171
}
172
}
173
174
return (protocol || 'http') + '://' + host + ':' + (port || 80);
175
};
176
177
/**
178
* Mergest 2 query strings in to once unique query string
179
*
180
* @param {String} base
181
* @param {String} addition
182
* @api public
183
*/
184
185
util.query = function (base, addition) {
186
var query = util.chunkQuery(base || '')
187
, components = [];
188
189
util.merge(query, util.chunkQuery(addition || ''));
190
for (var part in query) {
191
if (query.hasOwnProperty(part)) {
192
components.push(part + '=' + query[part]);
193
}
194
}
195
196
return components.length ? '?' + components.join('&') : '';
197
};
198
199
/**
200
* Transforms a querystring in to an object
201
*
202
* @param {String} qs
203
* @api public
204
*/
205
206
util.chunkQuery = function (qs) {
207
var query = {}
208
, params = qs.split('&')
209
, i = 0
210
, l = params.length
211
, kv;
212
213
for (; i < l; ++i) {
214
kv = params[i].split('=');
215
if (kv[0]) {
216
query[kv[0]] = kv[1];
217
}
218
}
219
220
return query;
221
};
222
223
/**
224
* Executes the given function when the page is loaded.
225
*
226
* io.util.load(function () { console.log('page loaded'); });
227
*
228
* @param {Function} fn
229
* @api public
230
*/
231
232
var pageLoaded = false;
233
234
util.load = function (fn) {
235
if ('document' in global && document.readyState === 'complete' || pageLoaded) {
236
return fn();
237
}
238
239
util.on(global, 'load', fn, false);
240
};
241
242
/**
243
* Adds an event.
244
*
245
* @api private
246
*/
247
248
util.on = function (element, event, fn, capture) {
249
if (element.attachEvent) {
250
element.attachEvent('on' + event, fn);
251
} else if (element.addEventListener) {
252
element.addEventListener(event, fn, capture);
253
}
254
};
255
256
/**
257
* Generates the correct `XMLHttpRequest` for regular and cross domain requests.
258
*
259
* @param {Boolean} [xdomain] Create a request that can be used cross domain.
260
* @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
261
* @api private
262
*/
263
264
util.request = function (xdomain) {
265
266
if (xdomain && 'undefined' != typeof XDomainRequest && !util.ua.hasCORS) {
267
return new XDomainRequest();
268
}
269
270
if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
271
return new XMLHttpRequest();
272
}
273
274
if (!xdomain) {
275
try {
276
return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
277
} catch(e) { }
278
}
279
280
return null;
281
};
282
283
/**
284
* XHR based transport constructor.
285
*
286
* @constructor
287
* @api public
288
*/
289
290
/**
291
* Change the internal pageLoaded value.
292
*/
293
294
if ('undefined' != typeof window) {
295
util.load(function () {
296
pageLoaded = true;
297
});
298
}
299
300
/**
301
* Defers a function to ensure a spinner is not displayed by the browser
302
*
303
* @param {Function} fn
304
* @api public
305
*/
306
307
util.defer = function (fn) {
308
if (!util.ua.webkit || 'undefined' != typeof importScripts) {
309
return fn();
310
}
311
312
util.load(function () {
313
setTimeout(fn, 100);
314
});
315
};
316
317
/**
318
* Merges two objects.
319
*
320
* @api public
321
*/
322
323
util.merge = function merge (target, additional, deep, lastseen) {
324
var seen = lastseen || []
325
, depth = typeof deep == 'undefined' ? 2 : deep
326
, prop;
327
328
for (prop in additional) {
329
if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
330
if (typeof target[prop] !== 'object' || !depth) {
331
target[prop] = additional[prop];
332
seen.push(additional[prop]);
333
} else {
334
util.merge(target[prop], additional[prop], depth - 1, seen);
335
}
336
}
337
}
338
339
return target;
340
};
341
342
/**
343
* Merges prototypes from objects
344
*
345
* @api public
346
*/
347
348
util.mixin = function (ctor, ctor2) {
349
util.merge(ctor.prototype, ctor2.prototype);
350
};
351
352
/**
353
* Shortcut for prototypical and static inheritance.
354
*
355
* @api private
356
*/
357
358
util.inherit = function (ctor, ctor2) {
359
function f() {};
360
f.prototype = ctor2.prototype;
361
ctor.prototype = new f;
362
};
363
364
/**
365
* Checks if the given object is an Array.
366
*
367
* io.util.isArray([]); // true
368
* io.util.isArray({}); // false
369
*
370
* @param Object obj
371
* @api public
372
*/
373
374
util.isArray = Array.isArray || function (obj) {
375
return Object.prototype.toString.call(obj) === '[object Array]';
376
};
377
378
/**
379
* Intersects values of two arrays into a third
380
*
381
* @api public
382
*/
383
384
util.intersect = function (arr, arr2) {
385
var ret = []
386
, longest = arr.length > arr2.length ? arr : arr2
387
, shortest = arr.length > arr2.length ? arr2 : arr;
388
389
for (var i = 0, l = shortest.length; i < l; i++) {
390
if (~util.indexOf(longest, shortest[i]))
391
ret.push(shortest[i]);
392
}
393
394
return ret;
395
};
396
397
/**
398
* Array indexOf compatibility.
399
*
400
* @see bit.ly/a5Dxa2
401
* @api public
402
*/
403
404
util.indexOf = function (arr, o, i) {
405
406
for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
407
i < j && arr[i] !== o; i++) {}
408
409
return j <= i ? -1 : i;
410
};
411
412
/**
413
* Converts enumerables to array.
414
*
415
* @api public
416
*/
417
418
util.toArray = function (enu) {
419
var arr = [];
420
421
for (var i = 0, l = enu.length; i < l; i++)
422
arr.push(enu[i]);
423
424
return arr;
425
};
426
427
/**
428
* UA / engines detection namespace.
429
*
430
* @namespace
431
*/
432
433
util.ua = {};
434
435
/**
436
* Whether the UA supports CORS for XHR.
437
*
438
* @api public
439
*/
440
441
util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
442
try {
443
var a = new XMLHttpRequest();
444
} catch (e) {
445
return false;
446
}
447
448
return a.withCredentials != undefined;
449
})();
450
451
/**
452
* Detect webkit.
453
*
454
* @api public
455
*/
456
457
util.ua.webkit = 'undefined' != typeof navigator
458
&& /webkit/i.test(navigator.userAgent);
459
460
/**
461
* Detect iPad/iPhone/iPod.
462
*
463
* @api public
464
*/
465
466
util.ua.iDevice = 'undefined' != typeof navigator
467
&& /iPad|iPhone|iPod/i.test(navigator.userAgent);
468
469
})('undefined' != typeof io ? io : module.exports);
470
/**
471
* socket.io
472
* Copyright(c) 2011 LearnBoost <[email protected]>
473
* MIT Licensed
474
*/
475
476
(function (exports, io) {
477
478
/**
479
* Expose constructor.
480
*/
481
482
exports.EventEmitter = EventEmitter;
483
484
/**
485
* Event emitter constructor.
486
*
487
* @api public.
488
*/
489
490
function EventEmitter () {};
491
492
/**
493
* Adds a listener
494
*
495
* @api public
496
*/
497
498
EventEmitter.prototype.on = function (name, fn) {
499
if (!this.$events) {
500
this.$events = {};
501
}
502
503
if (!this.$events[name]) {
504
this.$events[name] = fn;
505
} else if (io.util.isArray(this.$events[name])) {
506
this.$events[name].push(fn);
507
} else {
508
this.$events[name] = [this.$events[name], fn];
509
}
510
511
return this;
512
};
513
514
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
515
516
/**
517
* Adds a volatile listener.
518
*
519
* @api public
520
*/
521
522
EventEmitter.prototype.once = function (name, fn) {
523
var self = this;
524
525
function on () {
526
self.removeListener(name, on);
527
fn.apply(this, arguments);
528
};
529
530
on.listener = fn;
531
this.on(name, on);
532
533
return this;
534
};
535
536
/**
537
* Removes a listener.
538
*
539
* @api public
540
*/
541
542
EventEmitter.prototype.removeListener = function (name, fn) {
543
if (this.$events && this.$events[name]) {
544
var list = this.$events[name];
545
546
if (io.util.isArray(list)) {
547
var pos = -1;
548
549
for (var i = 0, l = list.length; i < l; i++) {
550
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
551
pos = i;
552
break;
553
}
554
}
555
556
if (pos < 0) {
557
return this;
558
}
559
560
list.splice(pos, 1);
561
562
if (!list.length) {
563
delete this.$events[name];
564
}
565
} else if (list === fn || (list.listener && list.listener === fn)) {
566
delete this.$events[name];
567
}
568
}
569
570
return this;
571
};
572
573
/**
574
* Removes all listeners for an event.
575
*
576
* @api public
577
*/
578
579
EventEmitter.prototype.removeAllListeners = function (name) {
580
if (name === undefined) {
581
this.$events = {};
582
return this;
583
}
584
585
if (this.$events && this.$events[name]) {
586
this.$events[name] = null;
587
}
588
589
return this;
590
};
591
592
/**
593
* Gets all listeners for a certain event.
594
*
595
* @api publci
596
*/
597
598
EventEmitter.prototype.listeners = function (name) {
599
if (!this.$events) {
600
this.$events = {};
601
}
602
603
if (!this.$events[name]) {
604
this.$events[name] = [];
605
}
606
607
if (!io.util.isArray(this.$events[name])) {
608
this.$events[name] = [this.$events[name]];
609
}
610
611
return this.$events[name];
612
};
613
614
/**
615
* Emits an event.
616
*
617
* @api public
618
*/
619
620
EventEmitter.prototype.emit = function (name) {
621
if (!this.$events) {
622
return false;
623
}
624
625
var handler = this.$events[name];
626
627
if (!handler) {
628
return false;
629
}
630
631
var args = Array.prototype.slice.call(arguments, 1);
632
633
if ('function' == typeof handler) {
634
handler.apply(this, args);
635
} else if (io.util.isArray(handler)) {
636
var listeners = handler.slice();
637
638
for (var i = 0, l = listeners.length; i < l; i++) {
639
listeners[i].apply(this, args);
640
}
641
} else {
642
return false;
643
}
644
645
return true;
646
};
647
648
})(
649
'undefined' != typeof io ? io : module.exports
650
, 'undefined' != typeof io ? io : module.parent.exports
651
);
652
653
/**
654
* socket.io
655
* Copyright(c) 2011 LearnBoost <[email protected]>
656
* MIT Licensed
657
*/
658
659
/**
660
* Based on JSON2 (http://www.JSON.org/js.html).
661
*/
662
663
(function (exports, nativeJSON) {
664
"use strict";
665
666
// use native JSON if it's available
667
if (nativeJSON && nativeJSON.parse) {
668
return exports.JSON = {
669
parse: nativeJSON.parse
670
, stringify: nativeJSON.stringify
671
};
672
}
673
674
var JSON = exports.JSON = {};
675
676
function f(n) {
677
// Format integers to have at least two digits.
678
return n < 10 ? '0' + n : n;
679
}
680
681
function date(d, key) {
682
return isFinite(d.valueOf()) ?
683
d.getUTCFullYear() + '-' +
684
f(d.getUTCMonth() + 1) + '-' +
685
f(d.getUTCDate()) + 'T' +
686
f(d.getUTCHours()) + ':' +
687
f(d.getUTCMinutes()) + ':' +
688
f(d.getUTCSeconds()) + 'Z' : null;
689
};
690
691
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
692
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
693
gap,
694
indent,
695
meta = { // table of character substitutions
696
'\b': '\\b',
697
'\t': '\\t',
698
'\n': '\\n',
699
'\f': '\\f',
700
'\r': '\\r',
701
'"' : '\\"',
702
'\\': '\\\\'
703
},
704
rep;
705
706
707
function quote(string) {
708
709
// If the string contains no control characters, no quote characters, and no
710
// backslash characters, then we can safely slap some quotes around it.
711
// Otherwise we must also replace the offending characters with safe escape
712
// sequences.
713
714
escapable.lastIndex = 0;
715
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
716
var c = meta[a];
717
return typeof c === 'string' ? c :
718
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
719
}) + '"' : '"' + string + '"';
720
}
721
722
723
function str(key, holder) {
724
725
// Produce a string from holder[key].
726
727
var i, // The loop counter.
728
k, // The member key.
729
v, // The member value.
730
length,
731
mind = gap,
732
partial,
733
value = holder[key];
734
735
// If the value has a toJSON method, call it to obtain a replacement value.
736
737
if (value instanceof Date) {
738
value = date(key);
739
}
740
741
// If we were called with a replacer function, then call the replacer to
742
// obtain a replacement value.
743
744
if (typeof rep === 'function') {
745
value = rep.call(holder, key, value);
746
}
747
748
// What happens next depends on the value's type.
749
750
switch (typeof value) {
751
case 'string':
752
return quote(value);
753
754
case 'number':
755
756
// JSON numbers must be finite. Encode non-finite numbers as null.
757
758
return isFinite(value) ? String(value) : 'null';
759
760
case 'boolean':
761
case 'null':
762
763
// If the value is a boolean or null, convert it to a string. Note:
764
// typeof null does not produce 'null'. The case is included here in
765
// the remote chance that this gets fixed someday.
766
767
return String(value);
768
769
// If the type is 'object', we might be dealing with an object or an array or
770
// null.
771
772
case 'object':
773
774
// Due to a specification blunder in ECMAScript, typeof null is 'object',
775
// so watch out for that case.
776
777
if (!value) {
778
return 'null';
779
}
780
781
// Make an array to hold the partial results of stringifying this object value.
782
783
gap += indent;
784
partial = [];
785
786
// Is the value an array?
787
788
if (Object.prototype.toString.apply(value) === '[object Array]') {
789
790
// The value is an array. Stringify every element. Use null as a placeholder
791
// for non-JSON values.
792
793
length = value.length;
794
for (i = 0; i < length; i += 1) {
795
partial[i] = str(i, value) || 'null';
796
}
797
798
// Join all of the elements together, separated with commas, and wrap them in
799
// brackets.
800
801
v = partial.length === 0 ? '[]' : gap ?
802
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
803
'[' + partial.join(',') + ']';
804
gap = mind;
805
return v;
806
}
807
808
// If the replacer is an array, use it to select the members to be stringified.
809
810
if (rep && typeof rep === 'object') {
811
length = rep.length;
812
for (i = 0; i < length; i += 1) {
813
if (typeof rep[i] === 'string') {
814
k = rep[i];
815
v = str(k, value);
816
if (v) {
817
partial.push(quote(k) + (gap ? ': ' : ':') + v);
818
}
819
}
820
}
821
} else {
822
823
// Otherwise, iterate through all of the keys in the object.
824
825
for (k in value) {
826
if (Object.prototype.hasOwnProperty.call(value, k)) {
827
v = str(k, value);
828
if (v) {
829
partial.push(quote(k) + (gap ? ': ' : ':') + v);
830
}
831
}
832
}
833
}
834
835
// Join all of the member texts together, separated with commas,
836
// and wrap them in braces.
837
838
v = partial.length === 0 ? '{}' : gap ?
839
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
840
'{' + partial.join(',') + '}';
841
gap = mind;
842
return v;
843
}
844
}
845
846
// If the JSON object does not yet have a stringify method, give it one.
847
848
JSON.stringify = function (value, replacer, space) {
849
850
// The stringify method takes a value and an optional replacer, and an optional
851
// space parameter, and returns a JSON text. The replacer can be a function
852
// that can replace values, or an array of strings that will select the keys.
853
// A default replacer method can be provided. Use of the space parameter can
854
// produce text that is more easily readable.
855
856
var i;
857
gap = '';
858
indent = '';
859
860
// If the space parameter is a number, make an indent string containing that
861
// many spaces.
862
863
if (typeof space === 'number') {
864
for (i = 0; i < space; i += 1) {
865
indent += ' ';
866
}
867
868
// If the space parameter is a string, it will be used as the indent string.
869
870
} else if (typeof space === 'string') {
871
indent = space;
872
}
873
874
// If there is a replacer, it must be a function or an array.
875
// Otherwise, throw an error.
876
877
rep = replacer;
878
if (replacer && typeof replacer !== 'function' &&
879
(typeof replacer !== 'object' ||
880
typeof replacer.length !== 'number')) {
881
throw new Error('JSON.stringify');
882
}
883
884
// Make a fake root object containing our value under the key of ''.
885
// Return the result of stringifying the value.
886
887
return str('', {'': value});
888
};
889
890
// If the JSON object does not yet have a parse method, give it one.
891
892
JSON.parse = function (text, reviver) {
893
// The parse method takes a text and an optional reviver function, and returns
894
// a JavaScript value if the text is a valid JSON text.
895
896
var j;
897
898
function walk(holder, key) {
899
900
// The walk method is used to recursively walk the resulting structure so
901
// that modifications can be made.
902
903
var k, v, value = holder[key];
904
if (value && typeof value === 'object') {
905
for (k in value) {
906
if (Object.prototype.hasOwnProperty.call(value, k)) {
907
v = walk(value, k);
908
if (v !== undefined) {
909
value[k] = v;
910
} else {
911
delete value[k];
912
}
913
}
914
}
915
}
916
return reviver.call(holder, key, value);
917
}
918
919
920
// Parsing happens in four stages. In the first stage, we replace certain
921
// Unicode characters with escape sequences. JavaScript handles many characters
922
// incorrectly, either silently deleting them, or treating them as line endings.
923
924
text = String(text);
925
cx.lastIndex = 0;
926
if (cx.test(text)) {
927
text = text.replace(cx, function (a) {
928
return '\\u' +
929
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
930
});
931
}
932
933
// In the second stage, we run the text against regular expressions that look
934
// for non-JSON patterns. We are especially concerned with '()' and 'new'
935
// because they can cause invocation, and '=' because it can cause mutation.
936
// But just to be safe, we want to reject all unexpected forms.
937
938
// We split the second stage into 4 regexp operations in order to work around
939
// crippling inefficiencies in IE's and Safari's regexp engines. First we
940
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
941
// replace all simple value tokens with ']' characters. Third, we delete all
942
// open brackets that follow a colon or comma or that begin the text. Finally,
943
// we look to see that the remaining characters are only whitespace or ']' or
944
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
945
946
if (/^[\],:{}\s]*$/
947
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
948
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
949
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
950
951
// In the third stage we use the eval function to compile the text into a
952
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
953
// in JavaScript: it can begin a block or an object literal. We wrap the text
954
// in parens to eliminate the ambiguity.
955
956
j = eval('(' + text + ')');
957
958
// In the optional fourth stage, we recursively walk the new structure, passing
959
// each name/value pair to a reviver function for possible transformation.
960
961
return typeof reviver === 'function' ?
962
walk({'': j}, '') : j;
963
}
964
965
// If the text is not JSON parseable, then a SyntaxError is thrown.
966
967
throw new SyntaxError('JSON.parse');
968
};
969
970
})(
971
'undefined' != typeof io ? io : module.exports
972
, typeof JSON !== 'undefined' ? JSON : undefined
973
);
974
975
/**
976
* socket.io
977
* Copyright(c) 2011 LearnBoost <[email protected]>
978
* MIT Licensed
979
*/
980
981
(function (exports, io) {
982
983
/**
984
* Parser namespace.
985
*
986
* @namespace
987
*/
988
989
var parser = exports.parser = {};
990
991
/**
992
* Packet types.
993
*/
994
995
var packets = parser.packets = [
996
'disconnect'
997
, 'connect'
998
, 'heartbeat'
999
, 'message'
1000
, 'json'
1001
, 'event'
1002
, 'ack'
1003
, 'error'
1004
, 'noop'
1005
];
1006
1007
/**
1008
* Errors reasons.
1009
*/
1010
1011
var reasons = parser.reasons = [
1012
'transport not supported'
1013
, 'client not handshaken'
1014
, 'unauthorized'
1015
];
1016
1017
/**
1018
* Errors advice.
1019
*/
1020
1021
var advice = parser.advice = [
1022
'reconnect'
1023
];
1024
1025
/**
1026
* Shortcuts.
1027
*/
1028
1029
var JSON = io.JSON
1030
, indexOf = io.util.indexOf;
1031
1032
/**
1033
* Encodes a packet.
1034
*
1035
* @api private
1036
*/
1037
1038
parser.encodePacket = function (packet) {
1039
var type = indexOf(packets, packet.type)
1040
, id = packet.id || ''
1041
, endpoint = packet.endpoint || ''
1042
, ack = packet.ack
1043
, data = null;
1044
1045
switch (packet.type) {
1046
case 'error':
1047
var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
1048
, adv = packet.advice ? indexOf(advice, packet.advice) : '';
1049
1050
if (reason !== '' || adv !== '')
1051
data = reason + (adv !== '' ? ('+' + adv) : '');
1052
1053
break;
1054
1055
case 'message':
1056
if (packet.data !== '')
1057
data = packet.data;
1058
break;
1059
1060
case 'event':
1061
var ev = { name: packet.name };
1062
1063
if (packet.args && packet.args.length) {
1064
ev.args = packet.args;
1065
}
1066
1067
data = JSON.stringify(ev);
1068
break;
1069
1070
case 'json':
1071
data = JSON.stringify(packet.data);
1072
break;
1073
1074
case 'connect':
1075
if (packet.qs)
1076
data = packet.qs;
1077
break;
1078
1079
case 'ack':
1080
data = packet.ackId
1081
+ (packet.args && packet.args.length
1082
? '+' + JSON.stringify(packet.args) : '');
1083
break;
1084
}
1085
1086
// construct packet with required fragments
1087
var encoded = [
1088
type
1089
, id + (ack == 'data' ? '+' : '')
1090
, endpoint
1091
];
1092
1093
// data fragment is optional
1094
if (data !== null && data !== undefined)
1095
encoded.push(data);
1096
1097
return encoded.join(':');
1098
};
1099
1100
/**
1101
* Encodes multiple messages (payload).
1102
*
1103
* @param {Array} messages
1104
* @api private
1105
*/
1106
1107
parser.encodePayload = function (packets) {
1108
var decoded = '';
1109
1110
if (packets.length == 1)
1111
return packets[0];
1112
1113
for (var i = 0, l = packets.length; i < l; i++) {
1114
var packet = packets[i];
1115
decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
1116
}
1117
1118
return decoded;
1119
};
1120
1121
/**
1122
* Decodes a packet
1123
*
1124
* @api private
1125
*/
1126
1127
var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
1128
1129
parser.decodePacket = function (data) {
1130
var pieces = data.match(regexp);
1131
1132
if (!pieces) return {};
1133
1134
var id = pieces[2] || ''
1135
, data = pieces[5] || ''
1136
, packet = {
1137
type: packets[pieces[1]]
1138
, endpoint: pieces[4] || ''
1139
};
1140
1141
// whether we need to acknowledge the packet
1142
if (id) {
1143
packet.id = id;
1144
if (pieces[3])
1145
packet.ack = 'data';
1146
else
1147
packet.ack = true;
1148
}
1149
1150
// handle different packet types
1151
switch (packet.type) {
1152
case 'error':
1153
var pieces = data.split('+');
1154
packet.reason = reasons[pieces[0]] || '';
1155
packet.advice = advice[pieces[1]] || '';
1156
break;
1157
1158
case 'message':
1159
packet.data = data || '';
1160
break;
1161
1162
case 'event':
1163
try {
1164
var opts = JSON.parse(data);
1165
packet.name = opts.name;
1166
packet.args = opts.args;
1167
} catch (e) { }
1168
1169
packet.args = packet.args || [];
1170
break;
1171
1172
case 'json':
1173
try {
1174
packet.data = JSON.parse(data);
1175
} catch (e) { }
1176
break;
1177
1178
case 'connect':
1179
packet.qs = data || '';
1180
break;
1181
1182
case 'ack':
1183
var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
1184
if (pieces) {
1185
packet.ackId = pieces[1];
1186
packet.args = [];
1187
1188
if (pieces[3]) {
1189
try {
1190
packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
1191
} catch (e) { }
1192
}
1193
}
1194
break;
1195
1196
case 'disconnect':
1197
case 'heartbeat':
1198
break;
1199
};
1200
1201
return packet;
1202
};
1203
1204
/**
1205
* Decodes data payload. Detects multiple messages
1206
*
1207
* @return {Array} messages
1208
* @api public
1209
*/
1210
1211
parser.decodePayload = function (data) {
1212
// IE doesn't like data[i] for unicode chars, charAt works fine
1213
if (data.charAt(0) == '\ufffd') {
1214
var ret = [];
1215
1216
for (var i = 1, length = ''; i < data.length; i++) {
1217
if (data.charAt(i) == '\ufffd') {
1218
ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
1219
i += Number(length) + 1;
1220
length = '';
1221
} else {
1222
length += data.charAt(i);
1223
}
1224
}
1225
1226
return ret;
1227
} else {
1228
return [parser.decodePacket(data)];
1229
}
1230
};
1231
1232
})(
1233
'undefined' != typeof io ? io : module.exports
1234
, 'undefined' != typeof io ? io : module.parent.exports
1235
);
1236
/**
1237
* socket.io
1238
* Copyright(c) 2011 LearnBoost <[email protected]>
1239
* MIT Licensed
1240
*/
1241
1242
(function (exports, io) {
1243
1244
/**
1245
* Expose constructor.
1246
*/
1247
1248
exports.Transport = Transport;
1249
1250
/**
1251
* This is the transport template for all supported transport methods.
1252
*
1253
* @constructor
1254
* @api public
1255
*/
1256
1257
function Transport (socket, sessid) {
1258
this.socket = socket;
1259
this.sessid = sessid;
1260
};
1261
1262
/**
1263
* Apply EventEmitter mixin.
1264
*/
1265
1266
io.util.mixin(Transport, io.EventEmitter);
1267
1268
1269
/**
1270
* Indicates whether heartbeats is enabled for this transport
1271
*
1272
* @api private
1273
*/
1274
1275
Transport.prototype.heartbeats = function () {
1276
return true;
1277
};
1278
1279
/**
1280
* Handles the response from the server. When a new response is received
1281
* it will automatically update the timeout, decode the message and
1282
* forwards the response to the onMessage function for further processing.
1283
*
1284
* @param {String} data Response from the server.
1285
* @api private
1286
*/
1287
1288
Transport.prototype.onData = function (data) {
1289
this.clearCloseTimeout();
1290
1291
// If the connection in currently open (or in a reopening state) reset the close
1292
// timeout since we have just received data. This check is necessary so
1293
// that we don't reset the timeout on an explicitly disconnected connection.
1294
if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) {
1295
this.setCloseTimeout();
1296
}
1297
1298
if (data !== '') {
1299
// todo: we should only do decodePayload for xhr transports
1300
var msgs = io.parser.decodePayload(data);
1301
1302
if (msgs && msgs.length) {
1303
for (var i = 0, l = msgs.length; i < l; i++) {
1304
this.onPacket(msgs[i]);
1305
}
1306
}
1307
}
1308
1309
return this;
1310
};
1311
1312
/**
1313
* Handles packets.
1314
*
1315
* @api private
1316
*/
1317
1318
Transport.prototype.onPacket = function (packet) {
1319
this.socket.setHeartbeatTimeout();
1320
1321
if (packet.type == 'heartbeat') {
1322
return this.onHeartbeat();
1323
}
1324
1325
if (packet.type == 'connect' && packet.endpoint == '') {
1326
this.onConnect();
1327
}
1328
1329
if (packet.type == 'error' && packet.advice == 'reconnect') {
1330
this.isOpen = false;
1331
}
1332
1333
this.socket.onPacket(packet);
1334
1335
return this;
1336
};
1337
1338
/**
1339
* Sets close timeout
1340
*
1341
* @api private
1342
*/
1343
1344
Transport.prototype.setCloseTimeout = function () {
1345
if (!this.closeTimeout) {
1346
var self = this;
1347
1348
this.closeTimeout = setTimeout(function () {
1349
self.onDisconnect();
1350
}, this.socket.closeTimeout);
1351
}
1352
};
1353
1354
/**
1355
* Called when transport disconnects.
1356
*
1357
* @api private
1358
*/
1359
1360
Transport.prototype.onDisconnect = function () {
1361
if (this.isOpen) this.close();
1362
this.clearTimeouts();
1363
this.socket.onDisconnect();
1364
return this;
1365
};
1366
1367
/**
1368
* Called when transport connects
1369
*
1370
* @api private
1371
*/
1372
1373
Transport.prototype.onConnect = function () {
1374
this.socket.onConnect();
1375
return this;
1376
};
1377
1378
/**
1379
* Clears close timeout
1380
*
1381
* @api private
1382
*/
1383
1384
Transport.prototype.clearCloseTimeout = function () {
1385
if (this.closeTimeout) {
1386
clearTimeout(this.closeTimeout);
1387
this.closeTimeout = null;
1388
}
1389
};
1390
1391
/**
1392
* Clear timeouts
1393
*
1394
* @api private
1395
*/
1396
1397
Transport.prototype.clearTimeouts = function () {
1398
this.clearCloseTimeout();
1399
1400
if (this.reopenTimeout) {
1401
clearTimeout(this.reopenTimeout);
1402
}
1403
};
1404
1405
/**
1406
* Sends a packet
1407
*
1408
* @param {Object} packet object.
1409
* @api private
1410
*/
1411
1412
Transport.prototype.packet = function (packet) {
1413
this.send(io.parser.encodePacket(packet));
1414
};
1415
1416
/**
1417
* Send the received heartbeat message back to server. So the server
1418
* knows we are still connected.
1419
*
1420
* @param {String} heartbeat Heartbeat response from the server.
1421
* @api private
1422
*/
1423
1424
Transport.prototype.onHeartbeat = function (heartbeat) {
1425
this.packet({ type: 'heartbeat' });
1426
};
1427
1428
/**
1429
* Called when the transport opens.
1430
*
1431
* @api private
1432
*/
1433
1434
Transport.prototype.onOpen = function () {
1435
this.isOpen = true;
1436
this.clearCloseTimeout();
1437
this.socket.onOpen();
1438
};
1439
1440
/**
1441
* Notifies the base when the connection with the Socket.IO server
1442
* has been disconnected.
1443
*
1444
* @api private
1445
*/
1446
1447
Transport.prototype.onClose = function () {
1448
var self = this;
1449
1450
/* FIXME: reopen delay causing a infinit loop
1451
this.reopenTimeout = setTimeout(function () {
1452
self.open();
1453
}, this.socket.options['reopen delay']);*/
1454
1455
this.isOpen = false;
1456
this.socket.onClose();
1457
this.onDisconnect();
1458
};
1459
1460
/**
1461
* Generates a connection url based on the Socket.IO URL Protocol.
1462
* See <https://github.com/learnboost/socket.io-node/> for more details.
1463
*
1464
* @returns {String} Connection url
1465
* @api private
1466
*/
1467
1468
Transport.prototype.prepareUrl = function () {
1469
var options = this.socket.options;
1470
1471
return this.scheme() + '://'
1472
+ options.host + ':' + options.port + '/'
1473
+ options.resource + '/' + io.protocol
1474
+ '/' + this.name + '/' + this.sessid;
1475
};
1476
1477
/**
1478
* Checks if the transport is ready to start a connection.
1479
*
1480
* @param {Socket} socket The socket instance that needs a transport
1481
* @param {Function} fn The callback
1482
* @api private
1483
*/
1484
1485
Transport.prototype.ready = function (socket, fn) {
1486
fn.call(this);
1487
};
1488
})(
1489
'undefined' != typeof io ? io : module.exports
1490
, 'undefined' != typeof io ? io : module.parent.exports
1491
);
1492
/**
1493
* socket.io
1494
* Copyright(c) 2011 LearnBoost <[email protected]>
1495
* MIT Licensed
1496
*/
1497
1498
(function (exports, io) {
1499
1500
/**
1501
* Expose constructor.
1502
*/
1503
1504
exports.Socket = Socket;
1505
1506
/**
1507
* Create a new `Socket.IO client` which can establish a persistent
1508
* connection with a Socket.IO enabled server.
1509
*
1510
* @api public
1511
*/
1512
1513
function Socket (options) {
1514
this.options = {
1515
port: 80
1516
, secure: false
1517
, document: 'document' in global ? document : false
1518
, resource: 'socket.io'
1519
, transports: io.transports
1520
, 'connect timeout': 10000
1521
, 'try multiple transports': true
1522
, 'reconnect': true
1523
, 'reconnection delay': 500
1524
, 'reconnection limit': Infinity
1525
, 'reopen delay': 3000
1526
, 'max reconnection attempts': 10
1527
, 'sync disconnect on unload': false
1528
, 'auto connect': true
1529
, 'flash policy port': 10843
1530
, 'manualFlush': false
1531
};
1532
1533
io.util.merge(this.options, options);
1534
1535
this.connected = false;
1536
this.open = false;
1537
this.connecting = false;
1538
this.reconnecting = false;
1539
this.namespaces = {};
1540
this.buffer = [];
1541
this.doBuffer = false;
1542
1543
if (this.options['sync disconnect on unload'] &&
1544
(!this.isXDomain() || io.util.ua.hasCORS)) {
1545
var self = this;
1546
io.util.on(global, 'beforeunload', function () {
1547
self.disconnectSync();
1548
}, false);
1549
}
1550
1551
if (this.options['auto connect']) {
1552
this.connect();
1553
}
1554
};
1555
1556
/**
1557
* Apply EventEmitter mixin.
1558
*/
1559
1560
io.util.mixin(Socket, io.EventEmitter);
1561
1562
/**
1563
* Returns a namespace listener/emitter for this socket
1564
*
1565
* @api public
1566
*/
1567
1568
Socket.prototype.of = function (name) {
1569
if (!this.namespaces[name]) {
1570
this.namespaces[name] = new io.SocketNamespace(this, name);
1571
1572
if (name !== '') {
1573
this.namespaces[name].packet({ type: 'connect' });
1574
}
1575
}
1576
1577
return this.namespaces[name];
1578
};
1579
1580
/**
1581
* Emits the given event to the Socket and all namespaces
1582
*
1583
* @api private
1584
*/
1585
1586
Socket.prototype.publish = function () {
1587
this.emit.apply(this, arguments);
1588
1589
var nsp;
1590
1591
for (var i in this.namespaces) {
1592
if (this.namespaces.hasOwnProperty(i)) {
1593
nsp = this.of(i);
1594
nsp.$emit.apply(nsp, arguments);
1595
}
1596
}
1597
};
1598
1599
/**
1600
* Performs the handshake
1601
*
1602
* @api private
1603
*/
1604
1605
function empty () { };
1606
1607
Socket.prototype.handshake = function (fn) {
1608
var self = this
1609
, options = this.options;
1610
1611
function complete (data) {
1612
if (data instanceof Error) {
1613
self.connecting = false;
1614
self.onError(data.message);
1615
} else {
1616
fn.apply(null, data.split(':'));
1617
}
1618
};
1619
1620
var url = [
1621
'http' + (options.secure ? 's' : '') + ':/'
1622
, options.host + ':' + options.port
1623
, options.resource
1624
, io.protocol
1625
, io.util.query(this.options.query, 't=' + +new Date)
1626
].join('/');
1627
1628
if (this.isXDomain() && !io.util.ua.hasCORS) {
1629
var insertAt = document.getElementsByTagName('script')[0]
1630
, script = document.createElement('script');
1631
1632
script.src = url + '&jsonp=' + io.j.length;
1633
insertAt.parentNode.insertBefore(script, insertAt);
1634
1635
io.j.push(function (data) {
1636
complete(data);
1637
script.parentNode.removeChild(script);
1638
});
1639
} else {
1640
var xhr = io.util.request();
1641
1642
xhr.open('GET', url, true);
1643
if (this.isXDomain()) {
1644
xhr.withCredentials = true;
1645
}
1646
xhr.onreadystatechange = function () {
1647
if (xhr.readyState == 4) {
1648
xhr.onreadystatechange = empty;
1649
1650
if (xhr.status == 200) {
1651
complete(xhr.responseText);
1652
} else if (xhr.status == 403) {
1653
self.onError(xhr.responseText);
1654
} else {
1655
self.connecting = false;
1656
!self.reconnecting && self.onError(xhr.responseText);
1657
}
1658
}
1659
};
1660
xhr.send(null);
1661
}
1662
};
1663
1664
/**
1665
* Find an available transport based on the options supplied in the constructor.
1666
*
1667
* @api private
1668
*/
1669
1670
Socket.prototype.getTransport = function (override) {
1671
var transports = override || this.transports, match;
1672
1673
for (var i = 0, transport; transport = transports[i]; i++) {
1674
if (io.Transport[transport]
1675
&& io.Transport[transport].check(this)
1676
&& (!this.isXDomain() || io.Transport[transport].xdomainCheck(this))) {
1677
return new io.Transport[transport](this, this.sessionid);
1678
}
1679
}
1680
1681
return null;
1682
};
1683
1684
/**
1685
* Connects to the server.
1686
*
1687
* @param {Function} [fn] Callback.
1688
* @returns {io.Socket}
1689
* @api public
1690
*/
1691
1692
Socket.prototype.connect = function (fn) {
1693
if (this.connecting) {
1694
return this;
1695
}
1696
1697
var self = this;
1698
self.connecting = true;
1699
1700
this.handshake(function (sid, heartbeat, close, transports) {
1701
self.sessionid = sid;
1702
self.closeTimeout = close * 1000;
1703
self.heartbeatTimeout = heartbeat * 1000;
1704
if(!self.transports)
1705
self.transports = self.origTransports = (transports ? io.util.intersect(
1706
transports.split(',')
1707
, self.options.transports
1708
) : self.options.transports);
1709
1710
self.setHeartbeatTimeout();
1711
1712
function connect (transports){
1713
if (self.transport) self.transport.clearTimeouts();
1714
1715
self.transport = self.getTransport(transports);
1716
if (!self.transport) return self.publish('connect_failed');
1717
1718
// once the transport is ready
1719
self.transport.ready(self, function () {
1720
self.connecting = true;
1721
self.publish('connecting', self.transport.name);
1722
self.transport.open();
1723
1724
if (self.options['connect timeout']) {
1725
self.connectTimeoutTimer = setTimeout(function () {
1726
if (!self.connected) {
1727
self.connecting = false;
1728
1729
if (self.options['try multiple transports']) {
1730
var remaining = self.transports;
1731
1732
while (remaining.length > 0 && remaining.splice(0,1)[0] !=
1733
self.transport.name) {}
1734
1735
if (remaining.length) {
1736
connect(remaining);
1737
} else {
1738
self.publish('connect_failed');
1739
}
1740
}
1741
}
1742
}, self.options['connect timeout']);
1743
}
1744
});
1745
}
1746
1747
connect(self.transports);
1748
1749
self.once('connect', function (){
1750
clearTimeout(self.connectTimeoutTimer);
1751
1752
fn && typeof fn == 'function' && fn();
1753
});
1754
});
1755
1756
return this;
1757
};
1758
1759
/**
1760
* Clears and sets a new heartbeat timeout using the value given by the
1761
* server during the handshake.
1762
*
1763
* @api private
1764
*/
1765
1766
Socket.prototype.setHeartbeatTimeout = function () {
1767
clearTimeout(this.heartbeatTimeoutTimer);
1768
if(this.transport && !this.transport.heartbeats()) return;
1769
1770
var self = this;
1771
this.heartbeatTimeoutTimer = setTimeout(function () {
1772
self.transport.onClose();
1773
}, this.heartbeatTimeout);
1774
};
1775
1776
/**
1777
* Sends a message.
1778
*
1779
* @param {Object} data packet.
1780
* @returns {io.Socket}
1781
* @api public
1782
*/
1783
1784
Socket.prototype.packet = function (data) {
1785
if (this.connected && !this.doBuffer) {
1786
this.transport.packet(data);
1787
} else {
1788
this.buffer.push(data);
1789
}
1790
1791
return this;
1792
};
1793
1794
/**
1795
* Sets buffer state
1796
*
1797
* @api private
1798
*/
1799
1800
Socket.prototype.setBuffer = function (v) {
1801
this.doBuffer = v;
1802
1803
if (!v && this.connected && this.buffer.length) {
1804
if (!this.options['manualFlush']) {
1805
this.flushBuffer();
1806
}
1807
}
1808
};
1809
1810
/**
1811
* Flushes the buffer data over the wire.
1812
* To be invoked manually when 'manualFlush' is set to true.
1813
*
1814
* @api public
1815
*/
1816
1817
Socket.prototype.flushBuffer = function() {
1818
this.transport.payload(this.buffer);
1819
this.buffer = [];
1820
};
1821
1822
1823
/**
1824
* Disconnect the established connect.
1825
*
1826
* @returns {io.Socket}
1827
* @api public
1828
*/
1829
1830
Socket.prototype.disconnect = function () {
1831
if (this.connected || this.connecting) {
1832
if (this.open) {
1833
this.of('').packet({ type: 'disconnect' });
1834
}
1835
1836
// handle disconnection immediately
1837
this.onDisconnect('booted');
1838
}
1839
1840
return this;
1841
};
1842
1843
/**
1844
* Disconnects the socket with a sync XHR.
1845
*
1846
* @api private
1847
*/
1848
1849
Socket.prototype.disconnectSync = function () {
1850
// ensure disconnection
1851
var xhr = io.util.request();
1852
var uri = [
1853
'http' + (this.options.secure ? 's' : '') + ':/'
1854
, this.options.host + ':' + this.options.port
1855
, this.options.resource
1856
, io.protocol
1857
, ''
1858
, this.sessionid
1859
].join('/') + '/?disconnect=1';
1860
1861
xhr.open('GET', uri, false);
1862
xhr.send(null);
1863
1864
// handle disconnection immediately
1865
this.onDisconnect('booted');
1866
};
1867
1868
/**
1869
* Check if we need to use cross domain enabled transports. Cross domain would
1870
* be a different port or different domain name.
1871
*
1872
* @returns {Boolean}
1873
* @api private
1874
*/
1875
1876
Socket.prototype.isXDomain = function () {
1877
1878
var port = global.location.port ||
1879
('https:' == global.location.protocol ? 443 : 80);
1880
1881
return this.options.host !== global.location.hostname
1882
|| this.options.port != port;
1883
};
1884
1885
/**
1886
* Called upon handshake.
1887
*
1888
* @api private
1889
*/
1890
1891
Socket.prototype.onConnect = function () {
1892
if (!this.connected) {
1893
this.connected = true;
1894
this.connecting = false;
1895
if (!this.doBuffer) {
1896
// make sure to flush the buffer
1897
this.setBuffer(false);
1898
}
1899
this.emit('connect');
1900
}
1901
};
1902
1903
/**
1904
* Called when the transport opens
1905
*
1906
* @api private
1907
*/
1908
1909
Socket.prototype.onOpen = function () {
1910
this.open = true;
1911
};
1912
1913
/**
1914
* Called when the transport closes.
1915
*
1916
* @api private
1917
*/
1918
1919
Socket.prototype.onClose = function () {
1920
this.open = false;
1921
clearTimeout(this.heartbeatTimeoutTimer);
1922
};
1923
1924
/**
1925
* Called when the transport first opens a connection
1926
*
1927
* @param text
1928
*/
1929
1930
Socket.prototype.onPacket = function (packet) {
1931
this.of(packet.endpoint).onPacket(packet);
1932
};
1933
1934
/**
1935
* Handles an error.
1936
*
1937
* @api private
1938
*/
1939
1940
Socket.prototype.onError = function (err) {
1941
if (err && err.advice) {
1942
if (err.advice === 'reconnect' && (this.connected || this.connecting)) {
1943
this.disconnect();
1944
if (this.options.reconnect) {
1945
this.reconnect();
1946
}
1947
}
1948
}
1949
1950
this.publish('error', err && err.reason ? err.reason : err);
1951
};
1952
1953
/**
1954
* Called when the transport disconnects.
1955
*
1956
* @api private
1957
*/
1958
1959
Socket.prototype.onDisconnect = function (reason) {
1960
var wasConnected = this.connected
1961
, wasConnecting = this.connecting;
1962
1963
this.connected = false;
1964
this.connecting = false;
1965
this.open = false;
1966
1967
if (wasConnected || wasConnecting) {
1968
this.transport.close();
1969
this.transport.clearTimeouts();
1970
if (wasConnected) {
1971
this.publish('disconnect', reason);
1972
1973
if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
1974
this.reconnect();
1975
}
1976
}
1977
}
1978
};
1979
1980
/**
1981
* Called upon reconnection.
1982
*
1983
* @api private
1984
*/
1985
1986
Socket.prototype.reconnect = function () {
1987
this.reconnecting = true;
1988
this.reconnectionAttempts = 0;
1989
this.reconnectionDelay = this.options['reconnection delay'];
1990
1991
var self = this
1992
, maxAttempts = this.options['max reconnection attempts']
1993
, tryMultiple = this.options['try multiple transports']
1994
, limit = this.options['reconnection limit'];
1995
1996
function reset () {
1997
if (self.connected) {
1998
for (var i in self.namespaces) {
1999
if (self.namespaces.hasOwnProperty(i) && '' !== i) {
2000
self.namespaces[i].packet({ type: 'connect' });
2001
}
2002
}
2003
self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
2004
}
2005
2006
clearTimeout(self.reconnectionTimer);
2007
2008
self.removeListener('connect_failed', maybeReconnect);
2009
self.removeListener('connect', maybeReconnect);
2010
2011
self.reconnecting = false;
2012
2013
delete self.reconnectionAttempts;
2014
delete self.reconnectionDelay;
2015
delete self.reconnectionTimer;
2016
delete self.redoTransports;
2017
2018
self.options['try multiple transports'] = tryMultiple;
2019
};
2020
2021
function maybeReconnect () {
2022
if (!self.reconnecting) {
2023
return;
2024
}
2025
2026
if (self.connected) {
2027
return reset();
2028
};
2029
2030
if (self.connecting && self.reconnecting) {
2031
return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
2032
}
2033
2034
if (self.reconnectionAttempts++ >= maxAttempts) {
2035
if (!self.redoTransports) {
2036
self.on('connect_failed', maybeReconnect);
2037
self.options['try multiple transports'] = true;
2038
self.transports = self.origTransports;
2039
self.transport = self.getTransport();
2040
self.redoTransports = true;
2041
self.connect();
2042
} else {
2043
self.publish('reconnect_failed');
2044
reset();
2045
}
2046
} else {
2047
if (self.reconnectionDelay < limit) {
2048
self.reconnectionDelay *= 2; // exponential back off
2049
}
2050
2051
self.connect();
2052
self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
2053
self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
2054
}
2055
};
2056
2057
this.options['try multiple transports'] = false;
2058
this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
2059
2060
this.on('connect', maybeReconnect);
2061
};
2062
2063
})(
2064
'undefined' != typeof io ? io : module.exports
2065
, 'undefined' != typeof io ? io : module.parent.exports
2066
);
2067
/**
2068
* socket.io
2069
* Copyright(c) 2011 LearnBoost <[email protected]>
2070
* MIT Licensed
2071
*/
2072
2073
(function (exports, io) {
2074
2075
/**
2076
* Expose constructor.
2077
*/
2078
2079
exports.SocketNamespace = SocketNamespace;
2080
2081
/**
2082
* Socket namespace constructor.
2083
*
2084
* @constructor
2085
* @api public
2086
*/
2087
2088
function SocketNamespace (socket, name) {
2089
this.socket = socket;
2090
this.name = name || '';
2091
this.flags = {};
2092
this.json = new Flag(this, 'json');
2093
this.ackPackets = 0;
2094
this.acks = {};
2095
};
2096
2097
/**
2098
* Apply EventEmitter mixin.
2099
*/
2100
2101
io.util.mixin(SocketNamespace, io.EventEmitter);
2102
2103
/**
2104
* Copies emit since we override it
2105
*
2106
* @api private
2107
*/
2108
2109
SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
2110
2111
/**
2112
* Creates a new namespace, by proxying the request to the socket. This
2113
* allows us to use the synax as we do on the server.
2114
*
2115
* @api public
2116
*/
2117
2118
SocketNamespace.prototype.of = function () {
2119
return this.socket.of.apply(this.socket, arguments);
2120
};
2121
2122
/**
2123
* Sends a packet.
2124
*
2125
* @api private
2126
*/
2127
2128
SocketNamespace.prototype.packet = function (packet) {
2129
packet.endpoint = this.name;
2130
this.socket.packet(packet);
2131
this.flags = {};
2132
return this;
2133
};
2134
2135
/**
2136
* Sends a message
2137
*
2138
* @api public
2139
*/
2140
2141
SocketNamespace.prototype.send = function (data, fn) {
2142
var packet = {
2143
type: this.flags.json ? 'json' : 'message'
2144
, data: data
2145
};
2146
2147
if ('function' == typeof fn) {
2148
packet.id = ++this.ackPackets;
2149
packet.ack = true;
2150
this.acks[packet.id] = fn;
2151
}
2152
2153
return this.packet(packet);
2154
};
2155
2156
/**
2157
* Emits an event
2158
*
2159
* @api public
2160
*/
2161
2162
SocketNamespace.prototype.emit = function (name) {
2163
var args = Array.prototype.slice.call(arguments, 1)
2164
, lastArg = args[args.length - 1]
2165
, packet = {
2166
type: 'event'
2167
, name: name
2168
};
2169
2170
if ('function' == typeof lastArg) {
2171
packet.id = ++this.ackPackets;
2172
packet.ack = 'data';
2173
this.acks[packet.id] = lastArg;
2174
args = args.slice(0, args.length - 1);
2175
}
2176
2177
packet.args = args;
2178
2179
return this.packet(packet);
2180
};
2181
2182
/**
2183
* Disconnects the namespace
2184
*
2185
* @api private
2186
*/
2187
2188
SocketNamespace.prototype.disconnect = function () {
2189
if (this.name === '') {
2190
this.socket.disconnect();
2191
} else {
2192
this.packet({ type: 'disconnect' });
2193
this.$emit('disconnect');
2194
}
2195
2196
return this;
2197
};
2198
2199
/**
2200
* Handles a packet
2201
*
2202
* @api private
2203
*/
2204
2205
SocketNamespace.prototype.onPacket = function (packet) {
2206
var self = this;
2207
2208
function ack () {
2209
self.packet({
2210
type: 'ack'
2211
, args: io.util.toArray(arguments)
2212
, ackId: packet.id
2213
});
2214
};
2215
2216
switch (packet.type) {
2217
case 'connect':
2218
this.$emit('connect');
2219
break;
2220
2221
case 'disconnect':
2222
if (this.name === '') {
2223
this.socket.onDisconnect(packet.reason || 'booted');
2224
} else {
2225
this.$emit('disconnect', packet.reason);
2226
}
2227
break;
2228
2229
case 'message':
2230
case 'json':
2231
var params = ['message', packet.data];
2232
2233
if (packet.ack == 'data') {
2234
params.push(ack);
2235
} else if (packet.ack) {
2236
this.packet({ type: 'ack', ackId: packet.id });
2237
}
2238
2239
this.$emit.apply(this, params);
2240
break;
2241
2242
case 'event':
2243
var params = [packet.name].concat(packet.args);
2244
2245
if (packet.ack == 'data')
2246
params.push(ack);
2247
2248
this.$emit.apply(this, params);
2249
break;
2250
2251
case 'ack':
2252
if (this.acks[packet.ackId]) {
2253
this.acks[packet.ackId].apply(this, packet.args);
2254
delete this.acks[packet.ackId];
2255
}
2256
break;
2257
2258
case 'error':
2259
if (packet.advice) {
2260
this.socket.onError(packet);
2261
} else {
2262
if (packet.reason == 'unauthorized') {
2263
this.$emit('connect_failed', packet.reason);
2264
} else {
2265
this.$emit('error', packet.reason);
2266
}
2267
}
2268
break;
2269
}
2270
};
2271
2272
/**
2273
* Flag interface.
2274
*
2275
* @api private
2276
*/
2277
2278
function Flag (nsp, name) {
2279
this.namespace = nsp;
2280
this.name = name;
2281
};
2282
2283
/**
2284
* Send a message
2285
*
2286
* @api public
2287
*/
2288
2289
Flag.prototype.send = function () {
2290
this.namespace.flags[this.name] = true;
2291
this.namespace.send.apply(this.namespace, arguments);
2292
};
2293
2294
/**
2295
* Emit an event
2296
*
2297
* @api public
2298
*/
2299
2300
Flag.prototype.emit = function () {
2301
this.namespace.flags[this.name] = true;
2302
this.namespace.emit.apply(this.namespace, arguments);
2303
};
2304
2305
})(
2306
'undefined' != typeof io ? io : module.exports
2307
, 'undefined' != typeof io ? io : module.parent.exports
2308
);
2309
2310
/**
2311
* socket.io
2312
* Copyright(c) 2011 LearnBoost <[email protected]>
2313
* MIT Licensed
2314
*/
2315
2316
(function (exports, io) {
2317
2318
/**
2319
* Expose constructor.
2320
*/
2321
2322
exports.websocket = WS;
2323
2324
/**
2325
* The WebSocket transport uses the HTML5 WebSocket API to establish an
2326
* persistent connection with the Socket.IO server. This transport will also
2327
* be inherited by the FlashSocket fallback as it provides a API compatible
2328
* polyfill for the WebSockets.
2329
*
2330
* @constructor
2331
* @extends {io.Transport}
2332
* @api public
2333
*/
2334
2335
function WS (socket) {
2336
io.Transport.apply(this, arguments);
2337
};
2338
2339
/**
2340
* Inherits from Transport.
2341
*/
2342
2343
io.util.inherit(WS, io.Transport);
2344
2345
/**
2346
* Transport name
2347
*
2348
* @api public
2349
*/
2350
2351
WS.prototype.name = 'websocket';
2352
2353
/**
2354
* Initializes a new `WebSocket` connection with the Socket.IO server. We attach
2355
* all the appropriate listeners to handle the responses from the server.
2356
*
2357
* @returns {Transport}
2358
* @api public
2359
*/
2360
2361
WS.prototype.open = function () {
2362
var query = io.util.query(this.socket.options.query)
2363
, self = this
2364
, Socket
2365
2366
2367
if (!Socket) {
2368
Socket = global.MozWebSocket || global.WebSocket;
2369
}
2370
2371
this.websocket = new Socket(this.prepareUrl() + query);
2372
2373
this.websocket.onopen = function () {
2374
self.onOpen();
2375
self.socket.setBuffer(false);
2376
};
2377
this.websocket.onmessage = function (ev) {
2378
self.onData(ev.data);
2379
};
2380
this.websocket.onclose = function () {
2381
self.onClose();
2382
self.socket.setBuffer(true);
2383
};
2384
this.websocket.onerror = function (e) {
2385
self.onError(e);
2386
};
2387
2388
return this;
2389
};
2390
2391
/**
2392
* Send a message to the Socket.IO server. The message will automatically be
2393
* encoded in the correct message format.
2394
*
2395
* @returns {Transport}
2396
* @api public
2397
*/
2398
2399
// Do to a bug in the current IDevices browser, we need to wrap the send in a
2400
// setTimeout, when they resume from sleeping the browser will crash if
2401
// we don't allow the browser time to detect the socket has been closed
2402
if (io.util.ua.iDevice) {
2403
WS.prototype.send = function (data) {
2404
var self = this;
2405
setTimeout(function() {
2406
self.websocket.send(data);
2407
},0);
2408
return this;
2409
};
2410
} else {
2411
WS.prototype.send = function (data) {
2412
this.websocket.send(data);
2413
return this;
2414
};
2415
}
2416
2417
/**
2418
* Payload
2419
*
2420
* @api private
2421
*/
2422
2423
WS.prototype.payload = function (arr) {
2424
for (var i = 0, l = arr.length; i < l; i++) {
2425
this.packet(arr[i]);
2426
}
2427
return this;
2428
};
2429
2430
/**
2431
* Disconnect the established `WebSocket` connection.
2432
*
2433
* @returns {Transport}
2434
* @api public
2435
*/
2436
2437
WS.prototype.close = function () {
2438
this.websocket.close();
2439
return this;
2440
};
2441
2442
/**
2443
* Handle the errors that `WebSocket` might be giving when we
2444
* are attempting to connect or send messages.
2445
*
2446
* @param {Error} e The error.
2447
* @api private
2448
*/
2449
2450
WS.prototype.onError = function (e) {
2451
this.socket.onError(e);
2452
};
2453
2454
/**
2455
* Returns the appropriate scheme for the URI generation.
2456
*
2457
* @api private
2458
*/
2459
WS.prototype.scheme = function () {
2460
return this.socket.options.secure ? 'wss' : 'ws';
2461
};
2462
2463
/**
2464
* Checks if the browser has support for native `WebSockets` and that
2465
* it's not the polyfill created for the FlashSocket transport.
2466
*
2467
* @return {Boolean}
2468
* @api public
2469
*/
2470
2471
WS.check = function () {
2472
return ('WebSocket' in global && !('__addTask' in WebSocket))
2473
|| 'MozWebSocket' in global;
2474
};
2475
2476
/**
2477
* Check if the `WebSocket` transport support cross domain communications.
2478
*
2479
* @returns {Boolean}
2480
* @api public
2481
*/
2482
2483
WS.xdomainCheck = function () {
2484
return true;
2485
};
2486
2487
/**
2488
* Add the transport to your public io.transports array.
2489
*
2490
* @api private
2491
*/
2492
2493
io.transports.push('websocket');
2494
2495
})(
2496
'undefined' != typeof io ? io.Transport : module.exports
2497
, 'undefined' != typeof io ? io : module.parent.exports
2498
);
2499
2500
/**
2501
* socket.io
2502
* Copyright(c) 2011 LearnBoost <[email protected]>
2503
* MIT Licensed
2504
*/
2505
2506
(function (exports, io) {
2507
2508
/**
2509
* Expose constructor.
2510
*/
2511
2512
exports.flashsocket = Flashsocket;
2513
2514
/**
2515
* The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket
2516
* specification. It uses a .swf file to communicate with the server. If you want
2517
* to serve the .swf file from a other server than where the Socket.IO script is
2518
* coming from you need to use the insecure version of the .swf. More information
2519
* about this can be found on the github page.
2520
*
2521
* @constructor
2522
* @extends {io.Transport.websocket}
2523
* @api public
2524
*/
2525
2526
function Flashsocket () {
2527
io.Transport.websocket.apply(this, arguments);
2528
};
2529
2530
/**
2531
* Inherits from Transport.
2532
*/
2533
2534
io.util.inherit(Flashsocket, io.Transport.websocket);
2535
2536
/**
2537
* Transport name
2538
*
2539
* @api public
2540
*/
2541
2542
Flashsocket.prototype.name = 'flashsocket';
2543
2544
/**
2545
* Disconnect the established `FlashSocket` connection. This is done by adding a
2546
* new task to the FlashSocket. The rest will be handled off by the `WebSocket`
2547
* transport.
2548
*
2549
* @returns {Transport}
2550
* @api public
2551
*/
2552
2553
Flashsocket.prototype.open = function () {
2554
var self = this
2555
, args = arguments;
2556
2557
WebSocket.__addTask(function () {
2558
io.Transport.websocket.prototype.open.apply(self, args);
2559
});
2560
return this;
2561
};
2562
2563
/**
2564
* Sends a message to the Socket.IO server. This is done by adding a new
2565
* task to the FlashSocket. The rest will be handled off by the `WebSocket`
2566
* transport.
2567
*
2568
* @returns {Transport}
2569
* @api public
2570
*/
2571
2572
Flashsocket.prototype.send = function () {
2573
var self = this, args = arguments;
2574
WebSocket.__addTask(function () {
2575
io.Transport.websocket.prototype.send.apply(self, args);
2576
});
2577
return this;
2578
};
2579
2580
/**
2581
* Disconnects the established `FlashSocket` connection.
2582
*
2583
* @returns {Transport}
2584
* @api public
2585
*/
2586
2587
Flashsocket.prototype.close = function () {
2588
WebSocket.__tasks.length = 0;
2589
io.Transport.websocket.prototype.close.call(this);
2590
return this;
2591
};
2592
2593
/**
2594
* The WebSocket fall back needs to append the flash container to the body
2595
* element, so we need to make sure we have access to it. Or defer the call
2596
* until we are sure there is a body element.
2597
*
2598
* @param {Socket} socket The socket instance that needs a transport
2599
* @param {Function} fn The callback
2600
* @api private
2601
*/
2602
2603
Flashsocket.prototype.ready = function (socket, fn) {
2604
function init () {
2605
var options = socket.options
2606
, port = options['flash policy port']
2607
, path = [
2608
'http' + (options.secure ? 's' : '') + ':/'
2609
, options.host + ':' + options.port
2610
, options.resource
2611
, 'static/flashsocket'
2612
, 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf'
2613
];
2614
2615
// Only start downloading the swf file when the checked that this browser
2616
// actually supports it
2617
if (!Flashsocket.loaded) {
2618
if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined') {
2619
// Set the correct file based on the XDomain settings
2620
WEB_SOCKET_SWF_LOCATION = path.join('/');
2621
}
2622
2623
if (port !== 843) {
2624
WebSocket.loadFlashPolicyFile('xmlsocket://' + options.host + ':' + port);
2625
}
2626
2627
WebSocket.__initialize();
2628
Flashsocket.loaded = true;
2629
}
2630
2631
fn.call(self);
2632
}
2633
2634
var self = this;
2635
if (document.body) return init();
2636
2637
io.util.load(init);
2638
};
2639
2640
/**
2641
* Check if the FlashSocket transport is supported as it requires that the Adobe
2642
* Flash Player plug-in version `10.0.0` or greater is installed. And also check if
2643
* the polyfill is correctly loaded.
2644
*
2645
* @returns {Boolean}
2646
* @api public
2647
*/
2648
2649
Flashsocket.check = function () {
2650
if (
2651
typeof WebSocket == 'undefined'
2652
|| !('__initialize' in WebSocket) || !swfobject
2653
) return false;
2654
2655
return swfobject.getFlashPlayerVersion().major >= 10;
2656
};
2657
2658
/**
2659
* Check if the FlashSocket transport can be used as cross domain / cross origin
2660
* transport. Because we can't see which type (secure or insecure) of .swf is used
2661
* we will just return true.
2662
*
2663
* @returns {Boolean}
2664
* @api public
2665
*/
2666
2667
Flashsocket.xdomainCheck = function () {
2668
return true;
2669
};
2670
2671
/**
2672
* Disable AUTO_INITIALIZATION
2673
*/
2674
2675
if (typeof window != 'undefined') {
2676
WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true;
2677
}
2678
2679
/**
2680
* Add the transport to your public io.transports array.
2681
*
2682
* @api private
2683
*/
2684
2685
io.transports.push('flashsocket');
2686
})(
2687
'undefined' != typeof io ? io.Transport : module.exports
2688
, 'undefined' != typeof io ? io : module.parent.exports
2689
);
2690
/* SWFObject v2.2 <http://code.google.com/p/swfobject/>
2691
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
2692
*/
2693
if ('undefined' != typeof window) {
2694
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O[(['Active'].concat('Object').join('X'))]!=D){try{var ad=new window[(['Active'].concat('Object').join('X'))](W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?(['Active'].concat('').join('X')):"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
2695
}
2696
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
2697
// License: New BSD License
2698
// Reference: http://dev.w3.org/html5/websockets/
2699
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
2700
2701
(function() {
2702
2703
if ('undefined' == typeof window || window.WebSocket) return;
2704
2705
var console = window.console;
2706
if (!console || !console.log || !console.error) {
2707
console = {log: function(){ }, error: function(){ }};
2708
}
2709
2710
if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
2711
console.error("Flash Player >= 10.0.0 is required.");
2712
return;
2713
}
2714
if (location.protocol == "file:") {
2715
console.error(
2716
"WARNING: web-socket-js doesn't work in file:///... URL " +
2717
"unless you set Flash Security Settings properly. " +
2718
"Open the page via Web server i.e. http://...");
2719
}
2720
2721
/**
2722
* This class represents a faux web socket.
2723
* @param {string} url
2724
* @param {array or string} protocols
2725
* @param {string} proxyHost
2726
* @param {int} proxyPort
2727
* @param {string} headers
2728
*/
2729
WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
2730
var self = this;
2731
self.__id = WebSocket.__nextId++;
2732
WebSocket.__instances[self.__id] = self;
2733
self.readyState = WebSocket.CONNECTING;
2734
self.bufferedAmount = 0;
2735
self.__events = {};
2736
if (!protocols) {
2737
protocols = [];
2738
} else if (typeof protocols == "string") {
2739
protocols = [protocols];
2740
}
2741
// Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
2742
// Otherwise, when onopen fires immediately, onopen is called before it is set.
2743
setTimeout(function() {
2744
WebSocket.__addTask(function() {
2745
WebSocket.__flash.create(
2746
self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
2747
});
2748
}, 0);
2749
};
2750
2751
/**
2752
* Send data to the web socket.
2753
* @param {string} data The data to send to the socket.
2754
* @return {boolean} True for success, false for failure.
2755
*/
2756
WebSocket.prototype.send = function(data) {
2757
if (this.readyState == WebSocket.CONNECTING) {
2758
throw "INVALID_STATE_ERR: Web Socket connection has not been established";
2759
}
2760
// We use encodeURIComponent() here, because FABridge doesn't work if
2761
// the argument includes some characters. We don't use escape() here
2762
// because of this:
2763
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
2764
// But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
2765
// preserve all Unicode characters either e.g. "\uffff" in Firefox.
2766
// Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
2767
// additional testing.
2768
var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
2769
if (result < 0) { // success
2770
return true;
2771
} else {
2772
this.bufferedAmount += result;
2773
return false;
2774
}
2775
};
2776
2777
/**
2778
* Close this web socket gracefully.
2779
*/
2780
WebSocket.prototype.close = function() {
2781
if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
2782
return;
2783
}
2784
this.readyState = WebSocket.CLOSING;
2785
WebSocket.__flash.close(this.__id);
2786
};
2787
2788
/**
2789
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
2790
*
2791
* @param {string} type
2792
* @param {function} listener
2793
* @param {boolean} useCapture
2794
* @return void
2795
*/
2796
WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
2797
if (!(type in this.__events)) {
2798
this.__events[type] = [];
2799
}
2800
this.__events[type].push(listener);
2801
};
2802
2803
/**
2804
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
2805
*
2806
* @param {string} type
2807
* @param {function} listener
2808
* @param {boolean} useCapture
2809
* @return void
2810
*/
2811
WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
2812
if (!(type in this.__events)) return;
2813
var events = this.__events[type];
2814
for (var i = events.length - 1; i >= 0; --i) {
2815
if (events[i] === listener) {
2816
events.splice(i, 1);
2817
break;
2818
}
2819
}
2820
};
2821
2822
/**
2823
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
2824
*
2825
* @param {Event} event
2826
* @return void
2827
*/
2828
WebSocket.prototype.dispatchEvent = function(event) {
2829
var events = this.__events[event.type] || [];
2830
for (var i = 0; i < events.length; ++i) {
2831
events[i](event);
2832
}
2833
var handler = this["on" + event.type];
2834
if (handler) handler(event);
2835
};
2836
2837
/**
2838
* Handles an event from Flash.
2839
* @param {Object} flashEvent
2840
*/
2841
WebSocket.prototype.__handleEvent = function(flashEvent) {
2842
if ("readyState" in flashEvent) {
2843
this.readyState = flashEvent.readyState;
2844
}
2845
if ("protocol" in flashEvent) {
2846
this.protocol = flashEvent.protocol;
2847
}
2848
2849
var jsEvent;
2850
if (flashEvent.type == "open" || flashEvent.type == "error") {
2851
jsEvent = this.__createSimpleEvent(flashEvent.type);
2852
} else if (flashEvent.type == "close") {
2853
// TODO implement jsEvent.wasClean
2854
jsEvent = this.__createSimpleEvent("close");
2855
} else if (flashEvent.type == "message") {
2856
var data = decodeURIComponent(flashEvent.message);
2857
jsEvent = this.__createMessageEvent("message", data);
2858
} else {
2859
throw "unknown event type: " + flashEvent.type;
2860
}
2861
2862
this.dispatchEvent(jsEvent);
2863
};
2864
2865
WebSocket.prototype.__createSimpleEvent = function(type) {
2866
if (document.createEvent && window.Event) {
2867
var event = document.createEvent("Event");
2868
event.initEvent(type, false, false);
2869
return event;
2870
} else {
2871
return {type: type, bubbles: false, cancelable: false};
2872
}
2873
};
2874
2875
WebSocket.prototype.__createMessageEvent = function(type, data) {
2876
if (document.createEvent && window.MessageEvent && !window.opera) {
2877
var event = document.createEvent("MessageEvent");
2878
event.initMessageEvent("message", false, false, data, null, null, window, null);
2879
return event;
2880
} else {
2881
// IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
2882
return {type: type, data: data, bubbles: false, cancelable: false};
2883
}
2884
};
2885
2886
/**
2887
* Define the WebSocket readyState enumeration.
2888
*/
2889
WebSocket.CONNECTING = 0;
2890
WebSocket.OPEN = 1;
2891
WebSocket.CLOSING = 2;
2892
WebSocket.CLOSED = 3;
2893
2894
WebSocket.__flash = null;
2895
WebSocket.__instances = {};
2896
WebSocket.__tasks = [];
2897
WebSocket.__nextId = 0;
2898
2899
/**
2900
* Load a new flash security policy file.
2901
* @param {string} url
2902
*/
2903
WebSocket.loadFlashPolicyFile = function(url){
2904
WebSocket.__addTask(function() {
2905
WebSocket.__flash.loadManualPolicyFile(url);
2906
});
2907
};
2908
2909
/**
2910
* Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
2911
*/
2912
WebSocket.__initialize = function() {
2913
if (WebSocket.__flash) return;
2914
2915
if (WebSocket.__swfLocation) {
2916
// For backword compatibility.
2917
window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
2918
}
2919
if (!window.WEB_SOCKET_SWF_LOCATION) {
2920
console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
2921
return;
2922
}
2923
var container = document.createElement("div");
2924
container.id = "webSocketContainer";
2925
// Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
2926
// Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
2927
// But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
2928
// Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
2929
// the best we can do as far as we know now.
2930
container.style.position = "absolute";
2931
if (WebSocket.__isFlashLite()) {
2932
container.style.left = "0px";
2933
container.style.top = "0px";
2934
} else {
2935
container.style.left = "-100px";
2936
container.style.top = "-100px";
2937
}
2938
var holder = document.createElement("div");
2939
holder.id = "webSocketFlash";
2940
container.appendChild(holder);
2941
document.body.appendChild(container);
2942
// See this article for hasPriority:
2943
// http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
2944
swfobject.embedSWF(
2945
WEB_SOCKET_SWF_LOCATION,
2946
"webSocketFlash",
2947
"1" /* width */,
2948
"1" /* height */,
2949
"10.0.0" /* SWF version */,
2950
null,
2951
null,
2952
{hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
2953
null,
2954
function(e) {
2955
if (!e.success) {
2956
console.error("[WebSocket] swfobject.embedSWF failed");
2957
}
2958
});
2959
};
2960
2961
/**
2962
* Called by Flash to notify JS that it's fully loaded and ready
2963
* for communication.
2964
*/
2965
WebSocket.__onFlashInitialized = function() {
2966
// We need to set a timeout here to avoid round-trip calls
2967
// to flash during the initialization process.
2968
setTimeout(function() {
2969
WebSocket.__flash = document.getElementById("webSocketFlash");
2970
WebSocket.__flash.setCallerUrl(location.href);
2971
WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
2972
for (var i = 0; i < WebSocket.__tasks.length; ++i) {
2973
WebSocket.__tasks[i]();
2974
}
2975
WebSocket.__tasks = [];
2976
}, 0);
2977
};
2978
2979
/**
2980
* Called by Flash to notify WebSockets events are fired.
2981
*/
2982
WebSocket.__onFlashEvent = function() {
2983
setTimeout(function() {
2984
try {
2985
// Gets events using receiveEvents() instead of getting it from event object
2986
// of Flash event. This is to make sure to keep message order.
2987
// It seems sometimes Flash events don't arrive in the same order as they are sent.
2988
var events = WebSocket.__flash.receiveEvents();
2989
for (var i = 0; i < events.length; ++i) {
2990
WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
2991
}
2992
} catch (e) {
2993
console.error(e);
2994
}
2995
}, 0);
2996
return true;
2997
};
2998
2999
// Called by Flash.
3000
WebSocket.__log = function(message) {
3001
console.log(decodeURIComponent(message));
3002
};
3003
3004
// Called by Flash.
3005
WebSocket.__error = function(message) {
3006
console.error(decodeURIComponent(message));
3007
};
3008
3009
WebSocket.__addTask = function(task) {
3010
if (WebSocket.__flash) {
3011
task();
3012
} else {
3013
WebSocket.__tasks.push(task);
3014
}
3015
};
3016
3017
/**
3018
* Test if the browser is running flash lite.
3019
* @return {boolean} True if flash lite is running, false otherwise.
3020
*/
3021
WebSocket.__isFlashLite = function() {
3022
if (!window.navigator || !window.navigator.mimeTypes) {
3023
return false;
3024
}
3025
var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
3026
if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
3027
return false;
3028
}
3029
return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
3030
};
3031
3032
if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
3033
if (window.addEventListener) {
3034
window.addEventListener("load", function(){
3035
WebSocket.__initialize();
3036
}, false);
3037
} else {
3038
window.attachEvent("onload", function(){
3039
WebSocket.__initialize();
3040
});
3041
}
3042
}
3043
3044
})();
3045
3046
/**
3047
* socket.io
3048
* Copyright(c) 2011 LearnBoost <[email protected]>
3049
* MIT Licensed
3050
*/
3051
3052
(function (exports, io) {
3053
3054
/**
3055
* Expose constructor.
3056
*
3057
* @api public
3058
*/
3059
3060
exports.XHR = XHR;
3061
3062
/**
3063
* XHR constructor
3064
*
3065
* @costructor
3066
* @api public
3067
*/
3068
3069
function XHR (socket) {
3070
if (!socket) return;
3071
3072
io.Transport.apply(this, arguments);
3073
this.sendBuffer = [];
3074
};
3075
3076
/**
3077
* Inherits from Transport.
3078
*/
3079
3080
io.util.inherit(XHR, io.Transport);
3081
3082
/**
3083
* Establish a connection
3084
*
3085
* @returns {Transport}
3086
* @api public
3087
*/
3088
3089
XHR.prototype.open = function () {
3090
this.socket.setBuffer(false);
3091
this.onOpen();
3092
this.get();
3093
3094
// we need to make sure the request succeeds since we have no indication
3095
// whether the request opened or not until it succeeded.
3096
this.setCloseTimeout();
3097
3098
return this;
3099
};
3100
3101
/**
3102
* Check if we need to send data to the Socket.IO server, if we have data in our
3103
* buffer we encode it and forward it to the `post` method.
3104
*
3105
* @api private
3106
*/
3107
3108
XHR.prototype.payload = function (payload) {
3109
var msgs = [];
3110
3111
for (var i = 0, l = payload.length; i < l; i++) {
3112
msgs.push(io.parser.encodePacket(payload[i]));
3113
}
3114
3115
this.send(io.parser.encodePayload(msgs));
3116
};
3117
3118
/**
3119
* Send data to the Socket.IO server.
3120
*
3121
* @param data The message
3122
* @returns {Transport}
3123
* @api public
3124
*/
3125
3126
XHR.prototype.send = function (data) {
3127
this.post(data);
3128
return this;
3129
};
3130
3131
/**
3132
* Posts a encoded message to the Socket.IO server.
3133
*
3134
* @param {String} data A encoded message.
3135
* @api private
3136
*/
3137
3138
function empty () { };
3139
3140
XHR.prototype.post = function (data) {
3141
var self = this;
3142
this.socket.setBuffer(true);
3143
3144
function stateChange () {
3145
if (this.readyState == 4) {
3146
this.onreadystatechange = empty;
3147
self.posting = false;
3148
3149
if (this.status == 200) {
3150
self.socket.setBuffer(false);
3151
} else {
3152
self.onClose();
3153
}
3154
}
3155
}
3156
3157
function onload () {
3158
this.onload = empty;
3159
self.socket.setBuffer(false);
3160
};
3161
3162
this.sendXHR = this.request('POST');
3163
3164
if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) {
3165
this.sendXHR.onload = this.sendXHR.onerror = onload;
3166
} else {
3167
this.sendXHR.onreadystatechange = stateChange;
3168
}
3169
3170
this.sendXHR.send(data);
3171
};
3172
3173
/**
3174
* Disconnects the established `XHR` connection.
3175
*
3176
* @returns {Transport}
3177
* @api public
3178
*/
3179
3180
XHR.prototype.close = function () {
3181
this.onClose();
3182
return this;
3183
};
3184
3185
/**
3186
* Generates a configured XHR request
3187
*
3188
* @param {String} url The url that needs to be requested.
3189
* @param {String} method The method the request should use.
3190
* @returns {XMLHttpRequest}
3191
* @api private
3192
*/
3193
3194
XHR.prototype.request = function (method) {
3195
var req = io.util.request(this.socket.isXDomain())
3196
, query = io.util.query(this.socket.options.query, 't=' + +new Date);
3197
3198
req.open(method || 'GET', this.prepareUrl() + query, true);
3199
3200
if (method == 'POST') {
3201
try {
3202
if (req.setRequestHeader) {
3203
req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
3204
} else {
3205
// XDomainRequest
3206
req.contentType = 'text/plain';
3207
}
3208
} catch (e) {}
3209
}
3210
3211
return req;
3212
};
3213
3214
/**
3215
* Returns the scheme to use for the transport URLs.
3216
*
3217
* @api private
3218
*/
3219
3220
XHR.prototype.scheme = function () {
3221
return this.socket.options.secure ? 'https' : 'http';
3222
};
3223
3224
/**
3225
* Check if the XHR transports are supported
3226
*
3227
* @param {Boolean} xdomain Check if we support cross domain requests.
3228
* @returns {Boolean}
3229
* @api public
3230
*/
3231
3232
XHR.check = function (socket, xdomain) {
3233
try {
3234
var request = io.util.request(xdomain),
3235
usesXDomReq = (global.XDomainRequest && request instanceof XDomainRequest),
3236
socketProtocol = (socket && socket.options && socket.options.secure ? 'https:' : 'http:'),
3237
isXProtocol = (global.location && socketProtocol != global.location.protocol);
3238
if (request && !(usesXDomReq && isXProtocol)) {
3239
return true;
3240
}
3241
} catch(e) {}
3242
3243
return false;
3244
};
3245
3246
/**
3247
* Check if the XHR transport supports cross domain requests.
3248
*
3249
* @returns {Boolean}
3250
* @api public
3251
*/
3252
3253
XHR.xdomainCheck = function (socket) {
3254
return XHR.check(socket, true);
3255
};
3256
3257
})(
3258
'undefined' != typeof io ? io.Transport : module.exports
3259
, 'undefined' != typeof io ? io : module.parent.exports
3260
);
3261
/**
3262
* socket.io
3263
* Copyright(c) 2011 LearnBoost <[email protected]>
3264
* MIT Licensed
3265
*/
3266
3267
(function (exports, io) {
3268
3269
/**
3270
* Expose constructor.
3271
*/
3272
3273
exports.htmlfile = HTMLFile;
3274
3275
/**
3276
* The HTMLFile transport creates a `forever iframe` based transport
3277
* for Internet Explorer. Regular forever iframe implementations will
3278
* continuously trigger the browsers buzy indicators. If the forever iframe
3279
* is created inside a `htmlfile` these indicators will not be trigged.
3280
*
3281
* @constructor
3282
* @extends {io.Transport.XHR}
3283
* @api public
3284
*/
3285
3286
function HTMLFile (socket) {
3287
io.Transport.XHR.apply(this, arguments);
3288
};
3289
3290
/**
3291
* Inherits from XHR transport.
3292
*/
3293
3294
io.util.inherit(HTMLFile, io.Transport.XHR);
3295
3296
/**
3297
* Transport name
3298
*
3299
* @api public
3300
*/
3301
3302
HTMLFile.prototype.name = 'htmlfile';
3303
3304
/**
3305
* Creates a new Ac...eX `htmlfile` with a forever loading iframe
3306
* that can be used to listen to messages. Inside the generated
3307
* `htmlfile` a reference will be made to the HTMLFile transport.
3308
*
3309
* @api private
3310
*/
3311
3312
HTMLFile.prototype.get = function () {
3313
this.doc = new window[(['Active'].concat('Object').join('X'))]('htmlfile');
3314
this.doc.open();
3315
this.doc.write('<html></html>');
3316
this.doc.close();
3317
this.doc.parentWindow.s = this;
3318
3319
var iframeC = this.doc.createElement('div');
3320
iframeC.className = 'socketio';
3321
3322
this.doc.body.appendChild(iframeC);
3323
this.iframe = this.doc.createElement('iframe');
3324
3325
iframeC.appendChild(this.iframe);
3326
3327
var self = this
3328
, query = io.util.query(this.socket.options.query, 't='+ +new Date);
3329
3330
this.iframe.src = this.prepareUrl() + query;
3331
3332
io.util.on(window, 'unload', function () {
3333
self.destroy();
3334
});
3335
};
3336
3337
/**
3338
* The Socket.IO server will write script tags inside the forever
3339
* iframe, this function will be used as callback for the incoming
3340
* information.
3341
*
3342
* @param {String} data The message
3343
* @param {document} doc Reference to the context
3344
* @api private
3345
*/
3346
3347
HTMLFile.prototype._ = function (data, doc) {
3348
this.onData(data);
3349
try {
3350
var script = doc.getElementsByTagName('script')[0];
3351
script.parentNode.removeChild(script);
3352
} catch (e) { }
3353
};
3354
3355
/**
3356
* Destroy the established connection, iframe and `htmlfile`.
3357
* And calls the `CollectGarbage` function of Internet Explorer
3358
* to release the memory.
3359
*
3360
* @api private
3361
*/
3362
3363
HTMLFile.prototype.destroy = function () {
3364
if (this.iframe) {
3365
try {
3366
this.iframe.src = 'about:blank';
3367
} catch(e){}
3368
3369
this.doc = null;
3370
this.iframe.parentNode.removeChild(this.iframe);
3371
this.iframe = null;
3372
3373
CollectGarbage();
3374
}
3375
};
3376
3377
/**
3378
* Disconnects the established connection.
3379
*
3380
* @returns {Transport} Chaining.
3381
* @api public
3382
*/
3383
3384
HTMLFile.prototype.close = function () {
3385
this.destroy();
3386
return io.Transport.XHR.prototype.close.call(this);
3387
};
3388
3389
/**
3390
* Checks if the browser supports this transport. The browser
3391
* must have an `Ac...eXObject` implementation.
3392
*
3393
* @return {Boolean}
3394
* @api public
3395
*/
3396
3397
HTMLFile.check = function (socket) {
3398
if (typeof window != "undefined" && (['Active'].concat('Object').join('X')) in window) {
3399
try {
3400
var a = new window[(['Active'].concat('Object').join('X'))]('htmlfile');
3401
return a && io.Transport.XHR.check(socket);
3402
} catch(e){}
3403
}
3404
return false;
3405
};
3406
3407
/**
3408
* Check if cross domain requests are supported.
3409
*
3410
* @returns {Boolean}
3411
* @api public
3412
*/
3413
3414
HTMLFile.xdomainCheck = function () {
3415
// we can probably do handling for sub-domains, we should
3416
// test that it's cross domain but a subdomain here
3417
return false;
3418
};
3419
3420
/**
3421
* Add the transport to your public io.transports array.
3422
*
3423
* @api private
3424
*/
3425
3426
io.transports.push('htmlfile');
3427
3428
})(
3429
'undefined' != typeof io ? io.Transport : module.exports
3430
, 'undefined' != typeof io ? io : module.parent.exports
3431
);
3432
3433
/**
3434
* socket.io
3435
* Copyright(c) 2011 LearnBoost <[email protected]>
3436
* MIT Licensed
3437
*/
3438
3439
(function (exports, io) {
3440
3441
/**
3442
* Expose constructor.
3443
*/
3444
3445
exports['xhr-polling'] = XHRPolling;
3446
3447
/**
3448
* The XHR-polling transport uses long polling XHR requests to create a
3449
* "persistent" connection with the server.
3450
*
3451
* @constructor
3452
* @api public
3453
*/
3454
3455
function XHRPolling () {
3456
io.Transport.XHR.apply(this, arguments);
3457
};
3458
3459
/**
3460
* Inherits from XHR transport.
3461
*/
3462
3463
io.util.inherit(XHRPolling, io.Transport.XHR);
3464
3465
/**
3466
* Merge the properties from XHR transport
3467
*/
3468
3469
io.util.merge(XHRPolling, io.Transport.XHR);
3470
3471
/**
3472
* Transport name
3473
*
3474
* @api public
3475
*/
3476
3477
XHRPolling.prototype.name = 'xhr-polling';
3478
3479
/**
3480
* Indicates whether heartbeats is enabled for this transport
3481
*
3482
* @api private
3483
*/
3484
3485
XHRPolling.prototype.heartbeats = function () {
3486
return false;
3487
};
3488
3489
/**
3490
* Establish a connection, for iPhone and Android this will be done once the page
3491
* is loaded.
3492
*
3493
* @returns {Transport} Chaining.
3494
* @api public
3495
*/
3496
3497
XHRPolling.prototype.open = function () {
3498
var self = this;
3499
3500
io.Transport.XHR.prototype.open.call(self);
3501
return false;
3502
};
3503
3504
/**
3505
* Starts a XHR request to wait for incoming messages.
3506
*
3507
* @api private
3508
*/
3509
3510
function empty () {};
3511
3512
XHRPolling.prototype.get = function () {
3513
if (!this.isOpen) return;
3514
3515
var self = this;
3516
3517
function stateChange () {
3518
if (this.readyState == 4) {
3519
this.onreadystatechange = empty;
3520
3521
if (this.status == 200) {
3522
self.onData(this.responseText);
3523
self.get();
3524
} else {
3525
self.onClose();
3526
}
3527
}
3528
};
3529
3530
function onload () {
3531
this.onload = empty;
3532
this.onerror = empty;
3533
self.retryCounter = 1;
3534
self.onData(this.responseText);
3535
self.get();
3536
};
3537
3538
function onerror () {
3539
self.retryCounter ++;
3540
if(!self.retryCounter || self.retryCounter > 3) {
3541
self.onClose();
3542
} else {
3543
self.get();
3544
}
3545
};
3546
3547
this.xhr = this.request();
3548
3549
if (global.XDomainRequest && this.xhr instanceof XDomainRequest) {
3550
this.xhr.onload = onload;
3551
this.xhr.onerror = onerror;
3552
} else {
3553
this.xhr.onreadystatechange = stateChange;
3554
}
3555
3556
this.xhr.send(null);
3557
};
3558
3559
/**
3560
* Handle the unclean close behavior.
3561
*
3562
* @api private
3563
*/
3564
3565
XHRPolling.prototype.onClose = function () {
3566
io.Transport.XHR.prototype.onClose.call(this);
3567
3568
if (this.xhr) {
3569
this.xhr.onreadystatechange = this.xhr.onload = this.xhr.onerror = empty;
3570
try {
3571
this.xhr.abort();
3572
} catch(e){}
3573
this.xhr = null;
3574
}
3575
};
3576
3577
/**
3578
* Webkit based browsers show a infinit spinner when you start a XHR request
3579
* before the browsers onload event is called so we need to defer opening of
3580
* the transport until the onload event is called. Wrapping the cb in our
3581
* defer method solve this.
3582
*
3583
* @param {Socket} socket The socket instance that needs a transport
3584
* @param {Function} fn The callback
3585
* @api private
3586
*/
3587
3588
XHRPolling.prototype.ready = function (socket, fn) {
3589
var self = this;
3590
3591
io.util.defer(function () {
3592
fn.call(self);
3593
});
3594
};
3595
3596
/**
3597
* Add the transport to your public io.transports array.
3598
*
3599
* @api private
3600
*/
3601
3602
io.transports.push('xhr-polling');
3603
3604
})(
3605
'undefined' != typeof io ? io.Transport : module.exports
3606
, 'undefined' != typeof io ? io : module.parent.exports
3607
);
3608
3609
/**
3610
* socket.io
3611
* Copyright(c) 2011 LearnBoost <[email protected]>
3612
* MIT Licensed
3613
*/
3614
3615
(function (exports, io) {
3616
/**
3617
* There is a way to hide the loading indicator in Firefox. If you create and
3618
* remove a iframe it will stop showing the current loading indicator.
3619
* Unfortunately we can't feature detect that and UA sniffing is evil.
3620
*
3621
* @api private
3622
*/
3623
3624
var indicator = global.document && "MozAppearance" in
3625
global.document.documentElement.style;
3626
3627
/**
3628
* Expose constructor.
3629
*/
3630
3631
exports['jsonp-polling'] = JSONPPolling;
3632
3633
/**
3634
* The JSONP transport creates an persistent connection by dynamically
3635
* inserting a script tag in the page. This script tag will receive the
3636
* information of the Socket.IO server. When new information is received
3637
* it creates a new script tag for the new data stream.
3638
*
3639
* @constructor
3640
* @extends {io.Transport.xhr-polling}
3641
* @api public
3642
*/
3643
3644
function JSONPPolling (socket) {
3645
io.Transport['xhr-polling'].apply(this, arguments);
3646
3647
this.index = io.j.length;
3648
3649
var self = this;
3650
3651
io.j.push(function (msg) {
3652
self._(msg);
3653
});
3654
};
3655
3656
/**
3657
* Inherits from XHR polling transport.
3658
*/
3659
3660
io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
3661
3662
/**
3663
* Transport name
3664
*
3665
* @api public
3666
*/
3667
3668
JSONPPolling.prototype.name = 'jsonp-polling';
3669
3670
/**
3671
* Posts a encoded message to the Socket.IO server using an iframe.
3672
* The iframe is used because script tags can create POST based requests.
3673
* The iframe is positioned outside of the view so the user does not
3674
* notice it's existence.
3675
*
3676
* @param {String} data A encoded message.
3677
* @api private
3678
*/
3679
3680
JSONPPolling.prototype.post = function (data) {
3681
var self = this
3682
, query = io.util.query(
3683
this.socket.options.query
3684
, 't='+ (+new Date) + '&i=' + this.index
3685
);
3686
3687
if (!this.form) {
3688
var form = document.createElement('form')
3689
, area = document.createElement('textarea')
3690
, id = this.iframeId = 'socketio_iframe_' + this.index
3691
, iframe;
3692
3693
form.className = 'socketio';
3694
form.style.position = 'absolute';
3695
form.style.top = '0px';
3696
form.style.left = '0px';
3697
form.style.display = 'none';
3698
form.target = id;
3699
form.method = 'POST';
3700
form.setAttribute('accept-charset', 'utf-8');
3701
area.name = 'd';
3702
form.appendChild(area);
3703
document.body.appendChild(form);
3704
3705
this.form = form;
3706
this.area = area;
3707
}
3708
3709
this.form.action = this.prepareUrl() + query;
3710
3711
function complete () {
3712
initIframe();
3713
self.socket.setBuffer(false);
3714
};
3715
3716
function initIframe () {
3717
if (self.iframe) {
3718
self.form.removeChild(self.iframe);
3719
}
3720
3721
try {
3722
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
3723
iframe = document.createElement('<iframe name="'+ self.iframeId +'">');
3724
} catch (e) {
3725
iframe = document.createElement('iframe');
3726
iframe.name = self.iframeId;
3727
}
3728
3729
iframe.id = self.iframeId;
3730
3731
self.form.appendChild(iframe);
3732
self.iframe = iframe;
3733
};
3734
3735
initIframe();
3736
3737
// we temporarily stringify until we figure out how to prevent
3738
// browsers from turning `\n` into `\r\n` in form inputs
3739
this.area.value = io.JSON.stringify(data);
3740
3741
try {
3742
this.form.submit();
3743
} catch(e) {}
3744
3745
if (this.iframe.attachEvent) {
3746
iframe.onreadystatechange = function () {
3747
if (self.iframe.readyState == 'complete') {
3748
complete();
3749
}
3750
};
3751
} else {
3752
this.iframe.onload = complete;
3753
}
3754
3755
this.socket.setBuffer(true);
3756
};
3757
3758
/**
3759
* Creates a new JSONP poll that can be used to listen
3760
* for messages from the Socket.IO server.
3761
*
3762
* @api private
3763
*/
3764
3765
JSONPPolling.prototype.get = function () {
3766
var self = this
3767
, script = document.createElement('script')
3768
, query = io.util.query(
3769
this.socket.options.query
3770
, 't='+ (+new Date) + '&i=' + this.index
3771
);
3772
3773
if (this.script) {
3774
this.script.parentNode.removeChild(this.script);
3775
this.script = null;
3776
}
3777
3778
script.async = true;
3779
script.src = this.prepareUrl() + query;
3780
script.onerror = function () {
3781
self.onClose();
3782
};
3783
3784
var insertAt = document.getElementsByTagName('script')[0];
3785
insertAt.parentNode.insertBefore(script, insertAt);
3786
this.script = script;
3787
3788
if (indicator) {
3789
setTimeout(function () {
3790
var iframe = document.createElement('iframe');
3791
document.body.appendChild(iframe);
3792
document.body.removeChild(iframe);
3793
}, 100);
3794
}
3795
};
3796
3797
/**
3798
* Callback function for the incoming message stream from the Socket.IO server.
3799
*
3800
* @param {String} data The message
3801
* @api private
3802
*/
3803
3804
JSONPPolling.prototype._ = function (msg) {
3805
this.onData(msg);
3806
if (this.isOpen) {
3807
this.get();
3808
}
3809
return this;
3810
};
3811
3812
/**
3813
* The indicator hack only works after onload
3814
*
3815
* @param {Socket} socket The socket instance that needs a transport
3816
* @param {Function} fn The callback
3817
* @api private
3818
*/
3819
3820
JSONPPolling.prototype.ready = function (socket, fn) {
3821
var self = this;
3822
if (!indicator) return fn.call(this);
3823
3824
io.util.load(function () {
3825
fn.call(self);
3826
});
3827
};
3828
3829
/**
3830
* Checks if browser supports this transport.
3831
*
3832
* @return {Boolean}
3833
* @api public
3834
*/
3835
3836
JSONPPolling.check = function () {
3837
return 'document' in global;
3838
};
3839
3840
/**
3841
* Check if cross domain requests are supported
3842
*
3843
* @returns {Boolean}
3844
* @api public
3845
*/
3846
3847
JSONPPolling.xdomainCheck = function () {
3848
return true;
3849
};
3850
3851
/**
3852
* Add the transport to your public io.transports array.
3853
*
3854
* @api private
3855
*/
3856
3857
io.transports.push('jsonp-polling');
3858
3859
})(
3860
'undefined' != typeof io ? io.Transport : module.exports
3861
, 'undefined' != typeof io ? io : module.parent.exports
3862
);
3863
3864
if (typeof define === "function" && define.amd) {
3865
define([], function () { return io; });
3866
} else {
3867
return io;
3868
}
3869
3870
})(window);
3871
3872