3 * (c) 2014-2021 Guillermo Rauch
4 * Released under the MIT License.
6 (function webpackUniversalModuleDefinition(root, factory) {
7 if(typeof exports === 'object' && typeof module === 'object')
8 module.exports = factory();
9 else if(typeof define === 'function' && define.amd)
11 else if(typeof exports === 'object')
12 exports["io"] = factory();
14 root["io"] = factory();
16 return /******/ (function(modules) { // webpackBootstrap
17 /******/ // The module cache
18 /******/ var installedModules = {};
20 /******/ // The require function
21 /******/ function __webpack_require__(moduleId) {
23 /******/ // Check if module is in cache
24 /******/ if(installedModules[moduleId])
25 /******/ return installedModules[moduleId].exports;
27 /******/ // Create a new module (and put it into the cache)
28 /******/ var module = installedModules[moduleId] = {
30 /******/ id: moduleId,
31 /******/ loaded: false
34 /******/ // Execute the module function
35 /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
37 /******/ // Flag the module as loaded
38 /******/ module.loaded = true;
40 /******/ // Return the exports of the module
41 /******/ return module.exports;
45 /******/ // expose the modules object (__webpack_modules__)
46 /******/ __webpack_require__.m = modules;
48 /******/ // expose the module cache
49 /******/ __webpack_require__.c = installedModules;
51 /******/ // __webpack_public_path__
52 /******/ __webpack_require__.p = "";
54 /******/ // Load entry module and return exports
55 /******/ return __webpack_require__(0);
57 /************************************************************************/
60 /***/ (function(module, exports, __webpack_require__) {
64 * Module dependencies.
67 var url = __webpack_require__(1);
68 var parser = __webpack_require__(7);
69 var Manager = __webpack_require__(12);
70 var debug = __webpack_require__(3)('socket.io-client');
76 module.exports = exports = lookup;
82 var cache = exports.managers = {};
85 * Looks up an existing `Manager` for multiplexing.
86 * If the user summons:
88 * `io('http://localhost/a');`
89 * `io('http://localhost/b');`
91 * We reuse the existing instance based on same scheme/port/host,
92 * and we initialize sockets for each namespace.
97 function lookup (uri, opts) {
98 if (typeof uri === 'object') {
105 var parsed = url(uri);
106 var source = parsed.source;
108 var path = parsed.path;
109 var sameNamespace = cache[id] && path in cache[id].nsps;
110 var newConnection = opts.forceNew || opts['force new connection'] ||
111 false === opts.multiplex || sameNamespace;
116 debug('ignoring socket cache for %s', source);
117 io = Manager(source, opts);
120 debug('new io instance for %s', source);
121 cache[id] = Manager(source, opts);
125 if (parsed.query && !opts.query) {
126 opts.query = parsed.query;
128 return io.socket(parsed.path, opts);
137 exports.protocol = parser.protocol;
142 * @param {String} uri
146 exports.connect = lookup;
149 * Expose constructors for standalone build.
154 exports.Manager = __webpack_require__(12);
155 exports.Socket = __webpack_require__(37);
160 /***/ (function(module, exports, __webpack_require__) {
164 * Module dependencies.
167 var parseuri = __webpack_require__(2);
168 var debug = __webpack_require__(3)('socket.io-client:url');
174 module.exports = url;
179 * @param {String} url
180 * @param {Object} An object meant to mimic window.location.
181 * Defaults to window.location.
185 function url (uri, loc) {
188 // default to window.location
189 loc = loc || (typeof location !== 'undefined' && location);
190 if (null == uri) uri = loc.protocol + '//' + loc.host;
192 // relative path support
193 if ('string' === typeof uri) {
194 if ('/' === uri.charAt(0)) {
195 if ('/' === uri.charAt(1)) {
196 uri = loc.protocol + uri;
198 uri = loc.host + uri;
202 if (!/^(https?|wss?):\/\//.test(uri)) {
203 debug('protocol-less url %s', uri);
204 if ('undefined' !== typeof loc) {
205 uri = loc.protocol + '//' + uri;
207 uri = 'https://' + uri;
212 debug('parse %s', uri);
216 // make sure we treat `localhost:80` and `localhost` equally
218 if (/^(http|ws)$/.test(obj.protocol)) {
220 } else if (/^(http|ws)s$/.test(obj.protocol)) {
225 obj.path = obj.path || '/';
227 var ipv6 = obj.host.indexOf(':') !== -1;
228 var host = ipv6 ? '[' + obj.host + ']' : obj.host;
231 obj.id = obj.protocol + '://' + host + ':' + obj.port;
233 obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
241 /***/ (function(module, exports) {
246 * @author Steven Levithan <stevenlevithan.com> (MIT license)
250 var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
253 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
256 module.exports = function parseuri(str) {
258 b = str.indexOf('['),
259 e = str.indexOf(']');
261 if (b != -1 && e != -1) {
262 str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
265 var m = re.exec(str || ''),
270 uri[parts[i]] = m[i] || '';
273 if (b != -1 && e != -1) {
275 uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
276 uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
280 uri.pathNames = pathNames(uri, uri['path']);
281 uri.queryKey = queryKey(uri, uri['query']);
286 function pathNames(obj, path) {
287 var regx = /\/{2,9}/g,
288 names = path.replace(regx, "/").split("/");
290 if (path.substr(0, 1) == '/' || path.length === 0) {
293 if (path.substr(path.length - 1, 1) == '/') {
294 names.splice(names.length - 1, 1);
300 function queryKey(uri, query) {
303 query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
315 /***/ (function(module, exports, __webpack_require__) {
317 /* WEBPACK VAR INJECTION */(function(process) {'use strict';
319 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
322 * This is the web browser implementation of `debug()`.
324 * Expose `debug()` as the module.
327 exports = module.exports = __webpack_require__(5);
329 exports.formatArgs = formatArgs;
332 exports.useColors = useColors;
333 exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
339 exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
342 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
343 * and the Firebug extension (any Firefox version) are known
344 * to support "%c" CSS customizations.
346 * TODO: add a `localStorage` variable to explicitly enable/disable colors
349 function useColors() {
350 // NB: In an Electron preload script, document will be defined but not fully
351 // initialized. Since we know we're in Chrome, we'll just detect this case
353 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
357 // Internet Explorer and Edge do not support colors.
358 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
362 // is webkit? http://stackoverflow.com/a/16459606/376773
363 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
364 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
365 // is firebug? http://stackoverflow.com/a/398120/376773
366 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
367 // is firefox >= v31?
368 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
369 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
370 // double check webkit in userAgent just in case we are in a worker
371 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
375 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
378 exports.formatters.j = function (v) {
380 return JSON.stringify(v);
382 return '[UnexpectedJSONParseError]: ' + err.message;
387 * Colorize log arguments if enabled.
392 function formatArgs(args) {
393 var useColors = this.useColors;
395 args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
397 if (!useColors) return;
399 var c = 'color: ' + this.color;
400 args.splice(1, 0, c, 'color: inherit');
402 // the final "%c" is somewhat tricky, because there could be other
403 // arguments passed either before or after the %c, so we need to
404 // figure out the correct index to insert the CSS into
407 args[0].replace(/%[a-zA-Z%]/g, function (match) {
408 if ('%%' === match) return;
410 if ('%c' === match) {
411 // we only are interested in the *last* %c
412 // (the user may have provided their own)
417 args.splice(lastC, 0, c);
421 * Invokes `console.log()` when available.
422 * No-op when `console.log` is not a "function".
428 // this hackery is required for IE8/9, where
429 // the `console.log` function doesn't have 'apply'
430 return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
436 * @param {String} namespaces
440 function save(namespaces) {
442 if (null == namespaces) {
443 exports.storage.removeItem('debug');
445 exports.storage.debug = namespaces;
453 * @return {String} returns the previously persisted debug modes
460 r = exports.storage.debug;
463 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
464 if (!r && typeof process !== 'undefined' && 'env' in process) {
465 r = process.env.DEBUG;
472 * Enable namespaces listed in `localStorage.debug` initially.
475 exports.enable(load());
478 * Localstorage attempts to return the localstorage.
480 * This is necessary because safari throws
481 * when a user disables cookies/localstorage
482 * and you attempt to access it.
484 * @return {LocalStorage}
488 function localstorage() {
490 return window.localStorage;
493 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
497 /***/ (function(module, exports) {
499 // shim for using process in browser
500 var process = module.exports = {};
502 // cached from whatever global is present so that test runners that stub it
503 // don't break things. But we need to wrap it in a try catch in case it is
504 // wrapped in strict mode code which doesn't define any globals. It's inside a
505 // function because try/catches deoptimize in certain engines.
507 var cachedSetTimeout;
508 var cachedClearTimeout;
510 function defaultSetTimout() {
511 throw new Error('setTimeout has not been defined');
513 function defaultClearTimeout () {
514 throw new Error('clearTimeout has not been defined');
518 if (typeof setTimeout === 'function') {
519 cachedSetTimeout = setTimeout;
521 cachedSetTimeout = defaultSetTimout;
524 cachedSetTimeout = defaultSetTimout;
527 if (typeof clearTimeout === 'function') {
528 cachedClearTimeout = clearTimeout;
530 cachedClearTimeout = defaultClearTimeout;
533 cachedClearTimeout = defaultClearTimeout;
536 function runTimeout(fun) {
537 if (cachedSetTimeout === setTimeout) {
538 //normal enviroments in sane situations
539 return setTimeout(fun, 0);
541 // if setTimeout wasn't available but was latter defined
542 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
543 cachedSetTimeout = setTimeout;
544 return setTimeout(fun, 0);
547 // when when somebody has screwed with setTimeout but no I.E. maddness
548 return cachedSetTimeout(fun, 0);
551 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
552 return cachedSetTimeout.call(null, fun, 0);
554 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
555 return cachedSetTimeout.call(this, fun, 0);
561 function runClearTimeout(marker) {
562 if (cachedClearTimeout === clearTimeout) {
563 //normal enviroments in sane situations
564 return clearTimeout(marker);
566 // if clearTimeout wasn't available but was latter defined
567 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
568 cachedClearTimeout = clearTimeout;
569 return clearTimeout(marker);
572 // when when somebody has screwed with setTimeout but no I.E. maddness
573 return cachedClearTimeout(marker);
576 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
577 return cachedClearTimeout.call(null, marker);
579 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
580 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
581 return cachedClearTimeout.call(this, marker);
589 var draining = false;
593 function cleanUpNextTick() {
594 if (!draining || !currentQueue) {
598 if (currentQueue.length) {
599 queue = currentQueue.concat(queue);
608 function drainQueue() {
612 var timeout = runTimeout(cleanUpNextTick);
615 var len = queue.length;
617 currentQueue = queue;
619 while (++queueIndex < len) {
621 currentQueue[queueIndex].run();
629 runClearTimeout(timeout);
632 process.nextTick = function (fun) {
633 var args = new Array(arguments.length - 1);
634 if (arguments.length > 1) {
635 for (var i = 1; i < arguments.length; i++) {
636 args[i - 1] = arguments[i];
639 queue.push(new Item(fun, args));
640 if (queue.length === 1 && !draining) {
641 runTimeout(drainQueue);
645 // v8 likes predictible objects
646 function Item(fun, array) {
650 Item.prototype.run = function () {
651 this.fun.apply(null, this.array);
653 process.title = 'browser';
654 process.browser = true;
657 process.version = ''; // empty string to avoid regexp issues
658 process.versions = {};
663 process.addListener = noop;
666 process.removeListener = noop;
667 process.removeAllListeners = noop;
669 process.prependListener = noop;
670 process.prependOnceListener = noop;
672 process.listeners = function (name) { return [] }
674 process.binding = function (name) {
675 throw new Error('process.binding is not supported');
678 process.cwd = function () { return '/' };
679 process.chdir = function (dir) {
680 throw new Error('process.chdir is not supported');
682 process.umask = function() { return 0; };
687 /***/ (function(module, exports, __webpack_require__) {
692 * This is the common logic for both the Node.js and web browser
693 * implementations of `debug()`.
695 * Expose `debug()` as the module.
698 exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
699 exports.coerce = coerce;
700 exports.disable = disable;
701 exports.enable = enable;
702 exports.enabled = enabled;
703 exports.humanize = __webpack_require__(6);
706 * Active `debug` instances.
708 exports.instances = [];
711 * The currently active debug mode names, and names to skip.
718 * Map of special "%n" handling functions, for the debug "format" argument.
720 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
723 exports.formatters = {};
727 * @param {String} namespace
732 function selectColor(namespace) {
736 for (i in namespace) {
737 hash = (hash << 5) - hash + namespace.charCodeAt(i);
738 hash |= 0; // Convert to 32bit integer
741 return exports.colors[Math.abs(hash) % exports.colors.length];
745 * Create a debugger with the given `namespace`.
747 * @param {String} namespace
752 function createDebug(namespace) {
758 if (!debug.enabled) return;
762 // set `diff` timestamp
763 var curr = +new Date();
764 var ms = curr - (prevTime || curr);
766 self.prev = prevTime;
770 // turn the `arguments` into a proper Array
771 var args = new Array(arguments.length);
772 for (var i = 0; i < args.length; i++) {
773 args[i] = arguments[i];
776 args[0] = exports.coerce(args[0]);
778 if ('string' !== typeof args[0]) {
779 // anything else let's inspect with %O
783 // apply any `formatters` transformations
785 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
786 // if we encounter an escaped % then don't increase the array index
787 if (match === '%%') return match;
789 var formatter = exports.formatters[format];
790 if ('function' === typeof formatter) {
791 var val = args[index];
792 match = formatter.call(self, val);
794 // now we need to remove `args[index]` since it's inlined in the `format`
795 args.splice(index, 1);
801 // apply env-specific formatting (colors, etc.)
802 exports.formatArgs.call(self, args);
804 var logFn = debug.log || exports.log || console.log.bind(console);
805 logFn.apply(self, args);
808 debug.namespace = namespace;
809 debug.enabled = exports.enabled(namespace);
810 debug.useColors = exports.useColors();
811 debug.color = selectColor(namespace);
812 debug.destroy = destroy;
814 // env-specific initialization logic for debug instances
815 if ('function' === typeof exports.init) {
819 exports.instances.push(debug);
825 var index = exports.instances.indexOf(this);
827 exports.instances.splice(index, 1);
835 * Enables a debug mode by namespaces. This can include modes
836 * separated by a colon and wildcards.
838 * @param {String} namespaces
842 function enable(namespaces) {
843 exports.save(namespaces);
849 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
850 var len = split.length;
852 for (i = 0; i < len; i++) {
853 if (!split[i]) continue; // ignore empty strings
854 namespaces = split[i].replace(/\*/g, '.*?');
855 if (namespaces[0] === '-') {
856 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
858 exports.names.push(new RegExp('^' + namespaces + '$'));
862 for (i = 0; i < exports.instances.length; i++) {
863 var instance = exports.instances[i];
864 instance.enabled = exports.enabled(instance.namespace);
869 * Disable debug output.
879 * Returns true if the given mode name is enabled, false otherwise.
881 * @param {String} name
886 function enabled(name) {
887 if (name[name.length - 1] === '*') {
891 for (i = 0, len = exports.skips.length; i < len; i++) {
892 if (exports.skips[i].test(name)) {
896 for (i = 0, len = exports.names.length; i < len; i++) {
897 if (exports.names[i].test(name)) {
912 function coerce(val) {
913 if (val instanceof Error) return val.stack || val.message;
919 /***/ (function(module, exports) {
932 * Parse or format the given `val`.
936 * - `long` verbose formatting [false]
938 * @param {String|Number} val
939 * @param {Object} [options]
940 * @throws {Error} throw an error if val is not a non-empty string or a number
941 * @return {String|Number}
945 module.exports = function(val, options) {
946 options = options || {};
947 var type = typeof val;
948 if (type === 'string' && val.length > 0) {
950 } else if (type === 'number' && isNaN(val) === false) {
951 return options.long ? fmtLong(val) : fmtShort(val);
954 'val is not a non-empty string or a valid number. val=' +
960 * Parse the given `str` and return milliseconds.
962 * @param {String} str
967 function parse(str) {
969 if (str.length > 100) {
972 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
978 var n = parseFloat(match[1]);
979 var type = (match[2] || 'ms').toLowerCase();
1009 case 'milliseconds':
1021 * Short format for `ms`.
1023 * @param {Number} ms
1028 function fmtShort(ms) {
1030 return Math.round(ms / d) + 'd';
1033 return Math.round(ms / h) + 'h';
1036 return Math.round(ms / m) + 'm';
1039 return Math.round(ms / s) + 's';
1045 * Long format for `ms`.
1047 * @param {Number} ms
1052 function fmtLong(ms) {
1053 return plural(ms, d, 'day') ||
1054 plural(ms, h, 'hour') ||
1055 plural(ms, m, 'minute') ||
1056 plural(ms, s, 'second') ||
1061 * Pluralization helper.
1064 function plural(ms, n, name) {
1069 return Math.floor(ms / n) + ' ' + name;
1071 return Math.ceil(ms / n) + ' ' + name + 's';
1077 /***/ (function(module, exports, __webpack_require__) {
1081 * Module dependencies.
1084 var debug = __webpack_require__(3)('socket.io-parser');
1085 var Emitter = __webpack_require__(8);
1086 var binary = __webpack_require__(9);
1087 var isArray = __webpack_require__(10);
1088 var isBuf = __webpack_require__(11);
1096 exports.protocol = 4;
1115 * Packet type `connect`.
1120 exports.CONNECT = 0;
1123 * Packet type `disconnect`.
1128 exports.DISCONNECT = 1;
1131 * Packet type `event`.
1139 * Packet type `ack`.
1147 * Packet type `error`.
1155 * Packet type 'binary event'
1160 exports.BINARY_EVENT = 5;
1163 * Packet type `binary ack`. For acks with binary arguments.
1168 exports.BINARY_ACK = 6;
1171 * Encoder constructor.
1176 exports.Encoder = Encoder;
1179 * Decoder constructor.
1184 exports.Decoder = Decoder;
1187 * A socket.io Encoder instance
1192 function Encoder() {}
1194 var ERROR_PACKET = exports.ERROR + '"encode error"';
1197 * Encode a packet as a single string if non-binary, or as a
1198 * buffer sequence, depending on packet type.
1200 * @param {Object} obj - packet object
1201 * @param {Function} callback - function to handle encodings (likely engine.write)
1202 * @return Calls callback with Array of encodings
1206 Encoder.prototype.encode = function(obj, callback){
1207 debug('encoding packet %j', obj);
1209 if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
1210 encodeAsBinary(obj, callback);
1212 var encoding = encodeAsString(obj);
1213 callback([encoding]);
1218 * Encode packet as string.
1220 * @param {Object} packet
1221 * @return {String} encoded
1225 function encodeAsString(obj) {
1228 var str = '' + obj.type;
1230 // attachments if we have them
1231 if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
1232 str += obj.attachments + '-';
1235 // if we have a namespace other than `/`
1236 // we append it followed by a comma `,`
1237 if (obj.nsp && '/' !== obj.nsp) {
1238 str += obj.nsp + ',';
1241 // immediately followed by the id
1242 if (null != obj.id) {
1247 if (null != obj.data) {
1248 var payload = tryStringify(obj.data);
1249 if (payload !== false) {
1252 return ERROR_PACKET;
1256 debug('encoded %j as %s', obj, str);
1260 function tryStringify(str) {
1262 return JSON.stringify(str);
1269 * Encode packet as 'buffer sequence' by removing blobs, and
1270 * deconstructing packet into object with placeholders and
1271 * a list of buffers.
1273 * @param {Object} packet
1274 * @return {Buffer} encoded
1278 function encodeAsBinary(obj, callback) {
1280 function writeEncoding(bloblessData) {
1281 var deconstruction = binary.deconstructPacket(bloblessData);
1282 var pack = encodeAsString(deconstruction.packet);
1283 var buffers = deconstruction.buffers;
1285 buffers.unshift(pack); // add packet info to beginning of data list
1286 callback(buffers); // write all the buffers
1289 binary.removeBlobs(obj, writeEncoding);
1293 * A socket.io Decoder instance
1295 * @return {Object} decoder
1299 function Decoder() {
1300 this.reconstructor = null;
1304 * Mix in `Emitter` with Decoder.
1307 Emitter(Decoder.prototype);
1310 * Decodes an encoded packet string into packet JSON.
1312 * @param {String} obj - encoded packet
1313 * @return {Object} packet
1317 Decoder.prototype.add = function(obj) {
1319 if (typeof obj === 'string') {
1320 packet = decodeString(obj);
1321 if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
1322 this.reconstructor = new BinaryReconstructor(packet);
1324 // no attachments, labeled binary but no binary data to follow
1325 if (this.reconstructor.reconPack.attachments === 0) {
1326 this.emit('decoded', packet);
1328 } else { // non-binary full packet
1329 this.emit('decoded', packet);
1331 } else if (isBuf(obj) || obj.base64) { // raw binary data
1332 if (!this.reconstructor) {
1333 throw new Error('got binary data when not reconstructing a packet');
1335 packet = this.reconstructor.takeBinaryData(obj);
1336 if (packet) { // received final buffer
1337 this.reconstructor = null;
1338 this.emit('decoded', packet);
1342 throw new Error('Unknown type: ' + obj);
1347 * Decode a packet String (JSON data)
1349 * @param {String} str
1350 * @return {Object} packet
1354 function decodeString(str) {
1358 type: Number(str.charAt(0))
1361 if (null == exports.types[p.type]) {
1362 return error('unknown packet type ' + p.type);
1365 // look up attachments if type binary
1366 if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
1368 while (str.charAt(++i) !== '-') {
1369 buf += str.charAt(i);
1370 if (i == str.length) break;
1372 if (buf != Number(buf) || str.charAt(i) !== '-') {
1373 throw new Error('Illegal attachments');
1375 p.attachments = Number(buf);
1378 // look up namespace (if any)
1379 if ('/' === str.charAt(i + 1)) {
1382 var c = str.charAt(i);
1383 if (',' === c) break;
1385 if (i === str.length) break;
1392 var next = str.charAt(i + 1);
1393 if ('' !== next && Number(next) == next) {
1396 var c = str.charAt(i);
1397 if (null == c || Number(c) != c) {
1401 p.id += str.charAt(i);
1402 if (i === str.length) break;
1404 p.id = Number(p.id);
1407 // look up json data
1408 if (str.charAt(++i)) {
1409 var payload = tryParse(str.substr(i));
1410 var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
1411 if (isPayloadValid) {
1414 return error('invalid payload');
1418 debug('decoded %s as %j', str, p);
1422 function tryParse(str) {
1424 return JSON.parse(str);
1431 * Deallocates a parser's resources
1436 Decoder.prototype.destroy = function() {
1437 if (this.reconstructor) {
1438 this.reconstructor.finishedReconstruction();
1443 * A manager of a binary event's 'buffer sequence'. Should
1444 * be constructed whenever a packet of type BINARY_EVENT is
1447 * @param {Object} packet
1448 * @return {BinaryReconstructor} initialized reconstructor
1452 function BinaryReconstructor(packet) {
1453 this.reconPack = packet;
1458 * Method to be called when binary data received from connection
1459 * after a BINARY_EVENT packet.
1461 * @param {Buffer | ArrayBuffer} binData - the raw binary data received
1462 * @return {null | Object} returns null if more binary data is expected or
1463 * a reconstructed packet object if all buffers have been received.
1467 BinaryReconstructor.prototype.takeBinaryData = function(binData) {
1468 this.buffers.push(binData);
1469 if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
1470 var packet = binary.reconstructPacket(this.reconPack, this.buffers);
1471 this.finishedReconstruction();
1478 * Cleans up binary packet reconstruction variables.
1483 BinaryReconstructor.prototype.finishedReconstruction = function() {
1484 this.reconPack = null;
1488 function error(msg) {
1490 type: exports.ERROR,
1491 data: 'parser error: ' + msg
1498 /***/ (function(module, exports, __webpack_require__) {
1506 module.exports = Emitter;
1510 * Initialize a new `Emitter`.
1515 function Emitter(obj) {
1516 if (obj) return mixin(obj);
1520 * Mixin the emitter properties.
1522 * @param {Object} obj
1527 function mixin(obj) {
1528 for (var key in Emitter.prototype) {
1529 obj[key] = Emitter.prototype[key];
1535 * Listen on the given `event` with `fn`.
1537 * @param {String} event
1538 * @param {Function} fn
1543 Emitter.prototype.on =
1544 Emitter.prototype.addEventListener = function(event, fn){
1545 this._callbacks = this._callbacks || {};
1546 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
1552 * Adds an `event` listener that will be invoked a single
1553 * time then automatically removed.
1555 * @param {String} event
1556 * @param {Function} fn
1561 Emitter.prototype.once = function(event, fn){
1563 this.off(event, on);
1564 fn.apply(this, arguments);
1573 * Remove the given callback for `event` or all
1574 * registered callbacks.
1576 * @param {String} event
1577 * @param {Function} fn
1582 Emitter.prototype.off =
1583 Emitter.prototype.removeListener =
1584 Emitter.prototype.removeAllListeners =
1585 Emitter.prototype.removeEventListener = function(event, fn){
1586 this._callbacks = this._callbacks || {};
1589 if (0 == arguments.length) {
1590 this._callbacks = {};
1595 var callbacks = this._callbacks['$' + event];
1596 if (!callbacks) return this;
1598 // remove all handlers
1599 if (1 == arguments.length) {
1600 delete this._callbacks['$' + event];
1604 // remove specific handler
1606 for (var i = 0; i < callbacks.length; i++) {
1608 if (cb === fn || cb.fn === fn) {
1609 callbacks.splice(i, 1);
1614 // Remove event specific arrays for event types that no
1615 // one is subscribed for to avoid memory leak.
1616 if (callbacks.length === 0) {
1617 delete this._callbacks['$' + event];
1624 * Emit `event` with the given args.
1626 * @param {String} event
1627 * @param {Mixed} ...
1631 Emitter.prototype.emit = function(event){
1632 this._callbacks = this._callbacks || {};
1634 var args = new Array(arguments.length - 1)
1635 , callbacks = this._callbacks['$' + event];
1637 for (var i = 1; i < arguments.length; i++) {
1638 args[i - 1] = arguments[i];
1642 callbacks = callbacks.slice(0);
1643 for (var i = 0, len = callbacks.length; i < len; ++i) {
1644 callbacks[i].apply(this, args);
1652 * Return array of callbacks for `event`.
1654 * @param {String} event
1659 Emitter.prototype.listeners = function(event){
1660 this._callbacks = this._callbacks || {};
1661 return this._callbacks['$' + event] || [];
1665 * Check if this emitter has `event` handlers.
1667 * @param {String} event
1672 Emitter.prototype.hasListeners = function(event){
1673 return !! this.listeners(event).length;
1679 /***/ (function(module, exports, __webpack_require__) {
1681 /*global Blob,File*/
1684 * Module requirements
1687 var isArray = __webpack_require__(10);
1688 var isBuf = __webpack_require__(11);
1689 var toString = Object.prototype.toString;
1690 var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
1691 var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
1694 * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
1695 * Anything with blobs or files should be fed through removeBlobs before coming
1698 * @param {Object} packet - socket.io event packet
1699 * @return {Object} with deconstructed packet and list of buffers
1703 exports.deconstructPacket = function(packet) {
1705 var packetData = packet.data;
1707 pack.data = _deconstructPacket(packetData, buffers);
1708 pack.attachments = buffers.length; // number of binary 'attachments'
1709 return {packet: pack, buffers: buffers};
1712 function _deconstructPacket(data, buffers) {
1713 if (!data) return data;
1716 var placeholder = { _placeholder: true, num: buffers.length };
1719 } else if (isArray(data)) {
1720 var newData = new Array(data.length);
1721 for (var i = 0; i < data.length; i++) {
1722 newData[i] = _deconstructPacket(data[i], buffers);
1725 } else if (typeof data === 'object' && !(data instanceof Date)) {
1727 for (var key in data) {
1728 newData[key] = _deconstructPacket(data[key], buffers);
1736 * Reconstructs a binary packet from its placeholder packet and buffers
1738 * @param {Object} packet - event packet with placeholders
1739 * @param {Array} buffers - binary buffers to put in placeholder positions
1740 * @return {Object} reconstructed packet
1744 exports.reconstructPacket = function(packet, buffers) {
1745 packet.data = _reconstructPacket(packet.data, buffers);
1746 packet.attachments = undefined; // no longer useful
1750 function _reconstructPacket(data, buffers) {
1751 if (!data) return data;
1753 if (data && data._placeholder) {
1754 return buffers[data.num]; // appropriate buffer (should be natural order anyway)
1755 } else if (isArray(data)) {
1756 for (var i = 0; i < data.length; i++) {
1757 data[i] = _reconstructPacket(data[i], buffers);
1759 } else if (typeof data === 'object') {
1760 for (var key in data) {
1761 data[key] = _reconstructPacket(data[key], buffers);
1769 * Asynchronously removes Blobs or Files from data via
1770 * FileReader's readAsArrayBuffer method. Used before encoding
1771 * data as msgpack. Calls callback with the blobless data.
1773 * @param {Object} data
1774 * @param {Function} callback
1778 exports.removeBlobs = function(data, callback) {
1779 function _removeBlobs(obj, curKey, containingObject) {
1780 if (!obj) return obj;
1783 if ((withNativeBlob && obj instanceof Blob) ||
1784 (withNativeFile && obj instanceof File)) {
1788 var fileReader = new FileReader();
1789 fileReader.onload = function() { // this.result == arraybuffer
1790 if (containingObject) {
1791 containingObject[curKey] = this.result;
1794 bloblessData = this.result;
1797 // if nothing pending its callback time
1798 if(! --pendingBlobs) {
1799 callback(bloblessData);
1803 fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
1804 } else if (isArray(obj)) { // handle array
1805 for (var i = 0; i < obj.length; i++) {
1806 _removeBlobs(obj[i], i, obj);
1808 } else if (typeof obj === 'object' && !isBuf(obj)) { // and object
1809 for (var key in obj) {
1810 _removeBlobs(obj[key], key, obj);
1815 var pendingBlobs = 0;
1816 var bloblessData = data;
1817 _removeBlobs(bloblessData);
1818 if (!pendingBlobs) {
1819 callback(bloblessData);
1826 /***/ (function(module, exports) {
1828 var toString = {}.toString;
1830 module.exports = Array.isArray || function (arr) {
1831 return toString.call(arr) == '[object Array]';
1837 /***/ (function(module, exports) {
1840 module.exports = isBuf;
1842 var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
1843 var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
1845 var isView = function (obj) {
1846 return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
1850 * Returns true if obj is a buffer or an arraybuffer.
1855 function isBuf(obj) {
1856 return (withNativeBuffer && Buffer.isBuffer(obj)) ||
1857 (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
1863 /***/ (function(module, exports, __webpack_require__) {
1867 * Module dependencies.
1870 var eio = __webpack_require__(13);
1871 var Socket = __webpack_require__(37);
1872 var Emitter = __webpack_require__(8);
1873 var parser = __webpack_require__(7);
1874 var on = __webpack_require__(39);
1875 var bind = __webpack_require__(40);
1876 var debug = __webpack_require__(3)('socket.io-client:manager');
1877 var indexOf = __webpack_require__(36);
1878 var Backoff = __webpack_require__(41);
1881 * IE6+ hasOwnProperty
1884 var has = Object.prototype.hasOwnProperty;
1890 module.exports = Manager;
1893 * `Manager` constructor.
1895 * @param {String} engine instance or engine uri/opts
1896 * @param {Object} options
1900 function Manager (uri, opts) {
1901 if (!(this instanceof Manager)) return new Manager(uri, opts);
1902 if (uri && ('object' === typeof uri)) {
1908 opts.path = opts.path || '/socket.io';
1912 this.reconnection(opts.reconnection !== false);
1913 this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
1914 this.reconnectionDelay(opts.reconnectionDelay || 1000);
1915 this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
1916 this.randomizationFactor(opts.randomizationFactor || 0.5);
1917 this.backoff = new Backoff({
1918 min: this.reconnectionDelay(),
1919 max: this.reconnectionDelayMax(),
1920 jitter: this.randomizationFactor()
1922 this.timeout(null == opts.timeout ? 20000 : opts.timeout);
1923 this.readyState = 'closed';
1925 this.connecting = [];
1926 this.lastPing = null;
1927 this.encoding = false;
1928 this.packetBuffer = [];
1929 var _parser = opts.parser || parser;
1930 this.encoder = new _parser.Encoder();
1931 this.decoder = new _parser.Decoder();
1932 this.autoConnect = opts.autoConnect !== false;
1933 if (this.autoConnect) this.open();
1937 * Propagate given event to sockets and emit on `this`
1942 Manager.prototype.emitAll = function () {
1943 this.emit.apply(this, arguments);
1944 for (var nsp in this.nsps) {
1945 if (has.call(this.nsps, nsp)) {
1946 this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
1952 * Update `socket.id` of all sockets
1957 Manager.prototype.updateSocketIds = function () {
1958 for (var nsp in this.nsps) {
1959 if (has.call(this.nsps, nsp)) {
1960 this.nsps[nsp].id = this.generateId(nsp);
1966 * generate `socket.id` for the given `nsp`
1968 * @param {String} nsp
1973 Manager.prototype.generateId = function (nsp) {
1974 return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id;
1981 Emitter(Manager.prototype);
1984 * Sets the `reconnection` config.
1986 * @param {Boolean} true/false if it should automatically reconnect
1987 * @return {Manager} self or value
1991 Manager.prototype.reconnection = function (v) {
1992 if (!arguments.length) return this._reconnection;
1993 this._reconnection = !!v;
1998 * Sets the reconnection attempts config.
2000 * @param {Number} max reconnection attempts before giving up
2001 * @return {Manager} self or value
2005 Manager.prototype.reconnectionAttempts = function (v) {
2006 if (!arguments.length) return this._reconnectionAttempts;
2007 this._reconnectionAttempts = v;
2012 * Sets the delay between reconnections.
2014 * @param {Number} delay
2015 * @return {Manager} self or value
2019 Manager.prototype.reconnectionDelay = function (v) {
2020 if (!arguments.length) return this._reconnectionDelay;
2021 this._reconnectionDelay = v;
2022 this.backoff && this.backoff.setMin(v);
2026 Manager.prototype.randomizationFactor = function (v) {
2027 if (!arguments.length) return this._randomizationFactor;
2028 this._randomizationFactor = v;
2029 this.backoff && this.backoff.setJitter(v);
2034 * Sets the maximum delay between reconnections.
2036 * @param {Number} delay
2037 * @return {Manager} self or value
2041 Manager.prototype.reconnectionDelayMax = function (v) {
2042 if (!arguments.length) return this._reconnectionDelayMax;
2043 this._reconnectionDelayMax = v;
2044 this.backoff && this.backoff.setMax(v);
2049 * Sets the connection timeout. `false` to disable
2051 * @return {Manager} self or value
2055 Manager.prototype.timeout = function (v) {
2056 if (!arguments.length) return this._timeout;
2062 * Starts trying to reconnect if reconnection is enabled and we have not
2063 * started reconnecting yet
2068 Manager.prototype.maybeReconnectOnOpen = function () {
2069 // Only try to reconnect if it's the first time we're connecting
2070 if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
2071 // keeps reconnection from firing twice for the same reconnection loop
2077 * Sets the current transport `socket`.
2079 * @param {Function} optional, callback
2080 * @return {Manager} self
2084 Manager.prototype.open =
2085 Manager.prototype.connect = function (fn, opts) {
2086 debug('readyState %s', this.readyState);
2087 if (~this.readyState.indexOf('open')) return this;
2089 debug('opening %s', this.uri);
2090 this.engine = eio(this.uri, this.opts);
2091 var socket = this.engine;
2093 this.readyState = 'opening';
2094 this.skipReconnect = false;
2097 var openSub = on(socket, 'open', function () {
2102 // emit `connect_error`
2103 var errorSub = on(socket, 'error', function (data) {
2104 debug('connect_error');
2106 self.readyState = 'closed';
2107 self.emitAll('connect_error', data);
2109 var err = new Error('Connection error');
2113 // Only do this if there is no fn to handle the error
2114 self.maybeReconnectOnOpen();
2118 // emit `connect_timeout`
2119 if (false !== this._timeout) {
2120 var timeout = this._timeout;
2121 debug('connect attempt will timeout after %d', timeout);
2123 if (timeout === 0) {
2124 openSub.destroy(); // prevents a race condition with the 'open' event
2128 var timer = setTimeout(function () {
2129 debug('connect attempt timed out after %d', timeout);
2132 socket.emit('error', 'timeout');
2133 self.emitAll('connect_timeout', timeout);
2137 destroy: function () {
2138 clearTimeout(timer);
2143 this.subs.push(openSub);
2144 this.subs.push(errorSub);
2150 * Called upon transport open.
2155 Manager.prototype.onopen = function () {
2162 this.readyState = 'open';
2166 var socket = this.engine;
2167 this.subs.push(on(socket, 'data', bind(this, 'ondata')));
2168 this.subs.push(on(socket, 'ping', bind(this, 'onping')));
2169 this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
2170 this.subs.push(on(socket, 'error', bind(this, 'onerror')));
2171 this.subs.push(on(socket, 'close', bind(this, 'onclose')));
2172 this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
2176 * Called upon a ping.
2181 Manager.prototype.onping = function () {
2182 this.lastPing = new Date();
2183 this.emitAll('ping');
2187 * Called upon a packet.
2192 Manager.prototype.onpong = function () {
2193 this.emitAll('pong', new Date() - this.lastPing);
2202 Manager.prototype.ondata = function (data) {
2203 this.decoder.add(data);
2207 * Called when parser fully decodes a packet.
2212 Manager.prototype.ondecoded = function (packet) {
2213 this.emit('packet', packet);
2217 * Called upon socket error.
2222 Manager.prototype.onerror = function (err) {
2223 debug('error', err);
2224 this.emitAll('error', err);
2228 * Creates a new socket for the given `nsp`.
2234 Manager.prototype.socket = function (nsp, opts) {
2235 var socket = this.nsps[nsp];
2237 socket = new Socket(this, nsp, opts);
2238 this.nsps[nsp] = socket;
2240 socket.on('connecting', onConnecting);
2241 socket.on('connect', function () {
2242 socket.id = self.generateId(nsp);
2245 if (this.autoConnect) {
2246 // manually call here since connecting event is fired before listening
2251 function onConnecting () {
2252 if (!~indexOf(self.connecting, socket)) {
2253 self.connecting.push(socket);
2261 * Called upon a socket close.
2263 * @param {Socket} socket
2266 Manager.prototype.destroy = function (socket) {
2267 var index = indexOf(this.connecting, socket);
2268 if (~index) this.connecting.splice(index, 1);
2269 if (this.connecting.length) return;
2277 * @param {Object} packet
2281 Manager.prototype.packet = function (packet) {
2282 debug('writing packet %j', packet);
2284 if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
2286 if (!self.encoding) {
2287 // encode, then write to engine with result
2288 self.encoding = true;
2289 this.encoder.encode(packet, function (encodedPackets) {
2290 for (var i = 0; i < encodedPackets.length; i++) {
2291 self.engine.write(encodedPackets[i], packet.options);
2293 self.encoding = false;
2294 self.processPacketQueue();
2296 } else { // add packet to the queue
2297 self.packetBuffer.push(packet);
2302 * If packet buffer is non-empty, begins encoding the
2303 * next packet in line.
2308 Manager.prototype.processPacketQueue = function () {
2309 if (this.packetBuffer.length > 0 && !this.encoding) {
2310 var pack = this.packetBuffer.shift();
2316 * Clean up transport subscriptions and packet buffer.
2321 Manager.prototype.cleanup = function () {
2324 var subsLength = this.subs.length;
2325 for (var i = 0; i < subsLength; i++) {
2326 var sub = this.subs.shift();
2330 this.packetBuffer = [];
2331 this.encoding = false;
2332 this.lastPing = null;
2334 this.decoder.destroy();
2338 * Close the current socket.
2343 Manager.prototype.close =
2344 Manager.prototype.disconnect = function () {
2345 debug('disconnect');
2346 this.skipReconnect = true;
2347 this.reconnecting = false;
2348 if ('opening' === this.readyState) {
2349 // `onclose` will not fire because
2350 // an open event never happened
2353 this.backoff.reset();
2354 this.readyState = 'closed';
2355 if (this.engine) this.engine.close();
2359 * Called upon engine close.
2364 Manager.prototype.onclose = function (reason) {
2368 this.backoff.reset();
2369 this.readyState = 'closed';
2370 this.emit('close', reason);
2372 if (this._reconnection && !this.skipReconnect) {
2378 * Attempt a reconnection.
2383 Manager.prototype.reconnect = function () {
2384 if (this.reconnecting || this.skipReconnect) return this;
2388 if (this.backoff.attempts >= this._reconnectionAttempts) {
2389 debug('reconnect failed');
2390 this.backoff.reset();
2391 this.emitAll('reconnect_failed');
2392 this.reconnecting = false;
2394 var delay = this.backoff.duration();
2395 debug('will wait %dms before reconnect attempt', delay);
2397 this.reconnecting = true;
2398 var timer = setTimeout(function () {
2399 if (self.skipReconnect) return;
2401 debug('attempting reconnect');
2402 self.emitAll('reconnect_attempt', self.backoff.attempts);
2403 self.emitAll('reconnecting', self.backoff.attempts);
2405 // check again for the case socket closed in above events
2406 if (self.skipReconnect) return;
2408 self.open(function (err) {
2410 debug('reconnect attempt error');
2411 self.reconnecting = false;
2413 self.emitAll('reconnect_error', err.data);
2415 debug('reconnect success');
2422 destroy: function () {
2423 clearTimeout(timer);
2430 * Called upon successful reconnect.
2435 Manager.prototype.onreconnect = function () {
2436 var attempt = this.backoff.attempts;
2437 this.reconnecting = false;
2438 this.backoff.reset();
2439 this.updateSocketIds();
2440 this.emitAll('reconnect', attempt);
2446 /***/ (function(module, exports, __webpack_require__) {
2449 module.exports = __webpack_require__(14);
2457 module.exports.parser = __webpack_require__(22);
2462 /***/ (function(module, exports, __webpack_require__) {
2465 * Module dependencies.
2468 var transports = __webpack_require__(15);
2469 var Emitter = __webpack_require__(8);
2470 var debug = __webpack_require__(3)('engine.io-client:socket');
2471 var index = __webpack_require__(36);
2472 var parser = __webpack_require__(22);
2473 var parseuri = __webpack_require__(2);
2474 var parseqs = __webpack_require__(30);
2480 module.exports = Socket;
2483 * Socket constructor.
2485 * @param {String|Object} uri or options
2486 * @param {Object} options
2490 function Socket (uri, opts) {
2491 if (!(this instanceof Socket)) return new Socket(uri, opts);
2495 if (uri && 'object' === typeof uri) {
2501 uri = parseuri(uri);
2502 opts.hostname = uri.host;
2503 opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
2504 opts.port = uri.port;
2505 if (uri.query) opts.query = uri.query;
2506 } else if (opts.host) {
2507 opts.hostname = parseuri(opts.host).host;
2510 this.secure = null != opts.secure ? opts.secure
2511 : (typeof location !== 'undefined' && 'https:' === location.protocol);
2513 if (opts.hostname && !opts.port) {
2514 // if no port is specified manually, use the protocol default
2515 opts.port = this.secure ? '443' : '80';
2518 this.agent = opts.agent || false;
2519 this.hostname = opts.hostname ||
2520 (typeof location !== 'undefined' ? location.hostname : 'localhost');
2521 this.port = opts.port || (typeof location !== 'undefined' && location.port
2523 : (this.secure ? 443 : 80));
2524 this.query = opts.query || {};
2525 if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
2526 this.upgrade = false !== opts.upgrade;
2527 this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
2528 this.forceJSONP = !!opts.forceJSONP;
2529 this.jsonp = false !== opts.jsonp;
2530 this.forceBase64 = !!opts.forceBase64;
2531 this.enablesXDR = !!opts.enablesXDR;
2532 this.withCredentials = false !== opts.withCredentials;
2533 this.timestampParam = opts.timestampParam || 't';
2534 this.timestampRequests = opts.timestampRequests;
2535 this.transports = opts.transports || ['polling', 'websocket'];
2536 this.transportOptions = opts.transportOptions || {};
2537 this.readyState = '';
2538 this.writeBuffer = [];
2539 this.prevBufferLen = 0;
2540 this.policyPort = opts.policyPort || 843;
2541 this.rememberUpgrade = opts.rememberUpgrade || false;
2542 this.binaryType = null;
2543 this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
2544 this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
2546 if (true === this.perMessageDeflate) this.perMessageDeflate = {};
2547 if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
2548 this.perMessageDeflate.threshold = 1024;
2551 // SSL options for Node.js client
2552 this.pfx = opts.pfx || null;
2553 this.key = opts.key || null;
2554 this.passphrase = opts.passphrase || null;
2555 this.cert = opts.cert || null;
2556 this.ca = opts.ca || null;
2557 this.ciphers = opts.ciphers || null;
2558 this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
2559 this.forceNode = !!opts.forceNode;
2561 // detect ReactNative environment
2562 this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
2564 // other options for Node.js or ReactNative client
2565 if (typeof self === 'undefined' || this.isReactNative) {
2566 if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
2567 this.extraHeaders = opts.extraHeaders;
2570 if (opts.localAddress) {
2571 this.localAddress = opts.localAddress;
2577 this.upgrades = null;
2578 this.pingInterval = null;
2579 this.pingTimeout = null;
2582 this.pingIntervalTimer = null;
2583 this.pingTimeoutTimer = null;
2588 Socket.priorWebsocketSuccess = false;
2594 Emitter(Socket.prototype);
2602 Socket.protocol = parser.protocol; // this is an int
2605 * Expose deps for legacy compatibility
2606 * and standalone browser access.
2609 Socket.Socket = Socket;
2610 Socket.Transport = __webpack_require__(21);
2611 Socket.transports = __webpack_require__(15);
2612 Socket.parser = __webpack_require__(22);
2615 * Creates transport of the given type.
2617 * @param {String} transport name
2618 * @return {Transport}
2622 Socket.prototype.createTransport = function (name) {
2623 debug('creating transport "%s"', name);
2624 var query = clone(this.query);
2626 // append engine.io protocol identifier
2627 query.EIO = parser.protocol;
2630 query.transport = name;
2632 // per-transport options
2633 var options = this.transportOptions[name] || {};
2635 // session id if we already have one
2636 if (this.id) query.sid = this.id;
2638 var transport = new transports[name]({
2641 agent: options.agent || this.agent,
2642 hostname: options.hostname || this.hostname,
2643 port: options.port || this.port,
2644 secure: options.secure || this.secure,
2645 path: options.path || this.path,
2646 forceJSONP: options.forceJSONP || this.forceJSONP,
2647 jsonp: options.jsonp || this.jsonp,
2648 forceBase64: options.forceBase64 || this.forceBase64,
2649 enablesXDR: options.enablesXDR || this.enablesXDR,
2650 withCredentials: options.withCredentials || this.withCredentials,
2651 timestampRequests: options.timestampRequests || this.timestampRequests,
2652 timestampParam: options.timestampParam || this.timestampParam,
2653 policyPort: options.policyPort || this.policyPort,
2654 pfx: options.pfx || this.pfx,
2655 key: options.key || this.key,
2656 passphrase: options.passphrase || this.passphrase,
2657 cert: options.cert || this.cert,
2658 ca: options.ca || this.ca,
2659 ciphers: options.ciphers || this.ciphers,
2660 rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
2661 perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
2662 extraHeaders: options.extraHeaders || this.extraHeaders,
2663 forceNode: options.forceNode || this.forceNode,
2664 localAddress: options.localAddress || this.localAddress,
2665 requestTimeout: options.requestTimeout || this.requestTimeout,
2666 protocols: options.protocols || void (0),
2667 isReactNative: this.isReactNative
2673 function clone (obj) {
2675 for (var i in obj) {
2676 if (obj.hasOwnProperty(i)) {
2684 * Initializes transport to use and starts probe.
2688 Socket.prototype.open = function () {
2690 if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
2691 transport = 'websocket';
2692 } else if (0 === this.transports.length) {
2693 // Emit error on next tick so it can be listened to
2695 setTimeout(function () {
2696 self.emit('error', 'No transports available');
2700 transport = this.transports[0];
2702 this.readyState = 'opening';
2704 // Retry with the next transport if the transport is disabled (jsonp: false)
2706 transport = this.createTransport(transport);
2708 this.transports.shift();
2714 this.setTransport(transport);
2718 * Sets the current transport. Disables the existing one (if any).
2723 Socket.prototype.setTransport = function (transport) {
2724 debug('setting transport %s', transport.name);
2727 if (this.transport) {
2728 debug('clearing existing transport %s', this.transport.name);
2729 this.transport.removeAllListeners();
2733 this.transport = transport;
2735 // set up transport listeners
2737 .on('drain', function () {
2740 .on('packet', function (packet) {
2741 self.onPacket(packet);
2743 .on('error', function (e) {
2746 .on('close', function () {
2747 self.onClose('transport close');
2752 * Probes a transport.
2754 * @param {String} transport name
2758 Socket.prototype.probe = function (name) {
2759 debug('probing transport "%s"', name);
2760 var transport = this.createTransport(name, { probe: 1 });
2764 Socket.priorWebsocketSuccess = false;
2766 function onTransportOpen () {
2767 if (self.onlyBinaryUpgrades) {
2768 var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
2769 failed = failed || upgradeLosesBinary;
2773 debug('probe transport "%s" opened', name);
2774 transport.send([{ type: 'ping', data: 'probe' }]);
2775 transport.once('packet', function (msg) {
2777 if ('pong' === msg.type && 'probe' === msg.data) {
2778 debug('probe transport "%s" pong', name);
2779 self.upgrading = true;
2780 self.emit('upgrading', transport);
2781 if (!transport) return;
2782 Socket.priorWebsocketSuccess = 'websocket' === transport.name;
2784 debug('pausing current transport "%s"', self.transport.name);
2785 self.transport.pause(function () {
2787 if ('closed' === self.readyState) return;
2788 debug('changing transport and sending upgrade packet');
2792 self.setTransport(transport);
2793 transport.send([{ type: 'upgrade' }]);
2794 self.emit('upgrade', transport);
2796 self.upgrading = false;
2800 debug('probe transport "%s" failed', name);
2801 var err = new Error('probe error');
2802 err.transport = transport.name;
2803 self.emit('upgradeError', err);
2808 function freezeTransport () {
2811 // Any callback called by transport should be ignored since now
2820 // Handle any error that happens while probing
2821 function onerror (err) {
2822 var error = new Error('probe error: ' + err);
2823 error.transport = transport.name;
2827 debug('probe transport "%s" failed because of error: %s', name, err);
2829 self.emit('upgradeError', error);
2832 function onTransportClose () {
2833 onerror('transport closed');
2836 // When the socket is closed while we're probing
2837 function onclose () {
2838 onerror('socket closed');
2841 // When the socket is upgraded while we're probing
2842 function onupgrade (to) {
2843 if (transport && to.name !== transport.name) {
2844 debug('"%s" works - aborting "%s"', to.name, transport.name);
2849 // Remove all listeners on the transport and on self
2850 function cleanup () {
2851 transport.removeListener('open', onTransportOpen);
2852 transport.removeListener('error', onerror);
2853 transport.removeListener('close', onTransportClose);
2854 self.removeListener('close', onclose);
2855 self.removeListener('upgrading', onupgrade);
2858 transport.once('open', onTransportOpen);
2859 transport.once('error', onerror);
2860 transport.once('close', onTransportClose);
2862 this.once('close', onclose);
2863 this.once('upgrading', onupgrade);
2869 * Called when connection is deemed open.
2874 Socket.prototype.onOpen = function () {
2875 debug('socket open');
2876 this.readyState = 'open';
2877 Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
2881 // we check for `readyState` in case an `open`
2882 // listener already closed the socket
2883 if ('open' === this.readyState && this.upgrade && this.transport.pause) {
2884 debug('starting upgrade probes');
2885 for (var i = 0, l = this.upgrades.length; i < l; i++) {
2886 this.probe(this.upgrades[i]);
2897 Socket.prototype.onPacket = function (packet) {
2898 if ('opening' === this.readyState || 'open' === this.readyState ||
2899 'closing' === this.readyState) {
2900 debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
2902 this.emit('packet', packet);
2904 // Socket is live - any packet counts
2905 this.emit('heartbeat');
2907 switch (packet.type) {
2909 this.onHandshake(JSON.parse(packet.data));
2918 var err = new Error('server error');
2919 err.code = packet.data;
2924 this.emit('data', packet.data);
2925 this.emit('message', packet.data);
2929 debug('packet received with socket readyState "%s"', this.readyState);
2934 * Called upon handshake completion.
2936 * @param {Object} handshake obj
2940 Socket.prototype.onHandshake = function (data) {
2941 this.emit('handshake', data);
2943 this.transport.query.sid = data.sid;
2944 this.upgrades = this.filterUpgrades(data.upgrades);
2945 this.pingInterval = data.pingInterval;
2946 this.pingTimeout = data.pingTimeout;
2948 // In case open handler closes socket
2949 if ('closed' === this.readyState) return;
2952 // Prolong liveness of socket on heartbeat
2953 this.removeListener('heartbeat', this.onHeartbeat);
2954 this.on('heartbeat', this.onHeartbeat);
2958 * Resets ping timeout.
2963 Socket.prototype.onHeartbeat = function (timeout) {
2964 clearTimeout(this.pingTimeoutTimer);
2966 self.pingTimeoutTimer = setTimeout(function () {
2967 if ('closed' === self.readyState) return;
2968 self.onClose('ping timeout');
2969 }, timeout || (self.pingInterval + self.pingTimeout));
2973 * Pings server every `this.pingInterval` and expects response
2974 * within `this.pingTimeout` or closes connection.
2979 Socket.prototype.setPing = function () {
2981 clearTimeout(self.pingIntervalTimer);
2982 self.pingIntervalTimer = setTimeout(function () {
2983 debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
2985 self.onHeartbeat(self.pingTimeout);
2986 }, self.pingInterval);
2990 * Sends a ping packet.
2995 Socket.prototype.ping = function () {
2997 this.sendPacket('ping', function () {
3003 * Called on `drain` event
3008 Socket.prototype.onDrain = function () {
3009 this.writeBuffer.splice(0, this.prevBufferLen);
3011 // setting prevBufferLen = 0 is very important
3012 // for example, when upgrading, upgrade packet is sent over,
3013 // and a nonzero prevBufferLen could cause problems on `drain`
3014 this.prevBufferLen = 0;
3016 if (0 === this.writeBuffer.length) {
3024 * Flush write buffers.
3029 Socket.prototype.flush = function () {
3030 if ('closed' !== this.readyState && this.transport.writable &&
3031 !this.upgrading && this.writeBuffer.length) {
3032 debug('flushing %d packets in socket', this.writeBuffer.length);
3033 this.transport.send(this.writeBuffer);
3034 // keep track of current length of writeBuffer
3035 // splice writeBuffer and callbackBuffer on `drain`
3036 this.prevBufferLen = this.writeBuffer.length;
3044 * @param {String} message.
3045 * @param {Function} callback function.
3046 * @param {Object} options.
3047 * @return {Socket} for chaining.
3051 Socket.prototype.write =
3052 Socket.prototype.send = function (msg, options, fn) {
3053 this.sendPacket('message', msg, options, fn);
3060 * @param {String} packet type.
3061 * @param {String} data.
3062 * @param {Object} options.
3063 * @param {Function} callback function.
3067 Socket.prototype.sendPacket = function (type, data, options, fn) {
3068 if ('function' === typeof data) {
3073 if ('function' === typeof options) {
3078 if ('closing' === this.readyState || 'closed' === this.readyState) {
3082 options = options || {};
3083 options.compress = false !== options.compress;
3090 this.emit('packetCreate', packet);
3091 this.writeBuffer.push(packet);
3092 if (fn) this.once('flush', fn);
3097 * Closes the connection.
3102 Socket.prototype.close = function () {
3103 if ('opening' === this.readyState || 'open' === this.readyState) {
3104 this.readyState = 'closing';
3108 if (this.writeBuffer.length) {
3109 this.once('drain', function () {
3110 if (this.upgrading) {
3116 } else if (this.upgrading) {
3124 self.onClose('forced close');
3125 debug('socket closing - telling transport to close');
3126 self.transport.close();
3129 function cleanupAndClose () {
3130 self.removeListener('upgrade', cleanupAndClose);
3131 self.removeListener('upgradeError', cleanupAndClose);
3135 function waitForUpgrade () {
3136 // wait for upgrade to finish since we can't send packets while pausing a transport
3137 self.once('upgrade', cleanupAndClose);
3138 self.once('upgradeError', cleanupAndClose);
3145 * Called upon transport error
3150 Socket.prototype.onError = function (err) {
3151 debug('socket error %j', err);
3152 Socket.priorWebsocketSuccess = false;
3153 this.emit('error', err);
3154 this.onClose('transport error', err);
3158 * Called upon transport close.
3163 Socket.prototype.onClose = function (reason, desc) {
3164 if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
3165 debug('socket close with reason: "%s"', reason);
3169 clearTimeout(this.pingIntervalTimer);
3170 clearTimeout(this.pingTimeoutTimer);
3172 // stop event from firing again for transport
3173 this.transport.removeAllListeners('close');
3175 // ensure transport won't stay open
3176 this.transport.close();
3178 // ignore further transport communication
3179 this.transport.removeAllListeners();
3182 this.readyState = 'closed';
3188 this.emit('close', reason, desc);
3190 // clean buffers after, so users can still
3191 // grab the buffers on `close` event
3192 self.writeBuffer = [];
3193 self.prevBufferLen = 0;
3198 * Filters upgrades, returning only those matching client transports.
3200 * @param {Array} server upgrades
3205 Socket.prototype.filterUpgrades = function (upgrades) {
3206 var filteredUpgrades = [];
3207 for (var i = 0, j = upgrades.length; i < j; i++) {
3208 if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
3210 return filteredUpgrades;
3216 /***/ (function(module, exports, __webpack_require__) {
3219 * Module dependencies
3222 var XMLHttpRequest = __webpack_require__(16);
3223 var XHR = __webpack_require__(19);
3224 var JSONP = __webpack_require__(33);
3225 var websocket = __webpack_require__(34);
3228 * Export transports.
3231 exports.polling = polling;
3232 exports.websocket = websocket;
3235 * Polling transport polymorphic constructor.
3236 * Decides on xhr vs jsonp based on feature detection.
3241 function polling (opts) {
3245 var jsonp = false !== opts.jsonp;
3247 if (typeof location !== 'undefined') {
3248 var isSSL = 'https:' === location.protocol;
3249 var port = location.port;
3251 // some user agents have empty `location.port`
3253 port = isSSL ? 443 : 80;
3256 xd = opts.hostname !== location.hostname || port !== opts.port;
3257 xs = opts.secure !== isSSL;
3262 xhr = new XMLHttpRequest(opts);
3264 if ('open' in xhr && !opts.forceJSONP) {
3265 return new XHR(opts);
3267 if (!jsonp) throw new Error('JSONP disabled');
3268 return new JSONP(opts);
3275 /***/ (function(module, exports, __webpack_require__) {
3277 // browser shim for xmlhttprequest module
3279 var hasCORS = __webpack_require__(17);
3280 var globalThis = __webpack_require__(18);
3282 module.exports = function (opts) {
3283 var xdomain = opts.xdomain;
3285 // scheme must be same when usign XDomainRequest
3286 // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
3287 var xscheme = opts.xscheme;
3289 // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
3290 // https://github.com/Automattic/engine.io-client/pull/217
3291 var enablesXDR = opts.enablesXDR;
3293 // XMLHttpRequest can be disabled on IE
3295 if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
3296 return new XMLHttpRequest();
3300 // Use XDomainRequest for IE8 if enablesXDR is true
3301 // because loading bar keeps flashing when using jsonp-polling
3302 // https://github.com/yujiosaka/socke.io-ie8-loading-example
3304 if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
3305 return new XDomainRequest();
3311 return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
3319 /***/ (function(module, exports) {
3325 * Logic borrowed from Modernizr:
3327 * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
3331 module.exports = typeof XMLHttpRequest !== 'undefined' &&
3332 'withCredentials' in new XMLHttpRequest();
3334 // if XMLHttp support is disabled in IE then it will throw
3335 // when trying to create
3336 module.exports = false;
3342 /***/ (function(module, exports) {
3344 module.exports = (function () {
3345 if (typeof self !== 'undefined') {
3347 } else if (typeof window !== 'undefined') {
3350 return Function('return this')(); // eslint-disable-line no-new-func
3357 /***/ (function(module, exports, __webpack_require__) {
3359 /* global attachEvent */
3362 * Module requirements.
3365 var XMLHttpRequest = __webpack_require__(16);
3366 var Polling = __webpack_require__(20);
3367 var Emitter = __webpack_require__(8);
3368 var inherit = __webpack_require__(31);
3369 var debug = __webpack_require__(3)('engine.io-client:polling-xhr');
3370 var globalThis = __webpack_require__(18);
3376 module.exports = XHR;
3377 module.exports.Request = Request;
3383 function empty () {}
3386 * XHR Polling constructor.
3388 * @param {Object} opts
3392 function XHR (opts) {
3393 Polling.call(this, opts);
3394 this.requestTimeout = opts.requestTimeout;
3395 this.extraHeaders = opts.extraHeaders;
3397 if (typeof location !== 'undefined') {
3398 var isSSL = 'https:' === location.protocol;
3399 var port = location.port;
3401 // some user agents have empty `location.port`
3403 port = isSSL ? 443 : 80;
3406 this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
3408 this.xs = opts.secure !== isSSL;
3413 * Inherits from Polling.
3416 inherit(XHR, Polling);
3419 * XHR supports binary
3422 XHR.prototype.supportsBinary = true;
3425 * Creates a request.
3427 * @param {String} method
3431 XHR.prototype.request = function (opts) {
3433 opts.uri = this.uri();
3436 opts.agent = this.agent || false;
3437 opts.supportsBinary = this.supportsBinary;
3438 opts.enablesXDR = this.enablesXDR;
3439 opts.withCredentials = this.withCredentials;
3441 // SSL options for Node.js client
3442 opts.pfx = this.pfx;
3443 opts.key = this.key;
3444 opts.passphrase = this.passphrase;
3445 opts.cert = this.cert;
3447 opts.ciphers = this.ciphers;
3448 opts.rejectUnauthorized = this.rejectUnauthorized;
3449 opts.requestTimeout = this.requestTimeout;
3451 // other options for Node.js client
3452 opts.extraHeaders = this.extraHeaders;
3454 return new Request(opts);
3460 * @param {String} data to send.
3461 * @param {Function} called upon flush.
3465 XHR.prototype.doWrite = function (data, fn) {
3466 var isBinary = typeof data !== 'string' && data !== undefined;
3467 var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
3469 req.on('success', fn);
3470 req.on('error', function (err) {
3471 self.onError('xhr post error', err);
3477 * Starts a poll cycle.
3482 XHR.prototype.doPoll = function () {
3484 var req = this.request();
3486 req.on('data', function (data) {
3489 req.on('error', function (err) {
3490 self.onError('xhr poll error', err);
3496 * Request constructor
3498 * @param {Object} options
3502 function Request (opts) {
3503 this.method = opts.method || 'GET';
3504 this.uri = opts.uri;
3505 this.xd = !!opts.xd;
3506 this.xs = !!opts.xs;
3507 this.async = false !== opts.async;
3508 this.data = undefined !== opts.data ? opts.data : null;
3509 this.agent = opts.agent;
3510 this.isBinary = opts.isBinary;
3511 this.supportsBinary = opts.supportsBinary;
3512 this.enablesXDR = opts.enablesXDR;
3513 this.withCredentials = opts.withCredentials;
3514 this.requestTimeout = opts.requestTimeout;
3516 // SSL options for Node.js client
3517 this.pfx = opts.pfx;
3518 this.key = opts.key;
3519 this.passphrase = opts.passphrase;
3520 this.cert = opts.cert;
3522 this.ciphers = opts.ciphers;
3523 this.rejectUnauthorized = opts.rejectUnauthorized;
3525 // other options for Node.js client
3526 this.extraHeaders = opts.extraHeaders;
3535 Emitter(Request.prototype);
3538 * Creates the XHR object and sends the request.
3543 Request.prototype.create = function () {
3544 var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
3546 // SSL options for Node.js client
3547 opts.pfx = this.pfx;
3548 opts.key = this.key;
3549 opts.passphrase = this.passphrase;
3550 opts.cert = this.cert;
3552 opts.ciphers = this.ciphers;
3553 opts.rejectUnauthorized = this.rejectUnauthorized;
3555 var xhr = this.xhr = new XMLHttpRequest(opts);
3559 debug('xhr open %s: %s', this.method, this.uri);
3560 xhr.open(this.method, this.uri, this.async);
3562 if (this.extraHeaders) {
3563 xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
3564 for (var i in this.extraHeaders) {
3565 if (this.extraHeaders.hasOwnProperty(i)) {
3566 xhr.setRequestHeader(i, this.extraHeaders[i]);
3572 if ('POST' === this.method) {
3574 if (this.isBinary) {
3575 xhr.setRequestHeader('Content-type', 'application/octet-stream');
3577 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
3583 xhr.setRequestHeader('Accept', '*/*');
3587 if ('withCredentials' in xhr) {
3588 xhr.withCredentials = this.withCredentials;
3591 if (this.requestTimeout) {
3592 xhr.timeout = this.requestTimeout;
3595 if (this.hasXDR()) {
3596 xhr.onload = function () {
3599 xhr.onerror = function () {
3600 self.onError(xhr.responseText);
3603 xhr.onreadystatechange = function () {
3604 if (xhr.readyState === 2) {
3606 var contentType = xhr.getResponseHeader('Content-Type');
3607 if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
3608 xhr.responseType = 'arraybuffer';
3612 if (4 !== xhr.readyState) return;
3613 if (200 === xhr.status || 1223 === xhr.status) {
3616 // make sure the `error` event handler that's user-set
3617 // does not throw in the same tick and gets caught here
3618 setTimeout(function () {
3619 self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
3625 debug('xhr data %s', this.data);
3626 xhr.send(this.data);
3628 // Need to defer since .create() is called directly fhrom the constructor
3629 // and thus the 'error' event can only be only bound *after* this exception
3630 // occurs. Therefore, also, we cannot throw here at all.
3631 setTimeout(function () {
3637 if (typeof document !== 'undefined') {
3638 this.index = Request.requestsCount++;
3639 Request.requests[this.index] = this;
3644 * Called upon successful response.
3649 Request.prototype.onSuccess = function () {
3650 this.emit('success');
3655 * Called if we have data.
3660 Request.prototype.onData = function (data) {
3661 this.emit('data', data);
3666 * Called upon error.
3671 Request.prototype.onError = function (err) {
3672 this.emit('error', err);
3682 Request.prototype.cleanup = function (fromError) {
3683 if ('undefined' === typeof this.xhr || null === this.xhr) {
3687 if (this.hasXDR()) {
3688 this.xhr.onload = this.xhr.onerror = empty;
3690 this.xhr.onreadystatechange = empty;
3699 if (typeof document !== 'undefined') {
3700 delete Request.requests[this.index];
3712 Request.prototype.onLoad = function () {
3717 contentType = this.xhr.getResponseHeader('Content-Type');
3719 if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
3720 data = this.xhr.response || this.xhr.responseText;
3722 data = this.xhr.responseText;
3733 * Check if it has XDomainRequest.
3738 Request.prototype.hasXDR = function () {
3739 return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
3743 * Aborts the request.
3748 Request.prototype.abort = function () {
3753 * Aborts pending requests when unloading the window. This is needed to prevent
3754 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
3758 Request.requestsCount = 0;
3759 Request.requests = {};
3761 if (typeof document !== 'undefined') {
3762 if (typeof attachEvent === 'function') {
3763 attachEvent('onunload', unloadHandler);
3764 } else if (typeof addEventListener === 'function') {
3765 var terminationEvent = 'onpagehide' in globalThis ? 'pagehide' : 'unload';
3766 addEventListener(terminationEvent, unloadHandler, false);
3770 function unloadHandler () {
3771 for (var i in Request.requests) {
3772 if (Request.requests.hasOwnProperty(i)) {
3773 Request.requests[i].abort();
3781 /***/ (function(module, exports, __webpack_require__) {
3784 * Module dependencies.
3787 var Transport = __webpack_require__(21);
3788 var parseqs = __webpack_require__(30);
3789 var parser = __webpack_require__(22);
3790 var inherit = __webpack_require__(31);
3791 var yeast = __webpack_require__(32);
3792 var debug = __webpack_require__(3)('engine.io-client:polling');
3798 module.exports = Polling;
3801 * Is XHR2 supported?
3804 var hasXHR2 = (function () {
3805 var XMLHttpRequest = __webpack_require__(16);
3806 var xhr = new XMLHttpRequest({ xdomain: false });
3807 return null != xhr.responseType;
3811 * Polling interface.
3813 * @param {Object} opts
3817 function Polling (opts) {
3818 var forceBase64 = (opts && opts.forceBase64);
3819 if (!hasXHR2 || forceBase64) {
3820 this.supportsBinary = false;
3822 Transport.call(this, opts);
3826 * Inherits from Transport.
3829 inherit(Polling, Transport);
3835 Polling.prototype.name = 'polling';
3838 * Opens the socket (triggers polling). We write a PING message to determine
3839 * when the transport is open.
3844 Polling.prototype.doOpen = function () {
3851 * @param {Function} callback upon buffers are flushed and transport is paused
3855 Polling.prototype.pause = function (onPause) {
3858 this.readyState = 'pausing';
3862 self.readyState = 'paused';
3866 if (this.polling || !this.writable) {
3870 debug('we are currently polling - waiting to pause');
3872 this.once('pollComplete', function () {
3873 debug('pre-pause polling complete');
3878 if (!this.writable) {
3879 debug('we are currently writing - waiting to pause');
3881 this.once('drain', function () {
3882 debug('pre-pause writing complete');
3892 * Starts polling cycle.
3897 Polling.prototype.poll = function () {
3899 this.polling = true;
3905 * Overloads onData to detect payloads.
3910 Polling.prototype.onData = function (data) {
3912 debug('polling got data %s', data);
3913 var callback = function (packet, index, total) {
3914 // if its the first message we consider the transport open
3915 if ('opening' === self.readyState && packet.type === 'open') {
3919 // if its a close packet, we close the ongoing requests
3920 if ('close' === packet.type) {
3925 // otherwise bypass onData and handle the message
3926 self.onPacket(packet);
3930 parser.decodePayload(data, this.socket.binaryType, callback);
3932 // if an event did not trigger closing
3933 if ('closed' !== this.readyState) {
3934 // if we got data we're not polling
3935 this.polling = false;
3936 this.emit('pollComplete');
3938 if ('open' === this.readyState) {
3941 debug('ignoring poll - transport state "%s"', this.readyState);
3947 * For polling, send a close packet.
3952 Polling.prototype.doClose = function () {
3956 debug('writing close packet');
3957 self.write([{ type: 'close' }]);
3960 if ('open' === this.readyState) {
3961 debug('transport open - closing');
3964 // in case we're trying to close while
3965 // handshaking is in progress (GH-164)
3966 debug('transport not open - deferring close');
3967 this.once('open', close);
3972 * Writes a packets payload.
3974 * @param {Array} data packets
3975 * @param {Function} drain callback
3979 Polling.prototype.write = function (packets) {
3981 this.writable = false;
3982 var callbackfn = function () {
3983 self.writable = true;
3987 parser.encodePayload(packets, this.supportsBinary, function (data) {
3988 self.doWrite(data, callbackfn);
3993 * Generates uri for connection.
3998 Polling.prototype.uri = function () {
3999 var query = this.query || {};
4000 var schema = this.secure ? 'https' : 'http';
4003 // cache busting is forced
4004 if (false !== this.timestampRequests) {
4005 query[this.timestampParam] = yeast();
4008 if (!this.supportsBinary && !query.sid) {
4012 query = parseqs.encode(query);
4014 // avoid port if default for schema
4015 if (this.port && (('https' === schema && Number(this.port) !== 443) ||
4016 ('http' === schema && Number(this.port) !== 80))) {
4017 port = ':' + this.port;
4020 // prepend ? to query
4022 query = '?' + query;
4025 var ipv6 = this.hostname.indexOf(':') !== -1;
4026 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
4032 /***/ (function(module, exports, __webpack_require__) {
4035 * Module dependencies.
4038 var parser = __webpack_require__(22);
4039 var Emitter = __webpack_require__(8);
4045 module.exports = Transport;
4048 * Transport abstract constructor.
4050 * @param {Object} options.
4054 function Transport (opts) {
4055 this.path = opts.path;
4056 this.hostname = opts.hostname;
4057 this.port = opts.port;
4058 this.secure = opts.secure;
4059 this.query = opts.query;
4060 this.timestampParam = opts.timestampParam;
4061 this.timestampRequests = opts.timestampRequests;
4062 this.readyState = '';
4063 this.agent = opts.agent || false;
4064 this.socket = opts.socket;
4065 this.enablesXDR = opts.enablesXDR;
4066 this.withCredentials = opts.withCredentials;
4068 // SSL options for Node.js client
4069 this.pfx = opts.pfx;
4070 this.key = opts.key;
4071 this.passphrase = opts.passphrase;
4072 this.cert = opts.cert;
4074 this.ciphers = opts.ciphers;
4075 this.rejectUnauthorized = opts.rejectUnauthorized;
4076 this.forceNode = opts.forceNode;
4078 // results of ReactNative environment detection
4079 this.isReactNative = opts.isReactNative;
4081 // other options for Node.js client
4082 this.extraHeaders = opts.extraHeaders;
4083 this.localAddress = opts.localAddress;
4090 Emitter(Transport.prototype);
4095 * @param {String} str
4096 * @return {Transport} for chaining
4100 Transport.prototype.onError = function (msg, desc) {
4101 var err = new Error(msg);
4102 err.type = 'TransportError';
4103 err.description = desc;
4104 this.emit('error', err);
4109 * Opens the transport.
4114 Transport.prototype.open = function () {
4115 if ('closed' === this.readyState || '' === this.readyState) {
4116 this.readyState = 'opening';
4124 * Closes the transport.
4129 Transport.prototype.close = function () {
4130 if ('opening' === this.readyState || 'open' === this.readyState) {
4139 * Sends multiple packets.
4141 * @param {Array} packets
4145 Transport.prototype.send = function (packets) {
4146 if ('open' === this.readyState) {
4147 this.write(packets);
4149 throw new Error('Transport not open');
4159 Transport.prototype.onOpen = function () {
4160 this.readyState = 'open';
4161 this.writable = true;
4168 * @param {String} data
4172 Transport.prototype.onData = function (data) {
4173 var packet = parser.decodePacket(data, this.socket.binaryType);
4174 this.onPacket(packet);
4178 * Called with a decoded packet.
4181 Transport.prototype.onPacket = function (packet) {
4182 this.emit('packet', packet);
4186 * Called upon close.
4191 Transport.prototype.onClose = function () {
4192 this.readyState = 'closed';
4199 /***/ (function(module, exports, __webpack_require__) {
4202 * Module dependencies.
4205 var keys = __webpack_require__(23);
4206 var hasBinary = __webpack_require__(24);
4207 var sliceBuffer = __webpack_require__(25);
4208 var after = __webpack_require__(26);
4209 var utf8 = __webpack_require__(27);
4212 if (typeof ArrayBuffer !== 'undefined') {
4213 base64encoder = __webpack_require__(28);
4217 * Check if we are running an android browser. That requires us to use
4218 * ArrayBuffer with polling transports...
4220 * http://ghinda.net/jpeg-blob-ajax-android/
4223 var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
4226 * Check if we are running in PhantomJS.
4227 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
4228 * https://github.com/ariya/phantomjs/issues/11395
4231 var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
4234 * When true, avoids using Blobs to encode payloads.
4237 var dontSendBlobs = isAndroid || isPhantomJS;
4240 * Current protocol version.
4243 exports.protocol = 3;
4249 var packets = exports.packets = {
4251 , close: 1 // non-ws
4259 var packetslist = keys(packets);
4262 * Premade error packet.
4265 var err = { type: 'error', data: 'parser error' };
4268 * Create a blob api even for blob builder when vendor prefixes exist
4271 var Blob = __webpack_require__(29);
4276 * <packet type id> [ <data> ]
4284 * Binary is encoded in an identical principle
4289 exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
4290 if (typeof supportsBinary === 'function') {
4291 callback = supportsBinary;
4292 supportsBinary = false;
4295 if (typeof utf8encode === 'function') {
4296 callback = utf8encode;
4300 var data = (packet.data === undefined)
4302 : packet.data.buffer || packet.data;
4304 if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
4305 return encodeArrayBuffer(packet, supportsBinary, callback);
4306 } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
4307 return encodeBlob(packet, supportsBinary, callback);
4310 // might be an object with { base64: true, data: dataAsBase64String }
4311 if (data && data.base64) {
4312 return encodeBase64Object(packet, callback);
4315 // Sending data as a utf-8 string
4316 var encoded = packets[packet.type];
4318 // data fragment is optional
4319 if (undefined !== packet.data) {
4320 encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
4323 return callback('' + encoded);
4327 function encodeBase64Object(packet, callback) {
4328 // packet data is an object { base64: true, data: dataAsBase64String }
4329 var message = 'b' + exports.packets[packet.type] + packet.data.data;
4330 return callback(message);
4334 * Encode packet helpers for binary types
4337 function encodeArrayBuffer(packet, supportsBinary, callback) {
4338 if (!supportsBinary) {
4339 return exports.encodeBase64Packet(packet, callback);
4342 var data = packet.data;
4343 var contentArray = new Uint8Array(data);
4344 var resultBuffer = new Uint8Array(1 + data.byteLength);
4346 resultBuffer[0] = packets[packet.type];
4347 for (var i = 0; i < contentArray.length; i++) {
4348 resultBuffer[i+1] = contentArray[i];
4351 return callback(resultBuffer.buffer);
4354 function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
4355 if (!supportsBinary) {
4356 return exports.encodeBase64Packet(packet, callback);
4359 var fr = new FileReader();
4360 fr.onload = function() {
4361 exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
4363 return fr.readAsArrayBuffer(packet.data);
4366 function encodeBlob(packet, supportsBinary, callback) {
4367 if (!supportsBinary) {
4368 return exports.encodeBase64Packet(packet, callback);
4371 if (dontSendBlobs) {
4372 return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
4375 var length = new Uint8Array(1);
4376 length[0] = packets[packet.type];
4377 var blob = new Blob([length.buffer, packet.data]);
4379 return callback(blob);
4383 * Encodes a packet with binary data in a base64 string
4385 * @param {Object} packet, has `type` and `data`
4386 * @return {String} base64 encoded message
4389 exports.encodeBase64Packet = function(packet, callback) {
4390 var message = 'b' + exports.packets[packet.type];
4391 if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
4392 var fr = new FileReader();
4393 fr.onload = function() {
4394 var b64 = fr.result.split(',')[1];
4395 callback(message + b64);
4397 return fr.readAsDataURL(packet.data);
4402 b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
4404 // iPhone Safari doesn't let you apply with typed arrays
4405 var typed = new Uint8Array(packet.data);
4406 var basic = new Array(typed.length);
4407 for (var i = 0; i < typed.length; i++) {
4408 basic[i] = typed[i];
4410 b64data = String.fromCharCode.apply(null, basic);
4412 message += btoa(b64data);
4413 return callback(message);
4417 * Decodes a packet. Changes format to Blob if requested.
4419 * @return {Object} with `type` and `data` (if any)
4423 exports.decodePacket = function (data, binaryType, utf8decode) {
4424 if (data === undefined) {
4428 if (typeof data === 'string') {
4429 if (data.charAt(0) === 'b') {
4430 return exports.decodeBase64Packet(data.substr(1), binaryType);
4434 data = tryDecode(data);
4435 if (data === false) {
4439 var type = data.charAt(0);
4441 if (Number(type) != type || !packetslist[type]) {
4445 if (data.length > 1) {
4446 return { type: packetslist[type], data: data.substring(1) };
4448 return { type: packetslist[type] };
4452 var asArray = new Uint8Array(data);
4453 var type = asArray[0];
4454 var rest = sliceBuffer(data, 1);
4455 if (Blob && binaryType === 'blob') {
4456 rest = new Blob([rest]);
4458 return { type: packetslist[type], data: rest };
4461 function tryDecode(data) {
4463 data = utf8.decode(data, { strict: false });
4471 * Decodes a packet encoded in a base64 string
4473 * @param {String} base64 encoded message
4474 * @return {Object} with `type` and `data` (if any)
4477 exports.decodeBase64Packet = function(msg, binaryType) {
4478 var type = packetslist[msg.charAt(0)];
4479 if (!base64encoder) {
4480 return { type: type, data: { base64: true, data: msg.substr(1) } };
4483 var data = base64encoder.decode(msg.substr(1));
4485 if (binaryType === 'blob' && Blob) {
4486 data = new Blob([data]);
4489 return { type: type, data: data };
4493 * Encodes multiple messages (payload).
4499 * 11:hello world2:hi
4501 * If any contents are binary, they will be encoded as base64 strings. Base64
4502 * encoded strings are marked with a b before the length specifier
4504 * @param {Array} packets
4508 exports.encodePayload = function (packets, supportsBinary, callback) {
4509 if (typeof supportsBinary === 'function') {
4510 callback = supportsBinary;
4511 supportsBinary = null;
4514 var isBinary = hasBinary(packets);
4516 if (supportsBinary && isBinary) {
4517 if (Blob && !dontSendBlobs) {
4518 return exports.encodePayloadAsBlob(packets, callback);
4521 return exports.encodePayloadAsArrayBuffer(packets, callback);
4524 if (!packets.length) {
4525 return callback('0:');
4528 function setLengthHeader(message) {
4529 return message.length + ':' + message;
4532 function encodeOne(packet, doneCallback) {
4533 exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
4534 doneCallback(null, setLengthHeader(message));
4538 map(packets, encodeOne, function(err, results) {
4539 return callback(results.join(''));
4544 * Async array map using after
4547 function map(ary, each, done) {
4548 var result = new Array(ary.length);
4549 var next = after(ary.length, done);
4551 var eachWithIndex = function(i, el, cb) {
4552 each(el, function(error, msg) {
4558 for (var i = 0; i < ary.length; i++) {
4559 eachWithIndex(i, ary[i], next);
4564 * Decodes data when a payload is maybe expected. Possible binary contents are
4565 * decoded from their base64 representation
4567 * @param {String} data, callback method
4571 exports.decodePayload = function (data, binaryType, callback) {
4572 if (typeof data !== 'string') {
4573 return exports.decodePayloadAsBinary(data, binaryType, callback);
4576 if (typeof binaryType === 'function') {
4577 callback = binaryType;
4583 // parser error - ignoring payload
4584 return callback(err, 0, 1);
4587 var length = '', n, msg;
4589 for (var i = 0, l = data.length; i < l; i++) {
4590 var chr = data.charAt(i);
4597 if (length === '' || (length != (n = Number(length)))) {
4598 // parser error - ignoring payload
4599 return callback(err, 0, 1);
4602 msg = data.substr(i + 1, n);
4604 if (length != msg.length) {
4605 // parser error - ignoring payload
4606 return callback(err, 0, 1);
4610 packet = exports.decodePacket(msg, binaryType, false);
4612 if (err.type === packet.type && err.data === packet.data) {
4613 // parser error in individual packet - ignoring payload
4614 return callback(err, 0, 1);
4617 var ret = callback(packet, i + n, l);
4618 if (false === ret) return;
4626 if (length !== '') {
4627 // parser error - ignoring payload
4628 return callback(err, 0, 1);
4634 * Encodes multiple messages (payload) as binary.
4636 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
4640 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
4642 * @param {Array} packets
4643 * @return {ArrayBuffer} encoded payload
4647 exports.encodePayloadAsArrayBuffer = function(packets, callback) {
4648 if (!packets.length) {
4649 return callback(new ArrayBuffer(0));
4652 function encodeOne(packet, doneCallback) {
4653 exports.encodePacket(packet, true, true, function(data) {
4654 return doneCallback(null, data);
4658 map(packets, encodeOne, function(err, encodedPackets) {
4659 var totalLength = encodedPackets.reduce(function(acc, p) {
4661 if (typeof p === 'string'){
4666 return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
4669 var resultArray = new Uint8Array(totalLength);
4671 var bufferIndex = 0;
4672 encodedPackets.forEach(function(p) {
4673 var isString = typeof p === 'string';
4676 var view = new Uint8Array(p.length);
4677 for (var i = 0; i < p.length; i++) {
4678 view[i] = p.charCodeAt(i);
4683 if (isString) { // not true binary
4684 resultArray[bufferIndex++] = 0;
4685 } else { // true binary
4686 resultArray[bufferIndex++] = 1;
4689 var lenStr = ab.byteLength.toString();
4690 for (var i = 0; i < lenStr.length; i++) {
4691 resultArray[bufferIndex++] = parseInt(lenStr[i]);
4693 resultArray[bufferIndex++] = 255;
4695 var view = new Uint8Array(ab);
4696 for (var i = 0; i < view.length; i++) {
4697 resultArray[bufferIndex++] = view[i];
4701 return callback(resultArray.buffer);
4709 exports.encodePayloadAsBlob = function(packets, callback) {
4710 function encodeOne(packet, doneCallback) {
4711 exports.encodePacket(packet, true, true, function(encoded) {
4712 var binaryIdentifier = new Uint8Array(1);
4713 binaryIdentifier[0] = 1;
4714 if (typeof encoded === 'string') {
4715 var view = new Uint8Array(encoded.length);
4716 for (var i = 0; i < encoded.length; i++) {
4717 view[i] = encoded.charCodeAt(i);
4719 encoded = view.buffer;
4720 binaryIdentifier[0] = 0;
4723 var len = (encoded instanceof ArrayBuffer)
4724 ? encoded.byteLength
4727 var lenStr = len.toString();
4728 var lengthAry = new Uint8Array(lenStr.length + 1);
4729 for (var i = 0; i < lenStr.length; i++) {
4730 lengthAry[i] = parseInt(lenStr[i]);
4732 lengthAry[lenStr.length] = 255;
4735 var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
4736 doneCallback(null, blob);
4741 map(packets, encodeOne, function(err, results) {
4742 return callback(new Blob(results));
4747 * Decodes data when a payload is maybe expected. Strings are decoded by
4748 * interpreting each byte as a key code for entries marked to start with 0. See
4749 * description of encodePayloadAsBinary
4751 * @param {ArrayBuffer} data, callback method
4755 exports.decodePayloadAsBinary = function (data, binaryType, callback) {
4756 if (typeof binaryType === 'function') {
4757 callback = binaryType;
4761 var bufferTail = data;
4764 while (bufferTail.byteLength > 0) {
4765 var tailArray = new Uint8Array(bufferTail);
4766 var isString = tailArray[0] === 0;
4769 for (var i = 1; ; i++) {
4770 if (tailArray[i] === 255) break;
4772 // 310 = char length of Number.MAX_VALUE
4773 if (msgLength.length > 310) {
4774 return callback(err, 0, 1);
4777 msgLength += tailArray[i];
4780 bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
4781 msgLength = parseInt(msgLength);
4783 var msg = sliceBuffer(bufferTail, 0, msgLength);
4786 msg = String.fromCharCode.apply(null, new Uint8Array(msg));
4788 // iPhone Safari doesn't let you apply to typed arrays
4789 var typed = new Uint8Array(msg);
4791 for (var i = 0; i < typed.length; i++) {
4792 msg += String.fromCharCode(typed[i]);
4798 bufferTail = sliceBuffer(bufferTail, msgLength);
4801 var total = buffers.length;
4802 buffers.forEach(function(buffer, i) {
4803 callback(exports.decodePacket(buffer, binaryType, true), i, total);
4810 /***/ (function(module, exports) {
4814 * Gets the keys for an object.
4816 * @return {Array} keys
4820 module.exports = Object.keys || function keys (obj){
4822 var has = Object.prototype.hasOwnProperty;
4824 for (var i in obj) {
4825 if (has.call(obj, i)) {
4835 /***/ (function(module, exports, __webpack_require__) {
4837 /* global Blob File */
4840 * Module requirements.
4843 var isArray = __webpack_require__(10);
4845 var toString = Object.prototype.toString;
4846 var withNativeBlob = typeof Blob === 'function' ||
4847 typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
4848 var withNativeFile = typeof File === 'function' ||
4849 typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
4855 module.exports = hasBinary;
4858 * Checks for binary data.
4860 * Supports Buffer, ArrayBuffer, Blob and File.
4862 * @param {Object} anything
4866 function hasBinary (obj) {
4867 if (!obj || typeof obj !== 'object') {
4872 for (var i = 0, l = obj.length; i < l; i++) {
4873 if (hasBinary(obj[i])) {
4880 if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
4881 (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
4882 (withNativeBlob && obj instanceof Blob) ||
4883 (withNativeFile && obj instanceof File)
4888 // see: https://github.com/Automattic/has-binary/pull/4
4889 if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
4890 return hasBinary(obj.toJSON(), true);
4893 for (var key in obj) {
4894 if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
4905 /***/ (function(module, exports) {
4908 * An abstraction for slicing an arraybuffer even when
4909 * ArrayBuffer.prototype.slice is not supported
4914 module.exports = function(arraybuffer, start, end) {
4915 var bytes = arraybuffer.byteLength;
4919 if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
4921 if (start < 0) { start += bytes; }
4922 if (end < 0) { end += bytes; }
4923 if (end > bytes) { end = bytes; }
4925 if (start >= bytes || start >= end || bytes === 0) {
4926 return new ArrayBuffer(0);
4929 var abv = new Uint8Array(arraybuffer);
4930 var result = new Uint8Array(end - start);
4931 for (var i = start, ii = 0; i < end; i++, ii++) {
4932 result[ii] = abv[i];
4934 return result.buffer;
4940 /***/ (function(module, exports) {
4942 module.exports = after
4944 function after(count, callback, err_cb) {
4946 err_cb = err_cb || noop
4949 return (count === 0) ? callback() : proxy
4951 function proxy(err, result) {
4952 if (proxy.count <= 0) {
4953 throw new Error('after called too many times')
4957 // after first error, rest are passed to err_cb
4961 // future error callbacks will go to error handler
4963 } else if (proxy.count === 0 && !bail) {
4964 callback(null, result)
4974 /***/ (function(module, exports) {
4976 /*! https://mths.be/utf8js v2.1.2 by @mathias */
4978 var stringFromCharCode = String.fromCharCode;
4980 // Taken from https://mths.be/punycode
4981 function ucs2decode(string) {
4984 var length = string.length;
4987 while (counter < length) {
4988 value = string.charCodeAt(counter++);
4989 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
4990 // high surrogate, and there is a next character
4991 extra = string.charCodeAt(counter++);
4992 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
4993 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
4995 // unmatched surrogate; only append this code unit, in case the next
4996 // code unit is the high surrogate of a surrogate pair
5007 // Taken from https://mths.be/punycode
5008 function ucs2encode(array) {
5009 var length = array.length;
5013 while (++index < length) {
5014 value = array[index];
5015 if (value > 0xFFFF) {
5017 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
5018 value = 0xDC00 | value & 0x3FF;
5020 output += stringFromCharCode(value);
5025 function checkScalarValue(codePoint, strict) {
5026 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
5029 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
5030 ' is not a scalar value'
5037 /*--------------------------------------------------------------------------*/
5039 function createByte(codePoint, shift) {
5040 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
5043 function encodeCodePoint(codePoint, strict) {
5044 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
5045 return stringFromCharCode(codePoint);
5048 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
5049 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
5051 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
5052 if (!checkScalarValue(codePoint, strict)) {
5055 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
5056 symbol += createByte(codePoint, 6);
5058 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
5059 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
5060 symbol += createByte(codePoint, 12);
5061 symbol += createByte(codePoint, 6);
5063 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
5067 function utf8encode(string, opts) {
5069 var strict = false !== opts.strict;
5071 var codePoints = ucs2decode(string);
5072 var length = codePoints.length;
5075 var byteString = '';
5076 while (++index < length) {
5077 codePoint = codePoints[index];
5078 byteString += encodeCodePoint(codePoint, strict);
5083 /*--------------------------------------------------------------------------*/
5085 function readContinuationByte() {
5086 if (byteIndex >= byteCount) {
5087 throw Error('Invalid byte index');
5090 var continuationByte = byteArray[byteIndex] & 0xFF;
5093 if ((continuationByte & 0xC0) == 0x80) {
5094 return continuationByte & 0x3F;
5097 // If we end up here, it’s not a continuation byte
5098 throw Error('Invalid continuation byte');
5101 function decodeSymbol(strict) {
5108 if (byteIndex > byteCount) {
5109 throw Error('Invalid byte index');
5112 if (byteIndex == byteCount) {
5117 byte1 = byteArray[byteIndex] & 0xFF;
5120 // 1-byte sequence (no continuation bytes)
5121 if ((byte1 & 0x80) == 0) {
5126 if ((byte1 & 0xE0) == 0xC0) {
5127 byte2 = readContinuationByte();
5128 codePoint = ((byte1 & 0x1F) << 6) | byte2;
5129 if (codePoint >= 0x80) {
5132 throw Error('Invalid continuation byte');
5136 // 3-byte sequence (may include unpaired surrogates)
5137 if ((byte1 & 0xF0) == 0xE0) {
5138 byte2 = readContinuationByte();
5139 byte3 = readContinuationByte();
5140 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
5141 if (codePoint >= 0x0800) {
5142 return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
5144 throw Error('Invalid continuation byte');
5149 if ((byte1 & 0xF8) == 0xF0) {
5150 byte2 = readContinuationByte();
5151 byte3 = readContinuationByte();
5152 byte4 = readContinuationByte();
5153 codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
5154 (byte3 << 0x06) | byte4;
5155 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
5160 throw Error('Invalid UTF-8 detected');
5166 function utf8decode(byteString, opts) {
5168 var strict = false !== opts.strict;
5170 byteArray = ucs2decode(byteString);
5171 byteCount = byteArray.length;
5173 var codePoints = [];
5175 while ((tmp = decodeSymbol(strict)) !== false) {
5176 codePoints.push(tmp);
5178 return ucs2encode(codePoints);
5190 /***/ (function(module, exports) {
5193 * base64-arraybuffer
5194 * https://github.com/niklasvh/base64-arraybuffer
5196 * Copyright (c) 2012 Niklas von Hertzen
5197 * Licensed under the MIT license.
5202 exports.encode = function(arraybuffer) {
5203 var bytes = new Uint8Array(arraybuffer),
5204 i, len = bytes.length, base64 = "";
5206 for (i = 0; i < len; i+=3) {
5207 base64 += chars[bytes[i] >> 2];
5208 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
5209 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
5210 base64 += chars[bytes[i + 2] & 63];
5213 if ((len % 3) === 2) {
5214 base64 = base64.substring(0, base64.length - 1) + "=";
5215 } else if (len % 3 === 1) {
5216 base64 = base64.substring(0, base64.length - 2) + "==";
5222 exports.decode = function(base64) {
5223 var bufferLength = base64.length * 0.75,
5224 len = base64.length, i, p = 0,
5225 encoded1, encoded2, encoded3, encoded4;
5227 if (base64[base64.length - 1] === "=") {
5229 if (base64[base64.length - 2] === "=") {
5234 var arraybuffer = new ArrayBuffer(bufferLength),
5235 bytes = new Uint8Array(arraybuffer);
5237 for (i = 0; i < len; i+=4) {
5238 encoded1 = chars.indexOf(base64[i]);
5239 encoded2 = chars.indexOf(base64[i+1]);
5240 encoded3 = chars.indexOf(base64[i+2]);
5241 encoded4 = chars.indexOf(base64[i+3]);
5243 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
5244 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
5245 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
5250 })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
5255 /***/ (function(module, exports) {
5258 * Create a blob builder even when vendor prefixes exist
5261 var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
5262 typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
5263 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
5264 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
5268 * Check if Blob constructor is supported
5271 var blobSupported = (function() {
5273 var a = new Blob(['hi']);
5274 return a.size === 2;
5281 * Check if Blob constructor supports ArrayBufferViews
5282 * Fails in Safari 6, so we need to map to ArrayBuffers there.
5285 var blobSupportsArrayBufferView = blobSupported && (function() {
5287 var b = new Blob([new Uint8Array([1,2])]);
5288 return b.size === 2;
5295 * Check if BlobBuilder is supported
5298 var blobBuilderSupported = BlobBuilder
5299 && BlobBuilder.prototype.append
5300 && BlobBuilder.prototype.getBlob;
5303 * Helper function that maps ArrayBufferViews to ArrayBuffers
5304 * Used by BlobBuilder constructor and old browsers that didn't
5305 * support it in the Blob constructor.
5308 function mapArrayBufferViews(ary) {
5309 return ary.map(function(chunk) {
5310 if (chunk.buffer instanceof ArrayBuffer) {
5311 var buf = chunk.buffer;
5313 // if this is a subarray, make a copy so we only
5314 // include the subarray region from the underlying buffer
5315 if (chunk.byteLength !== buf.byteLength) {
5316 var copy = new Uint8Array(chunk.byteLength);
5317 copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
5328 function BlobBuilderConstructor(ary, options) {
5329 options = options || {};
5331 var bb = new BlobBuilder();
5332 mapArrayBufferViews(ary).forEach(function(part) {
5336 return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
5339 function BlobConstructor(ary, options) {
5340 return new Blob(mapArrayBufferViews(ary), options || {});
5343 if (typeof Blob !== 'undefined') {
5344 BlobBuilderConstructor.prototype = Blob.prototype;
5345 BlobConstructor.prototype = Blob.prototype;
5348 module.exports = (function() {
5349 if (blobSupported) {
5350 return blobSupportsArrayBufferView ? Blob : BlobConstructor;
5351 } else if (blobBuilderSupported) {
5352 return BlobBuilderConstructor;
5361 /***/ (function(module, exports) {
5364 * Compiles a querystring
5365 * Returns string representation of the object
5371 exports.encode = function (obj) {
5374 for (var i in obj) {
5375 if (obj.hasOwnProperty(i)) {
5376 if (str.length) str += '&';
5377 str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
5385 * Parses a simple querystring into an object
5387 * @param {String} qs
5391 exports.decode = function(qs){
5393 var pairs = qs.split('&');
5394 for (var i = 0, l = pairs.length; i < l; i++) {
5395 var pair = pairs[i].split('=');
5396 qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
5404 /***/ (function(module, exports) {
5407 module.exports = function(a, b){
5408 var fn = function(){};
5409 fn.prototype = b.prototype;
5410 a.prototype = new fn;
5411 a.prototype.constructor = a;
5416 /***/ (function(module, exports) {
5420 var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
5428 * Return a string representing the specified number.
5430 * @param {Number} num The number to convert.
5431 * @returns {String} The string representation of the number.
5434 function encode(num) {
5438 encoded = alphabet[num % length] + encoded;
5439 num = Math.floor(num / length);
5446 * Return the integer value specified by the given string.
5448 * @param {String} str The string to convert.
5449 * @returns {Number} The integer value represented by the string.
5452 function decode(str) {
5455 for (i = 0; i < str.length; i++) {
5456 decoded = decoded * length + map[str.charAt(i)];
5463 * Yeast: A tiny growing id generator.
5465 * @returns {String} A unique id.
5469 var now = encode(+new Date());
5471 if (now !== prev) return seed = 0, prev = now;
5472 return now +'.'+ encode(seed++);
5476 // Map each character to its index.
5478 for (; i < length; i++) map[alphabet[i]] = i;
5481 // Expose the `yeast`, `encode` and `decode` functions.
5483 yeast.encode = encode;
5484 yeast.decode = decode;
5485 module.exports = yeast;
5490 /***/ (function(module, exports, __webpack_require__) {
5493 * Module requirements.
5496 var Polling = __webpack_require__(20);
5497 var inherit = __webpack_require__(31);
5498 var globalThis = __webpack_require__(18);
5504 module.exports = JSONPPolling;
5507 * Cached regular expressions.
5510 var rNewline = /\n/g;
5511 var rEscapedNewline = /\\n/g;
5514 * Global JSONP callbacks.
5523 function empty () { }
5526 * JSONP Polling constructor.
5528 * @param {Object} opts.
5532 function JSONPPolling (opts) {
5533 Polling.call(this, opts);
5535 this.query = this.query || {};
5537 // define global callbacks array if not present
5538 // we do this here (lazily) to avoid unneeded global pollution
5540 // we need to consider multiple engines in the same page
5541 callbacks = globalThis.___eio = (globalThis.___eio || []);
5544 // callback identifier
5545 this.index = callbacks.length;
5547 // add callback to jsonp global
5549 callbacks.push(function (msg) {
5553 // append to query string
5554 this.query.j = this.index;
5556 // prevent spurious errors from being emitted when the window is unloaded
5557 if (typeof addEventListener === 'function') {
5558 addEventListener('beforeunload', function () {
5559 if (self.script) self.script.onerror = empty;
5565 * Inherits from Polling.
5568 inherit(JSONPPolling, Polling);
5571 * JSONP only supports binary as base64 encoded strings
5574 JSONPPolling.prototype.supportsBinary = false;
5577 * Closes the socket.
5582 JSONPPolling.prototype.doClose = function () {
5584 this.script.parentNode.removeChild(this.script);
5589 this.form.parentNode.removeChild(this.form);
5594 Polling.prototype.doClose.call(this);
5598 * Starts a poll cycle.
5603 JSONPPolling.prototype.doPoll = function () {
5605 var script = document.createElement('script');
5608 this.script.parentNode.removeChild(this.script);
5612 script.async = true;
5613 script.src = this.uri();
5614 script.onerror = function (e) {
5615 self.onError('jsonp poll error', e);
5618 var insertAt = document.getElementsByTagName('script')[0];
5620 insertAt.parentNode.insertBefore(script, insertAt);
5622 (document.head || document.body).appendChild(script);
5624 this.script = script;
5626 var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
5629 setTimeout(function () {
5630 var iframe = document.createElement('iframe');
5631 document.body.appendChild(iframe);
5632 document.body.removeChild(iframe);
5638 * Writes with a hidden iframe.
5640 * @param {String} data to send
5641 * @param {Function} called upon flush.
5645 JSONPPolling.prototype.doWrite = function (data, fn) {
5649 var form = document.createElement('form');
5650 var area = document.createElement('textarea');
5651 var id = this.iframeId = 'eio_iframe_' + this.index;
5654 form.className = 'socketio';
5655 form.style.position = 'absolute';
5656 form.style.top = '-1000px';
5657 form.style.left = '-1000px';
5659 form.method = 'POST';
5660 form.setAttribute('accept-charset', 'utf-8');
5662 form.appendChild(area);
5663 document.body.appendChild(form);
5669 this.form.action = this.uri();
5671 function complete () {
5676 function initIframe () {
5679 self.form.removeChild(self.iframe);
5681 self.onError('jsonp polling iframe removal error', e);
5686 // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
5687 var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
5688 iframe = document.createElement(html);
5690 iframe = document.createElement('iframe');
5691 iframe.name = self.iframeId;
5692 iframe.src = 'javascript:0';
5695 iframe.id = self.iframeId;
5697 self.form.appendChild(iframe);
5698 self.iframe = iframe;
5703 // escape \n to prevent it from being converted into \r\n by some UAs
5704 // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
5705 data = data.replace(rEscapedNewline, '\\\n');
5706 this.area.value = data.replace(rNewline, '\\n');
5712 if (this.iframe.attachEvent) {
5713 this.iframe.onreadystatechange = function () {
5714 if (self.iframe.readyState === 'complete') {
5719 this.iframe.onload = complete;
5726 /***/ (function(module, exports, __webpack_require__) {
5729 * Module dependencies.
5732 var Transport = __webpack_require__(21);
5733 var parser = __webpack_require__(22);
5734 var parseqs = __webpack_require__(30);
5735 var inherit = __webpack_require__(31);
5736 var yeast = __webpack_require__(32);
5737 var debug = __webpack_require__(3)('engine.io-client:websocket');
5739 var BrowserWebSocket, NodeWebSocket;
5741 if (typeof WebSocket !== 'undefined') {
5742 BrowserWebSocket = WebSocket;
5743 } else if (typeof self !== 'undefined') {
5744 BrowserWebSocket = self.WebSocket || self.MozWebSocket;
5747 if (typeof window === 'undefined') {
5749 NodeWebSocket = __webpack_require__(35);
5754 * Get either the `WebSocket` or `MozWebSocket` globals
5755 * in the browser or try to resolve WebSocket-compatible
5756 * interface exposed by `ws` for Node-like environment.
5759 var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
5765 module.exports = WS;
5768 * WebSocket transport constructor.
5770 * @api {Object} connection options
5774 function WS (opts) {
5775 var forceBase64 = (opts && opts.forceBase64);
5777 this.supportsBinary = false;
5779 this.perMessageDeflate = opts.perMessageDeflate;
5780 this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
5781 this.protocols = opts.protocols;
5782 if (!this.usingBrowserWebSocket) {
5783 WebSocketImpl = NodeWebSocket;
5785 Transport.call(this, opts);
5789 * Inherits from Transport.
5792 inherit(WS, Transport);
5800 WS.prototype.name = 'websocket';
5803 * WebSockets support binary
5806 WS.prototype.supportsBinary = true;
5814 WS.prototype.doOpen = function () {
5815 if (!this.check()) {
5816 // let probe timeout
5820 var uri = this.uri();
5821 var protocols = this.protocols;
5825 if (!this.isReactNative) {
5826 opts.agent = this.agent;
5827 opts.perMessageDeflate = this.perMessageDeflate;
5829 // SSL options for Node.js client
5830 opts.pfx = this.pfx;
5831 opts.key = this.key;
5832 opts.passphrase = this.passphrase;
5833 opts.cert = this.cert;
5835 opts.ciphers = this.ciphers;
5836 opts.rejectUnauthorized = this.rejectUnauthorized;
5839 if (this.extraHeaders) {
5840 opts.headers = this.extraHeaders;
5842 if (this.localAddress) {
5843 opts.localAddress = this.localAddress;
5848 this.usingBrowserWebSocket && !this.isReactNative
5850 ? new WebSocketImpl(uri, protocols)
5851 : new WebSocketImpl(uri)
5852 : new WebSocketImpl(uri, protocols, opts);
5854 return this.emit('error', err);
5857 if (this.ws.binaryType === undefined) {
5858 this.supportsBinary = false;
5861 if (this.ws.supports && this.ws.supports.binary) {
5862 this.supportsBinary = true;
5863 this.ws.binaryType = 'nodebuffer';
5865 this.ws.binaryType = 'arraybuffer';
5868 this.addEventListeners();
5872 * Adds event listeners to the socket
5877 WS.prototype.addEventListeners = function () {
5880 this.ws.onopen = function () {
5883 this.ws.onclose = function () {
5886 this.ws.onmessage = function (ev) {
5887 self.onData(ev.data);
5889 this.ws.onerror = function (e) {
5890 self.onError('websocket error', e);
5895 * Writes data to socket.
5897 * @param {Array} array of packets.
5901 WS.prototype.write = function (packets) {
5903 this.writable = false;
5905 // encodePacket efficient as it uses WS framing
5906 // no need for encodePayload
5907 var total = packets.length;
5908 for (var i = 0, l = total; i < l; i++) {
5909 (function (packet) {
5910 parser.encodePacket(packet, self.supportsBinary, function (data) {
5911 if (!self.usingBrowserWebSocket) {
5912 // always create a new object (GH-437)
5914 if (packet.options) {
5915 opts.compress = packet.options.compress;
5918 if (self.perMessageDeflate) {
5919 var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
5920 if (len < self.perMessageDeflate.threshold) {
5921 opts.compress = false;
5926 // Sometimes the websocket has already been closed but the browser didn't
5927 // have a chance of informing us about it yet, in that case send will
5930 if (self.usingBrowserWebSocket) {
5931 // TypeError is thrown when passing the second argument on Safari
5934 self.ws.send(data, opts);
5937 debug('websocket closed before onclose event');
5949 // defer to next tick to allow Socket to clear writeBuffer
5950 setTimeout(function () {
5951 self.writable = true;
5963 WS.prototype.onClose = function () {
5964 Transport.prototype.onClose.call(this);
5973 WS.prototype.doClose = function () {
5974 if (typeof this.ws !== 'undefined') {
5980 * Generates uri for connection.
5985 WS.prototype.uri = function () {
5986 var query = this.query || {};
5987 var schema = this.secure ? 'wss' : 'ws';
5990 // avoid port if default for schema
5991 if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
5992 ('ws' === schema && Number(this.port) !== 80))) {
5993 port = ':' + this.port;
5996 // append timestamp to URI
5997 if (this.timestampRequests) {
5998 query[this.timestampParam] = yeast();
6001 // communicate binary support capabilities
6002 if (!this.supportsBinary) {
6006 query = parseqs.encode(query);
6008 // prepend ? to query
6010 query = '?' + query;
6013 var ipv6 = this.hostname.indexOf(':') !== -1;
6014 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
6018 * Feature detection for WebSocket.
6020 * @return {Boolean} whether this transport is available.
6024 WS.prototype.check = function () {
6025 return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
6031 /***/ (function(module, exports) {
6037 /***/ (function(module, exports) {
6040 var indexOf = [].indexOf;
6042 module.exports = function(arr, obj){
6043 if (indexOf) return arr.indexOf(obj);
6044 for (var i = 0; i < arr.length; ++i) {
6045 if (arr[i] === obj) return i;
6052 /***/ (function(module, exports, __webpack_require__) {
6056 * Module dependencies.
6059 var parser = __webpack_require__(7);
6060 var Emitter = __webpack_require__(8);
6061 var toArray = __webpack_require__(38);
6062 var on = __webpack_require__(39);
6063 var bind = __webpack_require__(40);
6064 var debug = __webpack_require__(3)('socket.io-client:socket');
6065 var parseqs = __webpack_require__(30);
6066 var hasBin = __webpack_require__(24);
6072 module.exports = exports = Socket;
6075 * Internal events (blacklisted).
6076 * These events can't be emitted by the user.
6089 reconnect_attempt: 1,
6090 reconnect_failed: 1,
6098 * Shortcut to `Emitter#emit`.
6101 var emit = Emitter.prototype.emit;
6104 * `Socket` constructor.
6109 function Socket (io, nsp, opts) {
6112 this.json = this; // compat
6115 this.receiveBuffer = [];
6116 this.sendBuffer = [];
6117 this.connected = false;
6118 this.disconnected = true;
6120 if (opts && opts.query) {
6121 this.query = opts.query;
6123 if (this.io.autoConnect) this.open();
6130 Emitter(Socket.prototype);
6133 * Subscribe to open, close and packet events
6138 Socket.prototype.subEvents = function () {
6139 if (this.subs) return;
6143 on(io, 'open', bind(this, 'onopen')),
6144 on(io, 'packet', bind(this, 'onpacket')),
6145 on(io, 'close', bind(this, 'onclose'))
6150 * "Opens" the socket.
6155 Socket.prototype.open =
6156 Socket.prototype.connect = function () {
6157 if (this.connected) return this;
6160 if (!this.io.reconnecting) this.io.open(); // ensure open
6161 if ('open' === this.io.readyState) this.onopen();
6162 this.emit('connecting');
6167 * Sends a `message` event.
6169 * @return {Socket} self
6173 Socket.prototype.send = function () {
6174 var args = toArray(arguments);
6175 args.unshift('message');
6176 this.emit.apply(this, args);
6182 * If the event is in `events`, it's emitted normally.
6184 * @param {String} event name
6185 * @return {Socket} self
6189 Socket.prototype.emit = function (ev) {
6190 if (events.hasOwnProperty(ev)) {
6191 emit.apply(this, arguments);
6195 var args = toArray(arguments);
6197 type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
6201 packet.options = {};
6202 packet.options.compress = !this.flags || false !== this.flags.compress;
6204 // event ack callback
6205 if ('function' === typeof args[args.length - 1]) {
6206 debug('emitting packet with ack id %d', this.ids);
6207 this.acks[this.ids] = args.pop();
6208 packet.id = this.ids++;
6211 if (this.connected) {
6212 this.packet(packet);
6214 this.sendBuffer.push(packet);
6225 * @param {Object} packet
6229 Socket.prototype.packet = function (packet) {
6230 packet.nsp = this.nsp;
6231 this.io.packet(packet);
6235 * Called upon engine `open`.
6240 Socket.prototype.onopen = function () {
6241 debug('transport is open - connecting');
6243 // write connect packet if necessary
6244 if ('/' !== this.nsp) {
6246 var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query;
6247 debug('sending connect packet with query %s', query);
6248 this.packet({type: parser.CONNECT, query: query});
6250 this.packet({type: parser.CONNECT});
6256 * Called upon engine `close`.
6258 * @param {String} reason
6262 Socket.prototype.onclose = function (reason) {
6263 debug('close (%s)', reason);
6264 this.connected = false;
6265 this.disconnected = true;
6267 this.emit('disconnect', reason);
6271 * Called with socket packet.
6273 * @param {Object} packet
6277 Socket.prototype.onpacket = function (packet) {
6278 var sameNamespace = packet.nsp === this.nsp;
6279 var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
6281 if (!sameNamespace && !rootNamespaceError) return;
6283 switch (packet.type) {
6284 case parser.CONNECT:
6289 this.onevent(packet);
6292 case parser.BINARY_EVENT:
6293 this.onevent(packet);
6300 case parser.BINARY_ACK:
6304 case parser.DISCONNECT:
6305 this.ondisconnect();
6309 this.emit('error', packet.data);
6315 * Called upon a server event.
6317 * @param {Object} packet
6321 Socket.prototype.onevent = function (packet) {
6322 var args = packet.data || [];
6323 debug('emitting event %j', args);
6325 if (null != packet.id) {
6326 debug('attaching ack callback to event');
6327 args.push(this.ack(packet.id));
6330 if (this.connected) {
6331 emit.apply(this, args);
6333 this.receiveBuffer.push(args);
6338 * Produces an ack callback to emit with an event.
6343 Socket.prototype.ack = function (id) {
6346 return function () {
6347 // prevent double callbacks
6350 var args = toArray(arguments);
6351 debug('sending ack %j', args);
6354 type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
6362 * Called upon a server acknowlegement.
6364 * @param {Object} packet
6368 Socket.prototype.onack = function (packet) {
6369 var ack = this.acks[packet.id];
6370 if ('function' === typeof ack) {
6371 debug('calling ack %s with %j', packet.id, packet.data);
6372 ack.apply(this, packet.data);
6373 delete this.acks[packet.id];
6375 debug('bad ack %s', packet.id);
6380 * Called upon server connect.
6385 Socket.prototype.onconnect = function () {
6386 this.connected = true;
6387 this.disconnected = false;
6388 this.emit('connect');
6389 this.emitBuffered();
6393 * Emit buffered events (received and emitted).
6398 Socket.prototype.emitBuffered = function () {
6400 for (i = 0; i < this.receiveBuffer.length; i++) {
6401 emit.apply(this, this.receiveBuffer[i]);
6403 this.receiveBuffer = [];
6405 for (i = 0; i < this.sendBuffer.length; i++) {
6406 this.packet(this.sendBuffer[i]);
6408 this.sendBuffer = [];
6412 * Called upon server disconnect.
6417 Socket.prototype.ondisconnect = function () {
6418 debug('server disconnect (%s)', this.nsp);
6420 this.onclose('io server disconnect');
6424 * Called upon forced client/server side disconnections,
6425 * this method ensures the manager stops tracking us and
6426 * that reconnections don't get triggered for this.
6431 Socket.prototype.destroy = function () {
6433 // clean subscriptions to avoid reconnections
6434 for (var i = 0; i < this.subs.length; i++) {
6435 this.subs[i].destroy();
6440 this.io.destroy(this);
6444 * Disconnects the socket manually.
6446 * @return {Socket} self
6450 Socket.prototype.close =
6451 Socket.prototype.disconnect = function () {
6452 if (this.connected) {
6453 debug('performing disconnect (%s)', this.nsp);
6454 this.packet({ type: parser.DISCONNECT });
6457 // remove socket from pool
6460 if (this.connected) {
6462 this.onclose('io client disconnect');
6468 * Sets the compress flag.
6470 * @param {Boolean} if `true`, compresses the sending data
6471 * @return {Socket} self
6475 Socket.prototype.compress = function (compress) {
6476 this.flags.compress = compress;
6481 * Sets the binary flag
6483 * @param {Boolean} whether the emitted data contains binary
6484 * @return {Socket} self
6488 Socket.prototype.binary = function (binary) {
6489 this.flags.binary = binary;
6496 /***/ (function(module, exports) {
6498 module.exports = toArray
6500 function toArray(list, index) {
6505 for (var i = index || 0; i < list.length; i++) {
6506 array[i - index] = list[i]
6515 /***/ (function(module, exports) {
6522 module.exports = on;
6525 * Helper for subscriptions.
6527 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
6528 * @param {String} event name
6529 * @param {Function} callback
6533 function on (obj, ev, fn) {
6536 destroy: function () {
6537 obj.removeListener(ev, fn);
6545 /***/ (function(module, exports) {
6551 var slice = [].slice;
6554 * Bind `obj` to `fn`.
6556 * @param {Object} obj
6557 * @param {Function|String} fn or string
6558 * @return {Function}
6562 module.exports = function(obj, fn){
6563 if ('string' == typeof fn) fn = obj[fn];
6564 if ('function' != typeof fn) throw new Error('bind() requires a function');
6565 var args = slice.call(arguments, 2);
6567 return fn.apply(obj, args.concat(slice.call(arguments)));
6574 /***/ (function(module, exports) {
6581 module.exports = Backoff;
6584 * Initialize backoff timer with `opts`.
6586 * - `min` initial timeout in milliseconds [100]
6587 * - `max` max timeout [10000]
6591 * @param {Object} opts
6595 function Backoff(opts) {
6597 this.ms = opts.min || 100;
6598 this.max = opts.max || 10000;
6599 this.factor = opts.factor || 2;
6600 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
6605 * Return the backoff duration.
6611 Backoff.prototype.duration = function(){
6612 var ms = this.ms * Math.pow(this.factor, this.attempts++);
6614 var rand = Math.random();
6615 var deviation = Math.floor(rand * this.jitter * ms);
6616 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
6618 return Math.min(ms, this.max) | 0;
6622 * Reset the number of attempts.
6627 Backoff.prototype.reset = function(){
6632 * Set the minimum duration
6637 Backoff.prototype.setMin = function(min){
6642 * Set the maximum duration
6647 Backoff.prototype.setMax = function(max){
6657 Backoff.prototype.setJitter = function(jitter){
6658 this.jitter = jitter;
6667 //# sourceMappingURL=socket.io.dev.js.map