PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/public/vendors/socket.io.js

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