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

/mobileapp/joshfire/vendor/socket.io.js

https://github.com/joshfire-platform-templates/tedx-deprecated
JavaScript | 3524 lines | 2645 code | 311 blank | 568 comment | 203 complexity | 3f214b1344f9c2a538550136807336a2 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. Joshfire.define([],function() {
  2. /*! Socket.IO.js build:0.7.2, development. Copyright(c) 2011 LearnBoost <dev@learnboost.com> MIT Licensed */
  3. /**
  4. * socket.io
  5. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  6. * MIT Licensed
  7. */
  8. (function (exports) {
  9. /**
  10. * IO namespace.
  11. *
  12. * @namespace
  13. */
  14. var io = exports;
  15. /**
  16. * Socket.IO version
  17. *
  18. * @api public
  19. */
  20. io.version = '0.7.2';
  21. /**
  22. * Protocol implemented.
  23. *
  24. * @api public
  25. */
  26. io.protocol = 1;
  27. /**
  28. * Available transports, these will be populated with the available transports
  29. *
  30. * @api public
  31. */
  32. io.transports = [];
  33. /**
  34. * Keep track of jsonp callbacks.
  35. *
  36. * @api private
  37. */
  38. io.j = [];
  39. /**
  40. * Keep track of our io.Sockets
  41. *
  42. * @api private
  43. */
  44. io.sockets = {};
  45. /**
  46. * Manages connections to hosts.
  47. *
  48. * @param {String} uri
  49. * @Param {Boolean} force creation of new socket (defaults to false)
  50. * @api public
  51. */
  52. io.connect = function (host, details) {
  53. var uri = io.util.parseUri(host)
  54. , uuri
  55. , socket;
  56. if ('undefined' != typeof document) {
  57. uri.host = uri.host || document.domain;
  58. uri.port = uri.port || document.location.port;
  59. }
  60. uuri = io.util.uniqueUri(uri);
  61. var options = {
  62. host: uri.host
  63. , secure: uri.protocol == 'https'
  64. , port: uri.port || 80
  65. };
  66. io.util.merge(options, details);
  67. if (options['force new connection'] || !io.sockets[uuri]) {
  68. socket = new io.Socket(options);
  69. }
  70. if (!options['force new connection'] && socket) {
  71. this.sockets[uuri] = socket;
  72. }
  73. socket = socket || this.sockets[uuri];
  74. // if path is different from '' or /
  75. return socket.of(uri.path.length > 1 ? uri.path : '');
  76. };
  77. })('object' === typeof module ? module.exports : (window.io = {}));
  78. /**
  79. * socket.io
  80. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  81. * MIT Licensed
  82. */
  83. (function (exports) {
  84. /**
  85. * Utilities namespace.
  86. *
  87. * @namespace
  88. */
  89. var util = exports.util = {};
  90. /**
  91. * Parses an URI
  92. *
  93. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  94. * @api public
  95. */
  96. var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  97. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
  98. 'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
  99. 'anchor'];
  100. util.parseUri = function (str) {
  101. var m = re.exec(str || '')
  102. , uri = {}
  103. , i = 14;
  104. while (i--) {
  105. uri[parts[i]] = m[i] || '';
  106. }
  107. return uri;
  108. };
  109. /**
  110. * Produces a unique url that identifies a Socket.IO connection.
  111. *
  112. * @param {Object} uri
  113. * @api public
  114. */
  115. util.uniqueUri = function (uri) {
  116. var protocol = uri.protocol
  117. , host = uri.host
  118. , port = uri.port;
  119. if ('undefined' != typeof document) {
  120. host = host || document.domain;
  121. port = port || (protocol == 'https'
  122. && document.location.protocol !== 'https:' ? 443 : document.location.port);
  123. } else {
  124. host = host || 'localhost';
  125. if (!port && protocol == 'https') {
  126. port = 443;
  127. }
  128. }
  129. return (protocol || 'http') + '://' + host + ':' + (port || 80);
  130. };
  131. /**
  132. * Executes the given function when the page is loaded.
  133. *
  134. * io.util.load(function () { console.log('page loaded'); });
  135. *
  136. * @param {Function} fn
  137. * @api public
  138. */
  139. var pageLoaded = false;
  140. util.load = function (fn) {
  141. if (document.readyState === 'complete' || pageLoaded) {
  142. return fn();
  143. }
  144. util.on(window, 'load', fn, false);
  145. };
  146. /**
  147. * Adds an event.
  148. *
  149. * @api private
  150. */
  151. util.on = function (element, event, fn, capture) {
  152. if (element.attachEvent) {
  153. element.attachEvent('on' + event, fn);
  154. } else {
  155. element.addEventListener(event, fn, capture);
  156. }
  157. };
  158. /**
  159. * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
  160. *
  161. * @param {Boolean} [xdomain] Create a request that can be used cross domain.
  162. * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
  163. * @api private
  164. */
  165. util.request = function (xdomain) {
  166. if ('undefined' != typeof window) {
  167. if (xdomain && window.XDomainRequest) {
  168. return new XDomainRequest();
  169. };
  170. if (window.XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
  171. return new XMLHttpRequest();
  172. };
  173. if (!xdomain) {
  174. try {
  175. return new window.ActiveXObject('Microsoft.XMLHTTP');
  176. } catch(e) { }
  177. }
  178. }
  179. return null;
  180. };
  181. /**
  182. * XHR based transport constructor.
  183. *
  184. * @constructor
  185. * @api public
  186. */
  187. /**
  188. * Change the internal pageLoaded value.
  189. */
  190. if ('undefined' != typeof window) {
  191. util.load(function () {
  192. pageLoaded = true;
  193. });
  194. }
  195. /**
  196. * Defers a function to ensure a spinner is not displayed by the browser
  197. *
  198. * @param {Function} fn
  199. * @api public
  200. */
  201. util.defer = function (fn) {
  202. if (!util.ua.webkit) {
  203. return fn();
  204. }
  205. util.load(function () {
  206. setTimeout(fn, 100);
  207. });
  208. };
  209. /**
  210. * Merges two objects.
  211. *
  212. * @api public
  213. */
  214. util.merge = function merge(target, additional, deep, lastseen){
  215. var seen = lastseen || []
  216. , depth = typeof deep == 'undefined' ? 2 : deep
  217. , prop;
  218. for (prop in additional){
  219. if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0){
  220. if (typeof target[prop] !== 'object' || !depth){
  221. target[prop] = additional[prop];
  222. seen.push(additional[prop]);
  223. } else {
  224. util.merge(target[prop], additional[prop], depth - 1, seen);
  225. }
  226. }
  227. }
  228. return target;
  229. };
  230. /**
  231. * Merges prototypes from objects
  232. *
  233. * @api public
  234. */
  235. util.mixin = function (ctor, ctor2) {
  236. util.merge(ctor.prototype, ctor2.prototype);
  237. };
  238. /**
  239. * Shortcut for prototypical and static inheritance.
  240. *
  241. * @api private
  242. */
  243. util.inherit = function (ctor, ctor2) {
  244. ctor.prototype = new ctor2;
  245. util.merge(ctor, ctor2);
  246. };
  247. /**
  248. * Checks if the given object is an Array.
  249. *
  250. * io.util.isArray([]); // true
  251. * io.util.isArray({}); // false
  252. *
  253. * @param Object obj
  254. * @api public
  255. */
  256. util.isArray = Array.isArray || function (obj) {
  257. return Object.prototype.toString.call(obj) === '[object Array]';
  258. };
  259. /**
  260. * Intersects values of two arrays into a third
  261. *
  262. * @api public
  263. */
  264. util.intersect = function (arr, arr2) {
  265. var ret = []
  266. , longest = arr.length > arr2.length ? arr : arr2
  267. , shortest = arr.length > arr2.length ? arr2 : arr
  268. for (var i = 0, l = shortest.length; i < l; i++) {
  269. if (~util.indexOf(longest, shortest[i]))
  270. ret.push(shortest[i]);
  271. }
  272. return ret;
  273. }
  274. /**
  275. * Array indexOf compatibility.
  276. *
  277. * @see bit.ly/a5Dxa2
  278. * @api public
  279. */
  280. util.indexOf = function (arr, o, i) {
  281. if (Array.prototype.indexOf) {
  282. return Array.prototype.indexOf.call(arr, o, i);
  283. }
  284. for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0
  285. ; i < j && arr[i] !== o; i++);
  286. return j <= i ? -1 : i;
  287. };
  288. /**
  289. * Converts enumerables to array.
  290. *
  291. * @api public
  292. */
  293. util.toArray = function (enu) {
  294. var arr = [];
  295. for (var i = 0, l = enu.length; i < l; i++)
  296. arr.push(enu[i]);
  297. return arr;
  298. };
  299. /**
  300. * UA / engines detection namespace.
  301. *
  302. * @namespace
  303. */
  304. util.ua = {};
  305. /**
  306. * Whether the UA supports CORS for XHR.
  307. *
  308. * @api public
  309. */
  310. util.ua.hasCORS = 'undefined' != typeof window && window.XMLHttpRequest &&
  311. (function () {
  312. try {
  313. var a = new XMLHttpRequest();
  314. } catch (e) {
  315. return false;
  316. }
  317. return a.withCredentials != undefined;
  318. })();
  319. /**
  320. * Detect webkit.
  321. *
  322. * @api public
  323. */
  324. util.ua.webkit = 'undefined' != typeof navigator
  325. && /webkit/i.test(navigator.userAgent);
  326. })('undefined' != typeof window ? io : module.exports);
  327. /**
  328. * socket.io
  329. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  330. * MIT Licensed
  331. */
  332. (function (exports, io) {
  333. /**
  334. * Expose constructor.
  335. */
  336. exports.EventEmitter = EventEmitter;
  337. /**
  338. * Event emitter constructor.
  339. *
  340. * @api public.
  341. */
  342. function EventEmitter () {};
  343. /**
  344. * Adds a listener
  345. *
  346. * @api public
  347. */
  348. EventEmitter.prototype.on = function (name, fn) {
  349. if (!this.$events) {
  350. this.$events = {};
  351. }
  352. if (!this.$events[name]) {
  353. this.$events[name] = fn;
  354. } else if (io.util.isArray(this.$events[name])) {
  355. this.$events[name].push(fn);
  356. } else {
  357. this.$events[name] = [this.$events[name], fn];
  358. }
  359. return this;
  360. };
  361. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  362. /**
  363. * Adds a volatile listener.
  364. *
  365. * @api public
  366. */
  367. EventEmitter.prototype.once = function (name, fn) {
  368. var self = this;
  369. function on () {
  370. self.removeListener(name, on);
  371. fn.apply(this, arguments);
  372. };
  373. on.listener = fn;
  374. this.on(name, on);
  375. return this;
  376. };
  377. /**
  378. * Removes a listener.
  379. *
  380. * @api public
  381. */
  382. EventEmitter.prototype.removeListener = function (name, fn) {
  383. if (this.$events && this.$events[name]) {
  384. var list = this.$events[name];
  385. if (io.util.isArray(list)) {
  386. var pos = -1;
  387. for (var i = 0, l = list.length; i < l; i++) {
  388. if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
  389. pos = i;
  390. break;
  391. }
  392. }
  393. if (pos < 0) {
  394. return this;
  395. }
  396. list.splice(pos, 1);
  397. if (!list.length) {
  398. delete this.$events[name];
  399. }
  400. } else if (list === fn || (list.listener && list.listener === fn)) {
  401. delete this.$events[name];
  402. }
  403. }
  404. return this;
  405. };
  406. /**
  407. * Removes all listeners for an event.
  408. *
  409. * @api public
  410. */
  411. EventEmitter.prototype.removeAllListeners = function (name) {
  412. // TODO: enable this when node 0.5 is stable
  413. //if (name === undefined) {
  414. //this.$events = {};
  415. //return this;
  416. //}
  417. if (this.$events && this.$events[name]) {
  418. this.$events[name] = null;
  419. }
  420. return this;
  421. };
  422. /**
  423. * Gets all listeners for a certain event.
  424. *
  425. * @api publci
  426. */
  427. EventEmitter.prototype.listeners = function (name) {
  428. if (!this.$events) {
  429. this.$events = {};
  430. }
  431. if (!this.$events[name]) {
  432. this.$events[name] = [];
  433. }
  434. if (!io.util.isArray(this.$events[name])) {
  435. this.$events[name] = [this.$events[name]];
  436. }
  437. return this.$events[name];
  438. };
  439. /**
  440. * Emits an event.
  441. *
  442. * @api public
  443. */
  444. EventEmitter.prototype.emit = function (name) {
  445. if (!this.$events) {
  446. return false;
  447. }
  448. var handler = this.$events[name];
  449. if (!handler) {
  450. return false;
  451. }
  452. var args = Array.prototype.slice.call(arguments, 1);
  453. if ('function' == typeof handler) {
  454. handler.apply(this, args);
  455. } else if (io.util.isArray(handler)) {
  456. var listeners = handler.slice();
  457. for (var i = 0, l = listeners.length; i < l; i++) {
  458. listeners[i].apply(this, args);
  459. }
  460. } else {
  461. return false;
  462. }
  463. return true;
  464. };
  465. })(
  466. 'undefined' != typeof io ? io : module.exports
  467. , 'undefined' != typeof io ? io : module.parent.exports
  468. );
  469. /**
  470. * socket.io
  471. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  472. * MIT Licensed
  473. */
  474. /**
  475. * Based on JSON2 (http://www.JSON.org/js.html).
  476. */
  477. (function (exports, nativeJSON) {
  478. "use strict";
  479. // use native JSON if it's available
  480. if (nativeJSON && nativeJSON.parse){
  481. return exports.JSON = {
  482. parse: nativeJSON.parse
  483. , stringify: nativeJSON.stringify
  484. }
  485. }
  486. var JSON = exports.JSON = {};
  487. function f(n) {
  488. // Format integers to have at least two digits.
  489. return n < 10 ? '0' + n : n;
  490. }
  491. function date(d, key) {
  492. return isFinite(d.valueOf()) ?
  493. d.getUTCFullYear() + '-' +
  494. f(d.getUTCMonth() + 1) + '-' +
  495. f(d.getUTCDate()) + 'T' +
  496. f(d.getUTCHours()) + ':' +
  497. f(d.getUTCMinutes()) + ':' +
  498. f(d.getUTCSeconds()) + 'Z' : null;
  499. };
  500. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  501. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  502. gap,
  503. indent,
  504. meta = { // table of character substitutions
  505. '\b': '\\b',
  506. '\t': '\\t',
  507. '\n': '\\n',
  508. '\f': '\\f',
  509. '\r': '\\r',
  510. '"' : '\\"',
  511. '\\': '\\\\'
  512. },
  513. rep;
  514. function quote(string) {
  515. // If the string contains no control characters, no quote characters, and no
  516. // backslash characters, then we can safely slap some quotes around it.
  517. // Otherwise we must also replace the offending characters with safe escape
  518. // sequences.
  519. escapable.lastIndex = 0;
  520. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  521. var c = meta[a];
  522. return typeof c === 'string' ? c :
  523. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  524. }) + '"' : '"' + string + '"';
  525. }
  526. function str(key, holder) {
  527. // Produce a string from holder[key].
  528. var i, // The loop counter.
  529. k, // The member key.
  530. v, // The member value.
  531. length,
  532. mind = gap,
  533. partial,
  534. value = holder[key];
  535. // If the value has a toJSON method, call it to obtain a replacement value.
  536. if (value instanceof Date) {
  537. value = date(key);
  538. }
  539. // If we were called with a replacer function, then call the replacer to
  540. // obtain a replacement value.
  541. if (typeof rep === 'function') {
  542. value = rep.call(holder, key, value);
  543. }
  544. // What happens next depends on the value's type.
  545. switch (typeof value) {
  546. case 'string':
  547. return quote(value);
  548. case 'number':
  549. // JSON numbers must be finite. Encode non-finite numbers as null.
  550. return isFinite(value) ? String(value) : 'null';
  551. case 'boolean':
  552. case 'null':
  553. // If the value is a boolean or null, convert it to a string. Note:
  554. // typeof null does not produce 'null'. The case is included here in
  555. // the remote chance that this gets fixed someday.
  556. return String(value);
  557. // If the type is 'object', we might be dealing with an object or an array or
  558. // null.
  559. case 'object':
  560. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  561. // so watch out for that case.
  562. if (!value) {
  563. return 'null';
  564. }
  565. // Make an array to hold the partial results of stringifying this object value.
  566. gap += indent;
  567. partial = [];
  568. // Is the value an array?
  569. if (Object.prototype.toString.apply(value) === '[object Array]') {
  570. // The value is an array. Stringify every element. Use null as a placeholder
  571. // for non-JSON values.
  572. length = value.length;
  573. for (i = 0; i < length; i += 1) {
  574. partial[i] = str(i, value) || 'null';
  575. }
  576. // Join all of the elements together, separated with commas, and wrap them in
  577. // brackets.
  578. v = partial.length === 0 ? '[]' : gap ?
  579. '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
  580. '[' + partial.join(',') + ']';
  581. gap = mind;
  582. return v;
  583. }
  584. // If the replacer is an array, use it to select the members to be stringified.
  585. if (rep && typeof rep === 'object') {
  586. length = rep.length;
  587. for (i = 0; i < length; i += 1) {
  588. if (typeof rep[i] === 'string') {
  589. k = rep[i];
  590. v = str(k, value);
  591. if (v) {
  592. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  593. }
  594. }
  595. }
  596. } else {
  597. // Otherwise, iterate through all of the keys in the object.
  598. for (k in value) {
  599. if (Object.prototype.hasOwnProperty.call(value, k)) {
  600. v = str(k, value);
  601. if (v) {
  602. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  603. }
  604. }
  605. }
  606. }
  607. // Join all of the member texts together, separated with commas,
  608. // and wrap them in braces.
  609. v = partial.length === 0 ? '{}' : gap ?
  610. '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
  611. '{' + partial.join(',') + '}';
  612. gap = mind;
  613. return v;
  614. }
  615. }
  616. // If the JSON object does not yet have a stringify method, give it one.
  617. JSON.stringify = function (value, replacer, space) {
  618. // The stringify method takes a value and an optional replacer, and an optional
  619. // space parameter, and returns a JSON text. The replacer can be a function
  620. // that can replace values, or an array of strings that will select the keys.
  621. // A default replacer method can be provided. Use of the space parameter can
  622. // produce text that is more easily readable.
  623. var i;
  624. gap = '';
  625. indent = '';
  626. // If the space parameter is a number, make an indent string containing that
  627. // many spaces.
  628. if (typeof space === 'number') {
  629. for (i = 0; i < space; i += 1) {
  630. indent += ' ';
  631. }
  632. // If the space parameter is a string, it will be used as the indent string.
  633. } else if (typeof space === 'string') {
  634. indent = space;
  635. }
  636. // If there is a replacer, it must be a function or an array.
  637. // Otherwise, throw an error.
  638. rep = replacer;
  639. if (replacer && typeof replacer !== 'function' &&
  640. (typeof replacer !== 'object' ||
  641. typeof replacer.length !== 'number')) {
  642. throw new Error('JSON.stringify');
  643. }
  644. // Make a fake root object containing our value under the key of ''.
  645. // Return the result of stringifying the value.
  646. return str('', {'': value});
  647. };
  648. // If the JSON object does not yet have a parse method, give it one.
  649. JSON.parse = function (text, reviver) {
  650. // The parse method takes a text and an optional reviver function, and returns
  651. // a JavaScript value if the text is a valid JSON text.
  652. var j;
  653. function walk(holder, key) {
  654. // The walk method is used to recursively walk the resulting structure so
  655. // that modifications can be made.
  656. var k, v, value = holder[key];
  657. if (value && typeof value === 'object') {
  658. for (k in value) {
  659. if (Object.prototype.hasOwnProperty.call(value, k)) {
  660. v = walk(value, k);
  661. if (v !== undefined) {
  662. value[k] = v;
  663. } else {
  664. delete value[k];
  665. }
  666. }
  667. }
  668. }
  669. return reviver.call(holder, key, value);
  670. }
  671. // Parsing happens in four stages. In the first stage, we replace certain
  672. // Unicode characters with escape sequences. JavaScript handles many characters
  673. // incorrectly, either silently deleting them, or treating them as line endings.
  674. text = String(text);
  675. cx.lastIndex = 0;
  676. if (cx.test(text)) {
  677. text = text.replace(cx, function (a) {
  678. return '\\u' +
  679. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  680. });
  681. }
  682. // In the second stage, we run the text against regular expressions that look
  683. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  684. // because they can cause invocation, and '=' because it can cause mutation.
  685. // But just to be safe, we want to reject all unexpected forms.
  686. // We split the second stage into 4 regexp operations in order to work around
  687. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  688. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  689. // replace all simple value tokens with ']' characters. Third, we delete all
  690. // open brackets that follow a colon or comma or that begin the text. Finally,
  691. // we look to see that the remaining characters are only whitespace or ']' or
  692. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  693. if (/^[\],:{}\s]*$/
  694. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  695. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  696. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  697. // In the third stage we use the eval function to compile the text into a
  698. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  699. // in JavaScript: it can begin a block or an object literal. We wrap the text
  700. // in parens to eliminate the ambiguity.
  701. j = eval('(' + text + ')');
  702. // In the optional fourth stage, we recursively walk the new structure, passing
  703. // each name/value pair to a reviver function for possible transformation.
  704. return typeof reviver === 'function' ?
  705. walk({'': j}, '') : j;
  706. }
  707. // If the text is not JSON parseable, then a SyntaxError is thrown.
  708. throw new SyntaxError('JSON.parse');
  709. };
  710. })(
  711. 'undefined' != typeof io ? io : module.exports
  712. , typeof JSON !== 'undefined' ? JSON : undefined
  713. );
  714. /**
  715. * socket.io
  716. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  717. * MIT Licensed
  718. */
  719. (function (exports, io) {
  720. /**
  721. * Parser namespace.
  722. *
  723. * @namespace
  724. */
  725. var parser = exports.parser = {};
  726. /**
  727. * Packet types.
  728. */
  729. var packets = parser.packets = [
  730. 'disconnect'
  731. , 'connect'
  732. , 'heartbeat'
  733. , 'message'
  734. , 'json'
  735. , 'event'
  736. , 'ack'
  737. , 'error'
  738. , 'noop'
  739. ];
  740. /**
  741. * Errors reasons.
  742. */
  743. var reasons = parser.reasons = [
  744. 'transport not supported'
  745. , 'client not handshaken'
  746. , 'unauthorized'
  747. ];
  748. /**
  749. * Errors advice.
  750. */
  751. var advice = parser.advice = [
  752. 'reconnect'
  753. ];
  754. /**
  755. * Shortcuts.
  756. */
  757. var JSON = io.JSON
  758. , indexOf = io.util.indexOf;
  759. /**
  760. * Encodes a packet.
  761. *
  762. * @api private
  763. */
  764. parser.encodePacket = function (packet) {
  765. var type = indexOf(packets, packet.type)
  766. , id = packet.id || ''
  767. , endpoint = packet.endpoint || ''
  768. , ack = packet.ack
  769. , data = null;
  770. switch (packet.type) {
  771. case 'error':
  772. var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
  773. , adv = packet.advice ? indexOf(advice, packet.advice) : ''
  774. if (reason !== '' || adv !== '')
  775. data = reason + (adv !== '' ? ('+' + adv) : '')
  776. break;
  777. case 'message':
  778. if (packet.data !== '')
  779. data = packet.data;
  780. break;
  781. case 'event':
  782. var ev = { name: packet.name };
  783. if (packet.args && packet.args.length) {
  784. ev.args = packet.args;
  785. }
  786. data = JSON.stringify(ev);
  787. break;
  788. case 'json':
  789. data = JSON.stringify(packet.data);
  790. break;
  791. case 'connect':
  792. if (packet.qs)
  793. data = packet.qs;
  794. break;
  795. case 'ack':
  796. data = packet.ackId
  797. + (packet.args && packet.args.length
  798. ? '+' + JSON.stringify(packet.args) : '');
  799. break;
  800. }
  801. // construct packet with required fragments
  802. var encoded = [
  803. type
  804. , id + (ack == 'data' ? '+' : '')
  805. , endpoint
  806. ];
  807. // data fragment is optional
  808. if (data !== null && data !== undefined)
  809. encoded.push(data);
  810. return encoded.join(':');
  811. };
  812. /**
  813. * Encodes multiple messages (payload).
  814. *
  815. * @param {Array} messages
  816. * @api private
  817. */
  818. parser.encodePayload = function (packets) {
  819. var decoded = '';
  820. if (packets.length == 1)
  821. return packets[0];
  822. for (var i = 0, l = packets.length; i < l; i++) {
  823. var packet = packets[i];
  824. decoded += '\ufffd' + packet.length + '\ufffd' + packets[i]
  825. }
  826. return decoded;
  827. };
  828. /**
  829. * Decodes a packet
  830. *
  831. * @api private
  832. */
  833. var regexp = /^([^:]+):([0-9]+)?(\+)?:([^:]+)?:?(.*)?$/;
  834. parser.decodePacket = function (data) {
  835. var pieces = data.match(regexp);
  836. if (!pieces) return {};
  837. var id = pieces[2] || ''
  838. , data = pieces[5] || ''
  839. , packet = {
  840. type: packets[pieces[1]]
  841. , endpoint: pieces[4] || ''
  842. };
  843. // whether we need to acknowledge the packet
  844. if (id) {
  845. packet.id = id;
  846. if (pieces[3])
  847. packet.ack = 'data';
  848. else
  849. packet.ack = true;
  850. }
  851. // handle different packet types
  852. switch (packet.type) {
  853. case 'error':
  854. var pieces = data.split('+');
  855. packet.reason = reasons[pieces[0]] || '';
  856. packet.advice = advice[pieces[1]] || '';
  857. break;
  858. case 'message':
  859. packet.data = data || '';
  860. break;
  861. case 'event':
  862. try {
  863. var opts = JSON.parse(data);
  864. packet.name = opts.name;
  865. packet.args = opts.args;
  866. } catch (e) { }
  867. packet.args = packet.args || [];
  868. break;
  869. case 'json':
  870. try {
  871. packet.data = JSON.parse(data);
  872. } catch (e) { }
  873. break;
  874. case 'connect':
  875. packet.qs = data || '';
  876. break;
  877. case 'ack':
  878. var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
  879. if (pieces) {
  880. packet.ackId = pieces[1];
  881. packet.args = [];
  882. if (pieces[3]) {
  883. try {
  884. packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
  885. } catch (e) { }
  886. }
  887. }
  888. break;
  889. case 'disconnect':
  890. case 'heartbeat':
  891. break;
  892. };
  893. return packet;
  894. };
  895. /**
  896. * Decodes data payload. Detects multiple messages
  897. *
  898. * @return {Array} messages
  899. * @api public
  900. */
  901. parser.decodePayload = function (data) {
  902. if (data[0] == '\ufffd') {
  903. var ret = [];
  904. for (var i = 1, length = ''; i < data.length; i++) {
  905. if (data[i] == '\ufffd') {
  906. ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
  907. i += Number(length) + 1;
  908. length = '';
  909. } else {
  910. length += data[i];
  911. }
  912. }
  913. return ret;
  914. } else {
  915. return [parser.decodePacket(data)];
  916. }
  917. };
  918. })(
  919. 'undefined' != typeof io ? io : module.exports
  920. , 'undefined' != typeof io ? io : module.parent.exports
  921. );
  922. /**
  923. * socket.io
  924. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  925. * MIT Licensed
  926. */
  927. (function (exports, io) {
  928. /**
  929. * Expose constructor.
  930. */
  931. exports.Transport = Transport;
  932. /**
  933. * This is the transport template for all supported transport methods.
  934. *
  935. * @constructor
  936. * @api public
  937. */
  938. function Transport (socket, sessid) {
  939. this.socket = socket;
  940. this.sessid = sessid;
  941. };
  942. /**
  943. * Apply EventEmitter mixin.
  944. */
  945. io.util.mixin(Transport, io.EventEmitter);
  946. /**
  947. * Handles the response from the server. When a new response is received
  948. * it will automatically update the timeout, decode the message and
  949. * forwards the response to the onMessage function for further processing.
  950. *
  951. * @param {String} data Response from the server.
  952. * @api private
  953. */
  954. Transport.prototype.onData = function(data){
  955. this.clearCloseTimeout();
  956. this.setCloseTimeout();
  957. if (data !== '') {
  958. // todo: we should only do decodePayload for xhr transports
  959. var msgs = io.parser.decodePayload(data);
  960. if (msgs && msgs.length) {
  961. for (var i = 0, l = msgs.length; i < l; i++) {
  962. this.onPacket(msgs[i]);
  963. }
  964. }
  965. }
  966. return this;
  967. };
  968. /**
  969. * Handles packets.
  970. *
  971. * @api private
  972. */
  973. Transport.prototype.onPacket = function (packet) {
  974. if (packet.type == 'heartbeat') {
  975. return this.onHeartbeat();
  976. }
  977. if (packet.type == 'connect' && packet.endpoint == ''){
  978. return this.onConnect();
  979. }
  980. this.socket.onPacket(packet);
  981. return this;
  982. };
  983. /**
  984. * Sets close timeout
  985. *
  986. * @api private
  987. */
  988. Transport.prototype.setCloseTimeout = function () {
  989. if (!this.closeTimeout) {
  990. var self = this;
  991. this.closeTimeout = setTimeout(function () {
  992. self.onDisconnect();
  993. }, this.socket.closeTimeout);
  994. }
  995. };
  996. /**
  997. * Called when transport disconnects.
  998. *
  999. * @api private
  1000. */
  1001. Transport.prototype.onDisconnect = function () {
  1002. if (this.close) this.close();
  1003. this.clearTimeouts();
  1004. this.socket.onDisconnect();
  1005. return this;
  1006. };
  1007. /**
  1008. * Called when transport connects
  1009. *
  1010. * @api private
  1011. */
  1012. Transport.prototype.onConnect = function () {
  1013. this.socket.onConnect();
  1014. return this;
  1015. }
  1016. /**
  1017. * Clears close timeout
  1018. *
  1019. * @api private
  1020. */
  1021. Transport.prototype.clearCloseTimeout = function () {
  1022. if (this.closeTimeout) {
  1023. clearTimeout(this.closeTimeout);
  1024. this.closeTimeout = null;
  1025. }
  1026. };
  1027. /**
  1028. * Clear timeouts
  1029. *
  1030. * @api private
  1031. */
  1032. Transport.prototype.clearTimeouts = function () {
  1033. this.clearCloseTimeout();
  1034. if (this.reopenTimeout) {
  1035. clearTimeout(this.reopenTimeout);
  1036. }
  1037. };
  1038. /**
  1039. * Sends a packet
  1040. *
  1041. * @param {Object} packet object.
  1042. * @api private
  1043. */
  1044. Transport.prototype.packet = function (packet) {
  1045. this.send(io.parser.encodePacket(packet));
  1046. };
  1047. /**
  1048. * Send the received heartbeat message back to server. So the server
  1049. * knows we are still connected.
  1050. *
  1051. * @param {String} heartbeat Heartbeat response from the server.
  1052. * @api private
  1053. */
  1054. Transport.prototype.onHeartbeat = function (heartbeat) {
  1055. this.packet({ type: 'heartbeat' });
  1056. };
  1057. /**
  1058. * Called when the transport opens.
  1059. *
  1060. * @api private
  1061. */
  1062. Transport.prototype.onOpen = function () {
  1063. this.open = true;
  1064. this.clearCloseTimeout();
  1065. this.socket.onOpen();
  1066. };
  1067. /**
  1068. * Notifies the base when the connection with the Socket.IO server
  1069. * has been disconnected.
  1070. *
  1071. * @api private
  1072. */
  1073. Transport.prototype.onClose = function () {
  1074. var self = this;
  1075. /* FIXME: reopen delay causing a infinit loop
  1076. this.reopenTimeout = setTimeout(function () {
  1077. self.open();
  1078. }, this.socket.options['reopen delay']);*/
  1079. this.open = false;
  1080. this.setCloseTimeout();
  1081. this.socket.onClose();
  1082. };
  1083. /**
  1084. * Generates a connection url based on the Socket.IO URL Protocol.
  1085. * See <https://github.com/learnboost/socket.io-node/> for more details.
  1086. *
  1087. * @returns {String} Connection url
  1088. * @api private
  1089. */
  1090. Transport.prototype.prepareUrl = function () {
  1091. var options = this.socket.options;
  1092. return this.scheme() + '://'
  1093. + options.host + ':' + options.port + '/'
  1094. + options.resource + '/' + io.protocol
  1095. + '/' + this.name + '/' + this.sessid;
  1096. };
  1097. })(
  1098. 'undefined' != typeof io ? io : module.exports
  1099. , 'undefined' != typeof io ? io : module.parent.exports
  1100. );
  1101. /**
  1102. * socket.io
  1103. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1104. * MIT Licensed
  1105. */
  1106. (function (exports, io) {
  1107. /**
  1108. * Expose constructor.
  1109. */
  1110. exports.Socket = Socket;
  1111. /**
  1112. * Create a new `Socket.IO client` which can establish a persisent
  1113. * connection with a Socket.IO enabled server.
  1114. *
  1115. * @api public
  1116. */
  1117. function Socket (options) {
  1118. this.options = {
  1119. port: 80
  1120. , secure: false
  1121. , document: document
  1122. , resource: 'socket.io'
  1123. , transports: io.transports
  1124. , 'connect timeout': 10000
  1125. , 'try multiple transports': true
  1126. , 'reconnect': true
  1127. , 'reconnection delay': 500
  1128. , 'reopen delay': 3000
  1129. , 'max reconnection attempts': 10
  1130. , 'sync disconnect on unload': true
  1131. , 'auto connect': true
  1132. };
  1133. io.util.merge(this.options, options);
  1134. this.connected = false;
  1135. this.open = false;
  1136. this.connecting = false;
  1137. this.reconnecting = false;
  1138. this.namespaces = {};
  1139. this.buffer = [];
  1140. this.doBuffer = false;
  1141. if (this.options['sync disconnect on unload'] &&
  1142. (!this.isXDomain() || io.util.ua.hasCORS)) {
  1143. var self = this;
  1144. io.util.on(window, 'beforeunload', function () {
  1145. self.disconnectSync();
  1146. }, false);
  1147. }
  1148. if (this.options['auto connect']) {
  1149. this.connect();
  1150. }
  1151. };
  1152. /**
  1153. * Apply EventEmitter mixin.
  1154. */
  1155. io.util.mixin(Socket, io.EventEmitter);
  1156. /**
  1157. * Returns a namespace listener/emitter for this socket
  1158. *
  1159. * @api public
  1160. */
  1161. Socket.prototype.of = function (name) {
  1162. if (!this.namespaces[name]) {
  1163. this.namespaces[name] = new io.SocketNamespace(this, name);
  1164. if (name !== '') {
  1165. this.namespaces[name].packet({ type: 'connect' });
  1166. }
  1167. }
  1168. return this.namespaces[name];
  1169. };
  1170. /**
  1171. * Emits the given event to the Socket and all namespaces
  1172. *
  1173. * @api private
  1174. */
  1175. Socket.prototype.publish = function(){
  1176. this.emit.apply(this, arguments);
  1177. var nsp;
  1178. for (var i in this.namespaces) {
  1179. if (this.namespaces.hasOwnProperty(i)) {
  1180. nsp = this.of(i);
  1181. nsp.$emit.apply(nsp, arguments);
  1182. }
  1183. }
  1184. };
  1185. /**
  1186. * Performs the handshake
  1187. *
  1188. * @api private
  1189. */
  1190. function empty () { };
  1191. Socket.prototype.handshake = function (fn) {
  1192. var self = this
  1193. , options = this.options;
  1194. function complete (data) {
  1195. if (data instanceof Error) {
  1196. self.onError(data.message);
  1197. } else {
  1198. fn.apply(null, data.split(':'));
  1199. }
  1200. };
  1201. var url = [
  1202. 'http' + (options.secure ? 's' : '') + ':/'
  1203. , options.host + ':' + options.port
  1204. , this.options.resource
  1205. , io.protocol
  1206. , '?t=' + + new Date
  1207. ].join('/');
  1208. if (this.isXDomain()) {
  1209. var insertAt = document.getElementsByTagName('script')[0]
  1210. , script = document.createElement('SCRIPT');
  1211. script.src = url + '&jsonp=' + io.j.length;
  1212. insertAt.parentNode.insertBefore(script, insertAt);
  1213. io.j.push(function (data) {
  1214. complete(data);
  1215. script.parentNode.removeChild(script);
  1216. });
  1217. } else {
  1218. var xhr = io.util.request();
  1219. xhr.open('GET', url);
  1220. xhr.onreadystatechange = function () {
  1221. if (xhr.readyState == 4) {
  1222. xhr.onreadystatechange = empty;
  1223. if (xhr.status == 200) {
  1224. complete(xhr.responseText);
  1225. } else {
  1226. !self.reconnecting && self.onError(xhr.responseText);
  1227. }
  1228. }
  1229. };
  1230. xhr.send(null);
  1231. }
  1232. };
  1233. /**
  1234. * Find an available transport based on the options supplied in the constructor.
  1235. *
  1236. * @api private
  1237. */
  1238. Socket.prototype.getTransport = function (override) {
  1239. var transports = override || this.transports, match;
  1240. for (var i = 0, transport; transport = transports[i]; i++) {
  1241. if (io.Transport[transport]
  1242. && io.Transport[transport].check(this)
  1243. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
  1244. return new io.Transport[transport](this, this.sessionid);
  1245. }
  1246. }
  1247. return null;
  1248. };
  1249. /**
  1250. * Connects to the server.
  1251. *
  1252. * @param {Function} [fn] Callback.
  1253. * @returns {io.Socket}
  1254. * @api public
  1255. */
  1256. Socket.prototype.connect = function (fn) {
  1257. if (this.connecting) {
  1258. return this;
  1259. }
  1260. var self = this;
  1261. this.handshake(function (sid, heartbeat, close, transports) {
  1262. self.sessionid = sid;
  1263. self.closeTimeout = close * 1000;
  1264. self.heartbeatTimeout = heartbeat * 1000;
  1265. self.transports = io.util.intersect(
  1266. transports.split(',')
  1267. , self.options.transports
  1268. );
  1269. self.transport = self.getTransport();
  1270. if (!self.transport) {
  1271. return;
  1272. }
  1273. self.connecting = true;
  1274. self.publish('connecting', self.transport.name);
  1275. self.transport.open();
  1276. if (self.options.connectTimeout) {
  1277. self.connectTimeoutTimer = setTimeout(function () {
  1278. if (!self.connected) {
  1279. if (self.options['try multiple transports']){
  1280. if (!self.remainingTransports) {
  1281. self.remainingTransports = self.transports.slice(0);
  1282. }
  1283. var transports = self.remainingTransports;
  1284. while (transports.length > 0 && transports.splice(0,1)[0] !=
  1285. self.transport.name) {}
  1286. if (transports.length) {
  1287. self.transport = self.getTransport(transports);
  1288. self.connect();
  1289. }
  1290. }
  1291. if (!self.remainingTransports || self.remainingTransports.length == 0) {
  1292. self.publish('connect_failed');
  1293. }
  1294. }
  1295. if(self.remainingTransports && self.remainingTransports.length == 0) {
  1296. delete self.remainingTransports;
  1297. }
  1298. }, self.options['connect timeout']);
  1299. }
  1300. if (fn && typeof fn == 'function') {
  1301. self.once('connect', fn);
  1302. }
  1303. });
  1304. return this;
  1305. };
  1306. /**
  1307. * Sends a message.
  1308. *
  1309. * @param {Object} data packet.
  1310. * @returns {io.Socket}
  1311. * @api public
  1312. */
  1313. Socket.prototype.packet = function (data) {
  1314. if (this.connected && !this.doBuffer) {
  1315. this.transport.packet(data);
  1316. } else {
  1317. this.buffer.push(data);
  1318. }
  1319. return this;
  1320. };
  1321. /**
  1322. * Sets buffer state
  1323. *
  1324. * @api private
  1325. */
  1326. Socket.prototype.setBuffer = function (v) {
  1327. this.doBuffer = v;
  1328. if (!v && this.connected && this.buffer.length) {
  1329. this.transport.payload(this.buffer);
  1330. this.buffer = [];
  1331. }
  1332. };
  1333. /**
  1334. * Disconnect the established connect.
  1335. *
  1336. * @returns {io.Socket}
  1337. * @api public
  1338. */
  1339. Socket.prototype.disconnect = function () {
  1340. if (this.connected) {
  1341. if (this.open) {
  1342. this.of('').packet({ type: 'disconnect' });
  1343. }
  1344. // handle disconnection immediately
  1345. this.onDisconnect('booted');
  1346. }
  1347. return this;
  1348. };
  1349. /**
  1350. * Disconnects the socket with a sync XHR.
  1351. *
  1352. * @api private
  1353. */
  1354. Socket.prototype.disconnectSync = function () {
  1355. // ensure disconnection
  1356. var xhr = io.util.request()
  1357. , uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
  1358. xhr.open('GET', uri, true);
  1359. // handle disconnection immediately
  1360. this.onDisconnect('booted');
  1361. };
  1362. /**
  1363. * Check if we need to use cross domain enabled transports. Cross domain would
  1364. * be a different port or different domain name.
  1365. *
  1366. * @returns {Boolean}
  1367. * @api private
  1368. */
  1369. Socket.prototype.isXDomain = function () {
  1370. var locPort = window.location.port || 80;
  1371. return this.options.host !== document.domain || this.options.port != locPort;
  1372. };
  1373. /**
  1374. * Called upon handshake.
  1375. *
  1376. * @api private
  1377. */
  1378. Socket.prototype.onConnect = function(){
  1379. this.connected = true;
  1380. this.connecting = false;
  1381. if (!this.doBuffer) {
  1382. // make sure to flush the buffer
  1383. this.setBuffer(false);
  1384. }
  1385. this.publish('connect');
  1386. };
  1387. /**
  1388. * Called when the transport opens
  1389. *
  1390. * @api private
  1391. */
  1392. Socket.prototype.onOpen = function () {
  1393. this.open = true;
  1394. };
  1395. /**
  1396. * Called when the transport closes.
  1397. *
  1398. * @api private
  1399. */
  1400. Socket.prototype.onClose = function () {
  1401. this.open = false;
  1402. };
  1403. /**
  1404. * Called when the transport first opens a connection
  1405. *
  1406. * @param text
  1407. */
  1408. Socket.prototype.onPacket = function (packet) {
  1409. this.of(packet.endpoint).onPacket(packet);
  1410. };
  1411. /**
  1412. * Handles an error.
  1413. *
  1414. * @api private
  1415. */
  1416. Socket.prototype.onError = function (err) {
  1417. if (err && err.advice){
  1418. if (err.advice === 'reconnect'){
  1419. this.disconnect();
  1420. this.reconnect();
  1421. }
  1422. }
  1423. this.publish('error', err && err.reason ? err.reason : err);
  1424. };
  1425. /**
  1426. * Called when the transport disconnects.
  1427. *
  1428. * @api private
  1429. */
  1430. Socket.prototype.onDisconnect = function (reason) {
  1431. var wasConnected = this.connected;
  1432. this.connected = false;
  1433. this.connecting = false;
  1434. this.open = false;
  1435. if (wasConnected) {
  1436. this.transport.close();
  1437. this.transport.clearTimeouts();
  1438. this.publish('disconnect', reason);
  1439. if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
  1440. this.reconnect();
  1441. }
  1442. }
  1443. };
  1444. /**
  1445. * Called upon reconnection.
  1446. *
  1447. * @api private
  1448. */
  1449. Socket.prototype.reconnect = function () {
  1450. this.reconnecting = true;
  1451. this.reconnectionAttempts = 0;
  1452. this.reconnectionDelay = this.options['reconnection delay'];
  1453. var self = this
  1454. , maxAttempts = this.options['max reconnection attempts']
  1455. , tryMultiple = this.options['try multiple transports']
  1456. function reset () {
  1457. if (self.connected) {
  1458. self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
  1459. }
  1460. self.removeListener('connect_failed', maybeReconnect);
  1461. self.removeListener('connect', maybeReconnect);
  1462. self.reconnecting = false;
  1463. delete self.reconnectionAttempts;
  1464. delete self.reconnectionDelay;
  1465. delete self.reconnectionTimer;
  1466. delete self.redoTransports;
  1467. self.options['try multiple transports'] = tryMultiple;
  1468. };
  1469. function maybeReconnect () {
  1470. if (!self.reconnecting) {
  1471. return;
  1472. }
  1473. if (self.connected) {
  1474. return reset();
  1475. };
  1476. if (self.connecting && self.reconnecting) {
  1477. return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1478. }
  1479. if (self.reconnectionAttempts++ >= maxAttempts) {
  1480. if (!self.redoTransports) {
  1481. self.on('connect_failed', maybeReconnect);
  1482. self.options['try multiple transports'] = true;
  1483. self.transport = self.getTransport();
  1484. self.redoTransports = true;
  1485. self.connect();
  1486. } else {
  1487. self.publish('reconnect_failed');
  1488. reset();
  1489. }
  1490. } else {
  1491. self.reconnectionDelay *= 2; // exponential back off
  1492. self.connect();
  1493. self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
  1494. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1495. }
  1496. };
  1497. this.options['try multiple transports'] = false;
  1498. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1499. this.on('connect', maybeReconnect);
  1500. };
  1501. })(
  1502. 'undefined' != typeof io ? io : module.exports
  1503. , 'undefined' != typeof io ? io : module.parent.exports
  1504. );
  1505. /**
  1506. * socket.io
  1507. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1508. * MIT Licensed
  1509. */
  1510. (function (exports, io) {
  1511. /**
  1512. * Expose constructor.
  1513. */
  1514. exports.SocketNamespace = SocketNamespace;
  1515. /**
  1516. * Socket namespace constructor.
  1517. *
  1518. * @constructor
  1519. * @api public
  1520. */
  1521. function SocketNamespace (socket, name) {
  1522. this.socket = socket;
  1523. this.name = name || '';
  1524. this.flags = {};
  1525. this.json = new Flag(this, 'json');
  1526. this.ackPackets = 0;
  1527. this.acks = {};
  1528. };
  1529. /**
  1530. * Apply EventEmitter mixin.
  1531. */
  1532. io.util.mixin(SocketNamespace, io.EventEmitter);
  1533. /**
  1534. * Copies emit since we override it
  1535. *
  1536. * @api private
  1537. */
  1538. SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
  1539. /**
  1540. * Sends a packet.
  1541. *
  1542. * @api private
  1543. */
  1544. SocketNamespace.prototype.packet = function (packet) {
  1545. packet.endpoint = this.name;
  1546. this.socket.packet(packet);
  1547. this.flags = {};
  1548. return this;
  1549. };
  1550. /**
  1551. * Sends a message
  1552. *
  1553. * @api public
  1554. */
  1555. SocketNamespace.prototype.send = function (data, fn) {
  1556. var packet = {
  1557. type: this.flags.json ? 'json' : 'message'
  1558. , data: data
  1559. };
  1560. if ('function' == typeof fn) {
  1561. packet.id = ++this.ackPackets;
  1562. packet.ack = fn.length ? 'data' : true;
  1563. this.acks[packet.id] = fn;
  1564. }
  1565. return this.packet(packet);
  1566. };
  1567. /**
  1568. * Emits an event
  1569. *
  1570. * @api public
  1571. */
  1572. SocketNamespace.prototype.emit = function (name) {
  1573. var args = Array.prototype.slice.call(arguments, 1)
  1574. , lastArg = args[args.length - 1]
  1575. , packet = {
  1576. type: 'event'
  1577. , name: name
  1578. };
  1579. if ('function' == typeof lastArg) {
  1580. packet.id = ++this.ackPackets;
  1581. packet.ack = lastArg.length ? 'data' : true;
  1582. this.acks[packet.id] = lastArg;
  1583. args = args.slice(0, args.length - 1);
  1584. }
  1585. packet.args = args;
  1586. return this.packet(packet);
  1587. };
  1588. /**
  1589. * Disconnects the namespace
  1590. *
  1591. * @api private
  1592. */
  1593. SocketNamespace.prototype.disconnect = function () {
  1594. if (this.name === '') {
  1595. this.socket.disconnect();
  1596. } else {
  1597. this.packet({ type: 'disconnect' });
  1598. this.$emit('disconnect');
  1599. }
  1600. return this;
  1601. };
  1602. /**
  1603. * Handles a packet
  1604. *
  1605. * @api private
  1606. */
  1607. SocketNamespace.prototype.onPacket = function (packet) {
  1608. var self = this;
  1609. function ack () {
  1610. self.packet({
  1611. type: 'ack'
  1612. , args: io.util.toArray(arguments)
  1613. , ackId: packet.id
  1614. });
  1615. };
  1616. switch (packet.type) {
  1617. case 'connect':
  1618. this.$emit('connect');
  1619. break;
  1620. case 'disconnect':
  1621. if (this.name === '') {
  1622. this.socket.onDisconnect(packet.reason || 'booted');
  1623. } else {
  1624. this.$emit('disconnect', packet.reason);
  1625. }
  1626. break;
  1627. case 'message':
  1628. case 'json':
  1629. var params = ['message', packet.data];
  1630. if (packet.ack == 'data') {
  1631. params.push(ack);
  1632. } else if (packet.ack) {
  1633. this.packet({ type: 'ack', ackId: packet.id });
  1634. }
  1635. this.$emit.apply(this, params);
  1636. break;
  1637. case 'event':
  1638. var params = [packet.name].concat(packet.args);
  1639. if (packet.ack == 'data')
  1640. params.push(ack);
  1641. this.$emit.apply(this, params);
  1642. break;
  1643. case 'ack':
  1644. if (this.acks[packet.ackId]) {
  1645. this.acks[packet.ackId].apply(this, packet.args);
  1646. delete this.acks[packet.ackId];
  1647. }
  1648. break;
  1649. case 'error':
  1650. if (packet.advice){
  1651. this.socket.onError(packet);
  1652. } else {
  1653. this.$emit('error', packet.reason);
  1654. }
  1655. break;
  1656. }
  1657. };
  1658. /**
  1659. * Flag interface.
  1660. *
  1661. * @api private
  1662. */
  1663. function Flag (nsp, name) {
  1664. this.namespace = nsp;
  1665. this.name = name;
  1666. };
  1667. /**
  1668. * Send a message
  1669. *
  1670. * @api public
  1671. */
  1672. Flag.prototype.send = function () {
  1673. this.namespace.flags[this.name] = true;
  1674. this.namespace.send.apply(this.namespace, arguments);
  1675. };
  1676. /**
  1677. * Emit an event
  1678. *
  1679. * @api public
  1680. */
  1681. Flag.prototype.emit = function () {
  1682. this.namespace.flags[this.name] = true;
  1683. this.namespace.emit.apply(this.namespace, arguments);
  1684. };
  1685. })(
  1686. 'undefined' != typeof io ? io : module.exports
  1687. , 'undefined' != typeof io ? io : module.parent.exports
  1688. );
  1689. /**
  1690. * socket.io
  1691. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1692. * MIT Licensed
  1693. */
  1694. (function (exports, io) {
  1695. /**
  1696. * Expose constructor.
  1697. */
  1698. exports.websocket = WS;
  1699. /**
  1700. * The WebSocket transport uses the HTML5 WebSocket API to establish an persistent
  1701. * connection with the Socket.IO server. This transport will also be inherited by the
  1702. * FlashSocket fallback as it provides a API compatible polyfill for the WebSockets.
  1703. *
  1704. * @constructor
  1705. * @augments {io.Transport}
  1706. * @api public
  1707. */
  1708. function WS (socket) {
  1709. io.Transport.apply(this, arguments);
  1710. };
  1711. /**
  1712. * Inherits from Transport.
  1713. */
  1714. io.util.inherit(WS, io.Transport);
  1715. /**
  1716. * Transport name
  1717. *
  1718. * @api public
  1719. */
  1720. WS.prototype.name = 'websocket';
  1721. /**
  1722. * Initializes a new `WebSocket` connection with the Socket.IO server. We attach
  1723. * all the appropriate listeners to handle the responses from the server.
  1724. *
  1725. * @returns {Transport}
  1726. * @api public
  1727. */
  1728. WS.prototype.open = function(){
  1729. this.websocket = new WebSocket(this.prepareUrl());
  1730. var self = this;
  1731. this.websocket.onopen = function () {
  1732. self.onOpen();
  1733. self.socket.setBuffer(false);
  1734. };
  1735. this.websocket.onmessage = function (ev) {
  1736. self.onData(ev.data);
  1737. };
  1738. this.websocket.onclose = function () {
  1739. self.onClose();
  1740. self.socket.setBuffer(true);
  1741. };
  1742. this.websocket.onerror = function (e) {
  1743. self.onError(e);
  1744. };
  1745. return this;
  1746. };
  1747. /**
  1748. * Send a message to the Socket.IO server. The message will automatically be encoded
  1749. * in the correct message format.
  1750. *
  1751. * @returns {Transport}
  1752. * @api public
  1753. */
  1754. WS.prototype.send = function (data) {
  1755. this.websocket.send(data);
  1756. return this;
  1757. };
  1758. /**
  1759. * Payload
  1760. *
  1761. * @api private
  1762. */
  1763. WS.prototype.payload = function (arr) {
  1764. for (var i = 0, l = arr.length; i < l; i++) {
  1765. this.packet(arr[i]);
  1766. }
  1767. return this;
  1768. };
  1769. /**
  1770. * Disconnect the established `WebSocket` connection.
  1771. *
  1772. * @returns {Transport}
  1773. * @api public
  1774. */
  1775. WS.prototype.close = function(){
  1776. this.websocket.close();
  1777. return this;
  1778. };
  1779. /**
  1780. * Handle the errors that `WebSocket` might be giving when we
  1781. * are attempting to connect or send messages.
  1782. *
  1783. * @param {Error} e The error.
  1784. * @api private
  1785. */
  1786. WS.prototype.onError = function(e){
  1787. this.socket.onError(e);
  1788. };
  1789. /**
  1790. * Returns the appropriate scheme for the URI generation.
  1791. *
  1792. * @api private
  1793. */
  1794. WS.prototype.scheme = function(){
  1795. return (this.socket.options.secure ? 'wss' : 'ws');
  1796. };
  1797. /**
  1798. * Checks if the browser has support for native `WebSockets` and…

Large files files are truncated, but you can click here to view the full file