PageRenderTime 28ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/static/socket.io.js

https://bitbucket.org/nshetty/plotting-cpu-graph-in-near-real-time-with-gevent-socket.io
JavaScript | 3818 lines | 2872 code | 331 blank | 615 comment | 227 complexity | c0d95498ff96d63b2cbf520a5033d220 MD5 | raw file

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

  1. /*! Socket.IO.js build:0.9.6, 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.6';
  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) {
  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. // TODO: enable this when node 0.5 is stable
  457. //if (name === undefined) {
  458. //this.$events = {};
  459. //return this;
  460. //}
  461. if (this.$events && this.$events[name]) {
  462. this.$events[name] = null;
  463. }
  464. return this;
  465. };
  466. /**
  467. * Gets all listeners for a certain event.
  468. *
  469. * @api publci
  470. */
  471. EventEmitter.prototype.listeners = function (name) {
  472. if (!this.$events) {
  473. this.$events = {};
  474. }
  475. if (!this.$events[name]) {
  476. this.$events[name] = [];
  477. }
  478. if (!io.util.isArray(this.$events[name])) {
  479. this.$events[name] = [this.$events[name]];
  480. }
  481. return this.$events[name];
  482. };
  483. /**
  484. * Emits an event.
  485. *
  486. * @api public
  487. */
  488. EventEmitter.prototype.emit = function (name) {
  489. if (!this.$events) {
  490. return false;
  491. }
  492. var handler = this.$events[name];
  493. if (!handler) {
  494. return false;
  495. }
  496. var args = Array.prototype.slice.call(arguments, 1);
  497. if ('function' == typeof handler) {
  498. handler.apply(this, args);
  499. } else if (io.util.isArray(handler)) {
  500. var listeners = handler.slice();
  501. for (var i = 0, l = listeners.length; i < l; i++) {
  502. listeners[i].apply(this, args);
  503. }
  504. } else {
  505. return false;
  506. }
  507. return true;
  508. };
  509. })(
  510. 'undefined' != typeof io ? io : module.exports
  511. , 'undefined' != typeof io ? io : module.parent.exports
  512. );
  513. /**
  514. * socket.io
  515. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  516. * MIT Licensed
  517. */
  518. /**
  519. * Based on JSON2 (http://www.JSON.org/js.html).
  520. */
  521. (function (exports, nativeJSON) {
  522. "use strict";
  523. // use native JSON if it's available
  524. if (nativeJSON && nativeJSON.parse){
  525. return exports.JSON = {
  526. parse: nativeJSON.parse
  527. , stringify: nativeJSON.stringify
  528. }
  529. }
  530. var JSON = exports.JSON = {};
  531. function f(n) {
  532. // Format integers to have at least two digits.
  533. return n < 10 ? '0' + n : n;
  534. }
  535. function date(d, key) {
  536. return isFinite(d.valueOf()) ?
  537. d.getUTCFullYear() + '-' +
  538. f(d.getUTCMonth() + 1) + '-' +
  539. f(d.getUTCDate()) + 'T' +
  540. f(d.getUTCHours()) + ':' +
  541. f(d.getUTCMinutes()) + ':' +
  542. f(d.getUTCSeconds()) + 'Z' : null;
  543. };
  544. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  545. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  546. gap,
  547. indent,
  548. meta = { // table of character substitutions
  549. '\b': '\\b',
  550. '\t': '\\t',
  551. '\n': '\\n',
  552. '\f': '\\f',
  553. '\r': '\\r',
  554. '"' : '\\"',
  555. '\\': '\\\\'
  556. },
  557. rep;
  558. function quote(string) {
  559. // If the string contains no control characters, no quote characters, and no
  560. // backslash characters, then we can safely slap some quotes around it.
  561. // Otherwise we must also replace the offending characters with safe escape
  562. // sequences.
  563. escapable.lastIndex = 0;
  564. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  565. var c = meta[a];
  566. return typeof c === 'string' ? c :
  567. '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  568. }) + '"' : '"' + string + '"';
  569. }
  570. function str(key, holder) {
  571. // Produce a string from holder[key].
  572. var i, // The loop counter.
  573. k, // The member key.
  574. v, // The member value.
  575. length,
  576. mind = gap,
  577. partial,
  578. value = holder[key];
  579. // If the value has a toJSON method, call it to obtain a replacement value.
  580. if (value instanceof Date) {
  581. value = date(key);
  582. }
  583. // If we were called with a replacer function, then call the replacer to
  584. // obtain a replacement value.
  585. if (typeof rep === 'function') {
  586. value = rep.call(holder, key, value);
  587. }
  588. // What happens next depends on the value's type.
  589. switch (typeof value) {
  590. case 'string':
  591. return quote(value);
  592. case 'number':
  593. // JSON numbers must be finite. Encode non-finite numbers as null.
  594. return isFinite(value) ? String(value) : 'null';
  595. case 'boolean':
  596. case 'null':
  597. // If the value is a boolean or null, convert it to a string. Note:
  598. // typeof null does not produce 'null'. The case is included here in
  599. // the remote chance that this gets fixed someday.
  600. return String(value);
  601. // If the type is 'object', we might be dealing with an object or an array or
  602. // null.
  603. case 'object':
  604. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  605. // so watch out for that case.
  606. if (!value) {
  607. return 'null';
  608. }
  609. // Make an array to hold the partial results of stringifying this object value.
  610. gap += indent;
  611. partial = [];
  612. // Is the value an array?
  613. if (Object.prototype.toString.apply(value) === '[object Array]') {
  614. // The value is an array. Stringify every element. Use null as a placeholder
  615. // for non-JSON values.
  616. length = value.length;
  617. for (i = 0; i < length; i += 1) {
  618. partial[i] = str(i, value) || 'null';
  619. }
  620. // Join all of the elements together, separated with commas, and wrap them in
  621. // brackets.
  622. v = partial.length === 0 ? '[]' : gap ?
  623. '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
  624. '[' + partial.join(',') + ']';
  625. gap = mind;
  626. return v;
  627. }
  628. // If the replacer is an array, use it to select the members to be stringified.
  629. if (rep && typeof rep === 'object') {
  630. length = rep.length;
  631. for (i = 0; i < length; i += 1) {
  632. if (typeof rep[i] === 'string') {
  633. k = rep[i];
  634. v = str(k, value);
  635. if (v) {
  636. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  637. }
  638. }
  639. }
  640. } else {
  641. // Otherwise, iterate through all of the keys in the object.
  642. for (k in value) {
  643. if (Object.prototype.hasOwnProperty.call(value, k)) {
  644. v = str(k, value);
  645. if (v) {
  646. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  647. }
  648. }
  649. }
  650. }
  651. // Join all of the member texts together, separated with commas,
  652. // and wrap them in braces.
  653. v = partial.length === 0 ? '{}' : gap ?
  654. '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
  655. '{' + partial.join(',') + '}';
  656. gap = mind;
  657. return v;
  658. }
  659. }
  660. // If the JSON object does not yet have a stringify method, give it one.
  661. JSON.stringify = function (value, replacer, space) {
  662. // The stringify method takes a value and an optional replacer, and an optional
  663. // space parameter, and returns a JSON text. The replacer can be a function
  664. // that can replace values, or an array of strings that will select the keys.
  665. // A default replacer method can be provided. Use of the space parameter can
  666. // produce text that is more easily readable.
  667. var i;
  668. gap = '';
  669. indent = '';
  670. // If the space parameter is a number, make an indent string containing that
  671. // many spaces.
  672. if (typeof space === 'number') {
  673. for (i = 0; i < space; i += 1) {
  674. indent += ' ';
  675. }
  676. // If the space parameter is a string, it will be used as the indent string.
  677. } else if (typeof space === 'string') {
  678. indent = space;
  679. }
  680. // If there is a replacer, it must be a function or an array.
  681. // Otherwise, throw an error.
  682. rep = replacer;
  683. if (replacer && typeof replacer !== 'function' &&
  684. (typeof replacer !== 'object' ||
  685. typeof replacer.length !== 'number')) {
  686. throw new Error('JSON.stringify');
  687. }
  688. // Make a fake root object containing our value under the key of ''.
  689. // Return the result of stringifying the value.
  690. return str('', {'': value});
  691. };
  692. // If the JSON object does not yet have a parse method, give it one.
  693. JSON.parse = function (text, reviver) {
  694. // The parse method takes a text and an optional reviver function, and returns
  695. // a JavaScript value if the text is a valid JSON text.
  696. var j;
  697. function walk(holder, key) {
  698. // The walk method is used to recursively walk the resulting structure so
  699. // that modifications can be made.
  700. var k, v, value = holder[key];
  701. if (value && typeof value === 'object') {
  702. for (k in value) {
  703. if (Object.prototype.hasOwnProperty.call(value, k)) {
  704. v = walk(value, k);
  705. if (v !== undefined) {
  706. value[k] = v;
  707. } else {
  708. delete value[k];
  709. }
  710. }
  711. }
  712. }
  713. return reviver.call(holder, key, value);
  714. }
  715. // Parsing happens in four stages. In the first stage, we replace certain
  716. // Unicode characters with escape sequences. JavaScript handles many characters
  717. // incorrectly, either silently deleting them, or treating them as line endings.
  718. text = String(text);
  719. cx.lastIndex = 0;
  720. if (cx.test(text)) {
  721. text = text.replace(cx, function (a) {
  722. return '\\u' +
  723. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  724. });
  725. }
  726. // In the second stage, we run the text against regular expressions that look
  727. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  728. // because they can cause invocation, and '=' because it can cause mutation.
  729. // But just to be safe, we want to reject all unexpected forms.
  730. // We split the second stage into 4 regexp operations in order to work around
  731. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  732. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  733. // replace all simple value tokens with ']' characters. Third, we delete all
  734. // open brackets that follow a colon or comma or that begin the text. Finally,
  735. // we look to see that the remaining characters are only whitespace or ']' or
  736. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  737. if (/^[\],:{}\s]*$/
  738. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  739. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  740. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  741. // In the third stage we use the eval function to compile the text into a
  742. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  743. // in JavaScript: it can begin a block or an object literal. We wrap the text
  744. // in parens to eliminate the ambiguity.
  745. j = eval('(' + text + ')');
  746. // In the optional fourth stage, we recursively walk the new structure, passing
  747. // each name/value pair to a reviver function for possible transformation.
  748. return typeof reviver === 'function' ?
  749. walk({'': j}, '') : j;
  750. }
  751. // If the text is not JSON parseable, then a SyntaxError is thrown.
  752. throw new SyntaxError('JSON.parse');
  753. };
  754. })(
  755. 'undefined' != typeof io ? io : module.exports
  756. , typeof JSON !== 'undefined' ? JSON : undefined
  757. );
  758. /**
  759. * socket.io
  760. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  761. * MIT Licensed
  762. */
  763. (function (exports, io) {
  764. /**
  765. * Parser namespace.
  766. *
  767. * @namespace
  768. */
  769. var parser = exports.parser = {};
  770. /**
  771. * Packet types.
  772. */
  773. var packets = parser.packets = [
  774. 'disconnect'
  775. , 'connect'
  776. , 'heartbeat'
  777. , 'message'
  778. , 'json'
  779. , 'event'
  780. , 'ack'
  781. , 'error'
  782. , 'noop'
  783. ];
  784. /**
  785. * Errors reasons.
  786. */
  787. var reasons = parser.reasons = [
  788. 'transport not supported'
  789. , 'client not handshaken'
  790. , 'unauthorized'
  791. ];
  792. /**
  793. * Errors advice.
  794. */
  795. var advice = parser.advice = [
  796. 'reconnect'
  797. ];
  798. /**
  799. * Shortcuts.
  800. */
  801. var JSON = io.JSON
  802. , indexOf = io.util.indexOf;
  803. /**
  804. * Encodes a packet.
  805. *
  806. * @api private
  807. */
  808. parser.encodePacket = function (packet) {
  809. var type = indexOf(packets, packet.type)
  810. , id = packet.id || ''
  811. , endpoint = packet.endpoint || ''
  812. , ack = packet.ack
  813. , data = null;
  814. switch (packet.type) {
  815. case 'error':
  816. var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
  817. , adv = packet.advice ? indexOf(advice, packet.advice) : '';
  818. if (reason !== '' || adv !== '')
  819. data = reason + (adv !== '' ? ('+' + adv) : '');
  820. break;
  821. case 'message':
  822. if (packet.data !== '')
  823. data = packet.data;
  824. break;
  825. case 'event':
  826. var ev = { name: packet.name };
  827. if (packet.args && packet.args.length) {
  828. ev.args = packet.args;
  829. }
  830. data = JSON.stringify(ev);
  831. break;
  832. case 'json':
  833. data = JSON.stringify(packet.data);
  834. break;
  835. case 'connect':
  836. if (packet.qs)
  837. data = packet.qs;
  838. break;
  839. case 'ack':
  840. data = packet.ackId
  841. + (packet.args && packet.args.length
  842. ? '+' + JSON.stringify(packet.args) : '');
  843. break;
  844. }
  845. // construct packet with required fragments
  846. var encoded = [
  847. type
  848. , id + (ack == 'data' ? '+' : '')
  849. , endpoint
  850. ];
  851. // data fragment is optional
  852. if (data !== null && data !== undefined)
  853. encoded.push(data);
  854. return encoded.join(':');
  855. };
  856. /**
  857. * Encodes multiple messages (payload).
  858. *
  859. * @param {Array} messages
  860. * @api private
  861. */
  862. parser.encodePayload = function (packets) {
  863. var decoded = '';
  864. if (packets.length == 1)
  865. return packets[0];
  866. for (var i = 0, l = packets.length; i < l; i++) {
  867. var packet = packets[i];
  868. decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
  869. }
  870. return decoded;
  871. };
  872. /**
  873. * Decodes a packet
  874. *
  875. * @api private
  876. */
  877. var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
  878. parser.decodePacket = function (data) {
  879. var pieces = data.match(regexp);
  880. if (!pieces) return {};
  881. var id = pieces[2] || ''
  882. , data = pieces[5] || ''
  883. , packet = {
  884. type: packets[pieces[1]]
  885. , endpoint: pieces[4] || ''
  886. };
  887. // whether we need to acknowledge the packet
  888. if (id) {
  889. packet.id = id;
  890. if (pieces[3])
  891. packet.ack = 'data';
  892. else
  893. packet.ack = true;
  894. }
  895. // handle different packet types
  896. switch (packet.type) {
  897. case 'error':
  898. var pieces = data.split('+');
  899. packet.reason = reasons[pieces[0]] || '';
  900. packet.advice = advice[pieces[1]] || '';
  901. break;
  902. case 'message':
  903. packet.data = data || '';
  904. break;
  905. case 'event':
  906. try {
  907. var opts = JSON.parse(data);
  908. packet.name = opts.name;
  909. packet.args = opts.args;
  910. } catch (e) { }
  911. packet.args = packet.args || [];
  912. break;
  913. case 'json':
  914. try {
  915. packet.data = JSON.parse(data);
  916. } catch (e) { }
  917. break;
  918. case 'connect':
  919. packet.qs = data || '';
  920. break;
  921. case 'ack':
  922. var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
  923. if (pieces) {
  924. packet.ackId = pieces[1];
  925. packet.args = [];
  926. if (pieces[3]) {
  927. try {
  928. packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
  929. } catch (e) { }
  930. }
  931. }
  932. break;
  933. case 'disconnect':
  934. case 'heartbeat':
  935. break;
  936. };
  937. return packet;
  938. };
  939. /**
  940. * Decodes data payload. Detects multiple messages
  941. *
  942. * @return {Array} messages
  943. * @api public
  944. */
  945. parser.decodePayload = function (data) {
  946. // IE doesn't like data[i] for unicode chars, charAt works fine
  947. if (data.charAt(0) == '\ufffd') {
  948. var ret = [];
  949. for (var i = 1, length = ''; i < data.length; i++) {
  950. if (data.charAt(i) == '\ufffd') {
  951. ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
  952. i += Number(length) + 1;
  953. length = '';
  954. } else {
  955. length += data.charAt(i);
  956. }
  957. }
  958. return ret;
  959. } else {
  960. return [parser.decodePacket(data)];
  961. }
  962. };
  963. })(
  964. 'undefined' != typeof io ? io : module.exports
  965. , 'undefined' != typeof io ? io : module.parent.exports
  966. );
  967. /**
  968. * socket.io
  969. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  970. * MIT Licensed
  971. */
  972. (function (exports, io) {
  973. /**
  974. * Expose constructor.
  975. */
  976. exports.Transport = Transport;
  977. /**
  978. * This is the transport template for all supported transport methods.
  979. *
  980. * @constructor
  981. * @api public
  982. */
  983. function Transport (socket, sessid) {
  984. this.socket = socket;
  985. this.sessid = sessid;
  986. };
  987. /**
  988. * Apply EventEmitter mixin.
  989. */
  990. io.util.mixin(Transport, io.EventEmitter);
  991. /**
  992. * Handles the response from the server. When a new response is received
  993. * it will automatically update the timeout, decode the message and
  994. * forwards the response to the onMessage function for further processing.
  995. *
  996. * @param {String} data Response from the server.
  997. * @api private
  998. */
  999. Transport.prototype.onData = function (data) {
  1000. this.clearCloseTimeout();
  1001. // If the connection in currently open (or in a reopening state) reset the close
  1002. // timeout since we have just received data. This check is necessary so
  1003. // that we don't reset the timeout on an explicitly disconnected connection.
  1004. if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) {
  1005. this.setCloseTimeout();
  1006. }
  1007. if (data !== '') {
  1008. // todo: we should only do decodePayload for xhr transports
  1009. var msgs = io.parser.decodePayload(data);
  1010. if (msgs && msgs.length) {
  1011. for (var i = 0, l = msgs.length; i < l; i++) {
  1012. this.onPacket(msgs[i]);
  1013. }
  1014. }
  1015. }
  1016. return this;
  1017. };
  1018. /**
  1019. * Handles packets.
  1020. *
  1021. * @api private
  1022. */
  1023. Transport.prototype.onPacket = function (packet) {
  1024. this.socket.setHeartbeatTimeout();
  1025. if (packet.type == 'heartbeat') {
  1026. return this.onHeartbeat();
  1027. }
  1028. if (packet.type == 'connect' && packet.endpoint == '') {
  1029. this.onConnect();
  1030. }
  1031. if (packet.type == 'error' && packet.advice == 'reconnect') {
  1032. this.open = false;
  1033. }
  1034. this.socket.onPacket(packet);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets close timeout
  1039. *
  1040. * @api private
  1041. */
  1042. Transport.prototype.setCloseTimeout = function () {
  1043. if (!this.closeTimeout) {
  1044. var self = this;
  1045. this.closeTimeout = setTimeout(function () {
  1046. self.onDisconnect();
  1047. }, this.socket.closeTimeout);
  1048. }
  1049. };
  1050. /**
  1051. * Called when transport disconnects.
  1052. *
  1053. * @api private
  1054. */
  1055. Transport.prototype.onDisconnect = function () {
  1056. if (this.close && this.open) this.close();
  1057. this.clearTimeouts();
  1058. this.socket.onDisconnect();
  1059. return this;
  1060. };
  1061. /**
  1062. * Called when transport connects
  1063. *
  1064. * @api private
  1065. */
  1066. Transport.prototype.onConnect = function () {
  1067. this.socket.onConnect();
  1068. return this;
  1069. }
  1070. /**
  1071. * Clears close timeout
  1072. *
  1073. * @api private
  1074. */
  1075. Transport.prototype.clearCloseTimeout = function () {
  1076. if (this.closeTimeout) {
  1077. clearTimeout(this.closeTimeout);
  1078. this.closeTimeout = null;
  1079. }
  1080. };
  1081. /**
  1082. * Clear timeouts
  1083. *
  1084. * @api private
  1085. */
  1086. Transport.prototype.clearTimeouts = function () {
  1087. this.clearCloseTimeout();
  1088. if (this.reopenTimeout) {
  1089. clearTimeout(this.reopenTimeout);
  1090. }
  1091. };
  1092. /**
  1093. * Sends a packet
  1094. *
  1095. * @param {Object} packet object.
  1096. * @api private
  1097. */
  1098. Transport.prototype.packet = function (packet) {
  1099. this.send(io.parser.encodePacket(packet));
  1100. };
  1101. /**
  1102. * Send the received heartbeat message back to server. So the server
  1103. * knows we are still connected.
  1104. *
  1105. * @param {String} heartbeat Heartbeat response from the server.
  1106. * @api private
  1107. */
  1108. Transport.prototype.onHeartbeat = function (heartbeat) {
  1109. this.packet({ type: 'heartbeat' });
  1110. };
  1111. /**
  1112. * Called when the transport opens.
  1113. *
  1114. * @api private
  1115. */
  1116. Transport.prototype.onOpen = function () {
  1117. this.open = true;
  1118. this.clearCloseTimeout();
  1119. this.socket.onOpen();
  1120. };
  1121. /**
  1122. * Notifies the base when the connection with the Socket.IO server
  1123. * has been disconnected.
  1124. *
  1125. * @api private
  1126. */
  1127. Transport.prototype.onClose = function () {
  1128. var self = this;
  1129. /* FIXME: reopen delay causing a infinit loop
  1130. this.reopenTimeout = setTimeout(function () {
  1131. self.open();
  1132. }, this.socket.options['reopen delay']);*/
  1133. this.open = false;
  1134. this.socket.onClose();
  1135. this.onDisconnect();
  1136. };
  1137. /**
  1138. * Generates a connection url based on the Socket.IO URL Protocol.
  1139. * See <https://github.com/learnboost/socket.io-node/> for more details.
  1140. *
  1141. * @returns {String} Connection url
  1142. * @api private
  1143. */
  1144. Transport.prototype.prepareUrl = function () {
  1145. var options = this.socket.options;
  1146. return this.scheme() + '://'
  1147. + options.host + ':' + options.port + '/'
  1148. + options.resource + '/' + io.protocol
  1149. + '/' + this.name + '/' + this.sessid;
  1150. };
  1151. /**
  1152. * Checks if the transport is ready to start a connection.
  1153. *
  1154. * @param {Socket} socket The socket instance that needs a transport
  1155. * @param {Function} fn The callback
  1156. * @api private
  1157. */
  1158. Transport.prototype.ready = function (socket, fn) {
  1159. fn.call(this);
  1160. };
  1161. })(
  1162. 'undefined' != typeof io ? io : module.exports
  1163. , 'undefined' != typeof io ? io : module.parent.exports
  1164. );
  1165. /**
  1166. * socket.io
  1167. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1168. * MIT Licensed
  1169. */
  1170. (function (exports, io, global) {
  1171. /**
  1172. * Expose constructor.
  1173. */
  1174. exports.Socket = Socket;
  1175. /**
  1176. * Create a new `Socket.IO client` which can establish a persistent
  1177. * connection with a Socket.IO enabled server.
  1178. *
  1179. * @api public
  1180. */
  1181. function Socket (options) {
  1182. this.options = {
  1183. port: 80
  1184. , secure: false
  1185. , document: 'document' in global ? document : false
  1186. , resource: 'socket.io'
  1187. , transports: io.transports
  1188. , 'connect timeout': 10000
  1189. , 'try multiple transports': true
  1190. , 'reconnect': true
  1191. , 'reconnection delay': 500
  1192. , 'reconnection limit': Infinity
  1193. , 'reopen delay': 3000
  1194. , 'max reconnection attempts': 10
  1195. , 'sync disconnect on unload': true
  1196. , 'auto connect': true
  1197. , 'flash policy port': 10843
  1198. };
  1199. io.util.merge(this.options, options);
  1200. this.connected = false;
  1201. this.open = false;
  1202. this.connecting = false;
  1203. this.reconnecting = false;
  1204. this.namespaces = {};
  1205. this.buffer = [];
  1206. this.doBuffer = false;
  1207. if (this.options['sync disconnect on unload'] &&
  1208. (!this.isXDomain() || io.util.ua.hasCORS)) {
  1209. var self = this;
  1210. io.util.on(global, 'unload', function () {
  1211. self.disconnectSync();
  1212. }, false);
  1213. }
  1214. if (this.options['auto connect']) {
  1215. this.connect();
  1216. }
  1217. };
  1218. /**
  1219. * Apply EventEmitter mixin.
  1220. */
  1221. io.util.mixin(Socket, io.EventEmitter);
  1222. /**
  1223. * Returns a namespace listener/emitter for this socket
  1224. *
  1225. * @api public
  1226. */
  1227. Socket.prototype.of = function (name) {
  1228. if (!this.namespaces[name]) {
  1229. this.namespaces[name] = new io.SocketNamespace(this, name);
  1230. if (name !== '') {
  1231. this.namespaces[name].packet({ type: 'connect' });
  1232. }
  1233. }
  1234. return this.namespaces[name];
  1235. };
  1236. /**
  1237. * Emits the given event to the Socket and all namespaces
  1238. *
  1239. * @api private
  1240. */
  1241. Socket.prototype.publish = function () {
  1242. this.emit.apply(this, arguments);
  1243. var nsp;
  1244. for (var i in this.namespaces) {
  1245. if (this.namespaces.hasOwnProperty(i)) {
  1246. nsp = this.of(i);
  1247. nsp.$emit.apply(nsp, arguments);
  1248. }
  1249. }
  1250. };
  1251. /**
  1252. * Performs the handshake
  1253. *
  1254. * @api private
  1255. */
  1256. function empty () { };
  1257. Socket.prototype.handshake = function (fn) {
  1258. var self = this
  1259. , options = this.options;
  1260. function complete (data) {
  1261. if (data instanceof Error) {
  1262. self.connecting = false;
  1263. self.onError(data.message);
  1264. } else {
  1265. fn.apply(null, data.split(':'));
  1266. }
  1267. };
  1268. var url = [
  1269. 'http' + (options.secure ? 's' : '') + ':/'
  1270. , options.host + ':' + options.port
  1271. , options.resource
  1272. , io.protocol
  1273. , io.util.query(this.options.query, 't=' + +new Date)
  1274. ].join('/');
  1275. if (this.isXDomain() && !io.util.ua.hasCORS) {
  1276. var insertAt = document.getElementsByTagName('script')[0]
  1277. , script = document.createElement('script');
  1278. script.src = url + '&jsonp=' + io.j.length;
  1279. insertAt.parentNode.insertBefore(script, insertAt);
  1280. io.j.push(function (data) {
  1281. complete(data);
  1282. script.parentNode.removeChild(script);
  1283. });
  1284. } else {
  1285. var xhr = io.util.request();
  1286. xhr.open('GET', url, true);
  1287. xhr.withCredentials = true;
  1288. xhr.onreadystatechange = function () {
  1289. if (xhr.readyState == 4) {
  1290. xhr.onreadystatechange = empty;
  1291. if (xhr.status == 200) {
  1292. complete(xhr.responseText);
  1293. } else {
  1294. self.connecting = false;
  1295. !self.reconnecting && self.onError(xhr.responseText);
  1296. }
  1297. }
  1298. };
  1299. xhr.send(null);
  1300. }
  1301. };
  1302. /**
  1303. * Find an available transport based on the options supplied in the constructor.
  1304. *
  1305. * @api private
  1306. */
  1307. Socket.prototype.getTransport = function (override) {
  1308. var transports = override || this.transports, match;
  1309. for (var i = 0, transport; transport = transports[i]; i++) {
  1310. if (io.Transport[transport]
  1311. && io.Transport[transport].check(this)
  1312. && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
  1313. return new io.Transport[transport](this, this.sessionid);
  1314. }
  1315. }
  1316. return null;
  1317. };
  1318. /**
  1319. * Connects to the server.
  1320. *
  1321. * @param {Function} [fn] Callback.
  1322. * @returns {io.Socket}
  1323. * @api public
  1324. */
  1325. Socket.prototype.connect = function (fn) {
  1326. if (this.connecting) {
  1327. return this;
  1328. }
  1329. var self = this;
  1330. self.connecting = true;
  1331. this.handshake(function (sid, heartbeat, close, transports) {
  1332. self.sessionid = sid;
  1333. self.closeTimeout = close * 1000;
  1334. self.heartbeatTimeout = heartbeat * 1000;
  1335. self.transports = transports ? io.util.intersect(
  1336. transports.split(',')
  1337. , self.options.transports
  1338. ) : self.options.transports;
  1339. self.setHeartbeatTimeout();
  1340. function connect (transports){
  1341. if (self.transport) self.transport.clearTimeouts();
  1342. self.transport = self.getTransport(transports);
  1343. if (!self.transport) return self.publish('connect_failed');
  1344. // once the transport is ready
  1345. self.transport.ready(self, function () {
  1346. self.connecting = true;
  1347. self.publish('connecting', self.transport.name);
  1348. self.transport.open();
  1349. if (self.options['connect timeout']) {
  1350. self.connectTimeoutTimer = setTimeout(function () {
  1351. if (!self.connected) {
  1352. self.connecting = false;
  1353. if (self.options['try multiple transports']) {
  1354. if (!self.remainingTransports) {
  1355. self.remainingTransports = self.transports.slice(0);
  1356. }
  1357. var remaining = self.remainingTransports;
  1358. while (remaining.length > 0 && remaining.splice(0,1)[0] !=
  1359. self.transport.name) {}
  1360. if (remaining.length){
  1361. connect(remaining);
  1362. } else {
  1363. self.publish('connect_failed');
  1364. }
  1365. }
  1366. }
  1367. }, self.options['connect timeout']);
  1368. }
  1369. });
  1370. }
  1371. connect(self.transports);
  1372. self.once('connect', function (){
  1373. clearTimeout(self.connectTimeoutTimer);
  1374. fn && typeof fn == 'function' && fn();
  1375. });
  1376. });
  1377. return this;
  1378. };
  1379. /**
  1380. * Clears and sets a new heartbeat timeout using the value given by the
  1381. * server during the handshake.
  1382. *
  1383. * @api private
  1384. */
  1385. Socket.prototype.setHeartbeatTimeout = function () {
  1386. clearTimeout(this.heartbeatTimeoutTimer);
  1387. var self = this;
  1388. this.heartbeatTimeoutTimer = setTimeout(function () {
  1389. self.transport.onClose();
  1390. }, this.heartbeatTimeout);
  1391. };
  1392. /**
  1393. * Sends a message.
  1394. *
  1395. * @param {Object} data packet.
  1396. * @returns {io.Socket}
  1397. * @api public
  1398. */
  1399. Socket.prototype.packet = function (data) {
  1400. if (this.connected && !this.doBuffer) {
  1401. this.transport.packet(data);
  1402. } else {
  1403. this.buffer.push(data);
  1404. }
  1405. return this;
  1406. };
  1407. /**
  1408. * Sets buffer state
  1409. *
  1410. * @api private
  1411. */
  1412. Socket.prototype.setBuffer = function (v) {
  1413. this.doBuffer = v;
  1414. if (!v && this.connected && this.buffer.length) {
  1415. this.transport.payload(this.buffer);
  1416. this.buffer = [];
  1417. }
  1418. };
  1419. /**
  1420. * Disconnect the established connect.
  1421. *
  1422. * @returns {io.Socket}
  1423. * @api public
  1424. */
  1425. Socket.prototype.disconnect = function () {
  1426. if (this.connected || this.connecting) {
  1427. if (this.open) {
  1428. this.of('').packet({ type: 'disconnect' });
  1429. }
  1430. // handle disconnection immediately
  1431. this.onDisconnect('booted');
  1432. }
  1433. return this;
  1434. };
  1435. /**
  1436. * Disconnects the socket with a sync XHR.
  1437. *
  1438. * @api private
  1439. */
  1440. Socket.prototype.disconnectSync = function () {
  1441. // ensure disconnection
  1442. var xhr = io.util.request()
  1443. , uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
  1444. xhr.open('GET', uri, true);
  1445. // handle disconnection immediately
  1446. this.onDisconnect('booted');
  1447. };
  1448. /**
  1449. * Check if we need to use cross domain enabled transports. Cross domain would
  1450. * be a different port or different domain name.
  1451. *
  1452. * @returns {Boolean}
  1453. * @api private
  1454. */
  1455. Socket.prototype.isXDomain = function () {
  1456. var port = global.location.port ||
  1457. ('https:' == global.location.protocol ? 443 : 80);
  1458. return this.options.host !== global.location.hostname
  1459. || this.options.port != port;
  1460. };
  1461. /**
  1462. * Called upon handshake.
  1463. *
  1464. * @api private
  1465. */
  1466. Socket.prototype.onConnect = function () {
  1467. if (!this.connected) {
  1468. this.connected = true;
  1469. this.connecting = false;
  1470. if (!this.doBuffer) {
  1471. // make sure to flush the buffer
  1472. this.setBuffer(false);
  1473. }
  1474. this.emit('connect');
  1475. }
  1476. };
  1477. /**
  1478. * Called when the transport opens
  1479. *
  1480. * @api private
  1481. */
  1482. Socket.prototype.onOpen = function () {
  1483. this.open = true;
  1484. };
  1485. /**
  1486. * Called when the transport closes.
  1487. *
  1488. * @api private
  1489. */
  1490. Socket.prototype.onClose = function () {
  1491. this.open = false;
  1492. clearTimeout(this.heartbeatTimeoutTimer);
  1493. };
  1494. /**
  1495. * Called when the transport first opens a connection
  1496. *
  1497. * @param text
  1498. */
  1499. Socket.prototype.onPacket = function (packet) {
  1500. this.of(packet.endpoint).onPacket(packet);
  1501. };
  1502. /**
  1503. * Handles an error.
  1504. *
  1505. * @api private
  1506. */
  1507. Socket.prototype.onError = function (err) {
  1508. if (err && err.advice) {
  1509. if (err.advice === 'reconnect' && (this.connected || this.connecting)) {
  1510. this.disconnect();
  1511. if (this.options.reconnect) {
  1512. this.reconnect();
  1513. }
  1514. }
  1515. }
  1516. this.publish('error', err && err.reason ? err.reason : err);
  1517. };
  1518. /**
  1519. * Called when the transport disconnects.
  1520. *
  1521. * @api private
  1522. */
  1523. Socket.prototype.onDisconnect = function (reason) {
  1524. var wasConnected = this.connected
  1525. , wasConnecting = this.connecting;
  1526. this.connected = false;
  1527. this.connecting = false;
  1528. this.open = false;
  1529. if (wasConnected || wasConnecting) {
  1530. this.transport.close();
  1531. this.transport.clearTimeouts();
  1532. if (wasConnected) {
  1533. this.publish('disconnect', reason);
  1534. if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
  1535. this.reconnect();
  1536. }
  1537. }
  1538. }
  1539. };
  1540. /**
  1541. * Called upon reconnection.
  1542. *
  1543. * @api private
  1544. */
  1545. Socket.prototype.reconnect = function () {
  1546. this.reconnecting = true;
  1547. this.reconnectionAttempts = 0;
  1548. this.reconnectionDelay = this.options['reconnection delay'];
  1549. var self = this
  1550. , maxAttempts = this.options['max reconnection attempts']
  1551. , tryMultiple = this.options['try multiple transports']
  1552. , limit = this.options['reconnection limit'];
  1553. function reset () {
  1554. if (self.connected) {
  1555. for (var i in self.namespaces) {
  1556. if (self.namespaces.hasOwnProperty(i) && '' !== i) {
  1557. self.namespaces[i].packet({ type: 'connect' });
  1558. }
  1559. }
  1560. self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
  1561. }
  1562. clearTimeout(self.reconnectionTimer);
  1563. self.removeListener('connect_failed', maybeReconnect);
  1564. self.removeListener('connect', maybeReconnect);
  1565. self.reconnecting = false;
  1566. delete self.reconnectionAttempts;
  1567. delete self.reconnectionDelay;
  1568. delete self.reconnectionTimer;
  1569. delete self.redoTransports;
  1570. self.options['try multiple transports'] = tryMultiple;
  1571. };
  1572. function maybeReconnect () {
  1573. if (!self.reconnecting) {
  1574. return;
  1575. }
  1576. if (self.connected) {
  1577. return reset();
  1578. };
  1579. if (self.connecting && self.reconnecting) {
  1580. return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
  1581. }
  1582. if (self.reconnectionAttempts++ >= maxAttempts) {
  1583. if (!self.redoTransports) {
  1584. self.on('connect_failed', maybeReconnect);
  1585. self.options['try multiple transports'] = true;
  1586. self.transport = self.getTransport();
  1587. self.redoTransports = true;
  1588. self.connect();
  1589. } else {
  1590. self.publish('reconnect_failed');
  1591. reset();
  1592. }
  1593. } else {
  1594. if (self.reconnectionDelay < limit) {
  1595. self.reconnectionDelay *= 2; // exponential back off
  1596. }
  1597. self.connect();
  1598. self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
  1599. self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
  1600. }
  1601. };
  1602. this.options['try multiple transports'] = false;
  1603. this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
  1604. this.on('connect', maybeReconnect);
  1605. };
  1606. })(
  1607. 'undefined' != typeof io ? io : module.exports
  1608. , 'undefined' != typeof io ? io : module.parent.exports
  1609. , this
  1610. );
  1611. /**
  1612. * socket.io
  1613. * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
  1614. * MIT Licensed
  1615. */
  1616. (function (exports, io) {
  1617. /**
  1618. * Expose constructor.
  1619. */
  1620. exports.SocketNamespace = SocketNamespace;
  1621. /**
  1622. * Socket namespace constructor.
  1623. *
  1624. * @constructor
  1625. * @api public
  1626. */
  1627. function SocketNamespace (socket, name) {
  1628. this.socket = socket;
  1629. this.name = name || '';
  1630. this.flags = {};
  1631. this.json = new Flag(this, 'json');
  1632. this.ackPackets = 0;
  1633. this.acks = {};
  1634. };
  1635. /**
  1636. * Apply EventEmitter mixin.
  1637. */
  1638. io.util.mixin(SocketNamespace, io.EventEmitter);
  1639. /**
  1640. * Copies emit since we override it
  1641. *
  1642. * @api private
  1643. */
  1644. SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
  1645. /**
  1646. * Creates a new namespace, by proxying the request to the socket. This
  1647. * allows us to use the synax as we do on the server.
  1648. *
  1649. * @api public
  1650. */
  1651. SocketNamespace.prototype.of = function () {
  1652. return this.socket.of.apply(this.socket, arguments);
  1653. };
  1654. /**
  1655. * Sends a packet.
  1656. *
  1657. * @api private
  1658. */
  1659. SocketNamespace.prototype.packet = function (packet) {
  1660. packet.endpoint = this.name;
  1661. this.socket.packet(packet);
  1662. this.flags = {};
  1663. return this;
  1664. };
  1665. /**
  1666. * Sends a message
  1667. *
  1668. * @api public
  1669. */
  1670. SocketNamespace.prototype.send = function (data, fn) {
  1671. var packet = {
  1672. type: this.flags.json ? 'json' : 'message'
  1673. , data: data
  1674. };
  1675. if ('function' == typeof fn) {
  1676. packet.id = ++this.ackPackets;
  1677. packet.ack = true;
  1678. this.acks[packet.id] = fn;
  1679. }
  1680. return this.packet(packet);
  1681. };
  1682. /**
  1683. * Emits an event
  1684. *
  1685. * @api public
  1686. */
  1687. SocketNamespace.prototype.emit = function (name) {
  1688. var args = Array.prototype.slice.call(arguments, 1)
  1689. , lastArg = args[args.length - 1]
  1690. , packet = {
  1691. type: 'event'
  1692. , name: name
  1693. };
  1694. if ('function' == typeof lastArg) {
  1695. packet.id = ++this.ackPackets;
  1696. packet.ack = 'data';
  1697. this.acks[packet.id] = lastArg;
  1698. args = args.slice(0, args.length - 1);
  1699. }
  1700. packet.args = args;
  1701. return this.packet(packet);
  1702. };
  1703. /**
  1704. * Disconnects the namespace
  1705. *
  1706. * @api private
  1707. */
  1708. SocketNamespace.prototype.disconnect = function () {
  1709. if (this.name === '') {
  1710. this.socket.disconnect();
  1711. } else {
  1712. this.packet({ type: 'disconnect' });
  1713. this.$emit('disconnect');
  1714. }
  1715. return this;
  1716. };
  1717. /**
  1718. * Handles a packet
  1719. *
  1720. * @api private
  1721. */
  1722. SocketNamespace.prototype.onPacket = function (packet) {
  1723. var self = this;
  1724. function ack () {
  1725. self.packet({
  1726. type: 'ack'
  1727. , args: io.util.toArray(arguments)
  1728. , ackId: packet.id
  1729. });
  1730. };
  1731. switch (packet.type) {
  1732. case 'connect':
  1733. this.$emit('connect');
  1734. break;
  1735. case 'disconnect':
  1736. if (this.name === '') {
  1737. this.socket.onDisconnect(packet.reason || 'booted');
  1738. } else {
  1739. this.$emit('disconnect', packet.reason);
  1740. }
  1741. break;
  1742. case 'message':
  1743. case 'json':
  1744. var params = ['message', packet.data];

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