From 0fd2646cf374d553e77ab3527ebaa55af1e6ee3d Mon Sep 17 00:00:00 2001 From: Ryan Peters Date: Tue, 16 Jan 2024 22:00:56 -0500 Subject: [PATCH] .net 8 updates --- BinaryDad.Coding/BinaryDad.Coding.csproj | 2 +- BinaryDad.Coding/Dockerfile | 8 +- .../js/signalr/dist/browser/signalr.js | 7796 +++++++---------- .../js/signalr/dist/browser/signalr.min.js | 17 +- 4 files changed, 3032 insertions(+), 4791 deletions(-) diff --git a/BinaryDad.Coding/BinaryDad.Coding.csproj b/BinaryDad.Coding/BinaryDad.Coding.csproj index da4f060..a42aa06 100644 --- a/BinaryDad.Coding/BinaryDad.Coding.csproj +++ b/BinaryDad.Coding/BinaryDad.Coding.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 Linux diff --git a/BinaryDad.Coding/Dockerfile b/BinaryDad.Coding/Dockerfile index 55e4d84..a866e95 100644 --- a/BinaryDad.Coding/Dockerfile +++ b/BinaryDad.Coding/Dockerfile @@ -1,10 +1,8 @@ -#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. - -FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base WORKDIR /app -EXPOSE 80 +EXPOSE 8080 -FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY ["BinaryDad.Coding/BinaryDad.Coding.csproj", "BinaryDad.Coding/"] RUN dotnet restore "BinaryDad.Coding/BinaryDad.Coding.csproj" diff --git a/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.js b/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.js index a0c96c5..86f7968 100644 --- a/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.js +++ b/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.js @@ -7,1885 +7,265 @@ exports["signalR"] = factory(); else root["signalR"] = factory(); -})(window, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ // The require scope +/******/ var __webpack_require__ = {}; +/******/ /************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); -/* harmony import */ var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); -/* harmony import */ var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["AbortError"]; }); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpError", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpClient", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpResponse", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultHttpClient", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["DefaultHttpClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnection", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnection"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionState", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionState"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionBuilder"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageType", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["MessageType"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["LogLevel"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpTransportType", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["HttpTransportType"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransferFormat", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullLogger", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["NullLogger"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonHubProtocol", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["JsonHubProtocol"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["Subject"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return _index__WEBPACK_IMPORTED_MODULE_1__["VERSION"]; }); - -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds. - -// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties -// that exist on Uint8Array with the same name, and JavaScript is magic. -// We make them 'writable' because the Buffer polyfill messes with it as well. -if (!Uint8Array.prototype.indexOf) { - Object.defineProperty(Uint8Array.prototype, "indexOf", { - value: Array.prototype.indexOf, - writable: true, - }); -} -if (!Uint8Array.prototype.slice) { - Object.defineProperty(Uint8Array.prototype, "slice", { - // wrap the slice in Uint8Array so it looks like a Uint8Array.slice call - // tslint:disable-next-line:object-literal-shorthand - value: function (start, end) { return new Uint8Array(Array.prototype.slice.call(this, start, end)); }, - writable: true, - }); -} -if (!Uint8Array.prototype.forEach) { - Object.defineProperty(Uint8Array.prototype, "forEach", { - value: Array.prototype.forEach, - writable: true, - }); -} - - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var require;/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version v4.2.2+97478eb6 - */ - -(function (global, factory) { - true ? module.exports = factory() : - undefined; -}(this, (function () { 'use strict'; - -function objectOrFunction(x) { - var type = typeof x; - return x !== null && (type === 'object' || type === 'function'); -} - -function isFunction(x) { - return typeof x === 'function'; -} - - - -var _isArray = void 0; -if (Array.isArray) { - _isArray = Array.isArray; -} else { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} - -var isArray = _isArray; - -var len = 0; -var vertxNext = void 0; -var customSchedulerFn = void 0; - -var asap = function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (customSchedulerFn) { - customSchedulerFn(flush); - } else { - scheduleFlush(); - } - } -}; - -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; -} - -function setAsap(asapFn) { - asap = asapFn; -} - -var browserWindow = typeof window !== 'undefined' ? window : undefined; -var browserGlobal = browserWindow || {}; -var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; - -// node -function useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function () { - return process.nextTick(flush); - }; -} - -// vertx -function useVertxTimer() { - if (typeof vertxNext !== 'undefined') { - return function () { - vertxNext(flush); - }; - } - - return useSetTimeout(); -} - -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function () { - node.data = iterations = ++iterations % 2; - }; -} - -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); - }; -} - -function useSetTimeout() { - // Store setTimeout reference so es6-promise will be unaffected by - // other code modifying setTimeout (like sinon.useFakeTimers()) - var globalSetTimeout = setTimeout; - return function () { - return globalSetTimeout(flush, 1); - }; -} - -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; - - callback(arg); - - queue[i] = undefined; - queue[i + 1] = undefined; - } - - len = 0; -} - -function attemptVertx() { - try { - var r = require; - var vertx = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module 'vertx'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} - -var scheduleFlush = void 0; -// Decide what async method to use to triggering processing of queued callbacks: -if (isNode) { - scheduleFlush = useNextTick(); -} else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); -} else if (isWorker) { - scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && "function" === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); -} - -function then(onFulfillment, onRejection) { - var parent = this; - - var child = new this.constructor(noop); - - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } - - var _state = parent._state; - - - if (_state) { - var callback = arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - - return child; -} - -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - let promise = new Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - let promise = Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` -*/ -function resolve$1(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(noop); - resolve(promise, object); - return promise; -} - -var PROMISE_ID = Math.random().toString(36).substring(16); - -function noop() {} - -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; - -var GET_THEN_ERROR = new ErrorObject(); - -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} - -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} - -function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} - -function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { - try { - then$$1.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } -} - -function handleForeignThenable(promise, thenable, then$$1) { - asap(function (promise) { - var sealed = false; - var error = tryThen(then$$1, thenable, function (value) { - if (sealed) { - return; - } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function (reason) { - if (sealed) { - return; - } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); - } - }, promise); -} - -function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function (value) { - return resolve(promise, value); - }, function (reason) { - return reject(promise, reason); - }); - } -} - -function handleMaybeThenable(promise, maybeThenable, then$$1) { - if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { - handleOwnThenable(promise, maybeThenable); - } else { - if (then$$1 === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - GET_THEN_ERROR.error = null; - } else if (then$$1 === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then$$1)) { - handleForeignThenable(promise, maybeThenable, then$$1); - } else { - fulfill(promise, maybeThenable); - } - } -} - -function resolve(promise, value) { - if (promise === value) { - reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } -} - -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - publish(promise); -} - -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } - - promise._result = value; - promise._state = FULFILLED; - - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} - -function reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; - - asap(publishRejection, promise); -} - -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; - - - parent._onerror = null; - - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - asap(publish, parent); - } -} - -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { - return; - } - - var child = void 0, - callback = void 0, - detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; -} - -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} - -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = void 0, - error = void 0, - succeeded = void 0, - failed = void 0; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value.error = null; - } else { - succeeded = true; - } - - if (promise === value) { - reject(promise, cannotReturnOwn()); - return; - } - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } -} - -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value) { - resolve(promise, value); - }, function rejectPromise(reason) { - reject(promise, reason); - }); - } catch (e) { - reject(promise, e); - } -} - -var id = 0; -function nextId() { - return id++; -} - -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; -} - -function validationError() { - return new Error('Array Methods must be provided an Array'); -} - -function validationError() { - return new Error('Array Methods must be provided an Array'); -} - -var Enumerator = function () { - function Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); - - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } - - if (isArray(input)) { - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(input); - if (this._remaining === 0) { - fulfill(this.promise, this._result); - } - } - } else { - reject(this.promise, validationError()); - } - } - - Enumerator.prototype._enumerate = function _enumerate(input) { - for (var i = 0; this._state === PENDING && i < input.length; i++) { - this._eachEntry(input[i], i); - } - }; - - Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { - var c = this._instanceConstructor; - var resolve$$1 = c.resolve; - - - if (resolve$$1 === resolve$1) { - var _then = getThen(entry); - - if (_then === then && entry._state !== PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof _then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === Promise$2) { - var promise = new c(noop); - handleMaybeThenable(promise, entry, _then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function (resolve$$1) { - return resolve$$1(entry); - }), i); - } - } else { - this._willSettleAt(resolve$$1(entry), i); - } - }; - - Enumerator.prototype._settledAt = function _settledAt(state, i, value) { - var promise = this.promise; - - - if (promise._state === PENDING) { - this._remaining--; - - if (state === REJECTED) { - reject(promise, value); - } else { - this._result[i] = value; - } - } - - if (this._remaining === 0) { - fulfill(promise, this._result); - } - }; - - Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { - var enumerator = this; - - subscribe(promise, undefined, function (value) { - return enumerator._settledAt(FULFILLED, i, value); - }, function (reason) { - return enumerator._settledAt(REJECTED, i, reason); - }); - }; - - return Enumerator; -}(); - -/** - `Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. - - Example: - - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static -*/ -function all(entries) { - return new Enumerator(this, entries).promise; -} - -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. -*/ -function race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!isArray(entries)) { - return new Constructor(function (_, reject) { - return reject(new TypeError('You must pass an array to race.')); - }); - } else { - return new Constructor(function (resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); - } - }); - } -} - -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - let promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. -*/ -function reject$1(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - reject(promise, reason); - return promise; -} - -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} - -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} - -/** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {Function} resolver - Useful for tooling. - @constructor -*/ - -var Promise$2 = function () { - function Promise(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise ? initializePromise(this, resolver) : needsNew(); - } - } - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - Chaining - -------- - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - Assimilation - ------------ - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - If the assimliated promise rejects, then the downstream promise will also reject. - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - Simple Example - -------------- - Synchronous Example - ```javascript - let result; - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - Errback Example - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - Promise Example; - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - Advanced Example - -------------- - Synchronous Example - ```javascript - let author, books; - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - Errback Example - ```js - function foundBooks(books) { - } - function failure(reason) { - } - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - Promise Example; - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - - - Promise.prototype.catch = function _catch(onRejection) { - return this.then(null, onRejection); - }; - - /** - `finally` will be invoked regardless of the promise's fate just as native - try/catch/finally behaves - - Synchronous example: - - ```js - findAuthor() { - if (Math.random() > 0.5) { - throw new Error(); - } - return new Author(); - } - - try { - return findAuthor(); // succeed or fail - } catch(error) { - return findOtherAuther(); - } finally { - // always runs - // doesn't affect the return value - } - ``` - - Asynchronous example: - - ```js - findAuthor().catch(function(reason){ - return findOtherAuther(); - }).finally(function(){ - // author was either found, or not - }); - ``` - - @method finally - @param {Function} callback - @return {Promise} - */ - - - Promise.prototype.finally = function _finally(callback) { - var promise = this; - var constructor = promise.constructor; - - return promise.then(function (value) { - return constructor.resolve(callback()).then(function () { - return value; - }); - }, function (reason) { - return constructor.resolve(callback()).then(function () { - throw reason; - }); - }); - }; - - return Promise; -}(); - -Promise$2.prototype.then = then; -Promise$2.all = all; -Promise$2.race = race; -Promise$2.resolve = resolve$1; -Promise$2.reject = reject$1; -Promise$2._setScheduler = setScheduler; -Promise$2._setAsap = setAsap; -Promise$2._asap = asap; - -/*global self*/ -function polyfill() { - var local = void 0; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } - - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } - } - - local.Promise = Promise$2; -} - -// Strange compat.. -Promise$2.polyfill = polyfill; -Promise$2.Promise = Promise$2; - -Promise$2.polyfill(); - -return Promise$2; - -}))); - - - -//# sourceMappingURL=es6-promise.auto.map - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(2))) - -/***/ }), -/* 2 */ -/***/ (function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || new Function("return this")(); -} catch (e) { - // This works if the window reference is available - if (typeof window === "object") g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; - - -/***/ }), -/* 3 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpError", function() { return _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"]; }); - -/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpClient", function() { return _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpResponse", function() { return _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"]; }); - -/* harmony import */ var _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultHttpClient", function() { return _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_2__["DefaultHttpClient"]; }); - -/* harmony import */ var _HubConnection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(12); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnection", function() { return _HubConnection__WEBPACK_IMPORTED_MODULE_3__["HubConnection"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionState", function() { return _HubConnection__WEBPACK_IMPORTED_MODULE_3__["HubConnectionState"]; }); - -/* harmony import */ var _HubConnectionBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HubConnectionBuilder", function() { return _HubConnectionBuilder__WEBPACK_IMPORTED_MODULE_4__["HubConnectionBuilder"]; }); - -/* harmony import */ var _IHubProtocol__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(15); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MessageType", function() { return _IHubProtocol__WEBPACK_IMPORTED_MODULE_5__["MessageType"]; }); - -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return _ILogger__WEBPACK_IMPORTED_MODULE_6__["LogLevel"]; }); - -/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(20); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HttpTransportType", function() { return _ITransport__WEBPACK_IMPORTED_MODULE_7__["HttpTransportType"]; }); - -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransferFormat", function() { return _ITransport__WEBPACK_IMPORTED_MODULE_7__["TransferFormat"]; }); - -/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(10); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullLogger", function() { return _Loggers__WEBPACK_IMPORTED_MODULE_8__["NullLogger"]; }); - -/* harmony import */ var _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(25); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonHubProtocol", function() { return _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_9__["JsonHubProtocol"]; }); - -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(16); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return _Subject__WEBPACK_IMPORTED_MODULE_10__["Subject"]; }); - -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(9); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return _Utils__WEBPACK_IMPORTED_MODULE_11__["VERSION"]; }); - -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - - - - - - - - - - - - - -/***/ }), -/* 4 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpError", function() { return HttpError; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return TimeoutError; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbortError", function() { return AbortError; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "AbortError": () => (/* reexport */ AbortError), + "DefaultHttpClient": () => (/* reexport */ DefaultHttpClient), + "HttpClient": () => (/* reexport */ HttpClient), + "HttpError": () => (/* reexport */ HttpError), + "HttpResponse": () => (/* reexport */ HttpResponse), + "HttpTransportType": () => (/* reexport */ HttpTransportType), + "HubConnection": () => (/* reexport */ HubConnection), + "HubConnectionBuilder": () => (/* reexport */ HubConnectionBuilder), + "HubConnectionState": () => (/* reexport */ HubConnectionState), + "JsonHubProtocol": () => (/* reexport */ JsonHubProtocol), + "LogLevel": () => (/* reexport */ LogLevel), + "MessageType": () => (/* reexport */ MessageType), + "NullLogger": () => (/* reexport */ NullLogger), + "Subject": () => (/* reexport */ Subject), + "TimeoutError": () => (/* reexport */ TimeoutError), + "TransferFormat": () => (/* reexport */ TransferFormat), + "VERSION": () => (/* reexport */ VERSION) +}); + +;// CONCATENATED MODULE: ./src/Errors.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /** Error thrown when an HTTP request fails. */ -var HttpError = /** @class */ (function (_super) { - __extends(HttpError, _super); +class HttpError extends Error { /** Constructs a new instance of {@link @microsoft/signalr.HttpError}. * * @param {string} errorMessage A descriptive error message. * @param {number} statusCode The HTTP status code represented by this error. */ - function HttpError(errorMessage, statusCode) { - var _newTarget = this.constructor; - var _this = this; - var trueProto = _newTarget.prototype; - _this = _super.call(this, errorMessage) || this; - _this.statusCode = statusCode; + constructor(errorMessage, statusCode) { + const trueProto = new.target.prototype; + super(`${errorMessage}: Status code '${statusCode}'`); + this.statusCode = statusCode; // Workaround issue in Typescript compiler // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 - _this.__proto__ = trueProto; - return _this; + this.__proto__ = trueProto; } - return HttpError; -}(Error)); - +} /** Error thrown when a timeout elapses. */ -var TimeoutError = /** @class */ (function (_super) { - __extends(TimeoutError, _super); +class TimeoutError extends Error { /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}. * * @param {string} errorMessage A descriptive error message. */ - function TimeoutError(errorMessage) { - var _newTarget = this.constructor; - if (errorMessage === void 0) { errorMessage = "A timeout occurred."; } - var _this = this; - var trueProto = _newTarget.prototype; - _this = _super.call(this, errorMessage) || this; + constructor(errorMessage = "A timeout occurred.") { + const trueProto = new.target.prototype; + super(errorMessage); // Workaround issue in Typescript compiler // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 - _this.__proto__ = trueProto; - return _this; + this.__proto__ = trueProto; } - return TimeoutError; -}(Error)); - +} /** Error thrown when an action is aborted. */ -var AbortError = /** @class */ (function (_super) { - __extends(AbortError, _super); +class AbortError extends Error { /** Constructs a new instance of {@link AbortError}. * * @param {string} errorMessage A descriptive error message. */ - function AbortError(errorMessage) { - var _newTarget = this.constructor; - if (errorMessage === void 0) { errorMessage = "An abort occurred."; } - var _this = this; - var trueProto = _newTarget.prototype; - _this = _super.call(this, errorMessage) || this; + constructor(errorMessage = "An abort occurred.") { + const trueProto = new.target.prototype; + super(errorMessage); // Workaround issue in Typescript compiler // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 - _this.__proto__ = trueProto; - return _this; + this.__proto__ = trueProto; } - return AbortError; -}(Error)); - - - -/***/ }), -/* 5 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpResponse", function() { return HttpResponse; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpClient", function() { return HttpClient; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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]; +} +/** Error thrown when the selected transport is unsupported by the browser. */ +/** @private */ +class UnsupportedTransportError extends Error { + /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}. + * + * @param {string} message A descriptive error message. + * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on. + */ + constructor(message, transport) { + const trueProto = new.target.prototype; + super(message); + this.transport = transport; + this.errorType = 'UnsupportedTransportError'; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + this.__proto__ = trueProto; } - return t; -}; +} +/** Error thrown when the selected transport is disabled by the browser. */ +/** @private */ +class DisabledTransportError extends Error { + /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}. + * + * @param {string} message A descriptive error message. + * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on. + */ + constructor(message, transport) { + const trueProto = new.target.prototype; + super(message); + this.transport = transport; + this.errorType = 'DisabledTransportError'; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + this.__proto__ = trueProto; + } +} +/** Error thrown when the selected transport cannot be started. */ +/** @private */ +class FailedToStartTransportError extends Error { + /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}. + * + * @param {string} message A descriptive error message. + * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on. + */ + constructor(message, transport) { + const trueProto = new.target.prototype; + super(message); + this.transport = transport; + this.errorType = 'FailedToStartTransportError'; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + this.__proto__ = trueProto; + } +} +/** Error thrown when the negotiation with the server failed to complete. */ +/** @private */ +class FailedToNegotiateWithServerError extends Error { + /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}. + * + * @param {string} message A descriptive error message. + */ + constructor(message) { + const trueProto = new.target.prototype; + super(message); + this.errorType = 'FailedToNegotiateWithServerError'; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + this.__proto__ = trueProto; + } +} +/** Error thrown when multiple errors have occurred. */ +/** @private */ +class AggregateErrors extends Error { + /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}. + * + * @param {string} message A descriptive error message. + * @param {Error[]} innerErrors The collection of errors this error is aggregating. + */ + constructor(message, innerErrors) { + const trueProto = new.target.prototype; + super(message); + this.innerErrors = innerErrors; + // Workaround issue in Typescript compiler + // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 + this.__proto__ = trueProto; + } +} + +;// CONCATENATED MODULE: ./src/HttpClient.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /** Represents an HTTP response. */ -var HttpResponse = /** @class */ (function () { - function HttpResponse(statusCode, statusText, content) { +class HttpResponse { + constructor(statusCode, statusText, content) { this.statusCode = statusCode; this.statusText = statusText; this.content = content; } - return HttpResponse; -}()); - +} /** Abstraction over an HTTP client. * * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms. */ -var HttpClient = /** @class */ (function () { - function HttpClient() { +class HttpClient { + get(url, options) { + return this.send({ + ...options, + method: "GET", + url, + }); + } + post(url, options) { + return this.send({ + ...options, + method: "POST", + url, + }); + } + delete(url, options) { + return this.send({ + ...options, + method: "DELETE", + url, + }); } - HttpClient.prototype.get = function (url, options) { - return this.send(__assign({}, options, { method: "GET", url: url })); - }; - HttpClient.prototype.post = function (url, options) { - return this.send(__assign({}, options, { method: "POST", url: url })); - }; - HttpClient.prototype.delete = function (url, options) { - return this.send(__assign({}, options, { method: "DELETE", url: url })); - }; /** Gets all cookies that apply to the specified URL. * * @param url The URL that the cookies are valid for. * @returns {string} A string containing all the key-value cookie pairs for the specified URL. */ // @ts-ignore - HttpClient.prototype.getCookieString = function (url) { + getCookieString(url) { return ""; - }; - return HttpClient; -}()); - - - -/***/ }), -/* 6 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultHttpClient", function() { return DefaultHttpClient; }); -/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var _FetchHttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7); -/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9); -/* harmony import */ var _XhrHttpClient__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); - - - - - -/** Default implementation of {@link @microsoft/signalr.HttpClient}. */ -var DefaultHttpClient = /** @class */ (function (_super) { - __extends(DefaultHttpClient, _super); - /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */ - function DefaultHttpClient(logger) { - var _this = _super.call(this) || this; - if (typeof fetch !== "undefined" || _Utils__WEBPACK_IMPORTED_MODULE_3__["Platform"].isNode) { - _this.httpClient = new _FetchHttpClient__WEBPACK_IMPORTED_MODULE_1__["FetchHttpClient"](logger); - } - else if (typeof XMLHttpRequest !== "undefined") { - _this.httpClient = new _XhrHttpClient__WEBPACK_IMPORTED_MODULE_4__["XhrHttpClient"](logger); - } - else { - throw new Error("No usable HttpClient found."); - } - return _this; } - /** @inheritDoc */ - DefaultHttpClient.prototype.send = function (request) { - // Check that abort was not signaled before calling send - if (request.abortSignal && request.abortSignal.aborted) { - return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]()); - } - if (!request.method) { - return Promise.reject(new Error("No method defined.")); - } - if (!request.url) { - return Promise.reject(new Error("No url defined.")); - } - return this.httpClient.send(request); - }; - DefaultHttpClient.prototype.getCookieString = function (url) { - return this.httpClient.getCookieString(url); - }; - return DefaultHttpClient; -}(_HttpClient__WEBPACK_IMPORTED_MODULE_2__["HttpClient"])); - - - -/***/ }), -/* 7 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FetchHttpClient", function() { return FetchHttpClient; }); -/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __assign = (undefined && undefined.__assign) || Object.assign || function(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; -}; -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; - } -}; - - - - -var FetchHttpClient = /** @class */ (function (_super) { - __extends(FetchHttpClient, _super); - function FetchHttpClient(logger) { - var _this = _super.call(this) || this; - _this.logger = logger; - if (typeof fetch === "undefined") { - // In order to ignore the dynamic require in webpack builds we need to do this magic - // @ts-ignore: TS doesn't know about these names - var requireFunc = true ? require : undefined; - // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests - _this.jar = new (requireFunc("tough-cookie")).CookieJar(); - _this.fetchType = requireFunc("node-fetch"); - // node-fetch doesn't have a nice API for getting and setting cookies - // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one - _this.fetchType = requireFunc("fetch-cookie")(_this.fetchType, _this.jar); - // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide - _this.abortControllerType = requireFunc("abort-controller"); - } - else { - _this.fetchType = fetch.bind(self); - _this.abortControllerType = AbortController; - } - return _this; - } - /** @inheritDoc */ - FetchHttpClient.prototype.send = function (request) { - return __awaiter(this, void 0, void 0, function () { - var abortController, error, timeoutId, msTimeout, response, e_1, content, payload; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - // Check that abort was not signaled before calling send - if (request.abortSignal && request.abortSignal.aborted) { - throw new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"](); - } - if (!request.method) { - throw new Error("No method defined."); - } - if (!request.url) { - throw new Error("No url defined."); - } - abortController = new this.abortControllerType(); - // Hook our abortSignal into the abort controller - if (request.abortSignal) { - request.abortSignal.onabort = function () { - abortController.abort(); - error = new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"](); - }; - } - timeoutId = null; - if (request.timeout) { - msTimeout = request.timeout; - timeoutId = setTimeout(function () { - abortController.abort(); - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Timeout from HTTP request."); - error = new _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"](); - }, msTimeout); - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.fetchType(request.url, { - body: request.content, - cache: "no-cache", - credentials: request.withCredentials === true ? "include" : "same-origin", - headers: __assign({ "Content-Type": "text/plain;charset=UTF-8", "X-Requested-With": "XMLHttpRequest" }, request.headers), - method: request.method, - mode: "cors", - redirect: "manual", - signal: abortController.signal, - })]; - case 2: - response = _a.sent(); - return [3 /*break*/, 5]; - case 3: - e_1 = _a.sent(); - if (error) { - throw error; - } - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Error from HTTP request. " + e_1 + "."); - throw e_1; - case 4: - if (timeoutId) { - clearTimeout(timeoutId); - } - if (request.abortSignal) { - request.abortSignal.onabort = null; - } - return [7 /*endfinally*/]; - case 5: - if (!response.ok) { - throw new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](response.statusText, response.status); - } - content = deserializeContent(response, request.responseType); - return [4 /*yield*/, content]; - case 6: - payload = _a.sent(); - return [2 /*return*/, new _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"](response.status, response.statusText, payload)]; - } - }); - }); - }; - FetchHttpClient.prototype.getCookieString = function (url) { - var cookies = ""; - if (_Utils__WEBPACK_IMPORTED_MODULE_3__["Platform"].isNode && this.jar) { - // @ts-ignore: unused variable - this.jar.getCookies(url, function (e, c) { return cookies = c.join("; "); }); - } - return cookies; - }; - return FetchHttpClient; -}(_HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"])); - -function deserializeContent(response, responseType) { - var content; - switch (responseType) { - case "arraybuffer": - content = response.arrayBuffer(); - break; - case "text": - content = response.text(); - break; - case "blob": - case "document": - case "json": - throw new Error(responseType + " is not supported."); - default: - content = response.text(); - break; - } - return content; } - -/***/ }), -/* 8 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return LogLevel; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +;// CONCATENATED MODULE: ./src/ILogger.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here. /** Indicates the severity of a log message. * @@ -1909,153 +289,92 @@ var LogLevel; LogLevel[LogLevel["None"] = 6] = "None"; })(LogLevel || (LogLevel = {})); - -/***/ }), -/* 9 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return VERSION; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Arg", function() { return Arg; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Platform", function() { return Platform; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataDetail", function() { return getDataDetail; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatArrayBuffer", function() { return formatArrayBuffer; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayBuffer", function() { return isArrayBuffer; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendMessage", function() { return sendMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createLogger", function() { return createLogger; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubjectSubscription", function() { return SubjectSubscription; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConsoleLogger", function() { return ConsoleLogger; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUserAgentHeader", function() { return getUserAgentHeader; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "constructUserAgent", function() { return constructUserAgent; }); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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]; +;// CONCATENATED MODULE: ./src/Loggers.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +/** A logger that does nothing when log messages are sent to it. */ +class NullLogger { + constructor() { } + /** @inheritDoc */ + // eslint-disable-next-line + log(_logLevel, _message) { } - return t; -}; -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; - } -}; +} +/** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */ +NullLogger.instance = new NullLogger(); + +;// CONCATENATED MODULE: ./src/Utils.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // Version token that will be replaced by the prepack command /** The version of the SignalR client. */ -var VERSION = "5.0.8"; +const VERSION = "8.0.0"; /** @private */ -var Arg = /** @class */ (function () { - function Arg() { - } - Arg.isRequired = function (val, name) { +class Arg { + static isRequired(val, name) { if (val === null || val === undefined) { - throw new Error("The '" + name + "' argument is required."); + throw new Error(`The '${name}' argument is required.`); } - }; - Arg.isNotEmpty = function (val, name) { + } + static isNotEmpty(val, name) { if (!val || val.match(/^\s*$/)) { - throw new Error("The '" + name + "' argument should not be empty."); + throw new Error(`The '${name}' argument should not be empty.`); } - }; - Arg.isIn = function (val, values, name) { + } + static isIn(val, values, name) { // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself. if (!(val in values)) { - throw new Error("Unknown " + name + " value: " + val + "."); + throw new Error(`Unknown ${name} value: ${val}.`); } - }; - return Arg; -}()); - -/** @private */ -var Platform = /** @class */ (function () { - function Platform() { } - Object.defineProperty(Platform, "isBrowser", { - get: function () { - return typeof window === "object"; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Platform, "isWebWorker", { - get: function () { - return typeof self === "object" && "importScripts" in self; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Platform, "isNode", { - get: function () { - return !this.isBrowser && !this.isWebWorker; - }, - enumerable: true, - configurable: true - }); - return Platform; -}()); - +} +/** @private */ +class Platform { + // react-native has a window but no document so we should check both + static get isBrowser() { + return !Platform.isNode && typeof window === "object" && typeof window.document === "object"; + } + // WebWorkers don't have a window object so the isBrowser check would fail + static get isWebWorker() { + return !Platform.isNode && typeof self === "object" && "importScripts" in self; + } + // react-native has a window but no document + static get isReactNative() { + return !Platform.isNode && typeof window === "object" && typeof window.document === "undefined"; + } + // Node apps shouldn't have a window object, but WebWorkers don't either + // so we need to check for both WebWorker and window + static get isNode() { + return typeof process !== "undefined" && process.release && process.release.name === "node"; + } +} /** @private */ function getDataDetail(data, includeContent) { - var detail = ""; + let detail = ""; if (isArrayBuffer(data)) { - detail = "Binary data of length " + data.byteLength; + detail = `Binary data of length ${data.byteLength}`; if (includeContent) { - detail += ". Content: '" + formatArrayBuffer(data) + "'"; + detail += `. Content: '${formatArrayBuffer(data)}'`; } } else if (typeof data === "string") { - detail = "String data of length " + data.length; + detail = `String data of length ${data.length}`; if (includeContent) { - detail += ". Content: '" + data + "'"; + detail += `. Content: '${data}'`; } } return detail; } /** @private */ function formatArrayBuffer(data) { - var view = new Uint8Array(data); + const view = new Uint8Array(data); // Uint8Array.map only supports returning another Uint8Array? - var str = ""; - view.forEach(function (num) { - var pad = num < 16 ? "0" : ""; - str += "0x" + pad + num.toString(16) + " "; + let str = ""; + view.forEach((num) => { + const pad = num < 16 ? "0" : ""; + str += `0x${pad}${num.toString(16)} `; }); // Trim of trailing space. return str.substr(0, str.length - 1); @@ -2069,105 +388,81 @@ function isArrayBuffer(val) { (val.constructor && val.constructor.name === "ArrayBuffer")); } /** @private */ -function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, logMessageContent, withCredentials, defaultHeaders) { - return __awaiter(this, void 0, void 0, function () { - var _a, headers, token, _b, name, value, responseType, response; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - headers = {}; - if (!accessTokenFactory) return [3 /*break*/, 2]; - return [4 /*yield*/, accessTokenFactory()]; - case 1: - token = _c.sent(); - if (token) { - headers = (_a = {}, - _a["Authorization"] = "Bearer " + token, - _a); - } - _c.label = 2; - case 2: - _b = getUserAgentHeader(), name = _b[0], value = _b[1]; - headers[name] = value; - logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(" + transportName + " transport) sending data. " + getDataDetail(content, logMessageContent) + "."); - responseType = isArrayBuffer(content) ? "arraybuffer" : "text"; - return [4 /*yield*/, httpClient.post(url, { - content: content, - headers: __assign({}, headers, defaultHeaders), - responseType: responseType, - withCredentials: withCredentials, - })]; - case 3: - response = _c.sent(); - logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(" + transportName + " transport) request complete. Response status: " + response.statusCode + "."); - return [2 /*return*/]; - } - }); +async function sendMessage(logger, transportName, httpClient, url, content, options) { + const headers = {}; + const [name, value] = getUserAgentHeader(); + headers[name] = value; + logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`); + const responseType = isArrayBuffer(content) ? "arraybuffer" : "text"; + const response = await httpClient.post(url, { + content, + headers: { ...headers, ...options.headers }, + responseType, + timeout: options.timeout, + withCredentials: options.withCredentials, }); + logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`); } /** @private */ function createLogger(logger) { if (logger === undefined) { - return new ConsoleLogger(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information); + return new ConsoleLogger(LogLevel.Information); } if (logger === null) { - return _Loggers__WEBPACK_IMPORTED_MODULE_1__["NullLogger"].instance; + return NullLogger.instance; } - if (logger.log) { + if (logger.log !== undefined) { return logger; } return new ConsoleLogger(logger); } /** @private */ -var SubjectSubscription = /** @class */ (function () { - function SubjectSubscription(subject, observer) { - this.subject = subject; - this.observer = observer; +class SubjectSubscription { + constructor(subject, observer) { + this._subject = subject; + this._observer = observer; } - SubjectSubscription.prototype.dispose = function () { - var index = this.subject.observers.indexOf(this.observer); + dispose() { + const index = this._subject.observers.indexOf(this._observer); if (index > -1) { - this.subject.observers.splice(index, 1); + this._subject.observers.splice(index, 1); } - if (this.subject.observers.length === 0 && this.subject.cancelCallback) { - this.subject.cancelCallback().catch(function (_) { }); + if (this._subject.observers.length === 0 && this._subject.cancelCallback) { + this._subject.cancelCallback().catch((_) => { }); } - }; - return SubjectSubscription; -}()); - -/** @private */ -var ConsoleLogger = /** @class */ (function () { - function ConsoleLogger(minimumLogLevel) { - this.minimumLogLevel = minimumLogLevel; - this.outputConsole = console; } - ConsoleLogger.prototype.log = function (logLevel, message) { - if (logLevel >= this.minimumLogLevel) { +} +/** @private */ +class ConsoleLogger { + constructor(minimumLogLevel) { + this._minLevel = minimumLogLevel; + this.out = console; + } + log(logLevel, message) { + if (logLevel >= this._minLevel) { + const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`; switch (logLevel) { - case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Critical: - case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Error: - this.outputConsole.error("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + case LogLevel.Critical: + case LogLevel.Error: + this.out.error(msg); break; - case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Warning: - this.outputConsole.warn("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + case LogLevel.Warning: + this.out.warn(msg); break; - case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information: - this.outputConsole.info("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + case LogLevel.Information: + this.out.info(msg); break; default: // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug - this.outputConsole.log("[" + new Date().toISOString() + "] " + _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel] + ": " + message); + this.out.log(msg); break; } } - }; - return ConsoleLogger; -}()); - + } +} /** @private */ function getUserAgentHeader() { - var userAgentHeaderName = "X-SignalR-User-Agent"; + let userAgentHeaderName = "X-SignalR-User-Agent"; if (Platform.isNode) { userAgentHeaderName = "User-Agent"; } @@ -2176,19 +471,19 @@ function getUserAgentHeader() { /** @private */ function constructUserAgent(version, os, runtime, runtimeVersion) { // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version]) - var userAgent = "Microsoft SignalR/"; - var majorAndMinor = version.split("."); - userAgent += majorAndMinor[0] + "." + majorAndMinor[1]; - userAgent += " (" + version + "; "; + let userAgent = "Microsoft SignalR/"; + const majorAndMinor = version.split("."); + userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`; + userAgent += ` (${version}; `; if (os && os !== "") { - userAgent += os + "; "; + userAgent += `${os}; `; } else { userAgent += "Unknown OS; "; } - userAgent += "" + runtime; + userAgent += `${runtime}`; if (runtimeVersion) { - userAgent += "; " + runtimeVersion; + userAgent += `; ${runtimeVersion}`; } else { userAgent += "; Unknown Runtime Version"; @@ -2196,7 +491,8 @@ function constructUserAgent(version, os, runtime, runtimeVersion) { userAgent += ")"; return userAgent; } -function getOsName() { +// eslint-disable-next-line spaced-comment +/*#__PURE__*/ function getOsName() { if (Platform.isNode) { switch (process.platform) { case "win32": @@ -2213,7 +509,8 @@ function getOsName() { return ""; } } -function getRuntimeVersion() { +// eslint-disable-next-line spaced-comment +/*#__PURE__*/ function getRuntimeVersion() { if (Platform.isNode) { return process.versions.node; } @@ -2227,70 +524,211 @@ function getRuntime() { return "Browser"; } } +/** @private */ +function getErrorString(e) { + if (e.stack) { + return e.stack; + } + else if (e.message) { + return e.message; + } + return `${e}`; +} +/** @private */ +function getGlobalThis() { + // globalThis is semi-new and not available in Node until v12 + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof __webpack_require__.g !== "undefined") { + return __webpack_require__.g; + } + throw new Error("could not find global"); +} + +;// CONCATENATED MODULE: ./src/DynamicImports.browser.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +/** @private */ +function configureFetch() { + return false; +} +/** @private */ +function configureAbortController() { + return false; +} +/** @private */ +function getWS() { + throw new Error("Trying to import 'ws' in the browser."); +} +/** @private */ +function getEventSource() { + throw new Error("Trying to import 'eventsource' in the browser."); +} + +;// CONCATENATED MODULE: ./src/FetchHttpClient.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. -/***/ }), -/* 10 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullLogger", function() { return NullLogger; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -/** A logger that does nothing when log messages are sent to it. */ -var NullLogger = /** @class */ (function () { - function NullLogger() { + + +class FetchHttpClient extends HttpClient { + constructor(logger) { + super(); + this._logger = logger; + // This is how you do "reference" arguments + const fetchObj = { _fetchType: undefined, _jar: undefined }; + if (configureFetch(fetchObj)) { + this._fetchType = fetchObj._fetchType; + this._jar = fetchObj._jar; + } + else { + this._fetchType = fetch.bind(getGlobalThis()); + } + this._abortControllerType = AbortController; + const abortObj = { _abortControllerType: this._abortControllerType }; + if (configureAbortController(abortObj)) { + this._abortControllerType = abortObj._abortControllerType; + } } /** @inheritDoc */ - // tslint:disable-next-line - NullLogger.prototype.log = function (_logLevel, _message) { - }; - /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */ - NullLogger.instance = new NullLogger(); - return NullLogger; -}()); - - - -/***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XhrHttpClient", function() { return XhrHttpClient; }); -/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var _HttpClient__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); - - - -var XhrHttpClient = /** @class */ (function (_super) { - __extends(XhrHttpClient, _super); - function XhrHttpClient(logger) { - var _this = _super.call(this) || this; - _this.logger = logger; - return _this; - } - /** @inheritDoc */ - XhrHttpClient.prototype.send = function (request) { - var _this = this; + async send(request) { // Check that abort was not signaled before calling send if (request.abortSignal && request.abortSignal.aborted) { - return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]()); + throw new AbortError(); + } + if (!request.method) { + throw new Error("No method defined."); + } + if (!request.url) { + throw new Error("No url defined."); + } + const abortController = new this._abortControllerType(); + let error; + // Hook our abortSignal into the abort controller + if (request.abortSignal) { + request.abortSignal.onabort = () => { + abortController.abort(); + error = new AbortError(); + }; + } + // If a timeout has been passed in, setup a timeout to call abort + // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout + let timeoutId = null; + if (request.timeout) { + const msTimeout = request.timeout; + timeoutId = setTimeout(() => { + abortController.abort(); + this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`); + error = new TimeoutError(); + }, msTimeout); + } + if (request.content === "") { + request.content = undefined; + } + if (request.content) { + // Explicitly setting the Content-Type header for React Native on Android platform. + request.headers = request.headers || {}; + if (isArrayBuffer(request.content)) { + request.headers["Content-Type"] = "application/octet-stream"; + } + else { + request.headers["Content-Type"] = "text/plain;charset=UTF-8"; + } + } + let response; + try { + response = await this._fetchType(request.url, { + body: request.content, + cache: "no-cache", + credentials: request.withCredentials === true ? "include" : "same-origin", + headers: { + "X-Requested-With": "XMLHttpRequest", + ...request.headers, + }, + method: request.method, + mode: "cors", + redirect: "follow", + signal: abortController.signal, + }); + } + catch (e) { + if (error) { + throw error; + } + this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`); + throw e; + } + finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (request.abortSignal) { + request.abortSignal.onabort = null; + } + } + if (!response.ok) { + const errorMessage = await deserializeContent(response, "text"); + throw new HttpError(errorMessage || response.statusText, response.status); + } + const content = deserializeContent(response, request.responseType); + const payload = await content; + return new HttpResponse(response.status, response.statusText, payload); + } + getCookieString(url) { + let cookies = ""; + if (Platform.isNode && this._jar) { + // @ts-ignore: unused variable + this._jar.getCookies(url, (e, c) => cookies = c.join("; ")); + } + return cookies; + } +} +function deserializeContent(response, responseType) { + let content; + switch (responseType) { + case "arraybuffer": + content = response.arrayBuffer(); + break; + case "text": + content = response.text(); + break; + case "blob": + case "document": + case "json": + throw new Error(`${responseType} is not supported.`); + default: + content = response.text(); + break; + } + return content; +} + +;// CONCATENATED MODULE: ./src/XhrHttpClient.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + + + + +class XhrHttpClient extends HttpClient { + constructor(logger) { + super(); + this._logger = logger; + } + /** @inheritDoc */ + send(request) { + // Check that abort was not signaled before calling send + if (request.abortSignal && request.abortSignal.aborted) { + return Promise.reject(new AbortError()); } if (!request.method) { return Promise.reject(new Error("No method defined.")); @@ -2298,17 +736,27 @@ var XhrHttpClient = /** @class */ (function (_super) { if (!request.url) { return Promise.reject(new Error("No url defined.")); } - return new Promise(function (resolve, reject) { - var xhr = new XMLHttpRequest(); + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); xhr.open(request.method, request.url, true); xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials; xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); - // Explicitly setting the Content-Type header for React Native on Android platform. - xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); - var headers = request.headers; + if (request.content === "") { + request.content = undefined; + } + if (request.content) { + // Explicitly setting the Content-Type header for React Native on Android platform. + if (isArrayBuffer(request.content)) { + xhr.setRequestHeader("Content-Type", "application/octet-stream"); + } + else { + xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); + } + } + const headers = request.headers; if (headers) { Object.keys(headers) - .forEach(function (header) { + .forEach((header) => { xhr.setRequestHeader(header, headers[header]); }); } @@ -2316,1128 +764,156 @@ var XhrHttpClient = /** @class */ (function (_super) { xhr.responseType = request.responseType; } if (request.abortSignal) { - request.abortSignal.onabort = function () { + request.abortSignal.onabort = () => { xhr.abort(); - reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"]()); + reject(new AbortError()); }; } if (request.timeout) { xhr.timeout = request.timeout; } - xhr.onload = function () { + xhr.onload = () => { if (request.abortSignal) { request.abortSignal.onabort = null; } if (xhr.status >= 200 && xhr.status < 300) { - resolve(new _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"](xhr.status, xhr.statusText, xhr.response || xhr.responseText)); + resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText)); } else { - reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText, xhr.status)); + reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status)); } }; - xhr.onerror = function () { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Error from HTTP request. " + xhr.status + ": " + xhr.statusText + "."); - reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText, xhr.status)); + xhr.onerror = () => { + this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`); + reject(new HttpError(xhr.statusText, xhr.status)); }; - xhr.ontimeout = function () { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Timeout from HTTP request."); - reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"]()); + xhr.ontimeout = () => { + this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`); + reject(new TimeoutError()); }; - xhr.send(request.content || ""); + xhr.send(request.content); }); - }; - return XhrHttpClient; -}(_HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"])); - - - -/***/ }), -/* 12 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HubConnectionState", function() { return HubConnectionState; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HubConnection", function() { return HubConnection; }); -/* harmony import */ var _HandshakeProtocol__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13); -/* harmony import */ var _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; } -}; +} + +;// CONCATENATED MODULE: ./src/DefaultHttpClient.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. -var DEFAULT_TIMEOUT_IN_MS = 30 * 1000; -var DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000; -/** Describes the current state of the {@link HubConnection} to the server. */ -var HubConnectionState; -(function (HubConnectionState) { - /** The hub connection is disconnected. */ - HubConnectionState["Disconnected"] = "Disconnected"; - /** The hub connection is connecting. */ - HubConnectionState["Connecting"] = "Connecting"; - /** The hub connection is connected. */ - HubConnectionState["Connected"] = "Connected"; - /** The hub connection is disconnecting. */ - HubConnectionState["Disconnecting"] = "Disconnecting"; - /** The hub connection is reconnecting. */ - HubConnectionState["Reconnecting"] = "Reconnecting"; -})(HubConnectionState || (HubConnectionState = {})); -/** Represents a connection to a SignalR Hub. */ -var HubConnection = /** @class */ (function () { - function HubConnection(connection, logger, protocol, reconnectPolicy) { - var _this = this; - this.nextKeepAlive = 0; - _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(connection, "connection"); - _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(logger, "logger"); - _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(protocol, "protocol"); - this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS; - this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS; - this.logger = logger; - this.protocol = protocol; - this.connection = connection; - this.reconnectPolicy = reconnectPolicy; - this.handshakeProtocol = new _HandshakeProtocol__WEBPACK_IMPORTED_MODULE_0__["HandshakeProtocol"](); - this.connection.onreceive = function (data) { return _this.processIncomingData(data); }; - this.connection.onclose = function (error) { return _this.connectionClosed(error); }; - this.callbacks = {}; - this.methods = {}; - this.closedCallbacks = []; - this.reconnectingCallbacks = []; - this.reconnectedCallbacks = []; - this.invocationId = 0; - this.receivedHandshakeResponse = false; - this.connectionState = HubConnectionState.Disconnected; - this.connectionStarted = false; - this.cachedPingMessage = this.protocol.writeMessage({ type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Ping }); +/** Default implementation of {@link @microsoft/signalr.HttpClient}. */ +class DefaultHttpClient extends HttpClient { + /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */ + constructor(logger) { + super(); + if (typeof fetch !== "undefined" || Platform.isNode) { + this._httpClient = new FetchHttpClient(logger); + } + else if (typeof XMLHttpRequest !== "undefined") { + this._httpClient = new XhrHttpClient(logger); + } + else { + throw new Error("No usable HttpClient found."); + } } - /** @internal */ - // Using a public static factory method means we can have a private constructor and an _internal_ - // create method that can be used by HubConnectionBuilder. An "internal" constructor would just - // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a - // public parameter-less constructor. - HubConnection.create = function (connection, logger, protocol, reconnectPolicy) { - return new HubConnection(connection, logger, protocol, reconnectPolicy); - }; - Object.defineProperty(HubConnection.prototype, "state", { - /** Indicates the state of the {@link HubConnection} to the server. */ - get: function () { - return this.connectionState; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(HubConnection.prototype, "connectionId", { - /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either - * in the disconnected state or if the negotiation step was skipped. - */ - get: function () { - return this.connection ? (this.connection.connectionId || null) : null; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(HubConnection.prototype, "baseUrl", { - /** Indicates the url of the {@link HubConnection} to the server. */ - get: function () { - return this.connection.baseUrl || ""; - }, - /** - * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or - * Reconnecting states. - * @param {string} url The url to connect to. - */ - set: function (url) { - if (this.connectionState !== HubConnectionState.Disconnected && this.connectionState !== HubConnectionState.Reconnecting) { - throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url."); - } - if (!url) { - throw new Error("The HubConnection url must be a valid url."); - } - this.connection.baseUrl = url; - }, - enumerable: true, - configurable: true - }); - /** Starts the connection. - * - * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error. - */ - HubConnection.prototype.start = function () { - this.startPromise = this.startWithStateTransitions(); - return this.startPromise; - }; - HubConnection.prototype.startWithStateTransitions = function () { - return __awaiter(this, void 0, void 0, function () { - var e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.connectionState !== HubConnectionState.Disconnected) { - return [2 /*return*/, Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."))]; - } - this.connectionState = HubConnectionState.Connecting; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Starting HubConnection."); - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.startInternal()]; - case 2: - _a.sent(); - this.connectionState = HubConnectionState.Connected; - this.connectionStarted = true; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "HubConnection connected successfully."); - return [3 /*break*/, 4]; - case 3: - e_1 = _a.sent(); - this.connectionState = HubConnectionState.Disconnected; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "HubConnection failed to start successfully because of error '" + e_1 + "'."); - return [2 /*return*/, Promise.reject(e_1)]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - HubConnection.prototype.startInternal = function () { - return __awaiter(this, void 0, void 0, function () { - var handshakePromise, handshakeRequest, e_2; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.stopDuringStartError = undefined; - this.receivedHandshakeResponse = false; - handshakePromise = new Promise(function (resolve, reject) { - _this.handshakeResolver = resolve; - _this.handshakeRejecter = reject; - }); - return [4 /*yield*/, this.connection.start(this.protocol.transferFormat)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - _a.trys.push([2, 5, , 7]); - handshakeRequest = { - protocol: this.protocol.name, - version: this.protocol.version, - }; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Sending handshake request."); - return [4 /*yield*/, this.sendMessage(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest))]; - case 3: - _a.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Using HubProtocol '" + this.protocol.name + "'."); - // defensively cleanup timeout in case we receive a message from the server before we finish start - this.cleanupTimeout(); - this.resetTimeoutPeriod(); - this.resetKeepAliveInterval(); - return [4 /*yield*/, handshakePromise]; - case 4: - _a.sent(); - // It's important to check the stopDuringStartError instead of just relying on the handshakePromise - // being rejected on close, because this continuation can run after both the handshake completed successfully - // and the connection was closed. - if (this.stopDuringStartError) { - // It's important to throw instead of returning a rejected promise, because we don't want to allow any state - // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise - // will cause the calling continuation to get scheduled to run later. - throw this.stopDuringStartError; - } - return [3 /*break*/, 7]; - case 5: - e_2 = _a.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Hub handshake failed with error '" + e_2 + "' during start(). Stopping HubConnection."); - this.cleanupTimeout(); - this.cleanupPingTimer(); - // HttpConnection.stop() should not complete until after the onclose callback is invoked. - // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes. - return [4 /*yield*/, this.connection.stop(e_2)]; - case 6: - // HttpConnection.stop() should not complete until after the onclose callback is invoked. - // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes. - _a.sent(); - throw e_2; - case 7: return [2 /*return*/]; - } - }); - }); - }; - /** Stops the connection. - * - * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error. - */ - HubConnection.prototype.stop = function () { - return __awaiter(this, void 0, void 0, function () { - var startPromise, e_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - startPromise = this.startPromise; - this.stopPromise = this.stopInternal(); - return [4 /*yield*/, this.stopPromise]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - _a.trys.push([2, 4, , 5]); - // Awaiting undefined continues immediately - return [4 /*yield*/, startPromise]; - case 3: - // Awaiting undefined continues immediately - _a.sent(); - return [3 /*break*/, 5]; - case 4: - e_3 = _a.sent(); - return [3 /*break*/, 5]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - HubConnection.prototype.stopInternal = function (error) { - if (this.connectionState === HubConnectionState.Disconnected) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Call to HubConnection.stop(" + error + ") ignored because it is already in the disconnected state."); - return Promise.resolve(); + /** @inheritDoc */ + send(request) { + // Check that abort was not signaled before calling send + if (request.abortSignal && request.abortSignal.aborted) { + return Promise.reject(new AbortError()); } - if (this.connectionState === HubConnectionState.Disconnecting) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state."); - return this.stopPromise; + if (!request.method) { + return Promise.reject(new Error("No method defined.")); } - this.connectionState = HubConnectionState.Disconnecting; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Stopping HubConnection."); - if (this.reconnectDelayHandle) { - // We're in a reconnect delay which means the underlying connection is currently already stopped. - // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and - // fire the onclose callbacks. - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Connection stopped during reconnect delay. Done reconnecting."); - clearTimeout(this.reconnectDelayHandle); - this.reconnectDelayHandle = undefined; - this.completeClose(); - return Promise.resolve(); + if (!request.url) { + return Promise.reject(new Error("No url defined.")); } - this.cleanupTimeout(); - this.cleanupPingTimer(); - this.stopDuringStartError = error || new Error("The connection was stopped before the hub handshake could complete."); - // HttpConnection.stop() should not complete until after either HttpConnection.start() fails - // or the onclose callback is invoked. The onclose callback will transition the HubConnection - // to the disconnected state if need be before HttpConnection.stop() completes. - return this.connection.stop(error); - }; - /** Invokes a streaming hub method on the server using the specified name and arguments. - * - * @typeparam T The type of the items returned by the server. - * @param {string} methodName The name of the server method to invoke. - * @param {any[]} args The arguments used to invoke the server method. - * @returns {IStreamResult} An object that yields results from the server as they are received. - */ - HubConnection.prototype.stream = function (methodName) { - var _this = this; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1]; - var invocationDescriptor = this.createStreamInvocation(methodName, args, streamIds); - var promiseQueue; - var subject = new _Subject__WEBPACK_IMPORTED_MODULE_3__["Subject"](); - subject.cancelCallback = function () { - var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId); - delete _this.callbacks[invocationDescriptor.invocationId]; - return promiseQueue.then(function () { - return _this.sendWithProtocol(cancelInvocation); - }); - }; - this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) { - if (error) { - subject.error(error); - return; - } - else if (invocationEvent) { - // invocationEvent will not be null when an error is not passed to the callback - if (invocationEvent.type === _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion) { - if (invocationEvent.error) { - subject.error(new Error(invocationEvent.error)); - } - else { - subject.complete(); - } - } - else { - subject.next((invocationEvent.item)); - } - } - }; - promiseQueue = this.sendWithProtocol(invocationDescriptor) - .catch(function (e) { - subject.error(e); - delete _this.callbacks[invocationDescriptor.invocationId]; - }); - this.launchStreams(streams, promiseQueue); - return subject; - }; - HubConnection.prototype.sendMessage = function (message) { - this.resetKeepAliveInterval(); - return this.connection.send(message); - }; - /** - * Sends a js object to the server. - * @param message The js object to serialize and send. - */ - HubConnection.prototype.sendWithProtocol = function (message) { - return this.sendMessage(this.protocol.writeMessage(message)); - }; - /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver. - * - * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still - * be processing the invocation. - * - * @param {string} methodName The name of the server method to invoke. - * @param {any[]} args The arguments used to invoke the server method. - * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error. - */ - HubConnection.prototype.send = function (methodName) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1]; - var sendPromise = this.sendWithProtocol(this.createInvocation(methodName, args, true, streamIds)); - this.launchStreams(streams, sendPromise); - return sendPromise; - }; - /** Invokes a hub method on the server using the specified name and arguments. - * - * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise - * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of - * resolving the Promise. - * - * @typeparam T The expected return type. - * @param {string} methodName The name of the server method to invoke. - * @param {any[]} args The arguments used to invoke the server method. - * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error. - */ - HubConnection.prototype.invoke = function (methodName) { - var _this = this; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1]; - var invocationDescriptor = this.createInvocation(methodName, args, false, streamIds); - var p = new Promise(function (resolve, reject) { - // invocationId will always have a value for a non-blocking invocation - _this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) { - if (error) { - reject(error); - return; - } - else if (invocationEvent) { - // invocationEvent will not be null when an error is not passed to the callback - if (invocationEvent.type === _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion) { - if (invocationEvent.error) { - reject(new Error(invocationEvent.error)); - } - else { - resolve(invocationEvent.result); - } - } - else { - reject(new Error("Unexpected message type: " + invocationEvent.type)); - } - } - }; - var promiseQueue = _this.sendWithProtocol(invocationDescriptor) - .catch(function (e) { - reject(e); - // invocationId will always have a value for a non-blocking invocation - delete _this.callbacks[invocationDescriptor.invocationId]; - }); - _this.launchStreams(streams, promiseQueue); - }); - return p; - }; - /** Registers a handler that will be invoked when the hub method with the specified method name is invoked. - * - * @param {string} methodName The name of the hub method to define. - * @param {Function} newMethod The handler that will be raised when the hub method is invoked. - */ - HubConnection.prototype.on = function (methodName, newMethod) { - if (!methodName || !newMethod) { - return; - } - methodName = methodName.toLowerCase(); - if (!this.methods[methodName]) { - this.methods[methodName] = []; - } - // Preventing adding the same handler multiple times. - if (this.methods[methodName].indexOf(newMethod) !== -1) { - return; - } - this.methods[methodName].push(newMethod); - }; - HubConnection.prototype.off = function (methodName, method) { - if (!methodName) { - return; - } - methodName = methodName.toLowerCase(); - var handlers = this.methods[methodName]; - if (!handlers) { - return; - } - if (method) { - var removeIdx = handlers.indexOf(method); - if (removeIdx !== -1) { - handlers.splice(removeIdx, 1); - if (handlers.length === 0) { - delete this.methods[methodName]; - } - } - } - else { - delete this.methods[methodName]; - } - }; - /** Registers a handler that will be invoked when the connection is closed. - * - * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any). - */ - HubConnection.prototype.onclose = function (callback) { - if (callback) { - this.closedCallbacks.push(callback); - } - }; - /** Registers a handler that will be invoked when the connection starts reconnecting. - * - * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any). - */ - HubConnection.prototype.onreconnecting = function (callback) { - if (callback) { - this.reconnectingCallbacks.push(callback); - } - }; - /** Registers a handler that will be invoked when the connection successfully reconnects. - * - * @param {Function} callback The handler that will be invoked when the connection successfully reconnects. - */ - HubConnection.prototype.onreconnected = function (callback) { - if (callback) { - this.reconnectedCallbacks.push(callback); - } - }; - HubConnection.prototype.processIncomingData = function (data) { - this.cleanupTimeout(); - if (!this.receivedHandshakeResponse) { - data = this.processHandshakeResponse(data); - this.receivedHandshakeResponse = true; - } - // Data may have all been read when processing handshake response - if (data) { - // Parse the messages - var messages = this.protocol.parseMessages(data, this.logger); - for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { - var message = messages_1[_i]; - switch (message.type) { - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation: - this.invokeClientMethod(message); - break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].StreamItem: - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion: - var callback = this.callbacks[message.invocationId]; - if (callback) { - if (message.type === _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion) { - delete this.callbacks[message.invocationId]; - } - callback(message); - } - break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Ping: - // Don't care about pings - break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Close: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Close message received from server."); - var error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined; - if (message.allowReconnect === true) { - // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async, - // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions. - // tslint:disable-next-line:no-floating-promises - this.connection.stop(error); - } - else { - // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing. - this.stopPromise = this.stopInternal(error); - } - break; - default: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "Invalid message type: " + message.type + "."); - break; - } - } - } - this.resetTimeoutPeriod(); - }; - HubConnection.prototype.processHandshakeResponse = function (data) { - var _a; - var responseMessage; - var remainingData; - try { - _a = this.handshakeProtocol.parseHandshakeResponse(data), remainingData = _a[0], responseMessage = _a[1]; - } - catch (e) { - var message = "Error parsing handshake response: " + e; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, message); - var error = new Error(message); - this.handshakeRejecter(error); - throw error; - } - if (responseMessage.error) { - var message = "Server returned handshake error: " + responseMessage.error; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, message); - var error = new Error(message); - this.handshakeRejecter(error); - throw error; - } - else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Server handshake complete."); - } - this.handshakeResolver(); - return remainingData; - }; - HubConnection.prototype.resetKeepAliveInterval = function () { - if (this.connection.features.inherentKeepAlive) { - return; - } - // Set the time we want the next keep alive to be sent - // Timer will be setup on next message receive - this.nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds; - this.cleanupPingTimer(); - }; - HubConnection.prototype.resetTimeoutPeriod = function () { - var _this = this; - if (!this.connection.features || !this.connection.features.inherentKeepAlive) { - // Set the timeout timer - this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.serverTimeoutInMilliseconds); - // Set keepAlive timer if there isn't one - if (this.pingServerHandle === undefined) { - var nextPing = this.nextKeepAlive - new Date().getTime(); - if (nextPing < 0) { - nextPing = 0; - } - // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute - this.pingServerHandle = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () { - var _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!(this.connectionState === HubConnectionState.Connected)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.sendMessage(this.cachedPingMessage)]; - case 2: - _b.sent(); - return [3 /*break*/, 4]; - case 3: - _a = _b.sent(); - // We don't care about the error. It should be seen elsewhere in the client. - // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering - this.cleanupPingTimer(); - return [3 /*break*/, 4]; - case 4: return [2 /*return*/]; - } - }); - }); }, nextPing); - } - } - }; - HubConnection.prototype.serverTimeout = function () { - // The server hasn't talked to us in a while. It doesn't like us anymore ... :( - // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting. - // tslint:disable-next-line:no-floating-promises - this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")); - }; - HubConnection.prototype.invokeClientMethod = function (invocationMessage) { - var _this = this; - var methods = this.methods[invocationMessage.target.toLowerCase()]; - if (methods) { - try { - methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); }); - } - catch (e) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "A callback for the method " + invocationMessage.target.toLowerCase() + " threw error '" + e + "'."); - } - if (invocationMessage.invocationId) { - // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response. - var message = "Server requested a response, which is not supported in this version of the client."; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, message); - // We don't want to wait on the stop itself. - this.stopPromise = this.stopInternal(new Error(message)); - } - } - else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning, "No client method with the name '" + invocationMessage.target + "' found."); - } - }; - HubConnection.prototype.connectionClosed = function (error) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "HubConnection.connectionClosed(" + error + ") called while in state " + this.connectionState + "."); - // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet. - this.stopDuringStartError = this.stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete."); - // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it. - // If it has already completed, this should just noop. - if (this.handshakeResolver) { - this.handshakeResolver(); - } - this.cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed.")); - this.cleanupTimeout(); - this.cleanupPingTimer(); - if (this.connectionState === HubConnectionState.Disconnecting) { - this.completeClose(error); - } - else if (this.connectionState === HubConnectionState.Connected && this.reconnectPolicy) { - // tslint:disable-next-line:no-floating-promises - this.reconnect(error); - } - else if (this.connectionState === HubConnectionState.Connected) { - this.completeClose(error); - } - // If none of the above if conditions were true were called the HubConnection must be in either: - // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it. - // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt - // and potentially continue the reconnect() loop. - // 3. The Disconnected state in which case we're already done. - }; - HubConnection.prototype.completeClose = function (error) { - var _this = this; - if (this.connectionStarted) { - this.connectionState = HubConnectionState.Disconnected; - this.connectionStarted = false; - try { - this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); }); - } - catch (e) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "An onclose callback called with error '" + error + "' threw error '" + e + "'."); - } - } - }; - HubConnection.prototype.reconnect = function (error) { - return __awaiter(this, void 0, void 0, function () { - var reconnectStartTime, previousReconnectAttempts, retryError, nextRetryDelay, e_4; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - reconnectStartTime = Date.now(); - previousReconnectAttempts = 0; - retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error."); - nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, 0, retryError); - if (nextRetryDelay === null) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."); - this.completeClose(error); - return [2 /*return*/]; - } - this.connectionState = HubConnectionState.Reconnecting; - if (error) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Connection reconnecting because of error '" + error + "'."); - } - else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Connection reconnecting."); - } - if (this.onreconnecting) { - try { - this.reconnectingCallbacks.forEach(function (c) { return c.apply(_this, [error]); }); - } - catch (e) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "An onreconnecting callback called with error '" + error + "' threw error '" + e + "'."); - } - // Exit early if an onreconnecting callback called connection.stop(). - if (this.connectionState !== HubConnectionState.Reconnecting) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting."); - return [2 /*return*/]; - } - } - _a.label = 1; - case 1: - if (!(nextRetryDelay !== null)) return [3 /*break*/, 7]; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Reconnect attempt number " + previousReconnectAttempts + " will start in " + nextRetryDelay + " ms."); - return [4 /*yield*/, new Promise(function (resolve) { - _this.reconnectDelayHandle = setTimeout(resolve, nextRetryDelay); - })]; - case 2: - _a.sent(); - this.reconnectDelayHandle = undefined; - if (this.connectionState !== HubConnectionState.Reconnecting) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting."); - return [2 /*return*/]; - } - _a.label = 3; - case 3: - _a.trys.push([3, 5, , 6]); - return [4 /*yield*/, this.startInternal()]; - case 4: - _a.sent(); - this.connectionState = HubConnectionState.Connected; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "HubConnection reconnected successfully."); - if (this.onreconnected) { - try { - this.reconnectedCallbacks.forEach(function (c) { return c.apply(_this, [_this.connection.connectionId]); }); - } - catch (e) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "An onreconnected callback called with connectionId '" + this.connection.connectionId + "; threw error '" + e + "'."); - } - } - return [2 /*return*/]; - case 5: - e_4 = _a.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Reconnect attempt failed because of error '" + e_4 + "'."); - if (this.connectionState !== HubConnectionState.Reconnecting) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "Connection moved to the '" + this.connectionState + "' from the reconnecting state during reconnect attempt. Done reconnecting."); - // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong. - if (this.connectionState === HubConnectionState.Disconnecting) { - this.completeClose(); - } - return [2 /*return*/]; - } - retryError = e_4 instanceof Error ? e_4 : new Error(e_4.toString()); - nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError); - return [3 /*break*/, 6]; - case 6: return [3 /*break*/, 1]; - case 7: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "Reconnect retries have been exhausted after " + (Date.now() - reconnectStartTime) + " ms and " + previousReconnectAttempts + " failed attempts. Connection disconnecting."); - this.completeClose(); - return [2 /*return*/]; - } - }); - }); - }; - HubConnection.prototype.getNextRetryDelay = function (previousRetryCount, elapsedMilliseconds, retryReason) { - try { - return this.reconnectPolicy.nextRetryDelayInMilliseconds({ - elapsedMilliseconds: elapsedMilliseconds, - previousRetryCount: previousRetryCount, - retryReason: retryReason, - }); - } - catch (e) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "IRetryPolicy.nextRetryDelayInMilliseconds(" + previousRetryCount + ", " + elapsedMilliseconds + ") threw error '" + e + "'."); - return null; - } - }; - HubConnection.prototype.cancelCallbacksWithError = function (error) { - var callbacks = this.callbacks; - this.callbacks = {}; - Object.keys(callbacks) - .forEach(function (key) { - var callback = callbacks[key]; - callback(null, error); - }); - }; - HubConnection.prototype.cleanupPingTimer = function () { - if (this.pingServerHandle) { - clearTimeout(this.pingServerHandle); - this.pingServerHandle = undefined; - } - }; - HubConnection.prototype.cleanupTimeout = function () { - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - } - }; - HubConnection.prototype.createInvocation = function (methodName, args, nonblocking, streamIds) { - if (nonblocking) { - if (streamIds.length !== 0) { - return { - arguments: args, - streamIds: streamIds, - target: methodName, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation, - }; - } - else { - return { - arguments: args, - target: methodName, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation, - }; - } - } - else { - var invocationId = this.invocationId; - this.invocationId++; - if (streamIds.length !== 0) { - return { - arguments: args, - invocationId: invocationId.toString(), - streamIds: streamIds, - target: methodName, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation, - }; - } - else { - return { - arguments: args, - invocationId: invocationId.toString(), - target: methodName, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Invocation, - }; - } - } - }; - HubConnection.prototype.launchStreams = function (streams, promiseQueue) { - var _this = this; - if (streams.length === 0) { - return; - } - // Synchronize stream data so they arrive in-order on the server - if (!promiseQueue) { - promiseQueue = Promise.resolve(); - } - var _loop_1 = function (streamId) { - streams[streamId].subscribe({ - complete: function () { - promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId)); }); - }, - error: function (err) { - var message; - if (err instanceof Error) { - message = err.message; - } - else if (err && err.toString) { - message = err.toString(); - } - else { - message = "Unknown error"; - } - promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId, message)); }); - }, - next: function (item) { - promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createStreamItemMessage(streamId, item)); }); - }, - }); - }; - // We want to iterate over the keys, since the keys are the stream ids - // tslint:disable-next-line:forin - for (var streamId in streams) { - _loop_1(streamId); - } - }; - HubConnection.prototype.replaceStreamingParams = function (args) { - var streams = []; - var streamIds = []; - for (var i = 0; i < args.length; i++) { - var argument = args[i]; - if (this.isObservable(argument)) { - var streamId = this.invocationId; - this.invocationId++; - // Store the stream for later use - streams[streamId] = argument; - streamIds.push(streamId.toString()); - // remove stream from args - args.splice(i, 1); - } - } - return [streams, streamIds]; - }; - HubConnection.prototype.isObservable = function (arg) { - // This allows other stream implementations to just work (like rxjs) - return arg && arg.subscribe && typeof arg.subscribe === "function"; - }; - HubConnection.prototype.createStreamInvocation = function (methodName, args, streamIds) { - var invocationId = this.invocationId; - this.invocationId++; - if (streamIds.length !== 0) { - return { - arguments: args, - invocationId: invocationId.toString(), - streamIds: streamIds, - target: methodName, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].StreamInvocation, - }; - } - else { - return { - arguments: args, - invocationId: invocationId.toString(), - target: methodName, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].StreamInvocation, - }; - } - }; - HubConnection.prototype.createCancelInvocation = function (id) { - return { - invocationId: id, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].CancelInvocation, - }; - }; - HubConnection.prototype.createStreamItemMessage = function (id, item) { - return { - invocationId: id, - item: item, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].StreamItem, - }; - }; - HubConnection.prototype.createCompletionMessage = function (id, error, result) { - if (error) { - return { - error: error, - invocationId: id, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion, - }; - } - return { - invocationId: id, - result: result, - type: _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__["MessageType"].Completion, - }; - }; - return HubConnection; -}()); + return this._httpClient.send(request); + } + getCookieString(url) { + return this._httpClient.getCookieString(url); + } +} +;// CONCATENATED MODULE: ./src/TextMessageFormat.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// Not exported from index +/** @private */ +class TextMessageFormat { + static write(output) { + return `${output}${TextMessageFormat.RecordSeparator}`; + } + static parse(input) { + if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) { + throw new Error("Message is incomplete."); + } + const messages = input.split(TextMessageFormat.RecordSeparator); + messages.pop(); + return messages; + } +} +TextMessageFormat.RecordSeparatorCode = 0x1e; +TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode); - -/***/ }), -/* 13 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HandshakeProtocol", function() { return HandshakeProtocol; }); -/* harmony import */ var _TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +;// CONCATENATED MODULE: ./src/HandshakeProtocol.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /** @private */ -var HandshakeProtocol = /** @class */ (function () { - function HandshakeProtocol() { - } +class HandshakeProtocol { // Handshake request is always JSON - HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) { - return _TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].write(JSON.stringify(handshakeRequest)); - }; - HandshakeProtocol.prototype.parseHandshakeResponse = function (data) { - var responseMessage; - var messageData; - var remainingData; - if (Object(_Utils__WEBPACK_IMPORTED_MODULE_1__["isArrayBuffer"])(data) || (typeof Buffer !== "undefined" && data instanceof Buffer)) { + writeHandshakeRequest(handshakeRequest) { + return TextMessageFormat.write(JSON.stringify(handshakeRequest)); + } + parseHandshakeResponse(data) { + let messageData; + let remainingData; + if (isArrayBuffer(data)) { // Format is binary but still need to read JSON text from handshake response - var binaryData = new Uint8Array(data); - var separatorIndex = binaryData.indexOf(_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].RecordSeparatorCode); + const binaryData = new Uint8Array(data); + const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode); if (separatorIndex === -1) { throw new Error("Message is incomplete."); } // content before separator is handshake response // optional content after is additional messages - var responseLength = separatorIndex + 1; - messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength)); + const responseLength = separatorIndex + 1; + messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength))); remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null; } else { - var textData = data; - var separatorIndex = textData.indexOf(_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].RecordSeparator); + const textData = data; + const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator); if (separatorIndex === -1) { throw new Error("Message is incomplete."); } // content before separator is handshake response // optional content after is additional messages - var responseLength = separatorIndex + 1; + const responseLength = separatorIndex + 1; messageData = textData.substring(0, responseLength); remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null; } // At this point we should have just the single handshake message - var messages = _TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].parse(messageData); - var response = JSON.parse(messages[0]); + const messages = TextMessageFormat.parse(messageData); + const response = JSON.parse(messages[0]); if (response.type) { throw new Error("Expected a handshake response from the server."); } - responseMessage = response; + const responseMessage = response; // multiple messages could have arrived with handshake // return additional data to be parsed as usual, or null if all parsed return [remainingData, responseMessage]; - }; - return HandshakeProtocol; -}()); - - - -/***/ }), -/* 14 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextMessageFormat", function() { return TextMessageFormat; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// Not exported from index -/** @private */ -var TextMessageFormat = /** @class */ (function () { - function TextMessageFormat() { } - TextMessageFormat.write = function (output) { - return "" + output + TextMessageFormat.RecordSeparator; - }; - TextMessageFormat.parse = function (input) { - if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) { - throw new Error("Message is incomplete."); - } - var messages = input.split(TextMessageFormat.RecordSeparator); - messages.pop(); - return messages; - }; - TextMessageFormat.RecordSeparatorCode = 0x1e; - TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode); - return TextMessageFormat; -}()); +} - - -/***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MessageType", function() { return MessageType; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +;// CONCATENATED MODULE: ./src/IHubProtocol.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /** Defines the type of a Hub Message. */ var MessageType; (function (MessageType) { @@ -3455,952 +931,1250 @@ var MessageType; MessageType[MessageType["Ping"] = 6] = "Ping"; /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */ MessageType[MessageType["Close"] = 7] = "Close"; + MessageType[MessageType["Ack"] = 8] = "Ack"; + MessageType[MessageType["Sequence"] = 9] = "Sequence"; })(MessageType || (MessageType = {})); - -/***/ }), -/* 16 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Subject", function() { return Subject; }); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +;// CONCATENATED MODULE: ./src/Subject.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /** Stream implementation to stream items to the server. */ -var Subject = /** @class */ (function () { - function Subject() { +class Subject { + constructor() { this.observers = []; } - Subject.prototype.next = function (item) { - for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { - var observer = _a[_i]; + next(item) { + for (const observer of this.observers) { observer.next(item); } - }; - Subject.prototype.error = function (err) { - for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { - var observer = _a[_i]; + } + error(err) { + for (const observer of this.observers) { if (observer.error) { observer.error(err); } } - }; - Subject.prototype.complete = function () { - for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { - var observer = _a[_i]; + } + complete() { + for (const observer of this.observers) { if (observer.complete) { observer.complete(); } } - }; - Subject.prototype.subscribe = function (observer) { + } + subscribe(observer) { this.observers.push(observer); - return new _Utils__WEBPACK_IMPORTED_MODULE_0__["SubjectSubscription"](this, observer); - }; - return Subject; -}()); - - - -/***/ }), -/* 17 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HubConnectionBuilder", function() { return HubConnectionBuilder; }); -/* harmony import */ var _DefaultReconnectPolicy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18); -/* harmony import */ var _HttpConnection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(19); -/* harmony import */ var _HubConnection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(12); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8); -/* harmony import */ var _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(25); -/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(10); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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; -}; - - - - - - - -// tslint:disable:object-literal-sort-keys -var LogLevelNameMapping = { - trace: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Trace, - debug: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Debug, - info: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Information, - information: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Information, - warn: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Warning, - warning: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Warning, - error: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Error, - critical: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].Critical, - none: _ILogger__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].None, -}; -function parseLogLevel(name) { - // Case-insensitive matching via lower-casing - // Yes, I know case-folding is a complicated problem in Unicode, but we only support - // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse. - var mapping = LogLevelNameMapping[name.toLowerCase()]; - if (typeof mapping !== "undefined") { - return mapping; - } - else { - throw new Error("Unknown log level: " + name); + return new SubjectSubscription(this, observer); } } -/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */ -var HubConnectionBuilder = /** @class */ (function () { - function HubConnectionBuilder() { - } - HubConnectionBuilder.prototype.configureLogging = function (logging) { - _Utils__WEBPACK_IMPORTED_MODULE_6__["Arg"].isRequired(logging, "logging"); - if (isLogger(logging)) { - this.logger = logging; - } - else if (typeof logging === "string") { - var logLevel = parseLogLevel(logging); - this.logger = new _Utils__WEBPACK_IMPORTED_MODULE_6__["ConsoleLogger"](logLevel); - } - else { - this.logger = new _Utils__WEBPACK_IMPORTED_MODULE_6__["ConsoleLogger"](logging); - } - return this; - }; - HubConnectionBuilder.prototype.withUrl = function (url, transportTypeOrOptions) { - _Utils__WEBPACK_IMPORTED_MODULE_6__["Arg"].isRequired(url, "url"); - _Utils__WEBPACK_IMPORTED_MODULE_6__["Arg"].isNotEmpty(url, "url"); - this.url = url; - // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed - // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called. - if (typeof transportTypeOrOptions === "object") { - this.httpConnectionOptions = __assign({}, this.httpConnectionOptions, transportTypeOrOptions); - } - else { - this.httpConnectionOptions = __assign({}, this.httpConnectionOptions, { transport: transportTypeOrOptions }); - } - return this; - }; - /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol. - * - * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use. - */ - HubConnectionBuilder.prototype.withHubProtocol = function (protocol) { - _Utils__WEBPACK_IMPORTED_MODULE_6__["Arg"].isRequired(protocol, "protocol"); - this.protocol = protocol; - return this; - }; - HubConnectionBuilder.prototype.withAutomaticReconnect = function (retryDelaysOrReconnectPolicy) { - if (this.reconnectPolicy) { - throw new Error("A reconnectPolicy has already been set."); - } - if (!retryDelaysOrReconnectPolicy) { - this.reconnectPolicy = new _DefaultReconnectPolicy__WEBPACK_IMPORTED_MODULE_0__["DefaultReconnectPolicy"](); - } - else if (Array.isArray(retryDelaysOrReconnectPolicy)) { - this.reconnectPolicy = new _DefaultReconnectPolicy__WEBPACK_IMPORTED_MODULE_0__["DefaultReconnectPolicy"](retryDelaysOrReconnectPolicy); - } - else { - this.reconnectPolicy = retryDelaysOrReconnectPolicy; - } - return this; - }; - /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder. - * - * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}. - */ - HubConnectionBuilder.prototype.build = function () { - // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one - // provided to configureLogger - var httpConnectionOptions = this.httpConnectionOptions || {}; - // If it's 'null', the user **explicitly** asked for null, don't mess with it. - if (httpConnectionOptions.logger === undefined) { - // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it. - httpConnectionOptions.logger = this.logger; - } - // Now create the connection - if (!this.url) { - throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection."); - } - var connection = new _HttpConnection__WEBPACK_IMPORTED_MODULE_1__["HttpConnection"](this.url, httpConnectionOptions); - return _HubConnection__WEBPACK_IMPORTED_MODULE_2__["HubConnection"].create(connection, this.logger || _Loggers__WEBPACK_IMPORTED_MODULE_5__["NullLogger"].instance, this.protocol || new _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_4__["JsonHubProtocol"](), this.reconnectPolicy); - }; - return HubConnectionBuilder; -}()); -function isLogger(logger) { - return logger.log !== undefined; +;// CONCATENATED MODULE: ./src/MessageBuffer.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + + +/** @private */ +class MessageBuffer { + constructor(protocol, connection, bufferSize) { + this._bufferSize = 100000; + this._messages = []; + this._totalMessageCount = 0; + this._waitForSequenceMessage = false; + // Message IDs start at 1 and always increment by 1 + this._nextReceivingSequenceId = 1; + this._latestReceivedSequenceId = 0; + this._bufferedByteCount = 0; + this._reconnectInProgress = false; + this._protocol = protocol; + this._connection = connection; + this._bufferSize = bufferSize; + } + async _send(message) { + const serializedMessage = this._protocol.writeMessage(message); + let backpressurePromise = Promise.resolve(); + // Only count invocation messages. Acks, pings, etc. don't need to be resent on reconnect + if (this._isInvocationMessage(message)) { + this._totalMessageCount++; + let backpressurePromiseResolver = () => { }; + let backpressurePromiseRejector = () => { }; + if (isArrayBuffer(serializedMessage)) { + this._bufferedByteCount += serializedMessage.byteLength; + } + else { + this._bufferedByteCount += serializedMessage.length; + } + if (this._bufferedByteCount >= this._bufferSize) { + backpressurePromise = new Promise((resolve, reject) => { + backpressurePromiseResolver = resolve; + backpressurePromiseRejector = reject; + }); + } + this._messages.push(new BufferedItem(serializedMessage, this._totalMessageCount, backpressurePromiseResolver, backpressurePromiseRejector)); + } + try { + // If this is set it means we are reconnecting or resending + // We don't want to send on a disconnected connection + // And we don't want to send if resend is running since that would mean sending + // this message twice + if (!this._reconnectInProgress) { + await this._connection.send(serializedMessage); + } + } + catch { + this._disconnected(); + } + await backpressurePromise; + } + _ack(ackMessage) { + let newestAckedMessage = -1; + // Find index of newest message being acked + for (let index = 0; index < this._messages.length; index++) { + const element = this._messages[index]; + if (element._id <= ackMessage.sequenceId) { + newestAckedMessage = index; + if (isArrayBuffer(element._message)) { + this._bufferedByteCount -= element._message.byteLength; + } + else { + this._bufferedByteCount -= element._message.length; + } + // resolve items that have already been sent and acked + element._resolver(); + } + else if (this._bufferedByteCount < this._bufferSize) { + // resolve items that now fall under the buffer limit but haven't been acked + element._resolver(); + } + else { + break; + } + } + if (newestAckedMessage !== -1) { + // We're removing everything including the message pointed to, so add 1 + this._messages = this._messages.slice(newestAckedMessage + 1); + } + } + _shouldProcessMessage(message) { + if (this._waitForSequenceMessage) { + if (message.type !== MessageType.Sequence) { + return false; + } + else { + this._waitForSequenceMessage = false; + return true; + } + } + // No special processing for acks, pings, etc. + if (!this._isInvocationMessage(message)) { + return true; + } + const currentId = this._nextReceivingSequenceId; + this._nextReceivingSequenceId++; + if (currentId <= this._latestReceivedSequenceId) { + if (currentId === this._latestReceivedSequenceId) { + // Should only hit this if we just reconnected and the server is sending + // Messages it has buffered, which would mean it hasn't seen an Ack for these messages + this._ackTimer(); + } + // Ignore, this is a duplicate message + return false; + } + this._latestReceivedSequenceId = currentId; + // Only start the timer for sending an Ack message when we have a message to ack. This also conveniently solves + // timer throttling by not having a recursive timer, and by starting the timer via a network call (recv) + this._ackTimer(); + return true; + } + _resetSequence(message) { + if (message.sequenceId > this._nextReceivingSequenceId) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")); + return; + } + this._nextReceivingSequenceId = message.sequenceId; + } + _disconnected() { + this._reconnectInProgress = true; + this._waitForSequenceMessage = true; + } + async _resend() { + const sequenceId = this._messages.length !== 0 + ? this._messages[0]._id + : this._totalMessageCount + 1; + await this._connection.send(this._protocol.writeMessage({ type: MessageType.Sequence, sequenceId })); + // Get a local variable to the _messages, just in case messages are acked while resending + // Which would slice the _messages array (which creates a new copy) + const messages = this._messages; + for (const element of messages) { + await this._connection.send(element._message); + } + this._reconnectInProgress = false; + } + _dispose(error) { + error !== null && error !== void 0 ? error : (error = new Error("Unable to reconnect to server.")); + // Unblock backpressure if any + for (const element of this._messages) { + element._rejector(error); + } + } + _isInvocationMessage(message) { + // There is no way to check if something implements an interface. + // So we individually check the messages in a switch statement. + // To make sure we don't miss any message types we rely on the compiler + // seeing the function returns a value and it will do the + // exhaustive check for us on the switch statement, since we don't use 'case default' + switch (message.type) { + case MessageType.Invocation: + case MessageType.StreamItem: + case MessageType.Completion: + case MessageType.StreamInvocation: + case MessageType.CancelInvocation: + return true; + case MessageType.Close: + case MessageType.Sequence: + case MessageType.Ping: + case MessageType.Ack: + return false; + } + } + _ackTimer() { + if (this._ackTimerHandle === undefined) { + this._ackTimerHandle = setTimeout(async () => { + try { + if (!this._reconnectInProgress) { + await this._connection.send(this._protocol.writeMessage({ type: MessageType.Ack, sequenceId: this._latestReceivedSequenceId })); + } + // Ignore errors, that means the connection is closed and we don't care about the Ack message anymore. + } + catch { } + clearTimeout(this._ackTimerHandle); + this._ackTimerHandle = undefined; + // 1 second delay so we don't spam Ack messages if there are many messages being received at once. + }, 1000); + } + } +} +class BufferedItem { + constructor(message, id, resolver, rejector) { + this._message = message; + this._id = id; + this._resolver = resolver; + this._rejector = rejector; + } } +;// CONCATENATED MODULE: ./src/HubConnection.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. -/***/ }), -/* 18 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultReconnectPolicy", function() { return DefaultReconnectPolicy; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// 0, 2, 10, 30 second delays before reconnect attempts. -var DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null]; -/** @private */ -var DefaultReconnectPolicy = /** @class */ (function () { - function DefaultReconnectPolicy(retryDelays) { - this.retryDelays = retryDelays !== undefined ? retryDelays.concat([null]) : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS; + + + + + +const DEFAULT_TIMEOUT_IN_MS = 30 * 1000; +const DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000; +const DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE = 100000; +/** Describes the current state of the {@link HubConnection} to the server. */ +var HubConnectionState; +(function (HubConnectionState) { + /** The hub connection is disconnected. */ + HubConnectionState["Disconnected"] = "Disconnected"; + /** The hub connection is connecting. */ + HubConnectionState["Connecting"] = "Connecting"; + /** The hub connection is connected. */ + HubConnectionState["Connected"] = "Connected"; + /** The hub connection is disconnecting. */ + HubConnectionState["Disconnecting"] = "Disconnecting"; + /** The hub connection is reconnecting. */ + HubConnectionState["Reconnecting"] = "Reconnecting"; +})(HubConnectionState || (HubConnectionState = {})); +/** Represents a connection to a SignalR Hub. */ +class HubConnection { + /** @internal */ + // Using a public static factory method means we can have a private constructor and an _internal_ + // create method that can be used by HubConnectionBuilder. An "internal" constructor would just + // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a + // public parameter-less constructor. + static create(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) { + return new HubConnection(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize); } - DefaultReconnectPolicy.prototype.nextRetryDelayInMilliseconds = function (retryContext) { - return this.retryDelays[retryContext.previousRetryCount]; - }; - return DefaultReconnectPolicy; -}()); - - - -/***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpConnection", function() { return HttpConnection; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransportSendQueue", function() { return TransportSendQueue; }); -/* harmony import */ var _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20); -/* harmony import */ var _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(21); -/* harmony import */ var _ServerSentEventsTransport__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(23); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9); -/* harmony import */ var _WebSocketTransport__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(24); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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]; + constructor(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) { + this._nextKeepAlive = 0; + this._freezeEventListener = () => { + this._logger.log(LogLevel.Warning, "The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep"); + }; + Arg.isRequired(connection, "connection"); + Arg.isRequired(logger, "logger"); + Arg.isRequired(protocol, "protocol"); + this.serverTimeoutInMilliseconds = serverTimeoutInMilliseconds !== null && serverTimeoutInMilliseconds !== void 0 ? serverTimeoutInMilliseconds : DEFAULT_TIMEOUT_IN_MS; + this.keepAliveIntervalInMilliseconds = keepAliveIntervalInMilliseconds !== null && keepAliveIntervalInMilliseconds !== void 0 ? keepAliveIntervalInMilliseconds : DEFAULT_PING_INTERVAL_IN_MS; + this._statefulReconnectBufferSize = statefulReconnectBufferSize !== null && statefulReconnectBufferSize !== void 0 ? statefulReconnectBufferSize : DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE; + this._logger = logger; + this._protocol = protocol; + this.connection = connection; + this._reconnectPolicy = reconnectPolicy; + this._handshakeProtocol = new HandshakeProtocol(); + this.connection.onreceive = (data) => this._processIncomingData(data); + this.connection.onclose = (error) => this._connectionClosed(error); + this._callbacks = {}; + this._methods = {}; + this._closedCallbacks = []; + this._reconnectingCallbacks = []; + this._reconnectedCallbacks = []; + this._invocationId = 0; + this._receivedHandshakeResponse = false; + this._connectionState = HubConnectionState.Disconnected; + this._connectionStarted = false; + this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping }); } - return t; -}; -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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; + /** Indicates the state of the {@link HubConnection} to the server. */ + get state() { + return this._connectionState; + } + /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either + * in the disconnected state or if the negotiation step was skipped. + */ + get connectionId() { + return this.connection ? (this.connection.connectionId || null) : null; + } + /** Indicates the url of the {@link HubConnection} to the server. */ + get baseUrl() { + return this.connection.baseUrl || ""; + } + /** + * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or + * Reconnecting states. + * @param {string} url The url to connect to. + */ + set baseUrl(url) { + if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) { + throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url."); + } + if (!url) { + throw new Error("The HubConnection url must be a valid url."); + } + this.connection.baseUrl = url; + } + /** Starts the connection. + * + * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error. + */ + start() { + this._startPromise = this._startWithStateTransitions(); + return this._startPromise; + } + async _startWithStateTransitions() { + if (this._connectionState !== HubConnectionState.Disconnected) { + return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state.")); + } + this._connectionState = HubConnectionState.Connecting; + this._logger.log(LogLevel.Debug, "Starting HubConnection."); + try { + await this._startInternal(); + if (Platform.isBrowser) { + // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working + window.document.addEventListener("freeze", this._freezeEventListener); } - 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 }; + this._connectionState = HubConnectionState.Connected; + this._connectionStarted = true; + this._logger.log(LogLevel.Debug, "HubConnection connected successfully."); + } + catch (e) { + this._connectionState = HubConnectionState.Disconnected; + this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`); + return Promise.reject(e); + } } -}; - - - - - - - -var MAX_REDIRECTS = 100; -/** @private */ -var HttpConnection = /** @class */ (function () { - function HttpConnection(url, options) { - if (options === void 0) { options = {}; } - this.stopPromiseResolver = function () { }; - this.features = {}; - this.negotiateVersion = 1; - _Utils__WEBPACK_IMPORTED_MODULE_5__["Arg"].isRequired(url, "url"); - this.logger = Object(_Utils__WEBPACK_IMPORTED_MODULE_5__["createLogger"])(options.logger); - this.baseUrl = this.resolveUrl(url); - options = options || {}; - options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent; - if (typeof options.withCredentials === "boolean" || options.withCredentials === undefined) { - options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials; - } - else { - throw new Error("withCredentials option was not a 'boolean' or 'undefined' value"); - } - var webSocketModule = null; - var eventSourceModule = null; - if (_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isNode && "function" !== "undefined") { - // In order to ignore the dynamic require in webpack builds we need to do this magic - // @ts-ignore: TS doesn't know about these names - var requireFunc = true ? require : undefined; - webSocketModule = requireFunc("ws"); - eventSourceModule = requireFunc("eventsource"); - } - if (!_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isNode && typeof WebSocket !== "undefined" && !options.WebSocket) { - options.WebSocket = WebSocket; - } - else if (_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isNode && !options.WebSocket) { - if (webSocketModule) { - options.WebSocket = webSocketModule; + async _startInternal() { + this._stopDuringStartError = undefined; + this._receivedHandshakeResponse = false; + // Set up the promise before any connection is (re)started otherwise it could race with received messages + const handshakePromise = new Promise((resolve, reject) => { + this._handshakeResolver = resolve; + this._handshakeRejecter = reject; + }); + await this.connection.start(this._protocol.transferFormat); + try { + let version = this._protocol.version; + if (!this.connection.features.reconnect) { + // Stateful Reconnect starts with HubProtocol version 2, newer clients connecting to older servers will fail to connect due to + // the handshake only supporting version 1, so we will try to send version 1 during the handshake to keep old servers working. + version = 1; + } + const handshakeRequest = { + protocol: this._protocol.name, + version, + }; + this._logger.log(LogLevel.Debug, "Sending handshake request."); + await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest)); + this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`); + // defensively cleanup timeout in case we receive a message from the server before we finish start + this._cleanupTimeout(); + this._resetTimeoutPeriod(); + this._resetKeepAliveInterval(); + await handshakePromise; + // It's important to check the stopDuringStartError instead of just relying on the handshakePromise + // being rejected on close, because this continuation can run after both the handshake completed successfully + // and the connection was closed. + if (this._stopDuringStartError) { + // It's important to throw instead of returning a rejected promise, because we don't want to allow any state + // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise + // will cause the calling continuation to get scheduled to run later. + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw this._stopDuringStartError; + } + const useStatefulReconnect = this.connection.features.reconnect || false; + if (useStatefulReconnect) { + this._messageBuffer = new MessageBuffer(this._protocol, this.connection, this._statefulReconnectBufferSize); + this.connection.features.disconnected = this._messageBuffer._disconnected.bind(this._messageBuffer); + this.connection.features.resend = () => { + if (this._messageBuffer) { + return this._messageBuffer._resend(); + } + }; + } + if (!this.connection.features.inherentKeepAlive) { + await this._sendMessage(this._cachedPingMessage); } } - if (!_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isNode && typeof EventSource !== "undefined" && !options.EventSource) { - options.EventSource = EventSource; + catch (e) { + this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`); + this._cleanupTimeout(); + this._cleanupPingTimer(); + // HttpConnection.stop() should not complete until after the onclose callback is invoked. + // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes. + await this.connection.stop(e); + throw e; } - else if (_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isNode && !options.EventSource) { - if (typeof eventSourceModule !== "undefined") { - options.EventSource = eventSourceModule; - } - } - this.httpClient = options.httpClient || new _DefaultHttpClient__WEBPACK_IMPORTED_MODULE_0__["DefaultHttpClient"](this.logger); - this.connectionState = "Disconnected" /* Disconnected */; - this.connectionStarted = false; - this.options = options; - this.onreceive = null; - this.onclose = null; } - HttpConnection.prototype.start = function (transferFormat) { - return __awaiter(this, void 0, void 0, function () { - var message, message; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - transferFormat = transferFormat || _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"].Binary; - _Utils__WEBPACK_IMPORTED_MODULE_5__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"], "transferFormat"); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Starting connection with transfer format '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][transferFormat] + "'."); - if (this.connectionState !== "Disconnected" /* Disconnected */) { - return [2 /*return*/, Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."))]; - } - this.connectionState = "Connecting" /* Connecting */; - this.startInternalPromise = this.startInternal(transferFormat); - return [4 /*yield*/, this.startInternalPromise]; - case 1: - _a.sent(); - if (!(this.connectionState === "Disconnecting" /* Disconnecting */)) return [3 /*break*/, 3]; - message = "Failed to start the HttpConnection before stop() was called."; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, message); - // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise. - return [4 /*yield*/, this.stopPromise]; - case 2: - // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise. - _a.sent(); - return [2 /*return*/, Promise.reject(new Error(message))]; - case 3: - if (this.connectionState !== "Connected" /* Connected */) { - message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!"; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, message); - return [2 /*return*/, Promise.reject(new Error(message))]; - } - _a.label = 4; - case 4: - this.connectionStarted = true; - return [2 /*return*/]; - } - }); - }); - }; - HttpConnection.prototype.send = function (data) { - if (this.connectionState !== "Connected" /* Connected */) { - return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")); + /** Stops the connection. + * + * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error. + */ + async stop() { + // Capture the start promise before the connection might be restarted in an onclose callback. + const startPromise = this._startPromise; + this.connection.features.reconnect = false; + this._stopPromise = this._stopInternal(); + await this._stopPromise; + try { + // Awaiting undefined continues immediately + await startPromise; } - if (!this.sendQueue) { - this.sendQueue = new TransportSendQueue(this.transport); + catch (e) { + // This exception is returned to the user as a rejected Promise from the start method. } - // Transport will not be null if state is connected - return this.sendQueue.send(data); - }; - HttpConnection.prototype.stop = function (error) { - return __awaiter(this, void 0, void 0, function () { - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.connectionState === "Disconnected" /* Disconnected */) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnected state."); - return [2 /*return*/, Promise.resolve()]; - } - if (this.connectionState === "Disconnecting" /* Disconnecting */) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state."); - return [2 /*return*/, this.stopPromise]; - } - this.connectionState = "Disconnecting" /* Disconnecting */; - this.stopPromise = new Promise(function (resolve) { - // Don't complete stop() until stopConnection() completes. - _this.stopPromiseResolver = resolve; - }); - // stopInternal should never throw so just observe it. - return [4 /*yield*/, this.stopInternal(error)]; - case 1: - // stopInternal should never throw so just observe it. - _a.sent(); - return [4 /*yield*/, this.stopPromise]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - HttpConnection.prototype.stopInternal = function (error) { - return __awaiter(this, void 0, void 0, function () { - var e_1, e_2; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - // Set error as soon as possible otherwise there is a race between - // the transport closing and providing an error and the error from a close message - // We would prefer the close message error. - this.stopError = error; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.startInternalPromise]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - e_1 = _a.sent(); - return [3 /*break*/, 4]; - case 4: - if (!this.transport) return [3 /*break*/, 9]; - _a.label = 5; - case 5: - _a.trys.push([5, 7, , 8]); - return [4 /*yield*/, this.transport.stop()]; - case 6: - _a.sent(); - return [3 /*break*/, 8]; - case 7: - e_2 = _a.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "HttpConnection.transport.stop() threw error '" + e_2 + "'."); - this.stopConnection(); - return [3 /*break*/, 8]; - case 8: - this.transport = undefined; - return [3 /*break*/, 10]; - case 9: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed."); - _a.label = 10; - case 10: return [2 /*return*/]; - } - }); - }); - }; - HttpConnection.prototype.startInternal = function (transferFormat) { - return __awaiter(this, void 0, void 0, function () { - var url, negotiateResponse, redirects, _loop_1, this_1, e_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - url = this.baseUrl; - this.accessTokenFactory = this.options.accessTokenFactory; - _a.label = 1; - case 1: - _a.trys.push([1, 12, , 13]); - if (!this.options.skipNegotiation) return [3 /*break*/, 5]; - if (!(this.options.transport === _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets)) return [3 /*break*/, 3]; - // No need to add a connection ID in this case - this.transport = this.constructTransport(_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets); - // We should just call connect directly in this case. - // No fallback or negotiate in this case. - return [4 /*yield*/, this.startTransport(url, transferFormat)]; - case 2: - // We should just call connect directly in this case. - // No fallback or negotiate in this case. - _a.sent(); - return [3 /*break*/, 4]; - case 3: throw new Error("Negotiation can only be skipped when using the WebSocket transport directly."); - case 4: return [3 /*break*/, 11]; - case 5: - negotiateResponse = null; - redirects = 0; - _loop_1 = function () { - var accessToken_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this_1.getNegotiationResponse(url)]; - case 1: - negotiateResponse = _a.sent(); - // the user tries to stop the connection when it is being started - if (this_1.connectionState === "Disconnecting" /* Disconnecting */ || this_1.connectionState === "Disconnected" /* Disconnected */) { - throw new Error("The connection was stopped during negotiation."); - } - if (negotiateResponse.error) { - throw new Error(negotiateResponse.error); - } - if (negotiateResponse.ProtocolVersion) { - throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."); - } - if (negotiateResponse.url) { - url = negotiateResponse.url; - } - if (negotiateResponse.accessToken) { - accessToken_1 = negotiateResponse.accessToken; - this_1.accessTokenFactory = function () { return accessToken_1; }; - } - redirects++; - return [2 /*return*/]; - } - }); - }; - this_1 = this; - _a.label = 6; - case 6: return [5 /*yield**/, _loop_1()]; - case 7: - _a.sent(); - _a.label = 8; - case 8: - if (negotiateResponse.url && redirects < MAX_REDIRECTS) return [3 /*break*/, 6]; - _a.label = 9; - case 9: - if (redirects === MAX_REDIRECTS && negotiateResponse.url) { - throw new Error("Negotiate redirection limit exceeded."); - } - return [4 /*yield*/, this.createTransport(url, this.options.transport, negotiateResponse, transferFormat)]; - case 10: - _a.sent(); - _a.label = 11; - case 11: - if (this.transport instanceof _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__["LongPollingTransport"]) { - this.features.inherentKeepAlive = true; - } - if (this.connectionState === "Connecting" /* Connecting */) { - // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise. - // start() will handle the case when stop was called and startInternal exits still in the disconnecting state. - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "The HttpConnection connected successfully."); - this.connectionState = "Connected" /* Connected */; - } - return [3 /*break*/, 13]; - case 12: - e_3 = _a.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Failed to start the connection: " + e_3); - this.connectionState = "Disconnected" /* Disconnected */; - this.transport = undefined; - // if start fails, any active calls to stop assume that start will complete the stop promise - this.stopPromiseResolver(); - return [2 /*return*/, Promise.reject(e_3)]; - case 13: return [2 /*return*/]; - } - }); - }); - }; - HttpConnection.prototype.getNegotiationResponse = function (url) { - return __awaiter(this, void 0, void 0, function () { - var headers, token, _a, name, value, negotiateUrl, response, negotiateResponse, e_4; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - headers = {}; - if (!this.accessTokenFactory) return [3 /*break*/, 2]; - return [4 /*yield*/, this.accessTokenFactory()]; - case 1: - token = _b.sent(); - if (token) { - headers["Authorization"] = "Bearer " + token; - } - _b.label = 2; - case 2: - _a = Object(_Utils__WEBPACK_IMPORTED_MODULE_5__["getUserAgentHeader"])(), name = _a[0], value = _a[1]; - headers[name] = value; - negotiateUrl = this.resolveNegotiateUrl(url); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Sending negotiation request: " + negotiateUrl + "."); - _b.label = 3; - case 3: - _b.trys.push([3, 5, , 6]); - return [4 /*yield*/, this.httpClient.post(negotiateUrl, { - content: "", - headers: __assign({}, headers, this.options.headers), - withCredentials: this.options.withCredentials, - })]; - case 4: - response = _b.sent(); - if (response.statusCode !== 200) { - return [2 /*return*/, Promise.reject(new Error("Unexpected status code returned from negotiate '" + response.statusCode + "'"))]; - } - negotiateResponse = JSON.parse(response.content); - if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) { - // Negotiate version 0 doesn't use connectionToken - // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version - negotiateResponse.connectionToken = negotiateResponse.connectionId; - } - return [2 /*return*/, negotiateResponse]; - case 5: - e_4 = _b.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Failed to complete negotiation with the server: " + e_4); - return [2 /*return*/, Promise.reject(e_4)]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - HttpConnection.prototype.createConnectUrl = function (url, connectionToken) { - if (!connectionToken) { - return url; + } + _stopInternal(error) { + if (this._connectionState === HubConnectionState.Disconnected) { + this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`); + return Promise.resolve(); } - return url + (url.indexOf("?") === -1 ? "?" : "&") + ("id=" + connectionToken); - }; - HttpConnection.prototype.createTransport = function (url, requestedTransport, negotiateResponse, requestedTransferFormat) { - return __awaiter(this, void 0, void 0, function () { - var connectUrl, transportExceptions, transports, negotiate, _i, transports_1, endpoint, transportOrError, ex_1, ex_2, message; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - connectUrl = this.createConnectUrl(url, negotiateResponse.connectionToken); - if (!this.isITransport(requestedTransport)) return [3 /*break*/, 2]; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Connection was provided an instance of ITransport, using that directly."); - this.transport = requestedTransport; - return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)]; - case 1: - _a.sent(); - this.connectionId = negotiateResponse.connectionId; - return [2 /*return*/]; - case 2: - transportExceptions = []; - transports = negotiateResponse.availableTransports || []; - negotiate = negotiateResponse; - _i = 0, transports_1 = transports; - _a.label = 3; - case 3: - if (!(_i < transports_1.length)) return [3 /*break*/, 13]; - endpoint = transports_1[_i]; - transportOrError = this.resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat); - if (!(transportOrError instanceof Error)) return [3 /*break*/, 4]; - // Store the error and continue, we don't want to cause a re-negotiate in these cases - transportExceptions.push(endpoint.transport + " failed: " + transportOrError); - return [3 /*break*/, 12]; - case 4: - if (!this.isITransport(transportOrError)) return [3 /*break*/, 12]; - this.transport = transportOrError; - if (!!negotiate) return [3 /*break*/, 9]; - _a.label = 5; - case 5: - _a.trys.push([5, 7, , 8]); - return [4 /*yield*/, this.getNegotiationResponse(url)]; - case 6: - negotiate = _a.sent(); - return [3 /*break*/, 8]; - case 7: - ex_1 = _a.sent(); - return [2 /*return*/, Promise.reject(ex_1)]; - case 8: - connectUrl = this.createConnectUrl(url, negotiate.connectionToken); - _a.label = 9; - case 9: - _a.trys.push([9, 11, , 12]); - return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)]; - case 10: - _a.sent(); - this.connectionId = negotiate.connectionId; - return [2 /*return*/]; - case 11: - ex_2 = _a.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Failed to start the transport '" + endpoint.transport + "': " + ex_2); - negotiate = undefined; - transportExceptions.push(endpoint.transport + " failed: " + ex_2); - if (this.connectionState !== "Connecting" /* Connecting */) { - message = "Failed to select transport before stop() was called."; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, message); - return [2 /*return*/, Promise.reject(new Error(message))]; - } - return [3 /*break*/, 12]; - case 12: - _i++; - return [3 /*break*/, 3]; - case 13: - if (transportExceptions.length > 0) { - return [2 /*return*/, Promise.reject(new Error("Unable to connect to the server with any of the available transports. " + transportExceptions.join(" ")))]; - } - return [2 /*return*/, Promise.reject(new Error("None of the transports supported by the client are supported by the server."))]; - } + if (this._connectionState === HubConnectionState.Disconnecting) { + this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`); + return this._stopPromise; + } + const state = this._connectionState; + this._connectionState = HubConnectionState.Disconnecting; + this._logger.log(LogLevel.Debug, "Stopping HubConnection."); + if (this._reconnectDelayHandle) { + // We're in a reconnect delay which means the underlying connection is currently already stopped. + // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and + // fire the onclose callbacks. + this._logger.log(LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting."); + clearTimeout(this._reconnectDelayHandle); + this._reconnectDelayHandle = undefined; + this._completeClose(); + return Promise.resolve(); + } + if (state === HubConnectionState.Connected) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._sendCloseMessage(); + } + this._cleanupTimeout(); + this._cleanupPingTimer(); + this._stopDuringStartError = error || new AbortError("The connection was stopped before the hub handshake could complete."); + // HttpConnection.stop() should not complete until after either HttpConnection.start() fails + // or the onclose callback is invoked. The onclose callback will transition the HubConnection + // to the disconnected state if need be before HttpConnection.stop() completes. + return this.connection.stop(error); + } + async _sendCloseMessage() { + try { + await this._sendWithProtocol(this._createCloseMessage()); + } + catch { + // Ignore, this is a best effort attempt to let the server know the client closed gracefully. + } + } + /** Invokes a streaming hub method on the server using the specified name and arguments. + * + * @typeparam T The type of the items returned by the server. + * @param {string} methodName The name of the server method to invoke. + * @param {any[]} args The arguments used to invoke the server method. + * @returns {IStreamResult} An object that yields results from the server as they are received. + */ + stream(methodName, ...args) { + const [streams, streamIds] = this._replaceStreamingParams(args); + const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds); + // eslint-disable-next-line prefer-const + let promiseQueue; + const subject = new Subject(); + subject.cancelCallback = () => { + const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId); + delete this._callbacks[invocationDescriptor.invocationId]; + return promiseQueue.then(() => { + return this._sendWithProtocol(cancelInvocation); }); - }); - }; - HttpConnection.prototype.constructTransport = function (transport) { - switch (transport) { - case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets: - if (!this.options.WebSocket) { - throw new Error("'WebSocket' is not supported in your environment."); - } - return new _WebSocketTransport__WEBPACK_IMPORTED_MODULE_6__["WebSocketTransport"](this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket, this.options.headers || {}); - case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents: - if (!this.options.EventSource) { - throw new Error("'EventSource' is not supported in your environment."); - } - return new _ServerSentEventsTransport__WEBPACK_IMPORTED_MODULE_4__["ServerSentEventsTransport"](this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource, this.options.withCredentials, this.options.headers || {}); - case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].LongPolling: - return new _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__["LongPollingTransport"](this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.withCredentials, this.options.headers || {}); - default: - throw new Error("Unknown transport: " + transport + "."); - } - }; - HttpConnection.prototype.startTransport = function (url, transferFormat) { - var _this = this; - this.transport.onreceive = this.onreceive; - this.transport.onclose = function (e) { return _this.stopConnection(e); }; - return this.transport.connect(url, transferFormat); - }; - HttpConnection.prototype.resolveTransportOrError = function (endpoint, requestedTransport, requestedTransferFormat) { - var transport = _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][endpoint.transport]; - if (transport === null || transport === undefined) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client."); - return new Error("Skipping transport '" + endpoint.transport + "' because it is not supported by this client."); - } - else { - if (transportMatches(requestedTransport, transport)) { - var transferFormats = endpoint.transferFormats.map(function (s) { return _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][s]; }); - if (transferFormats.indexOf(requestedTransferFormat) >= 0) { - if ((transport === _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets && !this.options.WebSocket) || - (transport === _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents && !this.options.EventSource)) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' because it is not supported in your environment.'"); - return new Error("'" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' is not supported in your environment."); + }; + this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => { + if (error) { + subject.error(error); + return; + } + else if (invocationEvent) { + // invocationEvent will not be null when an error is not passed to the callback + if (invocationEvent.type === MessageType.Completion) { + if (invocationEvent.error) { + subject.error(new Error(invocationEvent.error)); } else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Selecting transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "'."); - try { - return this.constructTransport(transport); - } - catch (ex) { - return ex; - } + subject.complete(); } } else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' because it does not support the requested transfer format '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][requestedTransferFormat] + "'."); - return new Error("'" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' does not support " + _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][requestedTransferFormat] + "."); + subject.next((invocationEvent.item)); } } - else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Skipping transport '" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' because it was disabled by the client."); - return new Error("'" + _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport] + "' is disabled by the client."); - } - } - }; - HttpConnection.prototype.isITransport = function (transport) { - return transport && typeof (transport) === "object" && "connect" in transport; - }; - HttpConnection.prototype.stopConnection = function (error) { - var _this = this; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "HttpConnection.stopConnection(" + error + ") called while in state " + this.connectionState + "."); - this.transport = undefined; - // If we have a stopError, it takes precedence over the error from the transport - error = this.stopError || error; - this.stopError = undefined; - if (this.connectionState === "Disconnected" /* Disconnected */) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is already in the disconnected state."); - return; - } - if (this.connectionState === "Connecting" /* Connecting */) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Warning, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is still in the connecting state."); - throw new Error("HttpConnection.stopConnection(" + error + ") was called while the connection is still in the connecting state."); - } - if (this.connectionState === "Disconnecting" /* Disconnecting */) { - // A call to stop() induced this call to stopConnection and needs to be completed. - // Any stop() awaiters will be scheduled to continue after the onclose callback fires. - this.stopPromiseResolver(); - } - if (error) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "Connection disconnected with error '" + error + "'."); + }; + promiseQueue = this._sendWithProtocol(invocationDescriptor) + .catch((e) => { + subject.error(e); + delete this._callbacks[invocationDescriptor.invocationId]; + }); + this._launchStreams(streams, promiseQueue); + return subject; + } + _sendMessage(message) { + this._resetKeepAliveInterval(); + return this.connection.send(message); + } + /** + * Sends a js object to the server. + * @param message The js object to serialize and send. + */ + _sendWithProtocol(message) { + if (this._messageBuffer) { + return this._messageBuffer._send(message); } else { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information, "Connection disconnected."); + return this._sendMessage(this._protocol.writeMessage(message)); } - if (this.sendQueue) { - this.sendQueue.stop().catch(function (e) { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "TransportSendQueue.stop() threw error '" + e + "'."); - }); - this.sendQueue = undefined; - } - this.connectionId = undefined; - this.connectionState = "Disconnected" /* Disconnected */; - if (this.connectionStarted) { - this.connectionStarted = false; - try { - if (this.onclose) { - this.onclose(error); + } + /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver. + * + * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still + * be processing the invocation. + * + * @param {string} methodName The name of the server method to invoke. + * @param {any[]} args The arguments used to invoke the server method. + * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error. + */ + send(methodName, ...args) { + const [streams, streamIds] = this._replaceStreamingParams(args); + const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds)); + this._launchStreams(streams, sendPromise); + return sendPromise; + } + /** Invokes a hub method on the server using the specified name and arguments. + * + * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise + * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of + * resolving the Promise. + * + * @typeparam T The expected return type. + * @param {string} methodName The name of the server method to invoke. + * @param {any[]} args The arguments used to invoke the server method. + * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error. + */ + invoke(methodName, ...args) { + const [streams, streamIds] = this._replaceStreamingParams(args); + const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds); + const p = new Promise((resolve, reject) => { + // invocationId will always have a value for a non-blocking invocation + this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => { + if (error) { + reject(error); + return; } + else if (invocationEvent) { + // invocationEvent will not be null when an error is not passed to the callback + if (invocationEvent.type === MessageType.Completion) { + if (invocationEvent.error) { + reject(new Error(invocationEvent.error)); + } + else { + resolve(invocationEvent.result); + } + } + else { + reject(new Error(`Unexpected message type: ${invocationEvent.type}`)); + } + } + }; + const promiseQueue = this._sendWithProtocol(invocationDescriptor) + .catch((e) => { + reject(e); + // invocationId will always have a value for a non-blocking invocation + delete this._callbacks[invocationDescriptor.invocationId]; + }); + this._launchStreams(streams, promiseQueue); + }); + return p; + } + on(methodName, newMethod) { + if (!methodName || !newMethod) { + return; + } + methodName = methodName.toLowerCase(); + if (!this._methods[methodName]) { + this._methods[methodName] = []; + } + // Preventing adding the same handler multiple times. + if (this._methods[methodName].indexOf(newMethod) !== -1) { + return; + } + this._methods[methodName].push(newMethod); + } + off(methodName, method) { + if (!methodName) { + return; + } + methodName = methodName.toLowerCase(); + const handlers = this._methods[methodName]; + if (!handlers) { + return; + } + if (method) { + const removeIdx = handlers.indexOf(method); + if (removeIdx !== -1) { + handlers.splice(removeIdx, 1); + if (handlers.length === 0) { + delete this._methods[methodName]; + } + } + } + else { + delete this._methods[methodName]; + } + } + /** Registers a handler that will be invoked when the connection is closed. + * + * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any). + */ + onclose(callback) { + if (callback) { + this._closedCallbacks.push(callback); + } + } + /** Registers a handler that will be invoked when the connection starts reconnecting. + * + * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any). + */ + onreconnecting(callback) { + if (callback) { + this._reconnectingCallbacks.push(callback); + } + } + /** Registers a handler that will be invoked when the connection successfully reconnects. + * + * @param {Function} callback The handler that will be invoked when the connection successfully reconnects. + */ + onreconnected(callback) { + if (callback) { + this._reconnectedCallbacks.push(callback); + } + } + _processIncomingData(data) { + this._cleanupTimeout(); + if (!this._receivedHandshakeResponse) { + data = this._processHandshakeResponse(data); + this._receivedHandshakeResponse = true; + } + // Data may have all been read when processing handshake response + if (data) { + // Parse the messages + const messages = this._protocol.parseMessages(data, this._logger); + for (const message of messages) { + if (this._messageBuffer && !this._messageBuffer._shouldProcessMessage(message)) { + // Don't process the message, we are either waiting for a SequenceMessage or received a duplicate message + continue; + } + switch (message.type) { + case MessageType.Invocation: + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._invokeClientMethod(message); + break; + case MessageType.StreamItem: + case MessageType.Completion: { + const callback = this._callbacks[message.invocationId]; + if (callback) { + if (message.type === MessageType.Completion) { + delete this._callbacks[message.invocationId]; + } + try { + callback(message); + } + catch (e) { + this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`); + } + } + break; + } + case MessageType.Ping: + // Don't care about pings + break; + case MessageType.Close: { + this._logger.log(LogLevel.Information, "Close message received from server."); + const error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined; + if (message.allowReconnect === true) { + // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async, + // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions. + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.connection.stop(error); + } + else { + // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing. + this._stopPromise = this._stopInternal(error); + } + break; + } + case MessageType.Ack: + if (this._messageBuffer) { + this._messageBuffer._ack(message); + } + break; + case MessageType.Sequence: + if (this._messageBuffer) { + this._messageBuffer._resetSequence(message); + } + break; + default: + this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`); + break; + } + } + } + this._resetTimeoutPeriod(); + } + _processHandshakeResponse(data) { + let responseMessage; + let remainingData; + try { + [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data); + } + catch (e) { + const message = "Error parsing handshake response: " + e; + this._logger.log(LogLevel.Error, message); + const error = new Error(message); + this._handshakeRejecter(error); + throw error; + } + if (responseMessage.error) { + const message = "Server returned handshake error: " + responseMessage.error; + this._logger.log(LogLevel.Error, message); + const error = new Error(message); + this._handshakeRejecter(error); + throw error; + } + else { + this._logger.log(LogLevel.Debug, "Server handshake complete."); + } + this._handshakeResolver(); + return remainingData; + } + _resetKeepAliveInterval() { + if (this.connection.features.inherentKeepAlive) { + return; + } + // Set the time we want the next keep alive to be sent + // Timer will be setup on next message receive + this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds; + this._cleanupPingTimer(); + } + _resetTimeoutPeriod() { + if (!this.connection.features || !this.connection.features.inherentKeepAlive) { + // Set the timeout timer + this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds); + // Set keepAlive timer if there isn't one + if (this._pingServerHandle === undefined) { + let nextPing = this._nextKeepAlive - new Date().getTime(); + if (nextPing < 0) { + nextPing = 0; + } + // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute + this._pingServerHandle = setTimeout(async () => { + if (this._connectionState === HubConnectionState.Connected) { + try { + await this._sendMessage(this._cachedPingMessage); + } + catch { + // We don't care about the error. It should be seen elsewhere in the client. + // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering + this._cleanupPingTimer(); + } + } + }, nextPing); + } + } + } + // eslint-disable-next-line @typescript-eslint/naming-convention + serverTimeout() { + // The server hasn't talked to us in a while. It doesn't like us anymore ... :( + // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting. + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")); + } + async _invokeClientMethod(invocationMessage) { + const methodName = invocationMessage.target.toLowerCase(); + const methods = this._methods[methodName]; + if (!methods) { + this._logger.log(LogLevel.Warning, `No client method with the name '${methodName}' found.`); + // No handlers provided by client but the server is expecting a response still, so we send an error + if (invocationMessage.invocationId) { + this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`); + await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null)); + } + return; + } + // Avoid issues with handlers removing themselves thus modifying the list while iterating through it + const methodsCopy = methods.slice(); + // Server expects a response + const expectsResponse = invocationMessage.invocationId ? true : false; + // We preserve the last result or exception but still call all handlers + let res; + let exception; + let completionMessage; + for (const m of methodsCopy) { + try { + const prevRes = res; + res = await m.apply(this, invocationMessage.arguments); + if (expectsResponse && res && prevRes) { + this._logger.log(LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`); + completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `Client provided multiple results.`, null); + } + // Ignore exception if we got a result after, the exception will be logged + exception = undefined; } catch (e) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error, "HttpConnection.onclose(" + error + ") threw error '" + e + "'."); + exception = e; + this._logger.log(LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`); } } - }; - HttpConnection.prototype.resolveUrl = function (url) { - // startsWith is not supported in IE - if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) { - return url; + if (completionMessage) { + await this._sendWithProtocol(completionMessage); } - if (!_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isBrowser || !window.document) { - throw new Error("Cannot resolve '" + url + "'."); + else if (expectsResponse) { + // If there is an exception that means either no result was given or a handler after a result threw + if (exception) { + completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `${exception}`, null); + } + else if (res !== undefined) { + completionMessage = this._createCompletionMessage(invocationMessage.invocationId, null, res); + } + else { + this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`); + // Client didn't provide a result or throw from a handler, server expects a response so we send an error + completionMessage = this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null); + } + await this._sendWithProtocol(completionMessage); } - // Setting the url to the href propery of an anchor tag handles normalization - // for us. There are 3 main cases. - // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b" - // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b" - // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b" - var aTag = window.document.createElement("a"); - aTag.href = url; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information, "Normalizing '" + url + "' to '" + aTag.href + "'."); - return aTag.href; - }; - HttpConnection.prototype.resolveNegotiateUrl = function (url) { - var index = url.indexOf("?"); - var negotiateUrl = url.substring(0, index === -1 ? url.length : index); - if (negotiateUrl[negotiateUrl.length - 1] !== "/") { - negotiateUrl += "/"; + else { + if (res) { + this._logger.log(LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`); + } } - negotiateUrl += "negotiate"; - negotiateUrl += index === -1 ? "" : url.substring(index); - if (negotiateUrl.indexOf("negotiateVersion") === -1) { - negotiateUrl += index === -1 ? "?" : "&"; - negotiateUrl += "negotiateVersion=" + this.negotiateVersion; - } - return negotiateUrl; - }; - return HttpConnection; -}()); - -function transportMatches(requestedTransport, actualTransport) { - return !requestedTransport || ((actualTransport & requestedTransport) !== 0); -} -/** @private */ -var TransportSendQueue = /** @class */ (function () { - function TransportSendQueue(transport) { - this.transport = transport; - this.buffer = []; - this.executing = true; - this.sendBufferedData = new PromiseSource(); - this.transportResult = new PromiseSource(); - this.sendLoopPromise = this.sendLoop(); } - TransportSendQueue.prototype.send = function (data) { - this.bufferData(data); - if (!this.transportResult) { - this.transportResult = new PromiseSource(); + _connectionClosed(error) { + this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`); + // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet. + this._stopDuringStartError = this._stopDuringStartError || error || new AbortError("The underlying connection was closed before the hub handshake could complete."); + // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it. + // If it has already completed, this should just noop. + if (this._handshakeResolver) { + this._handshakeResolver(); } - return this.transportResult.promise; - }; - TransportSendQueue.prototype.stop = function () { - this.executing = false; - this.sendBufferedData.resolve(); - return this.sendLoopPromise; - }; - TransportSendQueue.prototype.bufferData = function (data) { - if (this.buffer.length && typeof (this.buffer[0]) !== typeof (data)) { - throw new Error("Expected data to be of type " + typeof (this.buffer) + " but was of type " + typeof (data)); + this._cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed.")); + this._cleanupTimeout(); + this._cleanupPingTimer(); + if (this._connectionState === HubConnectionState.Disconnecting) { + this._completeClose(error); } - this.buffer.push(data); - this.sendBufferedData.resolve(); - }; - TransportSendQueue.prototype.sendLoop = function () { - return __awaiter(this, void 0, void 0, function () { - var transportResult, data, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (false) {} - return [4 /*yield*/, this.sendBufferedData.promise]; - case 1: - _a.sent(); - if (!this.executing) { - if (this.transportResult) { - this.transportResult.reject("Connection stopped."); - } - return [3 /*break*/, 6]; - } - this.sendBufferedData = new PromiseSource(); - transportResult = this.transportResult; - this.transportResult = undefined; - data = typeof (this.buffer[0]) === "string" ? - this.buffer.join("") : - TransportSendQueue.concatBuffers(this.buffer); - this.buffer.length = 0; - _a.label = 2; - case 2: - _a.trys.push([2, 4, , 5]); - return [4 /*yield*/, this.transport.send(data)]; - case 3: - _a.sent(); - transportResult.resolve(); - return [3 /*break*/, 5]; - case 4: - error_1 = _a.sent(); - transportResult.reject(error_1); - return [3 /*break*/, 5]; - case 5: return [3 /*break*/, 0]; - case 6: return [2 /*return*/]; - } + else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._reconnect(error); + } + else if (this._connectionState === HubConnectionState.Connected) { + this._completeClose(error); + } + // If none of the above if conditions were true were called the HubConnection must be in either: + // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it. + // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt + // and potentially continue the reconnect() loop. + // 3. The Disconnected state in which case we're already done. + } + _completeClose(error) { + if (this._connectionStarted) { + this._connectionState = HubConnectionState.Disconnected; + this._connectionStarted = false; + if (this._messageBuffer) { + this._messageBuffer._dispose(error !== null && error !== void 0 ? error : new Error("Connection closed.")); + this._messageBuffer = undefined; + } + if (Platform.isBrowser) { + window.document.removeEventListener("freeze", this._freezeEventListener); + } + try { + this._closedCallbacks.forEach((c) => c.apply(this, [error])); + } + catch (e) { + this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`); + } + } + } + async _reconnect(error) { + const reconnectStartTime = Date.now(); + let previousReconnectAttempts = 0; + let retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error."); + let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError); + if (nextRetryDelay === null) { + this._logger.log(LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."); + this._completeClose(error); + return; + } + this._connectionState = HubConnectionState.Reconnecting; + if (error) { + this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`); + } + else { + this._logger.log(LogLevel.Information, "Connection reconnecting."); + } + if (this._reconnectingCallbacks.length !== 0) { + try { + this._reconnectingCallbacks.forEach((c) => c.apply(this, [error])); + } + catch (e) { + this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`); + } + // Exit early if an onreconnecting callback called connection.stop(). + if (this._connectionState !== HubConnectionState.Reconnecting) { + this._logger.log(LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting."); + return; + } + } + while (nextRetryDelay !== null) { + this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`); + await new Promise((resolve) => { + this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay); }); - }); - }; - TransportSendQueue.concatBuffers = function (arrayBuffers) { - var totalLength = arrayBuffers.map(function (b) { return b.byteLength; }).reduce(function (a, b) { return a + b; }); - var result = new Uint8Array(totalLength); - var offset = 0; - for (var _i = 0, arrayBuffers_1 = arrayBuffers; _i < arrayBuffers_1.length; _i++) { - var item = arrayBuffers_1[_i]; - result.set(new Uint8Array(item), offset); - offset += item.byteLength; + this._reconnectDelayHandle = undefined; + if (this._connectionState !== HubConnectionState.Reconnecting) { + this._logger.log(LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting."); + return; + } + try { + await this._startInternal(); + this._connectionState = HubConnectionState.Connected; + this._logger.log(LogLevel.Information, "HubConnection reconnected successfully."); + if (this._reconnectedCallbacks.length !== 0) { + try { + this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId])); + } + catch (e) { + this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`); + } + } + return; + } + catch (e) { + this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`); + if (this._connectionState !== HubConnectionState.Reconnecting) { + this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`); + // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong. + if (this._connectionState === HubConnectionState.Disconnecting) { + this._completeClose(); + } + return; + } + retryError = e instanceof Error ? e : new Error(e.toString()); + nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError); + } } - return result.buffer; - }; - return TransportSendQueue; -}()); - -var PromiseSource = /** @class */ (function () { - function PromiseSource() { - var _this = this; - this.promise = new Promise(function (resolve, reject) { - var _a; - return _a = [resolve, reject], _this.resolver = _a[0], _this.rejecter = _a[1], _a; + this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`); + this._completeClose(); + } + _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) { + try { + return this._reconnectPolicy.nextRetryDelayInMilliseconds({ + elapsedMilliseconds, + previousRetryCount, + retryReason, + }); + } + catch (e) { + this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`); + return null; + } + } + _cancelCallbacksWithError(error) { + const callbacks = this._callbacks; + this._callbacks = {}; + Object.keys(callbacks) + .forEach((key) => { + const callback = callbacks[key]; + try { + callback(null, error); + } + catch (e) { + this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`); + } }); } - PromiseSource.prototype.resolve = function () { - this.resolver(); - }; - PromiseSource.prototype.reject = function (reason) { - this.rejecter(reason); - }; - return PromiseSource; -}()); + _cleanupPingTimer() { + if (this._pingServerHandle) { + clearTimeout(this._pingServerHandle); + this._pingServerHandle = undefined; + } + } + _cleanupTimeout() { + if (this._timeoutHandle) { + clearTimeout(this._timeoutHandle); + } + } + _createInvocation(methodName, args, nonblocking, streamIds) { + if (nonblocking) { + if (streamIds.length !== 0) { + return { + arguments: args, + streamIds, + target: methodName, + type: MessageType.Invocation, + }; + } + else { + return { + arguments: args, + target: methodName, + type: MessageType.Invocation, + }; + } + } + else { + const invocationId = this._invocationId; + this._invocationId++; + if (streamIds.length !== 0) { + return { + arguments: args, + invocationId: invocationId.toString(), + streamIds, + target: methodName, + type: MessageType.Invocation, + }; + } + else { + return { + arguments: args, + invocationId: invocationId.toString(), + target: methodName, + type: MessageType.Invocation, + }; + } + } + } + _launchStreams(streams, promiseQueue) { + if (streams.length === 0) { + return; + } + // Synchronize stream data so they arrive in-order on the server + if (!promiseQueue) { + promiseQueue = Promise.resolve(); + } + // We want to iterate over the keys, since the keys are the stream ids + // eslint-disable-next-line guard-for-in + for (const streamId in streams) { + streams[streamId].subscribe({ + complete: () => { + promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId))); + }, + error: (err) => { + let message; + if (err instanceof Error) { + message = err.message; + } + else if (err && err.toString) { + message = err.toString(); + } + else { + message = "Unknown error"; + } + promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message))); + }, + next: (item) => { + promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item))); + }, + }); + } + } + _replaceStreamingParams(args) { + const streams = []; + const streamIds = []; + for (let i = 0; i < args.length; i++) { + const argument = args[i]; + if (this._isObservable(argument)) { + const streamId = this._invocationId; + this._invocationId++; + // Store the stream for later use + streams[streamId] = argument; + streamIds.push(streamId.toString()); + // remove stream from args + args.splice(i, 1); + } + } + return [streams, streamIds]; + } + _isObservable(arg) { + // This allows other stream implementations to just work (like rxjs) + return arg && arg.subscribe && typeof arg.subscribe === "function"; + } + _createStreamInvocation(methodName, args, streamIds) { + const invocationId = this._invocationId; + this._invocationId++; + if (streamIds.length !== 0) { + return { + arguments: args, + invocationId: invocationId.toString(), + streamIds, + target: methodName, + type: MessageType.StreamInvocation, + }; + } + else { + return { + arguments: args, + invocationId: invocationId.toString(), + target: methodName, + type: MessageType.StreamInvocation, + }; + } + } + _createCancelInvocation(id) { + return { + invocationId: id, + type: MessageType.CancelInvocation, + }; + } + _createStreamItemMessage(id, item) { + return { + invocationId: id, + item, + type: MessageType.StreamItem, + }; + } + _createCompletionMessage(id, error, result) { + if (error) { + return { + error, + invocationId: id, + type: MessageType.Completion, + }; + } + return { + invocationId: id, + result, + type: MessageType.Completion, + }; + } + _createCloseMessage() { + return { type: MessageType.Close }; + } +} + +;// CONCATENATED MODULE: ./src/DefaultReconnectPolicy.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// 0, 2, 10, 30 second delays before reconnect attempts. +const DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null]; +/** @private */ +class DefaultReconnectPolicy { + constructor(retryDelays) { + this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS; + } + nextRetryDelayInMilliseconds(retryContext) { + return this._retryDelays[retryContext.previousRetryCount]; + } +} + +;// CONCATENATED MODULE: ./src/HeaderNames.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +class HeaderNames { +} +HeaderNames.Authorization = "Authorization"; +HeaderNames.Cookie = "Cookie"; + +;// CONCATENATED MODULE: ./src/AccessTokenHttpClient.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. -/***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/** @private */ +class AccessTokenHttpClient extends HttpClient { + constructor(innerClient, accessTokenFactory) { + super(); + this._innerClient = innerClient; + this._accessTokenFactory = accessTokenFactory; + } + async send(request) { + let allowRetry = true; + if (this._accessTokenFactory && (!this._accessToken || (request.url && request.url.indexOf("/negotiate?") > 0))) { + // don't retry if the request is a negotiate or if we just got a potentially new token from the access token factory + allowRetry = false; + this._accessToken = await this._accessTokenFactory(); + } + this._setAuthorizationHeader(request); + const response = await this._innerClient.send(request); + if (allowRetry && response.statusCode === 401 && this._accessTokenFactory) { + this._accessToken = await this._accessTokenFactory(); + this._setAuthorizationHeader(request); + return await this._innerClient.send(request); + } + return response; + } + _setAuthorizationHeader(request) { + if (!request.headers) { + request.headers = {}; + } + if (this._accessToken) { + request.headers[HeaderNames.Authorization] = `Bearer ${this._accessToken}`; + } + // don't remove the header if there isn't an access token factory, the user manually added the header in this case + else if (this._accessTokenFactory) { + if (request.headers[HeaderNames.Authorization]) { + delete request.headers[HeaderNames.Authorization]; + } + } + } + getCookieString(url) { + return this._innerClient.getCookieString(url); + } +} -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HttpTransportType", function() { return HttpTransportType; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransferFormat", function() { return TransferFormat; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +;// CONCATENATED MODULE: ./src/ITransport.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // This will be treated as a bit flag in the future, so we keep it using power-of-two values. /** Specifies a specific HTTP transport type. */ var HttpTransportType; @@ -4423,64 +2197,38 @@ var TransferFormat; TransferFormat[TransferFormat["Binary"] = 2] = "Binary"; })(TransferFormat || (TransferFormat = {})); - -/***/ }), -/* 21 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LongPollingTransport", function() { return LongPollingTransport; }); -/* harmony import */ var _AbortController__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22); -/* harmony import */ var _Errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8); -/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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]; +;// CONCATENATED MODULE: ./src/AbortController.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController +// We don't actually ever use the API being polyfilled, we always use the polyfill because +// it's a very new API right now. +// Not exported from index. +/** @private */ +class AbortController_AbortController { + constructor() { + this._isAborted = false; + this.onabort = null; } - return t; -}; -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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; + abort() { + if (!this._isAborted) { + this._isAborted = true; + if (this.onabort) { + this.onabort(); } - 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 }; + } } -}; + get signal() { + return this; + } + get aborted() { + return this._isAborted; + } +} + +;// CONCATENATED MODULE: ./src/LongPollingTransport.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. @@ -4488,674 +2236,426 @@ var __generator = (undefined && undefined.__generator) || function (thisArg, bod // Not exported from 'index', this type is internal. /** @private */ -var LongPollingTransport = /** @class */ (function () { - function LongPollingTransport(httpClient, accessTokenFactory, logger, logMessageContent, withCredentials, headers) { - this.httpClient = httpClient; - this.accessTokenFactory = accessTokenFactory; - this.logger = logger; - this.pollAbort = new _AbortController__WEBPACK_IMPORTED_MODULE_0__["AbortController"](); - this.logMessageContent = logMessageContent; - this.withCredentials = withCredentials; - this.headers = headers; - this.running = false; +class LongPollingTransport { + // This is an internal type, not exported from 'index' so this is really just internal. + get pollAborted() { + return this._pollAbort.aborted; + } + constructor(httpClient, logger, options) { + this._httpClient = httpClient; + this._logger = logger; + this._pollAbort = new AbortController_AbortController(); + this._options = options; + this._running = false; this.onreceive = null; this.onclose = null; } - Object.defineProperty(LongPollingTransport.prototype, "pollAborted", { - // This is an internal type, not exported from 'index' so this is really just internal. - get: function () { - return this.pollAbort.aborted; - }, - enumerable: true, - configurable: true - }); - LongPollingTransport.prototype.connect = function (url, transferFormat) { - return __awaiter(this, void 0, void 0, function () { - var _a, _b, name, value, headers, pollOptions, token, pollUrl, response; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(url, "url"); - _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isRequired(transferFormat, "transferFormat"); - _Utils__WEBPACK_IMPORTED_MODULE_4__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_3__["TransferFormat"], "transferFormat"); - this.url = url; - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Connecting."); - // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property) - if (transferFormat === _ITransport__WEBPACK_IMPORTED_MODULE_3__["TransferFormat"].Binary && - (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) { - throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); - } - _b = Object(_Utils__WEBPACK_IMPORTED_MODULE_4__["getUserAgentHeader"])(), name = _b[0], value = _b[1]; - headers = __assign((_a = {}, _a[name] = value, _a), this.headers); - pollOptions = { - abortSignal: this.pollAbort.signal, - headers: headers, - timeout: 100000, - withCredentials: this.withCredentials, - }; - if (transferFormat === _ITransport__WEBPACK_IMPORTED_MODULE_3__["TransferFormat"].Binary) { - pollOptions.responseType = "arraybuffer"; - } - return [4 /*yield*/, this.getAccessToken()]; - case 1: - token = _c.sent(); - this.updateHeaderToken(pollOptions, token); - pollUrl = url + "&_=" + Date.now(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) polling: " + pollUrl + "."); - return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)]; - case 2: - response = _c.sent(); - if (response.statusCode !== 200) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + "."); - // Mark running as false so that the poll immediately ends and runs the close logic - this.closeError = new _Errors__WEBPACK_IMPORTED_MODULE_1__["HttpError"](response.statusText || "", response.statusCode); - this.running = false; + async connect(url, transferFormat) { + Arg.isRequired(url, "url"); + Arg.isRequired(transferFormat, "transferFormat"); + Arg.isIn(transferFormat, TransferFormat, "transferFormat"); + this._url = url; + this._logger.log(LogLevel.Trace, "(LongPolling transport) Connecting."); + // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property) + if (transferFormat === TransferFormat.Binary && + (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) { + throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); + } + const [name, value] = getUserAgentHeader(); + const headers = { [name]: value, ...this._options.headers }; + const pollOptions = { + abortSignal: this._pollAbort.signal, + headers, + timeout: 100000, + withCredentials: this._options.withCredentials, + }; + if (transferFormat === TransferFormat.Binary) { + pollOptions.responseType = "arraybuffer"; + } + // Make initial long polling request + // Server uses first long polling request to finish initializing connection and it returns without data + const pollUrl = `${url}&_=${Date.now()}`; + this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`); + const response = await this._httpClient.get(pollUrl, pollOptions); + if (response.statusCode !== 200) { + this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`); + // Mark running as false so that the poll immediately ends and runs the close logic + this._closeError = new HttpError(response.statusText || "", response.statusCode); + this._running = false; + } + else { + this._running = true; + } + this._receiving = this._poll(this._url, pollOptions); + } + async _poll(url, pollOptions) { + try { + while (this._running) { + try { + const pollUrl = `${url}&_=${Date.now()}`; + this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`); + const response = await this._httpClient.get(pollUrl, pollOptions); + if (response.statusCode === 204) { + this._logger.log(LogLevel.Information, "(LongPolling transport) Poll terminated by server."); + this._running = false; + } + else if (response.statusCode !== 200) { + this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`); + // Unexpected status code + this._closeError = new HttpError(response.statusText || "", response.statusCode); + this._running = false; + } + else { + // Process the response + if (response.content) { + this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`); + if (this.onreceive) { + this.onreceive(response.content); + } } else { - this.running = true; + // This is another way timeout manifest. + this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing."); } - this.receiving = this.poll(this.url, pollOptions); - return [2 /*return*/]; + } } - }); - }); - }; - LongPollingTransport.prototype.getAccessToken = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.accessTokenFactory) return [3 /*break*/, 2]; - return [4 /*yield*/, this.accessTokenFactory()]; - case 1: return [2 /*return*/, _a.sent()]; - case 2: return [2 /*return*/, null]; - } - }); - }); - }; - LongPollingTransport.prototype.updateHeaderToken = function (request, token) { - if (!request.headers) { - request.headers = {}; - } - if (token) { - // tslint:disable-next-line:no-string-literal - request.headers["Authorization"] = "Bearer " + token; - return; - } - // tslint:disable-next-line:no-string-literal - if (request.headers["Authorization"]) { - // tslint:disable-next-line:no-string-literal - delete request.headers["Authorization"]; - } - }; - LongPollingTransport.prototype.poll = function (url, pollOptions) { - return __awaiter(this, void 0, void 0, function () { - var token, pollUrl, response, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, , 8, 9]); - _a.label = 1; - case 1: - if (!this.running) return [3 /*break*/, 7]; - return [4 /*yield*/, this.getAccessToken()]; - case 2: - token = _a.sent(); - this.updateHeaderToken(pollOptions, token); - _a.label = 3; - case 3: - _a.trys.push([3, 5, , 6]); - pollUrl = url + "&_=" + Date.now(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) polling: " + pollUrl + "."); - return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)]; - case 4: - response = _a.sent(); - if (response.statusCode === 204) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Information, "(LongPolling transport) Poll terminated by server."); - this.running = false; - } - else if (response.statusCode !== 200) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + "."); - // Unexpected status code - this.closeError = new _Errors__WEBPACK_IMPORTED_MODULE_1__["HttpError"](response.statusText || "", response.statusCode); - this.running = false; + catch (e) { + if (!this._running) { + // Log but disregard errors that occur after stopping + this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`); + } + else { + if (e instanceof TimeoutError) { + // Ignore timeouts and reissue the poll. + this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing."); } else { - // Process the response - if (response.content) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) data received. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_4__["getDataDetail"])(response.content, this.logMessageContent) + "."); - if (this.onreceive) { - this.onreceive(response.content); - } - } - else { - // This is another way timeout manifest. - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Poll timed out, reissuing."); - } + // Close the connection with the error as the result. + this._closeError = e; + this._running = false; } - return [3 /*break*/, 6]; - case 5: - e_1 = _a.sent(); - if (!this.running) { - // Log but disregard errors that occur after stopping - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Poll errored after shutdown: " + e_1.message); - } - else { - if (e_1 instanceof _Errors__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]) { - // Ignore timeouts and reissue the poll. - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Poll timed out, reissuing."); - } - else { - // Close the connection with the error as the result. - this.closeError = e_1; - this.running = false; - } - } - return [3 /*break*/, 6]; - case 6: return [3 /*break*/, 1]; - case 7: return [3 /*break*/, 9]; - case 8: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Polling complete."); - // We will reach here with pollAborted==false when the server returned a response causing the transport to stop. - // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent. - if (!this.pollAborted) { - this.raiseOnClose(); - } - return [7 /*endfinally*/]; - case 9: return [2 /*return*/]; + } } - }); - }); - }; - LongPollingTransport.prototype.send = function (data) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (!this.running) { - return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))]; + } + } + finally { + this._logger.log(LogLevel.Trace, "(LongPolling transport) Polling complete."); + // We will reach here with pollAborted==false when the server returned a response causing the transport to stop. + // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent. + if (!this.pollAborted) { + this._raiseOnClose(); + } + } + } + async send(data) { + if (!this._running) { + return Promise.reject(new Error("Cannot send until the transport is connected")); + } + return sendMessage(this._logger, "LongPolling", this._httpClient, this._url, data, this._options); + } + async stop() { + this._logger.log(LogLevel.Trace, "(LongPolling transport) Stopping polling."); + // Tell receiving loop to stop, abort any current request, and then wait for it to finish + this._running = false; + this._pollAbort.abort(); + try { + await this._receiving; + // Send DELETE to clean up long polling on the server + this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`); + const headers = {}; + const [name, value] = getUserAgentHeader(); + headers[name] = value; + const deleteOptions = { + headers: { ...headers, ...this._options.headers }, + timeout: this._options.timeout, + withCredentials: this._options.withCredentials, + }; + let error; + try { + await this._httpClient.delete(this._url, deleteOptions); + } + catch (err) { + error = err; + } + if (error) { + if (error instanceof HttpError) { + if (error.statusCode === 404) { + this._logger.log(LogLevel.Trace, "(LongPolling transport) A 404 response was returned from sending a DELETE request."); + } + else { + this._logger.log(LogLevel.Trace, `(LongPolling transport) Error sending a DELETE request: ${error}`); + } } - return [2 /*return*/, Object(_Utils__WEBPACK_IMPORTED_MODULE_4__["sendMessage"])(this.logger, "LongPolling", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent, this.withCredentials, this.headers)]; - }); - }); - }; - LongPollingTransport.prototype.stop = function () { - return __awaiter(this, void 0, void 0, function () { - var headers, _a, name_1, value, deleteOptions, token; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Stopping polling."); - // Tell receiving loop to stop, abort any current request, and then wait for it to finish - this.running = false; - this.pollAbort.abort(); - _b.label = 1; - case 1: - _b.trys.push([1, , 5, 6]); - return [4 /*yield*/, this.receiving]; - case 2: - _b.sent(); - // Send DELETE to clean up long polling on the server - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) sending DELETE request to " + this.url + "."); - headers = {}; - _a = Object(_Utils__WEBPACK_IMPORTED_MODULE_4__["getUserAgentHeader"])(), name_1 = _a[0], value = _a[1]; - headers[name_1] = value; - deleteOptions = { - headers: __assign({}, headers, this.headers), - withCredentials: this.withCredentials, - }; - return [4 /*yield*/, this.getAccessToken()]; - case 3: - token = _b.sent(); - this.updateHeaderToken(deleteOptions, token); - return [4 /*yield*/, this.httpClient.delete(this.url, deleteOptions)]; - case 4: - _b.sent(); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) DELETE request sent."); - return [3 /*break*/, 6]; - case 5: - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, "(LongPolling transport) Stop finished."); - // Raise close event here instead of in polling - // It needs to happen after the DELETE request is sent - this.raiseOnClose(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - LongPollingTransport.prototype.raiseOnClose = function () { + } + else { + this._logger.log(LogLevel.Trace, "(LongPolling transport) DELETE request accepted."); + } + } + finally { + this._logger.log(LogLevel.Trace, "(LongPolling transport) Stop finished."); + // Raise close event here instead of in polling + // It needs to happen after the DELETE request is sent + this._raiseOnClose(); + } + } + _raiseOnClose() { if (this.onclose) { - var logMessage = "(LongPolling transport) Firing onclose event."; - if (this.closeError) { - logMessage += " Error: " + this.closeError; + let logMessage = "(LongPolling transport) Firing onclose event."; + if (this._closeError) { + logMessage += " Error: " + this._closeError; } - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Trace, logMessage); - this.onclose(this.closeError); + this._logger.log(LogLevel.Trace, logMessage); + this.onclose(this._closeError); } - }; - return LongPollingTransport; -}()); - - - -/***/ }), -/* 22 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbortController", function() { return AbortController; }); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController -// We don't actually ever use the API being polyfilled, we always use the polyfill because -// it's a very new API right now. -// Not exported from index. -/** @private */ -var AbortController = /** @class */ (function () { - function AbortController() { - this.isAborted = false; - this.onabort = null; } - AbortController.prototype.abort = function () { - if (!this.isAborted) { - this.isAborted = true; - if (this.onabort) { - this.onabort(); - } - } - }; - Object.defineProperty(AbortController.prototype, "signal", { - get: function () { - return this; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AbortController.prototype, "aborted", { - get: function () { - return this.isAborted; - }, - enumerable: true, - configurable: true - }); - return AbortController; -}()); +} - - -/***/ }), -/* 23 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerSentEventsTransport", function() { return ServerSentEventsTransport; }); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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; -}; -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; - } -}; +;// CONCATENATED MODULE: ./src/ServerSentEventsTransport.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /** @private */ -var ServerSentEventsTransport = /** @class */ (function () { - function ServerSentEventsTransport(httpClient, accessTokenFactory, logger, logMessageContent, eventSourceConstructor, withCredentials, headers) { - this.httpClient = httpClient; - this.accessTokenFactory = accessTokenFactory; - this.logger = logger; - this.logMessageContent = logMessageContent; - this.withCredentials = withCredentials; - this.eventSourceConstructor = eventSourceConstructor; - this.headers = headers; +class ServerSentEventsTransport { + constructor(httpClient, accessToken, logger, options) { + this._httpClient = httpClient; + this._accessToken = accessToken; + this._logger = logger; + this._options = options; this.onreceive = null; this.onclose = null; } - ServerSentEventsTransport.prototype.connect = function (url, transferFormat) { - return __awaiter(this, void 0, void 0, function () { - var token; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(url, "url"); - _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(transferFormat, "transferFormat"); - _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"], "transferFormat"); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(SSE transport) Connecting."); - // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send - this.url = url; - if (!this.accessTokenFactory) return [3 /*break*/, 2]; - return [4 /*yield*/, this.accessTokenFactory()]; - case 1: - token = _a.sent(); - if (token) { - url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); + async connect(url, transferFormat) { + Arg.isRequired(url, "url"); + Arg.isRequired(transferFormat, "transferFormat"); + Arg.isIn(transferFormat, TransferFormat, "transferFormat"); + this._logger.log(LogLevel.Trace, "(SSE transport) Connecting."); + // set url before accessTokenFactory because this._url is only for send and we set the auth header instead of the query string for send + this._url = url; + if (this._accessToken) { + url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(this._accessToken)}`; + } + return new Promise((resolve, reject) => { + let opened = false; + if (transferFormat !== TransferFormat.Text) { + reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format")); + return; + } + let eventSource; + if (Platform.isBrowser || Platform.isWebWorker) { + eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials }); + } + else { + // Non-browser passes cookies via the dictionary + const cookies = this._httpClient.getCookieString(url); + const headers = {}; + headers.Cookie = cookies; + const [name, value] = getUserAgentHeader(); + headers[name] = value; + eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers } }); + } + try { + eventSource.onmessage = (e) => { + if (this.onreceive) { + try { + this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`); + this.onreceive(e.data); } - _a.label = 2; - case 2: return [2 /*return*/, new Promise(function (resolve, reject) { - var opened = false; - if (transferFormat !== _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"].Text) { - reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format")); - return; - } - var eventSource; - if (_Utils__WEBPACK_IMPORTED_MODULE_2__["Platform"].isBrowser || _Utils__WEBPACK_IMPORTED_MODULE_2__["Platform"].isWebWorker) { - eventSource = new _this.eventSourceConstructor(url, { withCredentials: _this.withCredentials }); - } - else { - // Non-browser passes cookies via the dictionary - var cookies = _this.httpClient.getCookieString(url); - var headers = {}; - headers.Cookie = cookies; - var _a = Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getUserAgentHeader"])(), name_1 = _a[0], value = _a[1]; - headers[name_1] = value; - eventSource = new _this.eventSourceConstructor(url, { withCredentials: _this.withCredentials, headers: __assign({}, headers, _this.headers) }); - } - try { - eventSource.onmessage = function (e) { - if (_this.onreceive) { - try { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(SSE transport) data received. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getDataDetail"])(e.data, _this.logMessageContent) + "."); - _this.onreceive(e.data); - } - catch (error) { - _this.close(error); - return; - } - } - }; - eventSource.onerror = function (e) { - var error = new Error(e.data || "Error occurred"); - if (opened) { - _this.close(error); - } - else { - reject(error); - } - }; - eventSource.onopen = function () { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information, "SSE connected to " + _this.url); - _this.eventSource = eventSource; - opened = true; - resolve(); - }; - } - catch (e) { - reject(e); - return; - } - })]; - } - }); + catch (error) { + this._close(error); + return; + } + } + }; + // @ts-ignore: not using event on purpose + eventSource.onerror = (e) => { + // EventSource doesn't give any useful information about server side closes. + if (opened) { + this._close(); + } + else { + reject(new Error("EventSource failed to connect. The connection could not be found on the server," + + " either the connection ID is not present on the server, or a proxy is refusing/buffering the connection." + + " If you have multiple servers check that sticky sessions are enabled.")); + } + }; + eventSource.onopen = () => { + this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`); + this._eventSource = eventSource; + opened = true; + resolve(); + }; + } + catch (e) { + reject(e); + return; + } }); - }; - ServerSentEventsTransport.prototype.send = function (data) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (!this.eventSource) { - return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))]; - } - return [2 /*return*/, Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["sendMessage"])(this.logger, "SSE", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent, this.withCredentials, this.headers)]; - }); - }); - }; - ServerSentEventsTransport.prototype.stop = function () { - this.close(); + } + async send(data) { + if (!this._eventSource) { + return Promise.reject(new Error("Cannot send until the transport is connected")); + } + return sendMessage(this._logger, "SSE", this._httpClient, this._url, data, this._options); + } + stop() { + this._close(); return Promise.resolve(); - }; - ServerSentEventsTransport.prototype.close = function (e) { - if (this.eventSource) { - this.eventSource.close(); - this.eventSource = undefined; + } + _close(e) { + if (this._eventSource) { + this._eventSource.close(); + this._eventSource = undefined; if (this.onclose) { this.onclose(e); } } - }; - return ServerSentEventsTransport; -}()); - - - -/***/ }), -/* 24 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebSocketTransport", function() { return WebSocketTransport; }); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8); -/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20); -/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -var __assign = (undefined && undefined.__assign) || Object.assign || function(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; -}; -var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; - } -}; +} + +;// CONCATENATED MODULE: ./src/WebSocketTransport.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + /** @private */ -var WebSocketTransport = /** @class */ (function () { - function WebSocketTransport(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) { - this.logger = logger; - this.accessTokenFactory = accessTokenFactory; - this.logMessageContent = logMessageContent; - this.webSocketConstructor = webSocketConstructor; - this.httpClient = httpClient; +class WebSocketTransport { + constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) { + this._logger = logger; + this._accessTokenFactory = accessTokenFactory; + this._logMessageContent = logMessageContent; + this._webSocketConstructor = webSocketConstructor; + this._httpClient = httpClient; this.onreceive = null; this.onclose = null; - this.headers = headers; + this._headers = headers; } - WebSocketTransport.prototype.connect = function (url, transferFormat) { - return __awaiter(this, void 0, void 0, function () { - var token; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(url, "url"); - _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isRequired(transferFormat, "transferFormat"); - _Utils__WEBPACK_IMPORTED_MODULE_2__["Arg"].isIn(transferFormat, _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"], "transferFormat"); - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) Connecting."); - if (!this.accessTokenFactory) return [3 /*break*/, 2]; - return [4 /*yield*/, this.accessTokenFactory()]; - case 1: - token = _a.sent(); - if (token) { - url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); - } - _a.label = 2; - case 2: return [2 /*return*/, new Promise(function (resolve, reject) { - url = url.replace(/^http/, "ws"); - var webSocket; - var cookies = _this.httpClient.getCookieString(url); - var opened = false; - if (_Utils__WEBPACK_IMPORTED_MODULE_2__["Platform"].isNode) { - var headers = {}; - var _a = Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getUserAgentHeader"])(), name_1 = _a[0], value = _a[1]; - headers[name_1] = value; - if (cookies) { - headers["Cookie"] = "" + cookies; - } - // Only pass headers when in non-browser environments - webSocket = new _this.webSocketConstructor(url, undefined, { - headers: __assign({}, headers, _this.headers), - }); - } - if (!webSocket) { - // Chrome is not happy with passing 'undefined' as protocol - webSocket = new _this.webSocketConstructor(url); - } - if (transferFormat === _ITransport__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"].Binary) { - webSocket.binaryType = "arraybuffer"; - } - // tslint:disable-next-line:variable-name - webSocket.onopen = function (_event) { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information, "WebSocket connected to " + url + "."); - _this.webSocket = webSocket; - opened = true; - resolve(); - }; - webSocket.onerror = function (event) { - var error = null; - // ErrorEvent is a browser only type we need to check if the type exists before using it - if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) { - error = event.error; - } - else { - error = new Error("There was an error with the transport."); - } - reject(error); - }; - webSocket.onmessage = function (message) { - _this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) data received. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getDataDetail"])(message.data, _this.logMessageContent) + "."); - if (_this.onreceive) { - try { - _this.onreceive(message.data); - } - catch (error) { - _this.close(error); - return; - } - } - }; - webSocket.onclose = function (event) { - // Don't call close handler if connection was never established - // We'll reject the connect call instead - if (opened) { - _this.close(event); - } - else { - var error = null; - // ErrorEvent is a browser only type we need to check if the type exists before using it - if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) { - error = event.error; - } - else { - error = new Error("There was an error with the transport."); - } - reject(error); - } - }; - })]; + async connect(url, transferFormat) { + Arg.isRequired(url, "url"); + Arg.isRequired(transferFormat, "transferFormat"); + Arg.isIn(transferFormat, TransferFormat, "transferFormat"); + this._logger.log(LogLevel.Trace, "(WebSockets transport) Connecting."); + let token; + if (this._accessTokenFactory) { + token = await this._accessTokenFactory(); + } + return new Promise((resolve, reject) => { + url = url.replace(/^http/, "ws"); + let webSocket; + const cookies = this._httpClient.getCookieString(url); + let opened = false; + if (Platform.isNode || Platform.isReactNative) { + const headers = {}; + const [name, value] = getUserAgentHeader(); + headers[name] = value; + if (token) { + headers[HeaderNames.Authorization] = `Bearer ${token}`; } - }); + if (cookies) { + headers[HeaderNames.Cookie] = cookies; + } + // Only pass headers when in non-browser environments + webSocket = new this._webSocketConstructor(url, undefined, { + headers: { ...headers, ...this._headers }, + }); + } + else { + if (token) { + url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(token)}`; + } + } + if (!webSocket) { + // Chrome is not happy with passing 'undefined' as protocol + webSocket = new this._webSocketConstructor(url); + } + if (transferFormat === TransferFormat.Binary) { + webSocket.binaryType = "arraybuffer"; + } + webSocket.onopen = (_event) => { + this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`); + this._webSocket = webSocket; + opened = true; + resolve(); + }; + webSocket.onerror = (event) => { + let error = null; + // ErrorEvent is a browser only type we need to check if the type exists before using it + if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) { + error = event.error; + } + else { + error = "There was an error with the transport"; + } + this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`); + }; + webSocket.onmessage = (message) => { + this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`); + if (this.onreceive) { + try { + this.onreceive(message.data); + } + catch (error) { + this._close(error); + return; + } + } + }; + webSocket.onclose = (event) => { + // Don't call close handler if connection was never established + // We'll reject the connect call instead + if (opened) { + this._close(event); + } + else { + let error = null; + // ErrorEvent is a browser only type we need to check if the type exists before using it + if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) { + error = event.error; + } + else { + error = "WebSocket failed to connect. The connection could not be found on the server," + + " either the endpoint may not be a SignalR endpoint," + + " the connection ID is not present on the server, or there is a proxy blocking WebSockets." + + " If you have multiple servers check that sticky sessions are enabled."; + } + reject(new Error(error)); + } + }; }); - }; - WebSocketTransport.prototype.send = function (data) { - if (this.webSocket && this.webSocket.readyState === this.webSocketConstructor.OPEN) { - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) sending data. " + Object(_Utils__WEBPACK_IMPORTED_MODULE_2__["getDataDetail"])(data, this.logMessageContent) + "."); - this.webSocket.send(data); + } + send(data) { + if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) { + this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`); + this._webSocket.send(data); return Promise.resolve(); } return Promise.reject("WebSocket is not in the OPEN state"); - }; - WebSocketTransport.prototype.stop = function () { - if (this.webSocket) { + } + stop() { + if (this._webSocket) { // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects - this.close(undefined); + this._close(undefined); } return Promise.resolve(); - }; - WebSocketTransport.prototype.close = function (event) { + } + _close(event) { // webSocket will be null if the transport did not start successfully - if (this.webSocket) { + if (this._webSocket) { // Clear websocket handlers because we are considering the socket closed now - this.webSocket.onclose = function () { }; - this.webSocket.onmessage = function () { }; - this.webSocket.onerror = function () { }; - this.webSocket.close(); - this.webSocket = undefined; + this._webSocket.onclose = () => { }; + this._webSocket.onmessage = () => { }; + this._webSocket.onerror = () => { }; + this._webSocket.close(); + this._webSocket = undefined; } - this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Trace, "(WebSockets transport) socket closed."); + this._logger.log(LogLevel.Trace, "(WebSockets transport) socket closed."); if (this.onclose) { - if (this.isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) { - this.onclose(new Error("WebSocket closed with status code: " + event.code + " (" + event.reason + ").")); + if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) { + this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || "no reason given"}).`)); } else if (event instanceof Error) { this.onclose(event); @@ -5164,51 +2664,606 @@ var WebSocketTransport = /** @class */ (function () { this.onclose(); } } - }; - WebSocketTransport.prototype.isCloseEvent = function (event) { + } + _isCloseEvent(event) { return event && typeof event.wasClean === "boolean" && typeof event.code === "number"; - }; - return WebSocketTransport; -}()); + } +} - - -/***/ }), -/* 25 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JsonHubProtocol", function() { return JsonHubProtocol; }); -/* harmony import */ var _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); -/* harmony import */ var _ILogger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _ITransport__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20); -/* harmony import */ var _Loggers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(10); -/* harmony import */ var _TextMessageFormat__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(14); -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +;// CONCATENATED MODULE: ./src/HttpConnection.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. -var JSON_HUB_PROTOCOL_NAME = "json"; + + + + + +const MAX_REDIRECTS = 100; +/** @private */ +class HttpConnection { + constructor(url, options = {}) { + this._stopPromiseResolver = () => { }; + this.features = {}; + this._negotiateVersion = 1; + Arg.isRequired(url, "url"); + this._logger = createLogger(options.logger); + this.baseUrl = this._resolveUrl(url); + options = options || {}; + options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent; + if (typeof options.withCredentials === "boolean" || options.withCredentials === undefined) { + options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials; + } + else { + throw new Error("withCredentials option was not a 'boolean' or 'undefined' value"); + } + options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout; + let webSocketModule = null; + let eventSourceModule = null; + if (Platform.isNode && "function" !== "undefined") { + webSocketModule = getWS(); + eventSourceModule = getEventSource(); + } + if (!Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) { + options.WebSocket = WebSocket; + } + else if (Platform.isNode && !options.WebSocket) { + if (webSocketModule) { + options.WebSocket = webSocketModule; + } + } + if (!Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) { + options.EventSource = EventSource; + } + else if (Platform.isNode && !options.EventSource) { + if (typeof eventSourceModule !== "undefined") { + options.EventSource = eventSourceModule; + } + } + this._httpClient = new AccessTokenHttpClient(options.httpClient || new DefaultHttpClient(this._logger), options.accessTokenFactory); + this._connectionState = "Disconnected" /* ConnectionState.Disconnected */; + this._connectionStarted = false; + this._options = options; + this.onreceive = null; + this.onclose = null; + } + async start(transferFormat) { + transferFormat = transferFormat || TransferFormat.Binary; + Arg.isIn(transferFormat, TransferFormat, "transferFormat"); + this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`); + if (this._connectionState !== "Disconnected" /* ConnectionState.Disconnected */) { + return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state.")); + } + this._connectionState = "Connecting" /* ConnectionState.Connecting */; + this._startInternalPromise = this._startInternal(transferFormat); + await this._startInternalPromise; + // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong. + if (this._connectionState === "Disconnecting" /* ConnectionState.Disconnecting */) { + // stop() was called and transitioned the client into the Disconnecting state. + const message = "Failed to start the HttpConnection before stop() was called."; + this._logger.log(LogLevel.Error, message); + // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise. + await this._stopPromise; + return Promise.reject(new AbortError(message)); + } + else if (this._connectionState !== "Connected" /* ConnectionState.Connected */) { + // stop() was called and transitioned the client into the Disconnecting state. + const message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!"; + this._logger.log(LogLevel.Error, message); + return Promise.reject(new AbortError(message)); + } + this._connectionStarted = true; + } + send(data) { + if (this._connectionState !== "Connected" /* ConnectionState.Connected */) { + return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")); + } + if (!this._sendQueue) { + this._sendQueue = new TransportSendQueue(this.transport); + } + // Transport will not be null if state is connected + return this._sendQueue.send(data); + } + async stop(error) { + if (this._connectionState === "Disconnected" /* ConnectionState.Disconnected */) { + this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`); + return Promise.resolve(); + } + if (this._connectionState === "Disconnecting" /* ConnectionState.Disconnecting */) { + this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`); + return this._stopPromise; + } + this._connectionState = "Disconnecting" /* ConnectionState.Disconnecting */; + this._stopPromise = new Promise((resolve) => { + // Don't complete stop() until stopConnection() completes. + this._stopPromiseResolver = resolve; + }); + // stopInternal should never throw so just observe it. + await this._stopInternal(error); + await this._stopPromise; + } + async _stopInternal(error) { + // Set error as soon as possible otherwise there is a race between + // the transport closing and providing an error and the error from a close message + // We would prefer the close message error. + this._stopError = error; + try { + await this._startInternalPromise; + } + catch (e) { + // This exception is returned to the user as a rejected Promise from the start method. + } + // The transport's onclose will trigger stopConnection which will run our onclose event. + // The transport should always be set if currently connected. If it wasn't set, it's likely because + // stop was called during start() and start() failed. + if (this.transport) { + try { + await this.transport.stop(); + } + catch (e) { + this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`); + this._stopConnection(); + } + this.transport = undefined; + } + else { + this._logger.log(LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed."); + } + } + async _startInternal(transferFormat) { + // Store the original base url and the access token factory since they may change + // as part of negotiating + let url = this.baseUrl; + this._accessTokenFactory = this._options.accessTokenFactory; + this._httpClient._accessTokenFactory = this._accessTokenFactory; + try { + if (this._options.skipNegotiation) { + if (this._options.transport === HttpTransportType.WebSockets) { + // No need to add a connection ID in this case + this.transport = this._constructTransport(HttpTransportType.WebSockets); + // We should just call connect directly in this case. + // No fallback or negotiate in this case. + await this._startTransport(url, transferFormat); + } + else { + throw new Error("Negotiation can only be skipped when using the WebSocket transport directly."); + } + } + else { + let negotiateResponse = null; + let redirects = 0; + do { + negotiateResponse = await this._getNegotiationResponse(url); + // the user tries to stop the connection when it is being started + if (this._connectionState === "Disconnecting" /* ConnectionState.Disconnecting */ || this._connectionState === "Disconnected" /* ConnectionState.Disconnected */) { + throw new AbortError("The connection was stopped during negotiation."); + } + if (negotiateResponse.error) { + throw new Error(negotiateResponse.error); + } + if (negotiateResponse.ProtocolVersion) { + throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."); + } + if (negotiateResponse.url) { + url = negotiateResponse.url; + } + if (negotiateResponse.accessToken) { + // Replace the current access token factory with one that uses + // the returned access token + const accessToken = negotiateResponse.accessToken; + this._accessTokenFactory = () => accessToken; + // set the factory to undefined so the AccessTokenHttpClient won't retry with the same token, since we know it won't change until a connection restart + this._httpClient._accessToken = accessToken; + this._httpClient._accessTokenFactory = undefined; + } + redirects++; + } while (negotiateResponse.url && redirects < MAX_REDIRECTS); + if (redirects === MAX_REDIRECTS && negotiateResponse.url) { + throw new Error("Negotiate redirection limit exceeded."); + } + await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat); + } + if (this.transport instanceof LongPollingTransport) { + this.features.inherentKeepAlive = true; + } + if (this._connectionState === "Connecting" /* ConnectionState.Connecting */) { + // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise. + // start() will handle the case when stop was called and startInternal exits still in the disconnecting state. + this._logger.log(LogLevel.Debug, "The HttpConnection connected successfully."); + this._connectionState = "Connected" /* ConnectionState.Connected */; + } + // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up. + // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection() + // will transition to the disconnected state. start() will wait for the transition using the stopPromise. + } + catch (e) { + this._logger.log(LogLevel.Error, "Failed to start the connection: " + e); + this._connectionState = "Disconnected" /* ConnectionState.Disconnected */; + this.transport = undefined; + // if start fails, any active calls to stop assume that start will complete the stop promise + this._stopPromiseResolver(); + return Promise.reject(e); + } + } + async _getNegotiationResponse(url) { + const headers = {}; + const [name, value] = getUserAgentHeader(); + headers[name] = value; + const negotiateUrl = this._resolveNegotiateUrl(url); + this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`); + try { + const response = await this._httpClient.post(negotiateUrl, { + content: "", + headers: { ...headers, ...this._options.headers }, + timeout: this._options.timeout, + withCredentials: this._options.withCredentials, + }); + if (response.statusCode !== 200) { + return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`)); + } + const negotiateResponse = JSON.parse(response.content); + if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) { + // Negotiate version 0 doesn't use connectionToken + // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version + negotiateResponse.connectionToken = negotiateResponse.connectionId; + } + if (negotiateResponse.useStatefulReconnect && this._options._useStatefulReconnect !== true) { + return Promise.reject(new FailedToNegotiateWithServerError("Client didn't negotiate Stateful Reconnect but the server did.")); + } + return negotiateResponse; + } + catch (e) { + let errorMessage = "Failed to complete negotiation with the server: " + e; + if (e instanceof HttpError) { + if (e.statusCode === 404) { + errorMessage = errorMessage + " Either this is not a SignalR endpoint or there is a proxy blocking the connection."; + } + } + this._logger.log(LogLevel.Error, errorMessage); + return Promise.reject(new FailedToNegotiateWithServerError(errorMessage)); + } + } + _createConnectUrl(url, connectionToken) { + if (!connectionToken) { + return url; + } + return url + (url.indexOf("?") === -1 ? "?" : "&") + `id=${connectionToken}`; + } + async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) { + let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken); + if (this._isITransport(requestedTransport)) { + this._logger.log(LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly."); + this.transport = requestedTransport; + await this._startTransport(connectUrl, requestedTransferFormat); + this.connectionId = negotiateResponse.connectionId; + return; + } + const transportExceptions = []; + const transports = negotiateResponse.availableTransports || []; + let negotiate = negotiateResponse; + for (const endpoint of transports) { + const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat, (negotiate === null || negotiate === void 0 ? void 0 : negotiate.useStatefulReconnect) === true); + if (transportOrError instanceof Error) { + // Store the error and continue, we don't want to cause a re-negotiate in these cases + transportExceptions.push(`${endpoint.transport} failed:`); + transportExceptions.push(transportOrError); + } + else if (this._isITransport(transportOrError)) { + this.transport = transportOrError; + if (!negotiate) { + try { + negotiate = await this._getNegotiationResponse(url); + } + catch (ex) { + return Promise.reject(ex); + } + connectUrl = this._createConnectUrl(url, negotiate.connectionToken); + } + try { + await this._startTransport(connectUrl, requestedTransferFormat); + this.connectionId = negotiate.connectionId; + return; + } + catch (ex) { + this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`); + negotiate = undefined; + transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport])); + if (this._connectionState !== "Connecting" /* ConnectionState.Connecting */) { + const message = "Failed to select transport before stop() was called."; + this._logger.log(LogLevel.Debug, message); + return Promise.reject(new AbortError(message)); + } + } + } + } + if (transportExceptions.length > 0) { + return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(" ")}`, transportExceptions)); + } + return Promise.reject(new Error("None of the transports supported by the client are supported by the server.")); + } + _constructTransport(transport) { + switch (transport) { + case HttpTransportType.WebSockets: + if (!this._options.WebSocket) { + throw new Error("'WebSocket' is not supported in your environment."); + } + return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {}); + case HttpTransportType.ServerSentEvents: + if (!this._options.EventSource) { + throw new Error("'EventSource' is not supported in your environment."); + } + return new ServerSentEventsTransport(this._httpClient, this._httpClient._accessToken, this._logger, this._options); + case HttpTransportType.LongPolling: + return new LongPollingTransport(this._httpClient, this._logger, this._options); + default: + throw new Error(`Unknown transport: ${transport}.`); + } + } + _startTransport(url, transferFormat) { + this.transport.onreceive = this.onreceive; + if (this.features.reconnect) { + this.transport.onclose = async (e) => { + let callStop = false; + if (this.features.reconnect) { + try { + this.features.disconnected(); + await this.transport.connect(url, transferFormat); + await this.features.resend(); + } + catch { + callStop = true; + } + } + else { + this._stopConnection(e); + return; + } + if (callStop) { + this._stopConnection(e); + } + }; + } + else { + this.transport.onclose = (e) => this._stopConnection(e); + } + return this.transport.connect(url, transferFormat); + } + _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat, useStatefulReconnect) { + const transport = HttpTransportType[endpoint.transport]; + if (transport === null || transport === undefined) { + this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`); + return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`); + } + else { + if (transportMatches(requestedTransport, transport)) { + const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]); + if (transferFormats.indexOf(requestedTransferFormat) >= 0) { + if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) || + (transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) { + this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`); + return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport); + } + else { + this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`); + try { + this.features.reconnect = transport === HttpTransportType.WebSockets ? useStatefulReconnect : undefined; + return this._constructTransport(transport); + } + catch (ex) { + return ex; + } + } + } + else { + this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`); + return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`); + } + } + else { + this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`); + return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport); + } + } + } + _isITransport(transport) { + return transport && typeof (transport) === "object" && "connect" in transport; + } + _stopConnection(error) { + this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`); + this.transport = undefined; + // If we have a stopError, it takes precedence over the error from the transport + error = this._stopError || error; + this._stopError = undefined; + if (this._connectionState === "Disconnected" /* ConnectionState.Disconnected */) { + this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`); + return; + } + if (this._connectionState === "Connecting" /* ConnectionState.Connecting */) { + this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`); + throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`); + } + if (this._connectionState === "Disconnecting" /* ConnectionState.Disconnecting */) { + // A call to stop() induced this call to stopConnection and needs to be completed. + // Any stop() awaiters will be scheduled to continue after the onclose callback fires. + this._stopPromiseResolver(); + } + if (error) { + this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`); + } + else { + this._logger.log(LogLevel.Information, "Connection disconnected."); + } + if (this._sendQueue) { + this._sendQueue.stop().catch((e) => { + this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`); + }); + this._sendQueue = undefined; + } + this.connectionId = undefined; + this._connectionState = "Disconnected" /* ConnectionState.Disconnected */; + if (this._connectionStarted) { + this._connectionStarted = false; + try { + if (this.onclose) { + this.onclose(error); + } + } + catch (e) { + this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`); + } + } + } + _resolveUrl(url) { + // startsWith is not supported in IE + if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) { + return url; + } + if (!Platform.isBrowser) { + throw new Error(`Cannot resolve '${url}'.`); + } + // Setting the url to the href propery of an anchor tag handles normalization + // for us. There are 3 main cases. + // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b" + // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b" + // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b" + const aTag = window.document.createElement("a"); + aTag.href = url; + this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`); + return aTag.href; + } + _resolveNegotiateUrl(url) { + const negotiateUrl = new URL(url); + if (negotiateUrl.pathname.endsWith('/')) { + negotiateUrl.pathname += "negotiate"; + } + else { + negotiateUrl.pathname += "/negotiate"; + } + const searchParams = new URLSearchParams(negotiateUrl.searchParams); + if (!searchParams.has("negotiateVersion")) { + searchParams.append("negotiateVersion", this._negotiateVersion.toString()); + } + if (searchParams.has("useStatefulReconnect")) { + if (searchParams.get("useStatefulReconnect") === "true") { + this._options._useStatefulReconnect = true; + } + } + else if (this._options._useStatefulReconnect === true) { + searchParams.append("useStatefulReconnect", "true"); + } + negotiateUrl.search = searchParams.toString(); + return negotiateUrl.toString(); + } +} +function transportMatches(requestedTransport, actualTransport) { + return !requestedTransport || ((actualTransport & requestedTransport) !== 0); +} +/** @private */ +class TransportSendQueue { + constructor(_transport) { + this._transport = _transport; + this._buffer = []; + this._executing = true; + this._sendBufferedData = new PromiseSource(); + this._transportResult = new PromiseSource(); + this._sendLoopPromise = this._sendLoop(); + } + send(data) { + this._bufferData(data); + if (!this._transportResult) { + this._transportResult = new PromiseSource(); + } + return this._transportResult.promise; + } + stop() { + this._executing = false; + this._sendBufferedData.resolve(); + return this._sendLoopPromise; + } + _bufferData(data) { + if (this._buffer.length && typeof (this._buffer[0]) !== typeof (data)) { + throw new Error(`Expected data to be of type ${typeof (this._buffer)} but was of type ${typeof (data)}`); + } + this._buffer.push(data); + this._sendBufferedData.resolve(); + } + async _sendLoop() { + while (true) { + await this._sendBufferedData.promise; + if (!this._executing) { + if (this._transportResult) { + this._transportResult.reject("Connection stopped."); + } + break; + } + this._sendBufferedData = new PromiseSource(); + const transportResult = this._transportResult; + this._transportResult = undefined; + const data = typeof (this._buffer[0]) === "string" ? + this._buffer.join("") : + TransportSendQueue._concatBuffers(this._buffer); + this._buffer.length = 0; + try { + await this._transport.send(data); + transportResult.resolve(); + } + catch (error) { + transportResult.reject(error); + } + } + } + static _concatBuffers(arrayBuffers) { + const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const item of arrayBuffers) { + result.set(new Uint8Array(item), offset); + offset += item.byteLength; + } + return result.buffer; + } +} +class PromiseSource { + constructor() { + this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]); + } + resolve() { + this._resolver(); + } + reject(reason) { + this._rejecter(reason); + } +} + +;// CONCATENATED MODULE: ./src/JsonHubProtocol.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + + + + + +const JSON_HUB_PROTOCOL_NAME = "json"; /** Implements the JSON Hub Protocol. */ -var JsonHubProtocol = /** @class */ (function () { - function JsonHubProtocol() { +class JsonHubProtocol { + constructor() { /** @inheritDoc */ this.name = JSON_HUB_PROTOCOL_NAME; /** @inheritDoc */ - this.version = 1; + this.version = 2; /** @inheritDoc */ - this.transferFormat = _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"].Text; + this.transferFormat = TransferFormat.Text; } /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation. * * @param {string} input A string containing the serialized representation. * @param {ILogger} logger A logger that will be used to log messages that occur during parsing. */ - JsonHubProtocol.prototype.parseMessages = function (input, logger) { + parseMessages(input, logger) { // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error. if (typeof input !== "string") { throw new Error("Invalid input for JSON hub protocol. Expected a string."); @@ -5217,82 +3272,285 @@ var JsonHubProtocol = /** @class */ (function () { return []; } if (logger === null) { - logger = _Loggers__WEBPACK_IMPORTED_MODULE_3__["NullLogger"].instance; + logger = NullLogger.instance; } // Parse the messages - var messages = _TextMessageFormat__WEBPACK_IMPORTED_MODULE_4__["TextMessageFormat"].parse(input); - var hubMessages = []; - for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { - var message = messages_1[_i]; - var parsedMessage = JSON.parse(message); + const messages = TextMessageFormat.parse(input); + const hubMessages = []; + for (const message of messages) { + const parsedMessage = JSON.parse(message); if (typeof parsedMessage.type !== "number") { throw new Error("Invalid payload."); } switch (parsedMessage.type) { - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Invocation: - this.isInvocationMessage(parsedMessage); + case MessageType.Invocation: + this._isInvocationMessage(parsedMessage); break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].StreamItem: - this.isStreamItemMessage(parsedMessage); + case MessageType.StreamItem: + this._isStreamItemMessage(parsedMessage); break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Completion: - this.isCompletionMessage(parsedMessage); + case MessageType.Completion: + this._isCompletionMessage(parsedMessage); break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Ping: + case MessageType.Ping: // Single value, no need to validate break; - case _IHubProtocol__WEBPACK_IMPORTED_MODULE_0__["MessageType"].Close: + case MessageType.Close: // All optional values, no need to validate break; + case MessageType.Ack: + this._isAckMessage(parsedMessage); + break; + case MessageType.Sequence: + this._isSequenceMessage(parsedMessage); + break; default: // Future protocol changes can add message types, old clients can ignore them - logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information, "Unknown message type '" + parsedMessage.type + "' ignored."); + logger.log(LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored."); continue; } hubMessages.push(parsedMessage); } return hubMessages; - }; + } /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it. * * @param {HubMessage} message The message to write. * @returns {string} A string containing the serialized representation of the message. */ - JsonHubProtocol.prototype.writeMessage = function (message) { - return _TextMessageFormat__WEBPACK_IMPORTED_MODULE_4__["TextMessageFormat"].write(JSON.stringify(message)); - }; - JsonHubProtocol.prototype.isInvocationMessage = function (message) { - this.assertNotEmptyString(message.target, "Invalid payload for Invocation message."); + writeMessage(message) { + return TextMessageFormat.write(JSON.stringify(message)); + } + _isInvocationMessage(message) { + this._assertNotEmptyString(message.target, "Invalid payload for Invocation message."); if (message.invocationId !== undefined) { - this.assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message."); + this._assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message."); } - }; - JsonHubProtocol.prototype.isStreamItemMessage = function (message) { - this.assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message."); + } + _isStreamItemMessage(message) { + this._assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message."); if (message.item === undefined) { throw new Error("Invalid payload for StreamItem message."); } - }; - JsonHubProtocol.prototype.isCompletionMessage = function (message) { + } + _isCompletionMessage(message) { if (message.result && message.error) { throw new Error("Invalid payload for Completion message."); } if (!message.result && message.error) { - this.assertNotEmptyString(message.error, "Invalid payload for Completion message."); + this._assertNotEmptyString(message.error, "Invalid payload for Completion message."); } - this.assertNotEmptyString(message.invocationId, "Invalid payload for Completion message."); - }; - JsonHubProtocol.prototype.assertNotEmptyString = function (value, errorMessage) { + this._assertNotEmptyString(message.invocationId, "Invalid payload for Completion message."); + } + _isAckMessage(message) { + if (typeof message.sequenceId !== 'number') { + throw new Error("Invalid SequenceId for Ack message."); + } + } + _isSequenceMessage(message) { + if (typeof message.sequenceId !== 'number') { + throw new Error("Invalid SequenceId for Sequence message."); + } + } + _assertNotEmptyString(value, errorMessage) { if (typeof value !== "string" || value === "") { throw new Error(errorMessage); } - }; - return JsonHubProtocol; -}()); + } +} + +;// CONCATENATED MODULE: ./src/HubConnectionBuilder.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. -/***/ }) -/******/ ]); + + + + +const LogLevelNameMapping = { + trace: LogLevel.Trace, + debug: LogLevel.Debug, + info: LogLevel.Information, + information: LogLevel.Information, + warn: LogLevel.Warning, + warning: LogLevel.Warning, + error: LogLevel.Error, + critical: LogLevel.Critical, + none: LogLevel.None, +}; +function parseLogLevel(name) { + // Case-insensitive matching via lower-casing + // Yes, I know case-folding is a complicated problem in Unicode, but we only support + // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse. + const mapping = LogLevelNameMapping[name.toLowerCase()]; + if (typeof mapping !== "undefined") { + return mapping; + } + else { + throw new Error(`Unknown log level: ${name}`); + } +} +/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */ +class HubConnectionBuilder { + configureLogging(logging) { + Arg.isRequired(logging, "logging"); + if (isLogger(logging)) { + this.logger = logging; + } + else if (typeof logging === "string") { + const logLevel = parseLogLevel(logging); + this.logger = new ConsoleLogger(logLevel); + } + else { + this.logger = new ConsoleLogger(logging); + } + return this; + } + withUrl(url, transportTypeOrOptions) { + Arg.isRequired(url, "url"); + Arg.isNotEmpty(url, "url"); + this.url = url; + // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed + // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called. + if (typeof transportTypeOrOptions === "object") { + this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions }; + } + else { + this.httpConnectionOptions = { + ...this.httpConnectionOptions, + transport: transportTypeOrOptions, + }; + } + return this; + } + /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol. + * + * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use. + */ + withHubProtocol(protocol) { + Arg.isRequired(protocol, "protocol"); + this.protocol = protocol; + return this; + } + withAutomaticReconnect(retryDelaysOrReconnectPolicy) { + if (this.reconnectPolicy) { + throw new Error("A reconnectPolicy has already been set."); + } + if (!retryDelaysOrReconnectPolicy) { + this.reconnectPolicy = new DefaultReconnectPolicy(); + } + else if (Array.isArray(retryDelaysOrReconnectPolicy)) { + this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy); + } + else { + this.reconnectPolicy = retryDelaysOrReconnectPolicy; + } + return this; + } + /** Configures {@link @microsoft/signalr.HubConnection.serverTimeoutInMilliseconds} for the {@link @microsoft/signalr.HubConnection}. + * + * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining. + */ + withServerTimeout(milliseconds) { + Arg.isRequired(milliseconds, "milliseconds"); + this._serverTimeoutInMilliseconds = milliseconds; + return this; + } + /** Configures {@link @microsoft/signalr.HubConnection.keepAliveIntervalInMilliseconds} for the {@link @microsoft/signalr.HubConnection}. + * + * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining. + */ + withKeepAliveInterval(milliseconds) { + Arg.isRequired(milliseconds, "milliseconds"); + this._keepAliveIntervalInMilliseconds = milliseconds; + return this; + } + /** Enables and configures options for the Stateful Reconnect feature. + * + * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining. + */ + withStatefulReconnect(options) { + if (this.httpConnectionOptions === undefined) { + this.httpConnectionOptions = {}; + } + this.httpConnectionOptions._useStatefulReconnect = true; + this._statefulReconnectBufferSize = options === null || options === void 0 ? void 0 : options.bufferSize; + return this; + } + /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder. + * + * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}. + */ + build() { + // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one + // provided to configureLogger + const httpConnectionOptions = this.httpConnectionOptions || {}; + // If it's 'null', the user **explicitly** asked for null, don't mess with it. + if (httpConnectionOptions.logger === undefined) { + // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it. + httpConnectionOptions.logger = this.logger; + } + // Now create the connection + if (!this.url) { + throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection."); + } + const connection = new HttpConnection(this.url, httpConnectionOptions); + return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy, this._serverTimeoutInMilliseconds, this._keepAliveIntervalInMilliseconds, this._statefulReconnectBufferSize); + } +} +function isLogger(logger) { + return logger.log !== undefined; +} + +;// CONCATENATED MODULE: ./src/index.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./src/browser-index.ts +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds. +// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties +// that exist on Uint8Array with the same name, and JavaScript is magic. +// We make them 'writable' because the Buffer polyfill messes with it as well. +if (!Uint8Array.prototype.indexOf) { + Object.defineProperty(Uint8Array.prototype, "indexOf", { + value: Array.prototype.indexOf, + writable: true, + }); +} +if (!Uint8Array.prototype.slice) { + Object.defineProperty(Uint8Array.prototype, "slice", { + // wrap the slice in Uint8Array so it looks like a Uint8Array.slice call + // eslint-disable-next-line object-shorthand + value: function (start, end) { return new Uint8Array(Array.prototype.slice.call(this, start, end)); }, + writable: true, + }); +} +if (!Uint8Array.prototype.forEach) { + Object.defineProperty(Uint8Array.prototype, "forEach", { + value: Array.prototype.forEach, + writable: true, + }); +} + + +/******/ return __webpack_exports__; +/******/ })() +; }); //# sourceMappingURL=signalr.js.map \ No newline at end of file diff --git a/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.min.js b/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.min.js index 1a9bca9..a6199ba 100644 --- a/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.min.js +++ b/BinaryDad.Coding/wwwroot/js/signalr/dist/browser/signalr.min.js @@ -1,17 +1,2 @@ -(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["signalR"]=factory();else root["signalR"]=factory()})(window,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={i:moduleId,l:false,exports:{}};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.l=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.d=function(exports,name,getter){if(!__webpack_require__.o(exports,name)){Object.defineProperty(exports,name,{enumerable:true,get:getter})}};__webpack_require__.r=function(exports){if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(exports,"__esModule",{value:true})};__webpack_require__.t=function(value,mode){if(mode&1)value=__webpack_require__(value);if(mode&8)return value;if(mode&4&&typeof value==="object"&&value&&value.__esModule)return value;var ns=Object.create(null);__webpack_require__.r(ns);Object.defineProperty(ns,"default",{enumerable:true,value:value});if(mode&2&&typeof value!="string")for(var key in value)__webpack_require__.d(ns,key,function(key){return value[key]}.bind(null,key));return ns};__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};__webpack_require__.d(getter,"a",getter);return getter};__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)};__webpack_require__.p="";return __webpack_require__(__webpack_require__.s=0)}([function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(1);var es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0___default=__webpack_require__.n(es6_promise_dist_es6_promise_auto_js__WEBPACK_IMPORTED_MODULE_0__);var _index__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(3);__webpack_require__.d(__webpack_exports__,"AbortError",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["AbortError"]});__webpack_require__.d(__webpack_exports__,"HttpError",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpError"]});__webpack_require__.d(__webpack_exports__,"TimeoutError",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["TimeoutError"]});__webpack_require__.d(__webpack_exports__,"HttpClient",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpClient"]});__webpack_require__.d(__webpack_exports__,"HttpResponse",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"]});__webpack_require__.d(__webpack_exports__,"DefaultHttpClient",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["DefaultHttpClient"]});__webpack_require__.d(__webpack_exports__,"HubConnection",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnection"]});__webpack_require__.d(__webpack_exports__,"HubConnectionState",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionState"]});__webpack_require__.d(__webpack_exports__,"HubConnectionBuilder",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HubConnectionBuilder"]});__webpack_require__.d(__webpack_exports__,"MessageType",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["MessageType"]});__webpack_require__.d(__webpack_exports__,"LogLevel",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["LogLevel"]});__webpack_require__.d(__webpack_exports__,"HttpTransportType",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["HttpTransportType"]});__webpack_require__.d(__webpack_exports__,"TransferFormat",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["TransferFormat"]});__webpack_require__.d(__webpack_exports__,"NullLogger",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["NullLogger"]});__webpack_require__.d(__webpack_exports__,"JsonHubProtocol",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["JsonHubProtocol"]});__webpack_require__.d(__webpack_exports__,"Subject",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["Subject"]});__webpack_require__.d(__webpack_exports__,"VERSION",function(){return _index__WEBPACK_IMPORTED_MODULE_1__["VERSION"]});if(!Uint8Array.prototype.indexOf){Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:true})}if(!Uint8Array.prototype.slice){Object.defineProperty(Uint8Array.prototype,"slice",{value:function(start,end){return new Uint8Array(Array.prototype.slice.call(this,start,end))},writable:true})}if(!Uint8Array.prototype.forEach){Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:true})}},function(module,exports,__webpack_require__){(function(global){var require; -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version v4.2.2+97478eb6 - */ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version v4.2.2+97478eb6 - */ -(function(global,factory){true?module.exports=factory():undefined})(this,function(){"use strict";function objectOrFunction(x){var type=typeof x;return x!==null&&(type==="object"||type==="function")}function isFunction(x){return typeof x==="function"}var _isArray=void 0;if(Array.isArray){_isArray=Array.isArray}else{_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}var isArray=_isArray;var len=0;var vertxNext=void 0;var customSchedulerFn=void 0;var asap=function asap(callback,arg){queue[len]=callback;queue[len+1]=arg;len+=2;if(len===2){if(customSchedulerFn){customSchedulerFn(flush)}else{scheduleFlush()}}};function setScheduler(scheduleFn){customSchedulerFn=scheduleFn}function setAsap(asapFn){asap=asapFn}var browserWindow=typeof window!=="undefined"?window:undefined;var browserGlobal=browserWindow||{};var BrowserMutationObserver=browserGlobal.MutationObserver||browserGlobal.WebKitMutationObserver;var isNode=typeof self==="undefined"&&typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function useNextTick(){return function(){return process.nextTick(flush)}}function useVertxTimer(){if(typeof vertxNext!=="undefined"){return function(){vertxNext(flush)}}return useSetTimeout()}function useMutationObserver(){var iterations=0;var observer=new BrowserMutationObserver(flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=flush;return function(){return channel.port2.postMessage(0)}}function useSetTimeout(){var globalSetTimeout=setTimeout;return function(){return globalSetTimeout(flush,1)}}var queue=new Array(1e3);function flush(){for(var i=0;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]-1){this.subject.observers.splice(index,1)}if(this.subject.observers.length===0&&this.subject.cancelCallback){this.subject.cancelCallback().catch(function(_){})}};return SubjectSubscription}();var ConsoleLogger=function(){function ConsoleLogger(minimumLogLevel){this.minimumLogLevel=minimumLogLevel;this.outputConsole=console}ConsoleLogger.prototype.log=function(logLevel,message){if(logLevel>=this.minimumLogLevel){switch(logLevel){case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Critical:case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Error:this.outputConsole.error("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break;case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Warning:this.outputConsole.warn("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break;case _ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"].Information:this.outputConsole.info("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break;default:this.outputConsole.log("["+(new Date).toISOString()+"] "+_ILogger__WEBPACK_IMPORTED_MODULE_0__["LogLevel"][logLevel]+": "+message);break}}};return ConsoleLogger}();function getUserAgentHeader(){var userAgentHeaderName="X-SignalR-User-Agent";if(Platform.isNode){userAgentHeaderName="User-Agent"}return[userAgentHeaderName,constructUserAgent(VERSION,getOsName(),getRuntime(),getRuntimeVersion())]}function constructUserAgent(version,os,runtime,runtimeVersion){var userAgent="Microsoft SignalR/";var majorAndMinor=version.split(".");userAgent+=majorAndMinor[0]+"."+majorAndMinor[1];userAgent+=" ("+version+"; ";if(os&&os!==""){userAgent+=os+"; "}else{userAgent+="Unknown OS; "}userAgent+=""+runtime;if(runtimeVersion){userAgent+="; "+runtimeVersion}else{userAgent+="; Unknown Runtime Version"}userAgent+=")";return userAgent}function getOsName(){if(Platform.isNode){switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}else{return""}}function getRuntimeVersion(){if(Platform.isNode){return process.versions.node}return undefined}function getRuntime(){if(Platform.isNode){return"NodeJS"}else{return"Browser"}}},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"NullLogger",function(){return NullLogger});var NullLogger=function(){function NullLogger(){}NullLogger.prototype.log=function(_logLevel,_message){};NullLogger.instance=new NullLogger;return NullLogger}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"XhrHttpClient",function(){return XhrHttpClient});var _Errors__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(4);var _HttpClient__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(5);var _ILogger__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(8);var __extends=undefined&&undefined.__extends||function(){var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p]};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var XhrHttpClient=function(_super){__extends(XhrHttpClient,_super);function XhrHttpClient(logger){var _this=_super.call(this)||this;_this.logger=logger;return _this}XhrHttpClient.prototype.send=function(request){var _this=this;if(request.abortSignal&&request.abortSignal.aborted){return Promise.reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"])}if(!request.method){return Promise.reject(new Error("No method defined."))}if(!request.url){return Promise.reject(new Error("No url defined."))}return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open(request.method,request.url,true);xhr.withCredentials=request.withCredentials===undefined?true:request.withCredentials;xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");var headers=request.headers;if(headers){Object.keys(headers).forEach(function(header){xhr.setRequestHeader(header,headers[header])})}if(request.responseType){xhr.responseType=request.responseType}if(request.abortSignal){request.abortSignal.onabort=function(){xhr.abort();reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["AbortError"])}}if(request.timeout){xhr.timeout=request.timeout}xhr.onload=function(){if(request.abortSignal){request.abortSignal.onabort=null}if(xhr.status>=200&&xhr.status<300){resolve(new _HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpResponse"](xhr.status,xhr.statusText,xhr.response||xhr.responseText))}else{reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText,xhr.status))}};xhr.onerror=function(){_this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning,"Error from HTTP request. "+xhr.status+": "+xhr.statusText+".");reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["HttpError"](xhr.statusText,xhr.status))};xhr.ontimeout=function(){_this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Warning,"Timeout from HTTP request.");reject(new _Errors__WEBPACK_IMPORTED_MODULE_0__["TimeoutError"])};xhr.send(request.content||"")})};return XhrHttpClient}(_HttpClient__WEBPACK_IMPORTED_MODULE_1__["HttpClient"])},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"HubConnectionState",function(){return HubConnectionState});__webpack_require__.d(__webpack_exports__,"HubConnection",function(){return HubConnection});var _HandshakeProtocol__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(13);var _IHubProtocol__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(15);var _ILogger__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(8);var _Subject__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(16);var _Utils__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(9);var __awaiter=undefined&&undefined.__awaiter||function(thisArg,_arguments,P,generator){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):new P(function(resolve){resolve(result.value)}).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=undefined&&undefined.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),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(_)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]responseLength?binaryData.slice(responseLength).buffer:null}else{var textData=data;var separatorIndex=textData.indexOf(_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].RecordSeparator);if(separatorIndex===-1){throw new Error("Message is incomplete.")}var responseLength=separatorIndex+1;messageData=textData.substring(0,responseLength);remainingData=textData.length>responseLength?textData.substring(responseLength):null}var messages=_TextMessageFormat__WEBPACK_IMPORTED_MODULE_0__["TextMessageFormat"].parse(messageData);var response=JSON.parse(messages[0]);if(response.type){throw new Error("Expected a handshake response from the server.")}responseMessage=response;return[remainingData,responseMessage]};return HandshakeProtocol}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"TextMessageFormat",function(){return TextMessageFormat});var TextMessageFormat=function(){function TextMessageFormat(){}TextMessageFormat.write=function(output){return""+output+TextMessageFormat.RecordSeparator};TextMessageFormat.parse=function(input){if(input[input.length-1]!==TextMessageFormat.RecordSeparator){throw new Error("Message is incomplete.")}var messages=input.split(TextMessageFormat.RecordSeparator);messages.pop();return messages};TextMessageFormat.RecordSeparatorCode=30;TextMessageFormat.RecordSeparator=String.fromCharCode(TextMessageFormat.RecordSeparatorCode);return TextMessageFormat}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"MessageType",function(){return MessageType});var MessageType;(function(MessageType){MessageType[MessageType["Invocation"]=1]="Invocation";MessageType[MessageType["StreamItem"]=2]="StreamItem";MessageType[MessageType["Completion"]=3]="Completion";MessageType[MessageType["StreamInvocation"]=4]="StreamInvocation";MessageType[MessageType["CancelInvocation"]=5]="CancelInvocation";MessageType[MessageType["Ping"]=6]="Ping";MessageType[MessageType["Close"]=7]="Close"})(MessageType||(MessageType={}))},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"Subject",function(){return Subject});var _Utils__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(9);var Subject=function(){function Subject(){this.observers=[]}Subject.prototype.next=function(item){for(var _i=0,_a=this.observers;_i<_a.length;_i++){var observer=_a[_i];observer.next(item)}};Subject.prototype.error=function(err){for(var _i=0,_a=this.observers;_i<_a.length;_i++){var observer=_a[_i];if(observer.error){observer.error(err)}}};Subject.prototype.complete=function(){for(var _i=0,_a=this.observers;_i<_a.length;_i++){var observer=_a[_i];if(observer.complete){observer.complete()}}};Subject.prototype.subscribe=function(observer){this.observers.push(observer);return new _Utils__WEBPACK_IMPORTED_MODULE_0__["SubjectSubscription"](this,observer)};return Subject}()},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"HubConnectionBuilder",function(){return HubConnectionBuilder});var _DefaultReconnectPolicy__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(18);var _HttpConnection__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(19);var _HubConnection__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(12);var _ILogger__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(8);var _JsonHubProtocol__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(25);var _Loggers__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(10);var _Utils__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(9);var __assign=undefined&&undefined.__assign||Object.assign||function(t){for(var s,i=1,n=arguments.length;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0){return[2,Promise.reject(new Error("Unable to connect to the server with any of the available transports. "+transportExceptions.join(" ")))]}return[2,Promise.reject(new Error("None of the transports supported by the client are supported by the server."))]}})})};HttpConnection.prototype.constructTransport=function(transport){switch(transport){case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets:if(!this.options.WebSocket){throw new Error("'WebSocket' is not supported in your environment.")}return new _WebSocketTransport__WEBPACK_IMPORTED_MODULE_6__["WebSocketTransport"](this.httpClient,this.accessTokenFactory,this.logger,this.options.logMessageContent||false,this.options.WebSocket,this.options.headers||{});case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents:if(!this.options.EventSource){throw new Error("'EventSource' is not supported in your environment.")}return new _ServerSentEventsTransport__WEBPACK_IMPORTED_MODULE_4__["ServerSentEventsTransport"](this.httpClient,this.accessTokenFactory,this.logger,this.options.logMessageContent||false,this.options.EventSource,this.options.withCredentials,this.options.headers||{});case _ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].LongPolling:return new _LongPollingTransport__WEBPACK_IMPORTED_MODULE_3__["LongPollingTransport"](this.httpClient,this.accessTokenFactory,this.logger,this.options.logMessageContent||false,this.options.withCredentials,this.options.headers||{});default:throw new Error("Unknown transport: "+transport+".")}};HttpConnection.prototype.startTransport=function(url,transferFormat){var _this=this;this.transport.onreceive=this.onreceive;this.transport.onclose=function(e){return _this.stopConnection(e)};return this.transport.connect(url,transferFormat)};HttpConnection.prototype.resolveTransportOrError=function(endpoint,requestedTransport,requestedTransferFormat){var transport=_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][endpoint.transport];if(transport===null||transport===undefined){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+endpoint.transport+"' because it is not supported by this client.");return new Error("Skipping transport '"+endpoint.transport+"' because it is not supported by this client.")}else{if(transportMatches(requestedTransport,transport)){var transferFormats=endpoint.transferFormats.map(function(s){return _ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][s]});if(transferFormats.indexOf(requestedTransferFormat)>=0){if(transport===_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].WebSockets&&!this.options.WebSocket||transport===_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"].ServerSentEvents&&!this.options.EventSource){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' because it is not supported in your environment.'");return new Error("'"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' is not supported in your environment.")}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Selecting transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"'.");try{return this.constructTransport(transport)}catch(ex){return ex}}}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' because it does not support the requested transfer format '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][requestedTransferFormat]+"'.");return new Error("'"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' does not support "+_ITransport__WEBPACK_IMPORTED_MODULE_2__["TransferFormat"][requestedTransferFormat]+".")}}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Skipping transport '"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' because it was disabled by the client.");return new Error("'"+_ITransport__WEBPACK_IMPORTED_MODULE_2__["HttpTransportType"][transport]+"' is disabled by the client.")}}};HttpConnection.prototype.isITransport=function(transport){return transport&&typeof transport==="object"&&"connect"in transport};HttpConnection.prototype.stopConnection=function(error){var _this=this;this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"HttpConnection.stopConnection("+error+") called while in state "+this.connectionState+".");this.transport=undefined;error=this.stopError||error;this.stopError=undefined;if(this.connectionState==="Disconnected"){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Debug,"Call to HttpConnection.stopConnection("+error+") was ignored because the connection is already in the disconnected state.");return}if(this.connectionState==="Connecting"){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Warning,"Call to HttpConnection.stopConnection("+error+") was ignored because the connection is still in the connecting state.");throw new Error("HttpConnection.stopConnection("+error+") was called while the connection is still in the connecting state.")}if(this.connectionState==="Disconnecting"){this.stopPromiseResolver()}if(error){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error,"Connection disconnected with error '"+error+"'.")}else{this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information,"Connection disconnected.")}if(this.sendQueue){this.sendQueue.stop().catch(function(e){_this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error,"TransportSendQueue.stop() threw error '"+e+"'.")});this.sendQueue=undefined}this.connectionId=undefined;this.connectionState="Disconnected";if(this.connectionStarted){this.connectionStarted=false;try{if(this.onclose){this.onclose(error)}}catch(e){this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Error,"HttpConnection.onclose("+error+") threw error '"+e+"'.")}}};HttpConnection.prototype.resolveUrl=function(url){if(url.lastIndexOf("https://",0)===0||url.lastIndexOf("http://",0)===0){return url}if(!_Utils__WEBPACK_IMPORTED_MODULE_5__["Platform"].isBrowser||!window.document){throw new Error("Cannot resolve '"+url+"'.")}var aTag=window.document.createElement("a");aTag.href=url;this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_1__["LogLevel"].Information,"Normalizing '"+url+"' to '"+aTag.href+"'.");return aTag.href};HttpConnection.prototype.resolveNegotiateUrl=function(url){var index=url.indexOf("?");var negotiateUrl=url.substring(0,index===-1?url.length:index);if(negotiateUrl[negotiateUrl.length-1]!=="/"){negotiateUrl+="/"}negotiateUrl+="negotiate";negotiateUrl+=index===-1?"":url.substring(index);if(negotiateUrl.indexOf("negotiateVersion")===-1){negotiateUrl+=index===-1?"?":"&";negotiateUrl+="negotiateVersion="+this.negotiateVersion}return negotiateUrl};return HttpConnection}();function transportMatches(requestedTransport,actualTransport){return!requestedTransport||(actualTransport&requestedTransport)!==0}var TransportSendQueue=function(){function TransportSendQueue(transport){this.transport=transport;this.buffer=[];this.executing=true;this.sendBufferedData=new PromiseSource;this.transportResult=new PromiseSource;this.sendLoopPromise=this.sendLoop()}TransportSendQueue.prototype.send=function(data){this.bufferData(data);if(!this.transportResult){this.transportResult=new PromiseSource}return this.transportResult.promise};TransportSendQueue.prototype.stop=function(){this.executing=false;this.sendBufferedData.resolve();return this.sendLoopPromise};TransportSendQueue.prototype.bufferData=function(data){if(this.buffer.length&&typeof this.buffer[0]!==typeof data){throw new Error("Expected data to be of type "+typeof this.buffer+" but was of type "+typeof data)}this.buffer.push(data);this.sendBufferedData.resolve()};TransportSendQueue.prototype.sendLoop=function(){return __awaiter(this,void 0,void 0,function(){var transportResult,data,error_1;return __generator(this,function(_a){switch(_a.label){case 0:if(false){}return[4,this.sendBufferedData.promise];case 1:_a.sent();if(!this.executing){if(this.transportResult){this.transportResult.reject("Connection stopped.")}return[3,6]}this.sendBufferedData=new PromiseSource;transportResult=this.transportResult;this.transportResult=undefined;data=typeof this.buffer[0]==="string"?this.buffer.join(""):TransportSendQueue.concatBuffers(this.buffer);this.buffer.length=0;_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,this.transport.send(data)];case 3:_a.sent();transportResult.resolve();return[3,5];case 4:error_1=_a.sent();transportResult.reject(error_1);return[3,5];case 5:return[3,0];case 6:return[2]}})})};TransportSendQueue.concatBuffers=function(arrayBuffers){var totalLength=arrayBuffers.map(function(b){return b.byteLength}).reduce(function(a,b){return a+b});var result=new Uint8Array(totalLength);var offset=0;for(var _i=0,arrayBuffers_1=arrayBuffers;_i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1](()=>{var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"t",{value:!0})};var e,s={};t.r(s),t.d(s,{AbortError:()=>r,DefaultHttpClient:()=>H,HttpClient:()=>d,HttpError:()=>i,HttpResponse:()=>u,HttpTransportType:()=>W,HubConnection:()=>N,HubConnectionBuilder:()=>Y,HubConnectionState:()=>A,JsonHubProtocol:()=>K,LogLevel:()=>e,MessageType:()=>R,NullLogger:()=>p,Subject:()=>U,TimeoutError:()=>n,TransferFormat:()=>O,VERSION:()=>f});class i extends Error{constructor(t,e){const s=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=s}}class n extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class r extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class o extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=s}}class h extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=s}}class c extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=s}}class a extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class l extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=s}}class u{constructor(t,e,s){this.statusCode=t,this.statusText=e,this.content=s}}class d{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(e||(e={}));class p{constructor(){}log(t,e){}}p.instance=new p;const f="7.0.4";class w{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,s){if(!(t in e))throw new Error(`Unknown ${s} value: ${t}.`)}}class g{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function m(t,e){let s="";return y(t)?(s=`Binary data of length ${t.byteLength}`,e&&(s+=`. Content: '${function(t){const e=new Uint8Array(t);let s="";return e.forEach((t=>{s+=`0x${t<16?"0":""}${t.toString(16)} `})),s.substr(0,s.length-1)}(t)}'`)):"string"==typeof t&&(s=`String data of length ${t.length}`,e&&(s+=`. Content: '${t}'`)),s}function y(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function b(t,s,i,n,r,o){const h={},[c,a]=E();h[c]=a,t.log(e.Trace,`(${s} transport) sending data. ${m(r,o.logMessageContent)}.`);const l=y(r)?"arraybuffer":"text",u=await i.post(n,{content:r,headers:{...h,...o.headers},responseType:l,timeout:o.timeout,withCredentials:o.withCredentials});t.log(e.Trace,`(${s} transport) request complete. Response status: ${u.statusCode}.`)}class v{constructor(t,e){this.i=t,this.h=e}dispose(){const t=this.i.observers.indexOf(this.h);t>-1&&this.i.observers.splice(t,1),0===this.i.observers.length&&this.i.cancelCallback&&this.i.cancelCallback().catch((t=>{}))}}class ${constructor(t){this.l=t,this.out=console}log(t,s){if(t>=this.l){const i=`[${(new Date).toISOString()}] ${e[t]}: ${s}`;switch(t){case e.Critical:case e.Error:this.out.error(i);break;case e.Warning:this.out.warn(i);break;case e.Information:this.out.info(i);break;default:this.out.log(i)}}}}function E(){let t="X-SignalR-User-Agent";return g.isNode&&(t="User-Agent"),[t,C(f,S(),g.isNode?"NodeJS":"Browser",k())]}function C(t,e,s,i){let n="Microsoft SignalR/";const r=t.split(".");return n+=`${r[0]}.${r[1]}`,n+=` (${t}; `,n+=e&&""!==e?`${e}; `:"Unknown OS; ",n+=`${s}`,n+=i?`; ${i}`:"; Unknown Runtime Version",n+=")",n}function S(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function k(){if(g.isNode)return process.versions.node}function P(t){return t.stack?t.stack:t.message?t.message:`${t}`}class T extends d{constructor(e){if(super(),this.u=e,"undefined"==typeof fetch){const t=require;this.p=new(t("tough-cookie").CookieJar),this.m=t("node-fetch"),this.m=t("fetch-cookie")(this.m,this.p)}else this.m=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this.v=t("abort-controller")}else this.v=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new r;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const s=new this.v;let o;t.abortSignal&&(t.abortSignal.onabort=()=>{s.abort(),o=new r});let h,c=null;if(t.timeout){const i=t.timeout;c=setTimeout((()=>{s.abort(),this.u.log(e.Warning,"Timeout from HTTP request."),o=new n}),i)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},y(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{h=await this.m(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:s.signal})}catch(t){if(o)throw o;throw this.u.log(e.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!h.ok){const t=await I(h,"text");throw new i(t||h.statusText,h.status)}const a=I(h,t.responseType),l=await a;return new u(h.status,h.statusText,l)}getCookieString(t){let e="";return g.isNode&&this.p&&this.p.getCookies(t,((t,s)=>e=s.join("; "))),e}}function I(t,e){let s;switch(e){case"arraybuffer":s=t.arrayBuffer();break;case"text":default:s=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return s}class _ extends d{constructor(t){super(),this.u=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?new Promise(((s,o)=>{const h=new XMLHttpRequest;h.open(t.method,t.url,!0),h.withCredentials=void 0===t.withCredentials||t.withCredentials,h.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(y(t.content)?h.setRequestHeader("Content-Type","application/octet-stream"):h.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{h.setRequestHeader(t,c[t])})),t.responseType&&(h.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{h.abort(),o(new r)}),t.timeout&&(h.timeout=t.timeout),h.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),h.status>=200&&h.status<300?s(new u(h.status,h.statusText,h.response||h.responseText)):o(new i(h.response||h.responseText||h.statusText,h.status))},h.onerror=()=>{this.u.log(e.Warning,`Error from HTTP request. ${h.status}: ${h.statusText}.`),o(new i(h.statusText,h.status))},h.ontimeout=()=>{this.u.log(e.Warning,"Timeout from HTTP request."),o(new n)},h.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class H extends d{constructor(t){if(super(),"undefined"!=typeof fetch||g.isNode)this.$=new T(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this.$=new _(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?this.$.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this.$.getCookieString(t)}}class D{static write(t){return`${t}${D.RecordSeparator}`}static parse(t){if(t[t.length-1]!==D.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(D.RecordSeparator);return e.pop(),e}}D.RecordSeparatorCode=30,D.RecordSeparator=String.fromCharCode(D.RecordSeparatorCode);class x{writeHandshakeRequest(t){return D.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,s;if(y(t)){const i=new Uint8Array(t),n=i.indexOf(D.RecordSeparatorCode);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,r))),s=i.byteLength>r?i.slice(r).buffer:null}else{const i=t,n=i.indexOf(D.RecordSeparator);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=i.substring(0,r),s=i.length>r?i.substring(r):null}const i=D.parse(e),n=JSON.parse(i[0]);if(n.type)throw new Error("Expected a handshake response from the server.");return[s,n]}}var R,A;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close"}(R||(R={}));class U{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new v(this,t)}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(A||(A={}));class N{constructor(t,s,i,n){this.C=0,this.S=()=>{this.u.log(e.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},w.isRequired(t,"connection"),w.isRequired(s,"logger"),w.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this.u=s,this.k=i,this.connection=t,this.P=n,this.T=new x,this.connection.onreceive=t=>this.I(t),this.connection.onclose=t=>this._(t),this.H={},this.D={},this.R=[],this.A=[],this.U=[],this.N=0,this.L=!1,this.M=A.Disconnected,this.j=!1,this.q=this.k.writeMessage({type:R.Ping})}static create(t,e,s,i){return new N(t,e,s,i)}get state(){return this.M}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this.M!==A.Disconnected&&this.M!==A.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this.W=this.O(),this.W}async O(){if(this.M!==A.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this.M=A.Connecting,this.u.log(e.Debug,"Starting HubConnection.");try{await this.F(),g.isBrowser&&window.document.addEventListener("freeze",this.S),this.M=A.Connected,this.j=!0,this.u.log(e.Debug,"HubConnection connected successfully.")}catch(t){return this.M=A.Disconnected,this.u.log(e.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async F(){this.B=void 0,this.L=!1;const t=new Promise(((t,e)=>{this.X=t,this.J=e}));await this.connection.start(this.k.transferFormat);try{const s={protocol:this.k.name,version:this.k.version};if(this.u.log(e.Debug,"Sending handshake request."),await this.V(this.T.writeHandshakeRequest(s)),this.u.log(e.Information,`Using HubProtocol '${this.k.name}'.`),this.G(),this.K(),this.Y(),await t,this.B)throw this.B;this.connection.features.inherentKeepAlive||await this.V(this.q)}catch(t){throw this.u.log(e.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this.G(),this.Z(),await this.connection.stop(t),t}}async stop(){const t=this.W;this.tt=this.et(),await this.tt;try{await t}catch(t){}}et(t){return this.M===A.Disconnected?(this.u.log(e.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve()):this.M===A.Disconnecting?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.tt):(this.M=A.Disconnecting,this.u.log(e.Debug,"Stopping HubConnection."),this.st?(this.u.log(e.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this.st),this.st=void 0,this.it(),Promise.resolve()):(this.G(),this.Z(),this.B=t||new r("The connection was stopped before the hub handshake could complete."),this.connection.stop(t)))}stream(t,...e){const[s,i]=this.nt(e),n=this.rt(t,e,i);let r;const o=new U;return o.cancelCallback=()=>{const t=this.ot(n.invocationId);return delete this.H[n.invocationId],r.then((()=>this.ht(t)))},this.H[n.invocationId]=(t,e)=>{e?o.error(e):t&&(t.type===R.Completion?t.error?o.error(new Error(t.error)):o.complete():o.next(t.item))},r=this.ht(n).catch((t=>{o.error(t),delete this.H[n.invocationId]})),this.ct(s,r),o}V(t){return this.Y(),this.connection.send(t)}ht(t){return this.V(this.k.writeMessage(t))}send(t,...e){const[s,i]=this.nt(e),n=this.ht(this.lt(t,e,!0,i));return this.ct(s,n),n}invoke(t,...e){const[s,i]=this.nt(e),n=this.lt(t,e,!1,i);return new Promise(((t,e)=>{this.H[n.invocationId]=(s,i)=>{i?e(i):s&&(s.type===R.Completion?s.error?e(new Error(s.error)):t(s.result):e(new Error(`Unexpected message type: ${s.type}`)))};const i=this.ht(n).catch((t=>{e(t),delete this.H[n.invocationId]}));this.ct(s,i)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this.D[t]||(this.D[t]=[]),-1===this.D[t].indexOf(e)&&this.D[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const s=this.D[t];if(s)if(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),0===s.length&&delete this.D[t])}else delete this.D[t]}onclose(t){t&&this.R.push(t)}onreconnecting(t){t&&this.A.push(t)}onreconnected(t){t&&this.U.push(t)}I(t){if(this.G(),this.L||(t=this.ut(t),this.L=!0),t){const s=this.k.parseMessages(t,this.u);for(const t of s)switch(t.type){case R.Invocation:this.dt(t);break;case R.StreamItem:case R.Completion:{const s=this.H[t.invocationId];if(s){t.type===R.Completion&&delete this.H[t.invocationId];try{s(t)}catch(t){this.u.log(e.Error,`Stream callback threw error: ${P(t)}`)}}break}case R.Ping:break;case R.Close:{this.u.log(e.Information,"Close message received from server.");const s=t.error?new Error("Server returned an error on close: "+t.error):void 0;!0===t.allowReconnect?this.connection.stop(s):this.tt=this.et(s);break}default:this.u.log(e.Warning,`Invalid message type: ${t.type}.`)}}this.K()}ut(t){let s,i;try{[i,s]=this.T.parseHandshakeResponse(t)}catch(t){const s="Error parsing handshake response: "+t;this.u.log(e.Error,s);const i=new Error(s);throw this.J(i),i}if(s.error){const t="Server returned handshake error: "+s.error;this.u.log(e.Error,t);const i=new Error(t);throw this.J(i),i}return this.u.log(e.Debug,"Server handshake complete."),this.X(),i}Y(){this.connection.features.inherentKeepAlive||(this.C=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this.Z())}K(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this.ft=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this.wt))){let t=this.C-(new Date).getTime();t<0&&(t=0),this.wt=setTimeout((async()=>{if(this.M===A.Connected)try{await this.V(this.q)}catch{this.Z()}}),t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async dt(t){const s=t.target.toLowerCase(),i=this.D[s];if(!i)return this.u.log(e.Warning,`No client method with the name '${s}' found.`),void(t.invocationId&&(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),await this.ht(this.gt(t.invocationId,"Client didn't provide a result.",null))));const n=i.slice(),r=!!t.invocationId;let o,h,c;for(const i of n)try{const n=o;o=await i.apply(this,t.arguments),r&&o&&n&&(this.u.log(e.Error,`Multiple results provided for '${s}'. Sending error to server.`),c=this.gt(t.invocationId,"Client provided multiple results.",null)),h=void 0}catch(t){h=t,this.u.log(e.Error,`A callback for the method '${s}' threw error '${t}'.`)}c?await this.ht(c):r?(h?c=this.gt(t.invocationId,`${h}`,null):void 0!==o?c=this.gt(t.invocationId,null,o):(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),c=this.gt(t.invocationId,"Client didn't provide a result.",null)),await this.ht(c)):o&&this.u.log(e.Error,`Result given for '${s}' method but server is not expecting a result.`)}_(t){this.u.log(e.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this.M}.`),this.B=this.B||t||new r("The underlying connection was closed before the hub handshake could complete."),this.X&&this.X(),this.yt(t||new Error("Invocation canceled due to the underlying connection being closed.")),this.G(),this.Z(),this.M===A.Disconnecting?this.it(t):this.M===A.Connected&&this.P?this.bt(t):this.M===A.Connected&&this.it(t)}it(t){if(this.j){this.M=A.Disconnected,this.j=!1,g.isBrowser&&window.document.removeEventListener("freeze",this.S);try{this.R.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onclose callback called with error '${t}' threw error '${s}'.`)}}}async bt(t){const s=Date.now();let i=0,n=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this.vt(i++,0,n);if(null===r)return this.u.log(e.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this.it(t);if(this.M=A.Reconnecting,t?this.u.log(e.Information,`Connection reconnecting because of error '${t}'.`):this.u.log(e.Information,"Connection reconnecting."),0!==this.A.length){try{this.A.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onreconnecting callback called with error '${t}' threw error '${s}'.`)}if(this.M!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this.u.log(e.Information,`Reconnect attempt number ${i} will start in ${r} ms.`),await new Promise((t=>{this.st=setTimeout(t,r)})),this.st=void 0,this.M!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this.F(),this.M=A.Connected,this.u.log(e.Information,"HubConnection reconnected successfully."),0!==this.U.length)try{this.U.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this.u.log(e.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this.u.log(e.Information,`Reconnect attempt failed because of error '${t}'.`),this.M!==A.Reconnecting)return this.u.log(e.Debug,`Connection moved to the '${this.M}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this.M===A.Disconnecting&&this.it());n=t instanceof Error?t:new Error(t.toString()),r=this.vt(i++,Date.now()-s,n)}}this.u.log(e.Information,`Reconnect retries have been exhausted after ${Date.now()-s} ms and ${i} failed attempts. Connection disconnecting.`),this.it()}vt(t,s,i){try{return this.P.nextRetryDelayInMilliseconds({elapsedMilliseconds:s,previousRetryCount:t,retryReason:i})}catch(i){return this.u.log(e.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${s}) threw error '${i}'.`),null}}yt(t){const s=this.H;this.H={},Object.keys(s).forEach((i=>{const n=s[i];try{n(null,t)}catch(s){this.u.log(e.Error,`Stream 'error' callback called with '${t}' threw error: ${P(s)}`)}}))}Z(){this.wt&&(clearTimeout(this.wt),this.wt=void 0)}G(){this.ft&&clearTimeout(this.ft)}lt(t,e,s,i){if(s)return 0!==i.length?{arguments:e,streamIds:i,target:t,type:R.Invocation}:{arguments:e,target:t,type:R.Invocation};{const s=this.N;return this.N++,0!==i.length?{arguments:e,invocationId:s.toString(),streamIds:i,target:t,type:R.Invocation}:{arguments:e,invocationId:s.toString(),target:t,type:R.Invocation}}}ct(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const s in t)t[s].subscribe({complete:()=>{e=e.then((()=>this.ht(this.gt(s))))},error:t=>{let i;i=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this.ht(this.gt(s,i))))},next:t=>{e=e.then((()=>this.ht(this.$t(s,t))))}})}}nt(t){const e=[],s=[];for(let i=0;i0)&&(e=!1,this.Pt=await this.kt()),this.Tt(t);const s=await this.St.send(t);return e&&401===s.statusCode&&this.kt?(this.Pt=await this.kt(),this.Tt(t),await this.St.send(t)):s}Tt(t){t.headers||(t.headers={}),this.Pt?t.headers[j.Authorization]=`Bearer ${this.Pt}`:this.kt&&t.headers[j.Authorization]&&delete t.headers[j.Authorization]}getCookieString(t){return this.St.getCookieString(t)}}var W,O;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(W||(W={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(O||(O={}));class F{constructor(){this.It=!1,this.onabort=null}abort(){this.It||(this.It=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this.It}}class B{constructor(t,e,s){this.$=t,this.u=e,this._t=new F,this.Ht=s,this.Dt=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._t.aborted}async connect(t,s){if(w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.xt=t,this.u.log(e.Trace,"(LongPolling transport) Connecting."),s===O.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=E(),o={[n]:r,...this.Ht.headers},h={abortSignal:this._t.signal,headers:o,timeout:1e5,withCredentials:this.Ht.withCredentials};s===O.Binary&&(h.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${c}.`);const a=await this.$.get(c,h);200!==a.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this.Rt=new i(a.statusText||"",a.statusCode),this.Dt=!1):this.Dt=!0,this.At=this.Ut(this.xt,h)}async Ut(t,s){try{for(;this.Dt;)try{const n=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this.$.get(n,s);204===r.statusCode?(this.u.log(e.Information,"(LongPolling transport) Poll terminated by server."),this.Dt=!1):200!==r.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this.Rt=new i(r.statusText||"",r.statusCode),this.Dt=!1):r.content?(this.u.log(e.Trace,`(LongPolling transport) data received. ${m(r.content,this.Ht.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this.Dt?t instanceof n?this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this.Rt=t,this.Dt=!1):this.u.log(e.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this.u.log(e.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this.Nt()}}async send(t){return this.Dt?b(this.u,"LongPolling",this.$,this.xt,t,this.Ht):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this.u.log(e.Trace,"(LongPolling transport) Stopping polling."),this.Dt=!1,this._t.abort();try{await this.At,this.u.log(e.Trace,`(LongPolling transport) sending DELETE request to ${this.xt}.`);const t={},[s,i]=E();t[s]=i;const n={headers:{...t,...this.Ht.headers},timeout:this.Ht.timeout,withCredentials:this.Ht.withCredentials};await this.$.delete(this.xt,n),this.u.log(e.Trace,"(LongPolling transport) DELETE request sent.")}finally{this.u.log(e.Trace,"(LongPolling transport) Stop finished."),this.Nt()}}Nt(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this.Rt&&(t+=" Error: "+this.Rt),this.u.log(e.Trace,t),this.onclose(this.Rt)}}}class X{constructor(t,e,s,i){this.$=t,this.Pt=e,this.u=s,this.Ht=i,this.onreceive=null,this.onclose=null}async connect(t,s){return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.u.log(e.Trace,"(SSE transport) Connecting."),this.xt=t,this.Pt&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this.Pt)}`),new Promise(((i,n)=>{let r,o=!1;if(s===O.Text){if(g.isBrowser||g.isWebWorker)r=new this.Ht.EventSource(t,{withCredentials:this.Ht.withCredentials});else{const e=this.$.getCookieString(t),s={};s.Cookie=e;const[i,n]=E();s[i]=n,r=new this.Ht.EventSource(t,{withCredentials:this.Ht.withCredentials,headers:{...s,...this.Ht.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this.u.log(e.Trace,`(SSE transport) data received. ${m(t.data,this.Ht.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this.Lt(t)}},r.onerror=t=>{o?this.Lt():n(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this.u.log(e.Information,`SSE connected to ${this.xt}`),this.Mt=r,o=!0,i()}}catch(t){return void n(t)}}else n(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this.Mt?b(this.u,"SSE",this.$,this.xt,t,this.Ht):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this.Lt(),Promise.resolve()}Lt(t){this.Mt&&(this.Mt.close(),this.Mt=void 0,this.onclose&&this.onclose(t))}}class J{constructor(t,e,s,i,n,r){this.u=s,this.kt=e,this.jt=i,this.qt=n,this.$=t,this.onreceive=null,this.onclose=null,this.Wt=r}async connect(t,s){let i;return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.u.log(e.Trace,"(WebSockets transport) Connecting."),this.kt&&(i=await this.kt()),new Promise(((n,r)=>{let o;t=t.replace(/^http/,"ws");const h=this.$.getCookieString(t);let c=!1;if(g.isNode||g.isReactNative){const e={},[s,n]=E();e[s]=n,i&&(e[j.Authorization]=`Bearer ${i}`),h&&(e[j.Cookie]=h),o=new this.qt(t,void 0,{headers:{...e,...this.Wt}})}else i&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);o||(o=new this.qt(t)),s===O.Binary&&(o.binaryType="arraybuffer"),o.onopen=s=>{this.u.log(e.Information,`WebSocket connected to ${t}.`),this.Ot=o,c=!0,n()},o.onerror=t=>{let s=null;s="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this.u.log(e.Information,`(WebSockets transport) ${s}.`)},o.onmessage=t=>{if(this.u.log(e.Trace,`(WebSockets transport) data received. ${m(t.data,this.jt)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this.Lt(t)}},o.onclose=t=>{if(c)this.Lt(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this.Ot&&this.Ot.readyState===this.qt.OPEN?(this.u.log(e.Trace,`(WebSockets transport) sending data. ${m(t,this.jt)}.`),this.Ot.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this.Ot&&this.Lt(void 0),Promise.resolve()}Lt(t){this.Ot&&(this.Ot.onclose=()=>{},this.Ot.onmessage=()=>{},this.Ot.onerror=()=>{},this.Ot.close(),this.Ot=void 0),this.u.log(e.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this.Ft(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}Ft(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class z{constructor(t,s={}){var i;if(this.Bt=()=>{},this.features={},this.Xt=1,w.isRequired(t,"url"),this.u=void 0===(i=s.logger)?new $(e.Information):null===i?p.instance:void 0!==i.log?i:new $(i),this.baseUrl=this.Jt(t),(s=s||{}).logMessageContent=void 0!==s.logMessageContent&&s.logMessageContent,"boolean"!=typeof s.withCredentials&&void 0!==s.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");s.withCredentials=void 0===s.withCredentials||s.withCredentials,s.timeout=void 0===s.timeout?1e5:s.timeout;let n=null,r=null;if(g.isNode){const t=require;n=t("ws"),r=t("eventsource")}g.isNode||"undefined"==typeof WebSocket||s.WebSocket?g.isNode&&!s.WebSocket&&n&&(s.WebSocket=n):s.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||s.EventSource?g.isNode&&!s.EventSource&&void 0!==r&&(s.EventSource=r):s.EventSource=EventSource,this.$=new q(s.httpClient||new H(this.u),s.accessTokenFactory),this.M="Disconnected",this.j=!1,this.Ht=s,this.onreceive=null,this.onclose=null}async start(t){if(t=t||O.Binary,w.isIn(t,O,"transferFormat"),this.u.log(e.Debug,`Starting connection with transfer format '${O[t]}'.`),"Disconnected"!==this.M)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this.M="Connecting",this.zt=this.F(t),await this.zt,"Disconnecting"===this.M){const t="Failed to start the HttpConnection before stop() was called.";return this.u.log(e.Error,t),await this.tt,Promise.reject(new r(t))}if("Connected"!==this.M){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this.u.log(e.Error,t),Promise.reject(new r(t))}this.j=!0}send(t){return"Connected"!==this.M?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this.Vt||(this.Vt=new V(this.transport)),this.Vt.send(t))}async stop(t){return"Disconnected"===this.M?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this.M?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.tt):(this.M="Disconnecting",this.tt=new Promise((t=>{this.Bt=t})),await this.et(t),void await this.tt)}async et(t){this.Gt=t;try{await this.zt}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this.u.log(e.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this.Kt()}this.transport=void 0}else this.u.log(e.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async F(t){let s=this.baseUrl;this.kt=this.Ht.accessTokenFactory,this.$.kt=this.kt;try{if(this.Ht.skipNegotiation){if(this.Ht.transport!==W.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this.Qt(W.WebSockets),await this.Yt(s,t)}else{let e=null,i=0;do{if(e=await this.Zt(s),"Disconnecting"===this.M||"Disconnected"===this.M)throw new r("The connection was stopped during negotiation.");if(e.error)throw new Error(e.error);if(e.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(e.url&&(s=e.url),e.accessToken){const t=e.accessToken;this.kt=()=>t,this.$.Pt=t,this.$.kt=void 0}i++}while(e.url&&i<100);if(100===i&&e.url)throw new Error("Negotiate redirection limit exceeded.");await this.te(s,this.Ht.transport,e,t)}this.transport instanceof B&&(this.features.inherentKeepAlive=!0),"Connecting"===this.M&&(this.u.log(e.Debug,"The HttpConnection connected successfully."),this.M="Connected")}catch(t){return this.u.log(e.Error,"Failed to start the connection: "+t),this.M="Disconnected",this.transport=void 0,this.Bt(),Promise.reject(t)}}async Zt(t){const s={},[n,r]=E();s[n]=r;const o=this.ee(t);this.u.log(e.Debug,`Sending negotiation request: ${o}.`);try{const t=await this.$.post(o,{content:"",headers:{...s,...this.Ht.headers},timeout:this.Ht.timeout,withCredentials:this.Ht.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const e=JSON.parse(t.content);return(!e.negotiateVersion||e.negotiateVersion<1)&&(e.connectionToken=e.connectionId),e}catch(t){let s="Failed to complete negotiation with the server: "+t;return t instanceof i&&404===t.statusCode&&(s+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this.u.log(e.Error,s),Promise.reject(new a(s))}}se(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async te(t,s,i,n){let o=this.se(t,i.connectionToken);if(this.ie(s))return this.u.log(e.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=s,await this.Yt(o,n),void(this.connectionId=i.connectionId);const h=[],a=i.availableTransports||[];let u=i;for(const i of a){const a=this.ne(i,s,n);if(a instanceof Error)h.push(`${i.transport} failed:`),h.push(a);else if(this.ie(a)){if(this.transport=a,!u){try{u=await this.Zt(t)}catch(t){return Promise.reject(t)}o=this.se(t,u.connectionToken)}try{return await this.Yt(o,n),void(this.connectionId=u.connectionId)}catch(t){if(this.u.log(e.Error,`Failed to start the transport '${i.transport}': ${t}`),u=void 0,h.push(new c(`${i.transport} failed: ${t}`,W[i.transport])),"Connecting"!==this.M){const t="Failed to select transport before stop() was called.";return this.u.log(e.Debug,t),Promise.reject(new r(t))}}}}return h.length>0?Promise.reject(new l(`Unable to connect to the server with any of the available transports. ${h.join(" ")}`,h)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}Qt(t){switch(t){case W.WebSockets:if(!this.Ht.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new J(this.$,this.kt,this.u,this.Ht.logMessageContent,this.Ht.WebSocket,this.Ht.headers||{});case W.ServerSentEvents:if(!this.Ht.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new X(this.$,this.$.Pt,this.u,this.Ht);case W.LongPolling:return new B(this.$,this.u,this.Ht);default:throw new Error(`Unknown transport: ${t}.`)}}Yt(t,e){return this.transport.onreceive=this.onreceive,this.transport.onclose=t=>this.Kt(t),this.transport.connect(t,e)}ne(t,s,i){const n=W[t.transport];if(null==n)return this.u.log(e.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||0!=(e&t)}(s,n))return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it was disabled by the client.`),new h(`'${W[n]}' is disabled by the client.`,n);if(!(t.transferFormats.map((t=>O[t])).indexOf(i)>=0))return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it does not support the requested transfer format '${O[i]}'.`),new Error(`'${W[n]}' does not support ${O[i]}.`);if(n===W.WebSockets&&!this.Ht.WebSocket||n===W.ServerSentEvents&&!this.Ht.EventSource)return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it is not supported in your environment.'`),new o(`'${W[n]}' is not supported in your environment.`,n);this.u.log(e.Debug,`Selecting transport '${W[n]}'.`);try{return this.Qt(n)}catch(t){return t}}ie(t){return t&&"object"==typeof t&&"connect"in t}Kt(t){if(this.u.log(e.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this.M}.`),this.transport=void 0,t=this.Gt||t,this.Gt=void 0,"Disconnected"!==this.M){if("Connecting"===this.M)throw this.u.log(e.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this.M&&this.Bt(),t?this.u.log(e.Error,`Connection disconnected with error '${t}'.`):this.u.log(e.Information,"Connection disconnected."),this.Vt&&(this.Vt.stop().catch((t=>{this.u.log(e.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this.Vt=void 0),this.connectionId=void 0,this.M="Disconnected",this.j){this.j=!1;try{this.onclose&&this.onclose(t)}catch(s){this.u.log(e.Error,`HttpConnection.onclose(${t}) threw error '${s}'.`)}}}else this.u.log(e.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}Jt(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!g.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const s=window.document.createElement("a");return s.href=t,this.u.log(e.Information,`Normalizing '${t}' to '${s.href}'.`),s.href}ee(t){const e=t.indexOf("?");let s=t.substring(0,-1===e?t.length:e);return"/"!==s[s.length-1]&&(s+="/"),s+="negotiate",s+=-1===e?"":t.substring(e),-1===s.indexOf("negotiateVersion")&&(s+=-1===e?"?":"&",s+="negotiateVersion="+this.Xt),s}}class V{constructor(t){this.re=t,this.oe=[],this.he=!0,this.ce=new G,this.ae=new G,this.le=this.ue()}send(t){return this.de(t),this.ae||(this.ae=new G),this.ae.promise}stop(){return this.he=!1,this.ce.resolve(),this.le}de(t){if(this.oe.length&&typeof this.oe[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this.oe} but was of type ${typeof t}`);this.oe.push(t),this.ce.resolve()}async ue(){for(;;){if(await this.ce.promise,!this.he){this.ae&&this.ae.reject("Connection stopped.");break}this.ce=new G;const t=this.ae;this.ae=void 0;const e="string"==typeof this.oe[0]?this.oe.join(""):V.pe(this.oe);this.oe.length=0;try{await this.re.send(e),t.resolve()}catch(e){t.reject(e)}}}static pe(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),s=new Uint8Array(e);let i=0;for(const e of t)s.set(new Uint8Array(e),i),i+=e.byteLength;return s.buffer}}class G{constructor(){this.promise=new Promise(((t,e)=>[this.fe,this.we]=[t,e]))}resolve(){this.fe()}reject(t){this.we(t)}}class K{constructor(){this.name="json",this.version=1,this.transferFormat=O.Text}parseMessages(t,s){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===s&&(s=p.instance);const i=D.parse(t),n=[];for(const t of i){const i=JSON.parse(t);if("number"!=typeof i.type)throw new Error("Invalid payload.");switch(i.type){case R.Invocation:this.ge(i);break;case R.StreamItem:this.me(i);break;case R.Completion:this.ye(i);break;case R.Ping:case R.Close:break;default:s.log(e.Information,"Unknown message type '"+i.type+"' ignored.");continue}n.push(i)}return n}writeMessage(t){return D.write(JSON.stringify(t))}ge(t){this.be(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this.be(t.invocationId,"Invalid payload for Invocation message.")}me(t){if(this.be(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}ye(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this.be(t.error,"Invalid payload for Completion message."),this.be(t.invocationId,"Invalid payload for Completion message.")}be(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const Q={trace:e.Trace,debug:e.Debug,info:e.Information,information:e.Information,warn:e.Warning,warning:e.Warning,error:e.Error,critical:e.Critical,none:e.None};class Y{configureLogging(t){if(w.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=Q[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new $(e)}else this.logger=new $(t);return this}withUrl(t,e){return w.isRequired(t,"url"),w.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return w.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new M(t):this.reconnectPolicy=t:this.reconnectPolicy=new M,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new z(this.url,t);return N.create(e,this.logger||p.instance,this.protocol||new K,this.reconnectPolicy)}}return Uint8Array.prototype.indexOf||Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:!0}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:function(t,e){return new Uint8Array(Array.prototype.slice.call(this,t,e))},writable:!0}),Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:!0}),s})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.signalR=e():t.signalR=e(); //# sourceMappingURL=signalr.min.js.map \ No newline at end of file