"use strict";(self.webpackChunklauncher=self.webpackChunklauncher||[]).push([[5092],{5092:(t,e,o)=>{o.r(e),o.d(e,{AbortError:()=>s,DefaultHttpClient:()=>R,HttpClient:()=>u,HttpError:()=>n,HttpResponse:()=>g,HttpTransportType:()=>F,HubConnection:()=>A,HubConnectionBuilder:()=>Z,HubConnectionState:()=>W,JsonHubProtocol:()=>G,LogLevel:()=>d,MessageType:()=>N,NullLogger:()=>p,Subject:()=>M,TimeoutError:()=>r,TransferFormat:()=>U,VERSION:()=>_});class n extends Error{constructor(t,e){const o=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=o}}class r extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class s extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class i extends Error{constructor(t,e){const o=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=o}}class c extends Error{constructor(t,e){const o=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=o}}class a extends Error{constructor(t,e){const o=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=o}}class l extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class h extends Error{constructor(t,e){const o=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=o}}class g{constructor(t,e,o){this.statusCode=t,this.statusText=e,this.content=o}}class u{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}var d;!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(d||(d={}));class p{constructor(){}log(t,e){}}p.instance=new p;const _="7.0.10";class f{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,o){if(!(t in e))throw new Error(`Unknown ${o} value: ${t}.`)}}class m{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function w(t,e){let o="";return b(t)?(o=`Binary data of length ${t.byteLength}`,e&&(o+=`. Content: '${function(t){const e=new Uint8Array(t);let o="";return e.forEach((t=>{o+=`0x${t<16?"0":""}${t.toString(16)} `})),o.substr(0,o.length-1)}(t)}'`)):"string"==typeof t&&(o=`String data of length ${t.length}`,e&&(o+=`. Content: '${t}'`)),o}function b(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function v(t,e,o,n,r,s){const i={},[c,a]=S();i[c]=a,t.log(d.Trace,`(${e} transport) sending data. ${w(r,s.logMessageContent)}.`);const l=b(r)?"arraybuffer":"text",h=await o.post(n,{content:r,headers:{...i,...s.headers},responseType:l,timeout:s.timeout,withCredentials:s.withCredentials});t.log(d.Trace,`(${e} transport) request complete. Response status: ${h.statusCode}.`)}class y{constructor(t,e){this._subject=t,this._observer=e}dispose(){const t=this._subject.observers.indexOf(this._observer);t>-1&&this._subject.observers.splice(t,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((t=>{}))}}class C{constructor(t){this._minLevel=t,this.out=console}log(t,e){if(t>=this._minLevel){const o=`[${(new Date).toISOString()}] ${d[t]}: ${e}`;switch(t){case d.Critical:case d.Error:this.out.error(o);break;case d.Warning:this.out.warn(o);break;case d.Information:this.out.info(o);break;default:this.out.log(o)}}}}function S(){let t="X-SignalR-User-Agent";return m.isNode&&(t="User-Agent"),[t,k(_,E(),m.isNode?"NodeJS":"Browser",T())]}function k(t,e,o,n){let r="Microsoft SignalR/";const s=t.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${t}; `,r+=e&&""!==e?`${e}; `:"Unknown OS; ",r+=`${o}`,r+=n?`; ${n}`:"; Unknown Runtime Version",r+=")",r}function E(){if(!m.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function T(){if(m.isNode)return process.versions.node}function I(t){return t.stack?t.stack:t.message?t.message:`${t}`}class P extends u{constructor(t){if(super(),this._logger=t,"undefined"==typeof fetch){const t=require;this._jar=new(t("tough-cookie").CookieJar),this._fetchType=t("node-fetch"),this._fetchType=t("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==o.g)return o.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this._abortControllerType=t("abort-controller")}else this._abortControllerType=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new s;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const e=new this._abortControllerType;let o;t.abortSignal&&(t.abortSignal.onabort=()=>{e.abort(),o=new s});let i,c=null;if(t.timeout){const n=t.timeout;c=setTimeout((()=>{e.abort(),this._logger.log(d.Warning,"Timeout from HTTP request."),o=new r}),n)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},b(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{i=await this._fetchType(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:e.signal})}catch(t){if(o)throw o;throw this._logger.log(d.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!i.ok){const t=await $(i,"text");throw new n(t||i.statusText,i.status)}const a=$(i,t.responseType),l=await a;return new g(i.status,i.statusText,l)}getCookieString(t){let e="";return m.isNode&&this._jar&&this._jar.getCookies(t,((t,o)=>e=o.join("; "))),e}}function $(t,e){let o;switch(e){case"arraybuffer":o=t.arrayBuffer();break;case"text":default:o=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return o}class D extends u{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new s):t.method?t.url?new Promise(((e,o)=>{const i=new XMLHttpRequest;i.open(t.method,t.url,!0),i.withCredentials=void 0===t.withCredentials||t.withCredentials,i.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(b(t.content)?i.setRequestHeader("Content-Type","application/octet-stream"):i.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{i.setRequestHeader(t,c[t])})),t.responseType&&(i.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{i.abort(),o(new s)}),t.timeout&&(i.timeout=t.timeout),i.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),i.status>=200&&i.status<300?e(new g(i.status,i.statusText,i.response||i.responseText)):o(new n(i.response||i.responseText||i.statusText,i.status))},i.onerror=()=>{this._logger.log(d.Warning,`Error from HTTP request. ${i.status}: ${i.statusText}.`),o(new n(i.statusText,i.status))},i.ontimeout=()=>{this._logger.log(d.Warning,"Timeout from HTTP request."),o(new r)},i.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class R extends u{constructor(t){if(super(),"undefined"!=typeof fetch||m.isNode)this._httpClient=new P(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new D(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new s):t.method?t.url?this._httpClient.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this._httpClient.getCookieString(t)}}class H{static write(t){return`${t}${H.RecordSeparator}`}static parse(t){if(t[t.length-1]!==H.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(H.RecordSeparator);return e.pop(),e}}H.RecordSeparatorCode=30,H.RecordSeparator=String.fromCharCode(H.RecordSeparatorCode);class x{writeHandshakeRequest(t){return H.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,o;if(b(t)){const n=new Uint8Array(t),r=n.indexOf(H.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(n.slice(0,s))),o=n.byteLength>s?n.slice(s).buffer:null}else{const n=t,r=n.indexOf(H.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;e=n.substring(0,s),o=n.length>s?n.substring(s):null}const n=H.parse(e),r=JSON.parse(n[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[o,r]}}var N,W;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close"}(N||(N={}));class M{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new y(this,t)}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(W||(W={}));class A{constructor(t,e,o,n){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(d.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},f.isRequired(t,"connection"),f.isRequired(e,"logger"),f.isRequired(o,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=e,this._protocol=o,this.connection=t,this._reconnectPolicy=n,this._handshakeProtocol=new x,this.connection.onreceive=t=>this._processIncomingData(t),this.connection.onclose=t=>this._connectionClosed(t),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=W.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:N.Ping})}static create(t,e,o,n){return new A(t,e,o,n)}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this._connectionState!==W.Disconnected&&this._connectionState!==W.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==W.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=W.Connecting,this._logger.log(d.Debug,"Starting HubConnection.");try{await this._startInternal(),m.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=W.Connected,this._connectionStarted=!0,this._logger.log(d.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=W.Disconnected,this._logger.log(d.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const t=new Promise(((t,e)=>{this._handshakeResolver=t,this._handshakeRejecter=e}));await this.connection.start(this._protocol.transferFormat);try{const e={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(d.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(e)),this._logger.log(d.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await t,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(t){throw this._logger.log(d.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(t),t}}async stop(){const t=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await t}catch(t){}}_stopInternal(t){return this._connectionState===W.Disconnected?(this._logger.log(d.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===W.Disconnecting?(this._logger.log(d.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=W.Disconnecting,this._logger.log(d.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(d.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new s("The connection was stopped before the hub handshake could complete."),this.connection.stop(t)))}stream(t,...e){const[o,n]=this._replaceStreamingParams(e),r=this._createStreamInvocation(t,e,n);let s;const i=new M;return i.cancelCallback=()=>{const t=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(t)))},this._callbacks[r.invocationId]=(t,e)=>{e?i.error(e):t&&(t.type===N.Completion?t.error?i.error(new Error(t.error)):i.complete():i.next(t.item))},s=this._sendWithProtocol(r).catch((t=>{i.error(t),delete this._callbacks[r.invocationId]})),this._launchStreams(o,s),i}_sendMessage(t){return this._resetKeepAliveInterval(),this.connection.send(t)}_sendWithProtocol(t){return this._sendMessage(this._protocol.writeMessage(t))}send(t,...e){const[o,n]=this._replaceStreamingParams(e),r=this._sendWithProtocol(this._createInvocation(t,e,!0,n));return this._launchStreams(o,r),r}invoke(t,...e){const[o,n]=this._replaceStreamingParams(e),r=this._createInvocation(t,e,!1,n);return new Promise(((t,e)=>{this._callbacks[r.invocationId]=(o,n)=>{n?e(n):o&&(o.type===N.Completion?o.error?e(new Error(o.error)):t(o.result):e(new Error(`Unexpected message type: ${o.type}`)))};const n=this._sendWithProtocol(r).catch((t=>{e(t),delete this._callbacks[r.invocationId]}));this._launchStreams(o,n)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this._methods[t]||(this._methods[t]=[]),-1===this._methods[t].indexOf(e)&&this._methods[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const o=this._methods[t];if(o)if(e){const n=o.indexOf(e);-1!==n&&(o.splice(n,1),0===o.length&&delete this._methods[t])}else delete this._methods[t]}onclose(t){t&&this._closedCallbacks.push(t)}onreconnecting(t){t&&this._reconnectingCallbacks.push(t)}onreconnected(t){t&&this._reconnectedCallbacks.push(t)}_processIncomingData(t){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(t=this._processHandshakeResponse(t),this._receivedHandshakeResponse=!0),t){const e=this._protocol.parseMessages(t,this._logger);for(const t of e)switch(t.type){case N.Invocation:this._invokeClientMethod(t);break;case N.StreamItem:case N.Completion:{const e=this._callbacks[t.invocationId];if(e){t.type===N.Completion&&delete this._callbacks[t.invocationId];try{e(t)}catch(t){this._logger.log(d.Error,`Stream callback threw error: ${I(t)}`)}}break}case N.Ping:break;case N.Close:{this._logger.log(d.Information,"Close message received from server.");const e=t.error?new Error("Server returned an error on close: "+t.error):void 0;!0===t.allowReconnect?this.connection.stop(e):this._stopPromise=this._stopInternal(e);break}default:this._logger.log(d.Warning,`Invalid message type: ${t.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(t){let e,o;try{[o,e]=this._handshakeProtocol.parseHandshakeResponse(t)}catch(t){const e="Error parsing handshake response: "+t;this._logger.log(d.Error,e);const o=new Error(e);throw this._handshakeRejecter(o),o}if(e.error){const t="Server returned handshake error: "+e.error;this._logger.log(d.Error,t);const o=new Error(t);throw this._handshakeRejecter(o),o}return this._logger.log(d.Debug,"Server handshake complete."),this._handshakeResolver(),o}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let t=this._nextKeepAlive-(new Date).getTime();t<0&&(t=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===W.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(t){const e=t.target.toLowerCase(),o=this._methods[e];if(!o)return this._logger.log(d.Warning,`No client method with the name '${e}' found.`),void(t.invocationId&&(this._logger.log(d.Warning,`No result given for '${e}' method and invocation ID '${t.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null))));const n=o.slice(),r=!!t.invocationId;let s,i,c;for(const o of n)try{const n=s;s=await o.apply(this,t.arguments),r&&s&&n&&(this._logger.log(d.Error,`Multiple results provided for '${e}'. Sending error to server.`),c=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),i=void 0}catch(t){i=t,this._logger.log(d.Error,`A callback for the method '${e}' threw error '${t}'.`)}c?await this._sendWithProtocol(c):r?(i?c=this._createCompletionMessage(t.invocationId,`${i}`,null):void 0!==s?c=this._createCompletionMessage(t.invocationId,null,s):(this._logger.log(d.Warning,`No result given for '${e}' method and invocation ID '${t.invocationId}'.`),c=this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(c)):s&&this._logger.log(d.Error,`Result given for '${e}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(d.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new s("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(t||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===W.Disconnecting?this._completeClose(t):this._connectionState===W.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===W.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=W.Disconnected,this._connectionStarted=!1,m.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((e=>e.apply(this,[t])))}catch(e){this._logger.log(d.Error,`An onclose callback called with error '${t}' threw error '${e}'.`)}}}async _reconnect(t){const e=Date.now();let o=0,n=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(o++,0,n);if(null===r)return this._logger.log(d.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(t);if(this._connectionState=W.Reconnecting,t?this._logger.log(d.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(d.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((e=>e.apply(this,[t])))}catch(e){this._logger.log(d.Error,`An onreconnecting callback called with error '${t}' threw error '${e}'.`)}if(this._connectionState!==W.Reconnecting)return void this._logger.log(d.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(d.Information,`Reconnect attempt number ${o} will start in ${r} ms.`),await new Promise((t=>{this._reconnectDelayHandle=setTimeout(t,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==W.Reconnecting)return void this._logger.log(d.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=W.Connected,this._logger.log(d.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this._logger.log(d.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this._logger.log(d.Information,`Reconnect attempt failed because of error '${t}'.`),this._connectionState!==W.Reconnecting)return this._logger.log(d.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===W.Disconnecting&&this._completeClose());n=t instanceof Error?t:new Error(t.toString()),r=this._getNextRetryDelay(o++,Date.now()-e,n)}}this._logger.log(d.Information,`Reconnect retries have been exhausted after ${Date.now()-e} ms and ${o} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(t,e,o){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:e,previousRetryCount:t,retryReason:o})}catch(o){return this._logger.log(d.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${e}) threw error '${o}'.`),null}}_cancelCallbacksWithError(t){const e=this._callbacks;this._callbacks={},Object.keys(e).forEach((o=>{const n=e[o];try{n(null,t)}catch(e){this._logger.log(d.Error,`Stream 'error' callback called with '${t}' threw error: ${I(e)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(t,e,o,n){if(o)return 0!==n.length?{arguments:e,streamIds:n,target:t,type:N.Invocation}:{arguments:e,target:t,type:N.Invocation};{const o=this._invocationId;return this._invocationId++,0!==n.length?{arguments:e,invocationId:o.toString(),streamIds:n,target:t,type:N.Invocation}:{arguments:e,invocationId:o.toString(),target:t,type:N.Invocation}}}_launchStreams(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const o in t)t[o].subscribe({complete:()=>{e=e.then((()=>this._sendWithProtocol(this._createCompletionMessage(o))))},error:t=>{let n;n=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this._sendWithProtocol(this._createCompletionMessage(o,n))))},next:t=>{e=e.then((()=>this._sendWithProtocol(this._createStreamItemMessage(o,t))))}})}}_replaceStreamingParams(t){const e=[],o=[];for(let n=0;n0)&&(e=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(t);const o=await this._innerClient.send(t);return e&&401===o.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(t),await this._innerClient.send(t)):o}_setAuthorizationHeader(t){t.headers||(t.headers={}),this._accessToken?t.headers[q.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[q.Authorization]&&delete t.headers[q.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}}var F,U;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(F||(F={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(U||(U={}));class B{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class z{constructor(t,e,o){this._httpClient=t,this._logger=e,this._pollAbort=new B,this._options=o,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(t,e){if(f.isRequired(t,"url"),f.isRequired(e,"transferFormat"),f.isIn(e,U,"transferFormat"),this._url=t,this._logger.log(d.Trace,"(LongPolling transport) Connecting."),e===U.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[o,r]=S(),s={[o]:r,...this._options.headers},i={abortSignal:this._pollAbort.signal,headers:s,timeout:1e5,withCredentials:this._options.withCredentials};e===U.Binary&&(i.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this._logger.log(d.Trace,`(LongPolling transport) polling: ${c}.`);const a=await this._httpClient.get(c,i);200!==a.statusCode?(this._logger.log(d.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new n(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _poll(t,e){try{for(;this._running;)try{const o=`${t}&_=${Date.now()}`;this._logger.log(d.Trace,`(LongPolling transport) polling: ${o}.`);const r=await this._httpClient.get(o,e);204===r.statusCode?(this._logger.log(d.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(d.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new n(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(d.Trace,`(LongPolling transport) data received. ${w(r.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(d.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this._running?t instanceof r?this._logger.log(d.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=t,this._running=!1):this._logger.log(d.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this._logger.log(d.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?v(this._logger,"LongPolling",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(d.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(d.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const t={},[e,o]=S();t[e]=o;const n={headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};await this._httpClient.delete(this._url,n),this._logger.log(d.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(d.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this._closeError&&(t+=" Error: "+this._closeError),this._logger.log(d.Trace,t),this.onclose(this._closeError)}}}class K{constructor(t,e,o,n){this._httpClient=t,this._accessToken=e,this._logger=o,this._options=n,this.onreceive=null,this.onclose=null}async connect(t,e){return f.isRequired(t,"url"),f.isRequired(e,"transferFormat"),f.isIn(e,U,"transferFormat"),this._logger.log(d.Trace,"(SSE transport) Connecting."),this._url=t,this._accessToken&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((o,n)=>{let r,s=!1;if(e===U.Text){if(m.isBrowser||m.isWebWorker)r=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{const e=this._httpClient.getCookieString(t),o={};o.Cookie=e;const[n,s]=S();o[n]=s,r=new this._options.EventSource(t,{withCredentials:this._options.withCredentials,headers:{...o,...this._options.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this._logger.log(d.Trace,`(SSE transport) data received. ${w(t.data,this._options.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this._close(t)}},r.onerror=t=>{s?this._close():n(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(d.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,o()}}catch(t){return void n(t)}}else n(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this._eventSource?v(this._logger,"SSE",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(t){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(t))}}class X{constructor(t,e,o,n,r,s){this._logger=o,this._accessTokenFactory=e,this._logMessageContent=n,this._webSocketConstructor=r,this._httpClient=t,this.onreceive=null,this.onclose=null,this._headers=s}async connect(t,e){let o;return f.isRequired(t,"url"),f.isRequired(e,"transferFormat"),f.isIn(e,U,"transferFormat"),this._logger.log(d.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(o=await this._accessTokenFactory()),new Promise(((n,r)=>{let s;t=t.replace(/^http/,"ws");const i=this._httpClient.getCookieString(t);let c=!1;if(m.isNode||m.isReactNative){const e={},[n,r]=S();e[n]=r,o&&(e[q.Authorization]=`Bearer ${o}`),i&&(e[q.Cookie]=i),s=new this._webSocketConstructor(t,void 0,{headers:{...e,...this._headers}})}else o&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(o)}`);s||(s=new this._webSocketConstructor(t)),e===U.Binary&&(s.binaryType="arraybuffer"),s.onopen=e=>{this._logger.log(d.Information,`WebSocket connected to ${t}.`),this._webSocket=s,c=!0,n()},s.onerror=t=>{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this._logger.log(d.Information,`(WebSockets transport) ${e}.`)},s.onmessage=t=>{if(this._logger.log(d.Trace,`(WebSockets transport) data received. ${w(t.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this._close(t)}},s.onclose=t=>{if(c)this._close(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(d.Trace,`(WebSockets transport) sending data. ${w(t,this._logMessageContent)}.`),this._webSocket.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(t){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(d.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}_isCloseEvent(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class J{constructor(t,e={}){var o;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,f.isRequired(t,"url"),this._logger=void 0===(o=e.logger)?new C(d.Information):null===o?p.instance:void 0!==o.log?o:new C(o),this.baseUrl=this._resolveUrl(t),(e=e||{}).logMessageContent=void 0!==e.logMessageContent&&e.logMessageContent,"boolean"!=typeof e.withCredentials&&void 0!==e.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");e.withCredentials=void 0===e.withCredentials||e.withCredentials,e.timeout=void 0===e.timeout?1e5:e.timeout;let n=null,r=null;if(m.isNode){const t=require;n=t("ws"),r=t("eventsource")}m.isNode||"undefined"==typeof WebSocket||e.WebSocket?m.isNode&&!e.WebSocket&&n&&(e.WebSocket=n):e.WebSocket=WebSocket,m.isNode||"undefined"==typeof EventSource||e.EventSource?m.isNode&&!e.EventSource&&void 0!==r&&(e.EventSource=r):e.EventSource=EventSource,this._httpClient=new O(e.httpClient||new R(this._logger),e.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=e,this.onreceive=null,this.onclose=null}async start(t){if(t=t||U.Binary,f.isIn(t,U,"transferFormat"),this._logger.log(d.Debug,`Starting connection with transfer format '${U[t]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(t),await this._startInternalPromise,"Disconnecting"===this._connectionState){const t="Failed to start the HttpConnection before stop() was called.";return this._logger.log(d.Error,t),await this._stopPromise,Promise.reject(new s(t))}if("Connected"!==this._connectionState){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(d.Error,t),Promise.reject(new s(t))}this._connectionStarted=!0}send(t){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new V(this.transport)),this._sendQueue.send(t))}async stop(t){return"Disconnected"===this._connectionState?(this._logger.log(d.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(d.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((t=>{this._stopPromiseResolver=t})),await this._stopInternal(t),void await this._stopPromise)}async _stopInternal(t){this._stopError=t;try{await this._startInternalPromise}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this._logger.log(d.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(d.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(t){let e=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==F.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(F.WebSockets),await this._startTransport(e,t)}else{let o=null,n=0;do{if(o=await this._getNegotiationResponse(e),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new s("The connection was stopped during negotiation.");if(o.error)throw new Error(o.error);if(o.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(o.url&&(e=o.url),o.accessToken){const t=o.accessToken;this._accessTokenFactory=()=>t,this._httpClient._accessToken=t,this._httpClient._accessTokenFactory=void 0}n++}while(o.url&&n<100);if(100===n&&o.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(e,this._options.transport,o,t)}this.transport instanceof z&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(d.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(t){return this._logger.log(d.Error,"Failed to start the connection: "+t),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(t)}}async _getNegotiationResponse(t){const e={},[o,r]=S();e[o]=r;const s=this._resolveNegotiateUrl(t);this._logger.log(d.Debug,`Sending negotiation request: ${s}.`);try{const t=await this._httpClient.post(s,{content:"",headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const o=JSON.parse(t.content);return(!o.negotiateVersion||o.negotiateVersion<1)&&(o.connectionToken=o.connectionId),o}catch(t){let e="Failed to complete negotiation with the server: "+t;return t instanceof n&&404===t.statusCode&&(e+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(d.Error,e),Promise.reject(new l(e))}}_createConnectUrl(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async _createTransport(t,e,o,n){let r=this._createConnectUrl(t,o.connectionToken);if(this._isITransport(e))return this._logger.log(d.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=e,await this._startTransport(r,n),void(this.connectionId=o.connectionId);const i=[],c=o.availableTransports||[];let l=o;for(const o of c){const c=this._resolveTransportOrError(o,e,n);if(c instanceof Error)i.push(`${o.transport} failed:`),i.push(c);else if(this._isITransport(c)){if(this.transport=c,!l){try{l=await this._getNegotiationResponse(t)}catch(t){return Promise.reject(t)}r=this._createConnectUrl(t,l.connectionToken)}try{return await this._startTransport(r,n),void(this.connectionId=l.connectionId)}catch(t){if(this._logger.log(d.Error,`Failed to start the transport '${o.transport}': ${t}`),l=void 0,i.push(new a(`${o.transport} failed: ${t}`,F[o.transport])),"Connecting"!==this._connectionState){const t="Failed to select transport before stop() was called.";return this._logger.log(d.Debug,t),Promise.reject(new s(t))}}}}return i.length>0?Promise.reject(new h(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`,i)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(t){switch(t){case F.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new X(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case F.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new K(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case F.LongPolling:return new z(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${t}.`)}}_startTransport(t,e){return this.transport.onreceive=this.onreceive,this.transport.onclose=t=>this._stopConnection(t),this.transport.connect(t,e)}_resolveTransportOrError(t,e,o){const n=F[t.transport];if(null==n)return this._logger.log(d.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||0!=(e&t)}(e,n))return this._logger.log(d.Debug,`Skipping transport '${F[n]}' because it was disabled by the client.`),new c(`'${F[n]}' is disabled by the client.`,n);if(!(t.transferFormats.map((t=>U[t])).indexOf(o)>=0))return this._logger.log(d.Debug,`Skipping transport '${F[n]}' because it does not support the requested transfer format '${U[o]}'.`),new Error(`'${F[n]}' does not support ${U[o]}.`);if(n===F.WebSockets&&!this._options.WebSocket||n===F.ServerSentEvents&&!this._options.EventSource)return this._logger.log(d.Debug,`Skipping transport '${F[n]}' because it is not supported in your environment.'`),new i(`'${F[n]}' is not supported in your environment.`,n);this._logger.log(d.Debug,`Selecting transport '${F[n]}'.`);try{return this._constructTransport(n)}catch(t){return t}}_isITransport(t){return t&&"object"==typeof t&&"connect"in t}_stopConnection(t){if(this._logger.log(d.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this._connectionState}.`),this.transport=void 0,t=this._stopError||t,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(d.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),t?this._logger.log(d.Error,`Connection disconnected with error '${t}'.`):this._logger.log(d.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((t=>{this._logger.log(d.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(t)}catch(e){this._logger.log(d.Error,`HttpConnection.onclose(${t}) threw error '${e}'.`)}}}else this._logger.log(d.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!m.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const e=window.document.createElement("a");return e.href=t,this._logger.log(d.Information,`Normalizing '${t}' to '${e.href}'.`),e.href}_resolveNegotiateUrl(t){const e=t.indexOf("?");let o=t.substring(0,-1===e?t.length:e);return"/"!==o[o.length-1]&&(o+="/"),o+="negotiate",o+=-1===e?"":t.substring(e),-1===o.indexOf("negotiateVersion")&&(o+=-1===e?"?":"&",o+="negotiateVersion="+this._negotiateVersion),o}}class V{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new Q,this._transportResult=new Q,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new Q),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(t){if(this._buffer.length&&typeof this._buffer[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof t}`);this._buffer.push(t),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Q;const t=this._transportResult;this._transportResult=void 0;const e="string"==typeof this._buffer[0]?this._buffer.join(""):V._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(e),t.resolve()}catch(e){t.reject(e)}}}static _concatBuffers(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),o=new Uint8Array(e);let n=0;for(const e of t)o.set(new Uint8Array(e),n),n+=e.byteLength;return o.buffer}}class Q{constructor(){this.promise=new Promise(((t,e)=>[this._resolver,this._rejecter]=[t,e]))}resolve(){this._resolver()}reject(t){this._rejecter(t)}}class G{constructor(){this.name="json",this.version=1,this.transferFormat=U.Text}parseMessages(t,e){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===e&&(e=p.instance);const o=H.parse(t),n=[];for(const t of o){const o=JSON.parse(t);if("number"!=typeof o.type)throw new Error("Invalid payload.");switch(o.type){case N.Invocation:this._isInvocationMessage(o);break;case N.StreamItem:this._isStreamItemMessage(o);break;case N.Completion:this._isCompletionMessage(o);break;case N.Ping:case N.Close:break;default:e.log(d.Information,"Unknown message type '"+o.type+"' ignored.");continue}n.push(o)}return n}writeMessage(t){return H.write(JSON.stringify(t))}_isInvocationMessage(t){this._assertNotEmptyString(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this._assertNotEmptyString(t.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(t){if(this._assertNotEmptyString(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this._assertNotEmptyString(t.error,"Invalid payload for Completion message."),this._assertNotEmptyString(t.invocationId,"Invalid payload for Completion message.")}_assertNotEmptyString(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const Y={trace:d.Trace,debug:d.Debug,info:d.Information,information:d.Information,warn:d.Warning,warning:d.Warning,error:d.Error,critical:d.Critical,none:d.None};class Z{configureLogging(t){if(f.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=Y[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new C(e)}else this.logger=new C(t);return this}withUrl(t,e){return f.isRequired(t,"url"),f.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return f.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new L(t):this.reconnectPolicy=t:this.reconnectPolicy=new L,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new J(this.url,t);return A.create(e,this.logger||p.instance,this.protocol||new G,this.reconnectPolicy)}}}}]);