12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435 |
- /*!
- * Engine.IO v6.2.2
- * (c) 2014-2022 Guillermo Rauch
- * Released under the MIT License.
- */
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.eio = factory());
- })(this, (function () { 'use strict';
- function _typeof(obj) {
- "@babel/helpers - typeof";
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
- return typeof obj;
- };
- } else {
- _typeof = function (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 _extends() {
- _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- 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 _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- 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 _construct(Parent, args, Class) {
- if (_isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
- }
- function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !_isNativeFunction(Class)) return Class;
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
- _cache.set(Class, Wrapper);
- }
- function Wrapper() {
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
- }
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return _setPrototypeOf(Wrapper, Class);
- };
- return _wrapNativeSuper(Class);
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- }
- return _assertThisInitialized(self);
- }
- 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 _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = _getPrototypeOf(object);
- if (object === null) break;
- }
- return object;
- }
- 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);
- }
- var PACKET_TYPES = Object.create(null); // no Map = no polyfill
- PACKET_TYPES["open"] = "0";
- PACKET_TYPES["close"] = "1";
- PACKET_TYPES["ping"] = "2";
- PACKET_TYPES["pong"] = "3";
- PACKET_TYPES["message"] = "4";
- PACKET_TYPES["upgrade"] = "5";
- PACKET_TYPES["noop"] = "6";
- var PACKET_TYPES_REVERSE = Object.create(null);
- Object.keys(PACKET_TYPES).forEach(function (key) {
- PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
- });
- var ERROR_PACKET = {
- type: "error",
- data: "parser error"
- };
- var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
- var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10
- var isView = function isView(obj) {
- return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
- };
- var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
- var type = _ref.type,
- data = _ref.data;
- if (withNativeBlob && data instanceof Blob) {
- if (supportsBinary) {
- return callback(data);
- } else {
- return encodeBlobAsBase64(data, callback);
- }
- } else if (withNativeArrayBuffer$1 && (data instanceof ArrayBuffer || isView(data))) {
- if (supportsBinary) {
- return callback(data);
- } else {
- return encodeBlobAsBase64(new Blob([data]), callback);
- }
- } // plain string
- return callback(PACKET_TYPES[type] + (data || ""));
- };
- var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
- var fileReader = new FileReader();
- fileReader.onload = function () {
- var content = fileReader.result.split(",")[1];
- callback("b" + content);
- };
- return fileReader.readAsDataURL(data);
- };
- /*
- * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
- * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
- * Released under MIT License
- */
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.
- var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
- for (var i$1 = 0; i$1 < chars.length; i$1++) {
- lookup[chars.charCodeAt(i$1)] = i$1;
- }
- var decode$1 = function decode(base64) {
- var bufferLength = base64.length * 0.75,
- len = base64.length,
- i,
- p = 0,
- encoded1,
- encoded2,
- encoded3,
- encoded4;
- if (base64[base64.length - 1] === '=') {
- bufferLength--;
- if (base64[base64.length - 2] === '=') {
- bufferLength--;
- }
- }
- var arraybuffer = new ArrayBuffer(bufferLength),
- bytes = new Uint8Array(arraybuffer);
- for (i = 0; i < len; i += 4) {
- encoded1 = lookup[base64.charCodeAt(i)];
- encoded2 = lookup[base64.charCodeAt(i + 1)];
- encoded3 = lookup[base64.charCodeAt(i + 2)];
- encoded4 = lookup[base64.charCodeAt(i + 3)];
- bytes[p++] = encoded1 << 2 | encoded2 >> 4;
- bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
- bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
- }
- return arraybuffer;
- };
- var withNativeArrayBuffer = typeof ArrayBuffer === "function";
- var decodePacket = function decodePacket(encodedPacket, binaryType) {
- if (typeof encodedPacket !== "string") {
- return {
- type: "message",
- data: mapBinary(encodedPacket, binaryType)
- };
- }
- var type = encodedPacket.charAt(0);
- if (type === "b") {
- return {
- type: "message",
- data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
- };
- }
- var packetType = PACKET_TYPES_REVERSE[type];
- if (!packetType) {
- return ERROR_PACKET;
- }
- return encodedPacket.length > 1 ? {
- type: PACKET_TYPES_REVERSE[type],
- data: encodedPacket.substring(1)
- } : {
- type: PACKET_TYPES_REVERSE[type]
- };
- };
- var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
- if (withNativeArrayBuffer) {
- var decoded = decode$1(data);
- return mapBinary(decoded, binaryType);
- } else {
- return {
- base64: true,
- data: data
- }; // fallback for old browsers
- }
- };
- var mapBinary = function mapBinary(data, binaryType) {
- switch (binaryType) {
- case "blob":
- return data instanceof ArrayBuffer ? new Blob([data]) : data;
- case "arraybuffer":
- default:
- return data;
- // assuming the data is already an ArrayBuffer
- }
- };
- var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
- var encodePayload = function encodePayload(packets, callback) {
- // some packets may be added to the array while encoding, so the initial length must be saved
- var length = packets.length;
- var encodedPackets = new Array(length);
- var count = 0;
- packets.forEach(function (packet, i) {
- // force base64 encoding for binary packets
- encodePacket(packet, false, function (encodedPacket) {
- encodedPackets[i] = encodedPacket;
- if (++count === length) {
- callback(encodedPackets.join(SEPARATOR));
- }
- });
- });
- };
- var decodePayload = function decodePayload(encodedPayload, binaryType) {
- var encodedPackets = encodedPayload.split(SEPARATOR);
- var packets = [];
- for (var i = 0; i < encodedPackets.length; i++) {
- var decodedPacket = decodePacket(encodedPackets[i], binaryType);
- packets.push(decodedPacket);
- if (decodedPacket.type === "error") {
- break;
- }
- }
- return packets;
- };
- var protocol = 4;
- /**
- * Initialize a new `Emitter`.
- *
- * @api public
- */
- function Emitter(obj) {
- if (obj) return mixin(obj);
- }
- /**
- * Mixin the emitter properties.
- *
- * @param {Object} obj
- * @return {Object}
- * @api private
- */
- function mixin(obj) {
- for (var key in Emitter.prototype) {
- obj[key] = Emitter.prototype[key];
- }
- return obj;
- }
- /**
- * Listen on the given `event` with `fn`.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
- Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
- this._callbacks = this._callbacks || {};
- (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
- return this;
- };
- /**
- * Adds an `event` listener that will be invoked a single
- * time then automatically removed.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
- Emitter.prototype.once = function (event, fn) {
- function on() {
- this.off(event, on);
- fn.apply(this, arguments);
- }
- on.fn = fn;
- this.on(event, on);
- return this;
- };
- /**
- * Remove the given callback for `event` or all
- * registered callbacks.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
- Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
- this._callbacks = this._callbacks || {}; // all
- if (0 == arguments.length) {
- this._callbacks = {};
- return this;
- } // specific event
- var callbacks = this._callbacks['$' + event];
- if (!callbacks) return this; // remove all handlers
- if (1 == arguments.length) {
- delete this._callbacks['$' + event];
- return this;
- } // remove specific handler
- var cb;
- for (var i = 0; i < callbacks.length; i++) {
- cb = callbacks[i];
- if (cb === fn || cb.fn === fn) {
- callbacks.splice(i, 1);
- break;
- }
- } // Remove event specific arrays for event types that no
- // one is subscribed for to avoid memory leak.
- if (callbacks.length === 0) {
- delete this._callbacks['$' + event];
- }
- return this;
- };
- /**
- * Emit `event` with the given args.
- *
- * @param {String} event
- * @param {Mixed} ...
- * @return {Emitter}
- */
- Emitter.prototype.emit = function (event) {
- this._callbacks = this._callbacks || {};
- var args = new Array(arguments.length - 1),
- callbacks = this._callbacks['$' + event];
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- if (callbacks) {
- callbacks = callbacks.slice(0);
- for (var i = 0, len = callbacks.length; i < len; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- return this;
- }; // alias used for reserved events (protected method)
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
- /**
- * Return array of callbacks for `event`.
- *
- * @param {String} event
- * @return {Array}
- * @api public
- */
- Emitter.prototype.listeners = function (event) {
- this._callbacks = this._callbacks || {};
- return this._callbacks['$' + event] || [];
- };
- /**
- * Check if this emitter has `event` handlers.
- *
- * @param {String} event
- * @return {Boolean}
- * @api public
- */
- Emitter.prototype.hasListeners = function (event) {
- return !!this.listeners(event).length;
- };
- var globalThisShim = function () {
- if (typeof self !== "undefined") {
- return self;
- } else if (typeof window !== "undefined") {
- return window;
- } else {
- return Function("return this")();
- }
- }();
- function pick(obj) {
- for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- attr[_key - 1] = arguments[_key];
- }
- return attr.reduce(function (acc, k) {
- if (obj.hasOwnProperty(k)) {
- acc[k] = obj[k];
- }
- return acc;
- }, {});
- } // Keep a reference to the real timeout functions so they can be used when overridden
- var NATIVE_SET_TIMEOUT = setTimeout;
- var NATIVE_CLEAR_TIMEOUT = clearTimeout;
- function installTimerFunctions(obj, opts) {
- if (opts.useNativeTimers) {
- obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
- obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
- } else {
- obj.setTimeoutFn = setTimeout.bind(globalThisShim);
- obj.clearTimeoutFn = clearTimeout.bind(globalThisShim);
- }
- } // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
- var BASE64_OVERHEAD = 1.33; // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
- function byteLength(obj) {
- if (typeof obj === "string") {
- return utf8Length(obj);
- } // arraybuffer or blob
- return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
- }
- function utf8Length(str) {
- var c = 0,
- length = 0;
- for (var i = 0, l = str.length; i < l; i++) {
- c = str.charCodeAt(i);
- if (c < 0x80) {
- length += 1;
- } else if (c < 0x800) {
- length += 2;
- } else if (c < 0xd800 || c >= 0xe000) {
- length += 3;
- } else {
- i++;
- length += 4;
- }
- }
- return length;
- }
- var TransportError = /*#__PURE__*/function (_Error) {
- _inherits(TransportError, _Error);
- var _super = _createSuper(TransportError);
- function TransportError(reason, description, context) {
- var _this;
- _classCallCheck(this, TransportError);
- _this = _super.call(this, reason);
- _this.description = description;
- _this.context = context;
- _this.type = "TransportError";
- return _this;
- }
- return TransportError;
- }( /*#__PURE__*/_wrapNativeSuper(Error));
- var Transport = /*#__PURE__*/function (_Emitter) {
- _inherits(Transport, _Emitter);
- var _super2 = _createSuper(Transport);
- /**
- * Transport abstract constructor.
- *
- * @param {Object} options.
- * @api private
- */
- function Transport(opts) {
- var _this2;
- _classCallCheck(this, Transport);
- _this2 = _super2.call(this);
- _this2.writable = false;
- installTimerFunctions(_assertThisInitialized(_this2), opts);
- _this2.opts = opts;
- _this2.query = opts.query;
- _this2.readyState = "";
- _this2.socket = opts.socket;
- return _this2;
- }
- /**
- * Emits an error.
- *
- * @param {String} reason
- * @param description
- * @param context - the error context
- * @return {Transport} for chaining
- * @api protected
- */
- _createClass(Transport, [{
- key: "onError",
- value: function onError(reason, description, context) {
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context));
- return this;
- }
- /**
- * Opens the transport.
- *
- * @api public
- */
- }, {
- key: "open",
- value: function open() {
- if ("closed" === this.readyState || "" === this.readyState) {
- this.readyState = "opening";
- this.doOpen();
- }
- return this;
- }
- /**
- * Closes the transport.
- *
- * @api public
- */
- }, {
- key: "close",
- value: function close() {
- if ("opening" === this.readyState || "open" === this.readyState) {
- this.doClose();
- this.onClose();
- }
- return this;
- }
- /**
- * Sends multiple packets.
- *
- * @param {Array} packets
- * @api public
- */
- }, {
- key: "send",
- value: function send(packets) {
- if ("open" === this.readyState) {
- this.write(packets);
- }
- }
- /**
- * Called upon open
- *
- * @api protected
- */
- }, {
- key: "onOpen",
- value: function onOpen() {
- this.readyState = "open";
- this.writable = true;
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open");
- }
- /**
- * Called with data.
- *
- * @param {String} data
- * @api protected
- */
- }, {
- key: "onData",
- value: function onData(data) {
- var packet = decodePacket(data, this.socket.binaryType);
- this.onPacket(packet);
- }
- /**
- * Called with a decoded packet.
- *
- * @api protected
- */
- }, {
- key: "onPacket",
- value: function onPacket(packet) {
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet);
- }
- /**
- * Called upon close.
- *
- * @api protected
- */
- }, {
- key: "onClose",
- value: function onClose(details) {
- this.readyState = "closed";
- _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details);
- }
- }]);
- return Transport;
- }(Emitter);
- // imported from https://github.com/unshiftio/yeast
- var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
- length = 64,
- map = {};
- var seed = 0,
- i = 0,
- prev;
- /**
- * Return a string representing the specified number.
- *
- * @param {Number} num The number to convert.
- * @returns {String} The string representation of the number.
- * @api public
- */
- function encode$1(num) {
- var encoded = '';
- do {
- encoded = alphabet[num % length] + encoded;
- num = Math.floor(num / length);
- } while (num > 0);
- return encoded;
- }
- /**
- * Yeast: A tiny growing id generator.
- *
- * @returns {String} A unique id.
- * @api public
- */
- function yeast() {
- var now = encode$1(+new Date());
- if (now !== prev) return seed = 0, prev = now;
- return now + '.' + encode$1(seed++);
- } //
- // Map each character to its index.
- //
- for (; i < length; i++) {
- map[alphabet[i]] = i;
- }
- // imported from https://github.com/galkn/querystring
- /**
- * Compiles a querystring
- * Returns string representation of the object
- *
- * @param {Object}
- * @api private
- */
- function encode(obj) {
- var str = '';
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- if (str.length) str += '&';
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
- }
- }
- return str;
- }
- /**
- * Parses a simple querystring into an object
- *
- * @param {String} qs
- * @api private
- */
- function decode(qs) {
- var qry = {};
- var pairs = qs.split('&');
- for (var i = 0, l = pairs.length; i < l; i++) {
- var pair = pairs[i].split('=');
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
- }
- return qry;
- }
- // imported from https://github.com/component/has-cors
- var value = false;
- try {
- value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
- } catch (err) {// if XMLHttp support is disabled in IE then it will throw
- // when trying to create
- }
- var hasCORS = value;
- // browser shim for xmlhttprequest module
- function XHR(opts) {
- var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE
- try {
- if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
- return new XMLHttpRequest();
- }
- } catch (e) {}
- if (!xdomain) {
- try {
- return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
- } catch (e) {}
- }
- }
- function empty() {}
- var hasXHR2 = function () {
- var xhr = new XHR({
- xdomain: false
- });
- return null != xhr.responseType;
- }();
- var Polling = /*#__PURE__*/function (_Transport) {
- _inherits(Polling, _Transport);
- var _super = _createSuper(Polling);
- /**
- * XHR Polling constructor.
- *
- * @param {Object} opts
- * @api public
- */
- function Polling(opts) {
- var _this;
- _classCallCheck(this, Polling);
- _this = _super.call(this, opts);
- _this.polling = false;
- if (typeof location !== "undefined") {
- var isSSL = "https:" === location.protocol;
- var port = location.port; // some user agents have empty `location.port`
- if (!port) {
- port = isSSL ? "443" : "80";
- }
- _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
- _this.xs = opts.secure !== isSSL;
- }
- /**
- * XHR supports binary
- */
- var forceBase64 = opts && opts.forceBase64;
- _this.supportsBinary = hasXHR2 && !forceBase64;
- return _this;
- }
- /**
- * Transport name.
- */
- _createClass(Polling, [{
- key: "doOpen",
- /**
- * Opens the socket (triggers polling). We write a PING message to determine
- * when the transport is open.
- *
- * @api private
- */
- value: function doOpen() {
- this.poll();
- }
- /**
- * Pauses polling.
- *
- * @param {Function} callback upon buffers are flushed and transport is paused
- * @api private
- */
- }, {
- key: "pause",
- value: function pause(onPause) {
- var _this2 = this;
- this.readyState = "pausing";
- var pause = function pause() {
- _this2.readyState = "paused";
- onPause();
- };
- if (this.polling || !this.writable) {
- var total = 0;
- if (this.polling) {
- total++;
- this.once("pollComplete", function () {
- --total || pause();
- });
- }
- if (!this.writable) {
- total++;
- this.once("drain", function () {
- --total || pause();
- });
- }
- } else {
- pause();
- }
- }
- /**
- * Starts polling cycle.
- *
- * @api public
- */
- }, {
- key: "poll",
- value: function poll() {
- this.polling = true;
- this.doPoll();
- this.emitReserved("poll");
- }
- /**
- * Overloads onData to detect payloads.
- *
- * @api private
- */
- }, {
- key: "onData",
- value: function onData(data) {
- var _this3 = this;
- var callback = function callback(packet) {
- // if its the first message we consider the transport open
- if ("opening" === _this3.readyState && packet.type === "open") {
- _this3.onOpen();
- } // if its a close packet, we close the ongoing requests
- if ("close" === packet.type) {
- _this3.onClose({
- description: "transport closed by the server"
- });
- return false;
- } // otherwise bypass onData and handle the message
- _this3.onPacket(packet);
- }; // decode payload
- decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing
- if ("closed" !== this.readyState) {
- // if we got data we're not polling
- this.polling = false;
- this.emitReserved("pollComplete");
- if ("open" === this.readyState) {
- this.poll();
- }
- }
- }
- /**
- * For polling, send a close packet.
- *
- * @api private
- */
- }, {
- key: "doClose",
- value: function doClose() {
- var _this4 = this;
- var close = function close() {
- _this4.write([{
- type: "close"
- }]);
- };
- if ("open" === this.readyState) {
- close();
- } else {
- // in case we're trying to close while
- // handshaking is in progress (GH-164)
- this.once("open", close);
- }
- }
- /**
- * Writes a packets payload.
- *
- * @param {Array} data packets
- * @param {Function} drain callback
- * @api private
- */
- }, {
- key: "write",
- value: function write(packets) {
- var _this5 = this;
- this.writable = false;
- encodePayload(packets, function (data) {
- _this5.doWrite(data, function () {
- _this5.writable = true;
- _this5.emitReserved("drain");
- });
- });
- }
- /**
- * Generates uri for connection.
- *
- * @api private
- */
- }, {
- key: "uri",
- value: function uri() {
- var query = this.query || {};
- var schema = this.opts.secure ? "https" : "http";
- var port = ""; // cache busting is forced
- if (false !== this.opts.timestampRequests) {
- query[this.opts.timestampParam] = yeast();
- }
- if (!this.supportsBinary && !query.sid) {
- query.b64 = 1;
- } // avoid port if default for schema
- if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) {
- port = ":" + this.opts.port;
- }
- var encodedQuery = encode(query);
- var ipv6 = this.opts.hostname.indexOf(":") !== -1;
- return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
- }
- /**
- * Creates a request.
- *
- * @param {String} method
- * @api private
- */
- }, {
- key: "request",
- value: function request() {
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- _extends(opts, {
- xd: this.xd,
- xs: this.xs
- }, this.opts);
- return new Request(this.uri(), opts);
- }
- /**
- * Sends data.
- *
- * @param {String} data to send.
- * @param {Function} called upon flush.
- * @api private
- */
- }, {
- key: "doWrite",
- value: function doWrite(data, fn) {
- var _this6 = this;
- var req = this.request({
- method: "POST",
- data: data
- });
- req.on("success", fn);
- req.on("error", function (xhrStatus, context) {
- _this6.onError("xhr post error", xhrStatus, context);
- });
- }
- /**
- * Starts a poll cycle.
- *
- * @api private
- */
- }, {
- key: "doPoll",
- value: function doPoll() {
- var _this7 = this;
- var req = this.request();
- req.on("data", this.onData.bind(this));
- req.on("error", function (xhrStatus, context) {
- _this7.onError("xhr poll error", xhrStatus, context);
- });
- this.pollXhr = req;
- }
- }, {
- key: "name",
- get: function get() {
- return "polling";
- }
- }]);
- return Polling;
- }(Transport);
- var Request = /*#__PURE__*/function (_Emitter) {
- _inherits(Request, _Emitter);
- var _super2 = _createSuper(Request);
- /**
- * Request constructor
- *
- * @param {Object} options
- * @api public
- */
- function Request(uri, opts) {
- var _this8;
- _classCallCheck(this, Request);
- _this8 = _super2.call(this);
- installTimerFunctions(_assertThisInitialized(_this8), opts);
- _this8.opts = opts;
- _this8.method = opts.method || "GET";
- _this8.uri = uri;
- _this8.async = false !== opts.async;
- _this8.data = undefined !== opts.data ? opts.data : null;
- _this8.create();
- return _this8;
- }
- /**
- * Creates the XHR object and sends the request.
- *
- * @api private
- */
- _createClass(Request, [{
- key: "create",
- value: function create() {
- var _this9 = this;
- var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
- opts.xdomain = !!this.opts.xd;
- opts.xscheme = !!this.opts.xs;
- var xhr = this.xhr = new XHR(opts);
- try {
- xhr.open(this.method, this.uri, this.async);
- try {
- if (this.opts.extraHeaders) {
- xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
- for (var i in this.opts.extraHeaders) {
- if (this.opts.extraHeaders.hasOwnProperty(i)) {
- xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
- }
- }
- }
- } catch (e) {}
- if ("POST" === this.method) {
- try {
- xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
- } catch (e) {}
- }
- try {
- xhr.setRequestHeader("Accept", "*/*");
- } catch (e) {} // ie6 check
- if ("withCredentials" in xhr) {
- xhr.withCredentials = this.opts.withCredentials;
- }
- if (this.opts.requestTimeout) {
- xhr.timeout = this.opts.requestTimeout;
- }
- xhr.onreadystatechange = function () {
- if (4 !== xhr.readyState) return;
- if (200 === xhr.status || 1223 === xhr.status) {
- _this9.onLoad();
- } else {
- // make sure the `error` event handler that's user-set
- // does not throw in the same tick and gets caught here
- _this9.setTimeoutFn(function () {
- _this9.onError(typeof xhr.status === "number" ? xhr.status : 0);
- }, 0);
- }
- };
- xhr.send(this.data);
- } catch (e) {
- // Need to defer since .create() is called directly from the constructor
- // and thus the 'error' event can only be only bound *after* this exception
- // occurs. Therefore, also, we cannot throw here at all.
- this.setTimeoutFn(function () {
- _this9.onError(e);
- }, 0);
- return;
- }
- if (typeof document !== "undefined") {
- this.index = Request.requestsCount++;
- Request.requests[this.index] = this;
- }
- }
- /**
- * Called upon error.
- *
- * @api private
- */
- }, {
- key: "onError",
- value: function onError(err) {
- this.emitReserved("error", err, this.xhr);
- this.cleanup(true);
- }
- /**
- * Cleans up house.
- *
- * @api private
- */
- }, {
- key: "cleanup",
- value: function cleanup(fromError) {
- if ("undefined" === typeof this.xhr || null === this.xhr) {
- return;
- }
- this.xhr.onreadystatechange = empty;
- if (fromError) {
- try {
- this.xhr.abort();
- } catch (e) {}
- }
- if (typeof document !== "undefined") {
- delete Request.requests[this.index];
- }
- this.xhr = null;
- }
- /**
- * Called upon load.
- *
- * @api private
- */
- }, {
- key: "onLoad",
- value: function onLoad() {
- var data = this.xhr.responseText;
- if (data !== null) {
- this.emitReserved("data", data);
- this.emitReserved("success");
- this.cleanup();
- }
- }
- /**
- * Aborts the request.
- *
- * @api public
- */
- }, {
- key: "abort",
- value: function abort() {
- this.cleanup();
- }
- }]);
- return Request;
- }(Emitter);
- Request.requestsCount = 0;
- Request.requests = {};
- /**
- * Aborts pending requests when unloading the window. This is needed to prevent
- * memory leaks (e.g. when using IE) and to ensure that no spurious error is
- * emitted.
- */
- if (typeof document !== "undefined") {
- // @ts-ignore
- if (typeof attachEvent === "function") {
- // @ts-ignore
- attachEvent("onunload", unloadHandler);
- } else if (typeof addEventListener === "function") {
- var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
- addEventListener(terminationEvent, unloadHandler, false);
- }
- }
- function unloadHandler() {
- for (var i in Request.requests) {
- if (Request.requests.hasOwnProperty(i)) {
- Request.requests[i].abort();
- }
- }
- }
- var nextTick = function () {
- var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
- if (isPromiseAvailable) {
- return function (cb) {
- return Promise.resolve().then(cb);
- };
- } else {
- return function (cb, setTimeoutFn) {
- return setTimeoutFn(cb, 0);
- };
- }
- }();
- var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
- var usingBrowserWebSocket = true;
- var defaultBinaryType = "arraybuffer";
- var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
- var WS = /*#__PURE__*/function (_Transport) {
- _inherits(WS, _Transport);
- var _super = _createSuper(WS);
- /**
- * WebSocket transport constructor.
- *
- * @api {Object} connection options
- * @api public
- */
- function WS(opts) {
- var _this;
- _classCallCheck(this, WS);
- _this = _super.call(this, opts);
- _this.supportsBinary = !opts.forceBase64;
- return _this;
- }
- /**
- * Transport name.
- *
- * @api public
- */
- _createClass(WS, [{
- key: "doOpen",
- /**
- * Opens socket.
- *
- * @api private
- */
- value: function doOpen() {
- if (!this.check()) {
- // let probe timeout
- return;
- }
- var uri = this.uri();
- var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed
- var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
- if (this.opts.extraHeaders) {
- opts.headers = this.opts.extraHeaders;
- }
- try {
- this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
- } catch (err) {
- return this.emitReserved("error", err);
- }
- this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
- this.addEventListeners();
- }
- /**
- * Adds event listeners to the socket
- *
- * @api private
- */
- }, {
- key: "addEventListeners",
- value: function addEventListeners() {
- var _this2 = this;
- this.ws.onopen = function () {
- if (_this2.opts.autoUnref) {
- _this2.ws._socket.unref();
- }
- _this2.onOpen();
- };
- this.ws.onclose = function (closeEvent) {
- return _this2.onClose({
- description: "websocket connection closed",
- context: closeEvent
- });
- };
- this.ws.onmessage = function (ev) {
- return _this2.onData(ev.data);
- };
- this.ws.onerror = function (e) {
- return _this2.onError("websocket error", e);
- };
- }
- /**
- * Writes data to socket.
- *
- * @param {Array} array of packets.
- * @api private
- */
- }, {
- key: "write",
- value: function write(packets) {
- var _this3 = this;
- this.writable = false; // encodePacket efficient as it uses WS framing
- // no need for encodePayload
- var _loop = function _loop(i) {
- var packet = packets[i];
- var lastPacket = i === packets.length - 1;
- encodePacket(packet, _this3.supportsBinary, function (data) {
- // always create a new object (GH-437)
- var opts = {};
- // have a chance of informing us about it yet, in that case send will
- // throw an error
- try {
- if (usingBrowserWebSocket) {
- // TypeError is thrown when passing the second argument on Safari
- _this3.ws.send(data);
- }
- } catch (e) {}
- if (lastPacket) {
- // fake drain
- // defer to next tick to allow Socket to clear writeBuffer
- nextTick(function () {
- _this3.writable = true;
- _this3.emitReserved("drain");
- }, _this3.setTimeoutFn);
- }
- });
- };
- for (var i = 0; i < packets.length; i++) {
- _loop(i);
- }
- }
- /**
- * Closes socket.
- *
- * @api private
- */
- }, {
- key: "doClose",
- value: function doClose() {
- if (typeof this.ws !== "undefined") {
- this.ws.close();
- this.ws = null;
- }
- }
- /**
- * Generates uri for connection.
- *
- * @api private
- */
- }, {
- key: "uri",
- value: function uri() {
- var query = this.query || {};
- var schema = this.opts.secure ? "wss" : "ws";
- var port = ""; // avoid port if default for schema
- if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) {
- port = ":" + this.opts.port;
- } // append timestamp to URI
- if (this.opts.timestampRequests) {
- query[this.opts.timestampParam] = yeast();
- } // communicate binary support capabilities
- if (!this.supportsBinary) {
- query.b64 = 1;
- }
- var encodedQuery = encode(query);
- var ipv6 = this.opts.hostname.indexOf(":") !== -1;
- return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
- }
- /**
- * Feature detection for WebSocket.
- *
- * @return {Boolean} whether this transport is available.
- * @api public
- */
- }, {
- key: "check",
- value: function check() {
- return !!WebSocket;
- }
- }, {
- key: "name",
- get: function get() {
- return "websocket";
- }
- }]);
- return WS;
- }(Transport);
- var transports = {
- websocket: WS,
- polling: Polling
- };
- // imported from https://github.com/galkn/parseuri
- /**
- * Parses an URI
- *
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
- * @api private
- */
- var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
- var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
- function parse(str) {
- var src = str,
- b = str.indexOf('['),
- e = str.indexOf(']');
- if (b != -1 && e != -1) {
- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
- }
- var m = re.exec(str || ''),
- uri = {},
- i = 14;
- while (i--) {
- uri[parts[i]] = m[i] || '';
- }
- if (b != -1 && e != -1) {
- uri.source = src;
- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
- uri.ipv6uri = true;
- }
- uri.pathNames = pathNames(uri, uri['path']);
- uri.queryKey = queryKey(uri, uri['query']);
- return uri;
- }
- function pathNames(obj, path) {
- var regx = /\/{2,9}/g,
- names = path.replace(regx, "/").split("/");
- if (path.substr(0, 1) == '/' || path.length === 0) {
- names.splice(0, 1);
- }
- if (path.substr(path.length - 1, 1) == '/') {
- names.splice(names.length - 1, 1);
- }
- return names;
- }
- function queryKey(uri, query) {
- var data = {};
- query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
- if ($1) {
- data[$1] = $2;
- }
- });
- return data;
- }
- var Socket = /*#__PURE__*/function (_Emitter) {
- _inherits(Socket, _Emitter);
- var _super = _createSuper(Socket);
- /**
- * Socket constructor.
- *
- * @param {String|Object} uri or options
- * @param {Object} opts - options
- * @api public
- */
- function Socket(uri) {
- var _this;
- var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- _classCallCheck(this, Socket);
- _this = _super.call(this);
- if (uri && "object" === _typeof(uri)) {
- opts = uri;
- uri = null;
- }
- if (uri) {
- uri = parse(uri);
- opts.hostname = uri.host;
- opts.secure = uri.protocol === "https" || uri.protocol === "wss";
- opts.port = uri.port;
- if (uri.query) opts.query = uri.query;
- } else if (opts.host) {
- opts.hostname = parse(opts.host).host;
- }
- installTimerFunctions(_assertThisInitialized(_this), opts);
- _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
- if (opts.hostname && !opts.port) {
- // if no port is specified manually, use the protocol default
- opts.port = _this.secure ? "443" : "80";
- }
- _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
- _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
- _this.transports = opts.transports || ["polling", "websocket"];
- _this.readyState = "";
- _this.writeBuffer = [];
- _this.prevBufferLen = 0;
- _this.opts = _extends({
- path: "/engine.io",
- agent: false,
- withCredentials: false,
- upgrade: true,
- timestampParam: "t",
- rememberUpgrade: false,
- rejectUnauthorized: true,
- perMessageDeflate: {
- threshold: 1024
- },
- transportOptions: {},
- closeOnBeforeunload: true
- }, opts);
- _this.opts.path = _this.opts.path.replace(/\/$/, "") + "/";
- if (typeof _this.opts.query === "string") {
- _this.opts.query = decode(_this.opts.query);
- } // set on handshake
- _this.id = null;
- _this.upgrades = null;
- _this.pingInterval = null;
- _this.pingTimeout = null; // set on heartbeat
- _this.pingTimeoutTimer = null;
- if (typeof addEventListener === "function") {
- if (_this.opts.closeOnBeforeunload) {
- // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
- // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
- // closed/reloaded)
- addEventListener("beforeunload", function () {
- if (_this.transport) {
- // silently close the transport
- _this.transport.removeAllListeners();
- _this.transport.close();
- }
- }, false);
- }
- if (_this.hostname !== "localhost") {
- _this.offlineEventListener = function () {
- _this.onClose("transport close", {
- description: "network connection lost"
- });
- };
- addEventListener("offline", _this.offlineEventListener, false);
- }
- }
- _this.open();
- return _this;
- }
- /**
- * Creates transport of the given type.
- *
- * @param {String} transport name
- * @return {Transport}
- * @api private
- */
- _createClass(Socket, [{
- key: "createTransport",
- value: function createTransport(name) {
- var query = _extends({}, this.opts.query); // append engine.io protocol identifier
- query.EIO = protocol; // transport name
- query.transport = name; // session id if we already have one
- if (this.id) query.sid = this.id;
- var opts = _extends({}, this.opts.transportOptions[name], this.opts, {
- query: query,
- socket: this,
- hostname: this.hostname,
- secure: this.secure,
- port: this.port
- });
- return new transports[name](opts);
- }
- /**
- * Initializes transport to use and starts probe.
- *
- * @api private
- */
- }, {
- key: "open",
- value: function open() {
- var _this2 = this;
- var transport;
- if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
- transport = "websocket";
- } else if (0 === this.transports.length) {
- // Emit error on next tick so it can be listened to
- this.setTimeoutFn(function () {
- _this2.emitReserved("error", "No transports available");
- }, 0);
- return;
- } else {
- transport = this.transports[0];
- }
- this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false)
- try {
- transport = this.createTransport(transport);
- } catch (e) {
- this.transports.shift();
- this.open();
- return;
- }
- transport.open();
- this.setTransport(transport);
- }
- /**
- * Sets the current transport. Disables the existing one (if any).
- *
- * @api private
- */
- }, {
- key: "setTransport",
- value: function setTransport(transport) {
- var _this3 = this;
- if (this.transport) {
- this.transport.removeAllListeners();
- } // set up transport
- this.transport = transport; // set up transport listeners
- transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) {
- return _this3.onClose("transport close", reason);
- });
- }
- /**
- * Probes a transport.
- *
- * @param {String} transport name
- * @api private
- */
- }, {
- key: "probe",
- value: function probe(name) {
- var _this4 = this;
- var transport = this.createTransport(name);
- var failed = false;
- Socket.priorWebsocketSuccess = false;
- var onTransportOpen = function onTransportOpen() {
- if (failed) return;
- transport.send([{
- type: "ping",
- data: "probe"
- }]);
- transport.once("packet", function (msg) {
- if (failed) return;
- if ("pong" === msg.type && "probe" === msg.data) {
- _this4.upgrading = true;
- _this4.emitReserved("upgrading", transport);
- if (!transport) return;
- Socket.priorWebsocketSuccess = "websocket" === transport.name;
- _this4.transport.pause(function () {
- if (failed) return;
- if ("closed" === _this4.readyState) return;
- cleanup();
- _this4.setTransport(transport);
- transport.send([{
- type: "upgrade"
- }]);
- _this4.emitReserved("upgrade", transport);
- transport = null;
- _this4.upgrading = false;
- _this4.flush();
- });
- } else {
- var err = new Error("probe error"); // @ts-ignore
- err.transport = transport.name;
- _this4.emitReserved("upgradeError", err);
- }
- });
- };
- function freezeTransport() {
- if (failed) return; // Any callback called by transport should be ignored since now
- failed = true;
- cleanup();
- transport.close();
- transport = null;
- } // Handle any error that happens while probing
- var onerror = function onerror(err) {
- var error = new Error("probe error: " + err); // @ts-ignore
- error.transport = transport.name;
- freezeTransport();
- _this4.emitReserved("upgradeError", error);
- };
- function onTransportClose() {
- onerror("transport closed");
- } // When the socket is closed while we're probing
- function onclose() {
- onerror("socket closed");
- } // When the socket is upgraded while we're probing
- function onupgrade(to) {
- if (transport && to.name !== transport.name) {
- freezeTransport();
- }
- } // Remove all listeners on the transport and on self
- var cleanup = function cleanup() {
- transport.removeListener("open", onTransportOpen);
- transport.removeListener("error", onerror);
- transport.removeListener("close", onTransportClose);
- _this4.off("close", onclose);
- _this4.off("upgrading", onupgrade);
- };
- transport.once("open", onTransportOpen);
- transport.once("error", onerror);
- transport.once("close", onTransportClose);
- this.once("close", onclose);
- this.once("upgrading", onupgrade);
- transport.open();
- }
- /**
- * Called when connection is deemed open.
- *
- * @api private
- */
- }, {
- key: "onOpen",
- value: function onOpen() {
- this.readyState = "open";
- Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
- this.emitReserved("open");
- this.flush(); // we check for `readyState` in case an `open`
- // listener already closed the socket
- if ("open" === this.readyState && this.opts.upgrade && this.transport.pause) {
- var i = 0;
- var l = this.upgrades.length;
- for (; i < l; i++) {
- this.probe(this.upgrades[i]);
- }
- }
- }
- /**
- * Handles a packet.
- *
- * @api private
- */
- }, {
- key: "onPacket",
- value: function onPacket(packet) {
- if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
- this.emitReserved("packet", packet); // Socket is live - any packet counts
- this.emitReserved("heartbeat");
- switch (packet.type) {
- case "open":
- this.onHandshake(JSON.parse(packet.data));
- break;
- case "ping":
- this.resetPingTimeout();
- this.sendPacket("pong");
- this.emitReserved("ping");
- this.emitReserved("pong");
- break;
- case "error":
- var err = new Error("server error"); // @ts-ignore
- err.code = packet.data;
- this.onError(err);
- break;
- case "message":
- this.emitReserved("data", packet.data);
- this.emitReserved("message", packet.data);
- break;
- }
- }
- }
- /**
- * Called upon handshake completion.
- *
- * @param {Object} data - handshake obj
- * @api private
- */
- }, {
- key: "onHandshake",
- value: function onHandshake(data) {
- this.emitReserved("handshake", data);
- this.id = data.sid;
- this.transport.query.sid = data.sid;
- this.upgrades = this.filterUpgrades(data.upgrades);
- this.pingInterval = data.pingInterval;
- this.pingTimeout = data.pingTimeout;
- this.maxPayload = data.maxPayload;
- this.onOpen(); // In case open handler closes socket
- if ("closed" === this.readyState) return;
- this.resetPingTimeout();
- }
- /**
- * Sets and resets ping timeout timer based on server pings.
- *
- * @api private
- */
- }, {
- key: "resetPingTimeout",
- value: function resetPingTimeout() {
- var _this5 = this;
- this.clearTimeoutFn(this.pingTimeoutTimer);
- this.pingTimeoutTimer = this.setTimeoutFn(function () {
- _this5.onClose("ping timeout");
- }, this.pingInterval + this.pingTimeout);
- if (this.opts.autoUnref) {
- this.pingTimeoutTimer.unref();
- }
- }
- /**
- * Called on `drain` event
- *
- * @api private
- */
- }, {
- key: "onDrain",
- value: function onDrain() {
- this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important
- // for example, when upgrading, upgrade packet is sent over,
- // and a nonzero prevBufferLen could cause problems on `drain`
- this.prevBufferLen = 0;
- if (0 === this.writeBuffer.length) {
- this.emitReserved("drain");
- } else {
- this.flush();
- }
- }
- /**
- * Flush write buffers.
- *
- * @api private
- */
- }, {
- key: "flush",
- value: function flush() {
- if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
- var packets = this.getWritablePackets();
- this.transport.send(packets); // keep track of current length of writeBuffer
- // splice writeBuffer and callbackBuffer on `drain`
- this.prevBufferLen = packets.length;
- this.emitReserved("flush");
- }
- }
- /**
- * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
- * long-polling)
- *
- * @private
- */
- }, {
- key: "getWritablePackets",
- value: function getWritablePackets() {
- var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
- if (!shouldCheckPayloadSize) {
- return this.writeBuffer;
- }
- var payloadSize = 1; // first packet type
- for (var i = 0; i < this.writeBuffer.length; i++) {
- var data = this.writeBuffer[i].data;
- if (data) {
- payloadSize += byteLength(data);
- }
- if (i > 0 && payloadSize > this.maxPayload) {
- return this.writeBuffer.slice(0, i);
- }
- payloadSize += 2; // separator + packet type
- }
- return this.writeBuffer;
- }
- /**
- * Sends a message.
- *
- * @param {String} message.
- * @param {Function} callback function.
- * @param {Object} options.
- * @return {Socket} for chaining.
- * @api public
- */
- }, {
- key: "write",
- value: function write(msg, options, fn) {
- this.sendPacket("message", msg, options, fn);
- return this;
- }
- }, {
- key: "send",
- value: function send(msg, options, fn) {
- this.sendPacket("message", msg, options, fn);
- return this;
- }
- /**
- * Sends a packet.
- *
- * @param {String} packet type.
- * @param {String} data.
- * @param {Object} options.
- * @param {Function} callback function.
- * @api private
- */
- }, {
- key: "sendPacket",
- value: function sendPacket(type, data, options, fn) {
- if ("function" === typeof data) {
- fn = data;
- data = undefined;
- }
- if ("function" === typeof options) {
- fn = options;
- options = null;
- }
- if ("closing" === this.readyState || "closed" === this.readyState) {
- return;
- }
- options = options || {};
- options.compress = false !== options.compress;
- var packet = {
- type: type,
- data: data,
- options: options
- };
- this.emitReserved("packetCreate", packet);
- this.writeBuffer.push(packet);
- if (fn) this.once("flush", fn);
- this.flush();
- }
- /**
- * Closes the connection.
- *
- * @api public
- */
- }, {
- key: "close",
- value: function close() {
- var _this6 = this;
- var close = function close() {
- _this6.onClose("forced close");
- _this6.transport.close();
- };
- var cleanupAndClose = function cleanupAndClose() {
- _this6.off("upgrade", cleanupAndClose);
- _this6.off("upgradeError", cleanupAndClose);
- close();
- };
- var waitForUpgrade = function waitForUpgrade() {
- // wait for upgrade to finish since we can't send packets while pausing a transport
- _this6.once("upgrade", cleanupAndClose);
- _this6.once("upgradeError", cleanupAndClose);
- };
- if ("opening" === this.readyState || "open" === this.readyState) {
- this.readyState = "closing";
- if (this.writeBuffer.length) {
- this.once("drain", function () {
- if (_this6.upgrading) {
- waitForUpgrade();
- } else {
- close();
- }
- });
- } else if (this.upgrading) {
- waitForUpgrade();
- } else {
- close();
- }
- }
- return this;
- }
- /**
- * Called upon transport error
- *
- * @api private
- */
- }, {
- key: "onError",
- value: function onError(err) {
- Socket.priorWebsocketSuccess = false;
- this.emitReserved("error", err);
- this.onClose("transport error", err);
- }
- /**
- * Called upon transport close.
- *
- * @api private
- */
- }, {
- key: "onClose",
- value: function onClose(reason, description) {
- if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
- // clear timers
- this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport
- this.transport.removeAllListeners("close"); // ensure transport won't stay open
- this.transport.close(); // ignore further transport communication
- this.transport.removeAllListeners();
- if (typeof removeEventListener === "function") {
- removeEventListener("offline", this.offlineEventListener, false);
- } // set ready state
- this.readyState = "closed"; // clear session id
- this.id = null; // emit close event
- this.emitReserved("close", reason, description); // clean buffers after, so users can still
- // grab the buffers on `close` event
- this.writeBuffer = [];
- this.prevBufferLen = 0;
- }
- }
- /**
- * Filters upgrades, returning only those matching client transports.
- *
- * @param {Array} server upgrades
- * @api private
- *
- */
- }, {
- key: "filterUpgrades",
- value: function filterUpgrades(upgrades) {
- var filteredUpgrades = [];
- var i = 0;
- var j = upgrades.length;
- for (; i < j; i++) {
- if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
- }
- return filteredUpgrades;
- }
- }]);
- return Socket;
- }(Emitter);
- Socket.protocol = protocol;
- var browserEntrypoint = (function (uri, opts) {
- return new Socket(uri, opts);
- });
- return browserEntrypoint;
- }));
- //# sourceMappingURL=engine.io.js.map
|