PageRenderTime 72ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/Examples/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js

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