UNPKG

socket.io-client

Version:

[![Build Status](https://github.com/socketio/socket.io-client/workflows/CI/badge.svg?branch=master)](https://github.com/socketio/socket.io-client/actions) [![Dependency Status](https://david-dm.org/socketio/socket.io-client.svg)](https://david-dm.org/sock

1,608 lines (1,330 loc) 185 kB
/*! * Socket.IO v4.0.0 * (c) 2014-2021 Guillermo Rauch * Released under the MIT License. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["io"] = factory(); else root["io"] = factory(); })(self, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./build/index.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./build/index.js": /*!************************!*\ !*** ./build/index.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports.Socket = exports.io = exports.Manager = exports.protocol = void 0; var url_1 = __webpack_require__(/*! ./url */ "./build/url.js"); var manager_1 = __webpack_require__(/*! ./manager */ "./build/manager.js"); var socket_1 = __webpack_require__(/*! ./socket */ "./build/socket.js"); Object.defineProperty(exports, "Socket", { enumerable: true, get: function get() { return socket_1.Socket; } }); var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")("socket.io-client"); /** * Module exports. */ module.exports = exports = lookup; /** * Managers cache. */ var cache = exports.managers = {}; function lookup(uri, opts) { if (_typeof(uri) === "object") { opts = uri; uri = undefined; } opts = opts || {}; var parsed = url_1.url(uri, opts.path); var source = parsed.source; var id = parsed.id; var path = parsed.path; var sameNamespace = cache[id] && path in cache[id]["nsps"]; var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace; var io; if (newConnection) { debug("ignoring socket cache for %s", source); io = new manager_1.Manager(source, opts); } else { if (!cache[id]) { debug("new io instance for %s", source); cache[id] = new manager_1.Manager(source, opts); } io = cache[id]; } if (parsed.query && !opts.query) { opts.query = parsed.queryKey; } return io.socket(parsed.path, opts); } exports.io = lookup; /** * Protocol version. * * @public */ var socket_io_parser_1 = __webpack_require__(/*! socket.io-parser */ "./node_modules/socket.io-parser/dist/index.js"); Object.defineProperty(exports, "protocol", { enumerable: true, get: function get() { return socket_io_parser_1.protocol; } }); /** * `connect`. * * @param {String} uri * @public */ exports.connect = lookup; /** * Expose constructors for standalone build. * * @public */ var manager_2 = __webpack_require__(/*! ./manager */ "./build/manager.js"); Object.defineProperty(exports, "Manager", { enumerable: true, get: function get() { return manager_2.Manager; } }); /***/ }), /***/ "./build/manager.js": /*!**************************!*\ !*** ./build/manager.js ***! \**************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.Manager = void 0; var eio = __webpack_require__(/*! engine.io-client */ "./node_modules/engine.io-client/lib/index.js"); var socket_1 = __webpack_require__(/*! ./socket */ "./build/socket.js"); var parser = __webpack_require__(/*! socket.io-parser */ "./node_modules/socket.io-parser/dist/index.js"); var on_1 = __webpack_require__(/*! ./on */ "./build/on.js"); var Backoff = __webpack_require__(/*! backo2 */ "./node_modules/backo2/index.js"); var typed_events_1 = __webpack_require__(/*! ./typed-events */ "./build/typed-events.js"); var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")("socket.io-client:manager"); var Manager = /*#__PURE__*/function (_typed_events_1$Stric) { _inherits(Manager, _typed_events_1$Stric); var _super = _createSuper(Manager); function Manager(uri, opts) { var _this; _classCallCheck(this, Manager); _this = _super.call(this); _this.nsps = {}; _this.subs = []; if (uri && "object" === _typeof(uri)) { opts = uri; uri = undefined; } opts = opts || {}; opts.path = opts.path || "/socket.io"; _this.opts = opts; _this.reconnection(opts.reconnection !== false); _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); _this.reconnectionDelay(opts.reconnectionDelay || 1000); _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); _this.randomizationFactor(opts.randomizationFactor || 0.5); _this.backoff = new Backoff({ min: _this.reconnectionDelay(), max: _this.reconnectionDelayMax(), jitter: _this.randomizationFactor() }); _this.timeout(null == opts.timeout ? 20000 : opts.timeout); _this._readyState = "closed"; _this.uri = uri; var _parser = opts.parser || parser; _this.encoder = new _parser.Encoder(); _this.decoder = new _parser.Decoder(); _this._autoConnect = opts.autoConnect !== false; if (_this._autoConnect) _this.open(); return _this; } _createClass(Manager, [{ key: "reconnection", value: function reconnection(v) { if (!arguments.length) return this._reconnection; this._reconnection = !!v; return this; } }, { key: "reconnectionAttempts", value: function reconnectionAttempts(v) { if (v === undefined) return this._reconnectionAttempts; this._reconnectionAttempts = v; return this; } }, { key: "reconnectionDelay", value: function reconnectionDelay(v) { var _a; if (v === undefined) return this._reconnectionDelay; this._reconnectionDelay = v; (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v); return this; } }, { key: "randomizationFactor", value: function randomizationFactor(v) { var _a; if (v === undefined) return this._randomizationFactor; this._randomizationFactor = v; (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v); return this; } }, { key: "reconnectionDelayMax", value: function reconnectionDelayMax(v) { var _a; if (v === undefined) return this._reconnectionDelayMax; this._reconnectionDelayMax = v; (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v); return this; } }, { key: "timeout", value: function timeout(v) { if (!arguments.length) return this._timeout; this._timeout = v; return this; } /** * Starts trying to reconnect if reconnection is enabled and we have not * started reconnecting yet * * @private */ }, { key: "maybeReconnectOnOpen", value: function maybeReconnectOnOpen() { // Only try to reconnect if it's the first time we're connecting if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) { // keeps reconnection from firing twice for the same reconnection loop this.reconnect(); } } /** * Sets the current transport `socket`. * * @param {Function} fn - optional, callback * @return self * @public */ }, { key: "open", value: function open(fn) { var _this2 = this; debug("readyState %s", this._readyState); if (~this._readyState.indexOf("open")) return this; debug("opening %s", this.uri); this.engine = eio(this.uri, this.opts); var socket = this.engine; var self = this; this._readyState = "opening"; this.skipReconnect = false; // emit `open` var openSubDestroy = on_1.on(socket, "open", function () { self.onopen(); fn && fn(); }); // emit `error` var errorSub = on_1.on(socket, "error", function (err) { debug("error"); self.cleanup(); self._readyState = "closed"; _this2.emitReserved("error", err); if (fn) { fn(err); } else { // Only do this if there is no fn to handle the error self.maybeReconnectOnOpen(); } }); if (false !== this._timeout) { var timeout = this._timeout; debug("connect attempt will timeout after %d", timeout); if (timeout === 0) { openSubDestroy(); // prevents a race condition with the 'open' event } // set timer var timer = setTimeout(function () { debug("connect attempt timed out after %d", timeout); openSubDestroy(); socket.close(); socket.emit("error", new Error("timeout")); }, timeout); if (this.opts.autoUnref) { timer.unref(); } this.subs.push(function subDestroy() { clearTimeout(timer); }); } this.subs.push(openSubDestroy); this.subs.push(errorSub); return this; } /** * Alias for open() * * @return self * @public */ }, { key: "connect", value: function connect(fn) { return this.open(fn); } /** * Called upon transport open. * * @private */ }, { key: "onopen", value: function onopen() { debug("open"); // clear old subs this.cleanup(); // mark as open this._readyState = "open"; this.emitReserved("open"); // add new subs var socket = this.engine; this.subs.push(on_1.on(socket, "ping", this.onping.bind(this)), on_1.on(socket, "data", this.ondata.bind(this)), on_1.on(socket, "error", this.onerror.bind(this)), on_1.on(socket, "close", this.onclose.bind(this)), on_1.on(this.decoder, "decoded", this.ondecoded.bind(this))); } /** * Called upon a ping. * * @private */ }, { key: "onping", value: function onping() { this.emitReserved("ping"); } /** * Called with data. * * @private */ }, { key: "ondata", value: function ondata(data) { this.decoder.add(data); } /** * Called when parser fully decodes a packet. * * @private */ }, { key: "ondecoded", value: function ondecoded(packet) { this.emitReserved("packet", packet); } /** * Called upon socket error. * * @private */ }, { key: "onerror", value: function onerror(err) { debug("error", err); this.emitReserved("error", err); } /** * Creates a new socket for the given `nsp`. * * @return {Socket} * @public */ }, { key: "socket", value: function socket(nsp, opts) { var socket = this.nsps[nsp]; if (!socket) { socket = new socket_1.Socket(this, nsp, opts); this.nsps[nsp] = socket; } return socket; } /** * Called upon a socket close. * * @param socket * @private */ }, { key: "_destroy", value: function _destroy(socket) { var nsps = Object.keys(this.nsps); for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) { var nsp = _nsps[_i]; var _socket = this.nsps[nsp]; if (_socket.active) { debug("socket %s is still active, skipping close", nsp); return; } } this._close(); } /** * Writes a packet. * * @param packet * @private */ }, { key: "_packet", value: function _packet(packet) { debug("writing packet %j", packet); var encodedPackets = this.encoder.encode(packet); for (var i = 0; i < encodedPackets.length; i++) { this.engine.write(encodedPackets[i], packet.options); } } /** * Clean up transport subscriptions and packet buffer. * * @private */ }, { key: "cleanup", value: function cleanup() { debug("cleanup"); this.subs.forEach(function (subDestroy) { return subDestroy(); }); this.subs.length = 0; this.decoder.destroy(); } /** * Close the current socket. * * @private */ }, { key: "_close", value: function _close() { debug("disconnect"); this.skipReconnect = true; this._reconnecting = false; if ("opening" === this._readyState) { // `onclose` will not fire because // an open event never happened this.cleanup(); } this.backoff.reset(); this._readyState = "closed"; if (this.engine) this.engine.close(); } /** * Alias for close() * * @private */ }, { key: "disconnect", value: function disconnect() { return this._close(); } /** * Called upon engine close. * * @private */ }, { key: "onclose", value: function onclose(reason) { debug("onclose"); this.cleanup(); this.backoff.reset(); this._readyState = "closed"; this.emitReserved("close", reason); if (this._reconnection && !this.skipReconnect) { this.reconnect(); } } /** * Attempt a reconnection. * * @private */ }, { key: "reconnect", value: function reconnect() { var _this3 = this; if (this._reconnecting || this.skipReconnect) return this; var self = this; if (this.backoff.attempts >= this._reconnectionAttempts) { debug("reconnect failed"); this.backoff.reset(); this.emitReserved("reconnect_failed"); this._reconnecting = false; } else { var delay = this.backoff.duration(); debug("will wait %dms before reconnect attempt", delay); this._reconnecting = true; var timer = setTimeout(function () { if (self.skipReconnect) return; debug("attempting reconnect"); _this3.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events if (self.skipReconnect) return; self.open(function (err) { if (err) { debug("reconnect attempt error"); self._reconnecting = false; self.reconnect(); _this3.emitReserved("reconnect_error", err); } else { debug("reconnect success"); self.onreconnect(); } }); }, delay); if (this.opts.autoUnref) { timer.unref(); } this.subs.push(function subDestroy() { clearTimeout(timer); }); } } /** * Called upon successful reconnect. * * @private */ }, { key: "onreconnect", value: function onreconnect() { var attempt = this.backoff.attempts; this._reconnecting = false; this.backoff.reset(); this.emitReserved("reconnect", attempt); } }]); return Manager; }(typed_events_1.StrictEventEmitter); exports.Manager = Manager; /***/ }), /***/ "./build/on.js": /*!*********************!*\ !*** ./build/on.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.on = void 0; function on(obj, ev, fn) { obj.on(ev, fn); return function subDestroy() { obj.off(ev, fn); }; } exports.on = on; /***/ }), /***/ "./build/socket.js": /*!*************************!*\ !*** ./build/socket.js ***! \*************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.Socket = void 0; var socket_io_parser_1 = __webpack_require__(/*! socket.io-parser */ "./node_modules/socket.io-parser/dist/index.js"); var on_1 = __webpack_require__(/*! ./on */ "./build/on.js"); var typed_events_1 = __webpack_require__(/*! ./typed-events */ "./build/typed-events.js"); var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")("socket.io-client:socket"); /** * Internal events. * These events can't be emitted by the user. */ var RESERVED_EVENTS = Object.freeze({ connect: 1, connect_error: 1, disconnect: 1, disconnecting: 1, // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener newListener: 1, removeListener: 1 }); var Socket = /*#__PURE__*/function (_typed_events_1$Stric) { _inherits(Socket, _typed_events_1$Stric); var _super = _createSuper(Socket); /** * `Socket` constructor. * * @public */ function Socket(io, nsp, opts) { var _this; _classCallCheck(this, Socket); _this = _super.call(this); _this.receiveBuffer = []; _this.sendBuffer = []; _this.ids = 0; _this.acks = {}; _this.flags = {}; _this.io = io; _this.nsp = nsp; _this.ids = 0; _this.acks = {}; _this.receiveBuffer = []; _this.sendBuffer = []; _this.connected = false; _this.disconnected = true; _this.flags = {}; if (opts && opts.auth) { _this.auth = opts.auth; } if (_this.io._autoConnect) _this.open(); return _this; } /** * Subscribe to open, close and packet events * * @private */ _createClass(Socket, [{ key: "subEvents", value: function subEvents() { if (this.subs) return; var io = this.io; this.subs = [on_1.on(io, "open", this.onopen.bind(this)), on_1.on(io, "packet", this.onpacket.bind(this)), on_1.on(io, "error", this.onerror.bind(this)), on_1.on(io, "close", this.onclose.bind(this))]; } /** * Whether the Socket will try to reconnect when its Manager connects or reconnects */ }, { key: "connect", /** * "Opens" the socket. * * @public */ value: function connect() { if (this.connected) return this; this.subEvents(); if (!this.io["_reconnecting"]) this.io.open(); // ensure open if ("open" === this.io._readyState) this.onopen(); return this; } /** * Alias for connect() */ }, { key: "open", value: function open() { return this.connect(); } /** * Sends a `message` event. * * @return self * @public */ }, { key: "send", value: function send() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift("message"); this.emit.apply(this, args); return this; } /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @return self * @public */ }, { key: "emit", value: function emit(ev) { if (RESERVED_EVENTS.hasOwnProperty(ev)) { throw new Error('"' + ev + '" is a reserved event name'); } for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } args.unshift(ev); var packet = { type: socket_io_parser_1.PacketType.EVENT, data: args }; packet.options = {}; packet.options.compress = this.flags.compress !== false; // event ack callback if ("function" === typeof args[args.length - 1]) { debug("emitting packet with ack id %d", this.ids); this.acks[this.ids] = args.pop(); packet.id = this.ids++; } var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable; var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected); if (discardPacket) { debug("discard packet as the transport is not currently writable"); } else if (this.connected) { this.packet(packet); } else { this.sendBuffer.push(packet); } this.flags = {}; return this; } /** * Sends a packet. * * @param packet * @private */ }, { key: "packet", value: function packet(_packet) { _packet.nsp = this.nsp; this.io._packet(_packet); } /** * Called upon engine `open`. * * @private */ }, { key: "onopen", value: function onopen() { var _this2 = this; debug("transport is open - connecting"); if (typeof this.auth == "function") { this.auth(function (data) { _this2.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: data }); }); } else { this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: this.auth }); } } /** * Called upon engine or manager `error`. * * @param err * @private */ }, { key: "onerror", value: function onerror(err) { if (!this.connected) { this.emitReserved("connect_error", err); } } /** * Called upon engine `close`. * * @param reason * @private */ }, { key: "onclose", value: function onclose(reason) { debug("close (%s)", reason); this.connected = false; this.disconnected = true; delete this.id; this.emitReserved("disconnect", reason); } /** * Called with socket packet. * * @param packet * @private */ }, { key: "onpacket", value: function onpacket(packet) { var sameNamespace = packet.nsp === this.nsp; if (!sameNamespace) return; switch (packet.type) { case socket_io_parser_1.PacketType.CONNECT: if (packet.data && packet.data.sid) { var id = packet.data.sid; this.onconnect(id); } else { this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)")); } break; case socket_io_parser_1.PacketType.EVENT: this.onevent(packet); break; case socket_io_parser_1.PacketType.BINARY_EVENT: this.onevent(packet); break; case socket_io_parser_1.PacketType.ACK: this.onack(packet); break; case socket_io_parser_1.PacketType.BINARY_ACK: this.onack(packet); break; case socket_io_parser_1.PacketType.DISCONNECT: this.ondisconnect(); break; case socket_io_parser_1.PacketType.CONNECT_ERROR: var err = new Error(packet.data.message); // @ts-ignore err.data = packet.data.data; this.emitReserved("connect_error", err); break; } } /** * Called upon a server event. * * @param packet * @private */ }, { key: "onevent", value: function onevent(packet) { var args = packet.data || []; debug("emitting event %j", args); if (null != packet.id) { debug("attaching ack callback to event"); args.push(this.ack(packet.id)); } if (this.connected) { this.emitEvent(args); } else { this.receiveBuffer.push(Object.freeze(args)); } } }, { key: "emitEvent", value: function emitEvent(args) { if (this._anyListeners && this._anyListeners.length) { var listeners = this._anyListeners.slice(); var _iterator = _createForOfIteratorHelper(listeners), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var listener = _step.value; listener.apply(this, args); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args); } /** * Produces an ack callback to emit with an event. * * @private */ }, { key: "ack", value: function ack(id) { var self = this; var sent = false; return function () { // prevent double callbacks if (sent) return; sent = true; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } debug("sending ack %j", args); self.packet({ type: socket_io_parser_1.PacketType.ACK, id: id, data: args }); }; } /** * Called upon a server acknowlegement. * * @param packet * @private */ }, { key: "onack", value: function onack(packet) { var ack = this.acks[packet.id]; if ("function" === typeof ack) { debug("calling ack %s with %j", packet.id, packet.data); ack.apply(this, packet.data); delete this.acks[packet.id]; } else { debug("bad ack %s", packet.id); } } /** * Called upon server connect. * * @private */ }, { key: "onconnect", value: function onconnect(id) { debug("socket connected with id %s", id); this.id = id; this.connected = true; this.disconnected = false; this.emitReserved("connect"); this.emitBuffered(); } /** * Emit buffered events (received and emitted). * * @private */ }, { key: "emitBuffered", value: function emitBuffered() { var _this3 = this; this.receiveBuffer.forEach(function (args) { return _this3.emitEvent(args); }); this.receiveBuffer = []; this.sendBuffer.forEach(function (packet) { return _this3.packet(packet); }); this.sendBuffer = []; } /** * Called upon server disconnect. * * @private */ }, { key: "ondisconnect", value: function ondisconnect() { debug("server disconnect (%s)", this.nsp); this.destroy(); this.onclose("io server disconnect"); } /** * Called upon forced client/server side disconnections, * this method ensures the manager stops tracking us and * that reconnections don't get triggered for this. * * @private */ }, { key: "destroy", value: function destroy() { if (this.subs) { // clean subscriptions to avoid reconnections this.subs.forEach(function (subDestroy) { return subDestroy(); }); this.subs = undefined; } this.io["_destroy"](this); } /** * Disconnects the socket manually. * * @return self * @public */ }, { key: "disconnect", value: function disconnect() { if (this.connected) { debug("performing disconnect (%s)", this.nsp); this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT }); } // remove socket from pool this.destroy(); if (this.connected) { // fire events this.onclose("io client disconnect"); } return this; } /** * Alias for disconnect() * * @return self * @public */ }, { key: "close", value: function close() { return this.disconnect(); } /** * Sets the compress flag. * * @param compress - if `true`, compresses the sending data * @return self * @public */ }, { key: "compress", value: function compress(_compress) { this.flags.compress = _compress; return this; } /** * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not * ready to send messages. * * @returns self * @public */ }, { key: "onAny", /** * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the * callback. * * @param listener * @public */ value: function onAny(listener) { this._anyListeners = this._anyListeners || []; this._anyListeners.push(listener); return this; } /** * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the * callback. The listener is added to the beginning of the listeners array. * * @param listener * @public */ }, { key: "prependAny", value: function prependAny(listener) { this._anyListeners = this._anyListeners || []; this._anyListeners.unshift(listener); return this; } /** * Removes the listener that will be fired when any event is emitted. * * @param listener * @public */ }, { key: "offAny", value: function offAny(listener) { if (!this._anyListeners) { return this; } if (listener) { var listeners = this._anyListeners; for (var i = 0; i < listeners.length; i++) { if (listener === listeners[i]) { listeners.splice(i, 1); return this; } } } else { this._anyListeners = []; } return this; } /** * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, * e.g. to remove listeners. * * @public */ }, { key: "listenersAny", value: function listenersAny() { return this._anyListeners || []; } }, { key: "active", get: function get() { return !!this.subs; } }, { key: "volatile", get: function get() { this.flags["volatile"] = true; return this; } }]); return Socket; }(typed_events_1.StrictEventEmitter); exports.Socket = Socket; /***/ }), /***/ "./build/typed-events.js": /*!*******************************!*\ !*** ./build/typed-events.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.StrictEventEmitter = void 0; var Emitter = __webpack_require__(/*! component-emitter */ "./node_modules/component-emitter/index.js"); /** * Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type * parameters for mappings of event names to event data types, and strictly * types method calls to the `EventEmitter` according to these event maps. * * @typeParam ListenEvents - `EventsMap` of user-defined events that can be * listened to with `on` or `once` * @typeParam EmitEvents - `EventsMap` of user-defined events that can be * emitted with `emit` * @typeParam ReservedEvents - `EventsMap` of reserved events, that can be * emitted by socket.io with `emitReserved`, and can be listened to with * `listen`. */ var StrictEventEmitter = /*#__PURE__*/function (_Emitter) { _inherits(StrictEventEmitter, _Emitter); var _super = _createSuper(StrictEventEmitter); function StrictEventEmitter() { _classCallCheck(this, StrictEventEmitter); return _super.apply(this, arguments); } _createClass(StrictEventEmitter, [{ key: "on", /** * Adds the `listener` function as an event listener for `ev`. * * @param ev Name of the event * @param listener Callback function */ value: function on(ev, listener) { _get(_getPrototypeOf(StrictEventEmitter.prototype), "on", this).call(this, ev, listener); return this; } /** * Adds a one-time `listener` function as an event listener for `ev`. * * @param ev Name of the event * @param listener Callback function */ }, { key: "once", value: function once(ev, listener) { _get(_getPrototypeOf(StrictEventEmitter.prototype), "once", this).call(this, ev, listener); return this; } /** * Emits an event. * * @param ev Name of the event * @param args Values to send to listeners of this event */ }, { key: "emit", value: function emit(ev) { var _get2; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } (_get2 = _get(_getPrototypeOf(StrictEventEmitter.prototype), "emit", this)).call.apply(_get2, [this, ev].concat(args)); return this; } /** * Emits a reserved event. * * This method is `protected`, so that only a class extending * `StrictEventEmitter` can emit its own reserved events. * * @param ev Reserved event name * @param args Arguments to emit along with the event */ }, { key: "emitReserved", value: function emitReserved(ev) { var _get3; for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } (_get3 = _get(_getPrototypeOf(StrictEventEmitter.prototype), "emit", this)).call.apply(_get3, [this, ev].concat(args)); return this; } /** * Returns the listeners listening to an event. * * @param event Event name * @returns Array of listeners subscribed to `event` */ }, { key: "listeners", value: function listeners(event) { return _get(_getPrototypeOf(StrictEventEmitter.prototype), "listeners", this).call(this, event); } }]); return StrictEventEmitter; }(Emitter); exports.StrictEventEmitter = StrictEventEmitter; /***/ }), /***/ "./build/url.js": /*!**********************!*\ !*** ./build/url.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.url = void 0; var parseuri = __webpack_require__(/*! parseuri */ "./node_modules/parseuri/index.js"); var debug = __webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js")("socket.io-c