lavva.exalushome.webcams
Version:
Library implementing webcams and abstraction layers for webcams configuration API in ExalusHome system
1 lines • 499 kB
JavaScript
(()=>{"use strict";var e,t,n,r,s,o,i,a,c={};c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();class u{constructor(){this.Guid="",this.RtspUrl="",this.UserName=null,this.Password=null}}class l{static GenerateUUID(){var e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(n){var r=16*Math.random();return e>0?(r=(e+r)%16|0,e=Math.floor(e/16)):(r=(t+r)%16|0,t=Math.floor(t/16)),("x"===n?r:3&r|8).toString(16)}))}static GenerateMd5(e){let t="0123456789abcdef";function n(e){let n,r="";for(n=0;n<=3;n++)r+=t.charAt(e>>8*n+4&15)+t.charAt(e>>8*n&15);return r}function r(e,t){let n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function s(e,t,n,s,o,i){return r(function(e,t){return e<<t|e>>>32-t}(r(r(t,e),r(s,i)),o),n)}function o(e,t,n,r,o,i,a){return s(t&n|~t&r,e,t,o,i,a)}function i(e,t,n,r,o,i,a){return s(t&r|n&~r,e,t,o,i,a)}function a(e,t,n,r,o,i,a){return s(t^n^r,e,t,o,i,a)}function c(e,t,n,r,o,i,a){return s(n^(t|~r),e,t,o,i,a)}let u,l,d,h,p,g=function(e){let t,n=1+(e.length+8>>6),r=new Array(16*n);for(t=0;t<16*n;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[16*n-2]=8*e.length,r}(""+e),f=1732584193,v=-271733879,y=-1732584194,m=271733878;for(u=0;u<g.length;u+=16)l=f,d=v,h=y,p=m,f=o(f,v,y,m,g[u+0],7,-680876936),m=o(m,f,v,y,g[u+1],12,-389564586),y=o(y,m,f,v,g[u+2],17,606105819),v=o(v,y,m,f,g[u+3],22,-1044525330),f=o(f,v,y,m,g[u+4],7,-176418897),m=o(m,f,v,y,g[u+5],12,1200080426),y=o(y,m,f,v,g[u+6],17,-1473231341),v=o(v,y,m,f,g[u+7],22,-45705983),f=o(f,v,y,m,g[u+8],7,1770035416),m=o(m,f,v,y,g[u+9],12,-1958414417),y=o(y,m,f,v,g[u+10],17,-42063),v=o(v,y,m,f,g[u+11],22,-1990404162),f=o(f,v,y,m,g[u+12],7,1804603682),m=o(m,f,v,y,g[u+13],12,-40341101),y=o(y,m,f,v,g[u+14],17,-1502002290),v=o(v,y,m,f,g[u+15],22,1236535329),f=i(f,v,y,m,g[u+1],5,-165796510),m=i(m,f,v,y,g[u+6],9,-1069501632),y=i(y,m,f,v,g[u+11],14,643717713),v=i(v,y,m,f,g[u+0],20,-373897302),f=i(f,v,y,m,g[u+5],5,-701558691),m=i(m,f,v,y,g[u+10],9,38016083),y=i(y,m,f,v,g[u+15],14,-660478335),v=i(v,y,m,f,g[u+4],20,-405537848),f=i(f,v,y,m,g[u+9],5,568446438),m=i(m,f,v,y,g[u+14],9,-1019803690),y=i(y,m,f,v,g[u+3],14,-187363961),v=i(v,y,m,f,g[u+8],20,1163531501),f=i(f,v,y,m,g[u+13],5,-1444681467),m=i(m,f,v,y,g[u+2],9,-51403784),y=i(y,m,f,v,g[u+7],14,1735328473),v=i(v,y,m,f,g[u+12],20,-1926607734),f=a(f,v,y,m,g[u+5],4,-378558),m=a(m,f,v,y,g[u+8],11,-2022574463),y=a(y,m,f,v,g[u+11],16,1839030562),v=a(v,y,m,f,g[u+14],23,-35309556),f=a(f,v,y,m,g[u+1],4,-1530992060),m=a(m,f,v,y,g[u+4],11,1272893353),y=a(y,m,f,v,g[u+7],16,-155497632),v=a(v,y,m,f,g[u+10],23,-1094730640),f=a(f,v,y,m,g[u+13],4,681279174),m=a(m,f,v,y,g[u+0],11,-358537222),y=a(y,m,f,v,g[u+3],16,-722521979),v=a(v,y,m,f,g[u+6],23,76029189),f=a(f,v,y,m,g[u+9],4,-640364487),m=a(m,f,v,y,g[u+12],11,-421815835),y=a(y,m,f,v,g[u+15],16,530742520),v=a(v,y,m,f,g[u+2],23,-995338651),f=c(f,v,y,m,g[u+0],6,-198630844),m=c(m,f,v,y,g[u+7],10,1126891415),y=c(y,m,f,v,g[u+14],15,-1416354905),v=c(v,y,m,f,g[u+5],21,-57434055),f=c(f,v,y,m,g[u+12],6,1700485571),m=c(m,f,v,y,g[u+3],10,-1894986606),y=c(y,m,f,v,g[u+10],15,-1051523),v=c(v,y,m,f,g[u+1],21,-2054922799),f=c(f,v,y,m,g[u+8],6,1873313359),m=c(m,f,v,y,g[u+15],10,-30611744),y=c(y,m,f,v,g[u+6],15,-1560198380),v=c(v,y,m,f,g[u+13],21,1309151649),f=c(f,v,y,m,g[u+4],6,-145523070),m=c(m,f,v,y,g[u+11],10,-1120210379),y=c(y,m,f,v,g[u+2],15,718787259),v=c(v,y,m,f,g[u+9],21,-343485551),f=r(f,l),v=r(v,d),y=r(y,h),m=r(m,p);return n(f)+n(v)+n(y)+n(m)}static IsIosNative(){var e;const t=null!=window.webkit&&null!=window.webkit.messageHandlers,n=void 0!==(null===(e=window.nativeEvent)||void 0===e?void 0:e.exalusFindController);return t&&n}}class d{static Delay(e){return new Promise((t=>setTimeout(t,e)))}}function h(e){return new Map(Object.entries(e))}function p(e,t="export.csv"){const n=new Blob(["\ufeff",e],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=t,s.style.display="none",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(r)}class g{constructor(){this.TransactionId=l.GenerateUUID()}}(o=e||(e={}))[o.OK=0]="OK",o[o.UnknownError=1]="UnknownError",o[o.FatalError=2]="FatalError",o[o.WrongData=3]="WrongData",o[o.ResourceDoesNotExists=4]="ResourceDoesNotExists",o[o.NoPermissionToPerformThisOperation=5]="NoPermissionToPerformThisOperation",o[o.SessionHasAlreadyLoggedOnUser=6]="SessionHasAlreadyLoggedOnUser",o[o.OperationNotPermitted=7]="OperationNotPermitted",o[o.NoPermissionsToCallGivenResource=8]="NoPermissionsToCallGivenResource",o[o.ResourceIsNotAvailable=9]="ResourceIsNotAvailable",o[o.Error=10]="Error",o[o.NoData=11]="NoData",o[o.NotSupportedMethod=12]="NotSupportedMethod",o[o.UserIsNotLoggedIn=13]="UserIsNotLoggedIn",o[o.MultiDataResponseStart=14]="MultiDataResponseStart",o[o.MultiDataResponse=15]="MultiDataResponse",o[o.MultiDataResponseStop=16]="MultiDataResponseStop",function(e){e[e.Get=0]="Get",e[e.Post=1]="Post",e[e.Delete=2]="Delete",e[e.Put=3]="Put",e[e.Options=4]="Options",e[e.Head=5]="Head"}(t||(t={})),function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(n||(n={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(r||(r={})),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"}(s||(s={}));class f{static write(e){return`${e}${f.RecordSeparator}`}static parse(e){if(e[e.length-1]!==f.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(f.RecordSeparator);return t.pop(),t}}f.RecordSeparatorCode=30,f.RecordSeparator=String.fromCharCode(f.RecordSeparatorCode);class v{constructor(){}log(e,t){}}v.instance=new v;class y{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,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class m{static get isBrowser(){return!m.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!m.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!m.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function w(e,t){let n="";return S(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${function(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function S(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function A(e,t,n,r,o,i){const a={},[c,u]=T();a[c]=u,e.log(s.Trace,`(${t} transport) sending data. ${w(o,i.logMessageContent)}.`);const l=S(o)?"arraybuffer":"text",d=await n.post(r,{content:o,headers:{...a,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(s.Trace,`(${t} transport) request complete. Response status: ${d.statusCode}.`)}class _{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 C{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${s[e]}: ${t}`;switch(e){case s.Critical:case s.Error:this.out.error(n);break;case s.Warning:this.out.warn(n);break;case s.Information:this.out.info(n);break;default:this.out.log(n)}}}}function T(){let e="X-SignalR-User-Agent";return m.isNode&&(e="User-Agent"),[e,D("8.0.7",k(),m.isNode?"NodeJS":"Browser",I())]}function D(e,t,n,r){let s="Microsoft SignalR/";const o=e.split(".");return s+=`${o[0]}.${o[1]}`,s+=` (${e}; `,s+=t&&""!==t?`${t}; `:"Unknown OS; ",s+=`${n}`,s+=r?`; ${r}`:"; Unknown Runtime Version",s+=")",s}function k(){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 I(){if(m.isNode)return process.versions.node}function b(e){return e.stack?e.stack:e.message?e.message:`${e}`}class E{writeHandshakeRequest(e){return f.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(S(e)){const r=new Uint8Array(e),s=r.indexOf(f.RecordSeparatorCode);if(-1===s)throw new Error("Message is incomplete.");const o=s+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(r.slice(0,o))),n=r.byteLength>o?r.slice(o).buffer:null}else{const r=e,s=r.indexOf(f.RecordSeparator);if(-1===s)throw new Error("Message is incomplete.");const o=s+1;t=r.substring(0,o),n=r.length>o?r.substring(o):null}const r=f.parse(t),s=JSON.parse(r[0]);if(s.type)throw new Error("Expected a handshake response from the server.");return[n,s]}}class N extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class G 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 P extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class U extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class O extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class M extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class x extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}!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"}(i||(i={}));class F{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 _(this,e)}}class L{constructor(e,t,n){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=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},r=()=>{};S(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,r=n}))),this._messages.push(new B(t,this._totalMessageCount,e,r))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;n<this._messages.length;n++){const r=this._messages[n];if(r._id<=e.sequenceId)t=n,S(r._message)?this._bufferedByteCount-=r._message.byteLength:this._bufferedByteCount-=r._message.length,r._resolver();else{if(!(this._bufferedByteCount<this._bufferSize))break;r._resolver()}}-1!==t&&(this._messages=this._messages.slice(t+1))}_shouldProcessMessage(e){if(this._waitForSequenceMessage)return e.type===i.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:i.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 i.Invocation:case i.StreamItem:case i.Completion:case i.StreamInvocation:case i.CancelInvocation:return!0;case i.Close:case i.Sequence:case i.Ping:case i.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:i.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class B{constructor(e,t,n,r){this._message=e,this._id=t,this._resolver=n,this._rejector=r}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(a||(a={}));class W{static create(e,t,n,r,s,o,i){return new W(e,t,n,r,s,o,i)}constructor(e,t,n,r,o,c,u){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(s.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")},y.isRequired(e,"connection"),y.isRequired(t,"logger"),y.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=o?o:3e4,this.keepAliveIntervalInMilliseconds=null!=c?c:15e3,this._statefulReconnectBufferSize=null!=u?u:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new E,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=a.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:i.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!==a.Disconnected&&this._connectionState!==a.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!==a.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=a.Connecting,this._logger.log(s.Debug,"Starting HubConnection.");try{await this._startInternal(),m.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=a.Connected,this._connectionStarted=!0,this._logger.log(s.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=a.Disconnected,this._logger.log(s.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 t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(s.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(s.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 L(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(s.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===a.Disconnected)return this._logger.log(s.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===a.Disconnecting)return this._logger.log(s.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=a.Disconnecting,this._logger.log(s.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(s.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===a.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[n,r]=this._replaceStreamingParams(t),s=this._createStreamInvocation(e,t,r);let o;const a=new F;return a.cancelCallback=()=>{const e=this._createCancelInvocation(s.invocationId);return delete this._callbacks[s.invocationId],o.then((()=>this._sendWithProtocol(e)))},this._callbacks[s.invocationId]=(e,t)=>{t?a.error(t):e&&(e.type===i.Completion?e.error?a.error(new Error(e.error)):a.complete():a.next(e.item))},o=this._sendWithProtocol(s).catch((e=>{a.error(e),delete this._callbacks[s.invocationId]})),this._launchStreams(n,o),a}_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[n,r]=this._replaceStreamingParams(t),s=this._sendWithProtocol(this._createInvocation(e,t,!0,r));return this._launchStreams(n,s),s}invoke(e,...t){const[n,r]=this._replaceStreamingParams(t),s=this._createInvocation(e,t,!1,r);return new Promise(((e,t)=>{this._callbacks[s.invocationId]=(n,r)=>{r?t(r):n&&(n.type===i.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const r=this._sendWithProtocol(s).catch((e=>{t(e),delete this._callbacks[s.invocationId]}));this._launchStreams(n,r)}))}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 n=this._methods[e];if(n)if(t){const r=n.indexOf(t);-1!==r&&(n.splice(r,1),0===n.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 t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case i.Invocation:this._invokeClientMethod(e).catch((e=>{this._logger.log(s.Error,`Invoke client method threw error: ${b(e)}`)}));break;case i.StreamItem:case i.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===i.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(s.Error,`Stream callback threw error: ${b(e)}`)}}break}case i.Ping:break;case i.Close:{this._logger.log(s.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case i.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case i.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(s.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(s.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(s.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(s.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===a.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 t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(s.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(s.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const r=n.slice(),o=!!e.invocationId;let i,a,c;for(const n of r)try{const r=i;i=await n.apply(this,e.arguments),o&&i&&r&&(this._logger.log(s.Error,`Multiple results provided for '${t}'. Sending error to server.`),c=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),a=void 0}catch(e){a=e,this._logger.log(s.Error,`A callback for the method '${t}' threw error '${e}'.`)}c?await this._sendWithProtocol(c):o?(a?c=this._createCompletionMessage(e.invocationId,`${a}`,null):void 0!==i?c=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(s.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),c=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(c)):i&&this._logger.log(s.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(s.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===a.Disconnecting?this._completeClose(e):this._connectionState===a.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===a.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=a.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),m.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(s.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,r=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),o=this._getNextRetryDelay(n++,0,r);if(null===o)return this._logger.log(s.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=a.Reconnecting,e?this._logger.log(s.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(s.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(s.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==a.Reconnecting)return void this._logger.log(s.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(s.Information,`Reconnect attempt number ${n} will start in ${o} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,o)})),this._reconnectDelayHandle=void 0,this._connectionState!==a.Reconnecting)return void this._logger.log(s.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=a.Connected,this._logger.log(s.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(s.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(s.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==a.Reconnecting)return this._logger.log(s.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===a.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(s.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(s.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const r=t[n];try{r(null,e)}catch(t){this._logger.log(s.Error,`Stream 'error' callback called with '${e}' threw error: ${b(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,r){if(n)return 0!==r.length?{arguments:t,streamIds:r,target:e,type:i.Invocation}:{arguments:t,target:e,type:i.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:i.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:i.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let r;r=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,r))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let r=0;r<e.length;r++){const s=e[r];if(this._isObservable(s)){const o=this._invocationId;this._invocationId++,t[o]=s,n.push(o.toString()),e.splice(r,1)}}return[t,n]}_isObservable(e){return e&&e.subscribe&&"function"==typeof e.subscribe}_createStreamInvocation(e,t,n){const r=this._invocationId;return this._invocationId++,0!==n.length?{arguments:t,invocationId:r.toString(),streamIds:n,target:e,type:i.StreamInvocation}:{arguments:t,invocationId:r.toString(),target:e,type:i.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:i.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:i.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:i.Completion}:{invocationId:e,result:n,type:i.Completion}}_createCloseMessage(){return{type:i.Close}}}const $=[0,2e3,1e4,3e4,null];class V{constructor(e){this._retryDelays=void 0!==e?[...e,null]:$}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class q{}q.Authorization="Authorization",q.Cookie="Cookie";class H{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class K{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""}}class j extends K{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 n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[q.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[q.Authorization]&&delete e.headers[q.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class z extends K{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch||m.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!==c.g)return c.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 t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new R});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(s.Warning,"Timeout from HTTP request."),n=new G}),r)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},S(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{r=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:t.signal})}catch(e){if(n)throw n;throw this._logger.log(s.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await J(r,"text");throw new N(e||r.statusText,r.status)}const i=J(r,e.responseType),a=await i;return new H(r.status,r.statusText,a)}getCookieString(e){let t="";return m.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function J(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class X extends K{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new R):e.method?e.url?new Promise(((t,n)=>{const r=new XMLHttpRequest;r.open(e.method,e.url,!0),r.withCredentials=void 0===e.withCredentials||e.withCredentials,r.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(S(e.content)?r.setRequestHeader("Content-Type","application/octet-stream"):r.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const o=e.headers;o&&Object.keys(o).forEach((e=>{r.setRequestHeader(e,o[e])})),e.responseType&&(r.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{r.abort(),n(new R)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new H(r.status,r.statusText,r.response||r.responseText)):n(new N(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(s.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new N(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(s.Warning,"Timeout from HTTP request."),n(new G)},r.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class Y extends K{constructor(e){if(super(),"undefined"!=typeof fetch||m.isNode)this._httpClient=new z(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new X(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 Q{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{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new Q,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(y.isRequired(e,"url"),y.isRequired(t,"transferFormat"),y.isIn(t,r,"transferFormat"),this._url=e,this._logger.log(s.Trace,"(LongPolling transport) Connecting."),t===r.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=T(),i={[n]:o,...this._options.headers},a={abortSignal:this._pollAbort.signal,headers:i,timeout:1e5,withCredentials:this._options.withCredentials};t===r.Binary&&(a.responseType="arraybuffer");const c=`${e}&_=${Date.now()}`;this._logger.log(s.Trace,`(LongPolling transport) polling: ${c}.`);const u=await this._httpClient.get(c,a);200!==u.statusCode?(this._logger.log(s.Error,`(LongPolling transport) Unexpected response code: ${u.statusCode}.`),this._closeError=new N(u.statusText||"",u.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,a)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(s.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(s.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(s.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new N(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(s.Trace,`(LongPolling transport) data received. ${w(r.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(s.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof G?this._logger.log(s.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(s.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(s.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?A(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(s.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(s.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=T();e[t]=n;const r={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let o;try{await this._httpClient.delete(this._url,r)}catch(e){o=e}o?o instanceof N&&(404===o.statusCode?this._logger.log(s.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(s.Trace,`(LongPolling transport) Error sending a DELETE request: ${o}`)):this._logger.log(s.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(s.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(s.Trace,e),this.onclose(this._closeError)}}}class ee{constructor(e,t,n,r){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=r,this.onreceive=null,this.onclose=null}async connect(e,t){return y.isRequired(e,"url"),y.isRequired(t,"transferFormat"),y.isIn(t,r,"transferFormat"),this._logger.log(s.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let i,a=!1;if(t===r.Text){if(m.isBrowser||m.isWebWorker)i=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,s]=T();n[r]=s,i=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{i.onmessage=e=>{if(this.onreceive)try{this._logger.log(s.Trace,`(SSE transport) data received. ${w(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onerror=e=>{a?this._close():o(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."))},i.onopen=()=>{this._logger.log(s.Information,`SSE connected to ${this._url}`),this._eventSource=i,a=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?A(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 te{constructor(e,t,n,r,s,o){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=r,this._webSocketConstructor=s,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=o}async connect(e,t){let n;return y.isRequired(e,"url"),y.isRequired(t,"transferFormat"),y.isIn(t,r,"transferFormat"),this._logger.log(s.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,i)=>{let a;e=e.replace(/^http/,"ws");const c=this._httpClient.getCookieString(e);let u=!1;if(m.isNode||m.isReactNative){const t={},[r,s]=T();t[r]=s,n&&(t[q.Authorization]=`Bearer ${n}`),c&&(t[q.Cookie]=c),a=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);a||(a=new this._webSocketConstructor(e)),t===r.Binary&&(a.binaryType="arraybuffer"),a.onopen=t=>{this._logger.log(s.Information,`WebSocket connected to ${e}.`),this._webSocket=a,u=!0,o()},a.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(s.Information,`(WebSockets transport) ${t}.`)},a.onmessage=e=>{if(this._logger.log(s.Trace,`(WebSockets transport) data received. ${w(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},a.onclose=e=>{if(u)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.",i(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(s.Trace,`(WebSockets transport) sending data. ${w(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(s.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 ne{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,y.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new C(s.Information):null===n?v.instance:void 0!==n.log?n:new C(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let r=null,o=null;if(m.isNode){const e=require;r=e("ws"),o=e("eventsource")}m.isNode||"undefined"==typeof WebSocket||t.WebSocket?m.isNode&&!t.WebSocket&&r&&(t.WebSocket=r):t.WebSocket=WebSocket,m.isNode||"undefined"==typeof EventSource||t.EventSource?m.isNode&&!t.EventSource&&void 0!==o&&(t.EventSource=o):t.EventSource=EventSource,this._httpClient=new j(t.httpClient||new Y(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||r.Binary,y.isIn(e,r,"transferFormat"),this._logger.log(s.Debug,`Starting connection with transfer format '${r[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(s.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(s.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 re(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(s.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(s.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(s.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(s.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==n.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(n.WebSockets),await this._startTransport(t,e)}else{let n=null,r=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new R("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.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(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}r++}while(n.url&&r<100);if(100===r&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof Z&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(s.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(s.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,r]=T();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(s.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...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 n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new M("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof N&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(s.Error,t),Promise.reject(new M(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,r,o){let i=this._createConnectUrl(e,r.connectionToken);if(this._isITransport(t))return this._logger.log(s.Debug,"Connection was provided