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