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B,sBAAsB/E,IAAwB,EAEnD1f,KAAK8R,EAA+BxP,aAAO,EAAPA,EAASkM,WAEtCxO,IACX,CAMOolB,QAGH,MAAMX,EAAwBzkB,KAAKykB,uBAAyB,CAAC,EAS7D,QANqC5a,IAAjC4a,EAAsBvf,SAEtBuf,EAAsBvf,OAASlF,KAAKkF,SAInClF,KAAKqC,IACN,MAAM,IAAItB,MAAM,4FAEpB,MAAMwN,EAAa,IAAIyP,EAAehe,KAAKqC,IAAKoiB,GAEhD,OAAOnT,EAAc+T,OACjB9W,EACAvO,KAAKkF,QAAUtC,EAAWI,SAC1BhD,KAAKsO,UAAY,IAAI2U,EACrBjjB,KAAKuR,gBACLvR,KAAKglB,GACLhlB,KAAKklB,GACLllB,KAAK8R,EACb,E,OC3PCvN,WAAWjE,UAAU+F,SACtB3G,OAAOC,eAAe4E,WAAWjE,UAAW,UAAW,CACnDM,MAAOyM,MAAM/M,UAAU+F,QACvBif,UAAU,IAGb/gB,WAAWjE,UAAUgN,OACtB5N,OAAOC,eAAe4E,WAAWjE,UAAW,QAAS,CAGjDM,MAAO,SAASwS,EAAgBmS,GAAgB,OAAO,IAAIhhB,WAAW8I,MAAM/M,UAAUgN,MAAM9M,KAAKR,KAAMoT,EAAOmS,GAAO,EACrHD,UAAU,IAGb/gB,WAAWjE,UAAUmE,SACtB/E,OAAOC,eAAe4E,WAAWjE,UAAW,UAAW,CACnDM,MAAOyM,MAAM/M,UAAUmE,QACvB6gB,UAAU,I,M/BxBK,iBAAZhmB,SAA0C,iBAAXkmB,OACxCA,OAAOlmB,QAAUH,IACQ,mBAAXsmB,QAAyBA,OAAOC,IAC9CD,OAAO,GAAItmB,GACe,iBAAZG,QACdA,QAAiB,QAAIH,IAErBD,EAAc,QAAIC","sources":["webpack://signalR/webpack/universalModuleDefinition","webpack://signalR/webpack/bootstrap","webpack://signalR/webpack/runtime/define property getters","webpack://signalR/webpack/runtime/global","webpack://signalR/webpack/runtime/hasOwnProperty shorthand","webpack://signalR/webpack/runtime/make namespace object","webpack://signalR/src/ILogger.ts","webpack://signalR/src/Errors.ts","webpack://signalR/src/HttpClient.ts","webpack://signalR/src/Loggers.ts","webpack://signalR/src/Utils.ts","webpack://signalR/src/FetchHttpClient.ts","webpack://signalR/src/XhrHttpClient.ts","webpack://signalR/src/DefaultHttpClient.ts","webpack://signalR/src/TextMessageFormat.ts","webpack://signalR/src/HandshakeProtocol.ts","webpack://signalR/src/IHubProtocol.ts","webpack://signalR/src/HubConnection.ts","webpack://signalR/src/Subject.ts","webpack://signalR/src/MessageBuffer.ts","webpack://signalR/src/DefaultReconnectPolicy.ts","webpack://signalR/src/HeaderNames.ts","webpack://signalR/src/AccessTokenHttpClient.ts","webpack://signalR/src/ITransport.ts","webpack://signalR/src/AbortController.ts","webpack://signalR/src/LongPollingTransport.ts","webpack://signalR/src/ServerSentEventsTransport.ts","webpack://signalR/src/WebSocketTransport.ts","webpack://signalR/src/HttpConnection.ts","webpack://signalR/src/JsonHubProtocol.ts","webpack://signalR/src/HubConnectionBuilder.ts","webpack://signalR/src/browser-index.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"signalR\"] = factory();\n\telse\n\t\troot[\"signalR\"] = factory();\n})(self, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\n// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.\r\n/** Indicates the severity of a log message.\r\n *\r\n * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.\r\n */\r\nexport enum LogLevel {\r\n /** Log level for very low severity diagnostic messages. */\r\n Trace = 0,\r\n /** Log level for low severity diagnostic messages. */\r\n Debug = 1,\r\n /** Log level for informational diagnostic messages. */\r\n Information = 2,\r\n /** Log level for diagnostic messages that indicate a non-fatal problem. */\r\n Warning = 3,\r\n /** Log level for diagnostic messages that indicate a failure in the current operation. */\r\n Error = 4,\r\n /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */\r\n Critical = 5,\r\n /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */\r\n None = 6,\r\n}\r\n\r\n/** An abstraction that provides a sink for diagnostic messages. */\r\nexport interface ILogger {\r\n /** Called by the framework to emit a diagnostic message.\r\n *\r\n * @param {LogLevel} logLevel The severity level of the message.\r\n * @param {string} message The message.\r\n */\r\n log(logLevel: LogLevel, message: string): void;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { HttpTransportType } from \"./ITransport\";\r\n\r\n/** Error thrown when an HTTP request fails. */\r\nexport class HttpError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** The HTTP status code represented by this error. */\r\n public statusCode: number;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n * @param {number} statusCode The HTTP status code represented by this error.\r\n */\r\n constructor(errorMessage: string, statusCode: number) {\r\n const trueProto = new.target.prototype;\r\n super(`${errorMessage}: Status code '${statusCode}'`);\r\n this.statusCode = statusCode;\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when a timeout elapses. */\r\nexport class TimeoutError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"A timeout occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when an action is aborted. */\r\nexport class AbortError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"An abort occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when the selected transport is unsupported by the browser. */\r\n/** @private */\r\nexport class UnsupportedTransportError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** The {@link @microsoft/signalr.HttpTransportType} this error occurred on. */\r\n public transport: HttpTransportType;\r\n\r\n /** The type name of this error. */\r\n public errorType: string;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.\r\n */\r\n constructor(message: string, transport: HttpTransportType) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'UnsupportedTransportError';\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when the selected transport is disabled by the browser. */\r\n/** @private */\r\nexport class DisabledTransportError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** The {@link @microsoft/signalr.HttpTransportType} this error occurred on. */\r\n public transport: HttpTransportType;\r\n\r\n /** The type name of this error. */\r\n public errorType: string;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.\r\n */\r\n constructor(message: string, transport: HttpTransportType) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'DisabledTransportError';\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when the selected transport cannot be started. */\r\n/** @private */\r\nexport class FailedToStartTransportError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** The {@link @microsoft/signalr.HttpTransportType} this error occurred on. */\r\n public transport: HttpTransportType;\r\n\r\n /** The type name of this error. */\r\n public errorType: string;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.\r\n */\r\n constructor(message: string, transport: HttpTransportType) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'FailedToStartTransportError';\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when the negotiation with the server failed to complete. */\r\n/** @private */\r\nexport class FailedToNegotiateWithServerError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** The type name of this error. */\r\n public errorType: string;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n */\r\n constructor(message: string) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.errorType = 'FailedToNegotiateWithServerError';\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when multiple errors have occurred. */\r\n/** @private */\r\nexport class AggregateErrors extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private __proto__: Error;\r\n\r\n /** The collection of errors this error is aggregating. */\r\n public innerErrors: Error[];\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {Error[]} innerErrors The collection of errors this error is aggregating.\r\n */\r\n constructor(message: string, innerErrors: Error[]) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n\r\n this.innerErrors = innerErrors;\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { AbortSignal } from \"./AbortController\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\n\r\n/** Represents an HTTP request. */\r\nexport interface HttpRequest {\r\n /** The HTTP method to use for the request. */\r\n method?: string;\r\n\r\n /** The URL for the request. */\r\n url?: string;\r\n\r\n /** The body content for the request. May be a string or an ArrayBuffer (for binary data). */\r\n content?: string | ArrayBuffer;\r\n\r\n /** An object describing headers to apply to the request. */\r\n headers?: MessageHeaders;\r\n\r\n /** The XMLHttpRequestResponseType to apply to the request. */\r\n responseType?: XMLHttpRequestResponseType;\r\n\r\n /** An AbortSignal that can be monitored for cancellation. */\r\n abortSignal?: AbortSignal;\r\n\r\n /** The time to wait for the request to complete before throwing a TimeoutError. Measured in milliseconds. */\r\n timeout?: number;\r\n\r\n /** This controls whether credentials such as cookies are sent in cross-site requests. */\r\n withCredentials?: boolean;\r\n}\r\n\r\n/** Represents an HTTP response. */\r\nexport class HttpResponse {\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n */\r\n constructor(statusCode: number);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code and message.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n */\r\n constructor(statusCode: number, statusText: string);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and string content.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n * @param {string} content The content of the response.\r\n */\r\n constructor(statusCode: number, statusText: string, content: string);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and binary content.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n * @param {ArrayBuffer} content The content of the response.\r\n */\r\n constructor(statusCode: number, statusText: string, content: ArrayBuffer);\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and binary content.\r\n *\r\n * @param {number} statusCode The status code of the response.\r\n * @param {string} statusText The status message of the response.\r\n * @param {string | ArrayBuffer} content The content of the response.\r\n */\r\n constructor(statusCode: number, statusText: string, content: string | ArrayBuffer);\r\n constructor(\r\n public readonly statusCode: number,\r\n public readonly statusText?: string,\r\n public readonly content?: string | ArrayBuffer) {\r\n }\r\n}\r\n\r\n/** Abstraction over an HTTP client.\r\n *\r\n * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.\r\n */\r\nexport abstract class HttpClient {\r\n /** Issues an HTTP GET request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public get(url: string): Promise;\r\n\r\n /** Issues an HTTP GET request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public get(url: string, options: HttpRequest): Promise;\r\n public get(url: string, options?: HttpRequest): Promise {\r\n return this.send({\r\n ...options,\r\n method: \"GET\",\r\n url,\r\n });\r\n }\r\n\r\n /** Issues an HTTP POST request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public post(url: string): Promise;\r\n\r\n /** Issues an HTTP POST request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public post(url: string, options: HttpRequest): Promise;\r\n public post(url: string, options?: HttpRequest): Promise {\r\n return this.send({\r\n ...options,\r\n method: \"POST\",\r\n url,\r\n });\r\n }\r\n\r\n /** Issues an HTTP DELETE request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public delete(url: string): Promise;\r\n\r\n /** Issues an HTTP DELETE request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {string} url The URL for the request.\r\n * @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.\r\n * @returns {Promise} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public delete(url: string, options: HttpRequest): Promise;\r\n public delete(url: string, options?: HttpRequest): Promise {\r\n return this.send({\r\n ...options,\r\n method: \"DELETE\",\r\n url,\r\n });\r\n }\r\n\r\n /** Issues an HTTP request to the specified URL, returning a {@link Promise} that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.\r\n *\r\n * @param {HttpRequest} request An {@link @microsoft/signalr.HttpRequest} describing the request to send.\r\n * @returns {Promise} A Promise that resolves with an HttpResponse describing the response, or rejects with an Error indicating a failure.\r\n */\r\n public abstract send(request: HttpRequest): Promise;\r\n\r\n /** Gets all cookies that apply to the specified URL.\r\n *\r\n * @param url The URL that the cookies are valid for.\r\n * @returns {string} A string containing all the key-value cookie pairs for the specified URL.\r\n */\r\n // @ts-ignore\r\n public getCookieString(url: string): string {\r\n return \"\";\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\n\r\n/** A logger that does nothing when log messages are sent to it. */\r\nexport class NullLogger implements ILogger {\r\n /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */\r\n public static instance: ILogger = new NullLogger();\r\n\r\n private constructor() {}\r\n\r\n /** @inheritDoc */\r\n // eslint-disable-next-line\r\n public log(_logLevel: LogLevel, _message: string): void {\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { IStreamSubscriber, ISubscription } from \"./Stream\";\r\nimport { Subject } from \"./Subject\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\n\r\n// Version token that will be replaced by the prepack command\r\n/** The version of the SignalR client. */\r\n\r\nexport const VERSION: string = \"0.0.0-DEV_BUILD\";\r\n/** @private */\r\nexport class Arg {\r\n public static isRequired(val: any, name: string): void {\r\n if (val === null || val === undefined) {\r\n throw new Error(`The '${name}' argument is required.`);\r\n }\r\n }\r\n public static isNotEmpty(val: string, name: string): void {\r\n if (!val || val.match(/^\\s*$/)) {\r\n throw new Error(`The '${name}' argument should not be empty.`);\r\n }\r\n }\r\n\r\n public static isIn(val: any, values: any, name: string): void {\r\n // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.\r\n if (!(val in values)) {\r\n throw new Error(`Unknown ${name} value: ${val}.`);\r\n }\r\n }\r\n}\r\n\r\n/** @private */\r\nexport class Platform {\r\n // react-native has a window but no document so we should check both\r\n public static get isBrowser(): boolean {\r\n return !Platform.isNode && typeof window === \"object\" && typeof window.document === \"object\";\r\n }\r\n\r\n // WebWorkers don't have a window object so the isBrowser check would fail\r\n public static get isWebWorker(): boolean {\r\n return !Platform.isNode && typeof self === \"object\" && \"importScripts\" in self;\r\n }\r\n\r\n // react-native has a window but no document\r\n static get isReactNative(): boolean {\r\n return !Platform.isNode && typeof window === \"object\" && typeof window.document === \"undefined\";\r\n }\r\n\r\n // Node apps shouldn't have a window object, but WebWorkers don't either\r\n // so we need to check for both WebWorker and window\r\n public static get isNode(): boolean {\r\n return typeof process !== \"undefined\" && process.release && process.release.name === \"node\";\r\n }\r\n}\r\n\r\n/** @private */\r\nexport function getDataDetail(data: any, includeContent: boolean): string {\r\n let detail = \"\";\r\n if (isArrayBuffer(data)) {\r\n detail = `Binary data of length ${data.byteLength}`;\r\n if (includeContent) {\r\n detail += `. Content: '${formatArrayBuffer(data)}'`;\r\n }\r\n } else if (typeof data === \"string\") {\r\n detail = `String data of length ${data.length}`;\r\n if (includeContent) {\r\n detail += `. Content: '${data}'`;\r\n }\r\n }\r\n return detail;\r\n}\r\n\r\n/** @private */\r\nexport function formatArrayBuffer(data: ArrayBuffer): string {\r\n const view = new Uint8Array(data);\r\n\r\n // Uint8Array.map only supports returning another Uint8Array?\r\n let str = \"\";\r\n view.forEach((num) => {\r\n const pad = num < 16 ? \"0\" : \"\";\r\n str += `0x${pad}${num.toString(16)} `;\r\n });\r\n\r\n // Trim of trailing space.\r\n return str.substr(0, str.length - 1);\r\n}\r\n\r\n// Also in signalr-protocol-msgpack/Utils.ts\r\n/** @private */\r\nexport function isArrayBuffer(val: any): val is ArrayBuffer {\r\n return val && typeof ArrayBuffer !== \"undefined\" &&\r\n (val instanceof ArrayBuffer ||\r\n // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof\r\n (val.constructor && val.constructor.name === \"ArrayBuffer\"));\r\n}\r\n\r\n/** @private */\r\nexport async function sendMessage(logger: ILogger, transportName: string, httpClient: HttpClient, url: string,\r\n content: string | ArrayBuffer, options: IHttpConnectionOptions): Promise {\r\n const headers: {[k: string]: string} = {};\r\n\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent!)}.`);\r\n\r\n const responseType = isArrayBuffer(content) ? \"arraybuffer\" : \"text\";\r\n const response = await httpClient.post(url, {\r\n content,\r\n headers: { ...headers, ...options.headers},\r\n responseType,\r\n timeout: options.timeout,\r\n withCredentials: options.withCredentials,\r\n });\r\n\r\n logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);\r\n}\r\n\r\n/** @private */\r\nexport function createLogger(logger?: ILogger | LogLevel): ILogger {\r\n if (logger === undefined) {\r\n return new ConsoleLogger(LogLevel.Information);\r\n }\r\n\r\n if (logger === null) {\r\n return NullLogger.instance;\r\n }\r\n\r\n if ((logger as ILogger).log !== undefined) {\r\n return logger as ILogger;\r\n }\r\n\r\n return new ConsoleLogger(logger as LogLevel);\r\n}\r\n\r\n/** @private */\r\nexport class SubjectSubscription implements ISubscription {\r\n private _subject: Subject;\r\n private _observer: IStreamSubscriber;\r\n\r\n constructor(subject: Subject, observer: IStreamSubscriber) {\r\n this._subject = subject;\r\n this._observer = observer;\r\n }\r\n\r\n public dispose(): void {\r\n const index: number = this._subject.observers.indexOf(this._observer);\r\n if (index > -1) {\r\n this._subject.observers.splice(index, 1);\r\n }\r\n\r\n if (this._subject.observers.length === 0 && this._subject.cancelCallback) {\r\n this._subject.cancelCallback().catch((_) => { });\r\n }\r\n }\r\n}\r\n\r\n/** @private */\r\nexport class ConsoleLogger implements ILogger {\r\n private readonly _minLevel: LogLevel;\r\n\r\n // Public for testing purposes.\r\n public out: {\r\n error(message: any): void,\r\n warn(message: any): void,\r\n info(message: any): void,\r\n log(message: any): void,\r\n };\r\n\r\n constructor(minimumLogLevel: LogLevel) {\r\n this._minLevel = minimumLogLevel;\r\n this.out = console;\r\n }\r\n\r\n public log(logLevel: LogLevel, message: string): void {\r\n if (logLevel >= this._minLevel) {\r\n const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`;\r\n switch (logLevel) {\r\n case LogLevel.Critical:\r\n case LogLevel.Error:\r\n this.out.error(msg);\r\n break;\r\n case LogLevel.Warning:\r\n this.out.warn(msg);\r\n break;\r\n case LogLevel.Information:\r\n this.out.info(msg);\r\n break;\r\n default:\r\n // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug\r\n this.out.log(msg);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/** @private */\r\nexport function getUserAgentHeader(): [string, string] {\r\n let userAgentHeaderName = \"X-SignalR-User-Agent\";\r\n if (Platform.isNode) {\r\n userAgentHeaderName = \"User-Agent\";\r\n }\r\n return [ userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion()) ];\r\n}\r\n\r\n/** @private */\r\nexport function constructUserAgent(version: string, os: string, runtime: string, runtimeVersion: string | undefined): string {\r\n // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])\r\n let userAgent: string = \"Microsoft SignalR/\";\r\n\r\n const majorAndMinor = version.split(\".\");\r\n userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;\r\n userAgent += ` (${version}; `;\r\n\r\n if (os && os !== \"\") {\r\n userAgent += `${os}; `;\r\n } else {\r\n userAgent += \"Unknown OS; \";\r\n }\r\n\r\n userAgent += `${runtime}`;\r\n\r\n if (runtimeVersion) {\r\n userAgent += `; ${runtimeVersion}`;\r\n } else {\r\n userAgent += \"; Unknown Runtime Version\";\r\n }\r\n\r\n userAgent += \")\";\r\n return userAgent;\r\n}\r\n\r\n// eslint-disable-next-line spaced-comment\r\n/*#__PURE__*/ function getOsName(): string {\r\n if (Platform.isNode) {\r\n switch (process.platform) {\r\n case \"win32\":\r\n return \"Windows NT\";\r\n case \"darwin\":\r\n return \"macOS\";\r\n case \"linux\":\r\n return \"Linux\";\r\n default:\r\n return process.platform;\r\n }\r\n } else {\r\n return \"\";\r\n }\r\n}\r\n\r\n// eslint-disable-next-line spaced-comment\r\n/*#__PURE__*/ function getRuntimeVersion(): string | undefined {\r\n if (Platform.isNode) {\r\n return process.versions.node;\r\n }\r\n return undefined;\r\n}\r\n\r\nfunction getRuntime(): string {\r\n if (Platform.isNode) {\r\n return \"NodeJS\";\r\n } else {\r\n return \"Browser\";\r\n }\r\n}\r\n\r\n/** @private */\r\nexport function getErrorString(e: any): string {\r\n if (e.stack) {\r\n return e.stack;\r\n } else if (e.message) {\r\n return e.message;\r\n }\r\n return `${e}`;\r\n}\r\n\r\n/** @private */\r\nexport function getGlobalThis(): unknown {\r\n // globalThis is semi-new and not available in Node until v12\r\n if (typeof globalThis !== \"undefined\") {\r\n return globalThis;\r\n }\r\n if (typeof self !== \"undefined\") {\r\n return self;\r\n }\r\n if (typeof window !== \"undefined\") {\r\n return window;\r\n }\r\n if (typeof global !== \"undefined\") {\r\n return global;\r\n }\r\n throw new Error(\"could not find global\");\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\n// @ts-ignore: This will be removed from built files and is here to make the types available during dev work\r\nimport { CookieJar } from \"@types/tough-cookie\";\r\n\r\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { Platform, getGlobalThis, isArrayBuffer } from \"./Utils\";\r\n\r\nexport class FetchHttpClient extends HttpClient {\r\n private readonly _abortControllerType: { prototype: AbortController, new(): AbortController };\r\n private readonly _fetchType: (input: RequestInfo, init?: RequestInit) => Promise;\r\n private readonly _jar?: CookieJar;\r\n\r\n private readonly _logger: ILogger;\r\n\r\n public constructor(logger: ILogger) {\r\n super();\r\n this._logger = logger;\r\n\r\n // Node added a fetch implementation to the global scope starting in v18.\r\n // We need to add a cookie jar in node to be able to share cookies with WebSocket\r\n if (typeof fetch === \"undefined\" || Platform.isNode) {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n\r\n // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests\r\n this._jar = new (requireFunc(\"tough-cookie\")).CookieJar();\r\n\r\n if (typeof fetch === \"undefined\") {\r\n this._fetchType = requireFunc(\"node-fetch\");\r\n } else {\r\n // Use fetch from Node if available\r\n this._fetchType = fetch;\r\n }\r\n\r\n // node-fetch doesn't have a nice API for getting and setting cookies\r\n // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one\r\n this._fetchType = requireFunc(\"fetch-cookie\")(this._fetchType, this._jar);\r\n } else {\r\n this._fetchType = fetch.bind(getGlobalThis());\r\n }\r\n if (typeof AbortController === \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n\r\n // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide\r\n this._abortControllerType = requireFunc(\"abort-controller\");\r\n } else {\r\n this._abortControllerType = AbortController;\r\n }\r\n }\r\n\r\n /** @inheritDoc */\r\n public async send(request: HttpRequest): Promise {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n throw new AbortError();\r\n }\r\n\r\n if (!request.method) {\r\n throw new Error(\"No method defined.\");\r\n }\r\n if (!request.url) {\r\n throw new Error(\"No url defined.\");\r\n }\r\n\r\n const abortController = new this._abortControllerType();\r\n\r\n let error: any;\r\n // Hook our abortSignal into the abort controller\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n abortController.abort();\r\n error = new AbortError();\r\n };\r\n }\r\n\r\n // If a timeout has been passed in, setup a timeout to call abort\r\n // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout\r\n let timeoutId: any = null;\r\n if (request.timeout) {\r\n const msTimeout = request.timeout!;\r\n timeoutId = setTimeout(() => {\r\n abortController.abort();\r\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n error = new TimeoutError();\r\n }, msTimeout);\r\n }\r\n\r\n if (request.content === \"\") {\r\n request.content = undefined;\r\n }\r\n if (request.content) {\r\n // Explicitly setting the Content-Type header for React Native on Android platform.\r\n request.headers = request.headers || {};\r\n if (isArrayBuffer(request.content)) {\r\n request.headers[\"Content-Type\"] = \"application/octet-stream\";\r\n } else {\r\n request.headers[\"Content-Type\"] = \"text/plain;charset=UTF-8\";\r\n }\r\n }\r\n\r\n let response: Response;\r\n try {\r\n response = await this._fetchType(request.url!, {\r\n body: request.content,\r\n cache: \"no-cache\",\r\n credentials: request.withCredentials === true ? \"include\" : \"same-origin\",\r\n headers: {\r\n \"X-Requested-With\": \"XMLHttpRequest\",\r\n ...request.headers,\r\n },\r\n method: request.method!,\r\n mode: \"cors\",\r\n redirect: \"follow\",\r\n signal: abortController.signal,\r\n });\r\n } catch (e) {\r\n if (error) {\r\n throw error;\r\n }\r\n this._logger.log(\r\n LogLevel.Warning,\r\n `Error from HTTP request. ${e}.`,\r\n );\r\n throw e;\r\n } finally {\r\n if (timeoutId) {\r\n clearTimeout(timeoutId);\r\n }\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n }\r\n\r\n if (!response.ok) {\r\n const errorMessage = await deserializeContent(response, \"text\") as string;\r\n throw new HttpError(errorMessage || response.statusText, response.status);\r\n }\r\n\r\n const content = deserializeContent(response, request.responseType);\r\n const payload = await content;\r\n\r\n return new HttpResponse(\r\n response.status,\r\n response.statusText,\r\n payload,\r\n );\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n let cookies: string = \"\";\r\n if (Platform.isNode && this._jar) {\r\n // @ts-ignore: unused variable\r\n this._jar.getCookies(url, (e, c) => cookies = c.join(\"; \"));\r\n }\r\n return cookies;\r\n }\r\n}\r\n\r\nfunction deserializeContent(response: Response, responseType?: XMLHttpRequestResponseType): Promise {\r\n let content;\r\n switch (responseType) {\r\n case \"arraybuffer\":\r\n content = response.arrayBuffer();\r\n break;\r\n case \"text\":\r\n content = response.text();\r\n break;\r\n case \"blob\":\r\n case \"document\":\r\n case \"json\":\r\n throw new Error(`${responseType} is not supported.`);\r\n default:\r\n content = response.text();\r\n break;\r\n }\r\n\r\n return content;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n\r\nexport class XhrHttpClient extends HttpClient {\r\n private readonly _logger: ILogger;\r\n\r\n public constructor(logger: ILogger) {\r\n super();\r\n this._logger = logger;\r\n }\r\n\r\n /** @inheritDoc */\r\n public send(request: HttpRequest): Promise {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n const xhr = new XMLHttpRequest();\r\n\r\n xhr.open(request.method!, request.url!, true);\r\n xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;\r\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\r\n if (request.content === \"\") {\r\n request.content = undefined;\r\n }\r\n if (request.content) {\r\n // Explicitly setting the Content-Type header for React Native on Android platform.\r\n if (isArrayBuffer(request.content)) {\r\n xhr.setRequestHeader(\"Content-Type\", \"application/octet-stream\");\r\n } else {\r\n xhr.setRequestHeader(\"Content-Type\", \"text/plain;charset=UTF-8\");\r\n }\r\n }\r\n\r\n const headers = request.headers;\r\n if (headers) {\r\n Object.keys(headers)\r\n .forEach((header) => {\r\n xhr.setRequestHeader(header, headers[header]);\r\n });\r\n }\r\n\r\n if (request.responseType) {\r\n xhr.responseType = request.responseType;\r\n }\r\n\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n xhr.abort();\r\n reject(new AbortError());\r\n };\r\n }\r\n\r\n if (request.timeout) {\r\n xhr.timeout = request.timeout;\r\n }\r\n\r\n xhr.onload = () => {\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));\r\n } else {\r\n reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));\r\n }\r\n };\r\n\r\n xhr.onerror = () => {\r\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);\r\n reject(new HttpError(xhr.statusText, xhr.status));\r\n };\r\n\r\n xhr.ontimeout = () => {\r\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n reject(new TimeoutError());\r\n };\r\n\r\n xhr.send(request.content);\r\n });\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { AbortError } from \"./Errors\";\r\nimport { FetchHttpClient } from \"./FetchHttpClient\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger } from \"./ILogger\";\r\nimport { Platform } from \"./Utils\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n\r\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\r\nexport class DefaultHttpClient extends HttpClient {\r\n private readonly _httpClient: HttpClient;\r\n\r\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\r\n public constructor(logger: ILogger) {\r\n super();\r\n\r\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\r\n this._httpClient = new FetchHttpClient(logger);\r\n } else if (typeof XMLHttpRequest !== \"undefined\") {\r\n this._httpClient = new XhrHttpClient(logger);\r\n } else {\r\n throw new Error(\"No usable HttpClient found.\");\r\n }\r\n }\r\n\r\n /** @inheritDoc */\r\n public send(request: HttpRequest): Promise {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n\r\n return this._httpClient.send(request);\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n return this._httpClient.getCookieString(url);\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\n// Not exported from index\r\n/** @private */\r\nexport class TextMessageFormat {\r\n public static RecordSeparatorCode = 0x1e;\r\n public static RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);\r\n\r\n public static write(output: string): string {\r\n return `${output}${TextMessageFormat.RecordSeparator}`;\r\n }\r\n\r\n public static parse(input: string): string[] {\r\n if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n const messages = input.split(TextMessageFormat.RecordSeparator);\r\n messages.pop();\r\n return messages;\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n\r\n/** @private */\r\nexport interface HandshakeRequestMessage {\r\n readonly protocol: string;\r\n readonly version: number;\r\n}\r\n\r\n/** @private */\r\nexport interface HandshakeResponseMessage {\r\n readonly error: string;\r\n readonly minorVersion: number;\r\n}\r\n\r\n/** @private */\r\nexport class HandshakeProtocol {\r\n // Handshake request is always JSON\r\n public writeHandshakeRequest(handshakeRequest: HandshakeRequestMessage): string {\r\n return TextMessageFormat.write(JSON.stringify(handshakeRequest));\r\n }\r\n\r\n public parseHandshakeResponse(data: any): [any, HandshakeResponseMessage] {\r\n let messageData: string;\r\n let remainingData: any;\r\n\r\n if (isArrayBuffer(data)) {\r\n // Format is binary but still need to read JSON text from handshake response\r\n const binaryData = new Uint8Array(data);\r\n const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));\r\n remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;\r\n } else {\r\n const textData: string = data;\r\n const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = textData.substring(0, responseLength);\r\n remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;\r\n }\r\n\r\n // At this point we should have just the single handshake message\r\n const messages = TextMessageFormat.parse(messageData);\r\n const response = JSON.parse(messages[0]);\r\n if (response.type) {\r\n throw new Error(\"Expected a handshake response from the server.\");\r\n }\r\n const responseMessage: HandshakeResponseMessage = response;\r\n\r\n // multiple messages could have arrived with handshake\r\n // return additional data to be parsed as usual, or null if all parsed\r\n return [remainingData, responseMessage];\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { ILogger } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\n\r\n/** Defines the type of a Hub Message. */\r\nexport enum MessageType {\r\n /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */\r\n Invocation = 1,\r\n /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */\r\n StreamItem = 2,\r\n /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */\r\n Completion = 3,\r\n /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */\r\n StreamInvocation = 4,\r\n /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */\r\n CancelInvocation = 5,\r\n /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */\r\n Ping = 6,\r\n /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */\r\n Close = 7,\r\n Ack = 8,\r\n Sequence = 9\r\n}\r\n\r\n/** Defines a dictionary of string keys and string values representing headers attached to a Hub message. */\r\nexport interface MessageHeaders {\r\n /** Gets or sets the header with the specified key. */\r\n [key: string]: string;\r\n}\r\n\r\n/** Union type of all known Hub messages. */\r\nexport type HubMessage =\r\n InvocationMessage |\r\n StreamInvocationMessage |\r\n StreamItemMessage |\r\n CompletionMessage |\r\n CancelInvocationMessage |\r\n PingMessage |\r\n CloseMessage |\r\n AckMessage |\r\n SequenceMessage;\r\n\r\n/** Defines properties common to all Hub messages. */\r\nexport interface HubMessageBase {\r\n /** A {@link @microsoft/signalr.MessageType} value indicating the type of this message. */\r\n readonly type: MessageType;\r\n}\r\n\r\n/** Defines properties common to all Hub messages relating to a specific invocation. */\r\nexport interface HubInvocationMessage extends HubMessageBase {\r\n /** A {@link @microsoft/signalr.MessageHeaders} dictionary containing headers attached to the message. */\r\n readonly headers?: MessageHeaders;\r\n /** The ID of the invocation relating to this message.\r\n *\r\n * This is expected to be present for {@link @microsoft/signalr.StreamInvocationMessage} and {@link @microsoft/signalr.CompletionMessage}. It may\r\n * be 'undefined' for an {@link @microsoft/signalr.InvocationMessage} if the sender does not expect a response.\r\n */\r\n readonly invocationId?: string;\r\n}\r\n\r\n/** A hub message representing a non-streaming invocation. */\r\nexport interface InvocationMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Invocation;\r\n /** The target method name. */\r\n readonly target: string;\r\n /** The target method arguments. */\r\n readonly arguments: any[];\r\n /** The target methods stream IDs. */\r\n readonly streamIds?: string[];\r\n}\r\n\r\n/** A hub message representing a streaming invocation. */\r\nexport interface StreamInvocationMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.StreamInvocation;\r\n\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n /** The target method name. */\r\n readonly target: string;\r\n /** The target method arguments. */\r\n readonly arguments: any[];\r\n /** The target methods stream IDs. */\r\n readonly streamIds?: string[];\r\n}\r\n\r\n/** A hub message representing a single item produced as part of a result stream. */\r\nexport interface StreamItemMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.StreamItem;\r\n\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n\r\n /** The item produced by the server. */\r\n readonly item?: any;\r\n}\r\n\r\n/** A hub message representing the result of an invocation. */\r\nexport interface CompletionMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Completion;\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n /** The error produced by the invocation, if any.\r\n *\r\n * Either {@link @microsoft/signalr.CompletionMessage.error} or {@link @microsoft/signalr.CompletionMessage.result} must be defined, but not both.\r\n */\r\n readonly error?: string;\r\n /** The result produced by the invocation, if any.\r\n *\r\n * Either {@link @microsoft/signalr.CompletionMessage.error} or {@link @microsoft/signalr.CompletionMessage.result} must be defined, but not both.\r\n */\r\n readonly result?: any;\r\n}\r\n\r\n/** A hub message indicating that the sender is still active. */\r\nexport interface PingMessage extends HubMessageBase {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Ping;\r\n}\r\n\r\n/** A hub message indicating that the sender is closing the connection.\r\n *\r\n * If {@link @microsoft/signalr.CloseMessage.error} is defined, the sender is closing the connection due to an error.\r\n */\r\nexport interface CloseMessage extends HubMessageBase {\r\n /** @inheritDoc */\r\n readonly type: MessageType.Close;\r\n /** The error that triggered the close, if any.\r\n *\r\n * If this property is undefined, the connection was closed normally and without error.\r\n */\r\n readonly error?: string;\r\n\r\n /** If true, clients with automatic reconnects enabled should attempt to reconnect after receiving the CloseMessage. Otherwise, they should not. */\r\n readonly allowReconnect?: boolean;\r\n}\r\n\r\n/** A hub message sent to request that a streaming invocation be canceled. */\r\nexport interface CancelInvocationMessage extends HubInvocationMessage {\r\n /** @inheritDoc */\r\n readonly type: MessageType.CancelInvocation;\r\n /** The invocation ID. */\r\n readonly invocationId: string;\r\n}\r\n\r\nexport interface AckMessage extends HubMessageBase\r\n{\r\n readonly type: MessageType.Ack;\r\n\r\n readonly sequenceId: number;\r\n}\r\n\r\nexport interface SequenceMessage extends HubMessageBase\r\n{\r\n readonly type: MessageType.Sequence;\r\n\r\n readonly sequenceId: number;\r\n}\r\n\r\n/** A protocol abstraction for communicating with SignalR Hubs. */\r\nexport interface IHubProtocol {\r\n /** The name of the protocol. This is used by SignalR to resolve the protocol between the client and server. */\r\n readonly name: string;\r\n /** The version of the protocol. */\r\n readonly version: number;\r\n /** The {@link @microsoft/signalr.TransferFormat} of the protocol. */\r\n readonly transferFormat: TransferFormat;\r\n\r\n /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * If {@link @microsoft/signalr.IHubProtocol.transferFormat} is 'Text', the `input` parameter must be a string, otherwise it must be an ArrayBuffer.\r\n *\r\n * @param {string | ArrayBuffer} input A string or ArrayBuffer containing the serialized representation.\r\n * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.\r\n */\r\n parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[];\r\n\r\n /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string or ArrayBuffer and returns it.\r\n *\r\n * If {@link @microsoft/signalr.IHubProtocol.transferFormat} is 'Text', the result of this method will be a string, otherwise it will be an ArrayBuffer.\r\n *\r\n * @param {HubMessage} message The message to write.\r\n * @returns {string | ArrayBuffer} A string or ArrayBuffer containing the serialized representation of the message.\r\n */\r\n writeMessage(message: HubMessage): string | ArrayBuffer;\r\n}","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { HandshakeProtocol, HandshakeRequestMessage, HandshakeResponseMessage } from \"./HandshakeProtocol\";\r\nimport { IConnection } from \"./IConnection\";\r\nimport { AbortError } from \"./Errors\";\r\nimport { CancelInvocationMessage, CloseMessage, CompletionMessage, IHubProtocol, InvocationMessage, MessageType, StreamInvocationMessage, StreamItemMessage } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { IRetryPolicy } from \"./IRetryPolicy\";\r\nimport { IStreamResult } from \"./Stream\";\r\nimport { Subject } from \"./Subject\";\r\nimport { Arg, getErrorString, Platform } from \"./Utils\";\r\nimport { MessageBuffer } from \"./MessageBuffer\";\r\n\r\nconst DEFAULT_TIMEOUT_IN_MS: number = 30 * 1000;\r\nconst DEFAULT_PING_INTERVAL_IN_MS: number = 15 * 1000;\r\nconst DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE = 100_000;\r\n\r\n/** Describes the current state of the {@link HubConnection} to the server. */\r\nexport enum HubConnectionState {\r\n /** The hub connection is disconnected. */\r\n Disconnected = \"Disconnected\",\r\n /** The hub connection is connecting. */\r\n Connecting = \"Connecting\",\r\n /** The hub connection is connected. */\r\n Connected = \"Connected\",\r\n /** The hub connection is disconnecting. */\r\n Disconnecting = \"Disconnecting\",\r\n /** The hub connection is reconnecting. */\r\n Reconnecting = \"Reconnecting\",\r\n}\r\n\r\n/** Represents a connection to a SignalR Hub. */\r\nexport class HubConnection {\r\n private readonly _cachedPingMessage: string | ArrayBuffer;\r\n // Needs to not start with _ for tests\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private readonly connection: IConnection;\r\n private readonly _logger: ILogger;\r\n private readonly _reconnectPolicy?: IRetryPolicy;\r\n private readonly _statefulReconnectBufferSize: number;\r\n private _protocol: IHubProtocol;\r\n private _handshakeProtocol: HandshakeProtocol;\r\n private _callbacks: { [invocationId: string]: (invocationEvent: StreamItemMessage | CompletionMessage | null, error?: Error) => void };\r\n private _methods: { [name: string]: (((...args: any[]) => void) | ((...args: any[]) => any))[] };\r\n private _invocationId: number;\r\n private _messageBuffer?: MessageBuffer;\r\n\r\n private _closedCallbacks: ((error?: Error) => void)[];\r\n private _reconnectingCallbacks: ((error?: Error) => void)[];\r\n private _reconnectedCallbacks: ((connectionId?: string) => void)[];\r\n\r\n private _receivedHandshakeResponse: boolean;\r\n private _handshakeResolver!: (value?: PromiseLike<{}>) => void;\r\n private _handshakeRejecter!: (reason?: any) => void;\r\n private _stopDuringStartError?: Error;\r\n\r\n private _connectionState: HubConnectionState;\r\n // connectionStarted is tracked independently from connectionState, so we can check if the\r\n // connection ever did successfully transition from connecting to connected before disconnecting.\r\n private _connectionStarted: boolean;\r\n private _startPromise?: Promise;\r\n private _stopPromise?: Promise;\r\n private _nextKeepAlive: number = 0;\r\n\r\n // The type of these a) doesn't matter and b) varies when building in browser and node contexts\r\n // Since we're building the WebPack bundle directly from the TypeScript, this matters (previously\r\n // we built the bundle from the compiled JavaScript).\r\n private _reconnectDelayHandle?: any;\r\n private _timeoutHandle?: any;\r\n private _pingServerHandle?: any;\r\n\r\n private _freezeEventListener = () =>\r\n {\r\n 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\");\r\n };\r\n\r\n /** The server timeout in milliseconds.\r\n *\r\n * If this timeout elapses without receiving any messages from the server, the connection will be terminated with an error.\r\n * The default timeout value is 30,000 milliseconds (30 seconds).\r\n */\r\n public serverTimeoutInMilliseconds: number;\r\n\r\n /** Default interval at which to ping the server.\r\n *\r\n * The default value is 15,000 milliseconds (15 seconds).\r\n * Allows the server to detect hard disconnects (like when a client unplugs their computer).\r\n * The ping will happen at most as often as the server pings.\r\n * If the server pings every 5 seconds, a value lower than 5 will ping every 5 seconds.\r\n */\r\n public keepAliveIntervalInMilliseconds: number;\r\n\r\n /** @internal */\r\n // Using a public static factory method means we can have a private constructor and an _internal_\r\n // create method that can be used by HubConnectionBuilder. An \"internal\" constructor would just\r\n // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a\r\n // public parameter-less constructor.\r\n public static create(\r\n connection: IConnection,\r\n logger: ILogger,\r\n protocol: IHubProtocol,\r\n reconnectPolicy?: IRetryPolicy,\r\n serverTimeoutInMilliseconds?: number,\r\n keepAliveIntervalInMilliseconds?: number,\r\n statefulReconnectBufferSize?: number): HubConnection {\r\n return new HubConnection(connection, logger, protocol, reconnectPolicy,\r\n serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize);\r\n }\r\n\r\n private constructor(\r\n connection: IConnection,\r\n logger: ILogger,\r\n protocol: IHubProtocol,\r\n reconnectPolicy?: IRetryPolicy,\r\n serverTimeoutInMilliseconds?: number,\r\n keepAliveIntervalInMilliseconds?: number,\r\n statefulReconnectBufferSize?: number) {\r\n Arg.isRequired(connection, \"connection\");\r\n Arg.isRequired(logger, \"logger\");\r\n Arg.isRequired(protocol, \"protocol\");\r\n\r\n this.serverTimeoutInMilliseconds = serverTimeoutInMilliseconds ?? DEFAULT_TIMEOUT_IN_MS;\r\n this.keepAliveIntervalInMilliseconds = keepAliveIntervalInMilliseconds ?? DEFAULT_PING_INTERVAL_IN_MS;\r\n\r\n this._statefulReconnectBufferSize = statefulReconnectBufferSize ?? DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE;\r\n\r\n this._logger = logger;\r\n this._protocol = protocol;\r\n this.connection = connection;\r\n this._reconnectPolicy = reconnectPolicy;\r\n this._handshakeProtocol = new HandshakeProtocol();\r\n\r\n this.connection.onreceive = (data: any) => this._processIncomingData(data);\r\n this.connection.onclose = (error?: Error) => this._connectionClosed(error);\r\n\r\n this._callbacks = {};\r\n this._methods = {};\r\n this._closedCallbacks = [];\r\n this._reconnectingCallbacks = [];\r\n this._reconnectedCallbacks = [];\r\n this._invocationId = 0;\r\n this._receivedHandshakeResponse = false;\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n\r\n this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping });\r\n }\r\n\r\n /** Indicates the state of the {@link HubConnection} to the server. */\r\n get state(): HubConnectionState {\r\n return this._connectionState;\r\n }\r\n\r\n /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either\r\n * in the disconnected state or if the negotiation step was skipped.\r\n */\r\n get connectionId(): string | null {\r\n return this.connection ? (this.connection.connectionId || null) : null;\r\n }\r\n\r\n /** Indicates the url of the {@link HubConnection} to the server. */\r\n get baseUrl(): string {\r\n return this.connection.baseUrl || \"\";\r\n }\r\n\r\n /**\r\n * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or\r\n * Reconnecting states.\r\n * @param {string} url The url to connect to.\r\n */\r\n set baseUrl(url: string) {\r\n if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {\r\n throw new Error(\"The HubConnection must be in the Disconnected or Reconnecting state to change the url.\");\r\n }\r\n\r\n if (!url) {\r\n throw new Error(\"The HubConnection url must be a valid url.\");\r\n }\r\n\r\n this.connection.baseUrl = url;\r\n }\r\n\r\n /** Starts the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error.\r\n */\r\n public start(): Promise {\r\n this._startPromise = this._startWithStateTransitions();\r\n return this._startPromise;\r\n }\r\n\r\n private async _startWithStateTransitions(): Promise {\r\n if (this._connectionState !== HubConnectionState.Disconnected) {\r\n return Promise.reject(new Error(\"Cannot start a HubConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n\r\n this._connectionState = HubConnectionState.Connecting;\r\n this._logger.log(LogLevel.Debug, \"Starting HubConnection.\");\r\n\r\n try {\r\n await this._startInternal();\r\n\r\n if (Platform.isBrowser) {\r\n // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working\r\n window.document.addEventListener(\"freeze\", this._freezeEventListener);\r\n }\r\n\r\n this._connectionState = HubConnectionState.Connected;\r\n this._connectionStarted = true;\r\n this._logger.log(LogLevel.Debug, \"HubConnection connected successfully.\");\r\n } catch (e) {\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n private async _startInternal() {\r\n this._stopDuringStartError = undefined;\r\n this._receivedHandshakeResponse = false;\r\n // Set up the promise before any connection is (re)started otherwise it could race with received messages\r\n const handshakePromise = new Promise((resolve, reject) => {\r\n this._handshakeResolver = resolve;\r\n this._handshakeRejecter = reject;\r\n });\r\n\r\n await this.connection.start(this._protocol.transferFormat);\r\n\r\n try {\r\n let version = this._protocol.version;\r\n if (!this.connection.features.reconnect) {\r\n // Stateful Reconnect starts with HubProtocol version 2, newer clients connecting to older servers will fail to connect due to\r\n // the handshake only supporting version 1, so we will try to send version 1 during the handshake to keep old servers working.\r\n version = 1;\r\n }\r\n\r\n const handshakeRequest: HandshakeRequestMessage = {\r\n protocol: this._protocol.name,\r\n version,\r\n };\r\n\r\n this._logger.log(LogLevel.Debug, \"Sending handshake request.\");\r\n\r\n await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));\r\n\r\n this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);\r\n\r\n // defensively cleanup timeout in case we receive a message from the server before we finish start\r\n this._cleanupTimeout();\r\n this._resetTimeoutPeriod();\r\n this._resetKeepAliveInterval();\r\n\r\n await handshakePromise;\r\n\r\n // It's important to check the stopDuringStartError instead of just relying on the handshakePromise\r\n // being rejected on close, because this continuation can run after both the handshake completed successfully\r\n // and the connection was closed.\r\n if (this._stopDuringStartError) {\r\n // It's important to throw instead of returning a rejected promise, because we don't want to allow any state\r\n // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise\r\n // will cause the calling continuation to get scheduled to run later.\r\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\r\n throw this._stopDuringStartError;\r\n }\r\n\r\n const useStatefulReconnect = this.connection.features.reconnect || false;\r\n if (useStatefulReconnect) {\r\n this._messageBuffer = new MessageBuffer(this._protocol, this.connection, this._statefulReconnectBufferSize);\r\n this.connection.features.disconnected = this._messageBuffer._disconnected.bind(this._messageBuffer);\r\n this.connection.features.resend = () => {\r\n if (this._messageBuffer) {\r\n return this._messageBuffer._resend();\r\n }\r\n }\r\n }\r\n\r\n if (!this.connection.features.inherentKeepAlive) {\r\n await this._sendMessage(this._cachedPingMessage);\r\n }\r\n } catch (e) {\r\n this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);\r\n\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n\r\n // HttpConnection.stop() should not complete until after the onclose callback is invoked.\r\n // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.\r\n await this.connection.stop(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /** Stops the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.\r\n */\r\n public async stop(): Promise {\r\n // Capture the start promise before the connection might be restarted in an onclose callback.\r\n const startPromise = this._startPromise;\r\n this.connection.features.reconnect = false;\r\n\r\n this._stopPromise = this._stopInternal();\r\n await this._stopPromise;\r\n\r\n try {\r\n // Awaiting undefined continues immediately\r\n await startPromise;\r\n } catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n }\r\n\r\n private _stopInternal(error?: Error): Promise {\r\n if (this._connectionState === HubConnectionState.Disconnected) {\r\n this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this._stopPromise!;\r\n }\r\n\r\n const state = this._connectionState;\r\n this._connectionState = HubConnectionState.Disconnecting;\r\n\r\n this._logger.log(LogLevel.Debug, \"Stopping HubConnection.\");\r\n\r\n if (this._reconnectDelayHandle) {\r\n // We're in a reconnect delay which means the underlying connection is currently already stopped.\r\n // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and\r\n // fire the onclose callbacks.\r\n this._logger.log(LogLevel.Debug, \"Connection stopped during reconnect delay. Done reconnecting.\");\r\n\r\n clearTimeout(this._reconnectDelayHandle);\r\n this._reconnectDelayHandle = undefined;\r\n\r\n this._completeClose();\r\n return Promise.resolve();\r\n }\r\n\r\n if (state === HubConnectionState.Connected) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._sendCloseMessage();\r\n }\r\n\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n this._stopDuringStartError = error || new AbortError(\"The connection was stopped before the hub handshake could complete.\");\r\n\r\n // HttpConnection.stop() should not complete until after either HttpConnection.start() fails\r\n // or the onclose callback is invoked. The onclose callback will transition the HubConnection\r\n // to the disconnected state if need be before HttpConnection.stop() completes.\r\n return this.connection.stop(error);\r\n }\r\n\r\n private async _sendCloseMessage() {\r\n try {\r\n await this._sendWithProtocol(this._createCloseMessage());\r\n } catch {\r\n // Ignore, this is a best effort attempt to let the server know the client closed gracefully.\r\n }\r\n }\r\n\r\n /** Invokes a streaming hub method on the server using the specified name and arguments.\r\n *\r\n * @typeparam T The type of the items returned by the server.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {IStreamResult} An object that yields results from the server as they are received.\r\n */\r\n public stream(methodName: string, ...args: any[]): IStreamResult {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);\r\n\r\n // eslint-disable-next-line prefer-const\r\n let promiseQueue: Promise;\r\n\r\n const subject = new Subject();\r\n subject.cancelCallback = () => {\r\n const cancelInvocation: CancelInvocationMessage = this._createCancelInvocation(invocationDescriptor.invocationId);\r\n\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n\r\n return promiseQueue.then(() => {\r\n return this._sendWithProtocol(cancelInvocation);\r\n });\r\n };\r\n\r\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent: CompletionMessage | StreamItemMessage | null, error?: Error) => {\r\n if (error) {\r\n subject.error(error);\r\n return;\r\n } else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n subject.error(new Error(invocationEvent.error));\r\n } else {\r\n subject.complete();\r\n }\r\n } else {\r\n subject.next((invocationEvent.item) as T);\r\n }\r\n }\r\n };\r\n\r\n promiseQueue = this._sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n subject.error(e);\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n });\r\n\r\n this._launchStreams(streams, promiseQueue);\r\n\r\n return subject;\r\n }\r\n\r\n private _sendMessage(message: any) {\r\n this._resetKeepAliveInterval();\r\n return this.connection.send(message);\r\n }\r\n\r\n /**\r\n * Sends a js object to the server.\r\n * @param message The js object to serialize and send.\r\n */\r\n private _sendWithProtocol(message: any) {\r\n if (this._messageBuffer) {\r\n return this._messageBuffer._send(message);\r\n } else {\r\n return this._sendMessage(this._protocol.writeMessage(message));\r\n }\r\n }\r\n\r\n /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.\r\n *\r\n * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still\r\n * be processing the invocation.\r\n *\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.\r\n */\r\n public send(methodName: string, ...args: any[]): Promise {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));\r\n\r\n this._launchStreams(streams, sendPromise);\r\n\r\n return sendPromise;\r\n }\r\n\r\n /** Invokes a hub method on the server using the specified name and arguments.\r\n *\r\n * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise\r\n * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of\r\n * resolving the Promise.\r\n *\r\n * @typeparam T The expected return type.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error.\r\n */\r\n public invoke(methodName: string, ...args: any[]): Promise {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);\r\n\r\n const p = new Promise((resolve, reject) => {\r\n // invocationId will always have a value for a non-blocking invocation\r\n this._callbacks[invocationDescriptor.invocationId!] = (invocationEvent: StreamItemMessage | CompletionMessage | null, error?: Error) => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n } else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n reject(new Error(invocationEvent.error));\r\n } else {\r\n resolve(invocationEvent.result);\r\n }\r\n } else {\r\n reject(new Error(`Unexpected message type: ${invocationEvent.type}`));\r\n }\r\n }\r\n };\r\n\r\n const promiseQueue = this._sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n reject(e);\r\n // invocationId will always have a value for a non-blocking invocation\r\n delete this._callbacks[invocationDescriptor.invocationId!];\r\n });\r\n\r\n this._launchStreams(streams, promiseQueue);\r\n });\r\n\r\n return p;\r\n }\r\n\r\n /** Registers a handler that will be invoked when the hub method with the specified method name is invoked.\r\n *\r\n * @param {string} methodName The name of the hub method to define.\r\n * @param {Function} newMethod The handler that will be raised when the hub method is invoked.\r\n */\r\n public on(methodName: string, newMethod: (...args: any[]) => any): void\r\n public on(methodName: string, newMethod: (...args: any[]) => void): void {\r\n if (!methodName || !newMethod) {\r\n return;\r\n }\r\n\r\n methodName = methodName.toLowerCase();\r\n if (!this._methods[methodName]) {\r\n this._methods[methodName] = [];\r\n }\r\n\r\n // Preventing adding the same handler multiple times.\r\n if (this._methods[methodName].indexOf(newMethod) !== -1) {\r\n return;\r\n }\r\n\r\n this._methods[methodName].push(newMethod);\r\n }\r\n\r\n /** Removes all handlers for the specified hub method.\r\n *\r\n * @param {string} methodName The name of the method to remove handlers for.\r\n */\r\n public off(methodName: string): void;\r\n\r\n /** Removes the specified handler for the specified hub method.\r\n *\r\n * You must pass the exact same Function instance as was previously passed to {@link @microsoft/signalr.HubConnection.on}. Passing a different instance (even if the function\r\n * body is the same) will not remove the handler.\r\n *\r\n * @param {string} methodName The name of the method to remove handlers for.\r\n * @param {Function} method The handler to remove. This must be the same Function instance as the one passed to {@link @microsoft/signalr.HubConnection.on}.\r\n */\r\n public off(methodName: string, method: (...args: any[]) => void): void;\r\n public off(methodName: string, method?: (...args: any[]) => void): void {\r\n if (!methodName) {\r\n return;\r\n }\r\n\r\n methodName = methodName.toLowerCase();\r\n const handlers = this._methods[methodName];\r\n if (!handlers) {\r\n return;\r\n }\r\n if (method) {\r\n const removeIdx = handlers.indexOf(method);\r\n if (removeIdx !== -1) {\r\n handlers.splice(removeIdx, 1);\r\n if (handlers.length === 0) {\r\n delete this._methods[methodName];\r\n }\r\n }\r\n } else {\r\n delete this._methods[methodName];\r\n }\r\n\r\n }\r\n\r\n /** Registers a handler that will be invoked when the connection is closed.\r\n *\r\n * @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).\r\n */\r\n public onclose(callback: (error?: Error) => void): void {\r\n if (callback) {\r\n this._closedCallbacks.push(callback);\r\n }\r\n }\r\n\r\n /** Registers a handler that will be invoked when the connection starts reconnecting.\r\n *\r\n * @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).\r\n */\r\n public onreconnecting(callback: (error?: Error) => void): void {\r\n if (callback) {\r\n this._reconnectingCallbacks.push(callback);\r\n }\r\n }\r\n\r\n /** Registers a handler that will be invoked when the connection successfully reconnects.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.\r\n */\r\n public onreconnected(callback: (connectionId?: string) => void): void {\r\n if (callback) {\r\n this._reconnectedCallbacks.push(callback);\r\n }\r\n }\r\n\r\n private _processIncomingData(data: any) {\r\n this._cleanupTimeout();\r\n\r\n if (!this._receivedHandshakeResponse) {\r\n data = this._processHandshakeResponse(data);\r\n this._receivedHandshakeResponse = true;\r\n }\r\n\r\n // Data may have all been read when processing handshake response\r\n if (data) {\r\n // Parse the messages\r\n const messages = this._protocol.parseMessages(data, this._logger);\r\n\r\n for (const message of messages) {\r\n if (this._messageBuffer && !this._messageBuffer._shouldProcessMessage(message)) {\r\n // Don't process the message, we are either waiting for a SequenceMessage or received a duplicate message\r\n continue;\r\n }\r\n\r\n switch (message.type) {\r\n case MessageType.Invocation:\r\n this._invokeClientMethod(message)\r\n .catch((e) => {\r\n this._logger.log(LogLevel.Error, `Invoke client method threw error: ${getErrorString(e)}`)\r\n });\r\n break;\r\n case MessageType.StreamItem:\r\n case MessageType.Completion: {\r\n const callback = this._callbacks[message.invocationId];\r\n if (callback) {\r\n if (message.type === MessageType.Completion) {\r\n delete this._callbacks[message.invocationId];\r\n }\r\n try {\r\n callback(message);\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);\r\n }\r\n }\r\n break;\r\n }\r\n case MessageType.Ping:\r\n // Don't care about pings\r\n break;\r\n case MessageType.Close: {\r\n this._logger.log(LogLevel.Information, \"Close message received from server.\");\r\n\r\n const error = message.error ? new Error(\"Server returned an error on close: \" + message.error) : undefined;\r\n\r\n if (message.allowReconnect === true) {\r\n // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,\r\n // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.connection.stop(error);\r\n } else {\r\n // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.\r\n this._stopPromise = this._stopInternal(error);\r\n }\r\n\r\n break;\r\n }\r\n case MessageType.Ack:\r\n if (this._messageBuffer) {\r\n this._messageBuffer._ack(message);\r\n }\r\n break;\r\n case MessageType.Sequence:\r\n if (this._messageBuffer) {\r\n this._messageBuffer._resetSequence(message);\r\n }\r\n break;\r\n default:\r\n this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n this._resetTimeoutPeriod();\r\n }\r\n\r\n private _processHandshakeResponse(data: any): any {\r\n let responseMessage: HandshakeResponseMessage;\r\n let remainingData: any;\r\n\r\n try {\r\n [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);\r\n } catch (e) {\r\n const message = \"Error parsing handshake response: \" + e;\r\n this._logger.log(LogLevel.Error, message);\r\n\r\n const error = new Error(message);\r\n this._handshakeRejecter(error);\r\n throw error;\r\n }\r\n if (responseMessage.error) {\r\n const message = \"Server returned handshake error: \" + responseMessage.error;\r\n this._logger.log(LogLevel.Error, message);\r\n\r\n const error = new Error(message);\r\n this._handshakeRejecter(error);\r\n throw error;\r\n } else {\r\n this._logger.log(LogLevel.Debug, \"Server handshake complete.\");\r\n }\r\n\r\n this._handshakeResolver();\r\n return remainingData;\r\n }\r\n\r\n private _resetKeepAliveInterval() {\r\n if (this.connection.features.inherentKeepAlive) {\r\n return;\r\n }\r\n\r\n // Set the time we want the next keep alive to be sent\r\n // Timer will be setup on next message receive\r\n this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;\r\n\r\n this._cleanupPingTimer();\r\n }\r\n\r\n private _resetTimeoutPeriod() {\r\n if (!this.connection.features || !this.connection.features.inherentKeepAlive) {\r\n // Set the timeout timer\r\n this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);\r\n\r\n // Set keepAlive timer if there isn't one\r\n if (this._pingServerHandle === undefined)\r\n {\r\n let nextPing = this._nextKeepAlive - new Date().getTime();\r\n if (nextPing < 0) {\r\n nextPing = 0;\r\n }\r\n\r\n // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute\r\n this._pingServerHandle = setTimeout(async () => {\r\n if (this._connectionState === HubConnectionState.Connected) {\r\n try {\r\n await this._sendMessage(this._cachedPingMessage);\r\n } catch {\r\n // We don't care about the error. It should be seen elsewhere in the client.\r\n // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering\r\n this._cleanupPingTimer();\r\n }\r\n }\r\n }, nextPing);\r\n }\r\n }\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private serverTimeout() {\r\n // The server hasn't talked to us in a while. It doesn't like us anymore ... :(\r\n // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.connection.stop(new Error(\"Server timeout elapsed without receiving a message from the server.\"));\r\n }\r\n\r\n private async _invokeClientMethod(invocationMessage: InvocationMessage) {\r\n const methodName = invocationMessage.target.toLowerCase();\r\n const methods = this._methods[methodName];\r\n if (!methods) {\r\n this._logger.log(LogLevel.Warning, `No client method with the name '${methodName}' found.`);\r\n\r\n // No handlers provided by client but the server is expecting a response still, so we send an error\r\n if (invocationMessage.invocationId) {\r\n this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);\r\n await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, \"Client didn't provide a result.\", null));\r\n }\r\n return;\r\n }\r\n\r\n // Avoid issues with handlers removing themselves thus modifying the list while iterating through it\r\n const methodsCopy = methods.slice();\r\n\r\n // Server expects a response\r\n const expectsResponse = invocationMessage.invocationId ? true : false;\r\n // We preserve the last result or exception but still call all handlers\r\n let res;\r\n let exception;\r\n let completionMessage;\r\n for (const m of methodsCopy) {\r\n try {\r\n const prevRes = res;\r\n res = await m.apply(this, invocationMessage.arguments);\r\n if (expectsResponse && res && prevRes) {\r\n this._logger.log(LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`);\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId!, `Client provided multiple results.`, null);\r\n }\r\n // Ignore exception if we got a result after, the exception will be logged\r\n exception = undefined;\r\n } catch (e) {\r\n exception = e;\r\n this._logger.log(LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`);\r\n }\r\n }\r\n if (completionMessage) {\r\n await this._sendWithProtocol(completionMessage);\r\n } else if (expectsResponse) {\r\n // If there is an exception that means either no result was given or a handler after a result threw\r\n if (exception) {\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId!, `${exception}`, null);\r\n } else if (res !== undefined) {\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId!, null, res);\r\n } else {\r\n this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);\r\n // Client didn't provide a result or throw from a handler, server expects a response so we send an error\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId!, \"Client didn't provide a result.\", null);\r\n }\r\n await this._sendWithProtocol(completionMessage);\r\n } else {\r\n if (res) {\r\n this._logger.log(LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`);\r\n }\r\n }\r\n }\r\n\r\n private _connectionClosed(error?: Error) {\r\n this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);\r\n\r\n // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.\r\n this._stopDuringStartError = this._stopDuringStartError || error || new AbortError(\"The underlying connection was closed before the hub handshake could complete.\");\r\n\r\n // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.\r\n // If it has already completed, this should just noop.\r\n if (this._handshakeResolver) {\r\n this._handshakeResolver();\r\n }\r\n\r\n this._cancelCallbacksWithError(error || new Error(\"Invocation canceled due to the underlying connection being closed.\"));\r\n\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._completeClose(error);\r\n } else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._reconnect(error);\r\n } else if (this._connectionState === HubConnectionState.Connected) {\r\n this._completeClose(error);\r\n }\r\n\r\n // If none of the above if conditions were true were called the HubConnection must be in either:\r\n // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.\r\n // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt\r\n // and potentially continue the reconnect() loop.\r\n // 3. The Disconnected state in which case we're already done.\r\n }\r\n\r\n private _completeClose(error?: Error) {\r\n if (this._connectionStarted) {\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n if (this._messageBuffer) {\r\n this._messageBuffer._dispose(error ?? new Error(\"Connection closed.\"));\r\n this._messageBuffer = undefined;\r\n }\r\n\r\n if (Platform.isBrowser) {\r\n window.document.removeEventListener(\"freeze\", this._freezeEventListener);\r\n }\r\n\r\n try {\r\n this._closedCallbacks.forEach((c) => c.apply(this, [error]));\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n\r\n private async _reconnect(error?: Error) {\r\n const reconnectStartTime = Date.now();\r\n let previousReconnectAttempts = 0;\r\n let retryError = error !== undefined ? error : new Error(\"Attempting to reconnect due to a unknown error.\");\r\n\r\n let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);\r\n\r\n if (nextRetryDelay === null) {\r\n this._logger.log(LogLevel.Debug, \"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.\");\r\n this._completeClose(error);\r\n return;\r\n }\r\n\r\n this._connectionState = HubConnectionState.Reconnecting;\r\n\r\n if (error) {\r\n this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);\r\n } else {\r\n this._logger.log(LogLevel.Information, \"Connection reconnecting.\");\r\n }\r\n\r\n if (this._reconnectingCallbacks.length !== 0) {\r\n try {\r\n this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n\r\n // Exit early if an onreconnecting callback called connection.stop().\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.\");\r\n return;\r\n }\r\n }\r\n\r\n while (nextRetryDelay !== null) {\r\n this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);\r\n\r\n await new Promise((resolve) => {\r\n this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay!);\r\n });\r\n this._reconnectDelayHandle = undefined;\r\n\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state during reconnect delay. Done reconnecting.\");\r\n return;\r\n }\r\n\r\n try {\r\n await this._startInternal();\r\n\r\n this._connectionState = HubConnectionState.Connected;\r\n this._logger.log(LogLevel.Information, \"HubConnection reconnected successfully.\");\r\n\r\n if (this._reconnectedCallbacks.length !== 0) {\r\n try {\r\n this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);\r\n }\r\n }\r\n\r\n return;\r\n } catch (e) {\r\n this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);\r\n\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);\r\n // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.\r\n if (this._connectionState as any === HubConnectionState.Disconnecting) {\r\n this._completeClose();\r\n }\r\n return;\r\n }\r\n\r\n retryError = e instanceof Error ? e : new Error((e as any).toString());\r\n nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);\r\n }\r\n }\r\n\r\n this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);\r\n\r\n this._completeClose();\r\n }\r\n\r\n private _getNextRetryDelay(previousRetryCount: number, elapsedMilliseconds: number, retryReason: Error) {\r\n try {\r\n return this._reconnectPolicy!.nextRetryDelayInMilliseconds({\r\n elapsedMilliseconds,\r\n previousRetryCount,\r\n retryReason,\r\n });\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);\r\n return null;\r\n }\r\n }\r\n\r\n private _cancelCallbacksWithError(error: Error) {\r\n const callbacks = this._callbacks;\r\n this._callbacks = {};\r\n\r\n Object.keys(callbacks)\r\n .forEach((key) => {\r\n const callback = callbacks[key];\r\n try {\r\n callback(null, error);\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);\r\n }\r\n });\r\n }\r\n\r\n private _cleanupPingTimer(): void {\r\n if (this._pingServerHandle) {\r\n clearTimeout(this._pingServerHandle);\r\n this._pingServerHandle = undefined;\r\n }\r\n }\r\n\r\n private _cleanupTimeout(): void {\r\n if (this._timeoutHandle) {\r\n clearTimeout(this._timeoutHandle);\r\n }\r\n }\r\n\r\n private _createInvocation(methodName: string, args: any[], nonblocking: boolean, streamIds: string[]): InvocationMessage {\r\n if (nonblocking) {\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n } else {\r\n return {\r\n arguments: args,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n } else {\r\n const invocationId = this._invocationId;\r\n this._invocationId++;\r\n\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n } else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n }\r\n\r\n private _launchStreams(streams: IStreamResult[], promiseQueue: Promise): void {\r\n if (streams.length === 0) {\r\n return;\r\n }\r\n\r\n // Synchronize stream data so they arrive in-order on the server\r\n if (!promiseQueue) {\r\n promiseQueue = Promise.resolve();\r\n }\r\n\r\n // We want to iterate over the keys, since the keys are the stream ids\r\n // eslint-disable-next-line guard-for-in\r\n for (const streamId in streams) {\r\n streams[streamId].subscribe({\r\n complete: () => {\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));\r\n },\r\n error: (err) => {\r\n let message: string;\r\n if (err instanceof Error) {\r\n message = err.message;\r\n } else if (err && err.toString) {\r\n message = err.toString();\r\n } else {\r\n message = \"Unknown error\";\r\n }\r\n\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));\r\n },\r\n next: (item) => {\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));\r\n },\r\n });\r\n }\r\n }\r\n\r\n private _replaceStreamingParams(args: any[]): [IStreamResult[], string[]] {\r\n const streams: IStreamResult[] = [];\r\n const streamIds: string[] = [];\r\n for (let i = 0; i < args.length; i++) {\r\n const argument = args[i];\r\n if (this._isObservable(argument)) {\r\n const streamId = this._invocationId;\r\n this._invocationId++;\r\n // Store the stream for later use\r\n streams[streamId] = argument;\r\n streamIds.push(streamId.toString());\r\n\r\n // remove stream from args\r\n args.splice(i, 1);\r\n }\r\n }\r\n\r\n return [streams, streamIds];\r\n }\r\n\r\n private _isObservable(arg: any): arg is IStreamResult {\r\n // This allows other stream implementations to just work (like rxjs)\r\n return arg && arg.subscribe && typeof arg.subscribe === \"function\";\r\n }\r\n\r\n private _createStreamInvocation(methodName: string, args: any[], streamIds: string[]): StreamInvocationMessage {\r\n const invocationId = this._invocationId;\r\n this._invocationId++;\r\n\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n } else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n }\r\n }\r\n\r\n private _createCancelInvocation(id: string): CancelInvocationMessage {\r\n return {\r\n invocationId: id,\r\n type: MessageType.CancelInvocation,\r\n };\r\n }\r\n\r\n private _createStreamItemMessage(id: string, item: any): StreamItemMessage {\r\n return {\r\n invocationId: id,\r\n item,\r\n type: MessageType.StreamItem,\r\n };\r\n }\r\n\r\n private _createCompletionMessage(id: string, error?: any, result?: any): CompletionMessage {\r\n if (error) {\r\n return {\r\n error,\r\n invocationId: id,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n\r\n return {\r\n invocationId: id,\r\n result,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n\r\n private _createCloseMessage(): CloseMessage {\r\n return { type: MessageType.Close };\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { IStreamResult, IStreamSubscriber, ISubscription } from \"./Stream\";\r\nimport { SubjectSubscription } from \"./Utils\";\r\n\r\n/** Stream implementation to stream items to the server. */\r\nexport class Subject implements IStreamResult {\r\n /** @internal */\r\n public observers: IStreamSubscriber[];\r\n\r\n /** @internal */\r\n public cancelCallback?: () => Promise;\r\n\r\n constructor() {\r\n this.observers = [];\r\n }\r\n\r\n public next(item: T): void {\r\n for (const observer of this.observers) {\r\n observer.next(item);\r\n }\r\n }\r\n\r\n public error(err: any): void {\r\n for (const observer of this.observers) {\r\n if (observer.error) {\r\n observer.error(err);\r\n }\r\n }\r\n }\r\n\r\n public complete(): void {\r\n for (const observer of this.observers) {\r\n if (observer.complete) {\r\n observer.complete();\r\n }\r\n }\r\n }\r\n\r\n public subscribe(observer: IStreamSubscriber): ISubscription {\r\n this.observers.push(observer);\r\n return new SubjectSubscription(this, observer);\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { IConnection } from \"./IConnection\";\r\nimport { AckMessage, HubMessage, IHubProtocol, MessageType, SequenceMessage } from \"./IHubProtocol\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n\r\n/** @private */\r\nexport class MessageBuffer {\r\n private readonly _protocol: IHubProtocol;\r\n private readonly _connection: IConnection;\r\n\r\n private readonly _bufferSize: number = 100_000;\r\n\r\n private _messages: BufferedItem[] = [];\r\n private _totalMessageCount: number = 0;\r\n private _waitForSequenceMessage: boolean = false;\r\n\r\n // Message IDs start at 1 and always increment by 1\r\n private _nextReceivingSequenceId = 1;\r\n private _latestReceivedSequenceId = 0;\r\n private _bufferedByteCount: number = 0;\r\n private _reconnectInProgress: boolean = false;\r\n\r\n private _ackTimerHandle?: any;\r\n\r\n constructor(protocol: IHubProtocol, connection: IConnection, bufferSize: number) {\r\n this._protocol = protocol;\r\n this._connection = connection;\r\n this._bufferSize = bufferSize;\r\n }\r\n\r\n public async _send(message: HubMessage): Promise {\r\n const serializedMessage = this._protocol.writeMessage(message);\r\n\r\n let backpressurePromise: Promise = Promise.resolve();\r\n\r\n // Only count invocation messages. Acks, pings, etc. don't need to be resent on reconnect\r\n if (this._isInvocationMessage(message)) {\r\n this._totalMessageCount++;\r\n let backpressurePromiseResolver: (value: void) => void = () => {};\r\n let backpressurePromiseRejector: (value?: void) => void = () => {};\r\n\r\n if (isArrayBuffer(serializedMessage)) {\r\n this._bufferedByteCount += serializedMessage.byteLength;\r\n } else {\r\n this._bufferedByteCount += serializedMessage.length;\r\n }\r\n\r\n if (this._bufferedByteCount >= this._bufferSize) {\r\n backpressurePromise = new Promise((resolve, reject) => {\r\n backpressurePromiseResolver = resolve;\r\n backpressurePromiseRejector = reject;\r\n });\r\n }\r\n\r\n this._messages.push(new BufferedItem(serializedMessage, this._totalMessageCount,\r\n backpressurePromiseResolver, backpressurePromiseRejector));\r\n }\r\n\r\n try {\r\n // If this is set it means we are reconnecting or resending\r\n // We don't want to send on a disconnected connection\r\n // And we don't want to send if resend is running since that would mean sending\r\n // this message twice\r\n if (!this._reconnectInProgress) {\r\n await this._connection.send(serializedMessage);\r\n }\r\n } catch {\r\n this._disconnected();\r\n }\r\n await backpressurePromise;\r\n }\r\n\r\n public _ack(ackMessage: AckMessage): void {\r\n let newestAckedMessage = -1;\r\n\r\n // Find index of newest message being acked\r\n for (let index = 0; index < this._messages.length; index++) {\r\n const element = this._messages[index];\r\n if (element._id <= ackMessage.sequenceId) {\r\n newestAckedMessage = index;\r\n if (isArrayBuffer(element._message)) {\r\n this._bufferedByteCount -= element._message.byteLength;\r\n } else {\r\n this._bufferedByteCount -= element._message.length;\r\n }\r\n // resolve items that have already been sent and acked\r\n element._resolver();\r\n } else if (this._bufferedByteCount < this._bufferSize) {\r\n // resolve items that now fall under the buffer limit but haven't been acked\r\n element._resolver();\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n if (newestAckedMessage !== -1) {\r\n // We're removing everything including the message pointed to, so add 1\r\n this._messages = this._messages.slice(newestAckedMessage + 1);\r\n }\r\n }\r\n\r\n public _shouldProcessMessage(message: HubMessage): boolean {\r\n if (this._waitForSequenceMessage) {\r\n if (message.type !== MessageType.Sequence) {\r\n return false;\r\n } else {\r\n this._waitForSequenceMessage = false;\r\n return true;\r\n }\r\n }\r\n\r\n // No special processing for acks, pings, etc.\r\n if (!this._isInvocationMessage(message)) {\r\n return true;\r\n }\r\n\r\n const currentId = this._nextReceivingSequenceId;\r\n this._nextReceivingSequenceId++;\r\n if (currentId <= this._latestReceivedSequenceId) {\r\n if (currentId === this._latestReceivedSequenceId) {\r\n // Should only hit this if we just reconnected and the server is sending\r\n // Messages it has buffered, which would mean it hasn't seen an Ack for these messages\r\n this._ackTimer();\r\n }\r\n // Ignore, this is a duplicate message\r\n return false;\r\n }\r\n\r\n this._latestReceivedSequenceId = currentId;\r\n\r\n // Only start the timer for sending an Ack message when we have a message to ack. This also conveniently solves\r\n // timer throttling by not having a recursive timer, and by starting the timer via a network call (recv)\r\n this._ackTimer();\r\n return true;\r\n }\r\n\r\n public _resetSequence(message: SequenceMessage): void {\r\n if (message.sequenceId > this._nextReceivingSequenceId) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._connection.stop(new Error(\"Sequence ID greater than amount of messages we've received.\"));\r\n return;\r\n }\r\n\r\n this._nextReceivingSequenceId = message.sequenceId;\r\n }\r\n\r\n public _disconnected(): void {\r\n this._reconnectInProgress = true;\r\n this._waitForSequenceMessage = true;\r\n }\r\n\r\n public async _resend(): Promise {\r\n const sequenceId = this._messages.length !== 0\r\n ? this._messages[0]._id\r\n : this._totalMessageCount + 1;\r\n await this._connection.send(this._protocol.writeMessage({ type: MessageType.Sequence, sequenceId }));\r\n\r\n // Get a local variable to the _messages, just in case messages are acked while resending\r\n // Which would slice the _messages array (which creates a new copy)\r\n const messages = this._messages;\r\n for (const element of messages) {\r\n await this._connection.send(element._message);\r\n }\r\n\r\n this._reconnectInProgress = false;\r\n }\r\n\r\n public _dispose(error?: Error): void {\r\n error ??= new Error(\"Unable to reconnect to server.\")\r\n\r\n // Unblock backpressure if any\r\n for (const element of this._messages) {\r\n element._rejector(error);\r\n }\r\n }\r\n\r\n private _isInvocationMessage(message: HubMessage): boolean {\r\n // There is no way to check if something implements an interface.\r\n // So we individually check the messages in a switch statement.\r\n // To make sure we don't miss any message types we rely on the compiler\r\n // seeing the function returns a value and it will do the\r\n // exhaustive check for us on the switch statement, since we don't use 'case default'\r\n switch (message.type) {\r\n case MessageType.Invocation:\r\n case MessageType.StreamItem:\r\n case MessageType.Completion:\r\n case MessageType.StreamInvocation:\r\n case MessageType.CancelInvocation:\r\n return true;\r\n case MessageType.Close:\r\n case MessageType.Sequence:\r\n case MessageType.Ping:\r\n case MessageType.Ack:\r\n return false;\r\n }\r\n }\r\n\r\n private _ackTimer(): void {\r\n if (this._ackTimerHandle === undefined) {\r\n this._ackTimerHandle = setTimeout(async () => {\r\n try {\r\n if (!this._reconnectInProgress) {\r\n await this._connection.send(this._protocol.writeMessage({ type: MessageType.Ack, sequenceId: this._latestReceivedSequenceId }))\r\n }\r\n // Ignore errors, that means the connection is closed and we don't care about the Ack message anymore.\r\n } catch { }\r\n\r\n clearTimeout(this._ackTimerHandle);\r\n this._ackTimerHandle = undefined;\r\n // 1 second delay so we don't spam Ack messages if there are many messages being received at once.\r\n }, 1000);\r\n }\r\n }\r\n}\r\n\r\nclass BufferedItem {\r\n constructor(message: string | ArrayBuffer, id: number, resolver: (value: void) => void, rejector: (value?: any) => void) {\r\n this._message = message;\r\n this._id = id;\r\n this._resolver = resolver;\r\n this._rejector = rejector;\r\n }\r\n\r\n _message: string | ArrayBuffer;\r\n _id: number;\r\n _resolver: (value: void) => void;\r\n _rejector: (value?: any) => void;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { IRetryPolicy, RetryContext } from \"./IRetryPolicy\";\r\n\r\n// 0, 2, 10, 30 second delays before reconnect attempts.\r\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\r\n\r\n/** @private */\r\nexport class DefaultReconnectPolicy implements IRetryPolicy {\r\n private readonly _retryDelays: (number | null)[];\r\n\r\n constructor(retryDelays?: number[]) {\r\n this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\r\n }\r\n\r\n public nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null {\r\n return this._retryDelays[retryContext.previousRetryCount];\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nexport abstract class HeaderNames {\r\n static readonly Authorization = \"Authorization\";\r\n static readonly Cookie = \"Cookie\";\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\n\r\n/** @private */\r\nexport class AccessTokenHttpClient extends HttpClient {\r\n private _innerClient: HttpClient;\r\n _accessToken: string | undefined;\r\n _accessTokenFactory: (() => string | Promise) | undefined;\r\n\r\n constructor(innerClient: HttpClient, accessTokenFactory: (() => string | Promise) | undefined) {\r\n super();\r\n\r\n this._innerClient = innerClient;\r\n this._accessTokenFactory = accessTokenFactory;\r\n }\r\n\r\n public async send(request: HttpRequest): Promise {\r\n let allowRetry = true;\r\n if (this._accessTokenFactory && (!this._accessToken || (request.url && request.url.indexOf(\"/negotiate?\") > 0))) {\r\n // don't retry if the request is a negotiate or if we just got a potentially new token from the access token factory\r\n allowRetry = false;\r\n this._accessToken = await this._accessTokenFactory();\r\n }\r\n this._setAuthorizationHeader(request);\r\n const response = await this._innerClient.send(request);\r\n\r\n if (allowRetry && response.statusCode === 401 && this._accessTokenFactory) {\r\n this._accessToken = await this._accessTokenFactory();\r\n this._setAuthorizationHeader(request);\r\n return await this._innerClient.send(request);\r\n }\r\n return response;\r\n }\r\n\r\n private _setAuthorizationHeader(request: HttpRequest) {\r\n if (!request.headers) {\r\n request.headers = {};\r\n }\r\n if (this._accessToken) {\r\n request.headers[HeaderNames.Authorization] = `Bearer ${this._accessToken}`\r\n }\r\n // don't remove the header if there isn't an access token factory, the user manually added the header in this case\r\n else if (this._accessTokenFactory) {\r\n if (request.headers[HeaderNames.Authorization]) {\r\n delete request.headers[HeaderNames.Authorization];\r\n }\r\n }\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n return this._innerClient.getCookieString(url);\r\n }\r\n}","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\n// This will be treated as a bit flag in the future, so we keep it using power-of-two values.\r\n/** Specifies a specific HTTP transport type. */\r\nexport enum HttpTransportType {\r\n /** Specifies no transport preference. */\r\n None = 0,\r\n /** Specifies the WebSockets transport. */\r\n WebSockets = 1,\r\n /** Specifies the Server-Sent Events transport. */\r\n ServerSentEvents = 2,\r\n /** Specifies the Long Polling transport. */\r\n LongPolling = 4,\r\n}\r\n\r\n/** Specifies the transfer format for a connection. */\r\nexport enum TransferFormat {\r\n /** Specifies that only text data will be transmitted over the connection. */\r\n Text = 1,\r\n /** Specifies that binary data will be transmitted over the connection. */\r\n Binary = 2,\r\n}\r\n\r\n/** An abstraction over the behavior of transports. This is designed to support the framework and not intended for use by applications. */\r\nexport interface ITransport {\r\n connect(url: string, transferFormat: TransferFormat): Promise;\r\n send(data: any): Promise;\r\n stop(): Promise;\r\n onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n onclose: ((error?: Error) => void) | null;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\n// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\r\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\r\n// it's a very new API right now.\r\n\r\n// Not exported from index.\r\n/** @private */\r\nexport class AbortController implements AbortSignal {\r\n private _isAborted: boolean = false;\r\n public onabort: (() => void) | null = null;\r\n\r\n public abort(): void {\r\n if (!this._isAborted) {\r\n this._isAborted = true;\r\n if (this.onabort) {\r\n this.onabort();\r\n }\r\n }\r\n }\r\n\r\n get signal(): AbortSignal {\r\n return this;\r\n }\r\n\r\n get aborted(): boolean {\r\n return this._isAborted;\r\n }\r\n}\r\n\r\n/** Represents a signal that can be monitored to determine if a request has been aborted. */\r\nexport interface AbortSignal {\r\n /** Indicates if the request has been aborted. */\r\n aborted: boolean;\r\n /** Set this to a handler that will be invoked when the request is aborted. */\r\n onabort: (() => void) | null;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { AbortController } from \"./AbortController\";\r\nimport { HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpRequest } from \"./HttpClient\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, sendMessage } from \"./Utils\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\n\r\n// Not exported from 'index', this type is internal.\r\n/** @private */\r\nexport class LongPollingTransport implements ITransport {\r\n private readonly _httpClient: HttpClient;\r\n private readonly _logger: ILogger;\r\n private readonly _options: IHttpConnectionOptions;\r\n private readonly _pollAbort: AbortController;\r\n\r\n private _url?: string;\r\n private _running: boolean;\r\n private _receiving?: Promise;\r\n private _closeError?: Error | unknown;\r\n\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((error?: Error | unknown) => void) | null;\r\n\r\n // This is an internal type, not exported from 'index' so this is really just internal.\r\n public get pollAborted(): boolean {\r\n return this._pollAbort.aborted;\r\n }\r\n\r\n constructor(httpClient: HttpClient, logger: ILogger, options: IHttpConnectionOptions) {\r\n this._httpClient = httpClient;\r\n this._logger = logger;\r\n this._pollAbort = new AbortController();\r\n this._options = options;\r\n\r\n this._running = false;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n\r\n public async connect(url: string, transferFormat: TransferFormat): Promise {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n\r\n this._url = url;\r\n\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Connecting.\");\r\n\r\n // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)\r\n if (transferFormat === TransferFormat.Binary &&\r\n (typeof XMLHttpRequest !== \"undefined\" && typeof new XMLHttpRequest().responseType !== \"string\")) {\r\n throw new Error(\"Binary protocols over XmlHttpRequest not implementing advanced features are not supported.\");\r\n }\r\n\r\n const [name, value] = getUserAgentHeader();\r\n const headers = { [name]: value, ...this._options.headers };\r\n\r\n const pollOptions: HttpRequest = {\r\n abortSignal: this._pollAbort.signal,\r\n headers,\r\n timeout: 100000,\r\n withCredentials: this._options.withCredentials,\r\n };\r\n\r\n if (transferFormat === TransferFormat.Binary) {\r\n pollOptions.responseType = \"arraybuffer\";\r\n }\r\n\r\n // Make initial long polling request\r\n // Server uses first long polling request to finish initializing connection and it returns without data\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this._httpClient.get(pollUrl, pollOptions);\r\n if (response.statusCode !== 200) {\r\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n\r\n // Mark running as false so that the poll immediately ends and runs the close logic\r\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this._running = false;\r\n } else {\r\n this._running = true;\r\n }\r\n\r\n this._receiving = this._poll(this._url, pollOptions);\r\n }\r\n\r\n private async _poll(url: string, pollOptions: HttpRequest): Promise {\r\n try {\r\n while (this._running) {\r\n try {\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this._httpClient.get(pollUrl, pollOptions);\r\n\r\n if (response.statusCode === 204) {\r\n this._logger.log(LogLevel.Information, \"(LongPolling transport) Poll terminated by server.\");\r\n\r\n this._running = false;\r\n } else if (response.statusCode !== 200) {\r\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n\r\n // Unexpected status code\r\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this._running = false;\r\n } else {\r\n // Process the response\r\n if (response.content) {\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent!)}.`);\r\n if (this.onreceive) {\r\n this.onreceive(response.content);\r\n }\r\n } else {\r\n // This is another way timeout manifest.\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n }\r\n }\r\n } catch (e) {\r\n if (!this._running) {\r\n // Log but disregard errors that occur after stopping\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${(e as any).message}`);\r\n } else {\r\n if (e instanceof TimeoutError) {\r\n // Ignore timeouts and reissue the poll.\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n } else {\r\n // Close the connection with the error as the result.\r\n this._closeError = e;\r\n this._running = false;\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Polling complete.\");\r\n\r\n // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.\r\n // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.\r\n if (!this.pollAborted) {\r\n this._raiseOnClose();\r\n }\r\n }\r\n }\r\n\r\n public async send(data: any): Promise {\r\n if (!this._running) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this._logger, \"LongPolling\", this._httpClient, this._url!, data, this._options);\r\n }\r\n\r\n public async stop(): Promise {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stopping polling.\");\r\n\r\n // Tell receiving loop to stop, abort any current request, and then wait for it to finish\r\n this._running = false;\r\n this._pollAbort.abort();\r\n\r\n try {\r\n await this._receiving;\r\n\r\n // Send DELETE to clean up long polling on the server\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);\r\n\r\n const headers: {[k: string]: string} = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n const deleteOptions: HttpRequest = {\r\n headers: { ...headers, ...this._options.headers },\r\n timeout: this._options.timeout,\r\n withCredentials: this._options.withCredentials,\r\n };\r\n\r\n let error;\r\n try {\r\n await this._httpClient.delete(this._url!, deleteOptions);\r\n } catch (err) {\r\n error = err;\r\n }\r\n\r\n if (error) {\r\n if (error instanceof HttpError) {\r\n if (error.statusCode === 404) {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) A 404 response was returned from sending a DELETE request.\");\r\n } else {\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Error sending a DELETE request: ${error}`);\r\n }\r\n }\r\n } else {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) DELETE request accepted.\");\r\n }\r\n\r\n } finally {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stop finished.\");\r\n\r\n // Raise close event here instead of in polling\r\n // It needs to happen after the DELETE request is sent\r\n this._raiseOnClose();\r\n }\r\n }\r\n\r\n private _raiseOnClose() {\r\n if (this.onclose) {\r\n let logMessage = \"(LongPolling transport) Firing onclose event.\";\r\n if (this._closeError) {\r\n logMessage += \" Error: \" + this._closeError;\r\n }\r\n this._logger.log(LogLevel.Trace, logMessage);\r\n this.onclose(this._closeError);\r\n }\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform, sendMessage } from \"./Utils\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\n\r\n/** @private */\r\nexport class ServerSentEventsTransport implements ITransport {\r\n private readonly _httpClient: HttpClient;\r\n private readonly _accessToken: string | undefined;\r\n private readonly _logger: ILogger;\r\n private readonly _options: IHttpConnectionOptions;\r\n private _eventSource?: EventSource;\r\n private _url?: string;\r\n\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((error?: Error | unknown) => void) | null;\r\n\r\n constructor(httpClient: HttpClient, accessToken: string | undefined, logger: ILogger,\r\n options: IHttpConnectionOptions) {\r\n this._httpClient = httpClient;\r\n this._accessToken = accessToken;\r\n this._logger = logger;\r\n this._options = options;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n\r\n public async connect(url: string, transferFormat: TransferFormat): Promise {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n\r\n this._logger.log(LogLevel.Trace, \"(SSE transport) Connecting.\");\r\n\r\n // set url before accessTokenFactory because this._url is only for send and we set the auth header instead of the query string for send\r\n this._url = url;\r\n\r\n if (this._accessToken) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(this._accessToken)}`;\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n let opened = false;\r\n if (transferFormat !== TransferFormat.Text) {\r\n reject(new Error(\"The Server-Sent Events transport only supports the 'Text' transfer format\"));\r\n return;\r\n }\r\n\r\n let eventSource: EventSource;\r\n if (Platform.isBrowser || Platform.isWebWorker) {\r\n eventSource = new this._options.EventSource!(url, { withCredentials: this._options.withCredentials });\r\n } else {\r\n // Non-browser passes cookies via the dictionary\r\n const cookies = this._httpClient.getCookieString(url);\r\n const headers: MessageHeaders = {};\r\n headers.Cookie = cookies;\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n eventSource = new this._options.EventSource!(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers} } as EventSourceInit);\r\n }\r\n\r\n try {\r\n eventSource.onmessage = (e: MessageEvent) => {\r\n if (this.onreceive) {\r\n try {\r\n this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent!)}.`);\r\n this.onreceive(e.data);\r\n } catch (error) {\r\n this._close(error);\r\n return;\r\n }\r\n }\r\n };\r\n\r\n // @ts-ignore: not using event on purpose\r\n eventSource.onerror = (e: Event) => {\r\n // EventSource doesn't give any useful information about server side closes.\r\n if (opened) {\r\n this._close();\r\n } else {\r\n reject(new Error(\"EventSource failed to connect. The connection could not be found on the server,\"\r\n + \" either the connection ID is not present on the server, or a proxy is refusing/buffering the connection.\"\r\n + \" If you have multiple servers check that sticky sessions are enabled.\"));\r\n }\r\n };\r\n\r\n eventSource.onopen = () => {\r\n this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);\r\n this._eventSource = eventSource;\r\n opened = true;\r\n resolve();\r\n };\r\n } catch (e) {\r\n reject(e);\r\n return;\r\n }\r\n });\r\n }\r\n\r\n public async send(data: any): Promise {\r\n if (!this._eventSource) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this._logger, \"SSE\", this._httpClient, this._url!, data, this._options);\r\n }\r\n\r\n public stop(): Promise {\r\n this._close();\r\n return Promise.resolve();\r\n }\r\n\r\n private _close(e?: Error | unknown) {\r\n if (this._eventSource) {\r\n this._eventSource.close();\r\n this._eventSource = undefined;\r\n\r\n if (this.onclose) {\r\n this.onclose(e);\r\n }\r\n }\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { ITransport, TransferFormat } from \"./ITransport\";\r\nimport { WebSocketConstructor } from \"./Polyfills\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform } from \"./Utils\";\r\n\r\n/** @private */\r\nexport class WebSocketTransport implements ITransport {\r\n private readonly _logger: ILogger;\r\n private readonly _accessTokenFactory: (() => string | Promise) | undefined;\r\n private readonly _logMessageContent: boolean;\r\n private readonly _webSocketConstructor: WebSocketConstructor;\r\n private readonly _httpClient: HttpClient;\r\n private _webSocket?: WebSocket;\r\n private _headers: MessageHeaders;\r\n\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((error?: Error) => void) | null;\r\n\r\n constructor(httpClient: HttpClient, accessTokenFactory: (() => string | Promise) | undefined, logger: ILogger,\r\n logMessageContent: boolean, webSocketConstructor: WebSocketConstructor, headers: MessageHeaders) {\r\n this._logger = logger;\r\n this._accessTokenFactory = accessTokenFactory;\r\n this._logMessageContent = logMessageContent;\r\n this._webSocketConstructor = webSocketConstructor;\r\n this._httpClient = httpClient;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n this._headers = headers;\r\n }\r\n\r\n public async connect(url: string, transferFormat: TransferFormat): Promise {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) Connecting.\");\r\n\r\n let token: string;\r\n if (this._accessTokenFactory) {\r\n token = await this._accessTokenFactory();\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n url = url.replace(/^http/, \"ws\");\r\n let webSocket: WebSocket | undefined;\r\n const cookies = this._httpClient.getCookieString(url);\r\n let opened = false;\r\n\r\n if (Platform.isNode || Platform.isReactNative) {\r\n const headers: {[k: string]: string} = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n if (token) {\r\n headers[HeaderNames.Authorization] = `Bearer ${token}`;\r\n }\r\n\r\n if (cookies) {\r\n headers[HeaderNames.Cookie] = cookies;\r\n }\r\n\r\n // Only pass headers when in non-browser environments\r\n webSocket = new this._webSocketConstructor(url, undefined, {\r\n headers: { ...headers, ...this._headers },\r\n });\r\n }\r\n else\r\n {\r\n if (token) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\r\n }\r\n }\r\n\r\n if (!webSocket) {\r\n // Chrome is not happy with passing 'undefined' as protocol\r\n webSocket = new this._webSocketConstructor(url);\r\n }\r\n\r\n if (transferFormat === TransferFormat.Binary) {\r\n webSocket.binaryType = \"arraybuffer\";\r\n }\r\n\r\n webSocket.onopen = (_event: Event) => {\r\n this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);\r\n this._webSocket = webSocket;\r\n opened = true;\r\n resolve();\r\n };\r\n\r\n webSocket.onerror = (event: Event) => {\r\n let error: any = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n } else {\r\n error = \"There was an error with the transport\";\r\n }\r\n\r\n this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);\r\n };\r\n\r\n webSocket.onmessage = (message: MessageEvent) => {\r\n this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);\r\n if (this.onreceive) {\r\n try {\r\n this.onreceive(message.data);\r\n } catch (error) {\r\n this._close(error);\r\n return;\r\n }\r\n }\r\n };\r\n\r\n webSocket.onclose = (event: CloseEvent) => {\r\n // Don't call close handler if connection was never established\r\n // We'll reject the connect call instead\r\n if (opened) {\r\n this._close(event);\r\n } else {\r\n let error: any = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n } else {\r\n error = \"WebSocket failed to connect. The connection could not be found on the server,\"\r\n + \" either the endpoint may not be a SignalR endpoint,\"\r\n + \" the connection ID is not present on the server, or there is a proxy blocking WebSockets.\"\r\n + \" If you have multiple servers check that sticky sessions are enabled.\";\r\n }\r\n\r\n reject(new Error(error));\r\n }\r\n };\r\n });\r\n }\r\n\r\n public send(data: any): Promise {\r\n if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {\r\n this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);\r\n this._webSocket.send(data);\r\n return Promise.resolve();\r\n }\r\n\r\n return Promise.reject(\"WebSocket is not in the OPEN state\");\r\n }\r\n\r\n public stop(): Promise {\r\n if (this._webSocket) {\r\n // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning\r\n // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects\r\n this._close(undefined);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n private _close(event: CloseEvent | Error | unknown): void {\r\n // webSocket will be null if the transport did not start successfully\r\n if (this._webSocket) {\r\n // Clear websocket handlers because we are considering the socket closed now\r\n this._webSocket.onclose = () => {};\r\n this._webSocket.onmessage = () => {};\r\n this._webSocket.onerror = () => {};\r\n this._webSocket.close();\r\n this._webSocket = undefined;\r\n }\r\n\r\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) socket closed.\");\r\n\r\n if (this.onclose) {\r\n if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {\r\n this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || \"no reason given\"}).`));\r\n } else if (event instanceof Error) {\r\n this.onclose(event);\r\n } else {\r\n this.onclose();\r\n }\r\n }\r\n }\r\n\r\n private _isCloseEvent(event?: any): event is CloseEvent {\r\n return event && typeof event.wasClean === \"boolean\" && typeof event.code === \"number\";\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { AccessTokenHttpClient } from \"./AccessTokenHttpClient\";\r\nimport { DefaultHttpClient } from \"./DefaultHttpClient\";\r\nimport { AggregateErrors, DisabledTransportError, FailedToNegotiateWithServerError, FailedToStartTransportError, HttpError, UnsupportedTransportError, AbortError } from \"./Errors\";\r\nimport { IConnection } from \"./IConnection\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { HttpTransportType, ITransport, TransferFormat } from \"./ITransport\";\r\nimport { LongPollingTransport } from \"./LongPollingTransport\";\r\nimport { ServerSentEventsTransport } from \"./ServerSentEventsTransport\";\r\nimport { Arg, createLogger, getUserAgentHeader, Platform } from \"./Utils\";\r\nimport { WebSocketTransport } from \"./WebSocketTransport\";\r\n\r\n/** @private */\r\nconst enum ConnectionState {\r\n Connecting = \"Connecting\",\r\n Connected = \"Connected\",\r\n Disconnected = \"Disconnected\",\r\n Disconnecting = \"Disconnecting\",\r\n}\r\n\r\n/** @private */\r\nexport interface INegotiateResponse {\r\n connectionId?: string;\r\n connectionToken?: string;\r\n negotiateVersion?: number;\r\n availableTransports?: IAvailableTransport[];\r\n url?: string;\r\n accessToken?: string;\r\n error?: string;\r\n useStatefulReconnect?: boolean;\r\n}\r\n\r\n/** @private */\r\nexport interface IAvailableTransport {\r\n transport: keyof typeof HttpTransportType;\r\n transferFormats: (keyof typeof TransferFormat)[];\r\n}\r\n\r\nconst MAX_REDIRECTS = 100;\r\n\r\n/** @private */\r\nexport class HttpConnection implements IConnection {\r\n private _connectionState: ConnectionState;\r\n // connectionStarted is tracked independently from connectionState, so we can check if the\r\n // connection ever did successfully transition from connecting to connected before disconnecting.\r\n private _connectionStarted: boolean;\r\n private readonly _httpClient: AccessTokenHttpClient;\r\n private readonly _logger: ILogger;\r\n private readonly _options: IHttpConnectionOptions;\r\n // Needs to not start with _ to be available for tests\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n private transport?: ITransport;\r\n private _startInternalPromise?: Promise;\r\n private _stopPromise?: Promise;\r\n private _stopPromiseResolver: (value?: PromiseLike) => void = () => {};\r\n private _stopError?: Error;\r\n private _accessTokenFactory?: () => string | Promise;\r\n private _sendQueue?: TransportSendQueue;\r\n\r\n public readonly features: any = {};\r\n public baseUrl: string;\r\n public connectionId?: string;\r\n public onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n public onclose: ((e?: Error) => void) | null;\r\n\r\n private readonly _negotiateVersion: number = 1;\r\n\r\n constructor(url: string, options: IHttpConnectionOptions = {}) {\r\n Arg.isRequired(url, \"url\");\r\n\r\n this._logger = createLogger(options.logger);\r\n this.baseUrl = this._resolveUrl(url);\r\n\r\n options = options || {};\r\n options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;\r\n if (typeof options.withCredentials === \"boolean\" || options.withCredentials === undefined) {\r\n options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;\r\n } else {\r\n throw new Error(\"withCredentials option was not a 'boolean' or 'undefined' value\");\r\n }\r\n options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout;\r\n\r\n let webSocketModule: any = null;\r\n let eventSourceModule: any = null;\r\n\r\n if (Platform.isNode && typeof require !== \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n webSocketModule = requireFunc(\"ws\");\r\n eventSourceModule = requireFunc(\"eventsource\");\r\n }\r\n\r\n if (!Platform.isNode && typeof WebSocket !== \"undefined\" && !options.WebSocket) {\r\n options.WebSocket = WebSocket;\r\n } else if (Platform.isNode && !options.WebSocket) {\r\n if (webSocketModule) {\r\n options.WebSocket = webSocketModule;\r\n }\r\n }\r\n\r\n if (!Platform.isNode && typeof EventSource !== \"undefined\" && !options.EventSource) {\r\n options.EventSource = EventSource;\r\n } else if (Platform.isNode && !options.EventSource) {\r\n if (typeof eventSourceModule !== \"undefined\") {\r\n options.EventSource = eventSourceModule;\r\n }\r\n }\r\n\r\n this._httpClient = new AccessTokenHttpClient(options.httpClient || new DefaultHttpClient(this._logger), options.accessTokenFactory);\r\n this._connectionState = ConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n this._options = options;\r\n\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n\r\n public start(): Promise;\r\n public start(transferFormat: TransferFormat): Promise;\r\n public async start(transferFormat?: TransferFormat): Promise {\r\n transferFormat = transferFormat || TransferFormat.Binary;\r\n\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n\r\n this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);\r\n\r\n if (this._connectionState !== ConnectionState.Disconnected) {\r\n return Promise.reject(new Error(\"Cannot start an HttpConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n\r\n this._connectionState = ConnectionState.Connecting;\r\n\r\n this._startInternalPromise = this._startInternal(transferFormat);\r\n await this._startInternalPromise;\r\n\r\n // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.\r\n if (this._connectionState as any === ConnectionState.Disconnecting) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"Failed to start the HttpConnection before stop() was called.\";\r\n this._logger.log(LogLevel.Error, message);\r\n\r\n // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.\r\n await this._stopPromise;\r\n\r\n return Promise.reject(new AbortError(message));\r\n } else if (this._connectionState as any !== ConnectionState.Connected) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!\";\r\n this._logger.log(LogLevel.Error, message);\r\n return Promise.reject(new AbortError(message));\r\n }\r\n\r\n this._connectionStarted = true;\r\n }\r\n\r\n public send(data: string | ArrayBuffer): Promise {\r\n if (this._connectionState !== ConnectionState.Connected) {\r\n return Promise.reject(new Error(\"Cannot send data if the connection is not in the 'Connected' State.\"));\r\n }\r\n\r\n if (!this._sendQueue) {\r\n this._sendQueue = new TransportSendQueue(this.transport!);\r\n }\r\n\r\n // Transport will not be null if state is connected\r\n return this._sendQueue.send(data);\r\n }\r\n\r\n public async stop(error?: Error): Promise {\r\n if (this._connectionState === ConnectionState.Disconnected) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n\r\n if (this._connectionState === ConnectionState.Disconnecting) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this._stopPromise;\r\n }\r\n\r\n this._connectionState = ConnectionState.Disconnecting;\r\n\r\n this._stopPromise = new Promise((resolve) => {\r\n // Don't complete stop() until stopConnection() completes.\r\n this._stopPromiseResolver = resolve;\r\n });\r\n\r\n // stopInternal should never throw so just observe it.\r\n await this._stopInternal(error);\r\n await this._stopPromise;\r\n }\r\n\r\n private async _stopInternal(error?: Error): Promise {\r\n // Set error as soon as possible otherwise there is a race between\r\n // the transport closing and providing an error and the error from a close message\r\n // We would prefer the close message error.\r\n this._stopError = error;\r\n\r\n try {\r\n await this._startInternalPromise;\r\n } catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n\r\n // The transport's onclose will trigger stopConnection which will run our onclose event.\r\n // The transport should always be set if currently connected. If it wasn't set, it's likely because\r\n // stop was called during start() and start() failed.\r\n if (this.transport) {\r\n try {\r\n await this.transport.stop();\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);\r\n this._stopConnection();\r\n }\r\n\r\n this.transport = undefined;\r\n } else {\r\n this._logger.log(LogLevel.Debug, \"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.\");\r\n }\r\n }\r\n\r\n private async _startInternal(transferFormat: TransferFormat): Promise {\r\n // Store the original base url and the access token factory since they may change\r\n // as part of negotiating\r\n let url = this.baseUrl;\r\n this._accessTokenFactory = this._options.accessTokenFactory;\r\n this._httpClient._accessTokenFactory = this._accessTokenFactory;\r\n\r\n try {\r\n if (this._options.skipNegotiation) {\r\n if (this._options.transport === HttpTransportType.WebSockets) {\r\n // No need to add a connection ID in this case\r\n this.transport = this._constructTransport(HttpTransportType.WebSockets);\r\n // We should just call connect directly in this case.\r\n // No fallback or negotiate in this case.\r\n await this._startTransport(url, transferFormat);\r\n } else {\r\n throw new Error(\"Negotiation can only be skipped when using the WebSocket transport directly.\");\r\n }\r\n } else {\r\n let negotiateResponse: INegotiateResponse | null = null;\r\n let redirects = 0;\r\n\r\n do {\r\n negotiateResponse = await this._getNegotiationResponse(url);\r\n // the user tries to stop the connection when it is being started\r\n if (this._connectionState === ConnectionState.Disconnecting || this._connectionState === ConnectionState.Disconnected) {\r\n throw new AbortError(\"The connection was stopped during negotiation.\");\r\n }\r\n\r\n if (negotiateResponse.error) {\r\n throw new Error(negotiateResponse.error);\r\n }\r\n\r\n if ((negotiateResponse as any).ProtocolVersion) {\r\n 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.\");\r\n }\r\n\r\n if (negotiateResponse.url) {\r\n url = negotiateResponse.url;\r\n }\r\n\r\n if (negotiateResponse.accessToken) {\r\n // Replace the current access token factory with one that uses\r\n // the returned access token\r\n const accessToken = negotiateResponse.accessToken;\r\n this._accessTokenFactory = () => accessToken;\r\n // 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\r\n this._httpClient._accessToken = accessToken;\r\n this._httpClient._accessTokenFactory = undefined;\r\n }\r\n\r\n redirects++;\r\n }\r\n while (negotiateResponse.url && redirects < MAX_REDIRECTS);\r\n\r\n if (redirects === MAX_REDIRECTS && negotiateResponse.url) {\r\n throw new Error(\"Negotiate redirection limit exceeded.\");\r\n }\r\n\r\n await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);\r\n }\r\n\r\n if (this.transport instanceof LongPollingTransport) {\r\n this.features.inherentKeepAlive = true;\r\n }\r\n\r\n if (this._connectionState === ConnectionState.Connecting) {\r\n // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.\r\n // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.\r\n this._logger.log(LogLevel.Debug, \"The HttpConnection connected successfully.\");\r\n this._connectionState = ConnectionState.Connected;\r\n }\r\n\r\n // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.\r\n // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()\r\n // will transition to the disconnected state. start() will wait for the transition using the stopPromise.\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, \"Failed to start the connection: \" + e);\r\n this._connectionState = ConnectionState.Disconnected;\r\n this.transport = undefined;\r\n\r\n // if start fails, any active calls to stop assume that start will complete the stop promise\r\n this._stopPromiseResolver();\r\n return Promise.reject(e);\r\n }\r\n }\r\n\r\n private async _getNegotiationResponse(url: string): Promise {\r\n const headers: {[k: string]: string} = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n\r\n const negotiateUrl = this._resolveNegotiateUrl(url);\r\n this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);\r\n try {\r\n const response = await this._httpClient.post(negotiateUrl, {\r\n content: \"\",\r\n headers: { ...headers, ...this._options.headers },\r\n timeout: this._options.timeout,\r\n withCredentials: this._options.withCredentials,\r\n });\r\n\r\n if (response.statusCode !== 200) {\r\n return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));\r\n }\r\n\r\n const negotiateResponse = JSON.parse(response.content as string) as INegotiateResponse;\r\n if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {\r\n // Negotiate version 0 doesn't use connectionToken\r\n // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version\r\n negotiateResponse.connectionToken = negotiateResponse.connectionId;\r\n }\r\n\r\n if (negotiateResponse.useStatefulReconnect && this._options._useStatefulReconnect !== true) {\r\n return Promise.reject(new FailedToNegotiateWithServerError(\"Client didn't negotiate Stateful Reconnect but the server did.\"));\r\n }\r\n\r\n return negotiateResponse;\r\n } catch (e) {\r\n let errorMessage = \"Failed to complete negotiation with the server: \" + e;\r\n if (e instanceof HttpError) {\r\n if (e.statusCode === 404) {\r\n errorMessage = errorMessage + \" Either this is not a SignalR endpoint or there is a proxy blocking the connection.\";\r\n }\r\n }\r\n this._logger.log(LogLevel.Error, errorMessage);\r\n\r\n return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));\r\n }\r\n }\r\n\r\n private _createConnectUrl(url: string, connectionToken: string | null | undefined) {\r\n if (!connectionToken) {\r\n return url;\r\n }\r\n\r\n return url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + `id=${connectionToken}`;\r\n }\r\n\r\n private async _createTransport(url: string, requestedTransport: HttpTransportType | ITransport | undefined, negotiateResponse: INegotiateResponse, requestedTransferFormat: TransferFormat): Promise {\r\n let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);\r\n if (this._isITransport(requestedTransport)) {\r\n this._logger.log(LogLevel.Debug, \"Connection was provided an instance of ITransport, using that directly.\");\r\n this.transport = requestedTransport;\r\n await this._startTransport(connectUrl, requestedTransferFormat);\r\n\r\n this.connectionId = negotiateResponse.connectionId;\r\n return;\r\n }\r\n\r\n const transportExceptions: any[] = [];\r\n const transports = negotiateResponse.availableTransports || [];\r\n let negotiate: INegotiateResponse | undefined = negotiateResponse;\r\n for (const endpoint of transports) {\r\n const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat,\r\n negotiate?.useStatefulReconnect === true);\r\n if (transportOrError instanceof Error) {\r\n // Store the error and continue, we don't want to cause a re-negotiate in these cases\r\n transportExceptions.push(`${endpoint.transport} failed:`);\r\n transportExceptions.push(transportOrError);\r\n } else if (this._isITransport(transportOrError)) {\r\n this.transport = transportOrError;\r\n if (!negotiate) {\r\n try {\r\n negotiate = await this._getNegotiationResponse(url);\r\n } catch (ex) {\r\n return Promise.reject(ex);\r\n }\r\n connectUrl = this._createConnectUrl(url, negotiate.connectionToken);\r\n }\r\n try {\r\n await this._startTransport(connectUrl, requestedTransferFormat);\r\n this.connectionId = negotiate.connectionId;\r\n return;\r\n } catch (ex) {\r\n this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);\r\n negotiate = undefined;\r\n transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));\r\n\r\n if (this._connectionState !== ConnectionState.Connecting) {\r\n const message = \"Failed to select transport before stop() was called.\";\r\n this._logger.log(LogLevel.Debug, message);\r\n return Promise.reject(new AbortError(message));\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (transportExceptions.length > 0) {\r\n return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(\" \")}`, transportExceptions));\r\n }\r\n return Promise.reject(new Error(\"None of the transports supported by the client are supported by the server.\"));\r\n }\r\n\r\n private _constructTransport(transport: HttpTransportType): ITransport {\r\n switch (transport) {\r\n case HttpTransportType.WebSockets:\r\n if (!this._options.WebSocket) {\r\n throw new Error(\"'WebSocket' is not supported in your environment.\");\r\n }\r\n return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent!,\r\n this._options.WebSocket, this._options.headers || {});\r\n case HttpTransportType.ServerSentEvents:\r\n if (!this._options.EventSource) {\r\n throw new Error(\"'EventSource' is not supported in your environment.\");\r\n }\r\n return new ServerSentEventsTransport(this._httpClient, this._httpClient._accessToken, this._logger, this._options);\r\n case HttpTransportType.LongPolling:\r\n return new LongPollingTransport(this._httpClient, this._logger, this._options);\r\n default:\r\n throw new Error(`Unknown transport: ${transport}.`);\r\n }\r\n }\r\n\r\n private _startTransport(url: string, transferFormat: TransferFormat): Promise {\r\n this.transport!.onreceive = this.onreceive;\r\n if (this.features.reconnect) {\r\n this.transport!.onclose = async (e) => {\r\n let callStop = false;\r\n if (this.features.reconnect) {\r\n try {\r\n this.features.disconnected();\r\n await this.transport!.connect(url, transferFormat);\r\n await this.features.resend();\r\n } catch {\r\n callStop = true;\r\n }\r\n } else {\r\n this._stopConnection(e);\r\n return;\r\n }\r\n\r\n if (callStop) {\r\n this._stopConnection(e);\r\n }\r\n };\r\n } else {\r\n this.transport!.onclose = (e) => this._stopConnection(e);\r\n }\r\n return this.transport!.connect(url, transferFormat);\r\n }\r\n\r\n private _resolveTransportOrError(endpoint: IAvailableTransport, requestedTransport: HttpTransportType | undefined,\r\n requestedTransferFormat: TransferFormat, useStatefulReconnect: boolean): ITransport | Error | unknown {\r\n const transport = HttpTransportType[endpoint.transport];\r\n if (transport === null || transport === undefined) {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n } else {\r\n if (transportMatches(requestedTransport, transport)) {\r\n const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);\r\n if (transferFormats.indexOf(requestedTransferFormat) >= 0) {\r\n if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) ||\r\n (transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);\r\n return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);\r\n } else {\r\n this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);\r\n try {\r\n this.features.reconnect = transport === HttpTransportType.WebSockets ? useStatefulReconnect : undefined;\r\n return this._constructTransport(transport);\r\n } catch (ex) {\r\n return ex;\r\n }\r\n }\r\n } else {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);\r\n return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);\r\n }\r\n } else {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);\r\n return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);\r\n }\r\n }\r\n }\r\n\r\n private _isITransport(transport: any): transport is ITransport {\r\n return transport && typeof (transport) === \"object\" && \"connect\" in transport;\r\n }\r\n\r\n private _stopConnection(error?: Error): void {\r\n this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);\r\n\r\n this.transport = undefined;\r\n\r\n // If we have a stopError, it takes precedence over the error from the transport\r\n error = this._stopError || error;\r\n this._stopError = undefined;\r\n\r\n if (this._connectionState === ConnectionState.Disconnected) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);\r\n return;\r\n }\r\n\r\n if (this._connectionState === ConnectionState.Connecting) {\r\n this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);\r\n throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);\r\n }\r\n\r\n if (this._connectionState === ConnectionState.Disconnecting) {\r\n // A call to stop() induced this call to stopConnection and needs to be completed.\r\n // Any stop() awaiters will be scheduled to continue after the onclose callback fires.\r\n this._stopPromiseResolver();\r\n }\r\n\r\n if (error) {\r\n this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);\r\n } else {\r\n this._logger.log(LogLevel.Information, \"Connection disconnected.\");\r\n }\r\n\r\n if (this._sendQueue) {\r\n this._sendQueue.stop().catch((e) => {\r\n this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);\r\n });\r\n this._sendQueue = undefined;\r\n }\r\n\r\n this.connectionId = undefined;\r\n this._connectionState = ConnectionState.Disconnected;\r\n\r\n if (this._connectionStarted) {\r\n this._connectionStarted = false;\r\n try {\r\n if (this.onclose) {\r\n this.onclose(error);\r\n }\r\n } catch (e) {\r\n this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n\r\n private _resolveUrl(url: string): string {\r\n // startsWith is not supported in IE\r\n if (url.lastIndexOf(\"https://\", 0) === 0 || url.lastIndexOf(\"http://\", 0) === 0) {\r\n return url;\r\n }\r\n\r\n if (!Platform.isBrowser) {\r\n throw new Error(`Cannot resolve '${url}'.`);\r\n }\r\n\r\n // Setting the url to the href propery of an anchor tag handles normalization\r\n // for us. There are 3 main cases.\r\n // 1. Relative path normalization e.g \"b\" -> \"http://localhost:5000/a/b\"\r\n // 2. Absolute path normalization e.g \"/a/b\" -> \"http://localhost:5000/a/b\"\r\n // 3. Networkpath reference normalization e.g \"//localhost:5000/a/b\" -> \"http://localhost:5000/a/b\"\r\n const aTag = window.document.createElement(\"a\");\r\n aTag.href = url;\r\n\r\n this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);\r\n return aTag.href;\r\n }\r\n\r\n private _resolveNegotiateUrl(url: string): string {\r\n const negotiateUrl = new URL(url);\r\n\r\n if (negotiateUrl.pathname.endsWith('/')) {\r\n negotiateUrl.pathname += \"negotiate\";\r\n } else {\r\n negotiateUrl.pathname += \"/negotiate\";\r\n }\r\n const searchParams = new URLSearchParams(negotiateUrl.searchParams);\r\n\r\n if (!searchParams.has(\"negotiateVersion\")) {\r\n searchParams.append(\"negotiateVersion\", this._negotiateVersion.toString());\r\n }\r\n\r\n if (searchParams.has(\"useStatefulReconnect\")) {\r\n if (searchParams.get(\"useStatefulReconnect\") === \"true\") {\r\n this._options._useStatefulReconnect = true;\r\n }\r\n } else if (this._options._useStatefulReconnect === true) {\r\n searchParams.append(\"useStatefulReconnect\", \"true\");\r\n }\r\n\r\n negotiateUrl.search = searchParams.toString();\r\n\r\n return negotiateUrl.toString();\r\n }\r\n}\r\n\r\nfunction transportMatches(requestedTransport: HttpTransportType | undefined, actualTransport: HttpTransportType) {\r\n return !requestedTransport || ((actualTransport & requestedTransport) !== 0);\r\n}\r\n\r\n/** @private */\r\nexport class TransportSendQueue {\r\n private _buffer: any[] = [];\r\n private _sendBufferedData: PromiseSource;\r\n private _executing: boolean = true;\r\n private _transportResult?: PromiseSource;\r\n private _sendLoopPromise: Promise;\r\n\r\n constructor(private readonly _transport: ITransport) {\r\n this._sendBufferedData = new PromiseSource();\r\n this._transportResult = new PromiseSource();\r\n\r\n this._sendLoopPromise = this._sendLoop();\r\n }\r\n\r\n public send(data: string | ArrayBuffer): Promise {\r\n this._bufferData(data);\r\n if (!this._transportResult) {\r\n this._transportResult = new PromiseSource();\r\n }\r\n return this._transportResult.promise;\r\n }\r\n\r\n public stop(): Promise {\r\n this._executing = false;\r\n this._sendBufferedData.resolve();\r\n return this._sendLoopPromise;\r\n }\r\n\r\n private _bufferData(data: string | ArrayBuffer): void {\r\n if (this._buffer.length && typeof(this._buffer[0]) !== typeof(data)) {\r\n throw new Error(`Expected data to be of type ${typeof(this._buffer)} but was of type ${typeof(data)}`);\r\n }\r\n\r\n this._buffer.push(data);\r\n this._sendBufferedData.resolve();\r\n }\r\n\r\n private async _sendLoop(): Promise {\r\n while (true) {\r\n await this._sendBufferedData.promise;\r\n\r\n if (!this._executing) {\r\n if (this._transportResult) {\r\n this._transportResult.reject(\"Connection stopped.\");\r\n }\r\n\r\n break;\r\n }\r\n\r\n this._sendBufferedData = new PromiseSource();\r\n\r\n const transportResult = this._transportResult!;\r\n this._transportResult = undefined;\r\n\r\n const data = typeof(this._buffer[0]) === \"string\" ?\r\n this._buffer.join(\"\") :\r\n TransportSendQueue._concatBuffers(this._buffer);\r\n\r\n this._buffer.length = 0;\r\n\r\n try {\r\n await this._transport.send(data);\r\n transportResult.resolve();\r\n } catch (error) {\r\n transportResult.reject(error);\r\n }\r\n }\r\n }\r\n\r\n private static _concatBuffers(arrayBuffers: ArrayBuffer[]): ArrayBuffer {\r\n const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);\r\n const result = new Uint8Array(totalLength);\r\n let offset = 0;\r\n for (const item of arrayBuffers) {\r\n result.set(new Uint8Array(item), offset);\r\n offset += item.byteLength;\r\n }\r\n\r\n return result.buffer;\r\n }\r\n}\r\n\r\nclass PromiseSource {\r\n private _resolver?: () => void;\r\n private _rejecter!: (reason?: any) => void;\r\n public promise: Promise;\r\n\r\n constructor() {\r\n this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);\r\n }\r\n\r\n public resolve(): void {\r\n this._resolver!();\r\n }\r\n\r\n public reject(reason?: any): void {\r\n this._rejecter!(reason);\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { AckMessage, CompletionMessage, HubMessage, IHubProtocol, InvocationMessage, MessageType, SequenceMessage, StreamItemMessage } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\n\r\nconst JSON_HUB_PROTOCOL_NAME: string = \"json\";\r\n\r\n/** Implements the JSON Hub Protocol. */\r\nexport class JsonHubProtocol implements IHubProtocol {\r\n\r\n /** @inheritDoc */\r\n public readonly name: string = JSON_HUB_PROTOCOL_NAME;\r\n /** @inheritDoc */\r\n public readonly version: number = 2;\r\n\r\n /** @inheritDoc */\r\n public readonly transferFormat: TransferFormat = TransferFormat.Text;\r\n\r\n /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * @param {string} input A string containing the serialized representation.\r\n * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.\r\n */\r\n public parseMessages(input: string, logger: ILogger): HubMessage[] {\r\n // The interface does allow \"ArrayBuffer\" to be passed in, but this implementation does not. So let's throw a useful error.\r\n if (typeof input !== \"string\") {\r\n throw new Error(\"Invalid input for JSON hub protocol. Expected a string.\");\r\n }\r\n\r\n if (!input) {\r\n return [];\r\n }\r\n\r\n if (logger === null) {\r\n logger = NullLogger.instance;\r\n }\r\n\r\n // Parse the messages\r\n const messages = TextMessageFormat.parse(input);\r\n\r\n const hubMessages = [];\r\n for (const message of messages) {\r\n const parsedMessage = JSON.parse(message) as HubMessage;\r\n if (typeof parsedMessage.type !== \"number\") {\r\n throw new Error(\"Invalid payload.\");\r\n }\r\n switch (parsedMessage.type) {\r\n case MessageType.Invocation:\r\n this._isInvocationMessage(parsedMessage);\r\n break;\r\n case MessageType.StreamItem:\r\n this._isStreamItemMessage(parsedMessage);\r\n break;\r\n case MessageType.Completion:\r\n this._isCompletionMessage(parsedMessage);\r\n break;\r\n case MessageType.Ping:\r\n // Single value, no need to validate\r\n break;\r\n case MessageType.Close:\r\n // All optional values, no need to validate\r\n break;\r\n case MessageType.Ack:\r\n this._isAckMessage(parsedMessage);\r\n break;\r\n case MessageType.Sequence:\r\n this._isSequenceMessage(parsedMessage);\r\n break;\r\n default:\r\n // Future protocol changes can add message types, old clients can ignore them\r\n logger.log(LogLevel.Information, \"Unknown message type '\" + parsedMessage.type + \"' ignored.\");\r\n continue;\r\n }\r\n hubMessages.push(parsedMessage);\r\n }\r\n\r\n return hubMessages;\r\n }\r\n\r\n /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.\r\n *\r\n * @param {HubMessage} message The message to write.\r\n * @returns {string} A string containing the serialized representation of the message.\r\n */\r\n public writeMessage(message: HubMessage): string {\r\n return TextMessageFormat.write(JSON.stringify(message));\r\n }\r\n\r\n private _isInvocationMessage(message: InvocationMessage): void {\r\n this._assertNotEmptyString(message.target, \"Invalid payload for Invocation message.\");\r\n\r\n if (message.invocationId !== undefined) {\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Invocation message.\");\r\n }\r\n }\r\n\r\n private _isStreamItemMessage(message: StreamItemMessage): void {\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for StreamItem message.\");\r\n\r\n if (message.item === undefined) {\r\n throw new Error(\"Invalid payload for StreamItem message.\");\r\n }\r\n }\r\n\r\n private _isCompletionMessage(message: CompletionMessage): void {\r\n if (message.result && message.error) {\r\n throw new Error(\"Invalid payload for Completion message.\");\r\n }\r\n\r\n if (!message.result && message.error) {\r\n this._assertNotEmptyString(message.error, \"Invalid payload for Completion message.\");\r\n }\r\n\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Completion message.\");\r\n }\r\n\r\n private _isAckMessage(message: AckMessage): void {\r\n if (typeof message.sequenceId !== 'number') {\r\n throw new Error(\"Invalid SequenceId for Ack message.\");\r\n }\r\n }\r\n\r\n private _isSequenceMessage(message: SequenceMessage): void {\r\n if (typeof message.sequenceId !== 'number') {\r\n throw new Error(\"Invalid SequenceId for Sequence message.\");\r\n }\r\n }\r\n\r\n private _assertNotEmptyString(value: any, errorMessage: string): void {\r\n if (typeof value !== \"string\" || value === \"\") {\r\n throw new Error(errorMessage);\r\n }\r\n }\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nimport { DefaultReconnectPolicy } from \"./DefaultReconnectPolicy\";\r\nimport { HttpConnection } from \"./HttpConnection\";\r\nimport { HubConnection } from \"./HubConnection\";\r\nimport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\nimport { IHubProtocol } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { IRetryPolicy } from \"./IRetryPolicy\";\r\nimport { IStatefulReconnectOptions } from \"./IStatefulReconnectOptions\";\r\nimport { HttpTransportType } from \"./ITransport\";\r\nimport { JsonHubProtocol } from \"./JsonHubProtocol\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { Arg, ConsoleLogger } from \"./Utils\";\r\n\r\nconst LogLevelNameMapping: {[k: string]: LogLevel} = {\r\n trace: LogLevel.Trace,\r\n debug: LogLevel.Debug,\r\n info: LogLevel.Information,\r\n information: LogLevel.Information,\r\n warn: LogLevel.Warning,\r\n warning: LogLevel.Warning,\r\n error: LogLevel.Error,\r\n critical: LogLevel.Critical,\r\n none: LogLevel.None,\r\n};\r\n\r\nfunction parseLogLevel(name: string): LogLevel {\r\n // Case-insensitive matching via lower-casing\r\n // Yes, I know case-folding is a complicated problem in Unicode, but we only support\r\n // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.\r\n const mapping = LogLevelNameMapping[name.toLowerCase()];\r\n if (typeof mapping !== \"undefined\") {\r\n return mapping;\r\n } else {\r\n throw new Error(`Unknown log level: ${name}`);\r\n }\r\n}\r\n\r\n/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */\r\nexport class HubConnectionBuilder {\r\n private _serverTimeoutInMilliseconds?: number;\r\n private _keepAliveIntervalInMilliseconds ?: number;\r\n\r\n /** @internal */\r\n public protocol?: IHubProtocol;\r\n /** @internal */\r\n public httpConnectionOptions?: IHttpConnectionOptions;\r\n /** @internal */\r\n public url?: string;\r\n /** @internal */\r\n public logger?: ILogger;\r\n\r\n /** If defined, this indicates the client should automatically attempt to reconnect if the connection is lost. */\r\n /** @internal */\r\n public reconnectPolicy?: IRetryPolicy;\r\n\r\n private _statefulReconnectBufferSize?: number;\r\n\r\n /** Configures console logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {LogLevel} logLevel The minimum level of messages to log. Anything at this level, or a more severe level, will be logged.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logLevel: LogLevel): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {ILogger} logger An object implementing the {@link @microsoft/signalr.ILogger} interface, which will be used to write all log messages.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logger: ILogger): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {string} logLevel A string representing a LogLevel setting a minimum level of messages to log.\r\n * See {@link https://learn.microsoft.com/aspnet/core/signalr/configuration#configure-logging|the documentation for client logging configuration} for more details.\r\n */\r\n public configureLogging(logLevel: string): HubConnectionBuilder;\r\n\r\n /** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @param {LogLevel | string | ILogger} logging A {@link @microsoft/signalr.LogLevel}, a string representing a LogLevel, or an object implementing the {@link @microsoft/signalr.ILogger} interface.\r\n * See {@link https://learn.microsoft.com/aspnet/core/signalr/configuration#configure-logging|the documentation for client logging configuration} for more details.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public configureLogging(logging: LogLevel | string | ILogger): HubConnectionBuilder;\r\n public configureLogging(logging: LogLevel | string | ILogger): HubConnectionBuilder {\r\n Arg.isRequired(logging, \"logging\");\r\n\r\n if (isLogger(logging)) {\r\n this.logger = logging;\r\n } else if (typeof logging === \"string\") {\r\n const logLevel = parseLogLevel(logging);\r\n this.logger = new ConsoleLogger(logLevel);\r\n } else {\r\n this.logger = new ConsoleLogger(logging);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use HTTP-based transports to connect to the specified URL.\r\n *\r\n * The transport will be selected automatically based on what the server and client support.\r\n *\r\n * @param {string} url The URL the connection will use.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified HTTP-based transport to connect to the specified URL.\r\n *\r\n * @param {string} url The URL the connection will use.\r\n * @param {HttpTransportType} transportType The specific transport to use.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string, transportType: HttpTransportType): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use HTTP-based transports to connect to the specified URL.\r\n *\r\n * @param {string} url The URL the connection will use.\r\n * @param {IHttpConnectionOptions} options An options object used to configure the connection.\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withUrl(url: string, options: IHttpConnectionOptions): HubConnectionBuilder;\r\n public withUrl(url: string, transportTypeOrOptions?: IHttpConnectionOptions | HttpTransportType): HubConnectionBuilder {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isNotEmpty(url, \"url\");\r\n\r\n this.url = url;\r\n\r\n // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed\r\n // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.\r\n if (typeof transportTypeOrOptions === \"object\") {\r\n this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };\r\n } else {\r\n this.httpConnectionOptions = {\r\n ...this.httpConnectionOptions,\r\n transport: transportTypeOrOptions,\r\n };\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.\r\n *\r\n * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.\r\n */\r\n public withHubProtocol(protocol: IHubProtocol): HubConnectionBuilder {\r\n Arg.isRequired(protocol, \"protocol\");\r\n\r\n this.protocol = protocol;\r\n return this;\r\n }\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.\r\n * By default, the client will wait 0, 2, 10 and 30 seconds respectively before trying up to 4 reconnect attempts.\r\n */\r\n public withAutomaticReconnect(): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.\r\n *\r\n * @param {number[]} retryDelays An array containing the delays in milliseconds before trying each reconnect attempt.\r\n * The length of the array represents how many failed reconnect attempts it takes before the client will stop attempting to reconnect.\r\n */\r\n public withAutomaticReconnect(retryDelays: number[]): HubConnectionBuilder;\r\n\r\n /** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.\r\n *\r\n * @param {IRetryPolicy} reconnectPolicy An {@link @microsoft/signalR.IRetryPolicy} that controls the timing and number of reconnect attempts.\r\n */\r\n public withAutomaticReconnect(reconnectPolicy: IRetryPolicy): HubConnectionBuilder;\r\n public withAutomaticReconnect(retryDelaysOrReconnectPolicy?: number[] | IRetryPolicy): HubConnectionBuilder {\r\n if (this.reconnectPolicy) {\r\n throw new Error(\"A reconnectPolicy has already been set.\");\r\n }\r\n\r\n if (!retryDelaysOrReconnectPolicy) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy();\r\n } else if (Array.isArray(retryDelaysOrReconnectPolicy)) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);\r\n } else {\r\n this.reconnectPolicy = retryDelaysOrReconnectPolicy;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Configures {@link @microsoft/signalr.HubConnection.serverTimeoutInMilliseconds} for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withServerTimeout(milliseconds: number): HubConnectionBuilder {\r\n Arg.isRequired(milliseconds, \"milliseconds\");\r\n\r\n this._serverTimeoutInMilliseconds = milliseconds;\r\n\r\n return this;\r\n }\r\n\r\n /** Configures {@link @microsoft/signalr.HubConnection.keepAliveIntervalInMilliseconds} for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withKeepAliveInterval(milliseconds: number): HubConnectionBuilder {\r\n Arg.isRequired(milliseconds, \"milliseconds\");\r\n\r\n this._keepAliveIntervalInMilliseconds = milliseconds;\r\n\r\n return this;\r\n }\r\n\r\n /** Enables and configures options for the Stateful Reconnect feature.\r\n *\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\r\n public withStatefulReconnect(options?: IStatefulReconnectOptions): HubConnectionBuilder {\r\n if (this.httpConnectionOptions === undefined) {\r\n this.httpConnectionOptions = {};\r\n }\r\n this.httpConnectionOptions._useStatefulReconnect = true;\r\n\r\n this._statefulReconnectBufferSize = options?.bufferSize;\r\n\r\n return this;\r\n }\r\n\r\n /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.\r\n *\r\n * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.\r\n */\r\n public build(): HubConnection {\r\n // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one\r\n // provided to configureLogger\r\n const httpConnectionOptions = this.httpConnectionOptions || {};\r\n\r\n // If it's 'null', the user **explicitly** asked for null, don't mess with it.\r\n if (httpConnectionOptions.logger === undefined) {\r\n // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.\r\n httpConnectionOptions.logger = this.logger;\r\n }\r\n\r\n // Now create the connection\r\n if (!this.url) {\r\n throw new Error(\"The 'HubConnectionBuilder.withUrl' method must be called before building the connection.\");\r\n }\r\n const connection = new HttpConnection(this.url, httpConnectionOptions);\r\n\r\n return HubConnection.create(\r\n connection,\r\n this.logger || NullLogger.instance,\r\n this.protocol || new JsonHubProtocol(),\r\n this.reconnectPolicy,\r\n this._serverTimeoutInMilliseconds,\r\n this._keepAliveIntervalInMilliseconds,\r\n this._statefulReconnectBufferSize);\r\n }\r\n}\r\n\r\nfunction isLogger(logger: any): logger is ILogger {\r\n return logger.log !== undefined;\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\n// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds.\r\n\r\n// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties\r\n// that exist on Uint8Array with the same name, and JavaScript is magic.\r\n// We make them 'writable' because the Buffer polyfill messes with it as well.\r\nif (!Uint8Array.prototype.indexOf) {\r\n Object.defineProperty(Uint8Array.prototype, \"indexOf\", {\r\n value: Array.prototype.indexOf,\r\n writable: true,\r\n });\r\n}\r\nif (!Uint8Array.prototype.slice) {\r\n Object.defineProperty(Uint8Array.prototype, \"slice\", {\r\n // wrap the slice in Uint8Array so it looks like a Uint8Array.slice call\r\n // eslint-disable-next-line object-shorthand\r\n value: function(start?: number, end?: number) { return new Uint8Array(Array.prototype.slice.call(this, start, end)); },\r\n writable: true,\r\n });\r\n}\r\nif (!Uint8Array.prototype.forEach) {\r\n Object.defineProperty(Uint8Array.prototype, \"forEach\", {\r\n value: Array.prototype.forEach,\r\n writable: true,\r\n });\r\n}\r\n\r\nexport * from \"./index\";\r\n"],"names":["root","factory","self","__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","g","globalThis","this","Function","e","window","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","LogLevel","HttpError","Error","constructor","errorMessage","statusCode","trueProto","super","__proto__","TimeoutError","AbortError","UnsupportedTransportError","message","transport","errorType","DisabledTransportError","FailedToStartTransportError","FailedToNegotiateWithServerError","AggregateErrors","innerErrors","HttpResponse","statusText","content","HttpClient","url","options","send","method","post","delete","getCookieString","NullLogger","log","_logLevel","_message","instance","VERSION","Arg","static","val","name","match","values","Platform","isBrowser","isNode","document","isWebWorker","isReactNative","process","release","getDataDetail","data","includeContent","detail","isArrayBuffer","byteLength","view","Uint8Array","str","forEach","num","toString","substr","length","formatArrayBuffer","ArrayBuffer","async","sendMessage","logger","transportName","httpClient","headers","getUserAgentHeader","Trace","logMessageContent","responseType","response","timeout","withCredentials","SubjectSubscription","subject","observer","_subject","_observer","dispose","index","observers","indexOf","splice","cancelCallback","catch","_","ConsoleLogger","minimumLogLevel","_minLevel","out","console","logLevel","msg","Date","toISOString","Critical","error","Warning","warn","Information","info","userAgentHeaderName","constructUserAgent","getOsName","getRuntimeVersion","version","os","runtime","runtimeVersion","userAgent","majorAndMinor","split","platform","versions","node","getErrorString","stack","FetchHttpClient","_logger","fetch","requireFunc","_jar","CookieJar","_fetchType","bind","getGlobalThis","AbortController","_abortControllerType","request","abortSignal","aborted","abortController","onabort","abort","timeoutId","msTimeout","setTimeout","undefined","body","cache","credentials","mode","redirect","signal","clearTimeout","ok","deserializeContent","status","payload","cookies","getCookies","c","join","arrayBuffer","text","XhrHttpClient","Promise","reject","resolve","xhr","XMLHttpRequest","open","setRequestHeader","keys","header","onload","responseText","onerror","ontimeout","DefaultHttpClient","_httpClient","TextMessageFormat","output","RecordSeparator","input","messages","pop","RecordSeparatorCode","String","fromCharCode","HandshakeProtocol","writeHandshakeRequest","handshakeRequest","write","JSON","stringify","parseHandshakeResponse","messageData","remainingData","binaryData","separatorIndex","responseLength","apply","Array","slice","buffer","textData","substring","parse","type","MessageType","HubConnectionState","Subject","next","item","err","complete","subscribe","push","MessageBuffer","protocol","connection","bufferSize","_bufferSize","_messages","_totalMessageCount","_waitForSequenceMessage","_nextReceivingSequenceId","_latestReceivedSequenceId","_bufferedByteCount","_reconnectInProgress","_protocol","_connection","serializedMessage","writeMessage","backpressurePromise","_isInvocationMessage","backpressurePromiseResolver","backpressurePromiseRejector","BufferedItem","_disconnected","_ack","ackMessage","newestAckedMessage","element","_id","sequenceId","_resolver","_shouldProcessMessage","Sequence","currentId","_ackTimer","_resetSequence","stop","_dispose","_rejector","Invocation","StreamItem","Completion","StreamInvocation","CancelInvocation","Close","Ping","Ack","_ackTimerHandle","id","resolver","rejector","HubConnection","reconnectPolicy","serverTimeoutInMilliseconds","keepAliveIntervalInMilliseconds","statefulReconnectBufferSize","_nextKeepAlive","_freezeEventListener","isRequired","_statefulReconnectBufferSize","_reconnectPolicy","_handshakeProtocol","onreceive","_processIncomingData","onclose","_connectionClosed","_callbacks","_methods","_closedCallbacks","_reconnectingCallbacks","_reconnectedCallbacks","_invocationId","_receivedHandshakeResponse","_connectionState","Disconnected","_connectionStarted","_cachedPingMessage","state","connectionId","baseUrl","Reconnecting","start","_startPromise","_startWithStateTransitions","Connecting","Debug","_startInternal","addEventListener","Connected","_stopDuringStartError","handshakePromise","_handshakeResolver","_handshakeRejecter","transferFormat","features","reconnect","_sendMessage","_cleanupTimeout","_resetTimeoutPeriod","_resetKeepAliveInterval","_messageBuffer","disconnected","resend","_resend","inherentKeepAlive","_cleanupPingTimer","startPromise","_stopPromise","_stopInternal","Disconnecting","_reconnectDelayHandle","_completeClose","_sendCloseMessage","_sendWithProtocol","_createCloseMessage","stream","methodName","args","streams","streamIds","_replaceStreamingParams","invocationDescriptor","_createStreamInvocation","promiseQueue","cancelInvocation","_createCancelInvocation","invocationId","then","invocationEvent","_launchStreams","_send","sendPromise","_createInvocation","invoke","result","on","newMethod","toLowerCase","off","handlers","removeIdx","callback","onreconnecting","onreconnected","_processHandshakeResponse","parseMessages","_invokeClientMethod","allowReconnect","responseMessage","getTime","_timeoutHandle","serverTimeout","_pingServerHandle","nextPing","invocationMessage","target","methods","_createCompletionMessage","methodsCopy","expectsResponse","res","exception","completionMessage","m","prevRes","arguments","_cancelCallbacksWithError","_reconnect","removeEventListener","reconnectStartTime","now","previousReconnectAttempts","retryError","nextRetryDelay","_getNextRetryDelay","previousRetryCount","elapsedMilliseconds","retryReason","nextRetryDelayInMilliseconds","callbacks","nonblocking","streamId","_createStreamItemMessage","i","argument","_isObservable","arg","DEFAULT_RETRY_DELAYS_IN_MILLISECONDS","DefaultReconnectPolicy","retryDelays","_retryDelays","retryContext","HeaderNames","Authorization","Cookie","AccessTokenHttpClient","innerClient","accessTokenFactory","_innerClient","_accessTokenFactory","allowRetry","_accessToken","_setAuthorizationHeader","HttpTransportType","TransferFormat","_isAborted","LongPollingTransport","pollAborted","_pollAbort","_options","_running","isIn","_url","Binary","pollOptions","pollUrl","_closeError","_receiving","_poll","_raiseOnClose","deleteOptions","logMessage","ServerSentEventsTransport","accessToken","encodeURIComponent","eventSource","opened","Text","EventSource","onmessage","_close","onopen","_eventSource","close","WebSocketTransport","webSocketConstructor","_logMessageContent","_webSocketConstructor","_headers","token","webSocket","replace","binaryType","_event","_webSocket","event","ErrorEvent","readyState","OPEN","_isCloseEvent","wasClean","code","reason","HttpConnection","_stopPromiseResolver","_negotiateVersion","_resolveUrl","webSocketModule","eventSourceModule","WebSocket","_startInternalPromise","_sendQueue","TransportSendQueue","_stopError","_stopConnection","skipNegotiation","WebSockets","_constructTransport","_startTransport","negotiateResponse","redirects","_getNegotiationResponse","ProtocolVersion","_createTransport","negotiateUrl","_resolveNegotiateUrl","negotiateVersion","connectionToken","useStatefulReconnect","_useStatefulReconnect","_createConnectUrl","requestedTransport","requestedTransferFormat","connectUrl","_isITransport","transportExceptions","transports","availableTransports","negotiate","endpoint","transportOrError","_resolveTransportOrError","ex","ServerSentEvents","LongPolling","callStop","connect","actualTransport","transportMatches","transferFormats","map","s","lastIndexOf","aTag","createElement","href","URL","pathname","endsWith","searchParams","URLSearchParams","has","append","search","_transport","_buffer","_executing","_sendBufferedData","PromiseSource","_transportResult","_sendLoopPromise","_sendLoop","_bufferData","promise","transportResult","_concatBuffers","arrayBuffers","totalLength","b","reduce","a","offset","set","_rejecter","JsonHubProtocol","hubMessages","parsedMessage","_isStreamItemMessage","_isCompletionMessage","_isAckMessage","_isSequenceMessage","_assertNotEmptyString","LogLevelNameMapping","trace","debug","information","warning","critical","none","None","HubConnectionBuilder","configureLogging","logging","mapping","parseLogLevel","withUrl","transportTypeOrOptions","isNotEmpty","httpConnectionOptions","withHubProtocol","withAutomaticReconnect","retryDelaysOrReconnectPolicy","isArray","withServerTimeout","milliseconds","_serverTimeoutInMilliseconds","withKeepAliveInterval","_keepAliveIntervalInMilliseconds","withStatefulReconnect","build","create","writable","end","module","define","amd"],"sourceRoot":""}