UNPKG

@casipe/react-service-provider

Version:
1,558 lines (1,529 loc) 767 kB
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, 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 o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); } function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); } function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } import React, { createContext, useEffect, useState, useContext } from 'react'; import Axios from 'axios'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ var _extendStatics = function extendStatics(d, b) { _extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return _extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); _extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var _assign = function __assign() { _assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return _assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function sent() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function next() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; 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$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]"; var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10 var isView$1 = function isView$1(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$1 && data instanceof Blob) { if (supportsBinary) { return callback(data); } else { return encodeBlobAsBase64(data, callback); } } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(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); }; function toArray(data) { if (data instanceof Uint8Array) { return data; } else if (data instanceof ArrayBuffer) { return new Uint8Array(data); } else { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); } } var TEXT_ENCODER; function encodePacketToBinary(packet, callback) { if (withNativeBlob$1 && packet.data instanceof Blob) { return packet.data.arrayBuffer().then(toArray).then(callback); } else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) { return callback(toArray(packet.data)); } encodePacket(packet, false, function (encoded) { if (!TEXT_ENCODER) { TEXT_ENCODER = new TextEncoder(); } callback(TEXT_ENCODER.encode(encoded)); }); } // imported from https://github.com/socketio/base64-arraybuffer var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index. var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup$1[chars.charCodeAt(i)] = i; } var decode$1 = function decode$1(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$1[base64.charCodeAt(i)]; encoded2 = lookup$1[base64.charCodeAt(i + 1)]; encoded3 = lookup$1[base64.charCodeAt(i + 2)]; encoded4 = lookup$1[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$1 = 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$1) { 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": if (data instanceof Blob) { // from WebSocket + binaryType "blob" return data; } else { // from HTTP long-polling or WebTransport return new Blob([data]); } case "arraybuffer": default: if (data instanceof ArrayBuffer) { // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer" return data; } else { // from WebTransport (Uint8Array) return data.buffer; } } }; 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 _i2 = 0; _i2 < encodedPackets.length; _i2++) { var decodedPacket = decodePacket(encodedPackets[_i2], binaryType); packets.push(decodedPacket); if (decodedPacket.type === "error") { break; } } return packets; }; function createPacketEncoderStream() { return new TransformStream({ transform: function transform(packet, controller) { encodePacketToBinary(packet, function (encodedPacket) { var payloadLength = encodedPacket.length; var header; // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length if (payloadLength < 126) { header = new Uint8Array(1); new DataView(header.buffer).setUint8(0, payloadLength); } else if (payloadLength < 65536) { header = new Uint8Array(3); var view = new DataView(header.buffer); view.setUint8(0, 126); view.setUint16(1, payloadLength); } else { header = new Uint8Array(9); var _view = new DataView(header.buffer); _view.setUint8(0, 127); _view.setBigUint64(1, BigInt(payloadLength)); } // first bit indicates whether the payload is plain text (0) or binary (1) if (packet.data && typeof packet.data !== "string") { header[0] |= 0x80; } controller.enqueue(header); controller.enqueue(encodedPacket); }); } }); } var TEXT_DECODER; function totalLength(chunks) { return chunks.reduce(function (acc, chunk) { return acc + chunk.length; }, 0); } function concatChunks(chunks, size) { if (chunks[0].length === size) { return chunks.shift(); } var buffer = new Uint8Array(size); var j = 0; for (var _i3 = 0; _i3 < size; _i3++) { buffer[_i3] = chunks[0][j++]; if (j === chunks[0].length) { chunks.shift(); j = 0; } } if (chunks.length && j < chunks[0].length) { chunks[0] = chunks[0].slice(j); } return buffer; } function createPacketDecoderStream(maxPayload, binaryType) { if (!TEXT_DECODER) { TEXT_DECODER = new TextDecoder(); } var chunks = []; var state = 0 /* State.READ_HEADER */; var expectedLength = -1; var isBinary = false; return new TransformStream({ transform: function transform(chunk, controller) { chunks.push(chunk); while (true) { if (state === 0 /* State.READ_HEADER */) { if (totalLength(chunks) < 1) { break; } var header = concatChunks(chunks, 1); isBinary = (header[0] & 0x80) === 0x80; expectedLength = header[0] & 0x7f; if (expectedLength < 126) { state = 3 /* State.READ_PAYLOAD */; } else if (expectedLength === 126) { state = 1 /* State.READ_EXTENDED_LENGTH_16 */; } else { state = 2 /* State.READ_EXTENDED_LENGTH_64 */; } } else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) { if (totalLength(chunks) < 2) { break; } var headerArray = concatChunks(chunks, 2); expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0); state = 3 /* State.READ_PAYLOAD */; } else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) { if (totalLength(chunks) < 8) { break; } var _headerArray = concatChunks(chunks, 8); var view = new DataView(_headerArray.buffer, _headerArray.byteOffset, _headerArray.length); var n = view.getUint32(0); if (n > Math.pow(2, 53 - 32) - 1) { // the maximum safe integer in JavaScript is 2^53 - 1 controller.enqueue(ERROR_PACKET); break; } expectedLength = n * Math.pow(2, 32) + view.getUint32(4); state = 3 /* State.READ_PAYLOAD */; } else { if (totalLength(chunks) < expectedLength) { break; } var data = concatChunks(chunks, expectedLength); controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType)); state = 0 /* State.READ_HEADER */; } if (expectedLength === 0 || expectedLength > maxPayload) { controller.enqueue(ERROR_PACKET); break; } } } }); } var protocol$1 = 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 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 globalThisShim = function () { if (typeof self !== "undefined") { return self; } else if (typeof window !== "undefined") { return window; } else { return Function("return this")(); } }(); var defaultBinaryType = "arraybuffer"; function createCookieJar() {} 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 = globalThisShim.setTimeout; var NATIVE_CLEAR_TIMEOUT = globalThisShim.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 = globalThisShim.setTimeout.bind(globalThisShim); obj.clearTimeoutFn = globalThisShim.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 _i4 = 0, l = str.length; _i4 < l; _i4++) { c = str.charCodeAt(_i4); if (c < 0x80) { length += 1; } else if (c < 0x800) { length += 2; } else if (c < 0xd800 || c >= 0xe000) { length += 3; } else { _i4++; length += 4; } } return length; } /** * Generates a random 8-characters string. */ function randomString() { return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5); } // 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 _i5 in obj) { if (obj.hasOwnProperty(_i5)) { if (str.length) str += '&'; str += encodeURIComponent(_i5) + '=' + encodeURIComponent(obj[_i5]); } } 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 _i6 = 0, l = pairs.length; _i6 < l; _i6++) { var pair = pairs[_i6].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; } var TransportError = /*#__PURE__*/function (_Error) { function TransportError(reason, description, context) { var _this2; _classCallCheck(this, TransportError); _this2 = _callSuper(this, TransportError, [reason]); _this2.description = description; _this2.context = context; _this2.type = "TransportError"; return _this2; } _inherits(TransportError, _Error); return _createClass(TransportError); }(/*#__PURE__*/_wrapNativeSuper(Error)); var Transport = /*#__PURE__*/function (_Emitter) { /** * Transport abstract constructor. * * @param {Object} opts - options * @protected */ function Transport(opts) { var _this3; _classCallCheck(this, Transport); _this3 = _callSuper(this, Transport); _this3.writable = false; installTimerFunctions(_this3, opts); _this3.opts = opts; _this3.query = opts.query; _this3.socket = opts.socket; _this3.supportsBinary = !opts.forceBase64; return _this3; } /** * Emits an error. * * @param {String} reason * @param description * @param context - the error context * @return {Transport} for chaining * @protected */ _inherits(Transport, _Emitter); return _createClass(Transport, [{ key: "onError", value: function onError(reason, description, context) { _superPropGet(Transport, "emitReserved", this, 3)(["error", new TransportError(reason, description, context)]); return this; } /** * Opens the transport. */ }, { key: "open", value: function open() { this.readyState = "opening"; this.doOpen(); return this; } /** * Closes the transport. */ }, { key: "close", value: function close() { if (this.readyState === "opening" || this.readyState === "open") { this.doClose(); this.onClose(); } return this; } /** * Sends multiple packets. * * @param {Array} packets */ }, { key: "send", value: function send(packets) { if (this.readyState === "open") { this.write(packets); } } /** * Called upon open * * @protected */ }, { key: "onOpen", value: function onOpen() { this.readyState = "open"; this.writable = true; _superPropGet(Transport, "emitReserved", this, 3)(["open"]); } /** * Called with data. * * @param {String} data * @protected */ }, { key: "onData", value: function onData(data) { var packet = decodePacket(data, this.socket.binaryType); this.onPacket(packet); } /** * Called with a decoded packet. * * @protected */ }, { key: "onPacket", value: function onPacket(packet) { _superPropGet(Transport, "emitReserved", this, 3)(["packet", packet]); } /** * Called upon close. * * @protected */ }, { key: "onClose", value: function onClose(details) { this.readyState = "closed"; _superPropGet(Transport, "emitReserved", this, 3)(["close", details]); } /** * Pauses the transport, in order not to lose packets during an upgrade. * * @param onPause */ }, { key: "pause", value: function pause(onPause) {} }, { key: "createUri", value: function createUri(schema) { var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query); } }, { key: "_hostname", value: function _hostname() { var hostname = this.opts.hostname; return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]"; } }, { key: "_port", value: function _port() { if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) { return ":" + this.opts.port; } else { return ""; } } }, { key: "_query", value: function _query(query) { var encodedQuery = encode(query); return encodedQuery.length ? "?" + encodedQuery : ""; } }]); }(Emitter); var Polling = /*#__PURE__*/function (_Transport) { function Polling() { var _this4; _classCallCheck(this, Polling); _this4 = _callSuper(this, Polling, arguments); _this4._polling = false; return _this4; } _inherits(Polling, _Transport); return _createClass(Polling, [{ key: "name", get: function get() { return "polling"; } /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @protected */ }, { key: "doOpen", value: function doOpen() { this._poll(); } /** * Pauses polling. * * @param {Function} onPause - callback upon buffers are flushed and transport is paused * @package */ }, { key: "pause", value: function pause(onPause) { var _this5 = this; this.readyState = "pausing"; var pause = function pause() { _this5.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. * * @private */ }, { key: "_poll", value: function _poll() { this._polling = true; this.doPoll(); this.emitReserved("poll"); } /** * Overloads onData to detect payloads. * * @protected */ }, { key: "onData", value: function onData(data) { var _this6 = this; var callback = function callback(packet) { // if its the first message we consider the transport open if ("opening" === _this6.readyState && packet.type === "open") { _this6.onOpen(); } // if its a close packet, we close the ongoing requests if ("close" === packet.type) { _this6.onClose({ description: "transport closed by the server" }); return false; } // otherwise bypass onData and handle the message _this6.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. * * @protected */ }, { key: "doClose", value: function doClose() { var _this7 = this; var close = function close() { _this7.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} packets - data packets * @protected */ }, { key: "write", value: function write(packets) { var _this8 = this; this.writable = false; encodePayload(packets, function (data) { _this8.doWrite(data, function () { _this8.writable = true; _this8.emitReserved("drain"); }); }); } /** * Generates uri for connection. * * @private */ }, { key: "uri", value: function uri() { var schema = this.opts.secure ? "https" : "http"; var query = this.query || {}; // cache busting is forced if (false !== this.opts.timestampRequests) { query[this.opts.timestampParam] = randomString(); } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } return this.createUri(schema, query); } }]); }(Transport); // 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; function empty() {} var BaseXHR = /*#__PURE__*/function (_Polling) { /** * XHR Polling constructor. * * @param {Object} opts * @package */ function BaseXHR(opts) { var _this9; _classCallCheck(this, BaseXHR); _this9 = _callSuper(this, BaseXHR, [opts]); 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"; } _this9.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port; } return _this9; } /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @private */ _inherits(BaseXHR, _Polling); return _createClass(BaseXHR, [{ key: "doWrite", value: function doWrite(data, fn) { var _this0 = this; var req = this.request({ method: "POST", data: data }); req.on("success", fn); req.on("error", function (xhrStatus, context) { _this0.onError("xhr post error", xhrStatus, context); }); } /** * Starts a poll cycle. * * @private */ }, { key: "doPoll", value: function doPoll() { var _this1 = this; var req = this.request(); req.on("data", this.onData.bind(this)); req.on("error", function (xhrStatus, context) { _this1.onError("xhr poll error", xhrStatus, context); }); this.pollXhr = req; } }]); }(Polling); var Request = /*#__PURE__*/function (_Emitter2) { /** * Request constructor * * @param {Object} options * @package */ function Request(createRequest, uri, opts) { var _this10; _classCallCheck(this, Request); _this10 = _callSuper(this, Request); _this10.createRequest = createRequest; installTimerFunctions(_this10, opts); _this10._opts = opts; _this10._method = opts.method || "GET"; _this10._uri = uri; _this10._data = undefined !== opts.data ? opts.data : null; _this10._create(); return _this10; } /** * Creates the XHR object and sends the request. * * @private */ _inherits(Request, _Emitter2); return _createClass(Request, [{ key: "_create", value: function _create() { var _this11 = this; var _a; var opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); opts.xdomain = !!this._opts.xd; var xhr = this._xhr = this.createRequest(opts); try { xhr.open(this._method, this._uri, true); try { if (this._opts.extraHeaders) { // @ts-ignore xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); for (var _i7 in this._opts.extraHeaders) { if (this._opts.extraHeaders.hasOwnProperty(_i7)) { xhr.setRequestHeader(_i7, this._opts.extraHeaders[_i7]); } } } } catch (e) {} if ("POST" === this._method) { try { xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); } catch (e) {} } try { xhr.setRequestHeader("Accept", "*/*"); } catch (e) {} (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr); // ie6 check if ("withCredentials" in xhr) { xhr.withCredentials = this._opts.withCredentials; } if (this._opts.requestTimeout) { xhr.timeout = this._opts.requestTimeout; } xhr.onreadystatechange = function () { var _a; if (xhr.readyState === 3) { (_a = _this11._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies( // @ts-ignore xhr.getResponseHeader("set-cookie")); } if (4 !== xhr.readyState) return; if (200 === xhr.status || 1223 === xhr.status) { _this11._onLoad(); } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here _this11.setTimeoutFn(function () { _this11._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 () { _this11._onError(e); }, 0); return; } if (typeof document !== "undefined") { this._index = Request.requestsCount++; Request.requests[this._index] = this; } } /** * Called upon error. * * @private */ }, { key: "_onError", value: function _onError(err) { this.emitReserved("error", err, this._xhr); this._cleanup(true); } /** * Cleans up house. * * @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. * * @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. * * @package */ }, { key: "abort", value: function abort() { this._cleanup(); } }]); }(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 _i8 in Request.requests) { if (Request.requests.hasOwnProperty(_i8)) { Request.requests[_i8].abort(); } } } var hasXHR2 = function () { var xhr = newRequest({ xdomain: false }); return xhr && xhr.responseType !== null; }(); /** * HTTP long-polling based on the built-in `XMLHttpRequest` object. * * Usage: browser * * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest */ var XHR = /*#__PURE__*/function (_BaseXHR) { function XHR(opts) { var _this12; _classCallCheck(this, XHR); _this12 = _callSuper(this, XHR, [opts]); var forceBase64 = opts && opts.forceBase64; _this12.supportsBinary = hasXHR2 && !forceBase64; return _this12; } _inherits(XHR, _BaseXHR); return _createClass(XHR, [{ key: "request", value: function request() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; Object.assign(opts, { xd: this.xd }, this.opts); return new Request(newRequest, this.uri(), opts); } }]); }(BaseXHR); function newRequest(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) {} } } // detect ReactNative environment var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative"; var BaseWS = /*#__PURE__*/function (_Transport2) { function BaseWS() { _classCallCheck(this, BaseWS); return _callSuper(this, BaseWS, arguments); } _inherits(BaseWS, _Transport2); return _createClass(BaseWS, [{ key: "name", get: function get() { return "websocket"; } }, { key: "doOpen", value: function doOpen() { 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 = this.createSocket(uri, protocols, opts); } catch (err) { return this.emitReserved("error", err); } this.ws.binaryType = this.socket.binaryType; this.addEventListeners(); } /** * Adds event lis