lavva.exalushome.portos
Version:
Library implementing communication and abstraction layers for Portos 433MHz API in ExalusHome system
2 lines • 507 kB
JavaScript
(()=>{"use strict";var e,t,n,r,o,s,i={d:(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}};i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.d({},{J:()=>Ey}),function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error",e[e.None=4]="None"}(e||(e={}));class a{constructor(){this._blockedServices=[],this._logLevel=e.Debug,void 0!==window.loglevel&&null!==window.loglevel&&(this._logLevel=window.loglevel),window.logger=this}EnableStackTrace(){a.DoesThrowStackTrace=!0}DisableStackTrace(){a.DoesThrowStackTrace=!1}IsBlocked(e){return void 0!==e&&this._blockedServices.any((t=>t==e))}DisableLogsFrom(e){this._blockedServices.all((t=>t!=e))&&this._blockedServices.push(e),this.Debug(a.ServiceName,`Disabling logs from ${e}`)}EnableLogsFrom(e){this._blockedServices.any((t=>t==e))&&(this._blockedServices=this._blockedServices.where((t=>t!=e)).toArray()),this.Debug(a.ServiceName,`Enaabling logs from ${e}`)}get LogLevel(){return this._logLevel}set LogLevel(e){this._logLevel=e}GetServiceName(){return a.ServiceName}GetTimeStamp(){const e=new Date;return`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()} | `}Warning(t,n){switch(this._logLevel){case e.Warning:case e.Info:case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.warn(`${this.GetTimeStamp()}[WARN] ${t}`):console.warn(`${this.GetTimeStamp()}[WARN] [${t}] ${n}`))}Error(t,n){switch(this._logLevel){case e.Warning:case e.Info:case e.Debug:case e.Error:break;case e.None:default:return}null!=t&&(null==n?console.error(`${this.GetTimeStamp()}[ERROR] ${t}`):console.error(`${this.GetTimeStamp()}[ERROR] [${t}] ${n}`))}Info(t,n){switch(this._logLevel){case e.Info:case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.info(`${this.GetTimeStamp()}[INFO] ${t}`):console.info(`${this.GetTimeStamp()}[INFO] [${t}] ${n}`))}Debug(t,n){switch(this._logLevel){case e.Debug:break;case e.None:default:return}void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.debug(`${this.GetTimeStamp()}[DEBUG] ${t}`):a.DoesThrowStackTrace||!0===window.stacktrace?console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n} \nstack:\n${(new Error).stack}}`):console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n}`))}Log(t,n){this._logLevel!==e.None&&(void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.log(`${this.GetTimeStamp()}[LOG] ${t}`):console.log(`${this.GetTimeStamp()}[LOG] [${t}] ${n}`)))}}a.ServiceName="LoggerService",a.DoesThrowStackTrace=!1;class c{constructor(){this.handlers=[]}Subscribe(e){this.handlers.includes(e)||this.handlers.push(e)}Unsubscribe(e){this.handlers=this.handlers.filter((t=>t!==e))}Invoke(e){this.handlers.slice(0).forEach((t=>{var n;try{t(e)}catch(e){null===(n=u.Log)||void 0===n||n.Error(e)}}))}}class u{constructor(){this._services=new Map,this._serviceRegistrationEvent=new c}static get Instance(){const e=globalThis;if(e.__dc_instance)return e.__dc_instance;const t=new u;return e.__dc_instance=t,"undefined"==typeof window||window.LavvaDI||(window.appservices=t),this.Log=new a,this.Log.Warning("Initializing DependencyContainer"),t.RegisterService(this.Log),this.IsInitialized=!0,t}RegisterService(e){this._services.set(e.GetServiceName(),e),this._serviceRegistrationEvent.Invoke(e)}GetService(e){return this._services.get(e)}GetServiceAsync(e,t){return this._services.has(e)?Promise.resolve(this._services.get(e)):new Promise(((n,r)=>{const o=r=>{r.GetServiceName()===e&&(this._serviceRegistrationEvent.Unsubscribe(o),null==t||t.CancellationEvent.Unsubscribe(s),n(r))},s=()=>{this._serviceRegistrationEvent.Unsubscribe(o),r(new Error("cancelled"))};null==t||t.CancellationEvent.Subscribe(s),this._serviceRegistrationEvent.Subscribe(o)}))}GetServiceWithTimeoutAsync(e,t){return this._services.has(e)?Promise.resolve(this._services.get(e)):new Promise(((n,r)=>{const o=t=>{t.GetServiceName()===e&&(window.clearTimeout(s),this._serviceRegistrationEvent.Unsubscribe(o),n(t))},s=window.setTimeout((()=>{this._serviceRegistrationEvent.Unsubscribe(o),r(new Error(`timeout waiting for "${e}"`))}),t);this._serviceRegistrationEvent.Subscribe(o)}))}}u.IsInitialized=!1;class l{GetServiceName(){return l.ServiceName}GetResourceName(e,t){return`_exalus_${hy.WorksInContextOf}_${e}_${t}`}Remove(e,t){localStorage.removeItem(this.GetResourceName(e,t))}DropStorage(e){const t=`_exalus_${hy.WorksInContextOf}_${e}`;Object.keys(localStorage).filter((e=>e.startsWith(t))).forEach((e=>{var t;null===(t=u.Log)||void 0===t||t.Warning(l.ServiceName,`Clearing API cache for key: ${e}`),localStorage.removeItem(e)}))}Save(e,t,n){localStorage.setItem(this.GetResourceName(e,t),JSON.stringify(n))}Read(e,t){var n;try{let n=this.GetResourceName(e,t),r=localStorage.getItem(n);return null==r?null:JSON.parse(r)}catch(r){return null===(n=u.Log)||void 0===n||n.Error(l.ServiceName,`Exception has occurred while reading ${this.GetResourceName(e,t)}`),null}}}l.ServiceName="LocalStorageService",function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(t||(t={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(n||(n={})),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"}(r||(r={}));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 h{constructor(){}log(e,t){}}h.instance=new h;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,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class g{static get isBrowser(){return!g.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!g.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!g.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function f(e,t){let n="";return v(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 v(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function y(e,t,n,o,s,i){const a={},[c,u]=S();a[c]=u,e.log(r.Trace,`(${t} transport) sending data. ${f(s,i.logMessageContent)}.`);const l=v(s)?"arraybuffer":"text",d=await n.post(o,{content:s,headers:{...a,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(r.Trace,`(${t} transport) request complete. Response status: ${d.statusCode}.`)}class m{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 w{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${r[e]}: ${t}`;switch(e){case r.Critical:case r.Error:this.out.error(n);break;case r.Warning:this.out.warn(n);break;case r.Information:this.out.info(n);break;default:this.out.log(n)}}}}function S(){let e="X-SignalR-User-Agent";return g.isNode&&(e="User-Agent"),[e,A("8.0.7",_(),g.isNode?"NodeJS":"Browser",C())]}function A(e,t,n,r){let o="Microsoft SignalR/";const s=e.split(".");return o+=`${s[0]}.${s[1]}`,o+=` (${e}; `,o+=t&&""!==t?`${t}; `:"Unknown OS; ",o+=`${n}`,o+=r?`; ${r}`:"; Unknown Runtime Version",o+=")",o}function _(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function C(){if(g.isNode)return process.versions.node}function D(e){return e.stack?e.stack:e.message?e.message:`${e}`}class T{writeHandshakeRequest(e){return d.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(v(e)){const r=new Uint8Array(e),o=r.indexOf(d.RecordSeparatorCode);if(-1===o)throw new Error("Message is incomplete.");const s=o+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(r.slice(0,s))),n=r.byteLength>s?r.slice(s).buffer:null}else{const r=e,o=r.indexOf(d.RecordSeparator);if(-1===o)throw new Error("Message is incomplete.");const s=o+1;t=r.substring(0,s),n=r.length>s?r.substring(s):null}const r=d.parse(t),o=JSON.parse(r[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[n,o]}}class k extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class I extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class E extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class b extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class G extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class N extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class R extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class P 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"}(o||(o={}));class U{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 m(this,e)}}class O{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=()=>{};v(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 M(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,v(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===o.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:o.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 o.Invocation:case o.StreamItem:case o.Completion:case o.StreamInvocation:case o.CancelInvocation:return!0;case o.Close:case o.Sequence:case o.Ping:case o.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:o.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class M{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"}(s||(s={}));class x{static create(e,t,n,r,o,s,i){return new x(e,t,n,r,o,s,i)}constructor(e,t,n,i,a,c,u){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(r.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(t,"logger"),p.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=a?a:3e4,this.keepAliveIntervalInMilliseconds=null!=c?c:15e3,this._statefulReconnectBufferSize=null!=u?u:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=i,this._handshakeProtocol=new T,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=s.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:o.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!==s.Disconnected&&this._connectionState!==s.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!==s.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=s.Connecting,this._logger.log(r.Debug,"Starting HubConnection.");try{await this._startInternal(),g.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=s.Connected,this._connectionStarted=!0,this._logger.log(r.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=s.Disconnected,this._logger.log(r.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(r.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(r.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 O(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(r.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===s.Disconnected)return this._logger.log(r.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===s.Disconnecting)return this._logger.log(r.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=s.Disconnecting,this._logger.log(r.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(r.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===s.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new E("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 i;const a=new U;return a.cancelCallback=()=>{const e=this._createCancelInvocation(s.invocationId);return delete this._callbacks[s.invocationId],i.then((()=>this._sendWithProtocol(e)))},this._callbacks[s.invocationId]=(e,t)=>{t?a.error(t):e&&(e.type===o.Completion?e.error?a.error(new Error(e.error)):a.complete():a.next(e.item))},i=this._sendWithProtocol(s).catch((e=>{a.error(e),delete this._callbacks[s.invocationId]})),this._launchStreams(n,i),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),o=this._sendWithProtocol(this._createInvocation(e,t,!0,r));return this._launchStreams(n,o),o}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===o.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 o.Invocation:this._invokeClientMethod(e).catch((e=>{this._logger.log(r.Error,`Invoke client method threw error: ${D(e)}`)}));break;case o.StreamItem:case o.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===o.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(r.Error,`Stream callback threw error: ${D(e)}`)}}break}case o.Ping:break;case o.Close:{this._logger.log(r.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 o.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case o.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(r.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(r.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(r.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(r.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===s.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(r.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(r.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 o=n.slice(),s=!!e.invocationId;let i,a,c;for(const n of o)try{const o=i;i=await n.apply(this,e.arguments),s&&i&&o&&(this._logger.log(r.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(r.Error,`A callback for the method '${t}' threw error '${e}'.`)}c?await this._sendWithProtocol(c):s?(a?c=this._createCompletionMessage(e.invocationId,`${a}`,null):void 0!==i?c=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(r.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(r.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(r.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new E("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===s.Disconnecting?this._completeClose(e):this._connectionState===s.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===s.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=s.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),g.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(r.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),i=this._getNextRetryDelay(n++,0,o);if(null===i)return this._logger.log(r.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=s.Reconnecting,e?this._logger.log(r.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(r.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(r.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==s.Reconnecting)return void this._logger.log(r.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==i;){if(this._logger.log(r.Information,`Reconnect attempt number ${n} will start in ${i} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,i)})),this._reconnectDelayHandle=void 0,this._connectionState!==s.Reconnecting)return void this._logger.log(r.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=s.Connected,this._logger.log(r.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(r.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(r.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==s.Reconnecting)return this._logger.log(r.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===s.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),i=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(r.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(r.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(r.Error,`Stream 'error' callback called with '${e}' threw error: ${D(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:o.Invocation}:{arguments:t,target:e,type:o.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:o.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:o.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 o=e[r];if(this._isObservable(o)){const s=this._invocationId;this._invocationId++,t[s]=o,n.push(s.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:o.StreamInvocation}:{arguments:t,invocationId:r.toString(),target:e,type:o.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:o.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:o.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:o.Completion}:{invocationId:e,result:n,type:o.Completion}}_createCloseMessage(){return{type:o.Close}}}const F=[0,2e3,1e4,3e4,null];class L{constructor(e){this._retryDelays=void 0!==e?[...e,null]:F}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class B{}B.Authorization="Authorization",B.Cookie="Cookie";class W{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class ${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 V extends ${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[B.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[B.Authorization]&&delete e.headers[B.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class q extends ${constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch||g.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!==i.g)return i.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 E;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 E});let o,s=null;if(e.timeout){const o=e.timeout;s=setTimeout((()=>{t.abort(),this._logger.log(r.Warning,"Timeout from HTTP request."),n=new I}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},v(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=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(r.Warning,`Error from HTTP request. ${e}.`),e}finally{s&&clearTimeout(s),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await H(o,"text");throw new k(e||o.statusText,o.status)}const i=H(o,e.responseType),a=await i;return new W(o.status,o.statusText,a)}getCookieString(e){let t="";return g.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function H(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 K extends ${constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new E):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(v(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const s=e.headers;s&&Object.keys(s).forEach((e=>{o.setRequestHeader(e,s[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new E)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new W(o.status,o.statusText,o.response||o.responseText)):n(new k(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(r.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new k(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(r.Warning,"Timeout from HTTP request."),n(new I)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class j extends ${constructor(e){if(super(),"undefined"!=typeof fetch||g.isNode)this._httpClient=new q(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new K(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new E):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 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 J{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new z,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(p.isRequired(e,"url"),p.isRequired(t,"transferFormat"),p.isIn(t,n,"transferFormat"),this._url=e,this._logger.log(r.Trace,"(LongPolling transport) Connecting."),t===n.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[o,s]=S(),i={[o]:s,...this._options.headers},a={abortSignal:this._pollAbort.signal,headers:i,timeout:1e5,withCredentials:this._options.withCredentials};t===n.Binary&&(a.responseType="arraybuffer");const c=`${e}&_=${Date.now()}`;this._logger.log(r.Trace,`(LongPolling transport) polling: ${c}.`);const u=await this._httpClient.get(c,a);200!==u.statusCode?(this._logger.log(r.Error,`(LongPolling transport) Unexpected response code: ${u.statusCode}.`),this._closeError=new k(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(r.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(r.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(r.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new k(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(r.Trace,`(LongPolling transport) data received. ${f(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(r.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof I?this._logger.log(r.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(r.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(r.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?y(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(r.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(r.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=S();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let s;try{await this._httpClient.delete(this._url,o)}catch(e){s=e}s?s instanceof k&&(404===s.statusCode?this._logger.log(r.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(r.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this._logger.log(r.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(r.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(r.Trace,e),this.onclose(this._closeError)}}}class X{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 p.isRequired(e,"url"),p.isRequired(t,"transferFormat"),p.isIn(t,n,"transferFormat"),this._logger.log(r.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((o,s)=>{let i,a=!1;if(t===n.Text){if(g.isBrowser||g.isWebWorker)i=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,o]=S();n[r]=o,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(r.Trace,`(SSE transport) data received. ${f(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onerror=e=>{a?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."))},i.onopen=()=>{this._logger.log(r.Information,`SSE connected to ${this._url}`),this._eventSource=i,a=!0,o()}}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?y(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 Y{constructor(e,t,n,r,o,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=r,this._webSocketConstructor=o,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let o;return p.isRequired(e,"url"),p.isRequired(t,"transferFormat"),p.isIn(t,n,"transferFormat"),this._logger.log(r.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(o=await this._accessTokenFactory()),new Promise(((s,i)=>{let a;e=e.replace(/^http/,"ws");const c=this._httpClient.getCookieString(e);let u=!1;if(g.isNode||g.isReactNative){const t={},[n,r]=S();t[n]=r,o&&(t[B.Authorization]=`Bearer ${o}`),c&&(t[B.Cookie]=c),a=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else o&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(o)}`);a||(a=new this._webSocketConstructor(e)),t===n.Binary&&(a.binaryType="arraybuffer"),a.onopen=t=>{this._logger.log(r.Information,`WebSocket connected to ${e}.`),this._webSocket=a,u=!0,s()},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(r.Information,`(WebSockets transport) ${t}.`)},a.onmessage=e=>{if(this._logger.log(r.Trace,`(WebSockets transport) data received. ${f(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(r.Trace,`(WebSockets transport) sending data. ${f(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(r.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 Q{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,p.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new w(r.Information):null===n?h.instance:void 0!==n.log?n:new w(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 o=null,s=null;if(g.isNode){const e=require;o=e("ws"),s=e("eventsource")}g.isNode||"undefined"==typeof WebSocket||t.WebSocket?g.isNode&&!t.WebSocket&&o&&(t.WebSocket=o):t.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||t.EventSource?g.isNode&&!t.EventSource&&void 0!==s&&(t.EventSource=s):t.EventSource=EventSource,this._httpClient=new V(t.httpClient||new j(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||n.Binary,p.isIn(e,n,"transferFormat"),this._logger.log(r.Debug,`Starting connection with transfer format '${n[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(r.Error,e),await this._stopPromise,Promise.reject(new E(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(r.Error,e),Promise.reject(new E(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 Z(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(r.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(r.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(r.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(r.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let n=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==t.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(t.WebSockets),await this._startTransport(n,e)}else{let t=null,r=0;do{if(t=await this._getNegotiationResponse(n),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new E("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&&(n=t.url),t.accessToken){const e=t.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}r++}while(t.url&&r<100);if(100===r&&t.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(n,this._options.transport,t,e)}this.transport instanceof J&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(r.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(r.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,o]=S();t[n]=o;const s=this._resolveNegotiateUrl(e);this._logger.log(r.Debug,`Sending negotiation request: ${s}.`);try{const e=await this._httpClient.post(s,{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 R("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 k&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(r.Error,t),Promise.reject(new R(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,n,o,s){let i=this._createConnectUrl(e,o.connectionToken);if(this._isITransport(n))return this._logger.log(r.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,await this._startTransport(i,s),void(this.connectionId=o.connectionId);const a=[],c=o.availableTransports||[];let u=o;for(const o of c){const c=this._resolveTransportOrError(o,n,s,!0===(null==u?void 0:u.useStatefulReconnect));if(c instanceof Error)a.push(`${o.transport} failed:`),a.push(c);else if(this._isITransport(c)){if(this.transport=c,!u){try{u=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}i=this._createConnectUrl(e,u.connectionToken)}try{return await this._startTransport(i,s),void(this.connectionId=u.connectionId)}catch(e){if(this._logger.log(r.Error,`Failed to start the transport '${o.transport}': ${e}`),u=void 0,a.push(new N(`${o.transport} failed: ${e}`,t[o.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(r.Debug,e),Promise.reject(new E(e))}}}}return a.length>0?Promise.reject(new P(`Unable to connect to the server with any of the available transports. ${a.join(" ")}`,a)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case t.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Y(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case t.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 t.LongPolling:return new J(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 n=>{let r=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{r=!0}r&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,o,s,i){const a=t[e.transport];if(null==a)return this._logger.log(r.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||!!(t&e)}(o,a))return this._logger.log(r.Debug,`Skipping transport '${t[a]}' because it was disabled by the client.`),new G(`'${t[a]}' is disabled by the client.`,a);if(!(e.transferFormats.map((e=>n[e])).indexOf(s)>=0))return this._logger.log(r.Debug,`Skipping transport '${t[a]}' because it does not support the requested transfer format '${n[s]}'.`),new Error(`'${t[a]}' does not support ${n[s]}.`);if(a===t.WebSockets&&!this._options.WebSocket||a===t.ServerSentEvents&&!this._options.EventSource)return this._logger.log(r.Debug,`Skipping transport '${t[a]}' because it is not supported in your environment.'`),new b(`'${t[a]}' is not supported in your environment.`,a);this._logger.log(r.Debug,`Selecting transport '${t[a]}'.`);try{return this.features.reconnect=a===t.WebSockets?i:void 0,this._constructTransport(a)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(r.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(r.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(r.Error,`Connection disconnected with error '${e}'.`):this._logger.log(r.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(r.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(t){this._logger.log(r.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(r.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(!g.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(r.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class Z{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new ee,this._transportResult=new ee,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new ee),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 ee;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Z._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)),n=new Uint8Array(t);let r=0;for(const t of e)n.set(new Uint8Array(t),r),r+=t.byteLength;return n.buffer}}class ee{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class te{constructor(){this.name="json",this.version=2,this.transferFormat=n.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=h.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 o.Invocation:this._isInvocationMessage(n);break;case o.StreamItem:this._isStreamItemMessage(n);break;case o.Completion:this._isCompletionMessage(n);break;case o.Ping:case o.Close:break;case o.Ack:this._isAckMessage(n);break;case o.Sequence:this._isSequenceMessage(n);break;default:t.log(r.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 ne={trace:r.Trace,debug:r.Debug,info:r.Information,information:r.Information,warn:r.Warning,warning:r.Warning,error:r.Error,critical:r.Critical,none:r.None};class re{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=ne[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new w(t)}else this.logger=new w(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 Q(this.url,e);return x.create(t,this.logger||h.instance,this.protocol||new te,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}class oe{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 o(e,t,n,o,s,i){return r(function(e,t){return e<<t|e>>>32-t}(r(r(t,e),r(o,i)),s),n)}function s(e,t,n,r,s,i,a){return o(t&n|~t&r,e,t,s,i,a)}function i(e,t,n,r,s,i,a){return o(t&r|n&~r,e,t,s,i,a)}function a(e,t,n,r,s,i,a){return o(t^n^r,e,t,s,i,a)}function c(e,t,n,r,s,i,a){return o(n^(t|~r),e,t,s,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=s(f,v,y,m,g[u+0],7,-680876936),m=s(m,f,v,y,g[u+1],12,-389564586),y=s(y,m,f,v,g[u+2],17,606105819),v=s(v,y,m,f,g[u+3],22,-1044525330),f=s(f,v,y,m,g[u+4],7,-176418897),m=s(m,f,v,y,g[u+5],12,1200080426),y=s(y,m,f,v,g[u+6],17,-1473231341),v=s(v,y,m,f,g[u+7],22,-45705983),f=s(f,v,y,m,g[u+8],7,1770035416),m=s(m,f,v,y,g[u+9],12,-1958414417),y=s(y,m,f,v,g[u+10],17,-42063),v=s(v,y,m,f,g[u+11],22,-1990404162),f=s(f,v,y,m,g[u+12],7,1804603682),m=s(m,f,v,y,g[u+13],12,-40341101),y=s(y,m,f,v,g[u+14],17,-1502002290),v=s(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 se{static Delay(e){return new Promise((t=>setTimeout(t,e)))}}function ie(e){return new Map(Object.entries(e))}function ae(e,t="export.csv"){const n=new Blob(["\ufeff",e],{type:"text/csv;charset=utf-8;"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=t,o.style.display="none",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}class ce{constructor(){this.TransactionId=oe.GenerateUUID()}}var ue,le,de,he,pe,ge,fe,ve,ye,me,we,Se,Ae,_e,Ce;(Ae=ue||(ue={}))[Ae.OK=0]="OK",Ae[Ae.UnknownError=1]="UnknownError",Ae[Ae.FatalError=2]="FatalError",Ae[Ae.WrongData=3]="WrongData",Ae[Ae.ResourceDoesNotExists=4]="ResourceDoesNotExists",Ae[Ae.NoPermissionToPerformThisOperation=5]="NoPermissionToPerformThisOperation",Ae[Ae.SessionHasAlreadyLoggedOnUser=6]="SessionHasAlreadyLoggedOnUser",Ae[Ae.OperationNotPermitted=7]="OperationNotPermitted",Ae[Ae.NoPermissionsToCallGivenResource=8]="NoPermissionsToCallGivenResource",Ae[Ae.ResourceIsNotAvailable=9]="ResourceIsNotAvailable",Ae[Ae.Error=10]="Error",Ae[Ae.NoData=11]="NoData",Ae[Ae.NotSupportedMethod=12]="NotSupportedMethod",Ae[Ae.UserIsNotLoggedIn=13]="UserIsNotLoggedIn",Ae[Ae.MultiDataResponseStart=14]="MultiDataResponseStart",Ae[Ae.MultiDataResponse=15]="MultiDataResponse",Ae[Ae.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"}(le||(le={}));class De{constructor(e,t){this.serialNumber=e,this.pin=t,this.SerialNumber=e,this.PIN=t}}!function(e){e[e.ByCloud=0]="ByCloud",e[e.LocalNetwork=1]="LocalNetwork",e[e.P2P=2]="P2P"}(de||(de={})),function(e){e[e.FailedToConnect=0]="FailedToConnect",e[e.AuthorizationFailed=1]="AuthorizationFailed",e[e.FailedToConnectToServer=2]="FailedToConnectToServer",e[e.Connected=3]="Connected",e[e.ControllerIsNotConnected=4]="ControllerIsNotConnected"}(he||(he={})),function(e){e[e.Disconnected=0]="Disconnected",e[e.Connecting=1]="Connecting",e[e.Connected=3]="Connected",e[e.Disconnecting=4]="Disconnecting",e[e.Failed=5]="Failed",e[e.Reconnecting=6]="Reconnecting",e[e.ConnectedAndAuthorized=7]="ConnectedAndAuthorized"}(pe||(pe={}));class Te extends Error{constructor(e){super(e),this.name="StreamError"}}class ke{constructor(){this._log=hy.Get(a.ServiceName),this.handlers=[]}Subscribe(e){this.handlers.includes(e)||this.handlers.push(e)}Unsubscribe(e){this.handlers=this.handlers.filter((t=>t!==e))}Invoke(){this.handlers.slice(0).forEach((e=>{try{e()}catch(e){this._log.Error(e)}}))}}!function(e){e.CannotExportConfiguration="CannotExportConfiguration"}(ge||(ge={})),(Ce=fe||(fe={}))[Ce.Any=0]="Any",Ce[Ce.Guest=10]="Guest",Ce[Ce.Standard=20]="Standard",Ce[Ce.Admin=30]="Admin",Ce[Ce.Installator=40]="Installator",Ce[Ce.Support=50]="Support",(_e=ve||(ve={}))[_e.Unknown=0]="Unknown",_e[_e.Men=1]="Men",_e[_e.Woman=2]="Woman",_e[_e.Other=3]="Other",function(e){e[e.En_Us=0]="En_Us",e[e.Pl_Pl=1]="Pl_Pl"}(ye||(ye={})),function(e){e[e.Unknown=0]="Unknown",e[e.WrongAuthData=1]="WrongAuthData",e[e.NoResponseFromController=2]="NoResponseFromController",e[e.AuthDisabled=3]="AuthDisabled",e[e.MethodNotSupported=4]="MethodNotSupported"}(me||(me={}));class Ie{constructor(e,t){this._type=we.Unknown,this._data="",this._type=e,this._data=t}get Type(){return this._type}set Type(e){this._type=e}get Data(){return this._data}set Data(e){this._data=e}}class Ee{constructor(e,t){this._type=null,this._data="",this._type=e,this._data=t}get Type(){return this._type}set Type(e){this._type=e}get Data(){return this._data}set Data(e){this._data=e}}!function(e){e[e.ResourceDoesNotExists=-6]="ResourceDoesNotExists",e[e.UnknownError=-5]="UnknownError",e[e.NoPermissions=-4]="NoPermissions",e[e.WrongData=-3]="WrongData",e[e.ControllerResponseTimeout=-2]="ControllerResponseTimeout",e[e.Failed=-1]="Failed",e[e.Unknown=0]="Unknown",e[e.Changed=1]="Changed"}(we||(we={})),function(e){e[e.Device=1]="Device",e[e.Person=2]="Person",e[e.DevicesGroups=3]="DevicesGroups"}(Se||(Se={}));class be{constructor(){this._guid="",this._ownerGuid="",this._ownerIdentity="",this._base64Image="",this._imageType=Se.Device,this._dateTime=""}get Guid(){return this._guid}get OwnerGuid(){return this._ownerGuid}get OwnerIdentity(){return this._ownerIdentity}get Base64Image(){return this._base64Image}get ImageType(){return this._imageType}get DateTime(){return this._dateTime}set Base64Image(e){this._base64Image=e}set Guid(e){this._guid=e}set OwnerGuid(e){this._ownerGuid=e}set OwnerIdentity(e){this._ownerIdentity=e}set ImageType(e){this._imageType=e}}var Ge=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Ne{constructor(){this._imageExistsCaseNumber=0,this._connection=hy.Get(It.ServiceName),this._logger=hy.Get(a.ServiceName)}GetServiceName(){return Ne.ServiceName}AddPictureAsync(e){return Ge(this,void 0,void 0,(function*(){var t,n;try{if(e.Base64Image.length*(3/4)>=512e3)return this._logger.Error(Ne.ServiceName,"Cannot add picture - Base64Imgae size exceeded."),ue.WrongData;let r=new Image;const o=new Promise(((t,n)=>{r.src=e.Base64Image,r.onload=function(){t(!0)},setTimeout((()=>t(!1)),5e3)}));if(!(yield o))return this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot load image - ensure that given base64 string is an image!"),ue.WrongData;if(0===r.height||0===r.width)return this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot read width/height of image - ensure that given base64 string is an image!"),ue.WrongData;if(null!=e.Guid&&""!=e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot add picture - Guid must be empty."),ue.WrongData;const s=new Pe;s.Guid=oe.GenerateUUID(),s.DateTime=(new Date).toISOString(),s.ImageType=e.ImageType,s.OwnerGuid=`${e.OwnerGuid}_${e.OwnerIdentity}`,s.Base64Image=e.Base64Image;const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Oe(s.Guid),8e3,!1);if(null==i||null==i.Status)return this._logger.Error(Ne.ServiceName,"Cannot add picture - unknown error!"),ue.UnknownError;if(i.Status==ue.ResourceDoesNotExists){const e=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Fe(s),8e3,!1);return null==e||null==e.Status?(this._logger.Error(Ne.ServiceName,"Cannot add picture - unknown error!"),ue.UnknownError):e.Status}return i.Status==ue.OK?(this._logger.Warning(Ne.ServiceName,"Cannot add picture - picture already exists, trying to add with regenerated GUID."),this._imageExistsCaseNumber<2?(this._imageExistsCaseNumber++,this.AddPictureAsync(e)):ue.UnknownError):(this._logger.Error(Ne.ServiceName,"Cannot add picture - cannot get current picture status."),ue.Error)}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot add picture! ${e}`),ue.FatalError}}))}EditPictureAsync(e){return Ge(this,void 0,void 0,(function*(){var t,n,r,o;try{if(""==e.Guid||null==e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - guid is empty."),ue.WrongData;if(e.Base64Image.length*(3/4)>=512e3)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - Base64Imgae size exceeded."),ue.WrongData;let s=new Image;const i=new Promise(((t,n)=>{s.src=e.Base64Image,s.onload=function(){t(!0)},setTimeout((()=>t(!1)),5e3)}));if(!(yield i))return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot load image - ensure that given base64 string is an image!"),ue.WrongData;if(0===s.height||0===s.width)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot read width/height of image - ensure that given base64 string is an image!"),ue.WrongData;const a=new Pe;a.DateTime=(new Date).toISOString(),a.ImageType=e.ImageType,a.Base64Image=e.Base64Image,a.Guid=e.Guid,e.Guid.includes("profilePicture")||e.Guid.includes("devices_group")?a.OwnerGuid=e.OwnerGuid:a.OwnerGuid=`${e.OwnerGuid}_${e.OwnerIdentity}`;const c=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Oe(a.Guid),8e3,!1);if(null===(n=u.Log)||void 0===n||n.Error(Ne.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! EditPictureAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),null==c||null==c.Status)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ue.UnknownError;if(c.Status==ue.ResourceDoesNotExists)return this._logger.Error(Ne.ServiceName,"Cannot edit picture - picture not exists."),ue.OperationNotPermitted;if(c.Status==ue.OK){const e=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Fe(a),8e3,!1);return null===(o=u.Log)||void 0===o||o.Error(Ne.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! EditPictureAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),null==e||null==e.Status?(this._logger.Error(Ne.ServiceName,"Cannot edit picture - unknown error!"),ue.UnknownError):e.Status}return this._logger.Error(Ne.ServiceName,"Cannot edit picture - cannot get current picture status."),ue.Error}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot edit picture! ${e}`),ue.FatalError}}))}DeletePictureAsync(e){return Ge(this,void 0,void 0,(function*(){var t,n;try{if(""==e.Guid||null==e.Guid)return this._logger.Error(Ne.ServiceName,"Cannot delete picture - guid is empty."),ue.WrongData;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Le(e.Guid),8e3,!1);return null===(n=u.Log)||void 0===n||n.Error(Ne.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! DeletePictureAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),null==r||null==r.Status?(this._logger.Error(Ne.ServiceName,"Cannot delete picture - unknown error!"),ue.UnknownError):r.Status}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot delete picture! ${e}`),ue.FatalError}}))}GetPicturesInfoAsync(){return Ge(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Me,8e3,!1);return null==t||null==t.Status?(this._logger.Error(Ne.ServiceName,"Cannot get pictures info - unknown error!"),new Ee(ue.UnknownError,"NoDataInResult")):t.Status!=ue.OK?(this._logger.Error(Ne.ServiceName,`Cannot get pictures info - controler responded with status ${t.Status}.`),new Ee(t.Status,"UnknownReason")):null==t.Data?(this._logger.Error(Ne.ServiceName,"Cannot get pictures info - controler responded with OK, but no data in result.}."),new Ee(ue.UnknownError,"NoDataInResult")):t.Data.map((e=>{const t=new Ue;return t.DateTime=e.DateTime,t.Guid=e.Guid,t.OwnerGuid=e.OwnerGuid,-1!=e.OwnerGuid.indexOf("_")?(t.OwnerGuid=e.OwnerGuid.substring(0,e.OwnerGuid.indexOf("_")),t.OwnerIdentity=e.OwnerGuid.substring(e.OwnerGuid.indexOf("_")+1)):e.Guid.includes("profilePicture")?(t.OwnerIdentity=e.Guid.substring(e.Guid.indexOf("_")+1),t.OwnerGuid=e.OwnerGuid):e.Guid.includes("devices_group")?(t.OwnerIdentity=e.Guid.substring(0,e.Guid.lastIndexOf("_")),t.OwnerGuid=e.OwnerGuid):(t.OwnerGuid=e.OwnerGuid,t.OwnerIdentity=""),t}))}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get picture info! ${e}`),new Ee(ue.FatalError,"ExceptionOccurred")}}))}GetPictureAsync(e){return Ge(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Oe(e),8e3,!1);if(null==n||null==n.Status)return this._logger.Error(Ne.ServiceName,"Cannot get picture - unknown error!"),new Ee(ue.UnknownError,"NoDataInResult");switch(n.Status){case ue.ResourceDoesNotExists:return new Ee(ue.ResourceDoesNotExists,"PictureNotFound");case ue.OK:if(null==n.Data)return new Ee(ue.Error,"RespondedWithOKButNoData");const e=new Re;return e.Base64Image=n.Data.Base64Image,e.DateTime=n.Data.DateTime,e.ImageType=n.Data.ImageType,e.Guid=n.Data.Guid,-1!=n.Data.OwnerGuid.indexOf("_")?(e.OwnerGuid=n.Data.OwnerGuid.substring(0,n.Data.OwnerGuid.indexOf("_")),e.OwnerIdentity=n.Data.OwnerGuid.substring(n.Data.OwnerGuid.indexOf("_")+1)):n.Data.Guid.includes("profilePicture")?(e.OwnerIdentity=n.Data.Guid.substring(n.Data.Guid.indexOf("_")+1),e.OwnerGuid=n.Data.OwnerGuid):n.Data.Guid.includes("devices_group")?(e.OwnerIdentity=n.Data.Guid.substring(0,n.Data.Guid.lastIndexOf("_")),e.OwnerGuid=n.Data.OwnerGuid):(e.OwnerGuid=n.Data.OwnerGuid,e.OwnerIdentity=""),e;default:return new Ee(n.Status,"UnknownReason")}}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get picture! ${e}`),new Ee(ue.FatalError,"ExceptionOccurred")}}))}GetPicturesListAsync(){return Ge(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new xe,8e3,!1);return null==t||null==t.Status?(this._logger.Error(Ne.ServiceName,"Cannot get pictures - unknown error!"),new Ee(ue.UnknownError,"NoDataInResult")):t.Status!=ue.OK?(this._logger.Error(Ne.ServiceName,`Cannot get pictures - controler responded with status ${t.Status}.`),new Ee(t.Status,"UnknownReason")):null==t.Data?(this._logger.Error(Ne.ServiceName,"Cannot get pictures - controler responded with OK, but no data in result.}."),new Ee(ue.UnknownError,"NoDataInResult")):t.Data.map((e=>{const t=new Re;return t.Base64Image=e.Base64Image,t.DateTime=e.DateTime,t.Guid=e.Guid,t.ImageType=e.ImageType,-1!=e.OwnerGuid.indexOf("_")?(t.OwnerGuid=e.OwnerGuid.substring(0,e.OwnerGuid.indexOf("_")),t.OwnerIdentity=e.OwnerGuid.substring(e.OwnerGuid.indexOf("_")+1)):e.Guid.includes("profilePicture")?(t.OwnerIdentity=e.Guid.substring(e.Guid.indexOf("_")+1),t.OwnerGuid=e.OwnerGuid):e.Guid.includes("devices_group")?(t.OwnerIdentity=e.Guid.substring(0,e.Guid.lastIndexOf("_")),t.OwnerGuid=e.OwnerGuid):(t.OwnerGuid=e.OwnerGuid,t.OwnerIdentity=""),t}))}catch(e){return this._logger.Error(Ne.ServiceName,`Cannot get pictures! ${e}`),new Ee(ue.FatalError,"ExceptionOccurred")}}))}}Ne.ServiceName="PictureService";class Re extends be{set DateTime(e){this._dateTime=e}}class Pe{constructor(){this.Guid="",this.OwnerGuid="",this.Base64Image="",this.ImageType=Se.Device,this.DateTime=""}}class Ue{constructor(){this._guid="",this._dateTime="",this._ownerGuid="",this._ownerIdentity=""}get Guid(){return this._guid}get DateTime(){return this._dateTime}get OwnerGuid(){return this._ownerGuid}get OwnerIdentity(){return this._ownerIdentity}set Guid(e){this._guid=e}set DateTime(e){this._dateTime=e}set OwnerGuid(e){this._ownerGuid=e}set OwnerIdentity(e){this._ownerIdentity=e}}class Oe extends ce{constructor(e){super(),this.Resource="/pictures/picture",this.Method=le.Get,this.Data=e}}class Me extends ce{constructor(){super(),this.Resource="/pictures/info",this.Method=le.Get}}class xe extends ce{constructor(){super(),this.Resource="/pictures/list",this.Method=le.Get}}class Fe extends ce{constructor(e){super(),this.Resource="/pictures/picture",this.Method=le.Put,this.Data=e}}class Le extends ce{constructor(e){super(),this.Resource="/pictures/picture",this.Method=le.Delete,this.Data=e}}class Be{constructor(){this._log=hy.Get(a.ServiceName),Be._localStorageService=hy.Get(l.ServiceName)}GetServiceName(){return Be.ServiceName}NormalizeCacheKey(e){if(null==e)return e;if(Array.isArray(e))return e.map((e=>this.NormalizeCacheKey(e)));if("object"!=typeof e)return e;const t={};return Object.keys(e).sort().forEach((n=>{"TransactionId"!==n&&"Status"!==n&&(t[n]=this.NormalizeCacheKey(e[n]))})),t}GetResourceName(e){return JSON.stringify(this.NormalizeCacheKey(e))}Cache(e){var t;e.Status===ue.OK&&(this._log.Debug(Be.ServiceName,`Caching request: ${e.Resource} ${e.Method}`),null===(t=Be._localStorageService)||void 0===t||t.Save(this.GetServiceName(),this.GetResourceName(e),e))}GetCache(e){var t;let n=null===(t=Be._localStorageService)||void 0===t?void 0:t.Read(this.GetServiceName(),this.GetResourceName(e));return null!=n&&this._log.Debug(Be.ServiceName,`Got request response from cache: ${e.Resource} ${e.Method}`),null==n?null:Object.assign(Object.assign({},n),{TransactionId:e.TransactionId})}ClearCache(){var e;null===(e=Be._localStorageService)||void 0===e||e.DropStorage(this.GetServiceName()),this._log.Debug(Be.ServiceName,`Clearing cache for ${this.GetServiceName()}`)}Remove(e){var t;null===(t=Be._localStorageService)||void 0===t||t.Remove(this.GetServiceName(),this.GetResourceName(e)),this._log.Debug(Be.ServiceName,`Clearing cache for cache: ${e.Resource} ${e.Method}`)}}Be._localStorageService=null,Be.ServiceName="WebApiCacheService";var We=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class $e{constructor(){this._connection=null,this._connection=hy.Get(It.ServiceName),this._pictureService=hy.Get(Ne.ServiceName),this._sessionService=hy.Get(Xe.ServiceName)}CanEditUser(e){const t=this._sessionService.User;return e.Guid===(null==t?void 0:t.Guid)||this.CanEditUsersOfAccessLevel(e.AccessLevel)}CanEditUsersOfAccessLevel(e){var t;const n=null===(t=this._sessionService.User)||void 0===t?void 0:t.AccessLevel;if(void 0===n)return!1;switch(e){case fe.Support:return n===fe.Support;case fe.Installator:return n>=fe.Installator;case fe.Admin:default:return n>=fe.Admin}}GetServiceName(){return $e.ServiceName}GetUsersAsync(){return We(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ke,2e4,!1);if(null==n)return Promise.resolve([]);if((null==n?void 0:n.Status)==ue.OK){if(null!=n.Data){const e=[];return n.Data.forEach((t=>{var n=new ze;n.AccessLevel=t.AccessLevel,n.Email=t.Email,n.Gender=t.Gender,n.Guid=t.Guid,n.IsAccountOnline=t.IsAccountOnline,n.Name=t.Name,n.IsActive=t.IsActive,n.IsBanned=t.IsBanned,n.Phone=t.Phone,n.Surname=t.Surname,e.push(n)})),e}return Promise.resolve([])}if((null==n?void 0:n.Status)==ue.NoData)return Promise.resolve([]);throw null===(t=u.Log)||void 0===t||t.Debug($e.ServiceName,`Failed to retrieve users, error: ${n.Status}`),new Error(`Failed to retrieve users, error: ${n.Status}`)}))}GetUserAsync(e){return We(this,void 0,void 0,(function*(){var t,n;if(""===e)return Promise.resolve(null);null==e&&(e="");const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ve(e),2e4,!1);if(null==r||null==r.Data)return Promise.resolve(null);if(r.Status!=ue.OK)return null===(n=u.Log)||void 0===n||n.Debug($e.ServiceName,`Failed to retrieve user, error: ${r.Status}`),Promise.resolve(null);const o=new ze;return o.AccessLevel=r.Data.AccessLevel,o.Email=r.Data.Email,o.Gender=r.Data.Gender,o.Guid=r.Data.Guid,o.IsAccountOnline=r.Data.IsAccountOnline,o.Name=r.Data.Name,o.IsActive=r.Data.IsActive,o.IsBanned=r.Data.IsBanned,o.Phone=r.Data.Phone,o.Surname=r.Data.Surname,o}))}CreateUserAsync(e,t){return We(this,void 0,void 0,(function*(){var n;if(null!=e.Guid&&""!=e.Guid)return new Ee(ue.WrongData,"GuidMustBeEmpty");const r=new qe;r.Name=e.Name.trim(),r.Surname=e.Surname.trim(),r.Email=e.Email.trim(),r.Password=t.trim(),r.Phone=e.Phone.trim(),r.Gender=e.Gender,r.AccessLevel=e.AccessLevel;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new He(r),2e4,!1);return hy.Get(Be.ServiceName).ClearCache(),null==o||null==o.Status?new Ee(ue.FatalError,"UnknownError"):(null==o.Data&&(o.Data=""),new Ee(o.Status,o.Data))}))}UpdateUserAsync(e){return We(this,void 0,void 0,(function*(){var t;if(null==e.Guid||""==e.Guid)return new Ee(ue.WrongData,"GuidCannotBeEmpty");const n=new qe;n.Guid=e.Guid,n.Name=e.Name.trim(),n.Surname=e.Surname.trim(),n.Email=e.Email.trim(),n.Phone=e.Phone.trim(),n.Gender=e.Gender,n.AccessLevel=e.AccessLevel;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new He(n),2e4,!1);return hy.Get(Be.ServiceName).ClearCache(),null==r||null==r.Status?new Ee(ue.FatalError,"UnknownError"):(null==r.Data&&(r.Data=""),new Ee(r.Status,r.Data))}))}ChangePasswordAsync(e,t){return We(this,void 0,void 0,(function*(){var n;if(null==e.Guid||""==e.Guid)return new Ee(ue.WrongData,"GuidCannotBeEmpty");const r=yield this.GetUserAsync(e.Guid);if(null==r)return new Ee(ue.ResourceIsNotAvailable,"CannotGetUser");const o=new qe;o.Guid=e.Guid,o.Password=t,o.AccessLevel=r.AccessLevel,o.Email=r.Email;const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new He(o),2e4,!1);return null==s||null==s.Status?new Ee(ue.FatalError,"UnknownError"):(null==s.Data&&(s.Data=""),new Ee(s.Status,s.Data))}))}DeleteUserAsync(e){return We(this,void 0,void 0,(function*(){var t,n,r;if(""===e)return ue.WrongData;null==e&&(e="");try{const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new je(e),2e4,!1);return hy.Get(Be.ServiceName).ClearCache(),null==r||null==r.Status?ue.FatalError:(r.Status!=ue.OK&&(null===(n=u.Log)||void 0===n||n.Debug($e.ServiceName,`Failed to delete user, error: ${r.Status}`)),r.Status)}catch(e){return null===(r=u.Log)||void 0===r||r.Error($e.ServiceName,`Failed to delete user: ${e}`),ue.FatalError}}))}GetUserProfilePictureAsync(e){return We(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new Ee(ue.WrongData,"GuidCannotBeEmpty");const t=yield this._pictureService.GetPicturesInfoAsync();if(null!=t.Type)return t;const n=t.find((t=>"profilePicture"==t.OwnerIdentity&&t.OwnerGuid==e.Guid));if(null!=n){const e=yield this._pictureService.GetPictureAsync(n.Guid);return hy.Get(Be.ServiceName).ClearCache(),e.Type,e}return new Ee(ue.ResourceDoesNotExists,"PictureNotFound")}))}SetUserProfilePictureAsync(e,t){return We(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new Ee(ue.WrongData,"GuidCannotBeEmpty");let n=new be;n.ImageType=Se.Person,n.OwnerGuid=e.Guid,n.OwnerIdentity="profilePicture",n.Base64Image=t;const r=yield this.GetUserProfilePictureAsync(e);if(hy.Get(Be.ServiceName).ClearCache(),r.Type==ue.ResourceDoesNotExists){const e=yield this._pictureService.AddPictureAsync(n);return e===ue.OK?new Ee(ue.OK,"PictureSet"):new Ee(e,"PictureServiceError")}if(null!=r.Type)return new Ee(ue.Error,"ErrorWhenTryingToCheckIfCurrentProfilePictureExists");{n.Guid=r.Guid,n.OwnerGuid=r.OwnerGuid;const e=yield this._pictureService.EditPictureAsync(n);return e===ue.OK?new Ee(ue.OK,"PictureSet"):new Ee(e,"PictureServiceError")}}))}}$e.ServiceName="UsersService";class Ve extends ce{constructor(e){super(),this.Resource="/users/user",this.Method=le.Get,this.Data=e}}class qe{constructor(){this.Guid="",this.Name="",this.Surname="",this.Email="",this.Password="",this.Phone="",this.Gender=ve.Unknown,this.AccessLevel=fe.Any}}class He extends ce{constructor(e){super(),this.Resource="/users/user",this.Method=le.Put,this.Data=e}}class Ke extends ce{constructor(){super(),this.Resource="/users/list",this.Method=le.Get}}class je extends ce{constructor(e){super(),this.Resource="/users/user",this.Method=le.Delete,this.Data=e}}class ze{constructor(){this._guid="",this._cloudGuid="",this._name="",this._surname="",this._phone="",this._email="",this._isAccountOnline=!0,this._isAccountActive=!0,this._isAccountBanned=!0,this._notificationChannels=[],this._gender=ve.Unknown,this._accessLevel=fe.Any,this._localization=ye.En_Us,this._softwareVersion=""}get Guid(){return this._guid}set Guid(e){this._guid=e}get CloudGuid(){return this._cloudGuid}set CloudGuid(e){this._cloudGuid=e}get Name(){return this._name}set Name(e){this._name=e}get Surname(){return this._surname}set Surname(e){this._surname=e}get Phone(){return this._phone}set Phone(e){this._phone=e}get AccessLevel(){return this._accessLevel}set AccessLevel(e){this._accessLevel=e}get Email(){return this._email}set Email(e){this._email=e}get IsAccountOnline(){return this._isAccountOnline}set IsAccountOnline(e){this._isAccountOnline=e}get IsActive(){return this._isAccountActive}set IsActive(e){this._isAccountActive=e}get IsBanned(){return this._isAccountBanned}set IsBanned(e){this._isAccountBanned=e}get NotificationChannels(){return this._notificationChannels}set NotificationChannels(e){this._notificationChannels=e}get Gender(){return this._gender}set Gender(e){this._gender=e}get Localization(){return this._localization}set Localization(e){this._localization=e}get SoftwareVersion(){return this._softwareVersion}set SoftwareVersion(e){this._softwareVersion=e}GetUserProfilePictureAsync(){return hy.Get($e.ServiceName).GetUserProfilePictureAsync({Guid:this._guid})}SetUserProfilePictureAsync(e){return hy.Get($e.ServiceName).SetUserProfilePictureAsync({Guid:this._guid},e)}}var Je=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Xe{constructor(){this._onUserLoggedInEvent=new c,this._onUserLoggedOutEvent=new c,this._email="",this._password="",this._authToken="",this._alreadySubsribedToNetworkEvents=!1,this._isLoggedIn=!1,this._user=null}isLoginError(e){return"number"==typeof e&&void 0!==me[e]}RestoreSessionAsync(){return Je(this,void 0,void 0,(function*(){var e,t,n;if(null===(e=u.Log)||void 0===e||e.Debug(Xe.ServiceName,`Creating RestoreSessionAsync ${this._email} ${this._password}`),void 0===this._user||null===this._user||!this._isLoggedIn)return!1;let r=yield this.UserLogInAsync(this._email,this._password);if(this.isLoginError(r)){if(null===(t=u.Log)||void 0===t||t.Error(Xe.ServiceName,"RestoreSessionAsync failed, user login failed"),r==me.WrongAuthData)throw new Error("Wrong authentication data!");return!1}return null===(n=u.Log)||void 0===n||n.Debug(Xe.ServiceName,"RestoreSessionAsync completed successfully"),!0}))}WaitForSessionCreationAsync(){return Je(this,void 0,void 0,(function*(){return new Promise((e=>{if(this._isLoggedIn&&null!=this._user)return e();const t=n=>{this._onUserLoggedInEvent.Unsubscribe(t),e()};this._onUserLoggedInEvent.Subscribe(t)}))}))}OnUserLoggedInEvent(){return this._onUserLoggedInEvent}OnUserLoggedOutEvent(){return this._onUserLoggedOutEvent}get User(){return this._user}UserLogOutAsync(){return Je(this,void 0,void 0,(function*(){var e,t;let n=new ce;n.Resource="/users/user/logout",n.Method=le.Put,this._email="",this._password="",(yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(n,2e4,!1)).Status==ue.OK?(this._onUserLoggedOutEvent.Invoke(this._user),null===(e=u.Log)||void 0===e||e.Debug(Xe.ServiceName,"User has been logged out."),this._user=null,hy.Get(Be.ServiceName).ClearCache()):null===(t=u.Log)||void 0===t||t.Debug(Xe.ServiceName,"Failed to logout user!")}))}AuthorizeAppAsync(e){return Je(this,void 0,void 0,(function*(){var t,n,r,o,s;let i=hy.Get(It.ServiceName);const a=yield i.SendAndWaitForResponseAsync(new Qe(e),2e4,!1);if(a.Status==ue.OK&&null!=a.Data){const r=!this._isLoggedIn||(null===(t=this._user)||void 0===t?void 0:t.Guid)!==a.Data.Guid;this._authToken=e;let o=new ze;this._user=o,o.AccessLevel=a.Data.AccessLevel,o.Email=a.Data.Email,this._email=a.Data.Email,o.Gender=a.Data.Gender,o.Guid=a.Data.Guid,o.IsAccountOnline=a.Data.IsAccountOnline,o.Name=a.Data.Name,o.IsActive=a.Data.IsActive,o.IsBanned=a.Data.IsBanned,o.Phone=a.Data.Phone,o.Surname=a.Data.Surname,o.SoftwareVersion=a.Data.SoftwareVersion;let s=hy.Get(ct.ServiceName);return void 0!==a.Data.ConfigurationTime&&null!=a.Data.ConfigurationTime?(ct.ConfigurationTimeRetrieved=new Date(a.Data.ConfigurationTime),yield s.CheckIfConfigurationTimeHasChangedAsync(new Date(a.Data.ConfigurationTime))):yield s.CheckIfConfigurationHasChangedAsync(),r&&hy.Get(Be.ServiceName).ClearCache(),this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,hy.Get(It.ServiceName).SubscribeTo("/info/users/user/loggedOut",(e=>Je(this,void 0,void 0,(function*(){var t,n;null===(t=u.Log)||void 0===t||t.Debug(Xe.ServiceName,`User logged out: ${JSON.stringify(e.Data)}`),this._isLoggedIn=!1,null===(n=this._onUserLoggedOutEvent)||void 0===n||n.Invoke(this._user),this._user=null,hy.Get(Be.ServiceName).ClearCache()}))))),null===(n=u.Log)||void 0===n||n.Debug(Xe.ServiceName,`Did logging in succeded?: ${a.Status==ue.OK}`),this._isLoggedIn=!0,this._onUserLoggedInEvent.Invoke(this._user),o}return a.Status===ue.OperationNotPermitted?(null===(r=u.Log)||void 0===r||r.Debug(Xe.ServiceName,`App login response: ${a.Data}`),me.AuthDisabled):a.Status===ue.ResourceDoesNotExists?(null===(o=u.Log)||void 0===o||o.Debug(Xe.ServiceName,`App login response: ${a.Data}`),me.MethodNotSupported):(null===(s=u.Log)||void 0===s||s.Debug(Xe.ServiceName,`App login response: ${a.Data}`),me.WrongAuthData)}))}UserLogInAsync(e,t){return Je(this,void 0,void 0,(function*(){var n,r,o;let s=hy.Get(It.ServiceName);const i=yield s.SendAndWaitForResponseAsync(new Ze(e,t),2e4,!1);if(i.Status==ue.OK&&null!=i.Data){const o=!this._isLoggedIn||(null===(n=this._user)||void 0===n?void 0:n.Guid)!==i.Data.Guid;this._email=e,this._password=t;let s=new ze;this._user=s,s.AccessLevel=i.Data.AccessLevel,s.Email=i.Data.Email,s.Gender=i.Data.Gender,s.Guid=i.Data.Guid,s.IsAccountOnline=i.Data.IsAccountOnline,s.Name=i.Data.Name,s.IsActive=i.Data.IsActive,s.IsBanned=i.Data.IsBanned,s.Phone=i.Data.Phone,s.Surname=i.Data.Surname,s.SoftwareVersion=i.Data.SoftwareVersion;let a=hy.Get(ct.ServiceName);return void 0!==i.Data.ConfigurationTime&&null!=i.Data.ConfigurationTime?(ct.ConfigurationTimeRetrieved=new Date(i.Data.ConfigurationTime),yield a.CheckIfConfigurationTimeHasChangedAsync(new Date(i.Data.ConfigurationTime))):yield a.CheckIfConfigurationHasChangedAsync(),o&&hy.Get(Be.ServiceName).ClearCache(),this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,hy.Get(It.ServiceName).SubscribeTo("/info/users/user/loggedOut",(e=>Je(this,void 0,void 0,(function*(){var t,n;null===(t=u.Log)||void 0===t||t.Debug(Xe.ServiceName,`User logged out: ${JSON.stringify(e.Data)}`),this._isLoggedIn=!1,null===(n=this._onUserLoggedOutEvent)||void 0===n||n.Invoke(this._user),this._user=null,hy.Get(Be.ServiceName).ClearCache()}))))),null===(r=u.Log)||void 0===r||r.Debug(Xe.ServiceName,`Did logging in succeded?: ${i.Status==ue.OK}`),this._isLoggedIn=!0,this._onUserLoggedInEvent.Invoke(this._user),s}return null===(o=u.Log)||void 0===o||o.Debug(Xe.ServiceName,`User login response: ${i.Data}`),me.WrongAuthData}))}GetServiceName(){return Xe.ServiceName}}Xe.ServiceName="SessionService";class Ye{constructor(e,t){this.Email="",this.Password="",this.Email=e,this.Password=t}}class Qe extends ce{constructor(e){super(),this.Data=e,this.Resource="/applications/app/auth",this.Method=le.Put}}class Ze extends ce{constructor(e,t){super(),this.Data=new Ye(e,t),this.Resource="/users/user/login",this.Method=le.Put}}class et{constructor(e){if(this.initialCount=e,this._running=0,this._waiting=[],this.Take=()=>{if(this._waiting.length>0&&this._running<this.initialCount){this._running++;const e=this._waiting.shift();null==e||e.Resolve({Release:this.Release})}},this.IsLocked=()=>this._running>0,this.AcquireAsync=()=>this._running<this.initialCount?(this._running++,Promise.resolve({Release:this.Release})):new Promise(((e,t)=>{this._waiting.push({Resolve:e,Reject:t})})),this.Release=()=>{if(0===this._running)throw new Error("Release called more times than AcquireAsync");this._running--,this.Take()},this.Purge=()=>{this._waiting.forEach((e=>{e.Reject(new Error("The semaphore was purged and as a result this task has been cancelled"))})),this._running=0,this._waiting=[]},e<1)throw new Error(`The semaphore was created with a max value of ${e} but the max value cannot be less than 1`)}}var tt=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class nt{constructor(){this._extensionInfoCache=new Map,this._protocolInfoCache=new Map,this._isExtensionInfoInitialized=!1,this._semaphore=new et(1)}GetServiceName(){return nt.ServiceName}GetExtensionsInfoAsync(e){return tt(this,arguments,void 0,(function*(e,t=!1){var n;null===(n=u.Log)||void 0===n||n.Debug(nt.ServiceName,`Getting ExtensionsInfo, data loaded from cache: ${!t}`);let r=yield this._semaphore.AcquireAsync();try{this._isExtensionInfoInitialized&&!t||(yield this.GetExtensionInfoFromControllerAsync())}finally{r.Release()}if(0==[...this._extensionInfoCache.values()].length)return[];if(null!=e){const t=this._extensionInfoCache.get(e);if(null==t)throw new st("Cannot get ExtensionsInfo, extension not found.");return[t]}return[...this._extensionInfoCache.values()]}))}GetProtocolInfoAsync(e){return tt(this,arguments,void 0,(function*(e,t=!1,n=!1){var r;if(null===(r=u.Log)||void 0===r||r.Debug(nt.ServiceName,`Getting ProtocolInfo, data loaded from cache: ${!t}`),t&&(yield this.GetProtocolExtensionInfoFromControllerAsync()),0!=[...this._protocolInfoCache.values()].length||n){if(0==[...this._protocolInfoCache.values()].length)throw new st("Cannot get ProtocolInfo, controler may return empty list of Extensions or other unknown error occurs!")}else yield this.GetProtocolInfoAsync(e,!0,!0);if(null!=e){const t=this._protocolInfoCache.get(e);if(null==t)throw new st("Cannot get ProtocolInfo, extension not found.");return[t]}return[...this._protocolInfoCache.values()]}))}GetExtensionInfoFromControllerAsync(){return tt(this,void 0,void 0,(function*(){const e=new rt,t=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(e,16e3,!1);if(null==t||null==t.Status)throw new st("Cannot get ExtensionsInfo from controller, controller response does not contain data!");if(t.Status!=ue.OK)throw new st(`Cannot get ExtensionsInfo from controller! Response status: ${t.Status}`);if(null==t.Data)throw new st("Cannot get ExtensionsInfo from controller, controller response does not contain data!");this._extensionInfoCache.clear(),t.Data.forEach((e=>{this._extensionInfoCache.set(e.ExtensionGuid,e)})),0!=[...this._extensionInfoCache.values()].length&&(this._isExtensionInfoInitialized=!0)}))}GetProtocolExtensionInfoFromControllerAsync(){return tt(this,void 0,void 0,(function*(){var e;const t=new ot,n=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(t,16e3,!1);if(null==n||null==n.Status)throw new st("Cannot get ProtocolInfo from controller, controller response does not contain data!");switch(n.Status){case ue.OK:if(null==n.Data)throw new st("Cannot get ProtocolInfo from controller, controller response does not contain data!");this._protocolInfoCache.clear(),n.Data.forEach((e=>{this._protocolInfoCache.set(e.PublicGuid,e)}));break;case ue.ResourceDoesNotExists:null===(e=u.Log)||void 0===e||e.Debug(nt.ServiceName,"Cannot get ProtocolInfo from controller, controller software does not implement this yet, update controller to the newest software!");break;default:throw new st(`Cannot get ProtocolInfo from controller! Response status: ${n.Status}`)}}))}}nt.ServiceName="StatisticsInfoService";class rt extends ce{constructor(){super(),this.Resource="/controller/extensions/",this.Method=le.Get}}class ot extends ce{constructor(){super(),this.Resource="/controller/protocols/",this.Method=le.Get}}class st extends Error{constructor(e){super(e),this.message=e,this.name="CannotGetExtensions"}}var it,at=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class ct{OnConfigurationChangedEvent(){return this._onConfigurationChangedEvent}GetServiceName(){return ct.ServiceName}constructor(){this._connection=null,this._session=null,this._localStorage=null,this._onEnteredConfigurationEvent=new ke,this._onExitedConfigurationEvent=new ke,this._onConfigurationTimeCheckedEvent=new c,this._configurationTime=new Date,this._appEnteredConfigurationMode=!1,this._didConfigurationChange=!0,this._didSynchronization=!1,this._onSynchronized=new ke,this._onConfigurationChangedEvent=new ke,this._connection=hy.Get(It.ServiceName),this._session=hy.Get(Xe.ServiceName),this._localStorage=hy.Get(l.ServiceName),this._connection.SubscribeTo("/info/configuration/mode/entry",(e=>{hy.Get(Be.ServiceName).ClearCache(),this._appEnteredConfigurationMode||this._onEnteredConfigurationEvent.Invoke()})),this._connection.SubscribeTo("/info/configuration/mode/exit",(e=>{var t;hy.Get(Be.ServiceName).ClearCache(),this._appEnteredConfigurationMode||this._onExitedConfigurationEvent.Invoke(),null===(t=this.OnConfigurationChangedEvent())||void 0===t||t.Invoke()}))}CheckIfControllerSoftwareVersionIsEnough(e,t){var n,r,o;const s=null!==(o=null===(r=null===(n=this._session)||void 0===n?void 0:n.User)||void 0===r?void 0:r.SoftwareVersion)&&void 0!==o?o:null;if(!s||!s.includes("."))return!1;const i=s.split(".");if(2!==i.length)return!1;const a=i.map((e=>parseInt(e,10)));if(a.some((e=>Number.isNaN(e)||e<0)))return!1;const[c,u]=a;return c>e||c===e&&u>=t}ImportControllerConfigurationAsync(e){return at(this,void 0,void 0,(function*(){var t,n,r;let o=yield e.text(),s=this.SplitStringBySize(o),i=new ut("");i.Status=ue.MultiDataResponseStart;let a=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(i,6e3,!1);if(void 0===a||(null==a?void 0:a.Status)!=ue.OK)return ue.Error;for(const e of s){let t=new ut(e);t.Status=ue.MultiDataResponse;let r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(t,6e3,!1);if(void 0===r||(null==r?void 0:r.Status)!=ue.OK)return ue.Error}i.Status=ue.MultiDataResponseStop;let c=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(i,12e4,!1);return void 0===c||(null==c?void 0:c.Status)!=ue.OK?ue.Error:ue.OK}))}SplitStringBySize(e,t=1e5){const n=Math.floor(t/2),r=[];let o=0;for(;o<e.length;){let s=e.slice(o,o+n);for(;new Blob([s]).size>t;)s=s.slice(0,-1);r.push(s),o+=s.length}return r}GetControllerSystemTimeAsync(){return at(this,void 0,void 0,(function*(){var e,t;try{let t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new yt,8e3,!1);return null==t||null==t.Status?ue.Error:t.Status!=ue.OK?t.Status:null==t.Data?ue.ResourceIsNotAvailable:new Date(t.Data)}catch(e){return null===(t=u.Log)||void 0===t||t.Error(ct.ServiceName,`Cannot get current controller time! ${e}`),ue.FatalError}}))}SetControllerSystemTimeAsync(e){return at(this,void 0,void 0,(function*(){var t,n;try{let n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new mt(e.toISOString()),8e3,!1);return null==n||null==n.Status?ue.Error:n.Status}catch(e){return null===(n=u.Log)||void 0===n||n.Error(ct.ServiceName,`Cannot set current controller time! ${e}`),ue.FatalError}}))}StartNtpTimeSynchronizationAsync(){return at(this,void 0,void 0,(function*(){var e,t;try{let t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new wt,8e3,!1);return null==t||null==t.Status?ue.Error:t.Status}catch(e){return null===(t=u.Log)||void 0===t||t.Error(ct.ServiceName,`Cannot set current controller time! ${e}`),ue.FatalError}}))}FactoryResetAsync(e){return at(this,void 0,void 0,(function*(){var t,n;try{hy.Get(Be.ServiceName).ClearCache();let r=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ht,2e3,!1))||void 0===n?void 0:n.Status;if(r==ue.OK){let t=300,n=0,r=100/t,o=setInterval((()=>{n+=r,e(parseFloat(n.toPrecision(1)))}),1e3);return yield se.Delay(1e3*t),hy.Get(Be.ServiceName).ClearCache(),clearInterval(o),ue.OK}return r}catch(e){return ue.FatalError}}))}RollbackLastUpdateAsync(e){return at(this,void 0,void 0,(function*(){var t,n;try{hy.Get(Be.ServiceName).ClearCache();let r=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new pt,2e3,!1))||void 0===n?void 0:n.Status;if(r==ue.OK){let t=420,n=0,r=100/t,o=setInterval((()=>{n+=r,e(parseFloat(n.toPrecision(1)))}),1e3);return yield se.Delay(1e3*t),hy.Get(Be.ServiceName).ClearCache(),clearInterval(o),ue.OK}return r}catch(e){return ue.FatalError}}))}RestartControllerAsync(e){return at(this,void 0,void 0,(function*(){var t,n;try{hy.Get(Be.ServiceName).ClearCache();let r=null===(n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new dt,2e3,!1))||void 0===n?void 0:n.Status;if(r==ue.OK){let t=240,n=0,r=100/t,o=setInterval((()=>{n+=r,e(parseFloat(n.toPrecision(1)))}),1e3);return yield se.Delay(1e3*t),hy.Get(Be.ServiceName).ClearCache(),clearInterval(o),ue.OK}return r}catch(e){return ue.FatalError}}))}DidCofigurationChangeAsync(){return at(this,void 0,void 0,(function*(){return new Promise((e=>{var t;this._didSynchronization?e(this._didConfigurationChange):null===(t=this._onSynchronized)||void 0===t||t.Subscribe((()=>{e(this._didConfigurationChange)}))}))}))}GetLastKnownConfigurationChangeTime(){var e;const t=null===(e=this._localStorage)||void 0===e?void 0:e.Read(this.GetServiceName(),"last_configuration_time");return null!=t?new Date(t):new Date}SaveLastConfigurationChangeTime(e){var t;null===(t=this._localStorage)||void 0===t||t.Save(this.GetServiceName(),"last_configuration_time",e.toString())}EnterConfigurationModeAsync(){return at(this,void 0,void 0,(function*(){var e;this._appEnteredConfigurationMode=!0,hy.Get(Be.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new gt,2e4,!1)}))}ExitConfigurationModeAsync(){return at(this,void 0,void 0,(function*(){var e;this._appEnteredConfigurationMode=!0,hy.Get(Be.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ft,2e4,!1),this._didConfigurationChange=!0,hy.Get(Be.ServiceName).ClearCache(),this._appEnteredConfigurationMode=!1}))}OnEnteredConfigurationEvent(){return this._onEnteredConfigurationEvent}OnExitedConfigurationEvent(){return this._didConfigurationChange=!0,this._onExitedConfigurationEvent}OnConfigurationTimeCheckedEvent(){return this._onConfigurationTimeCheckedEvent}GetLastConfigurationChangeTimeAsync(){return at(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new vt,2e4,!1);if(null==t||(null==t?void 0:t.Status)!=ue.OK)throw new Error("Failed to get last configuration change time");return this._configurationTime=new Date(t.Data),this._configurationTime}))}CheckIfConfigurationHasChangedAsync(){return at(this,void 0,void 0,(function*(){var e,t,n,r;const o=yield this.GetLastConfigurationChangeTimeAsync();return null===(e=u.Log)||void 0===e||e.Info(ct.ServiceName,`Checking if configuration time has changed. Current: ${o.toString()}, Last known: ${this.GetLastKnownConfigurationChangeTime().toString()}`),this.GetLastKnownConfigurationChangeTime().toString()!=o.toString()?(this.SaveLastConfigurationChangeTime(o),hy.Get(Be.ServiceName).ClearCache(),this._didSynchronization=!0,this._didConfigurationChange=!0,null===(t=this.OnConfigurationChangedEvent())||void 0===t||t.Invoke(),this._onConfigurationTimeCheckedEvent.Invoke(o),null===(n=this._onSynchronized)||void 0===n||n.Invoke(),!0):(this._didSynchronization=!0,this._didConfigurationChange=!1,null===(r=this._onSynchronized)||void 0===r||r.Invoke(),!1)}))}CheckIfConfigurationTimeHasChangedAsync(e){return at(this,void 0,void 0,(function*(){var t,n,r,o;return null===(t=u.Log)||void 0===t||t.Info(ct.ServiceName,`Checking if configuration time has changed. Current: ${e.toString()}, Last known: ${this.GetLastKnownConfigurationChangeTime().toString()}`),this.GetLastKnownConfigurationChangeTime().toString()!=e.toString()?(this.SaveLastConfigurationChangeTime(e),hy.Get(Be.ServiceName).ClearCache(),this._didSynchronization=!0,this._didConfigurationChange=!0,null===(n=this.OnConfigurationChangedEvent())||void 0===n||n.Invoke(),this._onConfigurationTimeCheckedEvent.Invoke(e),null===(r=this._onSynchronized)||void 0===r||r.Invoke(),!0):(this._didSynchronization=!0,this._didConfigurationChange=!1,null===(o=this._onSynchronized)||void 0===o||o.Invoke(),!1)}))}CanExportOrImportControllerConfigurationAsync(){return at(this,void 0,void 0,(function*(){try{let e=yield hy.Get(nt.ServiceName).GetExtensionsInfoAsync(),t=hy.Get(Xe.ServiceName).User;return null!=t&&null!=t.AccessLevel&&t.AccessLevel>=fe.Admin&&e.any((e=>"f4f0f066-7c43-46c6-a0bd-aedf93903dc0"==e.ExtensionGuid))}catch(e){return!1}}))}ExportControllerConfigurationAsync(){return at(this,void 0,void 0,(function*(){var e;let t=[],n=null;yield null===(e=this._connection)||void 0===e?void 0:e.SendAndHandleResponseAsync(new lt,3e4,(e=>{switch(e.Status){case ue.MultiDataResponseStart:break;case ue.MultiDataResponse:null!=e.Data&&void 0!==e.Data&&t.push(e.Data);break;case ue.MultiDataResponseStop:break;case ue.Error:case ue.FatalError:n=new Ee(ge.CannotExportConfiguration,"Cannot export configuration! Controller returned error!")}}),!0);let r=JSON.stringify(JSON.parse(t.join("")),null,2);return console.log(r),null!=n?n:hy.ExportStringAsFileToDownload(this.GetCurrentTimestampedFilename(),r)}))}GetCurrentTimestampedFilename(){var e,t;const n=new Date,r=n.getHours().toString().padStart(2,"0"),o=n.getMinutes().toString().padStart(2,"0"),s=n.getDate().toString().padStart(2,"0"),i=(n.getMonth()+1).toString().padStart(2,"0"),a=n.getFullYear().toString();return`${null===(t=null===(e=this._connection)||void 0===e?void 0:e.GetAuthorizationInfo())||void 0===t?void 0:t.SerialNumber}_${r}-${o}-${s}-${i}-${a}-config.cexp`}}ct.ServiceName="ControllerConfigurationService",ct.ConfigurationTimeRetrieved=null;class ut extends ce{constructor(e){super(),this.Resource="/configuration/backup/import",this.Method=le.Put,this.Data=e}}class lt extends ce{constructor(){super(),this.Resource="/configuration/backup/export",this.Method=le.Get}}class dt extends ce{constructor(){super(),this.Resource="/controller/restart",this.Method=le.Post}}class ht extends ce{constructor(){super(),this.Resource="/controller/factory_reset",this.Method=le.Post}}class pt extends ce{constructor(){super(),this.Resource="/controller/backups/restore/previous",this.Method=le.Post}}class gt extends ce{constructor(){super(),this.Resource="/system/configuration/mode/entry",this.Method=le.Put}}class ft extends ce{constructor(){super(),this.Resource="/system/configuration/mode/exit",this.Method=le.Put}}class vt extends ce{constructor(){super(),this.Resource="/system/configuration/change/time",this.Method=le.Get}}class yt extends ce{constructor(){super(),this.Resource="/system/time",this.Method=le.Get}}class mt extends ce{constructor(e){super(),this.Resource="/system/time",this.Method=le.Put,this.Data=e}}class wt extends ce{constructor(){super(),this.Resource="/system/time/ntp/update",this.Method=le.Put}}!function(e){e[e.Suspended=1]="Suspended",e[e.ReturnedFromSuspension=2]="ReturnedFromSuspension",e[e.EnteredLowPowerMode=3]="EnteredLowPowerMode",e[e.ExitedLowPowerMode=4]="ExitedLowPowerMode",e[e.LoggedIn=5]="LoggedIn",e[e.LoggedOut=6]="LoggedOut",e[e.Connected=7]="Connected",e[e.Disconnected=8]="Disconnected",e[e.FailedToConnect=9]="FailedToConnect",e[e.Connecting=10]="Connecting",e[e.Disconnecting=11]="Disconnecting",e[e.Reconnecting=12]="Reconnecting"}(it||(it={}));class St{constructor(){this._promise=Promise.resolve(),this._disable=()=>{}}Lock(){this._promise=new Promise((e=>this._disable=e))}Unlock(){this._disable()}WaitForLockAsync(){return this._promise}}var At=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class _t{constructor(){this._isConnectedAndAuthorized=!1,this._syncLock=new St,this._isInFouces=!0,this._canHibernate=!0,this._session=null,this._connection=null,this._currentAppState=it.Disconnected,this._returnedFromSuspension=!1,this._onReturnedFromSuspensionEvent=new ke,this._onSuspendedEvent=new ke,this._onEnterLowPowerModeEvent=new ke,this._onExitLowPowerModeEvent=new ke,this._onBackButtonPressedEvent=new ke,this._onForwardButtonPressedEvent=new ke,this._onAppStateChanged=new c,this.MonitorAppState(),this._onAppStateChanged.Subscribe((e=>this._currentAppState=e)),null==navigator.userAgent.match(/Safari/i)||navigator.mediaDevices?window.addEventListener("visibilitychange",(()=>At(this,void 0,void 0,(function*(){yield this._syncLock.WaitForLockAsync(),this._syncLock.Lock(),this.IsHidden()?this.Suspend():this.ReturnFromSuspension(),this._syncLock.Unlock()})))):(window.addEventListener("onblur",(()=>{this._isInFouces&&(this._isInFouces=!1,this.Suspend())})),window.addEventListener("onfocus",(()=>{this._isInFouces||(this._isInFouces=!0,this.ReturnFromSuspension())}))),window.addEventListener("popstate",(e=>{var t,n,r,o;document.location,e.state&&("forward"==e.state.direction?(null===(t=u.Log)||void 0===t||t.Warning(_t.ServiceName,"Forward button pressed"),null===(n=this._onForwardButtonPressedEvent)||void 0===n||n.Invoke()):(null===(r=u.Log)||void 0===r||r.Warning(_t.ServiceName,"Back button pressed"),null===(o=this._onBackButtonPressedEvent)||void 0===o||o.Invoke()))}))}MonitorAppState(){return At(this,void 0,void 0,(function*(){this._session=yield hy.GetAsync("SessionService"),this._connection=yield hy.GetAsync("ExalusConnectionService"),this._session.OnUserLoggedInEvent().Subscribe((e=>{var t;null===(t=u.Log)||void 0===t||t.Warning(_t.ServiceName,"App state changed to: logged in"),this._onAppStateChanged.Invoke(it.LoggedIn)})),this._session.OnUserLoggedOutEvent().Subscribe((e=>{var t;null===(t=u.Log)||void 0===t||t.Warning(_t.ServiceName,"App state changed to: logged out"),this._onAppStateChanged.Invoke(it.LoggedOut)})),this._connection.OnConnectionStateChangedEvent().Subscribe((e=>{var t,n,r,o,s,i;switch(e){case pe.ConnectedAndAuthorized:null===(t=u.Log)||void 0===t||t.Warning(_t.ServiceName,"App state changed to: connected"),this._isConnectedAndAuthorized=!0,this._onAppStateChanged.Invoke(it.Connected);break;case pe.Disconnected:null===(n=u.Log)||void 0===n||n.Warning(_t.ServiceName,"App state changed to: disconnected"),this._isConnectedAndAuthorized&&this._onAppStateChanged.Invoke(it.Disconnected),this._isConnectedAndAuthorized=!1;break;case pe.Connecting:null===(r=u.Log)||void 0===r||r.Warning(_t.ServiceName,"App state changed to: connecting"),this._onAppStateChanged.Invoke(it.Connecting);break;case pe.Disconnecting:null===(o=u.Log)||void 0===o||o.Warning(_t.ServiceName,"App state changed to: disconnecting"),this._onAppStateChanged.Invoke(it.Disconnecting);break;case pe.Reconnecting:null===(s=u.Log)||void 0===s||s.Warning(_t.ServiceName,"App state changed to: reconnecting"),this._onAppStateChanged.Invoke(it.Reconnecting);break;case pe.Failed:null===(i=u.Log)||void 0===i||i.Warning(_t.ServiceName,"App state changed to: failed"),this._onAppStateChanged.Invoke(it.FailedToConnect)}}))}))}get CurrentAppState(){return this._currentAppState}OnAppStateChanged(){return this._onAppStateChanged}Suspend(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!1,this._onSuspendedEvent.Invoke(),this._onAppStateChanged.Invoke(it.Suspended),null===(e=u.Log)||void 0===e||e.Warning(_t.ServiceName,"App state changed to: suspended"),null===(t=u.Log)||void 0===t||t.Warning(_t.ServiceName,"App switched to background"))}ReturnFromSuspension(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!0,this._onReturnedFromSuspensionEvent.Invoke(),this._onAppStateChanged.Invoke(it.ReturnedFromSuspension),null===(e=u.Log)||void 0===e||e.Warning(_t.ServiceName,"App state changed to: returned from suspension"),null===(t=u.Log)||void 0===t||t.Warning(_t.ServiceName,"App switched to foreground"))}EnterLowPowerMode(){this._onEnterLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(it.EnteredLowPowerMode)}ExitLowPowerMode(){this._onExitLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(it.ExitedLowPowerMode)}IsWorkingInWebView(){return"file:"===window.location.protocol||null!=navigator.userAgent.match(/Safari/i)&&!navigator.mediaDevices}IsHidden(){return document.hidden}IsActive(){return!this.IsHidden()}IsInBackground(){return this.IsHidden()}ReturnedFromSuspension(){return this._returnedFromSuspension}IsHibernationAllowed(){return this._canHibernate}DisallowHibernation(){this._canHibernate=!1}AllowHibernation(){this._canHibernate=!0}OnReturnedFromSuspension(){return this._onReturnedFromSuspensionEvent}OnSuspended(){return this._onSuspendedEvent}OnEnterLowPowerMode(){return this._onEnterLowPowerModeEvent}OnExitLowPowerMode(){return this._onExitLowPowerModeEvent}OnBackButtonPressed(){return this._onBackButtonPressedEvent}OnForwardButtonPressed(){return this._onForwardButtonPressedEvent}GetServiceName(){return _t.ServiceName}}_t.ServiceName="AppStateService";var Ct=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Dt{nextRetryDelayInMilliseconds(){return 1e3}}const Tt=[t.WebSockets,t.ServerSentEvents,t.LongPolling];class kt{constructor(){this._log=hy.Get(a.ServiceName)}log(e,t){if(!(e<It.SignalRLogLevel))switch(t=`[SignalR] ${t}`,e){case r.Critical:case r.Error:this._log.Error(t);break;case r.Warning:this._log.Warning(t);break;case r.Information:this._log.Info(t);break;default:this._log.Debug(t)}}}class It{constructor(){this._connectTask=null,this._authorizeTask=null,this._pingTimerId=null,this._consecutivePingFailures=0,this._disconnectedOnPurpose=!1,this._address="packets-broker1.tr7.pl",this._serversBrokerAddress="https://servers-broker.tr7.pl",this._serversBrokerAddressList=["https://servers-broker.tr7.pl","https://broker.tr7.pl","https://dev-broker.tr7.pl"],this._allBrokersChecked=!1,this._packetsBrokerServers=["packets-broker1.tr7.pl","packets-broker2.tr7.pl"],this._isAuthorized=!1,this._lastReceivedPacket=Date.now(),this._everConnected=!1,this._pendingRequests=new Map,this._log=hy.Get(a.ServiceName),this._appState=hy.Get(_t.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._dataReceivedEvent=new c,this._pongReceivedEvent=new ke,this._authorizationReceivedEvent=new c,this._registrationReceivedEvent=new c,this._streamStartedEvent=new c,this._connectionStateChangedEvent=new c,this._errorOccuredEvent=new c,this._tryReconnect=()=>{this._connectTask||navigator.onLine&&this.validateConnectionToController().then((e=>{e||(this._log.Debug(It.ServiceName,"Connection lost → reconnecting..."),this.serialisedConnect())}))},this._onVisibility=()=>{this._connectTask||"visible"===document.visibilityState&&(this._log.Debug(It.ServiceName,"Page visible → connection check"),this.validateConnectionToController().then((e=>{e||(this._log.Debug(It.ServiceName,"Connection lost → reconnecting..."),this.serialisedConnect())})))},this._onHidden=()=>{},this._onVisible=()=>{this._connectTask||this.validateConnectionToController().then((e=>{e||(this._log.Debug(It.ServiceName,"Connection lost → reconnecting..."),this.serialisedConnect())}))},this._appState.OnAppStateChanged().Subscribe((e=>Ct(this,void 0,void 0,(function*(){var t;switch(this._log.Debug(It.ServiceName,`App state changed: ${e}`),e){case it.ExitedLowPowerMode:case it.ReturnedFromSuspension:this._log.Debug(It.ServiceName,`Handling app state change: ${e}`),(yield this.RestoreConnectionAsync())&&(null===(t=this._session)||void 0===t||t.RestoreSessionAsync())}}))))}GetServiceName(){return It.ServiceName}GetAuthorizationInfo(){return this._serialId&&this._PIN?new De(this._serialId,this._PIN):null}GetControllerSerialNumber(){return this._serialId}GetControllerPin(){return this._PIN}SetServersBrokerAddress(e){this._serversBrokerAddress=e}SetDefaultPacketsBrokerAddress(e){this._address=e}EnablePacketsLogging(){window.packets=!0}DisablePacketsLogging(){window.packets=!1}SubscribeTo(e,t){const n=n=>{n.Resource===e&&t(n)};return this._dataReceivedEvent.Subscribe(n),()=>this._dataReceivedEvent.Unsubscribe(n)}reauthorizeIfPossible(){return Ct(this,void 0,void 0,(function*(){if(!this._serialId||!this._PIN)return this._isAuthorized=!1,!1;const e=yield this.AuthorizeAsync(new De(this._serialId,this._PIN));return this._isAuthorized=e,e}))}GetServerAddressAsync(){return Ct(this,void 0,void 0,(function*(){if(!this._serialId)return this._log.Warning(It.ServiceName,"GetServerAddressAsync() – serialId not set"),null;const e=`${this._serversBrokerAddress}/api/connections/broker/whichserver/${this._serialId}`;try{const t=yield fetch(e);switch(t.status){case 200:{const e=(yield t.text()).trim();return e?(this._log.Debug(It.ServiceName,`Broker address resolved: ${e}`),e):(this._log.Warning(It.ServiceName,"Broker returned empty address"),null)}case 204:return this._allBrokersChecked?(this._log.Error(It.ServiceName,"All servers-brokers checked, controller not found – likely offline"),null):(this._log.Warning(It.ServiceName,`Servers-broker ${this._serversBrokerAddress} returned 204 (no content) – controller not found on this server`),yield this.rotateServersBroker(),this.GetServerAddressAsync());default:return this._log.Warning(It.ServiceName,`GetServerAddressAsync() – HTTP ${t.status}`),null}}catch(e){return this._log.Error(It.ServiceName,String(e)),null}}))}rotateServersBroker(){return Ct(this,void 0,void 0,(function*(){const e=this._serversBrokerAddressList.indexOf(this._serversBrokerAddress),t=e+1<this._serversBrokerAddressList.length?e+1:0;this._serversBrokerAddress=this._serversBrokerAddressList[t],this._allBrokersChecked=0===t,this._log.Info(It.ServiceName,`Switching servers-broker to: ${this._serversBrokerAddress}`)}))}ConnectAsync(e){return Ct(this,void 0,void 0,(function*(){return this._address=e,this.serialisedConnect()}))}ConnectAndAuthorizeAsync(e){return Ct(this,void 0,void 0,(function*(){this._serialId=e.serialNumber,this._PIN=e.pin,hy.WorksInContextOf=this._serialId,this._allBrokersChecked=!1,this._serversBrokerAddress=this._serversBrokerAddressList[0];const t=yield this.GetServerAddressAsync();if(t&&(this.SetDefaultPacketsBrokerAddress(t),(yield this.serialisedConnect())===he.Connected&&(yield this.AuthorizeAsync(e))))return he.Connected;for(const t of this._packetsBrokerServers)if(this._log.Info(It.ServiceName,`Fallback broker: ${t}`),this.SetDefaultPacketsBrokerAddress(t),(yield this.serialisedConnect())===he.Connected&&(yield this.AuthorizeAsync(e)))return this._disconnectedOnPurpose=!1,he.Connected;return he.FailedToConnect}))}AuthorizeAsync(e){return Ct(this,void 0,void 0,(function*(){return this._authorizeTask||(this._authorizeTask=new Promise((t=>Ct(this,void 0,void 0,(function*(){var n;const r=window.setTimeout((()=>{this._authorizationReceivedEvent.Unsubscribe(o),this._isAuthorized=!1,this._log.Debug(It.ServiceName,`AuthorizeAsync timed out for id ${r}`),t(!1)}),2e3);this._log.Debug(It.ServiceName,`AuthorizeAsync - created timeoutId ${r}`);const o=e=>{window.clearTimeout(r),this._authorizationReceivedEvent.Unsubscribe(o),this._log.Debug(It.ServiceName,`Authorization → ${e}`),this._isAuthorized=e,e&&this._connectionStateChangedEvent.Invoke(pe.ConnectedAndAuthorized),this._log.Debug(It.ServiceName,`AuthorizeAsync isAuthorized: ${e} cleared timeoutId ${r}`),t(e)};this._authorizationReceivedEvent.Subscribe(o),this._log.Debug(It.ServiceName,`Authorizing to ${e.SerialNumber}... for timoeoutId ${r}`),yield null===(n=this._connection)||void 0===n?void 0:n.send("AuthorizeTo",e.SerialNumber,e.PIN)})))).finally((()=>{this._authorizeTask=null}))),this._authorizeTask}))}IsConnected(){var e;return(null===(e=this._connection)||void 0===e?void 0:e.state)===s.Connected}DisconnectAsync(){return Ct(this,void 0,void 0,(function*(){var e;this._disconnectedOnPurpose=!0,this._log.Debug(It.ServiceName,"Disconnecting..."),yield null===(e=this._connection)||void 0===e?void 0:e.stop(),this.cleanup()}))}SendAsync(e){return Ct(this,arguments,void 0,(function*(e,t=!1){var n,r;if(!this.IsConnected())throw new Error("Not connected");const o=()=>Ct(this,void 0,void 0,(function*(){yield this._connection.invoke("SendTo",this._serialId,e)})),s=!0===window.packets;(s||t)&&this._log.Debug(It.ServiceName,`⇢ ${e.Resource} ${e.Method} ${e.TransactionId}`+(s?`\n${JSON.stringify(e,null,2)}`:""));try{return yield o(),!0}catch(e){if(String(null!==(n=null==e?void 0:e.message)&&void 0!==n?n:e).toLowerCase().includes("unauthorized")){if(!(yield this.reauthorizeIfPossible())){this._allBrokersChecked=!1,this._serversBrokerAddress=this._serversBrokerAddressList[0];const e=yield this.GetServerAddressAsync();if(e&&e!==this._address){this._log.Info(It.ServiceName,`Switching to resolved broker: ${e}`);try{yield null===(r=this._connection)||void 0===r?void 0:r.stop()}catch(e){}this.cleanup(),yield this.ConnectAsync(e),yield this.reauthorizeIfPossible()}}if(this.IsConnected()&&this._isAuthorized)try{return yield o(),!0}catch(t){e=t}}return this._log.Error(It.ServiceName,String(e)),!1}}))}RestoreConnectionAsync(){return Ct(this,void 0,void 0,(function*(){var e,t;if(this._disconnectedOnPurpose)return!1;const n=this.GetAuthorizationInfo();if(null===n)return null===(e=u.Log)||void 0===e||e.Error(It.ServiceName,"RestoreSessionAsync failed, no authorization info"),!1;const r=Date.now();let o=0;do{if(this.IsConnected()&&(yield this.AuthorizeAsync(n)))return!0;if((yield this.ConnectAndAuthorizeAsync(n))===he.Connected)return!0;const e=Math.min(3e4,5e3*Math.pow(2,o++));yield new Promise((t=>setTimeout(t,e))),this._allBrokersChecked=!1,this._serversBrokerAddress=this._serversBrokerAddressList[0]}while(Date.now()-r<18e5);return null===(t=u.Log)||void 0===t||t.Error(It.ServiceName,"RestoreSessionAsync failed, authorization failed"),!1}))}SendAndWaitForResponseAsync(e,t,n){return Ct(this,arguments,void 0,(function*(e,t,n,r=!0,o=!0){var s,i,a;if(e.Method===le.Get&&n&&!(yield null===(s=this._controllerConfiguration)||void 0===s?void 0:s.DidCofigurationChangeAsync())){const t=null===(i=this._cache)||void 0===i?void 0:i.GetCache(e);if(t)return t}if(!this.IsConnected()&&!(yield this.RestoreConnectionAsync()))throw new Error("Failed to restore connection!");return"/users/user/login"!==e.Resource&&(yield null===(a=this._session)||void 0===a?void 0:a.WaitForSessionCreationAsync()),new Promise(((s,i)=>Ct(this,void 0,void 0,(function*(){const a=window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(c),this._pendingRequests.delete(e.TransactionId),i(new I("Response timeout"))}),t),c=u=>{var l;u.TransactionId===e.TransactionId&&(window.clearTimeout(a),this._dataReceivedEvent.Unsubscribe(c),this._pendingRequests.delete(e.TransactionId),e.Method===le.Get&&n&&u.Status!==ue.UserIsNotLoggedIn&&(null===(l=this._cache)||void 0===l||l.Cache(u)),o&&u.Status===ue.UserIsNotLoggedIn?(()=>{Ct(this,void 0,void 0,(function*(){var o;try{yield null===(o=this._session)||void 0===o?void 0:o.RestoreSessionAsync(),s(yield this.SendAndWaitForResponseAsync(e,t,n,r,!1))}catch(e){i(e)}}))})():s(u))};this._dataReceivedEvent.Subscribe(c),this._pendingRequests.set(e.TransactionId,{resolve:e=>s(e),reject:i,timeoutId:a}),(yield this.SendAsync(e,r))||(window.clearTimeout(a),this._dataReceivedEvent.Unsubscribe(c),this._pendingRequests.delete(e.TransactionId),i(new Error("Failed to send request")))}))))}))}SendAndHandleResponseAsync(e,t,n){return Ct(this,arguments,void 0,(function*(e,t,n,r=!0){var o;if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(o=this._session)||void 0===o?void 0:o.WaitForSessionCreationAsync()),new Promise(((o,s)=>Ct(this,void 0,void 0,(function*(){const i=()=>window.setTimeout((()=>{c(),s(new I("MultiDataResponse timeout"))}),t);let a=i();const c=()=>{window.clearTimeout(a),this._dataReceivedEvent.Unsubscribe(u),this._pendingRequests.delete(e.TransactionId)},u=t=>{if(t.TransactionId===e.TransactionId)switch(window.clearTimeout(a),t.Status){case ue.MultiDataResponseStart:case ue.MultiDataResponse:n(t),a=i();break;case ue.MultiDataResponseStop:case ue.OK:n(t),c(),o();break;default:c(),s(new Error(`Unexpected status ${t.Status}`))}};this._dataReceivedEvent.Subscribe(u),this._pendingRequests.set(e.TransactionId,{resolve:()=>o(),reject:s,timeoutId:a}),(yield this.SendAsync(e,r))||(c(),s(new Error("Failed to send request")))}))))}))}SendAndHandleStreamAsync(e,t){return Ct(this,arguments,void 0,(function*(e,t,n=!0){var r;if(!this.IsConnected())throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(r=this._session)||void 0===r?void 0:r.WaitForSessionCreationAsync()),new Promise(((r,o)=>Ct(this,void 0,void 0,(function*(){const s=window.setTimeout((()=>{this._streamStartedEvent.Unsubscribe(i),o(new I("Stream registration timeout"))}),8e3),i=n=>{n===e.TransactionId&&(window.clearTimeout(s),this._streamStartedEvent.Unsubscribe(i),this._connection.stream("WatchStream",n).subscribe({next:e=>t.Next(e),complete:()=>{t.Complete(),r()},error:e=>{t.Error(e),o(new Te(String(e)))}}))};this._streamStartedEvent.Subscribe(i),(yield this.SendAsync(e,n))||(window.clearTimeout(s),this._streamStartedEvent.Unsubscribe(i),o(new Error("Failed to send request")))}))))}))}PingControllerAsync(){return Ct(this,void 0,void 0,(function*(){if(!this.IsConnected()||!this._isAuthorized)return!1;if(Date.now()-this._lastReceivedPacket<It.PING_INTERVAL_MS)return!1;const e=new ce;e.Resource="/system/ping",e.Method=le.Get;try{return yield this.SendAndWaitForResponseAsync(e,2e3,!1,!1),!0}catch(e){return!1}}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}serialisedConnect(){return this._connectTask||(this._connectTask=this.connectCore().finally((()=>this._connectTask=null))),this._connectTask}waitForState(e){return Ct(this,arguments,void 0,(function*(e,t=1e4){var n;const r=Date.now();for(;;){const o=null===(n=this._connection)||void 0===n?void 0:n.state;if(null!=o&&e.includes(o))return;if(Date.now()-r>t)throw new Error(`waitForState timeout; state=${o}`);yield new Promise((e=>setTimeout(e,50)))}}))}connectCore(){return Ct(this,void 0,void 0,(function*(){var n,o;if(!this._address)return he.ControllerIsNotConnected;if(this._connection&&this._currentAddress!==this._address){this._log.Info(It.ServiceName,"Broker changed → rebuilding connection");try{yield this._connection.stop()}catch(e){}this.cleanup()}if(this._connection){const e=this._connection.state;if(e===s.Connected)return this._isAuthorized||(yield this.reauthorizeIfPossible()),he.Connected;if(e===s.Connecting||e===s.Reconnecting){this._log.Info(It.ServiceName,"Existing connection is starting/reconnecting – waiting.");try{yield this.waitForState([s.Connected,s.Disconnected])}catch(e){}if((null===(n=this._connection)||void 0===n?void 0:n.state)===s.Connected)return this._isAuthorized||(yield this.reauthorizeIfPossible()),he.Connected}e===s.Disconnecting&&(yield this.waitForState([s.Disconnected]).catch((()=>{})))}this.initializeServices(),this.cleanup();for(const n of Tt){const s=(new re).withAutomaticReconnect(new Dt).configureLogging(new kt).withStatefulReconnect({bufferSize:256e3}).withServerTimeout(It.SERVER_TIMOUT_MS).withKeepAliveInterval(It.PING_INTERVAL_MS-1e3).withUrl(`https://${this._address}/broker`,{skipNegotiation:n===t.WebSockets,transport:n});this._log.LogLevel===e.Debug&&s.configureLogging(r.Debug);const i=s.build();this._connection=i,this._currentAddress=this._address,this.wireConnectionEvents();try{return yield i.start(),yield this.reauthorizeIfPossible(),this.startPingLoop(),this._connectionStateChangedEvent.Invoke(pe.Connected),he.Connected}catch(e){this._log.Warning(It.ServiceName,`Transport ${t[n]} failed (${null==e?void 0:e.message}).`);try{yield i.stop()}catch(e){}try{null===(o=null==i?void 0:i.off)||void 0===o||o.call(i)}catch(e){}}}return this._connectionStateChangedEvent.Invoke(pe.Failed),he.FailedToConnect}))}waitForReconnection(e=0){return new Promise(((t,n)=>{if(!this._connection||this._connection.state!==s.Reconnecting)return void n(new Error("Connection is not in reconnecting state"));let r;e>0&&(r=window.setTimeout((()=>{this._connectionStateChangedEvent.Unsubscribe(o),n(new Error("Reconnection timeout"))}),e));const o=e=>{e===pe.Connected?(r&&window.clearTimeout(r),this._connectionStateChangedEvent.Unsubscribe(o),t()):e!==pe.Disconnected&&e!==pe.Failed||(r&&window.clearTimeout(r),this._connectionStateChangedEvent.Unsubscribe(o),n(new Error("Connection closed during reconnection")))};this._connectionStateChangedEvent.Subscribe(o),this._connection.state!==s.Reconnecting&&(r&&window.clearTimeout(r),this._connectionStateChangedEvent.Unsubscribe(o),this._connection.state===s.Connected?t():n(new Error(`Connection is in unexpected state: ${this._connection.state}`)))}))}initializeServices(){this._controllerConfiguration=hy.Get(ct.ServiceName),this._cache=hy.Get(Be.ServiceName),this._session=hy.Get(Xe.ServiceName)}wireConnectionEvents(){this._connection&&(this._connection.on("Pong",(()=>{this._lastReceivedPacket=Date.now(),this._pongReceivedEvent.Invoke()})),this._connection.on("controllerdisconnected",(()=>{this._isAuthorized=!1,this._connectionStateChangedEvent.Invoke(pe.Disconnected)})),this._connection.on("Authorization",(e=>this._authorizationReceivedEvent.Invoke(e))),this._connection.on("Registration",(e=>this._registrationReceivedEvent.Invoke(e))),this._connection.on("SendError",((e,t)=>{e.startsWith("NotAuthorized:")?this.AuthorizeAsync(new De(this._serialId,this._PIN)):this._errorOccuredEvent.Invoke([e,t])})),this._connection.on("Data",((e,t)=>{this._lastReceivedPacket=Date.now(),!0===window.packets&&this._log.Debug(It.ServiceName,`Received: ${JSON.stringify(JSON.parse(t),null,2)}`),this._dataReceivedEvent.Invoke(JSON.parse(t))})),this._connection.onclose((()=>{this._isAuthorized=!1,this.cleanup(),this._connectionStateChangedEvent.Invoke(pe.Disconnected)})),this._connection.onreconnecting((()=>this._connectionStateChangedEvent.Invoke(pe.Reconnecting))),this._connection.onreconnected((()=>Ct(this,void 0,void 0,(function*(){var e;this._connectionStateChangedEvent.Invoke(pe.Connected),(yield this.RestoreConnectionAsync())&&(null===(e=this._session)||void 0===e||e.RestoreSessionAsync())})))))}startPingLoop(){null!==this._pingTimerId&&clearInterval(this._pingTimerId),this._pingTimerId=window.setInterval((()=>{this.pingOnce()}),It.PING_INTERVAL_MS),window.addEventListener("online",this._tryReconnect),window.addEventListener("offline",this._tryReconnect),document.addEventListener("visibilitychange",this._onVisibility,!0),window.addEventListener("pagehide",this._onHidden,!0),window.addEventListener("pageshow",this._onVisible,!0)}isBusy(){var e;const t=null===(e=this._connection)||void 0===e?void 0:e.state;return t===s.Connecting||t===s.Disconnecting||t===s.Reconnecting}pingOnce(){return Ct(this,void 0,void 0,(function*(){this.IsConnected()&&!this.isBusy()&&(Date.now()-this._lastReceivedPacket<It.PING_INTERVAL_MS||((yield this.PingControllerAsync())?this._consecutivePingFailures=0:++this._consecutivePingFailures>=It.MAX_CONSECUTIVE_PING_FAILURES&&(this._consecutivePingFailures=0,this._log.Warning(It.ServiceName,"Ping failed too many times → reconnecting..."),this.serialisedConnect())))}))}validateConnectionToController(){return Ct(this,void 0,void 0,(function*(){var e;if(!this.IsConnected())return this._log.Warning(It.ServiceName,"Connection was lost"),!1;{const t=new ce;t.Resource="/system/ping",t.Method=le.Get;try{const n=yield this.SendAndWaitForResponseAsync(t,It.SERVER_TIMOUT_MS+1e3,!1,!1);return(null==n?void 0:n.Status)!==ue.OK?(this._log.Warning(It.ServiceName,"Connection check failed, "+(null==n?"result is null":`status: ${n.Status}`)),!1):(null===(e=this._connection)||void 0===e?void 0:e.state)===s.Reconnecting?(this._log.Warning(It.ServiceName,"Connection check failed, connection is in reconnecting state"),!1):(this._log.Info(It.ServiceName,"Connection still active"),!0)}catch(e){return!1}}}))}cleanup(){var e,t;null!==this._pingTimerId&&(clearInterval(this._pingTimerId),this._pingTimerId=null);for(const[,e]of this._pendingRequests)window.clearTimeout(e.timeoutId),e.reject(new Error("Connection lost"));this._pendingRequests.clear(),window.removeEventListener("online",this._tryReconnect),window.removeEventListener("offline",this._tryReconnect),document.removeEventListener("visibilitychange",this._onVisibility,!0),window.removeEventListener("pagehide",this._onHidden,!0),window.removeEventListener("pageshow",this._onVisible,!0);try{null===(t=null===(e=this._connection)||void 0===e?void 0:e.off)||void 0===t||t.call(e)}catch(e){}this._connection=void 0,this._currentAddress=void 0}}var Et,bt,Gt,Nt,Rt,Pt,Ut,Ot,Mt,xt,Ft,Lt,Bt,Wt,$t,Vt;It.PING_INTERVAL_MS=5e3,It.MAX_CONSECUTIVE_PING_FAILURES=6,It.SERVER_TIMOUT_MS=1e4,It.SignalRLogLevel=r.Warning,It.ServiceName="ExalusConnectionService",function(e){e[e.NoTasksExecuting=0]="NoTasksExecuting",e[e.ExecutingTasks=1]="ExecutingTasks"}(Et||(Et={})),(Lt=bt||(bt={}))[Lt.Default=0]="Default",Lt[Lt.Monostable=1]="Monostable",Lt[Lt.Bistable=2]="Bistable",Lt[Lt.Gate=3]="Gate",Lt[Lt.Gateway=4]="Gateway",function(e){e[e.None=0]="None",e[e.OnOff=1]="OnOff",e[e.OnOffLights=2]="OnOffLights",e[e.OnOffWithDelay=3]="OnOffWithDelay",e[e.GateSwitchState=4]="GateSwitchState",e[e.GatePulse=5]="GatePulse",e[e.GateOpenClose=6]="GateOpenClose",e[e.GatewayOpenClose=7]="GatewayOpenClose",e[e.GatewayPulse=8]="GatewayPulse",e[e.Monostable=9]="Monostable",e[e.Dimmer=10]="Dimmer",e[e.Blind=11]="Blind",e[e.Roller=12]="Roller",e[e.TemperatureSensor=13]="TemperatureSensor",e[e.BrightnessSensor=14]="BrightnessSensor",e[e.HumiditySensor=15]="HumiditySensor",e[e.PowerMeter=16]="PowerMeter",e[e.RGBLight=17]="RGBLight",e[e.RGBWLight=18]="RGBWLight",e[e.LightsWarmth=19]="LightsWarmth",e[e.TemperatureControl=20]="TemperatureControl",e[e.BlindsWithPrecisePosition=21]="BlindsWithPrecisePosition",e[e.MovementSensor=21]="MovementSensor",e[e.SimpleRemote=22]="SimpleRemote",e[e.BlindsRemote=23]="BlindsRemote",e[e.DistanceSensor=24]="DistanceSensor",e[e.Multisensor=25]="Multisensor",e[e.IOTransmitter=26]="IOTransmitter",e[e.DoorOpenClose=27]="DoorOpenClose",e[e.WindSensor=28]="WindSensor",e[e.BatterySensor=29]="BatterySensor",e[e.PressureSensor=30]="PressureSensor"}(Gt||(Gt={}));class qt{constructor(){this._type=Rt.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}(Bt=Nt||(Nt={}))[Bt.Unknown=0]="Unknown",Bt[Bt.BlindMotor=1]="BlindMotor",Bt[Bt.DinModule=2]="DinModule",Bt[Bt.DinModuleWithAntenna=3]="DinModuleWithAntenna",Bt[Bt.Remote=4]="Remote",Bt[Bt.RemoteForBlinds=5]="RemoteForBlinds",Bt[Bt.RemoteForFacadeBlinds=6]="RemoteForFacadeBlinds",Bt[Bt.MovementSensor=7]="MovementSensor",Bt[Bt.TemperatureSensor=8]="TemperatureSensor",Bt[Bt.HumiditySensor=9]="HumiditySensor",Bt[Bt.DinPowerMeter=10]="DinPowerMeter",Bt[Bt.Intercom=11]="Intercom",Bt[Bt.SecurityCamera=12]="SecurityCamera",Bt[Bt.Multisensor=13]="Multisensor",Bt[Bt.FloodSensor=14]="FloodSensor",Bt[Bt.FlushMountedReceiver=15]="FlushMountedReceiver",Bt[Bt.FlushMountedBlindController=16]="FlushMountedBlindController",Bt[Bt.FlushMountedDimmer=17]="FlushMountedDimmer",Bt[Bt.FlushMountedRelay=18]="FlushMountedRelay",Bt[Bt.FlushMountedGateController=19]="FlushMountedGateController",Bt[Bt.WindSensor=20]="WindSensor",Bt[Bt.FlushMountedGateAndGatewayController=21]="FlushMountedGateAndGatewayController",Bt[Bt.AirPressureSensor=22]="AirPressureSensor",Bt[Bt.LightBrightnessSensor=23]="LightBrightnessSensor",Bt[Bt.ReedSensor=24]="ReedSensor",Bt[Bt.FlushMountedTransceiver=25]="FlushMountedTransceiver",Bt[Bt.FlushMountedRGBLightController=26]="FlushMountedRGBLightController",Bt[Bt.WallMountedThermoregulator=27]="WallMountedThermoregulator",Bt[Bt.ImpulseCounter=28]="ImpulseCounter",Bt[Bt.FlushMountedFacadeController=29]="FlushMountedFacadeController",Bt[Bt.WallMountedGateController=30]="WallMountedGateController",Bt[Bt.WallMountedRGBLightController=31]="WallMountedRGBLightController",Bt[Bt.WallMountedDimmer=32]="WallMountedDimmer",Bt[Bt.WallMountedRemote=33]="WallMountedRemote",Bt[Bt.DinRelay=34]="DinRelay",Bt[Bt.DinReceiver=35]="DinReceiver",Bt[Bt.DinBlindController=36]="DinBlindController",Bt[Bt.DinTransceiver=37]="DinTransceiver",Bt[Bt.SocketPlugIn=38]="SocketPlugIn",Bt[Bt.WallMountedRelay=39]="WallMountedRelay",Bt[Bt.Retransmitter=40]="Retransmitter",function(e){e.Unknown="Unknown",e.SetBlindPosition="IBlindPosition",e.SetBlindPositionSimple="IBlindPositionSimple",e.SetBlindMicroventilation="IMicroventilation",e.TurnOff="IChannelOff",e.TurnOn="IChannelOn",e.TurnOnWithTime="IChannelOnWithTime",e.TogleState="IChannelSwitchState",e.SetLightBrightnessDynamicly="IDynamicLightBrightness",e.SetLightBrightness="ILightBrightness",e.SetLightColor="ILightColor",e.SetLightTemperature="ILightTemperature",e.PairDevice="IPair",e.UnpairDevice="IUnpair",e.IdentifyDevice="IIdentifyDevice",e.GetChannelsState="IGetDeviceState",e.GetPowerMeasurements="IGetPowerMeasurements",e.GetAvailableData="IGetAvailableData",e.MultipleDataRequest="IMultipleDataRequest",e.SetBlindOpenCloseTime="ISetBlindOpenCloseTime",e.SetTemperature="IChangeTemperature",e.SetGatePosition="IGatePosition",e.SetGatewayPosition="IGatewayPosition",e.ChangeGatePositionPulse="IGatePulse",e.ChangeGatewayPositionPulse="IGatewayPulse",e.SetFacadePosition="IFacadePosition",e.GetFacadeType="IGetFacadeType",e.LightRGBW="ILightRGBW",e.PreciseGateControl="IPreciseGateControl",e.PreciseGateControlSecure="IPreciseGateControlSecure"}(Rt||(Rt={}));class Ht{constructor(){this._type=Pt.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}!function(e){e.Unknown="Unknown",e.BatteryState="IBatteryState",e.BinarySensorState="IBinarySensor",e.BlindOpenCloseTime="IBlindOpenCloseTime",e.BlindPosition="IBlindPosition",e.BlindRemoteButtonState="IBlindsControlButton",e.BlindErrorState="IBlindError",e.MeasuredBrightness="IBrightness",e.RemoteButtonState="IButtonState",e.ChannelOnOffState="IChannelOnOff",e.IntercomState="IIntercom",e.DoorBellState="IDoorBell",e.FacadeRemoteButtonState="IFacadeControlButton",e.FacadePosition="IFacadeState",e.FacadeType="IFacadeType",e.FloodSensorState="IFloodSensor",e.GatePosition="IGatePosition",e.GatewayPosition="IGatewayPosition",e.GateControllerHealth="IGateControllerHealth",e.HumiditySensorState="IHumiditySensor",e.LightBrightness="ILightBrightness",e.LightColor="ILightColor",e.LightWarmth="ILightTemperature",e.LightTreshold="ILightTreshold",e.MovementSensorState="IMovementSensor",e.OnlineCamera="IOnlineCamera",e.OvercurrentProtectionState="IOvercurrentProtection",e.OvercurrentProtectionThreshold="IOvercurrentProtectionThreshold",e.ReedState="IReedState",e.SignalStrength="ISignalStrength",e.SmokeSensorState="ISmokeSensor",e.MeasuredTemperature="ITemperature",e.VibrationSensorState="IVibrationSensor",e.MeasuredWindSpeed="IWindSpeed",e.WindThreshold="IWindThreshold",e.MeasuredEnergy="IEnergy",e.MeasuredDistance="DistanceSensor",e.BlindCalibration="BlindCalibration",e.ConfigurationState="ConfigurationState",e.CurrentWindThreshold="CurrentWindThreshold",e.CurrentLightThreshold="CurrentLightThreshold",e.WindSpeedState="WindSpeed",e.TamperProtectionState="ITamperProtection",e.PressureSensorState="IPressureSensor",e.LightRGBWState="ILightRGBW",e.SceneExecuted="ISceneExecuted",e.HallState="IHallState",e.Intercom="IIntercom"}(Pt||(Pt={})),(Vt=Ut||(Ut={}))[Vt.NotResponding=0]="NotResponding",Vt[Vt.Working=1]="Working",Vt[Vt.Broken=2]="Broken",Vt[Vt.FirmareUpgradeMode=3]="FirmareUpgradeMode",($t=Ot||(Ot={}))[$t.TwoWay=1]="TwoWay",$t[$t.OneWay=2]="OneWay",$t[$t.ConditionalTwoWay=3]="ConditionalTwoWay",(Wt=Mt||(Mt={}))[Wt.Unknown=-1]="Unknown",Wt[Wt.Multipurpose=0]="Multipurpose",Wt[Wt.Controller=1]="Controller",Wt[Wt.Driver=2]="Driver",Wt[Wt.Receiver=3]="Receiver",Wt[Wt.Remote=4]="Remote",Wt[Wt.Sensor=5]="Sensor",Wt[Wt.Scene=6]="Scene";class Kt{constructor(){this.DeviceGuid="",this.Channel=0,this.Status=Et.NoTasksExecuting}}!function(e){e[e.Unknown=0]="Unknown",e[e.Executed=1]="Executed",e[e.ResponseTimeout=2]="ResponseTimeout",e[e.TaskRepeatedAndExecuted=3]="TaskRepeatedAndExecuted",e[e.TaskRepeatedResponseTimeout=4]="TaskRepeatedResponseTimeout",e[e.FlowControlNotAvailable=5]="FlowControlNotAvailable",e[e.ExecutionError=6]="ExecutionError"}(xt||(xt={})),function(e){e[e.ControllerResponseTimeout=-4]="ControllerResponseTimeout",e[e.DeviceNotFound=-3]="DeviceNotFound",e[e.DeviceResponseTimeout=-2]="DeviceResponseTimeout",e[e.Failed=-1]="Failed",e[e.Unknown=0]="Unknown",e[e.Executed=1]="Executed"}(Ft||(Ft={}));class jt{constructor(){this.Device=null,this.Channel=0,this.Task=null,this.Result=Ft.Unknown}}var zt,Jt,Xt,Yt,Qt,Zt,en,tn,nn,rn,on,sn,an,cn,un,ln,dn,hn,pn,gn,fn,vn,yn,mn,wn,Sn,An,_n,Cn,Dn,Tn;class kn{constructor(){this._type="",this._data=null,this._typeAsEnum=Pt.Unknown,this._serializedDataWithoutTime=""}get Data(){return this._data}set Data(e){this._data=e;let{Time:t}=e,n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(e,["Time"]);this._serializedDataWithoutTime=JSON.stringify(n)}get Type(){return this._type}set Type(e){this._type=e}get TypeAsEnum(){return this._typeAsEnum}set TypeAsEnum(e){this._typeAsEnum=e}get StatesComparisonData(){return this._serializedDataWithoutTime}}(Tn=zt||(zt={}))[Tn.Confident=0]="Confident",Tn[Tn.Unconfident=1]="Unconfident";class In extends kn{constructor(e){super(),this.TypeAsEnum=Pt.ChannelOnOffState,this.Type="ChannelOnOffState",this.Data=e.state}}class En{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=Jt.Unknown,this.Time=""}}!function(e){e[e.On=0]="On",e[e.Off=1]="Off",e[e.Unknown=2]="Unknown"}(Jt||(Jt={}));class bn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.HallState,this.Type="IHallState",this.Data=e.state}}class Gn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.SceneExecuted,this.Type="ISceneExecuted",this.Data=e.state}}class Nn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.IntercomState,this.Type="IntercomState",this.Data=e.state}}!function(e){e[e.Idle=0]="Idle",e[e.IncomingCall=1]="IncomingCall",e[e.AnsweringCall=2]="AnsweringCall",e[e.Busy=3]="Busy",e[e.NoAnswerToCall=4]="NoAnswerToCall",e[e.Unknown=5]="Unknown"}(Xt||(Xt={}));class Rn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.OnlineCamera,this.Type="OnlineCameraState",this.Data=e.state}}class Pn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.DoorBellState,this.Type="DoorBellState",this.Data=e.state}}class Un{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=Yt.Relased,this.Time=""}}!function(e){e[e.Pressed=0]="Pressed",e[e.Relased=1]="Relased",e[e.PressedAndRelased=2]="PressedAndRelased"}(Yt||(Yt={}));class On extends kn{constructor(e){super(),this.TypeAsEnum=Pt.ReedState,this.Type="ReedState",this.Data=e.state}}class Mn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=!1,this.Time=""}}class xn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BlindPosition,this.Type="BlindPostionState",this.Data=e.state}GetBlindStatus(){switch(this.Data.Position){case 200:return Qt.UnableToMove;case 201:return Qt.MotorOverheatedPleaseWait;default:return Qt.Working}}}!function(e){e[e.Unknown=0]="Unknown",e[e.Working=1]="Working",e[e.UnableToMove=200]="UnableToMove",e[e.MotorOverheatedPleaseWait=201]="MotorOverheatedPleaseWait"}(Qt||(Qt={}));class Fn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Position=0,this.RawPosition=0,this.Time=""}}class Ln extends kn{constructor(e){super(),this.TypeAsEnum=Pt.RemoteButtonState,this.Type="RemoteButtonState",this.Data=e.state}}class Bn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=Zt.Relased,this.Time=""}}!function(e){e[e.Pressed=1]="Pressed",e[e.Relased=2]="Relased",e[e.PressedAndRelased=3]="PressedAndRelased"}(Zt||(Zt={}));class Wn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.LightColor,this.Type="LightColorState",this.Data=e.state}}class $n{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.R=0,this.G=0,this.B=0,this.Time=""}}class Vn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.LightWarmth,this.Type="LightWarmthState",this.Data=e.state}}class qn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Temperature=0,this.Time=""}}class Hn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.LightBrightness,this.Type="LightBrightnessState",this.Data=e.state}}class Kn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Brightness=0,this.Time=""}}class jn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.MeasuredTemperature,this.Type="MeasuredTemperatureState",this.Data=e.state}}class zn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Temperature=0,this.Type=en.InsideTemperature,this.Time=""}}!function(e){e[e.AirTemperature=0]="AirTemperature",e[e.InsideTemperature=1]="InsideTemperature",e[e.OutsideTemperature=2]="OutsideTemperature",e[e.FloorTemperature=3]="FloorTemperature",e[e.SafetyTemperature=4]="SafetyTemperature",e[e.SetTemperature=5]="SetTemperature"}(en||(en={}));class Jn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BatteryState,this.Type="BatteryState",this.Data=e.state}}class Xn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=tn.Half,this.Percentage=-1,this.Time=""}}!function(e){e[e.Unknown=-1]="Unknown",e[e.Full=0]="Full",e[e.Empty=1]="Empty",e[e.Half=2]="Half",e[e.Percentage=3]="Percentage",e[e.Low=4]="Low",e[e.ExternalPower=5]="ExternalPower"}(tn||(tn={}));class Yn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.MeasuredBrightness,this.Type="MeasuredBrightnessState",this.Data=e.state}}class Qn{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Brightness=0,this.Time=""}}class Zn extends kn{constructor(e){super(),this.TypeAsEnum=Pt.MeasuredEnergy,this.Type="MeasuredEnergyState",this.Data=e.state,this.Data.MeasurementParameters=new Map(Object.entries(e.state.MeasurementParameters))}}class er{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Time="",this.MeasurementParameters=new Map}}!function(e){e.Voltage="Voltage",e.Current="Current",e.PhaseShift="PhaseShift",e.ActivePower="ActivePower",e.ReactivePower="ReactivePower",e.ApparentPower="ApparentPower",e.PowerFactor="PowerFactor",e.ActiveForwardEnergy="ActiveForwardEnergy",e.ActiveReverseEnergy="ActiveReverseEnergy",e.ApparentEnergy="ApparentEnergy",e.ReactiveForwardEnergy="ReactiveForwardEnergy",e.ReactiveReverseEnergy="ReactiveReverseEnergy",e.Frequency="Frequency",e.SPIErrorRate="SPIErrorRate",e.CRCErrorRate="CRCErrorRate",e.Timestamp="Timestamp",e.FailedMeasurementsRate="FailedMeasurementsRate",e.FundamentalActivePower="FundamentalActivePower",e.HarmonicActivePower="HarmonicActivePower"}(nn||(nn={}));class tr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.MeasuredDistance,this.Type="MeasuredDistanceState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(rn||(rn={}));class nr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.MovementSensorState,this.Type="MovementSensorState",this.Data=e.state}}class rr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Intensity=0,this.Movement=on.No,this.Time=""}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(on||(on={}));class or extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BlindRemoteButtonState,this.Type="BlindRemoteButtonState",this.Data=e.state}}class sr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=sn.StopReleased,this.Time=""}}!function(e){e[e.OpenPressed=1]="OpenPressed",e[e.OpenReleased=2]="OpenReleased",e[e.StopPressed=3]="StopPressed",e[e.StopReleased=4]="StopReleased",e[e.ClosePressed=5]="ClosePressed",e[e.CloseReleased=6]="CloseReleased"}(sn||(sn={}));class ir extends kn{constructor(e){super(),this.TypeAsEnum=Pt.FacadeRemoteButtonState,this.Type="FacadeRemoteButtonState",this.Data=e.state}}class ar{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=an.StopReleased,this.Time=""}}!function(e){e[e.OpenPressed=1]="OpenPressed",e[e.OpenReleased=2]="OpenReleased",e[e.StopPressed=3]="StopPressed",e[e.StopReleased=4]="StopReleased",e[e.ClosePressed=5]="ClosePressed",e[e.CloseReleased=6]="CloseReleased"}(an||(an={}));class cr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.SignalStrength,this.Type="SignalStrenghtState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Excellent=1]="Excellent",e[e.Good=2]="Good",e[e.Acceptable=3]="Acceptable",e[e.Low=4]="Low",e[e.Terrible=5]="Terrible",e[e.NoLink=6]="NoLink"}(cn||(cn={}));class ur extends kn{constructor(e){super(),this.TypeAsEnum=Pt.GatePosition,this.Type="GatePositionState",this.Data=e.state}}class lr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.PositionType=un.Unknown,this.Position=0,this.Time=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.PartiallyOpen=2]="PartiallyOpen",e[e.Close=3]="Close",e[e.On=4]="On",e[e.Off=5]="Off",e[e.Percentage=6]="Percentage"}(un||(un={}));class dr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.GatewayPosition,this.Type="GatewayPositionState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.PartiallyOpen=2]="PartiallyOpen",e[e.Close=3]="Close",e[e.On=4]="On",e[e.Off=5]="Off"}(ln||(ln={}));class hr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.GateControllerHealth,this.Type="GateControllerHealthState",this.Data=e.state}}!function(e){e[e.Unknown=-1]="Unknown",e[e.Inactive=0]="Inactive",e[e.Active=1]="Active",e[e.UnconnectedOrMalfunction=2]="UnconnectedOrMalfunction"}(dn||(dn={}));class pr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BlindCalibration,this.Type="BlindCalibrationState",this.Data=e.state}}!function(e){e[e.AutoLernIdle=0]="AutoLernIdle",e[e.AutoLernInProgress=1]="AutoLernInProgress",e[e.AutoLernSuccessfull=2]="AutoLernSuccessfull",e[e.AutoLernCancelled=4]="AutoLernCancelled"}(hn||(hn={}));class gr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.HumiditySensorState,this.Type="HumiditySensorState",this.Data=e.state}}class fr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Type=pn.AirHumidity,this.Humidity=0,this.Time=""}}!function(e){e[e.AirHumidity=0]="AirHumidity",e[e.InsideHumidity=1]="InsideHumidity",e[e.OutsideHumidity=2]="OutsideHumidity",e[e.SafetyHumidity=3]="SafetyHumidity",e[e.SetHumidity=4]="SetHumidity"}(pn||(pn={}));class vr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.VibrationSensorState,this.Type="VibrationSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(gn||(gn={}));class yr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BinarySensorState,this.Type="BinarySensorState",this.Data=e.state}}class mr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=fn.Low,this.Time=""}}!function(e){e[e.High=1]="High",e[e.Low=0]="Low"}(fn||(fn={}));class wr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.ConfigurationState,this.Type="ConfigurationState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.OngoingConfiguration=1]="OngoingConfiguration",e[e.NotConfigured=2]="NotConfigured",e[e.Configured=3]="Configured",e[e.PartiallyConfigured=4]="PartiallyConfigured"}(vn||(vn={}));class Sr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BlindOpenCloseTime,this.Type="BlindOpenCloseTimeState",this.Data=e.state}}class Ar extends kn{constructor(e){super(),this.TypeAsEnum=Pt.OvercurrentProtectionState,this.Type="OvercurrentProtectionState",this.Data=e.state}}class _r extends kn{constructor(e){super(),this.TypeAsEnum=Pt.OvercurrentProtectionThreshold,this.Type="OvercurrentProtectionThresholdState",this.Data=e.state}}class Cr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.FacadePosition,this.Type="FacadePositionState",this.Data=e.state}}class Dr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.FacadeType,this.Type="FacadeTypeState",this.Data=e.state}}class Tr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.CurrentWindThreshold,this.Type="CurrentWindThresholdState",this.Data=e.state}}class kr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.WindThreshold=yn.Unknown,this.Time=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded",e[e.Inactive=3]="Inactive"}(yn||(yn={}));class Ir extends kn{constructor(e){super(),this.TypeAsEnum=Pt.CurrentLightThreshold,this.Type="CurrentLightThresholdState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded"}(mn||(mn={}));class Er extends kn{constructor(e){super(),this.TypeAsEnum=Pt.WindSpeedState,this.Type="WindSpeedState",this.Data=e.state}}class br{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Value=0,this.Time=""}}class Gr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.FloodSensorState,this.Type="FloodSensorState",this.Data=e.state}}class Nr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.State=wn.NoFloodDetected,this.Time=""}}!function(e){e[e.FloodDetected=1]="FloodDetected",e[e.NoFloodDetected=0]="NoFloodDetected"}(wn||(wn={})),function(e){e[e.AirHumidity=0]="AirHumidity",e[e.InsideHumidity=1]="InsideHumidity",e[e.OutsideHumidity=2]="OutsideHumidity",e[e.SafetyHumidity=3]="SafetyHumidity",e[e.SetHumidity=4]="SetHumidity"}(Sn||(Sn={}));class Rr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.PressureSensorState,this.Type="PressureSensorState",this.Data=e.state}}class Pr{constructor(){this.Channel=0,this.StateReliability=zt.Unconfident,this.Pressure=0,this.Time="",this.PressureType=An.OutsidePressure}}!function(e){e[e.InsidePressure=0]="InsidePressure",e[e.OutsidePressure=1]="OutsidePressure",e[e.SetPressure=2]="SetPressure"}(An||(An={})),function(e){e[e.Facade90=0]="Facade90",e[e.Facade180=1]="Facade180"}(_n||(_n={}));class Ur extends kn{constructor(e){super(),this.TypeAsEnum=Pt.TamperProtectionState,this.Type="TamperProtection",this.Data=e.state}}!function(e){e[e.OK=0]="OK",e[e.Breach=1]="Breach"}(Cn||(Cn={}));class Or extends kn{constructor(e){super(),this.TypeAsEnum=Pt.LightRGBWState,this.Type="LightRGBW",this.Data=e.state}}class Mr extends kn{constructor(e){super(),this.TypeAsEnum=Pt.BlindErrorState,this.Type="BlindError",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.ObstacleDetected=1]="ObstacleDetected",e[e.MotorFailure=2]="MotorFailure"}(Dn||(Dn={}));class xr{constructor(){this._onDeviceStateChangedEvent=new c,this._onDeviceStateRefreshedOrChangedEvent=new c,this._onDeviceTasksExecutionChangedOnChannelsEvent=new c,this._onDeviceFirmwareVersionChangedEvent=new c,this._iconType=Nt.Unknown,this._serialNumber=null,this._model=null,this._modelGuid=null,this._manufacturerGuid=null,this._isVirtual=!1,this._isEnabled=!1,this._deviceState=Ut.Working,this._deviceType=Mt.Unknown,this._communicationWay=Ot.OneWay,this._availableTasksTypes=[],this._availableResponseTypes=[],this._channels=[],this._protocolGuid=null,this._softwareVersion=null,null==xr._devicesService&&(xr._devicesService=hy.Get(Ys.ServiceName));const e=this._onDeviceStateChangedEvent,t=this._onDeviceTasksExecutionChangedOnChannelsEvent;xr._devicesService.OnDeviceStateChangedEvent().Subscribe((t=>{t.Device.Guid==this._guid&&e.Invoke(t.State)})),xr._devicesService.OnDeviceStateRefreshedOrChangedEvent().Subscribe((e=>{e.Device.Guid==this._guid&&this._onDeviceStateRefreshedOrChangedEvent.Invoke(e.State)})),xr._devicesService.OnDevicesTasksExecutionChangeEvent().Subscribe((e=>{t.Invoke(e.filter((e=>e.DeviceGuid==this._guid)).map((e=>e.Channel)))}))}OnDeviceFirmwareVersionChangedEvent(){return this._onDeviceFirmwareVersionChangedEvent}OnDeviceStateRefreshedOrChangedEvent(){return this._onDeviceStateRefreshedOrChangedEvent}get ShouldChannelsBeGrouped(){if(this._deviceType===Mt.Remote)switch(this._modelGuid){case"afea26ac-d5de-4aa9-8e74-ff69679d097b":case"908a71ec-ca46-4431-9504-05b7801e77f8":case"d8fea502-541e-42d9-8ece-a1bcfaaa93f9":return!1;default:return this._availableTasksTypes.all((e=>e.Type!==Rt.SetBlindPositionSimple))}return!1}get States(){return a.DoesThrowStackTrace?hy.Get(Ys.ServiceName).GetDeviceStates(this).selectMany((e=>e.States)).toArray():xr._devicesService.GetDeviceStates(this).selectMany((e=>e.States)).toArray()}RemoveDeviceAsync(){return xr._devicesService.RemoveDeviceAsync(this)}ExecuteDeviceTaskAsync(e){return xr._devicesService.ExecuteDeviceTaskAsync(this,e)}OnDeviceTasksExecutionChangedOnChannelsEvent(){return this._onDeviceTasksExecutionChangedOnChannelsEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}get Guid(){return null==this._guid?"":this._guid}set Guid(e){this._guid=e}get IconType(){return this._iconType}set IconType(e){this._iconType=e}get Name(){return null==this._name?"":this._name}set Name(e){this._name=e}set SoftwareVersion(e){this._softwareVersion=e}get SoftwareVersion(){return this._softwareVersion}get ChannelsAmount(){return null==this._channelsAmount?0:this._channelsAmount}set ChannelsAmount(e){this._channelsAmount=e}get SerialNumber(){return this._serialNumber}set SerialNumber(e){this._serialNumber=e}get Model(){return this._model}set Model(e){this._model=e}get ModelGuid(){return this._modelGuid}set ModelGuid(e){this._modelGuid=e}get ManufacturerGuid(){return this._manufacturerGuid}set ManufacturerGuid(e){this._manufacturerGuid=e}get IsVirtual(){return this._isVirtual}set IsVirtual(e){this._isVirtual=e}get IsEnabled(){return this._isEnabled}set IsEnabled(e){this._isEnabled=e}get DeviceState(){return this._deviceState}set DeviceState(e){this._deviceState=e}get DeviceType(){return this._deviceType}set DeviceType(e){this._deviceType=e}get CommunicationWay(){return this._communicationWay}set CommunicationWay(e){this._communicationWay=e}get AvailableTaskTypes(){return this._availableTasksTypes}set AvailableTaskTypes(e){this._availableTasksTypes=e}get AvailableResponseTypes(){return this._availableResponseTypes}set AvailableResponseTypes(e){this._availableResponseTypes=e}get Channels(){return this._channels}get ProtocolGuid(){return this._protocolGuid}set ProtocolGuid(e){this._protocolGuid=e}ChangeDeviceNameAsync(e){return t=this,n=void 0,o=function*(){var t;try{const n=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(new Fr(this,e),2e4,!1);switch(n.Status){case ue.OK:return this._name=e,null===(t=u.Log)||void 0===t||t.Error("Device","EXIT CONFIGURATION MODE WILL BE FIRED! ChangeDeviceNameAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),new Ie(we.Changed,"");case ue.WrongData:if("DeviceNotFound"==n.Data)return new Ie(we.Failed,"DeviceNotFound");break;case ue.NoPermissionsToCallGivenResource:return new Ie(we.NoPermissions,"")}}catch(e){return e.message.includes("timeout")?new Ie(we.ControllerResponseTimeout,""):new Ie(we.UnknownError,"")}return new Ie(we.Unknown,"")},new((r=void 0)||(r=Promise))((function(e,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r((function(e){e(n)}))).then(i,a)}c((o=o.apply(t,n||[])).next())}));var t,n,r,o}ExecuteTaskAsync(e){return xr._devicesService.ExecuteDeviceTaskAsync(this,e)}}class Fr extends ce{constructor(e,t){super(),this.Resource="/devices/device/name",this.Method=le.Put;const n=new Lr;n.DeviceGuid=e.Guid,n.Name=t,this.Data=n}}class Lr{constructor(){this.DeviceGuid="",this.Name=""}}var Br,Wr,$r,Vr,qr;class Hr{constructor(){this._device=new xr,this._number=0,this._name="",this._iconName="",this._channelId="",this._mode=bt.Default,this._channelGroups=[],this._isHidden=!1,this._availableTasksTypes=[],this._availableResponseTypes=[],this._customData={},this._roles=[],this._configurations={},this.CustomDataAndRolesSupported=!1,this._onTasksExecutionChangedEvent=new c,this._onChannelStateChangedEvent=new c,this._onChannelStateRefreshedOrChangedEvent=new c,null==Hr._devicesService&&(Hr._devicesService=hy.Get(Ys.ServiceName))}SetCustomDataAsync(e,t){const n=this.GetChannelConfigurationData();if(Array.isArray(e))for(const t of e)n.CustomData[t.dataId]=t.data,this._customData[t.dataId]=t.data;else n.CustomData[e]=t,this._customData[e]=t;const r=new Kr;return r.DeviceGuid=this._device.Guid,r.ChannelConfiguration=n,this.ChangeConfigurationAsync(r)}OnChannelStateChangedEvent(){return this._onChannelStateChangedEvent}OnChannelStateRefreshedOrChangedEvent(){return this._onChannelStateRefreshedOrChangedEvent}get Configurations(){return this._configurations}set Configurations(e){this._configurations=e}IsCustomDataAndRolesSupported(){return this.CustomDataAndRolesSupported}get CustomData(){return this._customData}set CustomData(e){this._customData=e}get Roles(){return this._roles}set Roles(e){this._roles=e}get ChannelId(){return this._channelId}SetDevice(e){this._device=e,this._channelId=`${e.Guid}_${this.Number}`,this._device.OnDeviceStateChangedEvent().Subscribe((e=>{e.Data.Channel==this.Number&&this._onChannelStateChangedEvent.Invoke(e)})),this._device.OnDeviceStateRefreshedOrChangedEvent().Subscribe((e=>{e.Data.Channel==this.Number&&this._onChannelStateRefreshedOrChangedEvent.Invoke(e)}))}GetDevice(){return this._device}RemoveCustomDataAsync(e){const t=this.GetChannelConfigurationData();delete t.CustomData[e],delete this._customData[e];const n=new Kr;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this.ChangeConfigurationAsync(n)}GetChannelConfigurationData(){const e=new jr;return e.Channel=this._number,e.ChannelName=this._name,e.Configuration=this._mode,e.CustomData=this._customData,e.GroupsGuids=this._channelGroups,e.Hidden=this._isHidden,e.IconName=this._iconName,e}HideAsync(){const e=this.GetChannelConfigurationData();this._isHidden=!0,e.Hidden=!0;const t=new Kr;return t.DeviceGuid=this._device.Guid,t.ChannelConfiguration=e,this.ChangeConfigurationAsync(t)}ShowAsync(){const e=this.GetChannelConfigurationData();e.Hidden=!1,this._isHidden=!1;const t=new Kr;return t.DeviceGuid=this._device.Guid,t.ChannelConfiguration=e,this.ChangeConfigurationAsync(t)}ChangeNameAsync(e){const t=this.GetChannelConfigurationData(),n=new Kr;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,t.ChannelName=e,this._name=e,this.ChangeConfigurationAsync(n)}ChangeIconNameAsync(e){const t=this.GetChannelConfigurationData();t.IconName=e;const n=new Kr;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this._iconName=e,this.ChangeConfigurationAsync(n)}ChangeGroupsAsync(e){const t=this.GetChannelConfigurationData();t.GroupsGuids=e;const n=new Kr;return n.DeviceGuid=this._device.Guid,n.ChannelConfiguration=t,this._channelGroups=e,this.ChangeConfigurationAsync(n)}ChangeConfigurationAsync(e){return t=this,n=void 0,o=function*(){var t,n;try{const r=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(new zr(e),2e4,!1);switch(null===(t=u.Log)||void 0===t||t.Error("Device","EXIT CONFIGURATION MODE WILL BE FIRED! ChangeConfigurationAsync()"),yield hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),r.Status){case ue.OK:return this._name=e.ChannelConfiguration.ChannelName,this._iconName=e.ChannelConfiguration.IconName,this._channelGroups=e.ChannelConfiguration.GroupsGuids,this._isHidden=e.ChannelConfiguration.Hidden,this._mode=e.ChannelConfiguration.Configuration,this._customData=e.ChannelConfiguration.CustomData,this._roles=e.ChannelConfiguration.Roles,this._configurations=e.ChannelConfiguration.Configurations,new Ie(we.Changed,"");case ue.WrongData:if("DeviceNotFound"===r.Data)return null===(n=u.Log)||void 0===n||n.Error("Failed to change channel configuration, referenced device does not exist!"),new Ie(we.WrongData,"DeviceNotFound");break;case ue.FatalError:return new Ie(we.UnknownError,"")}}catch(e){if(e.message.includes("timeout"))return new Ie(we.ControllerResponseTimeout,"")}return new Ie(we.Unknown,"")},new((r=void 0)||(r=Promise))((function(e,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r((function(e){e(n)}))).then(i,a)}c((o=o.apply(t,n||[])).next())}));var t,n,r,o}get Number(){return this._number}set Number(e){this._number=e}get Name(){return this._name}set Name(e){this._name=e}get IconName(){return this._iconName}set IconName(e){this._iconName=e}get States(){return a.DoesThrowStackTrace?hy.Get(Ys.ServiceName).GetDeviceStates(this.GetDevice()).where((e=>e.Channel==this.Number)).selectMany((e=>e.States)).toArray():Hr._devicesService.GetDeviceStates(this.GetDevice()).where((e=>e.Channel==this.Number)).selectMany((e=>e.States)).toArray()}get Mode(){return this._mode}set Mode(e){this._mode=e}get ChannelGroups(){return this._channelGroups}set ChannelGroups(e){this._channelGroups=e}get IsHidden(){return this._isHidden}set IsHidden(e){this._isHidden=e}get AvailableTaskTypes(){return this._availableTasksTypes}set AvailableTaskTypes(e){this._availableTasksTypes=e}get AvailableResponseTypes(){return this._availableResponseTypes}set AvailableResponseTypes(e){this._availableResponseTypes=e}OnTasksExecutionChangeEvent(){return this._onTasksExecutionChangedEvent}ExecuteTaskAsync(e){return null!=this._device?(e.Channel=this.Number,e.DeviceGuid=this._device.Guid,Hr._devicesService.ExecuteDeviceTaskAsync(this._device,e)):Promise.resolve(Ft.Failed)}}Hr._devicesService=null;class Kr{constructor(){this.DeviceGuid="",this.ChannelConfiguration=new jr}}class jr{constructor(){this.Channel=0,this.ChannelName="",this.Configuration=bt.Default,this.GroupsGuids=[],this.IconName="",this.Hidden=!1,this.Configurations={},this.CustomData={},this.Roles=[]}}class zr extends ce{constructor(e){super(),this.Resource="/devices/device/channel/configuration",this.Method=le.Put,this.Data=e}}!function(e){e[e.TurnOn=0]="TurnOn",e[e.TurnOff=1]="TurnOff",e[e.ToggleState=2]="ToggleState",e[e.SetBlindPosition=3]="SetBlindPosition",e[e.SetLightColor=4]="SetLightColor",e[e.SetLightTemperature=5]="SetLightTemperature",e[e.SetLightBrightness=6]="SetLightBrightness",e[e.SetTemperature=7]="SetTemperature",e[e.GetState=8]="GetState",e[e.TurnOnWithTimeout=9]="TurnOnWithTimeout",e[e.SetLightBrightnessDynamicly=10]="SetLightBrightnessDynamicly",e[e.IdentifyDevice=11]="IdentifyDevice",e[e.SetBlindOpenCloseTime=12]="SetBlindOpenCloseTime",e[e.SetBlindMicroventilation=13]="SetBlindMicroventilation",e[e.GatewayPulse=25]="GatewayPulse",e[e.GatePulse=26]="GatePulse",e[e.SetFacadePositionAndTilt=29]="SetFacadePositionAndTilt",e[e.GetFacadeType=30]="GetFacadeType",e[e.LightRGBW=31]="LightRGBW",e[e.SetGatePositionPrecise=32]="SetGatePositionPrecise",e[e.SetGatePositionPreciseSecure=33]="SetGatePositionPreciseSecure"}(Br||(Br={}));class Jr{static NewGuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}class Xr{constructor(){this._taskType=Rt.GetChannelsState,this._featureType=Br.GetState,this._channel=0,this._guid=Jr.NewGuid(),this._deviceGuid=""}get TaskType(){return this._taskType}set TaskType(e){this._taskType=e}get FeatureType(){return this._featureType}set FeatureType(e){this._featureType=e}get Guid(){return this._guid}set Guid(e){this._guid=e}get DeviceGuid(){return this._deviceGuid}set DeviceGuid(e){this._deviceGuid=e}get Channel(){return this._channel}set Channel(e){this._channel=e}}class Yr extends Xr{constructor(){super(),this.Temperature=0,this.FeatureType=Br.SetTemperature,this.TaskType=Rt.SetTemperature}}class Qr extends Xr{constructor(){super(),this.FeatureType=Br.TurnOff,this.TaskType=Rt.TurnOff}}class Zr extends Xr{constructor(){super(),this.FeatureType=Br.TurnOn,this.TaskType=Rt.TurnOn}}class eo extends Xr{constructor(){super(),this.SwitchOffDelaySeconds=0,this.FeatureType=Br.TurnOnWithTimeout,this.TaskType=Rt.TurnOnWithTime}}class to extends Xr{constructor(){super(),this.Brightness=0,this.FeatureType=Br.SetLightBrightness,this.TaskType=Rt.SetLightBrightness}}class no extends Xr{constructor(){super(),this.FeatureType=Br.ToggleState,this.TaskType=Rt.TogleState}}class ro extends Xr{constructor(){super(),this.R=0,this.G=0,this.B=0,this.FeatureType=Br.SetLightColor,this.TaskType=Rt.SetLightColor}}class oo extends Xr{constructor(){super(),this.Temperature=0,this.FeatureType=Br.SetLightTemperature,this.TaskType=Rt.SetLightTemperature}}class so extends Xr{constructor(){super(),this.Action=Wr.Stop,this.Position=0,this.FeatureType=Br.SetBlindPosition,this.TaskType=Rt.SetBlindPosition}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(Wr||(Wr={}));class io extends Xr{constructor(){super(),this.GateControlAction=$r.Stop,this.Position=0,this.FeatureType=Br.SetGatePositionPrecise,this.TaskType=Rt.PreciseGateControl}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}($r||($r={}));class ao extends Xr{constructor(){super(),this.Action=Vr.Stop,this.Position=0,this.FeatureType=Br.SetBlindPosition,this.TaskType=Rt.SetBlindPositionSimple}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop"}(Vr||(Vr={}));class co extends Xr{constructor(){super(),this.Brightness=0,this.FeatureType=Br.SetLightBrightnessDynamicly,this.TaskType=Rt.SetLightBrightnessDynamicly}}class uo extends Xr{constructor(){super(),this.FeatureType=Br.IdentifyDevice,this.TaskType=Rt.IdentifyDevice}}class lo extends Xr{constructor(){super(),this.Data=new ho,this.FeatureType=Br.SetBlindOpenCloseTime,this.TaskType=Rt.SetBlindOpenCloseTime}}class ho{constructor(){this.Channel=0,this.CloseTime=0,this.OpenTime=0}}class po extends Xr{constructor(){super(),this.FeatureType=Br.GetState,this.TaskType=Rt.GetChannelsState}}class go extends Xr{constructor(){super(),this.Position=0,this.FeatureType=Br.SetBlindMicroventilation,this.TaskType=Rt.SetBlindMicroventilation}}class fo extends Xr{constructor(){super(),this.FeatureType=Br.GatePulse,this.TaskType=Rt.ChangeGatewayPositionPulse}}class vo extends Xr{constructor(){super(),this.FeatureType=Br.GatewayPulse,this.TaskType=Rt.ChangeGatewayPositionPulse}}class yo extends Xr{constructor(){super(),this.FacadeAction=qr.Stop,this.Tilt=0,this.Position=0,this.FeatureType=Br.SetFacadePositionAndTilt,this.TaskType=Rt.SetFacadePosition}}class mo extends Xr{constructor(){super(),this.FeatureType=Br.GetFacadeType,this.TaskType=Rt.GetFacadeType}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage",e[e.Tilt=4]="Tilt",e[e.TiltAndPercentage=5]="TiltAndPercentage"}(qr||(qr={}));class wo{constructor(){this.R=0,this.G=0,this.B=0,this.W=0,this.Brightness=0,this.Channel=0}}class So extends Xr{constructor(){super(),this.Data=new wo,this.FeatureType=Br.LightRGBW,this.TaskType=Rt.LightRGBW}}var Ao=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class _o{constructor(){this._manualDeviceProtocolServices=new Map}GetServiceName(){return _o.ServiceName}RegisterManuallyPairedDevicesProtocol(e){var t;null===(t=u.Log)||void 0===t||t.Debug(_o.ServiceName,`Registering new manual device protocol service: ${e.GetServiceName()}`),this._manualDeviceProtocolServices.set(e.GetServiceName(),e)}GetDevicesForManualPairingAsync(e){return Ao(this,void 0,void 0,(function*(){const t=[...this._manualDeviceProtocolServices.values()],n=[];if(null!=e)if(Array.isArray(e))for(let r=0;r<t.length;r++)e.any((e=>e==t[r].ProtocolExtensionGuid))&&n.push(...yield t[r].GetDevicesForManualPairingAsync());else{const r=t.find((t=>t.ProtocolExtensionGuid==e));null!=r&&n.push(...yield r.GetDevicesForManualPairingAsync())}else for(let e=0;e<t.length;e++)n.push(...yield t[e].GetDevicesForManualPairingAsync());return n}))}AddManuallyPairedDeviceAsync(e){return Ao(this,void 0,void 0,(function*(){var t;const n=[...this._manualDeviceProtocolServices.values()].find((t=>t.ProtocolExtensionGuid==e.ProtocolExtensionGuid));return null!=n?n.AddManuallyPairedDeviceAsync(e):(null===(t=u.Log)||void 0===t||t.Error(_o.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! AddManuallyPairedDeviceAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),Ft.Failed)}))}GetRegisteredProtocolGuids(){return[...this._manualDeviceProtocolServices.values()].map((e=>e.ProtocolExtensionGuid))}}_o.ServiceName="ManualDeviceService";class Co{constructor(){this.ResourceGuid="",this.Data=null,this.IsGlobal=!1,this.InsertTime=new Date}}var Do,To=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class ko{constructor(){this._connection=null,this._localDb=null,this._connection=hy.Get(It.ServiceName),this._localDb=hy.Get(l.ServiceName)}GetLocalDbName(e,t){return`${e}_${t}`}SaveAsync(e,t,n){return To(this,void 0,void 0,(function*(){try{let r=new Io(e,t,n),o=yield this._connection.SendAndWaitForResponseAsync(r,35e3,!1);if(o.Status===ue.OK){const r=new Go;r.ResourceGuid=e,r.Data=JSON.stringify(n),r.IsGlobal=t,this._localDb.Save(ko.ServiceName,this.GetLocalDbName(e,t),r)}return o.Status}catch(e){return ue.FatalError}}))}ReadAsync(e,t,n){return To(this,void 0,void 0,(function*(){try{let r=new Eo(e,t);if(!n){const n=this._localDb.Read(ko.ServiceName,this.GetLocalDbName(e,t));if(null!=n){const e=n,t=new Co;return t.Data=JSON.parse(e.Data),t.IsGlobal=e.IsGlobal,t.ResourceGuid=e.ResourceGuid,t}}let o=yield this._connection.SendAndWaitForResponseAsync(r,35e3,!1);if(o.Status===ue.OK){const e=new Co;return e.ResourceGuid=o.ResourceGuid,e.Data=JSON.parse(o.Data),e.IsGlobal=o.IsGlobal,e}return o.Status}catch(e){return ue.FatalError}}))}RemoveAsync(e,t){return To(this,void 0,void 0,(function*(){try{let n=new bo(e,t);return(yield this._connection.SendAndWaitForResponseAsync(n,35e3,!1)).Status}catch(e){return ue.FatalError}}))}GetServiceName(){return ko.ServiceName}}ko.ServiceName="RemoteStorageService";class Io extends ce{constructor(e,t,n){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=le.Put,this.ResourceGuid=e,this.Global=t,this.Data=JSON.stringify(n)}}class Eo extends ce{constructor(e,t){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=le.Get,this.ResourceGuid=e,this.Global=t}}class bo extends ce{constructor(e,t){super(),this.ResourceGuid="",this.Global=!1,this.Resource="/sync/config/",this.Method=le.Delete,this.ResourceGuid=e,this.Global=t}}class Go extends ce{constructor(){super(...arguments),this.ResourceGuid="",this.Data="",this.IsGlobal=!1,this.InsertTime=new Date}}class No{constructor(){this.Longitude=0,this.Latitude=0}}class Ro{constructor(){this.Longitude=0,this.Latitude=0,this.IsNetworkBased=!1}}!function(e){e[e.OK=0]="OK",e[e.NoPermissions=1]="NoPermissions",e[e.UserIsNotLoggedIn=2]="UserIsNotLoggedIn",e[e.UnknownError=3]="UnknownError"}(Do||(Do={}));var Po,Uo,Oo=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Mo{IsControllerGeolocationSetAsync(){return Oo(this,void 0,void 0,(function*(){let e=new xo,t=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(e,15e3,!0);return(null==t?void 0:t.Status)===ue.OK?null==t?void 0:t.Data:null==t?void 0:t.Status}))}GetCurrentGeolocationAsync(){return Oo(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Oo(this,void 0,void 0,(function*(){window.navigator.geolocation.getCurrentPosition((t=>{e(t)}),(t=>{e(t)}))}))))}))}SetControllerGeolocationAsync(e){return Oo(this,void 0,void 0,(function*(){var t,n,r;let o=new Lo;o.Data.Latitude=e.Latitude,o.Data.Longitude=e.Longitude,null===(t=u.Log)||void 0===t||t.Warning(Mo.ServiceName,`SetControllerGeolocationAsync() ${JSON.stringify(o)}`);let s=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(o,15e3,!1);switch(null===(n=u.Log)||void 0===n||n.Warning(Mo.ServiceName,`${JSON.stringify(s)}`),null===(r=u.Log)||void 0===r||r.Error(Mo.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! SetControllerGeolocationAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),null==s?void 0:s.Status){case ue.OK:const e=hy.Get(Be.ServiceName);return e.Remove(new xo),e.Remove(new Fo),new Ee(Do.OK,"");case ue.NoPermissionToPerformThisOperation:case ue.NoPermissionsToCallGivenResource:return new Ee(Do.NoPermissions,"");case ue.UserIsNotLoggedIn:return new Ee(Do.UserIsNotLoggedIn,"");default:return new Ee(Do.UnknownError,"")}}))}GetControlllerGeolocationAsync(){return Oo(this,void 0,void 0,(function*(){var e,t;let n=new Fo;null===(e=u.Log)||void 0===e||e.Warning(Mo.ServiceName,`GetControlllerGeolocationAsync(): ${JSON.stringify(n)}`);let r=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(n,15e3,!0);if(null===(t=u.Log)||void 0===t||t.Warning(Mo.ServiceName,`${JSON.stringify(r)}`),(null==r?void 0:r.Status)===ue.OK){let e=new Ro;return e.IsNetworkBased=(null==r?void 0:r.Data).IsNetworkBased,e.Latitude=(null==r?void 0:r.Data).Latitude,e.Longitude=(null==r?void 0:r.Data).Longitude,e}return null==r?void 0:r.Status}))}GetServiceName(){return Mo.ServiceName}}Mo.ServiceName="GeolocationService";class xo extends ce{constructor(){super(),this.Resource="/geolocation/isset",this.Method=le.Get}}class Fo extends ce{constructor(){super(),this.Resource="/geolocation/get",this.Method=le.Get}}class Lo extends ce{constructor(){super(),this.Data=new No,this.Resource="/geolocation/save",this.Method=le.Put}}!function(e){e[e.Device=0]="Device",e[e.Controller=1]="Controller"}(Po||(Po={}));class Bo{constructor(){this.UpdateGuid="",this.Channel="",this.Version="",this.CurrentVersion="",this.DownloadUri="",this.Download="",this.Name="",this.Description="",this.UpdateType=Uo.Unknown,this.ResourceGuid=""}}class Wo{constructor(){this.UpdateDescription=new Map,this.Update=new Bo,this.UpdatedResourceName="",this.CurrentResourceVersion=""}}!function(e){e[e.Unknown=0]="Unknown",e[e.Container=1]="Container",e[e.RadioFirmware=2]="RadioFirmware",e[e.DeviceFirmware=3]="DeviceFirmware",e[e.Configuration=4]="Configuration",e[e.ContainerScript=5]="ContainerScript",e[e.ContainerSoftware=6]="ContainerSoftware",e[e.RuntimeSoftware=7]="RuntimeSoftware",e[e.RuntimeScript=8]="RuntimeScript",e[e.RuntimeFixingScript=9]="RuntimeFixingScript"}(Uo||(Uo={}));class $o extends Error{constructor(e){super(e),this.message=e,this.name="UpdateProviderNotFound"}}var Vo,qo,Ho,Ko,jo,zo,Jo,Xo,Yo,Qo,Zo,es,ts,ns,rs,os,ss,is,as=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class cs{constructor(){this._services=new Map,this._runtimeInfo=new us,this._hardwareInfo=new ds,this._semaphore=new et(1),this._isRuntimeInfoInitialized=!1,this._isHardwareInfoInitialized=!1}GetServiceName(){return cs.ServiceName}RegisterUpdatesProvider(e){var t;null===(t=u.Log)||void 0===t||t.Debug(cs.ServiceName,`Registering new update provider: ${e.GetUpdateProviderName()}`),this._services.set(e.GetUpdateProviderName(),e)}GetUpdatesProviderAsync(e){return as(this,void 0,void 0,(function*(){var t;null===(t=u.Log)||void 0===t||t.Debug(cs.ServiceName,`Getting update provider [${e}] by GetUpdateProviderAsync<T>()`);const n=this._services.get(e);if(null==n)throw new $o("Cannot get update provider! Requested update provider has not been registered.");return n}))}GetUpdatesProvidersAsync(e){return as(this,void 0,void 0,(function*(){var t;null===(t=u.Log)||void 0===t||t.Debug(cs.ServiceName,`Getting update providers with type ${e} by GetUpdateProvidersAsync<T>()`);let n=[];if(n=[...this._services.values()].filter((t=>t.ProviderType==e)),0==n.length)throw new $o("Cannot get update providers! Requested update providers has not been registered.");return n}))}GetUpdatesProvidersByProtocolAsync(e,t,n){return as(this,void 0,void 0,(function*(){var r;if(new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)){null===(r=u.Log)||void 0===r||r.Debug(cs.ServiceName,`Getting update providers with protocol guid: [${e}] by GetUpdateProvidersByProtocolAsync<T>()`);let o=[];if(o=null!=n?[...this._services.values()].filter((r=>r.ProtocolGuid==e&&r.ProviderType==t&&r.AvailableExtensionVersion==n)):[...this._services.values()].filter((n=>n.ProtocolGuid==e&&n.ProviderType==t)),0==o.length)throw new $o("Cannot get update providers! Requested update providers has not been registered.");return o}throw new $o("Cannot get update providers! Bad parameters.")}))}GetUpdatesProvidersByExtensionAsync(e,t,n){return as(this,void 0,void 0,(function*(){var r;if(new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)){null===(r=u.Log)||void 0===r||r.Debug(cs.ServiceName,`Getting update providers with extension guid: [${e}] by GetUpdateProvidersByExtensionAsync<T>()`);let o=[];if(o=null!=n?[...this._services.values()].filter((r=>r.ExtensionGuid==e&&r.ProviderType==t&&r.AvailableExtensionVersion==n)):[...this._services.values()].filter((n=>n.ExtensionGuid==e&&n.ProviderType==t)),0==o.length)throw new $o("Cannot get update providers! Requested update providers has not been registered.");return o}throw new $o("Cannot get update providers! Bad parameters.")}))}GetSoftwareRuntimeInfoAsync(){return as(this,arguments,void 0,(function*(e=!1){var t=yield this._semaphore.AcquireAsync();try{return this._isRuntimeInfoInitialized&&!e||(yield this.GetRuntimeControllerInfoAsync()),this._runtimeInfo}finally{t.Release()}}))}GetRuntimeControllerInfoAsync(){return as(this,void 0,void 0,(function*(){var e;null===(e=u.Log)||void 0===e||e.Debug(cs.ServiceName,"Getting runtime version info from controller.");try{const e=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(new ls,16e3,!1);if(null==e||null==e.Status)throw new ps('Cannot get runtime info, controller response result is empty."',Vo.EmptyResponse);if(e.Status!=ue.OK)throw new ps(`Cannot get runtime info, controller responded with status ${e.Status}.`,Vo.WrongResponseStatus);if(null==e.Data)throw new ps("Cannot get runtime info, controller responded with status OK but response does not contains data.",Vo.NoDataInResponse);this._runtimeInfo=e.Data,this._isRuntimeInfoInitialized=!0}catch(e){throw e instanceof I?new ps("Cannot get runtime info, controller response timeout.",Vo.Timeout):e}}))}GetHardwareInfoAsync(){return as(this,arguments,void 0,(function*(e=!1){return!this._isHardwareInfoInitialized||e?(yield this.GetHardwareControllerInfoAsync(),this._hardwareInfo):this._hardwareInfo}))}GetHardwareControllerInfoAsync(){return as(this,void 0,void 0,(function*(){var e;null===(e=u.Log)||void 0===e||e.Debug(cs.ServiceName,"Getting hardware info from controller.");const t=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(new hs,8e3,!1);if(null==t||null==t.Status)throw new ps('Cannot get hardware info, controller response result is empty."',Vo.EmptyResponse);if(t.Status!=ue.OK)throw new ps(`Cannot get hardware info, controller responded with status ${t.Status}.`,Vo.WrongResponseStatus);if(null==t.Data)throw new ps("Cannot get hardware info, controller responded with status OK but response does not contains data.",Vo.NoDataInResponse);this._hardwareInfo=t.Data,this._isHardwareInfoInitialized=!0}))}}cs.ServiceName="UpdateProvider";class us{constructor(){this.BaseLinuxVersion="",this.BaseMonoVersion="",this.RuntimeVersion="",this.UpdateChannel="",this.SoftwareVersion=""}}class ls extends ce{constructor(){super(),this.Resource="/controller/software/info",this.Method=le.Get}}class ds{constructor(){this.GetControllerHardwareVersion=0,this.DevicePIN="",this.GetControllerSerialNumber="",this.HostnamePrefix="",this.DefaultStaticIpAddress="",this.GetAvailableHardware=[],this.ControllerSecret=""}}class hs extends ce{constructor(){super(),this.Resource="/controller/hardware/info",this.Method=le.Get}}class ps extends Error{constructor(e,t){super(e),this.message=e,this.code=0,this.name="CannotGetRuntimeInfo",this.code=t}}!function(e){e[e.Unknown=0]="Unknown",e[e.EmptyResponse=1]="EmptyResponse",e[e.NoDataInResponse=2]="NoDataInResponse",e[e.WrongResponseStatus=3]="WrongResponseStatus",e[e.Timeout=4]="Timeout"}(Vo||(Vo={})),function(e){e.OtherError="OtherError",e.FatalError="FatalError",e.NoData="NoData",e.InvalidSceneGuid="InvalidSceneGuid"}(qo||(qo={}));class gs{constructor(){this._comparisonParams=new Map,this.Type=Pt.Unknown,this.DeviceGuid="",this.ComparisonMethod=Ho.Default}GetCheckDeviceState(){return this._checkDeviceState}SetCheckDeviceState(e){this._checkDeviceState=e,e instanceof Xn&&(this.Type=Pt.BatteryState),e instanceof mr&&(this.Type=Pt.BinarySensorState),e instanceof Fn&&(this.Type=Pt.BlindPosition),e instanceof Kn&&(this.Type=Pt.LightBrightness),e instanceof Qn&&(this.Type=Pt.MeasuredBrightness),e instanceof Bn&&(this.Type=Pt.RemoteButtonState),e instanceof En&&(this.Type=Pt.ChannelOnOffState),e instanceof Un&&(this.Type=Pt.DoorBellState),e instanceof er&&(this.Type=Pt.MeasuredEnergy),e instanceof Nr&&(this.Type=Pt.FloodSensorState),e instanceof lr&&(this.Type=Pt.GatePosition),e instanceof $n&&(this.Type=Pt.LightColor),e instanceof qn&&(this.Type=Pt.LightWarmth),e instanceof Mn&&(this.Type=Pt.ReedState),e instanceof zn&&(this.Type=Pt.MeasuredTemperature),e instanceof fr&&(this.Type=Pt.HumiditySensorState),e instanceof sr&&(this.Type=Pt.BlindRemoteButtonState),e instanceof ar&&(this.Type=Pt.FacadeRemoteButtonState),e instanceof rr&&(this.Type=Pt.MovementSensorState),e instanceof er&&(this.Type=Pt.MeasuredEnergy),e instanceof Pr&&(this.Type=Pt.PressureSensorState),e instanceof br&&(this.Type=Pt.WindSpeedState),e instanceof kr&&(this.Type=Pt.CurrentWindThreshold)}GetComparisonParam(e){return this._comparisonParams.get(e)}GetComparisonParams(){return this._comparisonParams}SetComparisonParam(e,t){this._comparisonParams.set(e,t)}}class fs{constructor(e){this._value=e}get Value(){return this._value}set Value(e){this._value=e}}class vs{constructor(...e){this._value="00:00:00",e.length>1?this.SetTimeSpan(e[0],e[1],e[2],e[3]):this._value=e[0]}SetTimeSpan(e,t,n,r){this._value=r<=0?`${n.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`:`${r}.${n.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}get Value(){return this._value}}!function(e){e[e.Default=0]="Default",e[e.Delta=1]="Delta",e[e.StateRepeat=2]="StateRepeat"}(Ho||(Ho={})),function(e){e[e.DeltaValue=0]="DeltaValue",e[e.DeltaCalculationTimeRange=1]="DeltaCalculationTimeRange",e[e.StateRepeatCount=2]="StateRepeatCount",e[e.StateRepeatTimeRange=3]="StateRepeatTimeRange"}(Ko||(Ko={})),function(e){e[e.SunRise=1]="SunRise",e[e.SunSet=2]="SunSet"}(jo||(jo={}));class ys{constructor(){this.DeviceGuid=""}}!function(e){e[e.Unknown=-1]="Unknown",e[e.DeviceTask=0]="DeviceTask",e[e.DelayTask=1]="DelayTask",e[e.NotifyTask=2]="NotifyTask",e[e.LockExecution=3]="LockExecution"}(zo||(zo={})),function(e){e.Unknown="Unknown",e.DeviceTask="DeviceTask",e.DelayTask="DelayTask",e.NotifyTask="NotifyTask",e.LockExecution="LockExecution"}(Jo||(Jo={})),(is=Xo||(Xo={}))[is.Unknown=0]="Unknown",is[is.Second=1]="Second",is[is.Minute=2]="Minute",is[is.Hour=3]="Hour",is[is.Day=4]="Day",is[is.DayOfWeek=5]="DayOfWeek",is[is.Month=6]="Month",is[is.Year=7]="Year",is[is.Date=8]="Date",is[is.Time=9]="Time",is[is.WeatherType=11]="WeatherType",is[is.CompareNumbers=12]="CompareNumbers",is[is.CompareBooleans=13]="CompareBooleans",is[is.DeviceState=14]="DeviceState",is[is.Timer=15]="Timer",is[is.Temperature=17]="Temperature",is[is.DaysOfWeek=18]="DaysOfWeek",is[is.AstronomicalClockWithOffset=19]="AstronomicalClockWithOffset",is[is.SceneExecuted=20]="SceneExecuted",(ss=Yo||(Yo={}))[ss.Unknown=0]="Unknown",ss[ss.Equal=1]="Equal",ss[ss.NotEqueal=2]="NotEqueal",ss[ss.BiggerThan=3]="BiggerThan",ss[ss.SmallerThan=4]="SmallerThan",ss[ss.BiggerThanOrEqual=5]="BiggerThanOrEqual",ss[ss.SmallerThanOrEqual=6]="SmallerThanOrEqual",ss[ss.OneOfBothIsTrue=7]="OneOfBothIsTrue",ss[ss.BothAreTrue=8]="BothAreTrue",function(e){e[e.Unknown=0]="Unknown",e[e.BatteryState=1]="BatteryState",e[e.BinarySensor=2]="BinarySensor",e[e.BlindPosition=3]="BlindPosition",e[e.Brightness=4]="Brightness",e[e.ButtonState=5]="ButtonState",e[e.ChannelOnOff=6]="ChannelOnOff",e[e.DoorBell=7]="DoorBell",e[e.Energy=8]="Energy",e[e.FloodSensor=9]="FloodSensor",e[e.GatePosition=10]="GatePosition",e[e.HeatSensor=11]="HeatSensor",e[e.LightBrightness=12]="LightBrightness",e[e.LightColor=13]="LightColor",e[e.LightTemperature=14]="LightTemperature",e[e.MeasuredCurrent=15]="MeasuredCurrent",e[e.MeasuredPower=16]="MeasuredPower",e[e.MeasuredVoltage=17]="MeasuredVoltage",e[e.ReedState=18]="ReedState",e[e.SmokeSensor=19]="SmokeSensor",e[e.Temperature=20]="Temperature",e[e.BlindsControlButton=21]="BlindsControlButton",e[e.Movement=22]="Movement",e[e.WindSpeed=24]="WindSpeed",e[e.Humidity=25]="Humidity",e[e.AirPressure=26]="AirPressure",e[e.WindThreshold=31]="WindThreshold",e[e.FacadeControlButton=36]="FacadeControlButton"}(Qo||(Qo={})),function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(Zo||(Zo={})),(os=es||(es={})).Null="Null",os.Condition="Condition",os.ConditionGroup="ConditionGroup",os.ArgumentAsInt="ArgumentAsInt",os.ArgumentAsTimeSpan="ArgumentAsTimeSpan",os.ArgumentAsBoolean="ArgumentAsBoolean",os.ArgumentAsTimeout="ArgumentAsTimeout",os.ArgumentAsDayOfWeek="ArgumentAsDayOfWeek",os.ArgumentAsDaysOfWeek="ArgumentAsDaysOfWeek",os.ArgumentAsAstronomicalClock="ArgumentAsAstronomicalClock",os.ArgumentAsTime="ArgumentAsTime",os.ArgumentAsDeviceState="ArgumentAsDeviceState",os.ArgumentAsNumber="ArgumentAsNumber",os.ArgumentAsAstronomicalClockWithOffset="ArgumentAsAstronomicalClockWithOffset",os.ArgumentAsConditionInfo="ArgumentAsConditionInfo",function(e){e.DeviceTask="DeviceTask",e.DelayTask="DelayTask",e.LockExecutionTask="LockExecutionTask",e.NotifyTaskAppNotify="NotifyTaskAppNotify",e.NotifyTaskEmailNotify="NotifyTaskEmailNotify"}(ts||(ts={}));class ms extends Error{constructor(e){super(e),this.message=e,this.name="UnsupportedScenesDeviceState"}}!function(e){e[e.None=0]="None",e[e.AppNotification=1]="AppNotification",e[e.Email=2]="Email"}(ns||(ns={})),function(e){e[e.Timeout=0]="Timeout",e[e.TimeRange=1]="TimeRange"}(rs||(rs={}));var ws,Ss,As;class _s{constructor(e,t="Cube"){this._result=null,this._tmp=new Cs,this._tmpTask=null,this._prevSeqGuid="",this._currentSeqGuid="",this._editingExistingSequence=!1,this._rawExistingSequenceTasks=null,this._sequenceName="",this._sequenceIcon="",this._service=hy.Get(Ls.ServiceName),e&&(this._sequenceName=e,this._sequenceIcon=t,this._tmp.Guid=Jr.NewGuid())}SetSequenceName(e){const t=n=>{if(n.RightArgumentType!=As.Null)return t(n.RightArgument);n.Tasks.ControllerTasks.where((e=>e.TaskType==zo.NotifyTask)).toArray().forEach((t=>{t.Title=e}))};this._sequenceName=e,this._editingExistingSequence&&null!=this._result&&(this._result.Name=e,t(this._result))}SetSequenceIcon(e){this._sequenceIcon=e,this._editingExistingSequence&&null!=this._result&&(this._result.Icon=e)}GetNext(){if(null==this._result)return null;if(""==this._currentSeqGuid)return this._currentSeqGuid=this._result.Guid,this._service.MapSequence(JSON.parse(JSON.stringify(this._result)),!0);{const e=this.FindArgumentWithGuid(this._result,this._currentSeqGuid);return null==e?null:e.RightArgumentType==As.Condition?(this._prevSeqGuid=this._currentSeqGuid,this._currentSeqGuid=e.RightArgument.Guid,this._service.MapSequence(JSON.parse(JSON.stringify(e.RightArgument)),!0)):null}}CloneCurrentBuilder(){var e=new _s;return e._currentSeqGuid="",e._prevSeqGuid="",e._editingExistingSequence=structuredClone(this._editingExistingSequence),e._rawExistingSequenceTasks=structuredClone(this._rawExistingSequenceTasks),e._result=structuredClone(this._result),e._sequenceIcon=structuredClone(this._sequenceIcon),e._sequenceName=structuredClone(this._sequenceName),e._tmp=structuredClone(this._tmp),(e=>{const t=e=>{e.Guid=Jr.NewGuid(),e.RightArgumentType==As.Condition&&t(e.RightArgument)};null!=e._result&&t(e._result),null!=this._tmp&&(this._tmp.Guid=Jr.NewGuid())})(e),e}GetPrevious(){let e="";const t=(n,r)=>n.Guid==r?{sequence:n,prevGuid:e}:n.RightArgumentType==As.Condition?(e=n.Guid,t(n.RightArgument,r)):null;if(null==this._result)return null;if(""==this._currentSeqGuid||""==this._prevSeqGuid)return null;const n=t(this._result,this._prevSeqGuid);return null==n?null:(this._currentSeqGuid=n.sequence.Guid,this._prevSeqGuid=n.prevGuid,this._service.MapSequence(JSON.parse(JSON.stringify(n.sequence)),!0))}GetByGuid(e){if(null==this._result)return null;const t=this.FindArgumentWithGuid(this._result,e);return null==t?null:this._service.MapSequence(t)}EditCurrentSequence(e){const t=e=>{if(e.RightArgumentType!=As.Null)return t(e.RightArgument);this._rawExistingSequenceTasks=JSON.parse(JSON.stringify(e.Tasks))};return this._editingExistingSequence=!0,t(e._rawRequestData),Object.hasOwn(e._rawRequestData,"Condition")?this._result=e._rawRequestData.Condition:this._result=e._rawRequestData,{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequence:e=>this.RemoveSequenceByGuid(e),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,r=Yo.Equal)=>this.ArgumentAsDeviceState(e,t,n,r),ArgumentAsTime:(e,t,n=Yo.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),RemoveTask:e=>this.RemoveTask(e)}}ArgumentAsAstronomicalClockWithOffset(e,t,n){if(this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.AstronomicalClockWithOffset,this._tmp.LeftArgumentType=As.ArgumentAsAstronomicalClockWithOffset,this._tmp.AtMeetCondition=t,e.Offset<-3600||e.Offset>3600)throw new Ps("Offset must be in range between -3600 and 3600 seconds.");if(t)this._tmp.ConditionType=Yo.Equal;else{if(t||null==n)throw new Ps("Comparasion type must be provided if atMeetCondition is false!");this._tmp.ConditionType=n}return this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=As.ArgumentAsAstronomicalClockWithOffset,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsActionWithEmptyCondition(){return this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.Unknown,this._tmp.LeftArgumentType=As.Null,this._tmp.ConditionType=Yo.Equal,this._tmp.LeftArgument.Argument=null,this._tmp.LeftArgument.HandledType=As.Null,this._tmp.Name=this._sequenceName,this._tmp.Icon=this._sequenceIcon,this._tmp.AtMeetCondition=!1,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsDaysOfWeek(e,t,n=Yo.Equal){return this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.DaysOfWeek,this._tmp.LeftArgumentType=As.ArgumentAsDaysOfWeek,this._tmp.ConditionType=n,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=As.ArgumentAsDaysOfWeek,this._tmp.AtMeetCondition=t,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsTimeSpan(e,t=Yo.Equal){return this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.Timer,this._tmp.LeftArgumentType=As.ArgumentAsTimeSpan,this._tmp.ConditionType=t,this._tmp.AtMeetCondition=!0,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=As.ArgumentAsTimeSpan,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsTime(e,t,n=Yo.Equal){return this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.Time,this._tmp.LeftArgumentType=As.ArgumentAsTime,this._tmp.ConditionType=n,this._tmp.AtMeetCondition=t,this._tmp.LeftArgument.Argument=e,this._tmp.LeftArgument.HandledType=As.ArgumentAsTime,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsDeviceState(e,t,n,r=Yo.Equal){return this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.DeviceState,this._tmp.LeftArgumentType=As.ArgumentAsDeviceState,this._tmp.ConditionType=r,this._tmp.AtMeetCondition=t,this._tmp.ConditionTimeout=n,this._tmp.LeftArgument.Argument=this.GenerateDeviceStateArgument(e),this._tmp.LeftArgument.HandledType=As.ArgumentAsDeviceState,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}ArgumentAsSceneExecuted(e){this._tmp.Guid=Jr.NewGuid(),this._tmp.HandledType=Xo.SceneExecuted,this._tmp.LeftArgumentType=As.ArgumentAsConditionInfo,this._tmp.ConditionType=Yo.Equal,this._tmp.AtMeetCondition=!0;const t=new ys;return t.DeviceGuid=e.DeviceGuid,this._tmp.LeftArgument.Argument=t,this._tmp.LeftArgument.HandledType=As.ArgumentAsConditionInfo,{AddArgument:()=>this.AddSequence(),EditArgument:e=>this.EditSequence(e)}}GenerateDeviceStateArgument(e){const t=new ks;t.Channel=e.GetCheckDeviceState().Channel,t.ComparisonMethod=e.ComparisonMethod;let n={},r=e.GetComparisonParams().entries();for(const[e,t]of r)n=Object.assign(Object.assign({},n),{[Ko[e]]:t.Value});switch(t.ComparisonParams=n,t.DeviceGuid=e.DeviceGuid,t.DeviceStateType=this.MapResponseTypeToDeviceStateType(e.Type),e.Type){case Pt.BatteryState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State,t.CheckedDeviceState.Percentage=e.GetCheckDeviceState().Percentage;break;case Pt.BinarySensorState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case Pt.BlindPosition:t.CheckedDeviceState.Position=e.GetCheckDeviceState().Position;break;case Pt.LightBrightness:case Pt.MeasuredBrightness:t.CheckedDeviceState.Brightness=e.GetCheckDeviceState().Brightness;break;case Pt.RemoteButtonState:case Pt.ChannelOnOffState:case Pt.DoorBellState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case Pt.MeasuredEnergy:{let n={},r=e.GetCheckDeviceState().MeasurementParameters.entries();for(const[e,t]of r)n=Object.assign(Object.assign({},n),{[nn[e]]:t});t.CheckedDeviceState.MeasurementParameters=n;break}case Pt.FloodSensorState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case Pt.GatePosition:t.CheckedDeviceState.Position=e.GetCheckDeviceState().Position,t.CheckedDeviceState.PositionType=e.GetCheckDeviceState().PositionType;break;case Pt.LightColor:{const n=e.GetCheckDeviceState();t.CheckedDeviceState.R=n.R,t.CheckedDeviceState.G=n.G,t.CheckedDeviceState.B=n.B;break}case Pt.LightWarmth:t.CheckedDeviceState.Temperature=e.GetCheckDeviceState().Temperature;break;case Pt.ReedState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case Pt.SmokeSensorState:throw new ms("Unsupported device state!");case Pt.MeasuredTemperature:t.CheckedDeviceState.Temperature=e.GetCheckDeviceState().Temperature;break;case Pt.HumiditySensorState:t.CheckedDeviceState.Humidity=e.GetCheckDeviceState().Humidity;break;case Pt.BlindRemoteButtonState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case Pt.LightRGBWState:{let n=e.GetCheckDeviceState();t.CheckedDeviceState.R=n.R,t.CheckedDeviceState.G=n.G,t.CheckedDeviceState.B=n.B,t.CheckedDeviceState.W=n.W;break}case Pt.FacadeRemoteButtonState:t.CheckedDeviceState.State=e.GetCheckDeviceState().State;break;case Pt.MovementSensorState:{let n=e.GetCheckDeviceState();t.CheckedDeviceState.Movement=n.Movement,t.CheckedDeviceState.Intensity=n.Intensity;break}case Pt.PressureSensorState:t.CheckedDeviceState.Pressure=e.GetCheckDeviceState().Pressure,t.CheckedDeviceState.PressureType=e.GetCheckDeviceState().PressureType;break;case Pt.WindSpeedState:t.CheckedDeviceState.Value=e.GetCheckDeviceState().Value;break;case Pt.CurrentWindThreshold:t.CheckedDeviceState.WindThreshold=e.GetCheckDeviceState().WindThreshold;break;case Pt.Unknown:t.CheckedDeviceState={};break;default:throw new ms("Unsupported device state!")}return t}MapResponseTypeToDeviceStateType(e){switch(e){case Pt.BatteryState:return Qo.BatteryState;case Pt.BinarySensorState:return Qo.BinarySensor;case Pt.BlindPosition:return Qo.BlindPosition;case Pt.LightBrightness:return Qo.LightBrightness;case Pt.RemoteButtonState:return Qo.ButtonState;case Pt.ChannelOnOffState:return Qo.ChannelOnOff;case Pt.DoorBellState:return Qo.DoorBell;case Pt.MeasuredEnergy:return Qo.Energy;case Pt.FloodSensorState:return Qo.FloodSensor;case Pt.GatePosition:return Qo.GatePosition;case Pt.MeasuredBrightness:return Qo.Brightness;case Pt.LightColor:return Qo.LightColor;case Pt.LightWarmth:return Qo.LightTemperature;case Pt.ReedState:return Qo.ReedState;case Pt.SmokeSensorState:return Qo.SmokeSensor;case Pt.MeasuredTemperature:return Qo.Temperature;case Pt.HumiditySensorState:return Qo.Humidity;case Pt.BlindRemoteButtonState:return Qo.BlindsControlButton;case Pt.FacadeRemoteButtonState:return Qo.FacadeControlButton;case Pt.MovementSensorState:return Qo.Movement;case Pt.PressureSensorState:return Qo.AirPressure;case Pt.WindSpeedState:return Qo.WindSpeed;case Pt.CurrentWindThreshold:return Qo.WindThreshold;default:return Qo.Unknown}}AddSequence(){const e=(t,n)=>{if(t.RightArgumentType!=As.Null)return e(t.RightArgument,n);t.RightArgumentType=As.Condition,t.RightArgument=n,this._editingExistingSequence&&null!=this._rawExistingSequenceTasks&&(n.Tasks=JSON.parse(JSON.stringify(this._rawExistingSequenceTasks)),t.Tasks=new Is)};null==this._result?(this._tmp.Name=this._sequenceName,this._tmp.Icon=this._sequenceIcon,this._result=this._tmp,this._result.AtMeetCondition=!0):e(this._result,this._tmp);const t=this._service.MapSequence(JSON.parse(JSON.stringify(this._tmp)));return this._tmp=new Cs,{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,r=Yo.Equal)=>this.ArgumentAsDeviceState(e,t,n,r),ArgumentAsTime:(e,t,n=Yo.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:t}}EditSequence(e){const t=(n,r)=>{if(n.Guid!=e||n.ObjectType!=As.Condition){if(n.RightArgumentType==As.Condition)return t(n.RightArgument,r);throw new Us(`Cannot edit sequence with given GUID ${e} - sequence not foud in chain`)}n.AtMeetCondition=r.AtMeetCondition,n.ConditionTimeout=r.ConditionTimeout,n.ConditionType=r.ConditionType,n.ExecuteOnce=r.ExecuteOnce,n.HandledType=r.HandledType,n.IsDisabled=r.IsDisabled,n.LeftArgument=r.LeftArgument,n.LeftArgumentType=r.LeftArgumentType,n.ObjectType=r.ObjectType,n.Tasks=r.Tasks,r.Guid=n.Guid,r.Icon=n.Icon,r.Name=n.Name};if(null==this._result)throw new Us(`Cannot edit sequence with given GUID ${e} - sequence not initialized (no root element)`);t(this._result,this._tmp);const n=this._service.MapSequence(JSON.parse(JSON.stringify(this._tmp)));return this._tmp=new Cs,console.log(`new tmp guid: ${this._tmp.Guid}`),this._result.AtMeetCondition||(this._result.AtMeetCondition=!0),{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,r=Yo.Equal)=>this.ArgumentAsDeviceState(e,t,n,r),ArgumentAsTime:(e,t,n=Yo.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:n}}RemoveSequenceByGuid(e){let t;const n=(e,n)=>{""==this._currentSeqGuid&&""==this._prevSeqGuid||(this._currentSeqGuid==n?(this._currentSeqGuid=e.RightArgumentType==As.Condition?e.RightArgument.Guid:"",this._prevSeqGuid=null!=t?t.Guid:""):this._prevSeqGuid==n&&(this._prevSeqGuid=null!=t?t.Guid:""))},r=(e,o)=>{if(e.Guid!=o){if(t=e,e.RightArgumentType==As.Null)throw new Us(`Cannot remove sequence, sequence with given guid ${o} not found!`);return r(e.RightArgument,o)}null==t?this._result=null:(t.RightArgument=e.RightArgument,t.RightArgumentType=e.RightArgumentType),n(e,o)};if(null==this._result)throw new Us("Cannot remove sequence, sequence not configured!");return this._result.Guid==e&&this._result.RightArgumentType!=As.Null?(this._result.RightArgument.Name=this._result.Name,this._result.RightArgument.Icon=this._result.Icon,this._result.RightArgument.Guid=this._result.Guid,this._result=this._result.RightArgument,this._result.AtMeetCondition=!0,n(this._result,e)):r(this._result,e),{GetNext:()=>this.GetNext(),GetPrevious:()=>this.GetPrevious(),GetByGuid:e=>this.GetByGuid(e),GetAllowedArguments:()=>this.GetAllowedArguments(),RemoveSequenceByGuid:e=>this.RemoveSequenceByGuid(e),Commit:()=>this.Commit(),ArgumentAsActionWithEmptyCondition:()=>this.ArgumentAsActionWithEmptyCondition(),ArgumentAsAstronomicalClockWithOffset:(e,t,n)=>this.ArgumentAsAstronomicalClockWithOffset(e,t,n),ArgumentAsDaysOfWeek:(e,t,n)=>this.ArgumentAsDaysOfWeek(e,t,n),ArgumentAsDeviceState:(e,t,n,r=Yo.Equal)=>this.ArgumentAsDeviceState(e,t,n,r),ArgumentAsTime:(e,t,n=Yo.Equal)=>this.ArgumentAsTime(e,t,n),ArgumentAsTimeSpan:(e,t)=>this.ArgumentAsTimeSpan(e,t),ArgumentAsSceneExecuted:e=>this.ArgumentAsSceneExecuted(e),SequenceData:null}}Commit(){const e=t=>{if(t.RightArgumentType!=As.Null)return e(t.RightArgument);null!=this._rawExistingSequenceTasks&&(t.Tasks=this._rawExistingSequenceTasks)};if(null==this._result)throw new Us("Sequence are not initialized! Not found root sequence.");return this._editingExistingSequence&&e(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:e=>this.NotifyTask(e),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}DeviceTask(e){if(this._tmpTask=this.ParseDeviceTask(e),null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:oe.GenerateMd5(JSON.stringify(this._tmpTask))}}ParseDeviceTask(e){const t=new bs;return t.Channel=e.Channel,t.DeviceGuid=e.DeviceGuid,t.ControlFeature=this.MapTaskTypeToControlFeature(e.TaskType),t.Data={},t.Data.Channel=e.Channel,e.TaskType==Rt.SetBlindPosition||e instanceof so?(t.Data.Position=e.Position,t.Data.Action=e.Action):e.TaskType==Rt.SetBlindPositionSimple||e instanceof ao?(t.Data.Action=e.Action,t.Data.Position=0):e.TaskType==Rt.SetLightColor||e instanceof ro?(t.Data.R=e.R,t.Data.G=e.G,t.Data.B=e.B):e.TaskType==Rt.SetLightTemperature||e instanceof oo?t.Data.Temperature=e.Temperature:e.TaskType==Rt.SetLightBrightness||e instanceof to?t.Data.Brightness=e.Brightness:e.TaskType==Rt.SetTemperature||e instanceof Yr?t.Data.Temperature=e.Temperature:e.TaskType==Rt.TurnOnWithTime||e instanceof eo?t.Data.SwitchOffDelaySeconds=e.SwitchOffDelaySeconds:e.TaskType==Rt.SetLightBrightnessDynamicly||e instanceof co?t.Data.Brightness=e.Brightness:e.TaskType==Rt.SetBlindOpenCloseTime||e instanceof lo?(t.Data.CloseTime=e.Data.CloseTime,t.Data.OpenTime=e.Data.OpenTime):e.TaskType==Rt.SetBlindMicroventilation||e instanceof go?t.Data.Position=e.Position:e.TaskType==Rt.SetFacadePosition||e instanceof yo?(t.Data.FacadeAction=e.FacadeAction,t.Data.Position=e.Position,t.Data.Tilt=e.Tilt):e.TaskType==Rt.LightRGBW||e instanceof So?(t.Data.R=e.Data.R,t.Data.G=e.Data.G,t.Data.B=e.Data.B,t.Data.W=e.Data.W,t.Data.Brightness=e.Data.Brightness):(e.TaskType==Rt.PreciseGateControl||e instanceof io)&&(t.Data.Position=e.Position,t.Data.GateControlAction=e.GateControlAction),t}DelayTask(e){const t=new Gs;if("00:00:00"==e.Delay.Value)throw new Ps("Delay must be other than 00:00:00!");if(t.Delay=e.Delay.Value,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:oe.GenerateMd5(JSON.stringify(t))}}NotifyTask(e){if(e.NotifyType==ns.Email)throw new Ms("NotifyType 'Email' is not supported!");if(e.NotifyType==ns.None)throw new Error("NotifyType mus be set!");if(""==e.Message)throw new Ps("Message must be set!");if(e.Message.length>1e3)throw new Ps("Message is too long! Max length is 1000 characters.");const t=new Rs;if(t.NotifyType=e.NotifyType,t.Message=e.Message,t.NotificationClients=e.NotificationClients,t.Title=this._sequenceName,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:oe.GenerateMd5(JSON.stringify(t))}}LockExecutionTask(e){const t=new Ns;if(t.LockType=e.LockType,t.LockType==rs.Timeout&&"00:00:00"!=t.LockEndHour)throw new Ms("Parameter LockEndHour at lock type `Timeout` must be default!");if(t.LockStartHour=e.LockStartHour.Value,t.LockEndHour=e.LockEndHour.Value,t.ResetLockScenesGuids=e.ResetLockScenesGuids,this._tmpTask=t,null==this._result)throw new Error("No context!");return{AddTask:()=>this.AddTask(),EditTask:e=>this.EditTask(e),TaskId:oe.GenerateMd5(JSON.stringify(t))}}AddTask(){const e=t=>{var n;if(t.RightArgumentType!=As.Null)return e(t.RightArgument);if(null==this._tmpTask)throw Error("No task context!");void 0!==t.Tasks.DevicesTasks&&null!==t.Tasks.DevicesTasks||(t.Tasks.DevicesTasks=[]),this._tmpTask instanceof bs&&t.Tasks.DevicesTasks.push(structuredClone(this._tmpTask)),t.Tasks.ControllerTasks.push(structuredClone(this._tmpTask)),this._tmpTask=null,null===(n=u.Log)||void 0===n||n.Debug(`Task added to sequence: \n${JSON.stringify(this._tmpTask)} \ntasks on a list: \n${JSON.stringify(t.Tasks)}`)};if(null==this._result)throw new Error("No context!");return e(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:e=>this.NotifyTask(e),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}EditTask(e){const t=n=>{var r;if(n.RightArgumentType!=As.Null)return t(n.RightArgument);if(null==this._tmpTask)throw Error("No task context!");if(null==n.Tasks.ControllerTasks||0==n.Tasks.ControllerTasks.length)throw new Os("Task not found, cannot edit!");this._tmpTask instanceof bs&&null!=n.Tasks.DevicesTasks&&(n.Tasks.DevicesTasks=n.Tasks.DevicesTasks.map((t=>oe.GenerateMd5(JSON.stringify(t))==e?structuredClone(this._tmpTask):t))),n.Tasks.ControllerTasks=n.Tasks.ControllerTasks.map((t=>oe.GenerateMd5(JSON.stringify(t))==e?structuredClone(this._tmpTask):t)),this._tmpTask=null,null===(r=u.Log)||void 0===r||r.Debug(`Task edited in sequence: \n${JSON.stringify(this._tmpTask)} \ntasks on a list: \n${JSON.stringify(n.Tasks)}`)};if(null==this._result)throw new Error("No context!");return t(this._result),{GetSupportedTypesOfTasks:()=>this.GetSupportedTaskTypesAsync(),DeviceTask:e=>this.DeviceTask(e),DelayTask:e=>this.DelayTask(e),NotifyTask:e=>this.NotifyTask(e),LockExecutionTask:e=>this.LockExecutionTask(e),RemoveTask:e=>this.RemoveTask(e),Build:()=>this.Build(),BuildToISequence:()=>this._service.MapSequence(JSON.parse(JSON.stringify(this._result))),ValidateScene:()=>this.ValidateScene()}}RemoveTask(e){const t=(e,n)=>{var r,o;if(e.RightArgumentType!=As.Null)return t(e.RightArgument,n);{const t=e.Tasks.ControllerTasks.filter((e=>oe.GenerateMd5(JSON.stringify(e))!=n));if(e.Tasks.ControllerTasks=null==t?[]:t,null===(o=null===(r=e.Tasks)||void 0===r?void 0:r.DevicesTasks)||void 0===o?void 0:o.any()){const t=e.Tasks.DevicesTasks.filter((e=>oe.GenerateMd5(JSON.stringify(e))!=n));e.Tasks.DevicesTasks=null==t?[]:t}}};if(null==this._result)throw Error("Cannot remove task, sequence not configured!");t(this._result,e)}MapTaskTypeToControlFeature(e){switch(e){case Rt.Unknown:throw new Ps("Unsupported task type!");case Rt.SetBlindPosition:case Rt.SetBlindPositionSimple:return Br.SetBlindPosition;case Rt.SetBlindMicroventilation:return Br.SetBlindMicroventilation;case Rt.TurnOff:return Br.TurnOff;case Rt.TurnOn:return Br.TurnOn;case Rt.TurnOnWithTime:return Br.TurnOnWithTimeout;case Rt.TogleState:return Br.ToggleState;case Rt.SetLightBrightnessDynamicly:return Br.SetLightBrightnessDynamicly;case Rt.SetLightBrightness:return Br.SetLightBrightness;case Rt.SetLightColor:return Br.SetLightColor;case Rt.SetLightTemperature:return Br.SetLightTemperature;case Rt.PairDevice:case Rt.UnpairDevice:throw new Ps("Unsupported task type!");case Rt.IdentifyDevice:return Br.IdentifyDevice;case Rt.GetChannelsState:return Br.GetState;case Rt.GetPowerMeasurements:case Rt.GetAvailableData:case Rt.MultipleDataRequest:throw new Ps("Unsupported task type!");case Rt.SetBlindOpenCloseTime:return Br.SetBlindOpenCloseTime;case Rt.SetTemperature:return Br.SetTemperature;case Rt.ChangeGatePositionPulse:return Br.GatePulse;case Rt.ChangeGatewayPositionPulse:return Br.GatewayPulse;case Rt.SetFacadePosition:case Rt.GetFacadeType:return Br.SetFacadePositionAndTilt;case Rt.LightRGBW:return Br.LightRGBW;case Rt.PreciseGateControl:return Br.SetGatePositionPrecise;default:throw new Ps("Unsupported task type!")}}GetSupportedTaskTypesAsync(){return e=this,t=void 0,r=function*(){const e=yield hy.Get(cs.ServiceName).GetSoftwareRuntimeInfoAsync(),[t,n]=e.SoftwareVersion.split(".").map((e=>parseInt(e))),r=[ts.DeviceTask];return(t>5||5==t&&n>=27)&&r.push(ts.DelayTask),(t>5||5==t&&n>=37)&&r.push(ts.LockExecutionTask),(t>6||6==t&&n>=3)&&r.push(ts.NotifyTaskAppNotify),r},new((n=void 0)||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}));var e,t,n,r}Build(){const e=t=>{if(t.RightArgumentType!=As.Null)return e(t.RightArgument);t.Tasks.ControllerTasks=t.Tasks.ControllerTasks.map((e=>(Object.hasOwn(e,"_taskGuid")&&delete e._taskGuid,e)))};if(null!=this._result)return e(this._result),this._result;throw Error("Cannot build sequence, sequence not configured!")}FindArgumentWithGuid(e,t){return e.Guid==t?e:e.RightArgumentType==As.Condition?this.FindArgumentWithGuid(e.RightArgument,t):null}GetAllowedArguments(){const e=[];return null==this._result?(e.push({ArgumentType:Ss.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:Ss.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:Ss.ArgumentAsDeviceState,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:Ss.ArgumentAsSceneExecuted,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:Ss.ArgumentAsTime,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e.push({ArgumentType:Ss.ArgumentAsTimeSpan,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1})):null!=this._result&&(null==this._result.RightArgument||this._result.RightArgument instanceof Ds)&&(this._result.LeftArgumentType==As.ArgumentAsDaysOfWeek&&(e.push({ArgumentType:Ss.ArgumentAsTime,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0}),e.push({ArgumentType:Ss.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0})),this._result.LeftArgumentType==As.ArgumentAsTime&&e.push({ArgumentType:Ss.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!1}),this._result.LeftArgumentType==As.ArgumentAsAstronomicalClockWithOffset&&e.push({ArgumentType:Ss.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!1})),0==e.any((e=>e.ArgumentType==Ss.ArgumentAsAstronomicalClockWithOffset))&&e.push({ArgumentType:Ss.ArgumentAsAstronomicalClockWithOffset,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==Ss.ArgumentAsDaysOfWeek))&&e.push({ArgumentType:Ss.ArgumentAsDaysOfWeek,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==Ss.ArgumentAsDeviceState))&&e.push({ArgumentType:Ss.ArgumentAsDeviceState,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==Ss.ArgumentAsSceneExecuted))&&e.push({ArgumentType:Ss.ArgumentAsSceneExecuted,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),0==e.any((e=>e.ArgumentType==Ss.ArgumentAsTime))&&e.push({ArgumentType:Ss.ArgumentAsTime,InitialAtMeetConditionValue:!1,ChangableAtMeetCondition:!0}),0==e.any((e=>e.ArgumentType==Ss.ArgumentAsTimeSpan))&&e.push({ArgumentType:Ss.ArgumentAsTimeSpan,InitialAtMeetConditionValue:!0,ChangableAtMeetCondition:!1}),e}ValidateScene(){var e,t,n,r;if(null==this._result)throw new Error("No context!");const o=[],s=(e,t,n)=>e.RightArgumentType==As.Null?e.LeftArgumentType==t&&e.AtMeetCondition==n?e:null:e.LeftArgumentType==t&&e.AtMeetCondition==n?e:s(e.RightArgument,t,n),i=s(this._result,As.ArgumentAsDaysOfWeek,!0);null!=i&&((null===(e=i.RightArgument)||void 0===e?void 0:e.LeftArgumentType)==As.ArgumentAsTime||(null===(t=i.RightArgument)||void 0===t?void 0:t.LeftArgumentType)==As.ArgumentAsAstronomicalClockWithOffset)&&o.push(ws.OptimizeDayOfWeekArgument);const a=s(this._result,As.ArgumentAsTime,!0);return null!=a&&(null===(n=a.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==As.ArgumentAsDaysOfWeek&&(null===(r=a.RightArgument)||void 0===r?void 0:r.AtMeetCondition)&&o.push(ws.OptimizeAtInDayOfWeekArgument),{IsValid:0==o.length,Errors:o,TryFix:()=>this.TryFix(o),Ignore:()=>this.Commit()}}TryFix(e){if(null==this._result)throw new Error("No context!");if(e.includes(ws.OptimizeDayOfWeekArgument)){const e=t=>{var n,r;return t.LeftArgumentType==As.ArgumentAsDaysOfWeek?(null===(n=t.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==As.ArgumentAsTime||(null===(r=t.RightArgument)||void 0===r?void 0:r.LeftArgumentType)==As.ArgumentAsAstronomicalClockWithOffset?t:e(t.RightArgument):t.RightArgumentType==As.Null?null:e(t.RightArgument)},t=e(this._result);if(null==t)throw new Error("Something wrong! Cannot find 'days of week' argument! Cannot fix!");const n=structuredClone(t),r=t.RightArgument;t.LeftArgument=r.LeftArgument,t.LeftArgumentType=r.LeftArgumentType,t.HandledType=r.HandledType,r.LeftArgument=n.LeftArgument,r.LeftArgumentType=n.LeftArgumentType,r.HandledType=n.HandledType,r.AtMeetCondition=!1}if(this.ValidateScene().Errors.includes(ws.OptimizeAtInDayOfWeekArgument)){const e=t=>{var n,r;return t.LeftArgumentType==As.ArgumentAsTime?(null===(n=t.RightArgument)||void 0===n?void 0:n.LeftArgumentType)==As.ArgumentAsDaysOfWeek&&(null===(r=t.RightArgument)||void 0===r?void 0:r.AtMeetCondition)?t:e(t.RightArgument):t.RightArgumentType==As.Null?null:e(t.RightArgument)},t=e(this._result);if(null==t)return this.Commit();t.RightArgument.AtMeetCondition=!1}return this.Commit()}}!function(e){e.OptimizeDayOfWeekArgument="OptimizeDayOfWeekArgument",e.OptimizeAtInDayOfWeekArgument="OptimizeAtInDayOfWeekArgument"}(ws||(ws={})),function(e){e.Unknown="Unknown",e.ArgumentAsAstronomicalClockWithOffset="ArgumentAsAstronomicalClockWithOffset",e.ArgumentAsDaysOfWeek="ArgumentAsDaysOfWeek",e.ArgumentAsTimeSpan="ArgumentAsTimeSpan",e.ArgumentAsTime="ArgumentAsTime",e.ArgumentAsDeviceState="ArgumentAsDeviceState",e.ArgumentAsSceneExecuted="ArgumentAsSceneExecuted"}(Ss||(Ss={}));class Cs{constructor(){this.Tasks=new Is,this.Guid="",this.ObjectType=1,this.Name="",this.Icon="",this.AtMeetCondition=!1,this.ExecuteOnce=!1,this.IsDisabled=!1,this.HandledType=Xo.Unknown,this.ConditionType=Yo.Unknown,this.ConditionTimeout=0,this.LeftArgumentType=As.Null,this.RightArgumentType=As.Null,this.LeftArgument=new Ts({},As.Null),this.RightArgument=new Ds}}class Ds{constructor(){this.HandledType=0,this.Argument=null}}class Ts{constructor(e,t){this.Argument=e,this.HandledType=t}}class ks{constructor(){this.DeviceStateType=Qo.Unknown,this.Channel=0,this.DeviceGuid="",this.ComparisonMethod=Ho.Default,this.ComparisonParams=null,this.CheckedDeviceState={}}}class Is{constructor(){this.ControllerTasks=[],this.DevicesTasks=[]}}class Es{constructor(){this.Guid=Jr.NewGuid(),this.RunParallel=!1,this.TaskType=zo.Unknown}}class bs extends Es{constructor(){super(...arguments),this.TaskType=zo.DeviceTask,this.DeviceGuid="",this.Channel=0,this.ControlFeature=Br.TurnOn}}class Gs extends Es{constructor(){super(...arguments),this.TaskType=zo.DelayTask,this.Delay="00:00:00"}}class Ns extends Es{constructor(){super(...arguments),this.TaskType=zo.LockExecution,this.LockType=rs.Timeout,this.LockStartHour="00:00:00",this.LockEndHour="00:00:00",this.ResetLockScenesGuids=[]}}class Rs extends Es{constructor(){super(...arguments),this.TaskType=zo.NotifyTask,this.Title="",this.Message="",this.NotifyType=ns.None,this.NotificationClients=[]}}!function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(As||(As={}));class Ps extends Error{constructor(e){super(e),this.message=e,this.name="BadParametersScenesBuilderException"}}class Us extends Error{constructor(e){super(e),this.message=e,this.name="SequenceNotFoundScenesBuilderException"}}class Os extends Error{constructor(e){super(e),this.message=e,this.name="TaskNotFoundScenesBuilderException"}}class Ms extends Error{constructor(e){super(e),this.message=e,this.name="UnsupportedArgumentScenesBuilderException"}}var xs,Fs=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Ls{constructor(){this._connection=hy.Get(It.ServiceName),this._configurationService=hy.Get(ct.ServiceName)}GetServiceName(){return Ls.ServiceName}GetSequencesListAsync(){return Fs(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Bs,12e3,!1);return null===(t=u.Log)||void 0===t||t.Debug(`GetSequencesListAsync result:\n ${JSON.stringify(n)}}`),null==n?new Ee(qo.OtherError,"Cannot get sequences list - response is null."):n.Status!=ue.OK?new Ee(qo.OtherError,`Cannot get sequences list - controller responded with response code ${n.Status}.`):null==n.Data?new Ee(qo.NoData,"Cannot get sequences list - controller responded with status OK, but response does not contain data!"):n.Data}))}GetSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t;let n="";n="string"==typeof e?e:e.Guid;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ws(n),12e3,!1);if(null==r)return new Ee(qo.OtherError,"Cannot get sequence - response is null.");if(r.Status!=ue.OK)return new Ee(qo.OtherError,`Cannot get sequence - controller responded with response code ${r.Status}.`);if(null==r.Data)return new Ee(qo.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!");const o=r.Data;let s=this.MapSequence(o);if("string"==typeof e){let e=yield this.GetSequencesListAsync();if(e instanceof Ee){let t=e;console.warn(`Cannot get sequence - response is null. Error: ${t.Data} ${t.Type}`)}else{const t=e.find((e=>e.Guid==n));if(!t)return new Ee(qo.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!");s.IsDisabled=t.IsDisabled}}else{const e=o;s.IsDisabled=e.IsDisabled}return s}))}GetSequenceBuilder(e,t){return new _s(e,t)}CreateSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t,n,r,o;try{yield this._configurationService.EnterConfigurationModeAsync(),null===(t=u.Log)||void 0===t||t.Debug(`Creating sequence ${e.Name} json: \n${JSON.stringify(e)}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Hs(e),2e4,!1);return null==r||null==r.Status?ue.Error:r.Status}catch(t){return null===(r=u.Log)||void 0===r||r.Error(`Creating sequence ${e.Name} error: ${t}`),ue.FatalError}finally{null===(o=u.Log)||void 0===o||o.Error(Ls.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! CreateSequenceAsync()"),yield this._configurationService.ExitConfigurationModeAsync(),yield hy.Get(Ys.ServiceName).GetDevicesAsync(!0)}}))}CheckIfSequenceIsUsedInAnotherSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new $s(n),12e3,!1);if(null==r)return new Ee(qo.OtherError,"Cannot get sequence - response is null.");switch(r.Status){case ue.WrongData:return new Ee(qo.InvalidSceneGuid,"Cannot check if sequence is used in another sequence! Sequence not found, invalid sequence guid!");case ue.OK:return null==r.Data?new Ee(qo.NoData,"Cannot get sequence - controller responded with status OK, but response does not contain data!"):r.Data;default:return new Ee(qo.OtherError,`Cannot check if sequence is used in another sequence! Controller responded with code: ${r.Status}`)}}catch(e){return new Ee(qo.FatalError,`Cannot check if sequence is used in another sequence! Fatal error! ${e}`)}}))}DeleteSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid,yield this._configurationService.EnterConfigurationModeAsync();const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new js(n),12e3,!1);return null==r||null==r.Status?ue.Error:r.Status}catch(e){return ue.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync(),yield hy.Get(Ys.ServiceName).GetDevicesAsync(!0)}}))}EditSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t,n;try{const n={Guid:e.Guid,Icon:e.Icon,Name:e.Name,Condition:e};var r=n.Condition.IsDisabled;n.Condition.IsDisabled=!1,yield this._configurationService.EnterConfigurationModeAsync();const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ks(n),2e4,!1);return n.Condition.IsDisabled=r,null==o||null==o.Status?ue.Error:o.Status}catch(t){return null===(n=u.Log)||void 0===n||n.Error(`Editing sequence ${e.Name} error: ${t}`),ue.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync(),yield hy.Get(Ys.ServiceName).GetDevicesAsync(!0)}}))}EnableSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new zs(n),12e3,!1);return null==r||null==r.Status?ue.Error:r.Status}catch(e){return ue.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}DisableSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){var t;try{let n="";n="string"==typeof e?e:e.Guid;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Js(n),12e3,!1);return null==r||null==r.Status?ue.Error:r.Status}catch(e){return ue.FatalError}finally{yield this._configurationService.ExitConfigurationModeAsync()}}))}RunSequenceAsync(e){return Fs(this,void 0,void 0,(function*(){let t="";if("string"==typeof e){const n=yield this.GetSequencesListAsync();if(null!=n.Type)return ue.Error;{const r=n.find((t=>t.Guid==e));if(!r)return ue.Error;t=r.DeviceGuid}}else t=e.DeviceGuid;const n=new Zr;switch(n.Channel=1,n.DeviceGuid=t,yield hy.Get(Ys.ServiceName).ExecuteDeviceTaskAsync({Guid:t},n)){case Ft.Executed:return ue.OK;case Ft.DeviceNotFound:return ue.WrongData;default:return ue.Error}}))}GetUtilsAsync(){return Fs(this,void 0,void 0,(function*(){const e=yield this.SunCalculatorAsync();return{GetSunRiseTime:e.GetSunRiseTime,GetSunSetTime:e.GetSunSetTime,ParseLinearScaleToLux:this._parseLinearScaleToLux,ParseLuxToLinearScale:this._parseLuxToLinearScale}}))}_parseLinearScaleToLux(e){if(!(e<0||e>1))return Math.round(Math.pow(10,5*e))}_parseLuxToLinearScale(e){if(e<=0)return 0;const t=Math.log10(e)/5;return t>1?1:t}SunCalculatorAsync(){return Fs(this,void 0,void 0,(function*(){var e;const t=hy.Get(Mo.ServiceName),n=new No;let r=!1;n.Latitude=49.9958888026741,n.Longitude=18.9172596008914;try{if(!0===(yield t.IsControllerGeolocationSetAsync())){const e=yield t.GetControlllerGeolocationAsync();e instanceof Ro&&(n.Latitude=e.Latitude,n.Longitude=e.Longitude)}}catch(t){null===(e=u.Log)||void 0===e||e.Warning(`Cannot get localization data, using default values: 49.9958888026741, 18.9172596008914. Error: ${t}`)}const o=e=>{let t=7.95204*Math.sin(.01768*e+3.03217)+9.98906*Math.sin(.03383*e+3.4687)+4*(n.Longitude-15*Math.round(n.Longitude/15));return((e=new Date)=>{const t=new Date(e.getFullYear(),0,1).getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();return Math.max(t,n)!==e.getTimezoneOffset()})()&&(t-=60),t},s=e=>Math.asin(-.39795*Math.cos(2*Math.PI*(e+10)/365)),i=e=>{const t=n.Latitude*Math.PI/180;let r=Math.sin(t)*Math.sin(e)/(Math.cos(t)*Math.cos(e));return r=(e=>(e<-1&&(e=-1),e>1&&(e=1),e))(r),r},a=e=>{const t=Math.ceil(e/60),n=e-60*t,r=new Date;return new Date(r.getFullYear(),r.getMonth(),r.getDate(),t,n)},c=e=>{const t=new Date;t.setDate(t.getDate()+e);const n=(u=t,Math.floor((u.valueOf()-new Date(u.getFullYear(),0,0).valueOf())/1e3/60/60/24));var u;const l=o(n),d=s(n),h=((e,t)=>{let n=720-720/Math.PI*Math.acos(-e)-t;return n<0&&(n+=1440),n})(i(d),l),p=a(h);return new Date>p&&!r?(r=!0,c(1)):(r=!1,new Date(t.getFullYear(),t.getMonth(),t.getDate(),p.getHours(),p.getMinutes()))},l=e=>{const t=new Date;t.setDate(t.getDate()+e);const n=(c=t,Math.floor((c.valueOf()-new Date(c.getFullYear(),0,0).valueOf())/1e3/60/60/24));var c;const u=o(n),d=s(n),h=i(d),p=Math.floor(((e,t)=>{let n=720+720/Math.PI*Math.acos(-e)-t;return n>1439&&(n-=1439),n})(h,u)),g=a(p);return new Date>g&&!r?(r=!0,l(1)):(r=!1,new Date(t.getFullYear(),t.getMonth(),t.getDate(),g.getHours(),g.getMinutes()))};return{GetSunRiseTime:()=>c(0),GetSunSetTime:()=>l(0)}}))}MapSequence(e,t=!1){const n=Object.assign({},e),r=e=>{if(e.RightArgumentType!=xs.Null)return!Object.hasOwn(e.Tasks,"ControllerTasks")&&Object.hasOwn(e.Tasks,"DevicesTasks")&&delete Object.assign(e.Tasks,{ControllerTasks:e.Tasks.DevicesTasks}).DevicesTasks,r(e.RightArgument);!Object.hasOwn(e.Tasks,"ControllerTasks")&&Object.hasOwn(e.Tasks,"DevicesTasks")&&(delete Object.assign(e.Tasks,{ControllerTasks:e.Tasks.DevicesTasks}).DevicesTasks,e.Tasks.ControllerTasks.map((e=>{e.TaskType=zo.DeviceTask,e.RunParallel=!1}))),null!=e.Tasks.ControllerTasks&&e.Tasks.ControllerTasks.map((e=>{null==(null==e?void 0:e.Guid)&&(e.Guid=Jr.NewGuid())}))};return r(e),n._rawRequestData=JSON.parse(JSON.stringify(e)),t?(n.RightArgument=null,n.RightArgumentType=es.Null):(n.RightArgumentType=this.MapArgumentType(e.RightArgumentType),n.RightArgument=this.MapRightArgument(e.RightArgument,n.RightArgumentType)),n.LeftArgumentType=this.MapArgumentType(e.LeftArgumentType),n.LeftArgument=this.MapLeftArgument(e.LeftArgument,n.LeftArgumentType),n.Tasks.ControllerTasks=this.MapControllerTasks(e.Tasks.ControllerTasks),void 0===n.DoesHaveTriggers&&(n.DoesHaveTriggers=n.LeftArgumentType==es.Null),n}MapRightArgument(e,t){return 0==e.HandledType||(e.LeftArgumentType=this.MapArgumentType(e.LeftArgumentType),e.LeftArgument=this.MapLeftArgument(e.LeftArgument,e.LeftArgumentType),e.Tasks.ControllerTasks=this.MapControllerTasks(e.Tasks.ControllerTasks),Object.hasOwn(e.Tasks,"DevicesTasks")&&delete e.Tasks.DevicesTasks,t===es.Condition&&(e.RightArgumentType=this.MapArgumentType(e.RightArgumentType),e.RightArgument=this.MapRightArgument(e.RightArgument,e.RightArgumentType))),e}MapLeftArgument(e,t){let n=new Vs;switch(n.HandledType=e.HandledType,t){case es.ArgumentAsAstronomicalClock:n.Argument.ArgumentAsAstronomicalClock={Position:e.Argument};break;case es.ArgumentAsAstronomicalClockWithOffset:n.Argument.ArgumentAsAstronomicalClockWithOffset={Offset:e.Argument.Offset,Position:e.Argument.Position};break;case es.ArgumentAsBoolean:n.Argument.ArgumentAsBoolean=e.Argument;break;case es.ArgumentAsDayOfWeek:n.Argument.ArgumentAsDayOfWeek=e.Argument;break;case es.ArgumentAsDaysOfWeek:n.Argument.ArgumentAsDaysOfWeek=e.Argument;break;case es.ArgumentAsInt:n.Argument.ArgumentAsInt=e.Argument;break;case es.ArgumentAsTimeout:n.Argument.ArgumentAsTimeout=e.Argument;break;case es.ArgumentAsTimeSpan:n.Argument.ArgumentAsTimeSpan={days:e.Argument.days,hours:e.Argument.hours,minutes:e.Argument.minutes,seconds:e.Argument.seconds};break;case es.ArgumentAsTime:n.Argument.ArgumentAsTime={Hour:e.Argument.Hour,Minute:e.Argument.Minute,Second:e.Argument.Second};break;case es.ArgumentAsDeviceState:{const t=new gs;t.Type=this.MapDeviceStateTypeToResponseType(e.Argument.DeviceStateType),t.SetCheckDeviceState(this.CreateDeviceState(e.Argument.CheckedDeviceState,e.Argument.Channel,t.Type)),t.DeviceGuid=e.Argument.DeviceGuid,t.ComparisonMethod=null==e.Argument.ComparisonMethod?Ho.Default:e.Argument.ComparisonMethod,null!=e.Argument.ComparisonParams&&Object.entries(e.Argument.ComparisonParams).forEach((e=>{switch(e[0]){case"DeltaValue":case"StateRepeatCount":t.SetComparisonParam(Ko[e[0]],new fs(e[1]));break;case"DeltaCalculationTimeRange":case"StateRepeatTimeRange":t.SetComparisonParam(Ko[e[0]],new vs(e[1]))}})),n.Argument.ArgumentAsDeviceState=t;break}case es.ArgumentAsConditionInfo:n.Argument.ArgumentAsConditionInfo={DeviceGuid:e.Argument.DeviceGuid}}return n}MapArgumentType(e){return es[xs[e]]}MapDeviceStateTypeToResponseType(e){switch(e){case Qo.BatteryState:return Pt.BatteryState;case Qo.BinarySensor:return Pt.BinarySensorState;case Qo.BlindPosition:return Pt.BlindPosition;case Qo.Brightness:return Pt.MeasuredBrightness;case Qo.ButtonState:return Pt.RemoteButtonState;case Qo.ChannelOnOff:return Pt.ChannelOnOffState;case Qo.DoorBell:return Pt.DoorBellState;case Qo.Energy:return Pt.MeasuredEnergy;case Qo.FloodSensor:return Pt.FloodSensorState;case Qo.GatePosition:return Pt.GatePosition;case Qo.LightBrightness:return Pt.LightBrightness;case Qo.LightColor:return Pt.LightColor;case Qo.LightTemperature:return Pt.LightWarmth;case Qo.ReedState:return Pt.ReedState;case Qo.SmokeSensor:return Pt.SmokeSensorState;case Qo.Temperature:return Pt.MeasuredTemperature;case Qo.Humidity:return Pt.HumiditySensorState;case Qo.BlindsControlButton:return Pt.BlindRemoteButtonState;case Qo.FacadeControlButton:return Pt.FacadeRemoteButtonState;case Qo.Movement:return Pt.MovementSensorState;case Qo.AirPressure:return Pt.PressureSensorState;case Qo.WindSpeed:return Pt.WindSpeedState;case Qo.WindThreshold:return Pt.CurrentWindThreshold;default:return Pt.Unknown}}CreateDeviceState(e,t,n){switch(n){case Pt.BatteryState:return{Channel:t,StateReliability:zt.Unconfident,Percentage:e.Percentage,State:e.State,Time:""};case Pt.BinarySensorState:return{Channel:t,StateReliability:zt.Unconfident,State:e.State,Time:""};case Pt.BlindPosition:return{Channel:t,StateReliability:zt.Unconfident,Position:e.Position,RawPosition:e.RawPosition,Time:""};case Pt.LightBrightness:case Pt.MeasuredBrightness:return{Channel:t,StateReliability:zt.Unconfident,Brightness:e.Brightness,Time:""};case Pt.RemoteButtonState:case Pt.ChannelOnOffState:case Pt.DoorBellState:return{Channel:t,StateReliability:zt.Unconfident,State:e.State,Time:""};case Pt.MeasuredEnergy:{const n=new Map;for(let[t,r]of Object.entries(e.MeasurementParameters))n.set(nn[t],r);return{Channel:t,StateReliability:zt.Unconfident,MeasurementParameters:n,Time:""}}case Pt.FloodSensorState:return{Channel:t,StateReliability:zt.Unconfident,State:e.State,Time:""};case Pt.GatePosition:return{Channel:t,StateReliability:zt.Unconfident,Position:e.Position,PositionType:e.PositionType,Time:""};case Pt.LightColor:return{Channel:t,StateReliability:zt.Unconfident,R:e.R,G:e.G,B:e.B,Time:""};case Pt.LightWarmth:return{Channel:t,StateReliability:zt.Unconfident,Temperature:e.Temperature,Time:""};case Pt.ReedState:return{Channel:t,StateReliability:zt.Unconfident,State:e.State,Time:""};case Pt.SmokeSensorState:throw new ms("Unsupported device state!");case Pt.MeasuredTemperature:return{Channel:t,StateReliability:zt.Unconfident,Temperature:e.Temperature,Time:"",Type:e.Type};case Pt.HumiditySensorState:return{Channel:t,StateReliability:zt.Unconfident,Humidity:e.Humidity,Time:"",Type:e.Type};case Pt.BlindRemoteButtonState:return{Channel:t,StateReliability:zt.Unconfident,State:e.State,Time:""};case Pt.LightRGBWState:return{StateReliability:zt.Unconfident,Channel:t,Time:"",Brightness:100,R:e.R,G:e.G,B:e.B,W:e.W};case Pt.FacadeRemoteButtonState:return{Channel:t,Time:"",StateReliability:zt.Unconfident,State:e.State};case Pt.MovementSensorState:return{Channel:t,Time:"",StateReliability:zt.Unconfident,Movement:e.Movement,Intensity:e.Intensity};case Pt.PressureSensorState:return{Channel:t,Time:"",StateReliability:zt.Unconfident,Pressure:e.Pressure,PressureType:e.PressureType};case Pt.WindSpeedState:return{Channel:t,Time:"",StateReliability:zt.Unconfident,Value:e.Value};case Pt.CurrentWindThreshold:return{Channel:t,Time:"",StateReliability:zt.Unconfident,WindThreshold:e.WindThreshold};case Pt.Unknown:return new kn;default:throw new ms("Unsupported device state!")}}MapDeviceTask(e){var t;let n=new Xr,r=e;switch(null===(t=u.Log)||void 0===t||t.Debug(`[TASK] object: ${JSON.stringify(r)}`),r.ControlFeature){case Br.TurnOn:n=new Zr,n.TaskType=Rt.TurnOn;break;case Br.TurnOff:n=new Qr,n.TaskType=Rt.TurnOff;break;case Br.ToggleState:n=new no,n.TaskType=Rt.TogleState;break;case Br.SetBlindPosition:{const e=hy.Get(Ys.ServiceName).GetDevice(r.DeviceGuid);(null==e?void 0:e.AvailableTaskTypes.any((e=>"IBlindPositionSimple"==e.InterfaceType)))?(n=new ao,n.TaskType=Rt.SetBlindPositionSimple,n.Action=r.Data.Action):(n=new so,n.TaskType=Rt.SetBlindPosition,n.Action=r.Data.Action,n.Position=r.Data.Position);break}case Br.SetLightColor:n=new ro,n.TaskType=Rt.SetLightColor,n.R=r.Data.R,n.G=r.Data.G,n.B=r.Data.B;break;case Br.SetLightTemperature:n=new oo,n.TaskType=Rt.SetLightTemperature,n.Temperature=r.Data.Temperature;break;case Br.SetLightBrightness:n=new to,n.TaskType=Rt.SetLightBrightness,n.Brightness=r.Data.Brightness;break;case Br.SetTemperature:n=new Yr,n.TaskType=Rt.SetTemperature,n.Temperature=r.Data.Temperature;break;case Br.GetState:n=new po,n.TaskType=Rt.GetChannelsState;break;case Br.TurnOnWithTimeout:n=new eo,n.TaskType=Rt.TurnOnWithTime,n.SwitchOffDelaySeconds=r.Data.SwitchOffDelaySeconds;break;case Br.SetLightBrightnessDynamicly:n=new co,n.TaskType=Rt.SetLightBrightnessDynamicly,n.Brightness=r.Data.Brightness;break;case Br.IdentifyDevice:n=new uo,n.TaskType=Rt.IdentifyDevice;break;case Br.SetBlindOpenCloseTime:n=new lo,n.TaskType=Rt.SetBlindOpenCloseTime,n.Data.CloseTime=r.Data;break;case Br.SetBlindMicroventilation:n=new go,n.TaskType=Rt.SetBlindMicroventilation,n.Position=r.Data.Position;break;case Br.GatewayPulse:n=new vo,n.TaskType=Rt.ChangeGatewayPositionPulse;break;case Br.GatePulse:n=new fo,n.TaskType=Rt.ChangeGatePositionPulse;break;case Br.SetFacadePositionAndTilt:n=new yo,n.TaskType=Rt.SetFacadePosition,n.Position=r.Data.Position,n.Tilt=r.Data.Tilt,n.FacadeAction=qr.TiltAndPercentage;break;case Br.GetFacadeType:n=new mo,n.TaskType=Rt.GetFacadeType;break;case Br.LightRGBW:n=new So,n.TaskType=Rt.LightRGBW,n.Data=r.Data;break;case Br.SetGatePositionPrecise:n=new io,n.TaskType=Rt.PreciseGateControl,n.Position=r.Data.Position,n.GateControlAction=r.Data.GateControlAction}return n.Channel=r.Channel,n.DeviceGuid=r.DeviceGuid,n.FeatureType=r.ControlFeature,n.Guid=Jr.NewGuid(),n}MapControllerTasks(e){var t,n;const r=[];null===(t=u.Log)||void 0===t||t.Debug(`[TASKS] received tasks object: ${JSON.stringify(e)}`);for(let t of e){const e=new qs;switch(e.Guid=t.Guid,e.TaskId=oe.GenerateMd5(JSON.stringify(t)),t.TaskType){case zo.DeviceTask:e.TaskType=Jo.DeviceTask,e.Task.DeviceTask=this.MapDeviceTask(t);break;case zo.DelayTask:e.TaskType=Jo.DelayTask,e.Task.DelayTask={Delay:new vs(t.Delay)};break;case zo.NotifyTask:e.TaskType=Jo.NotifyTask,e.Task.NotifyTask={Message:t.Message,NotifyType:t.NotifyType,NotificationClients:t.NotificationClients};break;case zo.LockExecution:case zo.LockExecution:e.TaskType=Jo.LockExecution,null===(n=u.Log)||void 0===n||n.Debug(`[TASKS] received task LockExecution object: ${JSON.stringify(t)}`),e.Task.LockExecution={LockStartHour:new vs(t.LockStartHour),LockEndHour:new vs(t.LockEndHour),LockType:t.LockType,ResetLockScenesGuids:t.ResetLockScenesGuids};case zo.Unknown:}r.push(e)}return r}GetSupportedTaskTypesAsync(){return Fs(this,void 0,void 0,(function*(){const e=yield hy.Get(cs.ServiceName).GetSoftwareRuntimeInfoAsync(),[t,n]=e.SoftwareVersion.split(".").map((e=>parseInt(e))),r=[ts.DeviceTask];return(t>5||5==t&&n>=27)&&r.push(ts.DelayTask),(t>5||5==t&&n>=37)&&r.push(ts.LockExecutionTask),(t>6||6==t&&n>=3)&&r.push(ts.NotifyTaskAppNotify),r}))}}Ls.ServiceName="ScenesService";class Bs extends ce{constructor(){super(),this.Resource="/logic/sequences/list",this.Method=le.Get}}class Ws extends ce{constructor(e){super(),this.Resource="/logic/sequence",this.Method=le.Get,this.Data=e}}class $s extends ce{constructor(e){super(),this.Resource="/logic/sequences/used",this.Method=le.Get,this.Data=e}}class Vs{constructor(){this.HandledType=xs.Null,this.Argument={}}}!function(e){e[e.Null=0]="Null",e[e.Condition=1]="Condition",e[e.ConditionGroup=2]="ConditionGroup",e[e.ArgumentAsInt=3]="ArgumentAsInt",e[e.ArgumentAsTimeSpan=4]="ArgumentAsTimeSpan",e[e.ArgumentAsBoolean=5]="ArgumentAsBoolean",e[e.ArgumentAsTimeout=6]="ArgumentAsTimeout",e[e.ArgumentAsDayOfWeek=7]="ArgumentAsDayOfWeek",e[e.ArgumentAsDaysOfWeek=8]="ArgumentAsDaysOfWeek",e[e.ArgumentAsAstronomicalClock=9]="ArgumentAsAstronomicalClock",e[e.ArgumentAsTime=10]="ArgumentAsTime",e[e.ArgumentAsDeviceState=11]="ArgumentAsDeviceState",e[e.ArgumentAsNumber=12]="ArgumentAsNumber",e[e.ArgumentAsAstronomicalClockWithOffset=13]="ArgumentAsAstronomicalClockWithOffset",e[e.ArgumentAsConditionInfo=14]="ArgumentAsConditionInfo"}(xs||(xs={}));class qs{constructor(){this.TaskId="",this.Guid="",this.TaskType=Jo.Unknown,this.Task={}}}class Hs extends ce{constructor(e){super(),this.Resource="/logic/sequence",this.Method=le.Put,this.Data=e}}class Ks extends ce{constructor(e){super(),this.Resource="/logic/sequence/edit",this.Method=le.Put,this.Data=e}}class js extends ce{constructor(e){super(),this.Resource="/logic/sequence",this.Method=le.Delete,this.Data=e}}class zs extends ce{constructor(e){super(),this.Resource="/logic/sequence/enable",this.Method=le.Post,this.Data=e}}class Js extends ce{constructor(e){super(),this.Resource="/logic/sequence/disable",this.Method=le.Post,this.Data=e}}var Xs=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Ys{constructor(){var e;this._devices=[],this._onDevicesTasksChangedEvent=new c,this._onDeviceFoundEvent=new c,this._onDeviceRegisteredEvent=new c,this._onDeviceRemovedEvent=new c,this._onDeviceFirmwareVersionChangedEvent=new c,this._onDeviceStateChangedEvent=new c,this._onDeviceStateRefreshedOrChangedEvent=new c,this._connection=null,this._session=null,this._controllerConfiguration=null,this._synchronized=!1,this._synchronizedDevicesStates=!1,this._devicesChannelsStates=[],this._onDevicesSynchronized=new ke,this._onDevicesStatesSynchronized=new ke,this._syncSemaphore=new et(1),this._connection=hy.Get(It.ServiceName),this._session=hy.Get(Xe.ServiceName),this._controllerConfiguration=hy.Get(ct.ServiceName),this._onDeviceStateChangedEvent.Subscribe((e=>Xs(this,void 0,void 0,(function*(){return this.PutDeviceStateOnList(e.Device,e.State)})))),null===(e=this._session)||void 0===e||e.OnUserLoggedInEvent().Subscribe((e=>Xs(this,void 0,void 0,(function*(){var t,n;try{null===(t=u.Log)||void 0===t||t.Debug(Ys.ServiceName,`User logged in: ${e.Guid} syncing devices...`),yield this.ResyncDevicesAsync()}catch(e){null===(n=u.Log)||void 0===n||n.Error(Ys.ServiceName,`Failed to sync devices and states: ${e}`)}})))),this._connection.SubscribeTo("/info/devices/tasks",(e=>{this.ParseDeviceTaskInfo(e.Data)})),this._connection.SubscribeTo("/info/devices/device/found",(e=>{this.MapApiDevices(e.Data).forEach((e=>{var t;e.DeviceType!=Mt.Scene&&(null===(t=u.Log)||void 0===t||t.Debug(Ys.ServiceName,`Found device: ${e.Name} guid: ${e.Guid}`),this._onDeviceFoundEvent.Invoke(e))}))})),this._connection.SubscribeTo("/info/devices/device/firmware/updated",(e=>{const t=e.Data.DeviceGuid,n=e.Data.Version,r=this._devices.find((e=>e.Guid==t));void 0!==r&&(this._onDeviceFirmwareVersionChangedEvent.Invoke({Device:r,FirmwareVersion:n}),r.SoftwareVersion=n,r.OnDeviceFirmwareVersionChangedEvent().Invoke({FirmwareVersion:n}))})),this._connection.SubscribeTo("/info/devices/device/state/changed",(e=>{var t;const n=e.Data,r=this._devices.filter((e=>e.Guid==n.DeviceGuid));if(r.length>0){const e=r[0],o=this.MapApiDeviceStateToDeviceState(e,n);if(null!=o){this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:o}),o.TypeAsEnum==Pt.SignalStrength?e.Channels.forEach((t=>{let r=new cr(Object.assign({},n));r.Data.Channel=t.Number,this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:r})})):o.TypeAsEnum==Pt.BatteryState&&e.Channels.forEach((t=>{let r=new Jn(Object.assign({},n));r.Data.Channel=t.Number,this._onDeviceStateRefreshedOrChangedEvent.Invoke({Device:e,State:r})}));let r=e.States.find((e=>e.TypeAsEnum===o.TypeAsEnum&&e.Data.Channel===o.Data.Channel));if(r){let s=r.StatesComparisonData;if(o.TypeAsEnum==Pt.BlindErrorState&&(null===(t=o.Data)||void 0===t?void 0:t.ErrorCode)!=r.Data.ErrorCode)return void this._onDeviceStateChangedEvent.Invoke({Device:e,State:o});r.Data=o.Data,s!==o.StatesComparisonData&&(this._onDeviceStateChangedEvent.Invoke({Device:e,State:o}),o.TypeAsEnum==Pt.SignalStrength?e.Channels.forEach((t=>{let r=new cr(Object.assign({},n));r.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:r})})):o.TypeAsEnum==Pt.BatteryState&&e.Channels.forEach((t=>{let r=new Jn(Object.assign({},n));r.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:r})})))}else e.States.push(o),this._onDeviceStateChangedEvent.Invoke({Device:e,State:o}),o.TypeAsEnum==Pt.SignalStrength?e.Channels.forEach((t=>{let r=new cr(Object.assign({},n));r.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:r})})):o.TypeAsEnum==Pt.BatteryState&&e.Channels.forEach((t=>{let r=new Jn(Object.assign({},n));r.Data.Channel=t.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:r})}))}}})),this._connection.SubscribeTo("/info/devices/devices/registered",(e=>{hy.Get(Be.ServiceName).ClearCache(),this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=u.Log)||void 0===t||t.Debug(Ys.ServiceName,`Registered device: ${e.Name} guid: ${e.Guid}`),this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e)}))})),this._connection.SubscribeTo("/info/devices/devices/removed",(e=>{hy.Get(Be.ServiceName).ClearCache(),this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=u.Log)||void 0===t||t.Debug(Ys.ServiceName,`Removed device: ${e.Name} guid: ${e.Guid}`),this._devices=this._devices.filter((t=>t.Guid!=e.Guid)),this._onDeviceRemovedEvent.Invoke(e)}))}))}ResyncDevicesAsync(){return Xs(this,void 0,void 0,(function*(){var e;const t=yield this._syncSemaphore.AcquireAsync();try{this._synchronized=!1,this._synchronizedDevicesStates=!1,this._devices=yield this.GetPairedDevicesAsync(!0),this._synchronized=!0,this._onDevicesSynchronized.Invoke(),yield this.SyncDevicesStatesAsync(),this._synchronizedDevicesStates=!0,this._onDevicesStatesSynchronized.Invoke()}catch(t){null===(e=u.Log)||void 0===e||e.Error(Ys.ServiceName,`Failed to sync devices and states: ${t}`)}finally{t.Release()}}))}WaitForSynchronizationAsync(){var e;return this._synchronized?(null===(e=u.Log)||void 0===e||e.Debug(Ys.ServiceName,"Already synchronized"),Promise.resolve()):new Promise((e=>{const t=window.setTimeout((()=>{this._onDevicesSynchronized.Unsubscribe(n),e()}),3e4),n=()=>{var r;null===(r=u.Log)||void 0===r||r.Debug(Ys.ServiceName,"Fired onDevicesSynchronized event – clearing timeout & resolving promise"),window.clearTimeout(t),this._onDevicesSynchronized.Unsubscribe(n),e()};this._onDevicesSynchronized.Subscribe(n)}))}WaitForDevicesStatesSynchronizationAsync(){var e;return this._synchronizedDevicesStates?(null===(e=u.Log)||void 0===e||e.Debug(Ys.ServiceName,"Already synchronized states"),Promise.resolve()):new Promise((e=>{const t=window.setTimeout((()=>{this._onDevicesStatesSynchronized.Unsubscribe(n),e()}),12e4),n=()=>{var r;null===(r=u.Log)||void 0===r||r.Debug(Ys.ServiceName,"Fired onDevicesStatesSynchronized event, CLEARING timeout AND resolving WaitForDevicesStatesSynchronizationAsync promise"),window.clearTimeout(t),this._onDevicesStatesSynchronized.Unsubscribe(n),e()};this._onDevicesStatesSynchronized.Subscribe(n)}))}ProtocolGuidToProtocolName(e){switch(e){case"1fca7e8a-a2dc-4883-bd94-4e9b2012f685":return"ExtaLife";case"cd25bdff-628c-4dbc-a16a-648c96a819d4":return"Portos 433MHz";case"634c2bb2-1a4f-4db6-8dd4-d5fbaf92678e":return"Supla";case"194aeb81-990c-4a02-9236-59e902958fda":return"RTSP";case"b3e4644e-ab5b-494e-b3c5-66fabe7fff64":return"Wekta";case"247198e1-e360-4355-9886-232ac1456eea":return"Lavva Wi-Fi";default:return null}}CanDisplaySceneDevices(){return this.CheckIfControllerSoftwareVersionIsEnough(6,56)}CheckIfControllerSoftwareVersionIsEnough(e,t){var n,r,o;const s=null!==(o=null===(r=null===(n=this._session)||void 0===n?void 0:n.User)||void 0===r?void 0:r.SoftwareVersion)&&void 0!==o?o:null;if(!s||!s.includes("."))return!1;const i=s.split(".");if(2!==i.length)return!1;const a=i.map((e=>parseInt(e,10)));if(a.some((e=>Number.isNaN(e)||e<0)))return!1;const[c,u]=a;return c>e||c===e&&u>=t}CheckIfDeviceUsedInScenesAsync(e){return Xs(this,void 0,void 0,(function*(){var t,n,r,o,s,i;try{let i;if("string"==typeof e){const n=this.GetDevice(e);if(null==n)return null===(t=u.Log)||void 0===t||t.Error("Cannot check if device is used in scenes! Device with given guid not exists"),ue.ResourceDoesNotExists;i=n}else i=e;const a=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new di(i.Guid),2e4,!1);if(null==a||null==a.Status)return null===(r=u.Log)||void 0===r||r.Error("Cannot check if device is used in scenes! Response or status is null!"),ue.FatalError;if(a.Status!=ue.OK)return a.Status;if(null==a.Data)return null===(o=u.Log)||void 0===o||o.Error("Cannot check if device is used in scenes! No data!"),ue.FatalError;let c=yield hy.Get(Ls.ServiceName).GetSequencesListAsync();if(c instanceof Ee)return null===(s=u.Log)||void 0===s||s.Error(`Cannot check if device is used in scenes! Cannot get sequence list, ScenesServiceErrorCode: ${c.Type}`),ue.Error;const l=new fi;return l.DeviceGuid=i.Guid,a.Data.ConditionsAsCondition.forEach((e=>{const t=c.find((t=>t.Guid==e));t&&l.ConditionsAsCondition.push(t)})),a.Data.ConditionsAsTask.forEach((e=>{const t=c.find((t=>t.Guid==e));t&&l.ConditionsAsCondition.push(t)})),l}catch(e){return null===(i=u.Log)||void 0===i||i.Error(`Cannot check if device is used in scenes! ${e}`),ue.FatalError}}))}CanEditDevicesInfo(){var e,t;return null!==this._session&&void 0!==this._session&&null!==this._session.User&&void 0!==this._session.User&&(null===(t=null===(e=this._session)||void 0===e?void 0:e.User)||void 0===t?void 0:t.AccessLevel)>=fe.Admin}CanAddAndRemoveAndConfigureDevices(){var e,t;return null!==this._session&&void 0!==this._session&&null!==this._session.User&&void 0!==this._session.User&&(null===(t=null===(e=this._session)||void 0===e?void 0:e.User)||void 0===t?void 0:t.AccessLevel)>=fe.Installator}GetDeviceChannelByChannelId(e){return this._devices.firstOrDefault((t=>t.Channels.any((t=>t.ChannelId==e)))).Channels.firstOrDefault((t=>t.ChannelId==e))}EnableFastStatesSyncAsync(){return Xs(this,void 0,void 0,(function*(){var e;const t=hy.Get(ko.ServiceName).SaveAsync("FastDevicesSync",!1,!0);return null===(e=u.Log)||void 0===e||e.Error(Ys.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! EnableFastStatesSyncAsync()"),yield hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),t}))}DisableFastStatesSyncAsync(){return Xs(this,void 0,void 0,(function*(){var e;const t=hy.Get(ko.ServiceName).SaveAsync("FastDevicesSync",!1,!1);return null===(e=u.Log)||void 0===e||e.Error(Ys.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! DisableFastStatesSyncAsync()"),yield hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),t}))}IsFastStatesSyncEnabledAsync(){return Xs(this,void 0,void 0,(function*(){const e=yield hy.Get(ko.ServiceName).ReadAsync("FastDevicesSync",!1,!1);return e instanceof Co?e.Data:e!=ue.ResourceDoesNotExists&&e}))}GetDevicesForManualPairingAsync(e){return Xs(this,void 0,void 0,(function*(){let t=hy.Get(_o.ServiceName);const n=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");return Array.isArray(e)||n.test(e)?yield t.GetDevicesForManualPairingAsync(e):yield t.GetDevicesForManualPairingAsync()}))}AddManuallyPairedDevice(e){return Xs(this,void 0,void 0,(function*(){var t;let n=yield hy.Get(_o.ServiceName).AddManuallyPairedDeviceAsync(e);return null===(t=u.Log)||void 0===t||t.Error(Ys.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! AddManuallyPairedDevice()"),yield hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),n}))}GetDeviceChannelStates(e,t){var n,r;return null!==(r=null===(n=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid)))||void 0===n?void 0:n.ChannelsStates.filter((e=>e.Channel==t)))&&void 0!==r?r:[]}GetDeviceStates(e){var t,n;return null!==(n=null===(t=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid)))||void 0===t?void 0:t.ChannelsStates)&&void 0!==n?n:[]}PutDeviceStateOnList(e,t){let n=this._devicesChannelsStates.firstOrDefault((t=>t.DeviceGuid==e.Guid));if(null==n){let r=new Qs;r.Channel=t.Data.Channel,r.States=[t],n={DeviceGuid:e.Guid,ChannelsStates:[r]},this._devicesChannelsStates.push(n)}else{let e=n.ChannelsStates.firstOrDefault((e=>e.Channel==t.Data.Channel));if(null==e)e=new Qs,e.Channel=t.Data.Channel,e.States=[t],n.ChannelsStates.push(e);else{let n=e.States.firstOrDefault((e=>e.Type==t.Type));null!=n&&(n.TypeAsEnum==Pt.BlindErrorState?e.States=e.States.where((e=>e.Data.ErrorCode!=t.Data.ErrorCode)).toArray():e.States=e.States.where((e=>e.Type!=t.Type)).toArray()),e.States.push(t)}}}GetCurrentlyRunningTaksAsync(){return Xs(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new si,15e3,!1);(null==t?void 0:t.Status)==ue.OK&&null!=t.Data&&this.ParseDeviceTaskInfo(t.Data)}))}ParseDeviceTaskInfo(e){const t=[];e.forEach((e=>{const n=e.split(";"),r=new Kt;if(r.DeviceGuid=n[0],r.Channel=Number(n[1]),r.Status=Et.ExecutingTasks,t.push(r),0===r.Channel){const e=this._devices.find((e=>e.Guid==r.DeviceGuid));void 0!==e&&e.Channels.forEach((n=>{const r=new Kt;r.DeviceGuid=e.Guid,r.Channel=n.Number,r.Status=Et.ExecutingTasks,t.push(r)}))}})),this._onDevicesTasksChangedEvent.Invoke(t)}MapApiDeviceStateToDeviceState(e,t){var n;switch(t.state,t.DataType){case"ChannelOnOff":return new In(t);case"DoorBell":return new Pn(t);case"ReedPosition":return new On(t);case"BlindPosition":return new xn(t);case"ButtonState":return new Ln(t);case"LightColor":return new Wn(t);case"LightTemperature":return new Vn(t);case"LightBrightness":return new Hn(t);case"TemperatureSensor":case"TemperatureState":case"MeasuredTemperature":return new jn(t);case"BatteryState":return new Jn(t);case"MeasuredBrightness":case"DeviceBrightnessState":return new Yn(t);case"EnergyMeasuredPower":case"EnergyMeasuredCurrent":case"EnergyMeasuredVoltage":break;case"IEnergy":case"Energy":case"IGetPowerMeasurements":return new Zn(t);case"DistanceSensor":return new tr(t);case"MovementSensor":return new nr(t);case"BlindsControlButton":return new or(t);case"FacadeControlButton":return new ir(t);case"SignalStrength":return new cr(t);case"GatePosition":return new ur(t);case"GatewayPosition":return new dr(t);case"GateControllerHealth":return new hr(t);case"IBlindCalibrationStatus":case"BlindCalibration":return new pr(t);case"HumiditySensor":case"HumidityState":return new gr(t);case"VibrationSensor":return new vr(t);case"DigitalInputSensor":return new yr(t);case"ConfigurationState":return new wr(t);case"BlindOpenCloseTime":case"IBlindOpenCloseTime":return new Sr(t);case"IOvercurrentProtection":case"OvercurrentProtection":return new Ar(t);case"IOvercurrentProtectionThreshold":case"OvercurrentProtectionThreshold":return new _r(t);case"FacadePosition":case"FacadeState":return new Cr(t);case"FacadeTypeState":return new Dr(t);case"CurrentWindThreshold":return new Tr(t);case"CurrentLightThreshold":return new Ir(t);case"WindSpeed":return new Er(t);case"FloodSensor":return new Gr(t);case"PressureState":return new Rr(t);case"ITamperProtection":case"TamperProtection":return new Ur(t);case"ILightRGBW":case"LightRGBW":return new Or(t);case"OnlineCamera":case"IOnlineCamera":return new Rn(t);case"BlindError":case"IBlindError":return t.state.ErrorData=ie(t.state.ErrorData),new Mr(t);case"HallState":return new bn(t);case"SceneExecuted":return new Gn(t);case"Intercom":return new Nn(t);default:null===(n=u.Log)||void 0===n||n.Debug(Ys.ServiceName,`Not supported device state ${t.DataType}`)}return null}GetServiceName(){return Ys.ServiceName}SyncDevicesStatesAsync(){return Xs(this,arguments,void 0,(function*(e=!1){var t,n;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ei,15e3,!1);if(!0!==(yield this.IsFastStatesSyncEnabledAsync())||e){let e=new ti;e.Data=!0;const t=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(e,35e3,!1);return(null==t?void 0:t.Status)==ue.OK}return(null==r?void 0:r.Status)==ue.OK}))}OnDevicesTasksExecutionChangeEvent(){return this._onDevicesTasksChangedEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}OnDeviceStateRefreshedOrChangedEvent(){return this._onDeviceStateRefreshedOrChangedEvent}OnDeviceRegisteredEvent(){return this._onDeviceRegisteredEvent}OnDeviceRemovedEvent(){return this._onDeviceRemovedEvent}OnDeviceFoundEvent(){return this._onDeviceFoundEvent}MapApiDevices(e){const t=[];return null==e?[]:(e.forEach((e=>{var n,r,o,s;let i=new xr;i.Guid=e.Guid,i.Name=e.DeviceName,i.ChannelsAmount=e.ChannelsNumber,i.DeviceType=e.DeviceType,i.CommunicationWay=e.CommunicationWay,i.DeviceState=e.DeviceState,i.IsEnabled=e.IsEnabled,i.IsVirtual=e.IsVirtual,i.SerialNumber=e.DeviceSerialNumber,i.ManufacturerGuid=e.ManufacturerGuid,i.ModelGuid=e.DeviceModelGuid,i.Model=e.DeviceModel,i.Name=e.DeviceName,i.ProtocolGuid=e.ProtocolGuid,void 0!==e.IconType&&null!==e.IconType?i.IconType=e.IconType:i.IconType=Nt.Unknown;try{if(null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{let t=new qt;if(i.CommunicationWay==Ot.OneWay)"IBlindPosition"===e&&(t.InterfaceType="IBlindPositionSimple");else switch(e){case"IGatePosition":t.InterfaceType="IGatePulse";break;case"IGatewayPosition":t.InterfaceType="IGatewayPulse";break;default:t.InterfaceType=e}i.AvailableTaskTypes.push(t)})),null===(r=e.AvailableResponses)||void 0===r||r.forEach((e=>{let t=new Ht;t.InterfaceType=e,i.AvailableResponseTypes.push(t)})),null===(o=e.ChannelsConfiguration)||void 0===o||o.forEach((e=>{var t,n,r;try{let r=new Hr;r.Number=e.Channel,i.Channels.push(r),r.SetDevice(i),r.Name=e.ChannelName,r.ChannelGroups=e.GroupsGuids,r.IconName=e.IconName,r.IsHidden=e.Hidden,r.Configurations=e.Configurations,r.CustomDataAndRolesSupported=void 0!==e.CustomData&&null!==e.CustomData,void 0!==e.CustomData&&null!==e.CustomData&&(r.CustomData=e.CustomData),void 0!==e.Roles&&null!==e.Roles&&(r.Roles=e.Roles),null===(t=e.AvailableResponses)||void 0===t||t.forEach((e=>{let t=new Ht;t.InterfaceType=e,r.AvailableResponseTypes.push(t)})),null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{let t=new qt;i.AvailableTaskTypes.any((e=>"IBlindPositionSimple"==e.InterfaceType))?"IBlindPosition"==e&&(t.InterfaceType="IBlindPositionSimple"):t.InterfaceType=e,r.AvailableTaskTypes.push(t)}))}catch(e){null===(r=u.Log)||void 0===r||r.Error(e)}})),"f4cc5043-2198-47df-9361-4cd130ed0323"===i.ModelGuid&&i.Channels.first().AvailableTaskTypes.all((e=>e.Type!=Rt.GetPowerMeasurements))){let e=new qt;e.InterfaceType="IGetPowerMeasurements",i.Channels.first().AvailableTaskTypes.push(e)}}catch(e){null===(s=u.Log)||void 0===s||s.Error(e)}t.push(i)})),t)}GetPairedDevicesAsync(){return Xs(this,arguments,void 0,(function*(e=!1){var t,n,r;let o=yield null===(t=this._controllerConfiguration)||void 0===t?void 0:t.DidCofigurationChangeAsync();if(this._synchronized&&!o)return e?Promise.resolve(this._devices):Promise.resolve(this._devices.filter((e=>e.DeviceType!=Mt.Scene)));const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Zs,15e3,!0);return null==s||void 0===s?[]:s.Status==ue.OK&&null!=s.Data?(this._devices=this.MapApiDevices(s.Data),e?this._devices:this._devices.filter((e=>e.DeviceType!=Mt.Scene))):(null===(r=u.Log)||void 0===r||r.Error(Ys.ServiceName,`Failed to get devices. ${s.Status} ${s.Data}`),[])}))}GetDevicesAsync(){return Xs(this,arguments,void 0,(function*(e=!1){return yield this.WaitForSynchronizationAsync(),this.GetPairedDevicesAsync(e)}))}GetFoundDevicesAsync(){return Xs(this,void 0,void 0,(function*(){var e,t;const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new oi,15e3,!1);return null==n?[]:n.Status==ue.OK&&null!=n.Data?this.MapApiDevices(n.Data).where((e=>e.DeviceType!==Mt.Scene)).toArray():(null===(t=u.Log)||void 0===t||t.Error(Ys.ServiceName,`Failed to get found devices. ${n.Status} ${n.Data}`),[])}))}GetDevice(e){return this._devices.find((t=>t.Guid===e))}FindDevicesAsync(){return Xs(this,void 0,void 0,(function*(){var e;hy.Get(Be.ServiceName).ClearCache(),yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ni,35e3,!1)}))}StopSearchingForDevices(){return Xs(this,void 0,void 0,(function*(){var e;yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new ri,2e4,!1)}))}RegisterDeviceAsync(e){return Xs(this,void 0,void 0,(function*(){var t,n,r;try{const r=new ii;r.Data=e.Guid;const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(r,2e4,!1);return null===(n=u.Log)||void 0===n||n.Error(Ys.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! RegisterDeviceAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),(null==o?void 0:o.Status)==ue.OK?(this._devices.any((t=>t.Guid==e.Guid))||this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e),Ft.Executed):Ft.Failed}catch(e){return null===(r=u.Log)||void 0===r||r.Error(Ys.ServiceName,`Failed to paired devices: ${e}`),Ft.ControllerResponseTimeout}}))}RemoveDeviceAsync(e){return Xs(this,arguments,void 0,(function*(e,t=!1){var n,r,o;try{let o=new ai;t&&(o=new ci),o.Data=e.Guid;const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(o,35e3,!1);return null===(r=u.Log)||void 0===r||r.Error(Ys.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! RemoveDeviceAsync()"),hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),(null==s?void 0:s.Status)==ue.OK?(this._devices=this._devices.where((t=>t.Guid!=e.Guid)).toArray(),this._onDeviceRemovedEvent.Invoke(e),Ft.Executed):Ft.Failed}catch(e){return null===(o=u.Log)||void 0===o||o.Error(Ys.ServiceName,`Failed to unpair device: ${e}`),Ft.ControllerResponseTimeout}}))}MapDeviceTaskToDeviceTaskInfo(e,t){let n=new hi;const r=t;switch(r.FeatureType){case Br.SetTemperature:n.Data=r.Temperature;break;case Br.SetLightBrightness:n.Data=r.Brightness;break;case Br.SetLightColor:n=new pi;const e=r;n.R=e.R,n.G=e.G,n.B=e.B;break;case Br.SetLightTemperature:n.Data=r.Temperature;break;case Br.SetGatePositionPrecise:switch(r.GateControlAction){case $r.Open:n.Data=101;break;case $r.Close:n.Data=102;break;case $r.Stop:n.Data=103;break;case $r.Percentage:n.Data=r.Position}break;case Br.SetGatePositionPreciseSecure:let t=0,o=r.Pin;switch(r.GateControlAction){case $r.Open:t=101;break;case $r.Close:t=102;break;case $r.Stop:t=103;break;case $r.Percentage:t=r.Position}n.Data={Position:t,Pin:o};break;case Br.SetBlindPosition:switch(r.Action){case Wr.Open:n.Data=101;break;case Wr.Close:n.Data=102;break;case Wr.Stop:n.Data=103;break;case Wr.Percentage:n.Data=r.Position}break;case Br.SetLightBrightnessDynamicly:n.Data=r.Brightness;break;case Br.SetBlindOpenCloseTime:n.Data=r.Data;break;case Br.SetBlindMicroventilation:n.Data=r.Position;break;case Br.SetFacadePositionAndTilt:n=new gi;const s=r;n.FacadeAction=s.FacadeAction,n.Tilt=s.Tilt,n.Position=s.Position;break;case Br.LightRGBW:n.Data=r.Data;break;case Br.GatePulse:case Br.GatewayPulse:n.Data=0;break;case Br.TurnOnWithTimeout:n.Data=r.SwitchOffDelaySeconds}return n.Channel=r.Channel,n.DeviceGuid=e.Guid,n.ControlFeature=r.FeatureType,n}ExecuteDeviceTaskAsync(e,t){return Xs(this,void 0,void 0,(function*(){var n,r,o,s,i,a,c,l;try{null===(n=u.Log)||void 0===n||n.Debug(Ys.ServiceName,`Preparing device task execution, device: ${e.Guid} task: ${t.TaskType} channel: ${t.Channel}`);let l=this.MapDeviceTaskToDeviceTaskInfo(e,t);try{const e=new ui(l);null===(r=u.Log)||void 0===r||r.Debug(Ys.ServiceName,`Sending device task for execution, device: ${l.DeviceGuid} task: ${l.ControlFeature} channel: ${l.Channel} request: ${JSON.stringify(e)}`);const t=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(e,15e3,!1);switch(null==t?void 0:t.Status){case ue.OK:return Ft.Executed;case ue.FatalError:return null===(s=u.Log)||void 0===s||s.Error(Ys.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),Ft.Failed;case ue.WrongData:if("DeviceNotFound"===t.Data)return Ft.DeviceNotFound;break;case ue.Error:return"DeviceResponseTimeout"===t.Data?Ft.DeviceResponseTimeout:(null===(i=u.Log)||void 0===i||i.Error(Ys.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${t.Data}`),Ft.Failed)}}catch(e){return e.message.includes("timeout")?(null===(a=u.Log)||void 0===a||a.Error(Ys.ServiceName,`Failed to get controller response in time.\n${e}`),Ft.ControllerResponseTimeout):(null===(c=u.Log)||void 0===c||c.Error(Ys.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),Ft.Failed)}return Ft.Unknown}catch(e){return null===(l=u.Log)||void 0===l||l.Error(Ys.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),Ft.Failed}}))}ExecuteDevicesTasksAsync(e){return Xs(this,void 0,void 0,(function*(){var t,n,r,o;let s=[],i=[],a=0;for(const[t,n]of e){const e=this.MapDeviceTaskToDeviceTaskInfo(t,n);e.SequnceExecutionOrder=a,a++,i.push(e)}const c=new li(i);try{const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(c,12e4,!1);let o=-1;null===(n=null==r?void 0:r.Data)||void 0===n||n.forEach((t=>{var n,i;o++;let a=Ft.Unknown;switch(t.Status){case ue.OK:a=Ft.Executed;break;case ue.FatalError:null===(n=u.Log)||void 0===n||n.Error(Ys.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),a=Ft.Failed;break;case ue.WrongData:"DeviceNotFound"===t.Data&&(a=Ft.DeviceNotFound);break;case ue.Error:"DeviceResponseTimeout"===t.Data?a=Ft.DeviceResponseTimeout:(null===(i=u.Log)||void 0===i||i.Error(Ys.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${r.Data}`),a=Ft.Failed)}let c=0,l=new jt;for(const[t,n]of e){if(c==o){l.Device=t,l.Task=n,l.Channel=n.Channel,l.Result=a,s.push(l);break}c++}}))}catch(t){if(t.message.includes("timeout")){null===(r=u.Log)||void 0===r||r.Error(Ys.ServiceName,`Failed to get controller response in time.\n${t}`);for(const[t,n]of e){let e=new jt;s.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=Ft.ControllerResponseTimeout}}else{null===(o=u.Log)||void 0===o||o.Error(Ys.ServiceName,`Unknown error occured when tried to execute task on device.\n${t}`);for(const[t,n]of e){let e=new jt;s.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=Ft.Failed}}}return s}))}}Ys.ServiceName="DevicesService";class Qs{constructor(){this.Channel=0,this.States=[]}}class Zs extends ce{constructor(){super(),this.Resource="/devices/list",this.Method=le.Get}}class ei extends ce{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states",this.Method=le.Get}}class ti extends ce{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states/sync",this.Method=le.Get}}class ni extends ce{constructor(){super(),this.Resource="/devices/search",this.Method=le.Post}}class ri extends ce{constructor(){super(),this.Resource="/devices/search/stop",this.Method=le.Post}}class oi extends ce{constructor(){super(),this.Resource="/devices/found/list",this.Method=le.Get}}class si extends ce{constructor(){super(),this.Resource="/devices/tasks",this.Method=le.Get}}class ii extends ce{constructor(){super(),this.Resource="/devices/device/pair",this.Method=le.Put}}class ai extends ce{constructor(){super(),this.Resource="/devices/device/unpair",this.Method=le.Put}}class ci extends ce{constructor(){super(),this.Resource="/devices/device/unpair/force",this.Method=le.Put}}class ui extends ce{constructor(e){super(),this.Resource="/devices/device/control",this.Method=le.Post,this.Data=e}}class li extends ce{constructor(e){super(),this.Resource="/devices/devices/control",this.Method=le.Post,this.Data=e}}class di extends ce{constructor(e){super(),this.Resource="/logic/device/used",this.Method=le.Get,this.Data=e}}class hi{constructor(){this.DeviceGuid="",this.Channel=0,this.ControlFeature=Br.GetState,this.SequnceExecutionOrder=0}}class pi extends hi{constructor(){super(...arguments),this.R=0,this.G=0,this.B=0}}class gi extends hi{constructor(){super(...arguments),this.FacadeAction=qr.Stop,this.Tilt=0,this.Position=0}}class fi{constructor(){this.DeviceGuid="",this.ConditionsAsCondition=[],this.ConditionsAsTask=[]}}class vi extends RangeError{paramName;constructor(e){super(`${e} was out of range. Must be non-negative and less than the size of the collection.`),this.paramName=e,this.name="ArgumentOutOfRangeException",this.stack=this.stack||(new Error).stack}}const yi=Object.freeze({MoreThanOneElement:"Sequence contains more than one element",MoreThanOneMatchingElement:"Sequence contains more than one matching element",NoElements:"Sequence contains no elements",NoMatch:"Sequence contains no matching element"});class mi extends Error{constructor(e){super(e),this.name="InvalidOperationException",this.stack=this.stack||(new Error).stack}}const wi=(e,t)=>e===t;class Si{iterator;constructor(e){this.iterator=e}[Symbol.asyncIterator](){return this.iterator()}}class Ai{dataFunc;constructor(e){this.dataFunc=e}[Symbol.asyncIterator](){const{dataFunc:e}=this;return async function*(){if(1===e.type)for(const t of e.generator())yield t;else for(const t of await e.generator())yield t}()}}class _i{iterator;constructor(e){this.iterator=e}[Symbol.iterator](){return this.iterator()}}class Ci extends Array{}const Di=(e,t,n,r)=>{if(r){if(!n)throw new ReferenceError("TAccumulate function is undefined");return Ii(e,t,n,r)}return n?ki(e,t,n):Ti(e,t)},Ti=(e,t)=>{let n;for(const r of e)n=n?t(n,r):r;if(void 0===n)throw new mi(yi.NoElements);return n},ki=(e,t,n)=>{let r=t;for(const t of e)r=n(r,t);return r},Ii=(e,t,n,r)=>{let o=t;for(const t of e)o=n(o,t);return r(o)},Ei=(e,t)=>{for(const n of e)if(!1===t(n))return!1;return!0},bi=async(e,t)=>{for(const n of e)if(!1===await t(n))return!1;return!0},Gi=(e,t)=>t?Ri(e,t):Ni(e),Ni=e=>{for(const t of e)return!0;return!1},Ri=(e,t)=>{for(const n of e)if(!0===t(n))return!0;return!1},Pi=async(e,t)=>{for(const n of e)if(!0===await t(n))return!0;return!1},Ui=(e,t)=>new _i((function*(){yield*e,yield t})),Oi=e=>{if(Array.isArray(e)){if(0===e.length)throw new mi(yi.NoElements);return new Si((async function*(){for await(const t of e)yield t}))}return new Si(e)},Mi=e=>Oi((async function*(){for(const t of e)yield t})),xi=(e,t)=>new Ai({generator:t,type:e}),Fi=e=>xi(0,(async()=>{const t=[];for(const n of e)t.push(n);return t})),Li=(e,t)=>{let n=0,r=0;if(t)for(const o of e)n+=t(o),r+=1;else for(const t of e)n+=t,r+=1;if(0===r)throw new mi(yi.NoElements);return n/r},Bi=async(e,t)=>{let n=0,r=0;for(const o of e)n+=await t(o),r+=1;if(0===r)throw new mi(yi.NoElements);return n/r},Wi=(e,t)=>{if(t<1)throw new vi("size");return new _i((function*(){let n=[];for(const r of e)n.push(r),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},$i=(e,t)=>new _i((function*(){yield*e,yield*t})),Vi=(e,t,n=wi)=>{for(const r of e)if(n(t,r))return!0;return!1},qi=async(e,t,n)=>{for(const r of e)if(await n(t,r))return!0;return!1},Hi=(e,t)=>t?ji(e,t):Ki(e),Ki=e=>{let t=0;for(const n of e)t++;return t},ji=(e,t)=>{let n=0;for(const r of e)!0===t(r)&&n++;return n},zi=async(e,t)=>{let n=0;for(const r of e)!0===await t(r)&&n++;return n},Ji=(e,t)=>new _i((function*(){let n=!1;for(const t of e)n=!0,yield t;n||(yield t)})),Xi=(e,t=wi)=>new _i((function*(){const n=[];for(const r of e)n.find((e=>t(e,r)))||(n.push(r),yield r)})),Yi=(e,t)=>Oi((async function*(){const n=[];e:for(const r of e){for(const e of n)if(await t(e,r))continue e;n.push(r),yield r}})),Qi=(e,t)=>new _i((function*(){for(const n of e)t(n),yield n})),Zi=(e,t)=>Oi((async function*(){for(const n of e)await t(n),yield n})),ea=(e,t)=>{if(t<0)throw new vi("index");let n=0;for(const r of e)if(t===n++)return r;throw new vi("index")},ta=(e,t)=>{let n=0;for(const r of e)if(t===n++)return r;return null},na=(e,t,n=wi)=>new _i((function*(){const r=[...t];for(const t of e){let e=!1;for(let o=0;o<r.length;o++)if(!0===n(t,r[o])){e=!0;break}!1===e&&(yield t)}})),ra=(e,t,n)=>Oi((async function*(){const r=[...t];for(const t of e){let e=!1;for(let o=0;o<r.length;o++){const s=r[o];if(!0===await n(t,s)){e=!0;break}}!1===e&&(yield t)}})),oa=(e,t)=>t?ia(e,t):sa(e),sa=e=>{const t=e[Symbol.iterator]().next();if(!0===t.done)throw new mi(yi.NoElements);return t.value},ia=(e,t)=>{for(const n of e)if(!0===t(n))return n;throw new mi(yi.NoMatch)},aa=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;throw new mi(yi.NoMatch)},ca=(e,t)=>t?la(e,t):ua(e),ua=e=>e[Symbol.iterator]().next().value??null,la=(e,t)=>{for(const n of e)if(!0===t(n))return n;return null},da=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;return null};class ha extends Ci{key;constructor(e,t){super(1),this.key=e,this[0]=t}}const pa=(e,t,n)=>{let r;return r=n?((e,t,n)=>function*(){const r=new Array;for(const o of e){const e=t(o);let s=!1;for(let t=0;t<r.length;t++){const i=r[t];if(n(i.key,e)){i.push(o),s=!0;break}}!1===s&&r.push(new ha(e,o))}for(const e of r)yield e})(e,t,n):((e,t)=>function*(){const n={};for(const r of e){const e=t(r),o=n[e];o?o.push(r):n[e]=new ha(e,r)}for(const e in n)yield n[e]})(e,t),new _i(r)},ga=(e,t,n)=>n?va(e,t,n):fa(e,t),fa=(e,t)=>Oi((async function*(){const n={};for(const r of e){const e=await t(r),o=n[e];o?o.push(r):n[e]=new ha(e,r)}for(const e in n)yield n[e]})),va=(e,t,n)=>Oi((async function*(){const r=new Array;for(const o of e){const e=await t(o);let s=!1;for(let t=0;t<r.length;t++){const i=r[t];if(!0===await n(i.key,e)){i.push(o),s=!0;break}}!1===s&&r.push(new ha(e,o))}for(const e of r)yield e})),ya=(e,t,n,r)=>r?((e,t,n,r)=>new _i((function*(){const o=new Array;for(const s of e){const e=t(s);let i=!1;for(let t=0;t<o.length;t++){const a=o[t];if(r(a.key,e)){a.push(n(s)),i=!0;break}}if(!1===i){const t=n(s);o.push(new ha(e,t))}}for(const e of o)yield e})))(e,t,n,r):((e,t,n)=>new _i((function*(){const r={};for(const o of e){const e=t(o),s=r[e],i=n(o);s?s.push(i):r[e]=new ha(e,i)}for(const e in r)yield r[e]})))(e,t,n),ma=(e,t,n,r,o,s)=>{const i=s?wa(e,t,n,r,o,s):Sa(e,t,n,r,o);return new _i(i)},wa=(e,t,n,r,o,s)=>function*(){const i=[];for(const e of t){const t=r(e),n=i.find((e=>s(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for(const t of e){const e=n(t),r=i.find((t=>s(t.key,e)))??{key:e,values:[]};yield o(t,r.values)}},Sa=(e,t,n,r,o)=>function*(){const s=new Map;for(const e of t){const t=r(e),n=s.get(t);n?n.push(e):s.set(t,[e])}for(const t of e){const e=n(t),r=s.get(e)??[];yield o(t,r)}},Aa=(e,t,n,r,o,s)=>{const i=s?_a(e,t,n,r,o,s):Ca(e,t,n,r,o);return Oi(i)},_a=(e,t,n,r,o,s)=>async function*(){const i=[];for(const e of t){const t=await r(e),n=i.find((e=>s(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for(const t of e){const e=await n(t),r=i.find((t=>s(t.key,e)))??{key:e,values:[]};yield o(t,r.values)}},Ca=(e,t,n,r,o)=>async function*(){const s=new Map;for(const e of t){const t=await r(e),n=s.get(t);n?n.push(e):s.set(t,[e])}for(const t of e){const e=await n(t),r=s.get(e)??[];yield o(t,r)}},Da=(e,t,n=wi)=>new _i((function*(){const r=[...e.distinct(n)];if(0===r.length)return;const o=[...t];for(let e=0;e<r.length;e++){const t=r[e];for(let e=0;e<o.length;e++)if(!0===n(t,o[e])){yield t;break}}})),Ta=(e,t,n)=>Oi((async function*(){const r=[];for await(const t of e.distinctAsync(n))r.push(t);if(0===r.length)return;const o=[...t];for(let e=0;e<r.length;e++){const t=r[e];for(let e=0;e<o.length;e++){const r=o[e];if(!0===await n(t,r)){yield t;break}}}})),ka=(e,t,n,r,o,s=wi)=>new _i((function*(){const i=[...t];for(const t of e){const e=n(t);for(const n of i){const i=r(n);!0===s(e,i)&&(yield o(t,n))}}})),Ia=(e,t)=>t?ba(e,t):Ea(e),Ea=e=>{let t;for(const n of e)t=n;if(!t)throw new mi(yi.NoElements);return t},ba=(e,t)=>{let n;for(const r of e)!0===t(r)&&(n=r);if(!n)throw new mi(yi.NoMatch);return n},Ga=async(e,t)=>{let n;for(const r of e)!0===await t(r)&&(n=r);if(!n)throw new mi(yi.NoMatch);return n},Na=(e,t)=>t?Pa(e,t):Ra(e),Ra=e=>{let t=null;for(const n of e)t=n;return t},Pa=(e,t)=>{let n=null;for(const r of e)!0===t(r)&&(n=r);return n},Ua=async(e,t)=>{let n=null;for(const r of e)!0===await t(r)&&(n=r);return n},Oa=(e,t)=>t?xa(e,t):Ma(e),Ma=e=>{let t=null;for(const n of e)t=Math.max(t??Number.NEGATIVE_INFINITY,n);if(null===t)throw new mi(yi.NoElements);return t},xa=(e,t)=>{let n=null;for(const r of e)n=Math.max(n??Number.NEGATIVE_INFINITY,t(r));if(null===n)throw new mi(yi.NoElements);return n},Fa=async(e,t)=>{let n=null;for(const r of e)n=Math.max(n??Number.NEGATIVE_INFINITY,await t(r));if(null===n)throw new mi(yi.NoElements);return n},La=(e,t)=>t?Wa(e,t):Ba(e),Ba=e=>{let t=null;for(const n of e)t=Math.min(t??Number.POSITIVE_INFINITY,n);if(null===t)throw new mi(yi.NoElements);return t},Wa=(e,t)=>{let n=null;for(const r of e)n=Math.min(n??Number.POSITIVE_INFINITY,t(r));if(null===n)throw new mi(yi.NoElements);return n},$a=async(e,t)=>{let n=null;for(const r of e)n=Math.min(n??Number.POSITIVE_INFINITY,await t(r));if(null===n)throw new mi(yi.NoElements);return n},Va=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new _i((function*(){for(const t of e)n(t)&&(yield t)}))};async function*qa(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for(const r of e){const e=await t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}function*Ha(e,t,n,r){const o=((e,t)=>{const n=new Map;for(const r of e){const e=t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}class Ka extends Si{orderedPairs;constructor(e){super((async function*(){for await(const t of e())yield*t})),this.orderedPairs=e}static generateAsync(e,t,n,r){let o;return o=e instanceof Ka?async function*(){for await(const o of e.orderedPairs())yield*qa(o,t,n,r)}:()=>async function*(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for await(const r of e){const e=await t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}(e,t,n,r),new Ka(o)}static generate(e,t,n,r){let o;return o=e instanceof Ka?async function*(){for await(const o of e.orderedPairs())yield*Ha(o,t,n,r)}:()=>async function*(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for await(const r of e){const e=t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}(e,t,n,r),new Ka(o)}thenBy(e,t){return Ka.generate(this,e,!0,t)}thenByAsync(e,t){return Ka.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Ka.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Ka.generateAsync(this,e,!1,t)}}function*ja(e,t,n,r){const o=((e,t)=>{const n=new Map;for(const r of e){const e=t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}async function*za(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for(const r of e){const e=await t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}class Ja extends _i{orderedPairs;constructor(e){super((function*(){for(const t of e())yield*t})),this.orderedPairs=e}static generate(e,t,n,r){let o;return o=e instanceof Ja?function*(){for(const o of e.orderedPairs())yield*ja(o,t,n,r)}:()=>ja(e,t,n,r),new Ja(o)}static generateAsync(e,t,n,r){let o;return o=e instanceof Ja?async function*(){for(const o of e.orderedPairs())yield*za(o,t,n,r)}:()=>za(e,t,n,r),new Ka(o)}thenBy(e,t){return Ja.generate(this,e,!0,t)}thenByAsync(e,t){return Ja.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Ja.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Ja.generateAsync(this,e,!1,t)}}const Xa=(e,t)=>Ja.generate(e,(e=>e),!0,t),Ya=(e,t,n)=>Ja.generate(e,t,!0,n),Qa=(e,t,n)=>Ja.generateAsync(e,t,!0,n),Za=(e,t,n)=>Ja.generate(e,t,!1,n),ec=(e,t,n)=>Ja.generateAsync(e,t,!1,n),tc=(e,t)=>Ja.generate(e,(e=>e),!1,t),nc=(e,t)=>{const n=[],r=[];for(const o of e)!0===t(o)?r.push(o):n.push(o);return[r,n]},rc=async(e,t)=>{const n=[],r=[];for(const o of e)!0===await t(o)?r.push(o):n.push(o);return[r,n]},oc=(e,t)=>new _i((function*(){yield t,yield*e})),sc=e=>new _i((function*(){const t=[...e];for(let e=t.length-1;e>=0;e--)yield t[e]})),ic=(e,t)=>{if("function"==typeof t){const{length:n}=t;return 1===n?ac(e,t):cc(e,t)}return uc(e,t)},ac=(e,t)=>new _i((function*(){for(const n of e)yield t(n)})),cc=(e,t)=>new _i((function*(){let n=0;for(const r of e)yield t(r,n),n++})),uc=(e,t)=>new _i((function*(){for(const n of e)yield n[t]})),lc=(e,t)=>"function"==typeof t?1===t.length?dc(e,t):hc(e,t):pc(e,t),dc=(e,t)=>Oi((async function*(){for(const n of e)yield t(n)})),hc=(e,t)=>Oi((async function*(){let n=0;for(const r of e)yield t(r,n),n++})),pc=(e,t)=>Oi((async function*(){for(const n of e)yield n[t]})),gc=(e,t)=>"function"==typeof t?1===t.length?fc(e,t):vc(e,t):yc(e,t),fc=(e,t)=>new _i((function*(){for(const n of e)for(const e of t(n))yield e})),vc=(e,t)=>new _i((function*(){let n=0;for(const r of e){for(const e of t(r,n))yield e;n++}})),yc=(e,t)=>new _i((function*(){for(const n of e)for(const e of n[t])yield e})),mc=(e,t)=>1===t.length?wc(e,t):Sc(e,t),wc=(e,t)=>Oi((async function*(){for(const n of e){const e=await t(n);for(const t of e)yield t}})),Sc=(e,t)=>Oi((async function*(){let n=0;for(const r of e){const e=await t(r,n);for(const t of e)yield t;n++}})),Ac=(e,t,n=wi)=>{const r=e[Symbol.iterator](),o=t[Symbol.iterator]();let s=r.next(),i=o.next();for(;!s.done&&!i.done;){if(!n(s.value,i.value))return!1;s=r.next(),i=o.next()}return!0===s.done&&!0===i.done},_c=async(e,t,n)=>{const r=e[Symbol.iterator](),o=t[Symbol.iterator]();let s=r.next(),i=o.next();for(;!s.done&&!i.done;){if(!1===await n(s.value,i.value))return!1;s=r.next(),i=o.next()}return!0===s.done&&!0===i.done},Cc=(e,t)=>t?Tc(e,t):Dc(e),Dc=e=>{let t=!1,n=null;for(const r of e){if(!0===t)throw new mi(yi.MoreThanOneElement);t=!0,n=r}if(!1===t)throw new mi(yi.NoElements);return n},Tc=(e,t)=>{let n=!1,r=null;for(const o of e)if(t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new mi(yi.NoMatch);return r},kc=async(e,t)=>{let n=!1,r=null;for(const o of e)if(await t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new mi(yi.NoMatch);return r},Ic=(e,t)=>t?bc(e,t):Ec(e),Ec=e=>{let t=!1,n=null;for(const r of e){if(!0===t)throw new mi(yi.MoreThanOneElement);t=!0,n=r}return n},bc=(e,t)=>{let n=!1,r=null;for(const o of e)if(t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}return r},Gc=async(e,t)=>{let n=!1,r=null;for(const o of e)if(await t(o)){if(!0===n)throw new mi(yi.MoreThanOneElement);n=!0,r=o}return r},Nc=(e,t)=>new _i((function*(){let n=0;for(const r of e)n++>=t&&(yield r)})),Rc=(e,t)=>1===t.length?Pc(e,t):Uc(e,t),Pc=(e,t)=>new _i((function*(){let n=!0;for(const r of e)!1===n?yield r:!1===t(r)&&(n=!1,yield r)})),Uc=(e,t)=>new _i((function*(){let n=0,r=!0;for(const o of e)!1===r?yield o:!1===t(o,n)&&(r=!1,yield o),n++})),Oc=(e,t)=>1===t.length?Mc(e,t):xc(e,t),Mc=(e,t)=>Oi((async function*(){let n=!0;for(const r of e)!1===n?yield r:!1===await t(r)&&(n=!1,yield r)})),xc=(e,t)=>Oi((async function*(){let n=0,r=!0;for(const o of e)!1===r?yield o:!1===await t(o,n)&&(r=!1,yield o),n++})),Fc=(e,t)=>t?Bc(e,t):Lc(e),Lc=e=>{let t=0;for(const n of e)t+=n;return t},Bc=(e,t)=>{let n=0;for(const r of e)n+=t(r);return n},Wc=async(e,t)=>{let n=0;for(const r of e)n+=await t(r);return n},$c=(e,t)=>new _i((function*(){let n=t>0?t:0;for(const t of e){if(0==n--)break;yield t}})),Vc=(e,t)=>1===t.length?qc(e,t):Hc(e,t),qc=(e,t)=>new _i((function*(){for(const n of e){if(!t(n))break;yield n}})),Hc=(e,t)=>new _i((function*(){let n=0;for(const r of e){if(!t(r,n++))break;yield r}})),Kc=(e,t)=>1===t.length?jc(e,t):zc(e,t),jc=(e,t)=>Oi((async function*(){for(const n of e){if(!await t(n))break;yield n}})),zc=(e,t)=>Oi((async function*(){let n=0;for(const r of e){if(!await t(r,n++))break;yield r}})),Jc=e=>[...e],Xc=(e,t)=>{const n=new Map;for(const r of e){const e=t(r),o=n.get(e);void 0===o?n.set(e,[r]):o.push(r)}return n},Yc=async(e,t)=>{const n=new Map;for(const r of e){const e=await t(r),o=n.get(e);void 0===o?n.set(e,[r]):o.push(r)}return n},Qc=(e,t)=>{const n={};for(const r of e)n[t(r)]=r;return n},Zc=async(e,t)=>{const n={};for(const r of e)n[await t(r)]=r;return n},eu=e=>new Set(e),tu=(e,t,n)=>n?ru(e,t,n):nu(e,t),nu=(e,t)=>new _i((function*(){const n=new Set;for(const t of e)!1===n.has(t)&&(yield t,n.add(t));for(const e of t)!1===n.has(e)&&(yield e,n.add(e))})),ru=(e,t,n)=>new _i((function*(){const r=[];for(const o of[e,t])for(const e of o){let t=!1;for(const o of r)if(!0===n(e,o)){t=!0;break}!1===t&&(yield e,r.push(e))}})),ou=(e,t,n)=>Oi((async function*(){const r=[];for(const o of[e,t])for(const e of o){let t=!1;for(const o of r)if(!0===await n(e,o)){t=!0;break}!1===t&&(yield e,r.push(e))}})),su=(e,t)=>1===t.length?iu(e,t):au(e,t),iu=(e,t)=>new _i((function*(){for(const n of e)!0===t(n)&&(yield n)})),au=(e,t)=>new _i((function*(){let n=0;for(const r of e)!0===t(r,n++)&&(yield r)})),cu=(e,t)=>1===t.length?uu(e,t):lu(e,t),uu=(e,t)=>Oi((async function*(){for(const n of e)!0===await t(n)&&(yield n)})),lu=(e,t)=>Oi((async function*(){let n=0;for(const r of e)!0===await t(r,n++)&&(yield r)})),du=(e,t,n)=>n?pu(e,t,n):hu(e,t),hu=(e,t)=>new _i((function*(){const n=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=n.next(),t=r.next();if(e.done||t.done)break;yield[e.value,t.value]}})),pu=(e,t,n)=>new _i((function*(){const r=e[Symbol.iterator](),o=t[Symbol.iterator]();for(;;){const e=r.next(),t=o.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),gu=(e,t,n)=>Oi((async function*(){const r=e[Symbol.iterator](),o=t[Symbol.iterator]();for(;;){const e=r.next(),t=o.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),fu=e=>{const t=e.prototype,n=(e,n)=>{const r=function(...t){return e(this,...t)};Object.defineProperty(r,"length",{value:e.length-1}),t[n]=r};n(Di,"aggregate"),n(Ei,"all"),n(bi,"allAsync"),n(Gi,"any"),n(Pi,"anyAsync"),n(Ui,"append"),n(Mi,"asAsync"),n(Fi,"asParallel"),n(Li,"average"),n(Bi,"averageAsync"),n(Wi,"chunk"),n($i,"concatenate"),n(Vi,"contains"),n(qi,"containsAsync"),n(Hi,"count"),n(zi,"countAsync"),n(Ji,"defaultIfEmpty"),n(Xi,"distinct"),n(Yi,"distinctAsync"),n(Qi,"each"),n(Zi,"eachAsync"),n(ea,"elementAt"),n(ta,"elementAtOrDefault"),n(na,"except"),n(ra,"exceptAsync"),n(oa,"first"),n(aa,"firstAsync"),n(ca,"firstOrDefault"),n(da,"firstOrDefaultAsync"),n(pa,"groupBy"),n(ga,"groupByAsync"),n(ya,"groupByWithSel"),n(ma,"groupJoin"),n(Aa,"groupJoinAsync"),n(Da,"intersect"),n(Ta,"intersectAsync"),n(ka,"joinByKey"),n(Ia,"last"),n(Ga,"lastAsync"),n(Na,"lastOrDefault"),n(Ua,"lastOrDefaultAsync"),n(Oa,"max"),n(Fa,"maxAsync"),n(La,"min"),n($a,"minAsync"),n(Va,"ofType"),n(Xa,"order"),n(Ya,"orderBy"),n(Qa,"orderByAsync"),n(Za,"orderByDescending"),n(ec,"orderByDescendingAsync"),n(tc,"orderDescending"),n(oc,"prepend"),n(sc,"reverse"),n(ic,"select"),n(lc,"selectAsync"),n(gc,"selectMany"),n(mc,"selectManyAsync"),n(Ac,"sequenceEquals"),n(_c,"sequenceEqualsAsync"),n(Cc,"single"),n(kc,"singleAsync"),n(Ic,"singleOrDefault"),n(Gc,"singleOrDefaultAsync"),n(Nc,"skip"),n(Rc,"skipWhile"),n(Oc,"skipWhileAsync"),n(Fc,"sum"),n(Wc,"sumAsync"),n($c,"take"),n(Vc,"takeWhile"),n(Kc,"takeWhileAsync"),n(Jc,"toArray"),n(Xc,"toMap"),n(Yc,"toMapAsync"),n(Qc,"toObject"),n(Zc,"toObjectAsync"),n(nc,"partition"),n(rc,"partitionAsync"),n(eu,"toSet"),n(tu,"union"),n(ou,"unionAsync"),n(su,"where"),n(cu,"whereAsync"),n(du,"zip"),n(gu,"zipAsync")},vu=(e,t,n,r)=>{if(r){if(!n)throw new ReferenceError("TAccumulate function is undefined");return wu(e,t,n,r)}return n?mu(e,t,n):yu(e,t)},yu=async(e,t)=>{let n;for await(const r of e)n=n?t(n,r):r;if(void 0===n)throw new mi(yi.NoElements);return n},mu=async(e,t,n)=>{let r=t;for await(const t of e)r=n(r,t);return r},wu=async(e,t,n,r)=>{let o=t;for await(const t of e)o=n(o,t);return r(o)},Su=async(e,t)=>{for await(const n of e)if(!1===t(n))return!1;return!0},Au=async(e,t)=>{for await(const n of e)if(!1===await t(n))return!1;return!0},_u=(e,t)=>new Si((async function*(){yield*e,yield t})),Cu=(e,t)=>t?Tu(e,t):Du(e),Du=async e=>{for await(const t of e)return!0;return!1},Tu=async(e,t)=>{for await(const n of e)if(!0===t(n))return!0;return!1},ku=async(e,t)=>{for await(const n of e)if(!0===await t(n))return!0;return!1},Iu=e=>xi(0,(async()=>{const t=[];for await(const n of e)t.push(n);return t})),Eu=async(e,t)=>{let n=0,r=0;if(t)for await(const o of e)n+=t(o),r+=1;else for await(const t of e)n+=t,r+=1;if(0===r)throw new mi(yi.NoElements);return n/r},bu=async(e,t)=>{let n=0,r=0;for await(const o of e)n+=await t(o),r+=1;if(0===r)throw new mi(yi.NoElements);return n/r},Gu=(e,t)=>{if(t<1)throw new vi("size");return new Si((async function*(){let n=[];for await(const r of e)n.push(r),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},Nu=(e,t)=>new Si((async function*(){yield*e,yield*t})),Ru=async(e,t,n=wi)=>{for await(const r of e)if(n(t,r))return!0;return!1},Pu=async(e,t,n)=>{for await(const r of e)if(await n(t,r))return!0;return!1},Uu=(e,t)=>t?Mu(e,t):Ou(e),Ou=async e=>{let t=0;for await(const n of e)t++;return t},Mu=async(e,t)=>{let n=0;for await(const r of e)!0===t(r)&&n++;return n},xu=async(e,t)=>{let n=0;for await(const r of e)!0===await t(r)&&n++;return n},Fu=(e,t)=>new Si((async function*(){let n=!1;for await(const t of e)n=!0,yield t;n||(yield t)})),Lu=(e,t=wi)=>new Si((async function*(){const n=[];for await(const r of e)n.find((e=>t(e,r)))||(n.push(r),yield r)})),Bu=(e,t)=>new Si((async function*(){const n=[];e:for await(const r of e){for(const e of n)if(await t(e,r))continue e;n.push(r),yield r}})),Wu=(e,t)=>new Si((async function*(){for await(const n of e)t(n),yield n})),$u=(e,t)=>new Si((async function*(){for await(const n of e)await t(n),yield n})),Vu=async(e,t)=>{if(t<0)throw new vi("index");let n=0;for await(const r of e)if(t===n++)return r;throw new vi("index")},qu=async(e,t)=>{let n=0;for await(const r of e)if(t===n++)return r;return null},Hu=(e,t,n=wi)=>new Si((async function*(){const r=[];for await(const e of t)r.push(e);for await(const t of e){let e=!1;for(let o=0;o<r.length;o++){const s=r[o];if(!0===n(t,s)){e=!0;break}}!1===e&&(yield t)}})),Ku=(e,t,n)=>new Si((async function*(){const r=[];for await(const e of t)r.push(e);for await(const t of e){let e=!1;for(let o=0;o<r.length;o++){const s=r[o];if(!0===await n(t,s)){e=!0;break}}!1===e&&(yield t)}})),ju=(e,t)=>t?Ju(e,t):zu(e),zu=async e=>{const t=await e[Symbol.asyncIterator]().next();if(!0===t.done)throw new mi(yi.NoElements);return t.value},Ju=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;throw new mi(yi.NoMatch)},Xu=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;throw new mi(yi.NoMatch)},Yu=(e,t)=>t?Zu(e,t):Qu(e),Qu=async e=>(await e[Symbol.asyncIterator]().next()).value??null,Zu=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;return null},el=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;return null},tl=(e,t,n)=>n?nl(e,t,n):rl(e,t),nl=(e,t,n)=>new Si((async function*(){const r=new Array;for await(const o of e){const e=t(o);let s=!1;for(let t=0;t<r.length;t++){const i=r[t];if(n(i.key,e)){i.push(o),s=!0;break}}!1===s&&r.push(new ha(e,o))}for(const e of r)yield e})),rl=(e,t)=>new Si((async function*(){const n={};for await(const r of e){const e=t(r),o=n[e];o?o.push(r):n[e]=new ha(e,r)}for(const e in n)yield n[e]})),ol=(e,t,n)=>n?il(e,t,n):sl(e,t),sl=(e,t)=>new Si((async function*(){const n={};for await(const r of e){const e=await t(r),o=n[e];o?o.push(r):n[e]=new ha(e,r)}for(const e in n)yield n[e]})),il=(e,t,n)=>new Si((async function*(){const r=new Array;for await(const o of e){const e=await t(o);let s=!1;for(let t=0;t<r.length;t++){const i=r[t];if(!0===await n(i.key,e)){i.push(o),s=!0;break}}!1===s&&r.push(new ha(e,o))}for(const e of r)yield e})),al=(e,t,n,r)=>r?ul(e,t,n,r):cl(e,t,n),cl=(e,t,n)=>new Si((async function*(){const r={};for await(const o of e){const e=t(o),s=r[e],i=n(o);s?s.push(i):r[e]=new ha(e,i)}for(const e in r)yield r[e]})),ul=(e,t,n,r)=>new Si((async function*(){const o=new Array;for await(const s of e){const e=t(s);let i=!1;for(let t=0;t<o.length;t++){const a=o[t];if(r(a.key,e)){a.push(n(s)),i=!0;break}}if(!1===i){const t=n(s);o.push(new ha(e,t))}}for(const e of o)yield e})),ll=(e,t,n,r,o,s)=>{const i=s?dl(e,t,n,r,o,s):hl(e,t,n,r,o);return new Si(i)},dl=(e,t,n,r,o,s)=>async function*(){const i=[];for await(const e of t){const t=r(e),n=i.find((e=>s(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for await(const t of e){const e=n(t),r=i.find((t=>s(t.key,e)))??{key:e,values:[]};yield o(t,r.values)}},hl=(e,t,n,r,o)=>async function*(){const s=new Map;for await(const e of t){const t=r(e),n=s.get(t);n?n.push(e):s.set(t,[e])}for await(const t of e){const e=n(t),r=s.get(e)??[];yield o(t,r)}},pl=(e,t,n,r,o,s)=>{const i=s?gl(e,t,n,r,o,s):fl(e,t,n,r,o);return new Si(i)},gl=(e,t,n,r,o,s)=>async function*(){const i=[];for await(const e of t){const t=await r(e),n=i.find((e=>s(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}for await(const t of e){const e=await n(t),r=i.find((t=>s(t.key,e)))??{key:e,values:[]};yield o(t,r.values)}},fl=(e,t,n,r,o)=>async function*(){const s=new Map;for await(const e of t){const t=await r(e),n=s.get(t);n?n.push(e):s.set(t,[e])}for await(const t of e){const e=await n(t),r=s.get(e)??[];yield o(t,r)}},vl=(e,t,n=wi)=>new Si((async function*(){const r=await e.distinct(n).toArray();if(0===r.length)return;const o=await t.toArray();for(let e=0;e<r.length;e++){const t=r[e];for(let e=0;e<o.length;e++){const r=o[e];if(!0===n(t,r)){yield t;break}}}})),yl=(e,t,n)=>new Si((async function*(){const r=await e.distinctAsync(n).toArray();if(0===r.length)return;const o=await t.toArray();for(let e=0;e<r.length;e++){const t=r[e];for(let e=0;e<o.length;e++){const r=o[e];if(!0===await n(t,r)){yield t;break}}}})),ml=(e,t,n,r,o,s=wi)=>new Si((async function*(){const i=[];for await(const e of t)i.push(e);for await(const t of e){const e=n(t);for(const n of i){const i=r(n);!0===s(e,i)&&(yield o(t,n))}}})),wl=(e,t)=>t?Al(e,t):Sl(e),Sl=async e=>{let t=null;for await(const n of e)t=n;if(!t)throw new mi(yi.NoElements);return t},Al=async(e,t)=>{let n=null;for await(const r of e)!0===t(r)&&(n=r);if(!n)throw new mi(yi.NoMatch);return n},_l=async(e,t)=>{let n=null;for await(const r of e)!0===await t(r)&&(n=r);if(!n)throw new mi(yi.NoMatch);return n},Cl=(e,t)=>t?Tl(e,t):Dl(e),Dl=async e=>{let t=null;for await(const n of e)t=n;return t},Tl=async(e,t)=>{let n=null;for await(const r of e)!0===t(r)&&(n=r);return n},kl=async(e,t)=>{let n=null;for await(const r of e)!0===await t(r)&&(n=r);return n},Il=(e,t)=>t?bl(e,t):El(e),El=async e=>{let t=null;for await(const n of e)t=Math.max(t??Number.NEGATIVE_INFINITY,n);if(null===t)throw new mi(yi.NoElements);return t},bl=async(e,t)=>{let n=null;for await(const r of e)n=Math.max(n??Number.NEGATIVE_INFINITY,t(r));if(null===n)throw new mi(yi.NoElements);return n},Gl=async(e,t)=>{let n=null;for await(const r of e)n=Math.max(n??Number.NEGATIVE_INFINITY,await t(r));if(null===n)throw new mi(yi.NoElements);return n},Nl=(e,t)=>t?Pl(e,t):Rl(e),Rl=async e=>{let t=null;for await(const n of e)t=Math.min(t??Number.POSITIVE_INFINITY,n);if(null===t)throw new mi(yi.NoElements);return t},Pl=async(e,t)=>{let n=null;for await(const r of e)n=Math.min(n??Number.POSITIVE_INFINITY,t(r));if(null===n)throw new mi(yi.NoElements);return n},Ul=async(e,t)=>{let n=null;for await(const r of e)n=Math.min(n??Number.POSITIVE_INFINITY,await t(r));if(null===n)throw new mi(yi.NoElements);return n},Ol=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new Si((async function*(){for await(const t of e)n(t)&&(yield t)}))},Ml=(e,t)=>Ka.generate(e,(e=>e),!0,t),xl=(e,t,n)=>Ka.generate(e,t,!0,n),Fl=(e,t,n)=>Ka.generateAsync(e,t,!0,n),Ll=(e,t,n)=>Ka.generate(e,t,!1,n),Bl=(e,t,n)=>Ka.generateAsync(e,t,!1,n),Wl=(e,t)=>Ka.generate(e,(e=>e),!1,t),$l=async(e,t)=>{const n=[],r=[];for await(const o of e)!0===t(o)?r.push(o):n.push(o);return[r,n]},Vl=async(e,t)=>{const n=[],r=[];for await(const o of e)!0===await t(o)?r.push(o):n.push(o);return[r,n]},ql=(e,t)=>new Si((async function*(){yield t,yield*e})),Hl=e=>new Si((async function*(){const t=[];for await(const n of e)t.push(n);for(let e=t.length-1;e>=0;e--)yield t[e]})),Kl=(e,t)=>"function"==typeof t?1===t.length?jl(e,t):zl(e,t):Jl(e,t),jl=(e,t)=>new Si((async function*(){for await(const n of e)yield t(n)})),zl=(e,t)=>new Si((async function*(){let n=0;for await(const r of e)yield t(r,n),n++})),Jl=(e,t)=>new Si((async function*(){for await(const n of e)yield n[t]})),Xl=(e,t)=>"string"==typeof t?Ql(e,t):Yl(e,t),Yl=(e,t)=>new Si((async function*(){for await(const n of e)yield t(n)})),Ql=(e,t)=>new Si((async function*(){for await(const n of e)yield n[t]})),Zl=(e,t)=>"function"==typeof t?1===t.length?ed(e,t):td(e,t):nd(e,t),ed=(e,t)=>new Si((async function*(){for await(const n of e)for(const e of t(n))yield e})),td=(e,t)=>new Si((async function*(){let n=0;for await(const r of e){for(const e of t(r,n))yield e;n++}})),nd=(e,t)=>new Si((async function*(){for await(const n of e)for(const e of n[t])yield e})),rd=(e,t)=>1===t.length?new Si((async function*(){for await(const n of e){const e=await t(n);for(const t of e)yield t}})):new Si((async function*(){let n=0;for await(const r of e){const e=await t(r,n);for(const t of e)yield t;n++}})),od=async(e,t,n=wi)=>{const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();let s=await Promise.all([r.next(),o.next()]),i=s[0],a=s[1];for(;!i.done&&!a.done;){if(!n(i.value,a.value))return!1;s=await Promise.all([r.next(),o.next()]),i=s[0],a=s[1]}return!0===i.done&&!0===a.done},sd=async(e,t,n)=>{const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();let s=await Promise.all([r.next(),o.next()]),i=s[0],a=s[1];for(;!i.done&&!a.done;){if(!1===await n(i.value,a.value))return!1;s=await Promise.all([r.next(),o.next()]),i=s[0],a=s[1]}return!0===i.done&&!0===a.done},id=(e,t)=>t?cd(e,t):ad(e),ad=async e=>{let t=!1,n=null;for await(const r of e){if(!0===t)throw new mi(yi.MoreThanOneElement);t=!0,n=r}if(!1===t)throw new mi(yi.NoElements);return n},cd=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new mi(yi.NoMatch);return r},ud=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(await t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new mi(yi.NoMatch);return r},ld=(e,t)=>t?hd(e,t):dd(e),dd=async e=>{let t=!1,n=null;for await(const r of e){if(!0===t)throw new mi(yi.MoreThanOneElement);t=!0,n=r}return n},hd=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}return r},pd=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(await t(o)){if(!0===n)throw new mi(yi.MoreThanOneMatchingElement);n=!0,r=o}return r},gd=(e,t)=>new Si((async function*(){let n=0;for await(const r of e)n++>=t&&(yield r)})),fd=(e,t)=>1===t.length?vd(e,t):yd(e,t),vd=(e,t)=>new Si((async function*(){let n=!0;for await(const r of e)!1===n?yield r:!1===t(r)&&(n=!1,yield r)})),yd=(e,t)=>new Si((async function*(){let n=0,r=!0;for await(const o of e)!1===r?yield o:!1===t(o,n)&&(r=!1,yield o),n++})),md=(e,t)=>1===t.length?wd(e,t):Sd(e,t),wd=(e,t)=>new Si((async function*(){let n=!0;for await(const r of e)!1===n?yield r:!1===await t(r)&&(n=!1,yield r)})),Sd=(e,t)=>new Si((async function*(){let n=0,r=!0;for await(const o of e)!1===r?yield o:!1===await t(o,n)&&(r=!1,yield o),n++})),Ad=(e,t)=>t?Cd(e,t):_d(e),_d=async e=>{let t=0;for await(const n of e)t+=n;return t},Cd=async(e,t)=>{let n=0;for await(const r of e)n+=t(r);return n},Dd=async(e,t)=>{let n=0;for await(const r of e)n+=await t(r);return n},Td=(e,t)=>new Si((async function*(){let n=t>0?t:0;for await(const t of e){if(0==n--)break;yield t}})),kd=(e,t)=>1===t.length?Id(e,t):Ed(e,t),Id=(e,t)=>new Si((async function*(){for await(const n of e){if(!t(n))break;yield n}})),Ed=(e,t)=>new Si((async function*(){let n=0;for await(const r of e){if(!t(r,n++))break;yield r}})),bd=(e,t)=>1===t.length?Gd(e,t):Nd(e,t),Gd=(e,t)=>new Si((async function*(){for await(const n of e){if(!await t(n))break;yield n}})),Nd=(e,t)=>new Si((async function*(){let n=0;for await(const r of e){if(!await t(r,n++))break;yield r}})),Rd=async e=>{const t=[];for await(const n of e)t.push(n);return t},Pd=async(e,t)=>{const n=new Map;for await(const r of e){const e=t(r),o=n.get(e);void 0===o?n.set(e,[r]):o.push(r)}return n},Ud=async(e,t)=>{const n=new Map;for await(const r of e){const e=await t(r),o=n.get(e);void 0===o?n.set(e,[r]):o.push(r)}return n},Od=async(e,t)=>{const n={};for await(const r of e)n[t(r)]=r;return n},Md=async(e,t)=>{const n={};for await(const r of e)n[await t(r)]=r;return n},xd=async e=>{const t=new Set;for await(const n of e)t.add(n);return t},Fd=(e,t,n)=>n?Bd(e,t,n):Ld(e,t),Ld=(e,t)=>new Si((async function*(){const n=new Set;for await(const t of e)!1===n.has(t)&&(yield t,n.add(t));for await(const e of t)!1===n.has(e)&&(yield e,n.add(e))})),Bd=(e,t,n)=>new Si((async function*(){const r=[];for(const o of[e,t])for await(const e of o){let t=!1;for(const o of r)if(!0===n(e,o)){t=!0;break}!1===t&&(yield e,r.push(e))}})),Wd=(e,t,n)=>new Si((async function*(){const r=[];for(const o of[e,t])for await(const e of o){let t=!1;for(const o of r)if(!0===await n(e,o)){t=!0;break}!1===t&&(yield e,r.push(e))}})),$d=(e,t)=>1===t.length?Vd(e,t):qd(e,t),Vd=(e,t)=>new Si((async function*(){for await(const n of e)!0===t(n)&&(yield n)})),qd=(e,t)=>new Si((async function*(){let n=0;for await(const r of e)!0===t(r,n++)&&(yield r)})),Hd=(e,t)=>1===t.length?Kd(e,t):jd(e,t),Kd=(e,t)=>new Si((async function*(){for await(const n of e)!0===await t(n)&&(yield n)})),jd=(e,t)=>new Si((async function*(){let n=0;for await(const r of e)!0===await t(r,n++)&&(yield r)})),zd=(e,t,n)=>n?Xd(e,t,n):Jd(e,t),Jd=(e,t)=>new Si((async function*(){const n=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([n.next(),r.next()]);if(e.done||t.done)break;yield[e.value,t.value]}})),Xd=(e,t,n)=>new Si((async function*(){const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([r.next(),o.next()]);if(e.done||t.done)break;yield n(e.value,t.value)}})),Yd=(e,t,n)=>new Si((async function*(){const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();for(;;){const e=await Promise.all([r.next(),o.next()]),t=e[0],s=e[1];if(t.done||s.done)break;yield n(t.value,s.value)}})),Qd=(e,t,n,r)=>{if(r){if(!n)throw new ReferenceError("TAccumulate function is undefined");return th(e,t,n,r)}return n?eh(e,t,n):Zd(e,t)},Zd=async(e,t)=>{let n;for await(const r of e)n=n?t(n,r):r;if(void 0===n)throw new mi(yi.NoElements);return n},eh=async(e,t,n)=>{let r=t;for await(const t of e)r=n(r,t);return r},th=async(e,t,n,r)=>{let o=t;for await(const t of e)o=n(o,t);return r(o)},nh=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:()=>n.generator().then((e=>{const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=t(e[r]);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n].then(t);return r},type:1};case 2:return{generator:async()=>{const e=await n.generator(),r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n].then(t);return r},type:2}}},rh=(e,t)=>{const n=nh(e,(e=>{if(!t(e))throw new Error(String(!1));return!0}));switch(n.type){case 0:return n.generator().then((()=>!0),(()=>!1));case 1:return Promise.all(n.generator()).then((()=>!0),(()=>!1));case 2:return n.generator().then(Promise.all.bind(Promise)).then((()=>!0),(()=>!1))}},oh=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=t(e[n]);return r},type:2};case 1:return{generator:()=>n.generator().map((async e=>{const n=await e;return await t(n)})),type:1};case 2:return{generator:async()=>(await n.generator()).map((e=>e.then(t))),type:2}}},sh=(e,t)=>{const n=oh(e,(async e=>{if(!1===await t(e))throw new Error(String(!1));return!0}));switch(n.type){case 1:return Promise.all(n.generator()).then((()=>!0),(()=>!1));case 2:return n.generator().then(Promise.all.bind(Promise)).then((()=>!0),(()=>!1))}},ih=(e,t)=>{const n=e.dataFunc;switch(n.type){case 1:return new Ai({generator:()=>{const e=n.generator();return e.push(Promise.resolve(t)),e},type:n.type});case 2:return new Ai({generator:async()=>{const e=await n.generator();return e.push(Promise.resolve(t)),e},type:n.type});case 0:return new Ai({generator:async()=>{const e=await n.generator();return e.push(t),e},type:n.type})}},ah=(e,t)=>t?uh(e,t):ch(e),ch=async e=>{const t=e.dataFunc;let n;switch(t.type){case 1:return n=t.generator(),0!==n.length;case 0:case 2:return n=await t.generator(),0!==n.length}},uh=async(e,t)=>{const n=nh(e,t);let r;switch(n.type){case 0:return r=await n.generator(),r.includes(!0);case 1:return r=await Promise.all(n.generator()),r.includes(!0);case 2:return r=await Promise.all(await n.generator()),r.includes(!0)}},lh=async(e,t)=>{const n=oh(e,t);let r;switch(n.type){case 1:return r=n.generator(),0!==r.length&&new Promise(((e,t)=>{let n=0;for(const o of r)o.then((t=>{n++,t?e(!0):n===r.length&&e(!1)}),t)}));case 2:return r=await n.generator(),0===Promise.length?!1:(await Promise.all(r)).includes(!0)}},dh=e=>Oi((async function*(){for await(const t of e)yield t})),hh=async e=>{switch(e.type){case 0:return await e.generator();case 1:return await Promise.all(e.generator());case 2:const t=await e.generator();return await Promise.all(t)}},ph=async(e,t)=>{let n;n=t?nh(e,t):e.dataFunc;const r=await hh(n);if(0===r.length)throw new mi(yi.NoElements);let o=0;for(const e of r)o+=e;return o/r.length},gh=async(e,t)=>{const n=oh(e,t),r=await hh(n);if(0===r.length)throw new mi(yi.NoElements);let o=0;for(const e of r)o+=e;return o/r.length},fh=(e,t)=>{if(t<1)throw new vi("size");let n;switch(e.dataFunc.type){case 1:const r=e.dataFunc.generator;n={type:1,generator:()=>{const e=[];let n=[];for(const o of r())n.push(o),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 2:const o=e.dataFunc.generator;n={type:2,generator:async()=>{const e=[];let n=[];for(const r of await o())n.push(r),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 0:const s=e.dataFunc.generator;n={type:0,generator:async()=>{const e=[];let n=[];for(const r of await s())n.push(r),n.length===t&&(e.push(n),n=[]);return n.length&&e.push(n),e}}}return new Ai(n)},vh=(e,t)=>new Ai({generator:async()=>{const[n,r]=await Promise.all([e.toArray(),t.toArray()]);return[...n,...r]},type:0}),yh=async(e,t,n=wi)=>{let r;switch(r=nh(e,n?e=>n(t,e):e=>e===t),r.type){case 0:return(await r.generator()).some((e=>e));case 1:return(await Promise.all(r.generator())).some((e=>e));case 2:return(await Promise.all(await r.generator())).some((e=>e))}},mh=async(e,t,n)=>{const r=oh(e,(e=>n(t,e)));switch(r.type){case 1:return(await Promise.all(r.generator())).some((e=>e));case 2:return(await Promise.all(await r.generator())).some((e=>e))}},wh=(e,t)=>t?Ah(e,t):Sh(e),Sh=async e=>{const t=e.dataFunc;switch(t.type){case 0:case 2:return(await e.toArray()).length;case 1:return t.generator().length}},Ah=async(e,t)=>{const n=await e.toArray();let r=0;for(let e=0;e<n.length;e++)!0===t(n[e])&&r++;return r},_h=async(e,t)=>{const n=oh(e,t);let r;switch(n.type){case 1:r=Promise.all(n.generator());break;case 2:r=Promise.all(await n.generator())}let o=0;for(const e of await r)e&&o++;return o},Ch=(e,t)=>{const n=e.dataFunc,r=t instanceof Promise;let o;switch(n.type){case 0:o={generator:()=>n.generator().then((e=>e.length?e:r?t.then((e=>[e])):[t])),type:n.type};break;case 1:o={generator:()=>{const e=n.generator();return e.length?e:r?[t]:[Promise.resolve(t)]},type:n.type};break;case 2:o={generator:async()=>{const e=await n.generator();return e.length?e:r?[t]:[Promise.resolve(t)]},type:n.type}}return new Ai(o)},Dh=(e,t=wi)=>new Ai({generator:async()=>{const n=[];for(const r of await e.toArray())n.find((e=>t(e,r)))||n.push(r);return n},type:0}),Th=(e,t)=>new Ai({generator:async()=>{const n=[];e:for(const r of await e.toArray()){for(const e of n)if(await t(e,r))continue e;n.push(r)}return n},type:0}),kh=(e,t)=>new Ai(nh(e,(e=>(t(e),e)))),Ih=(e,t)=>{const n=oh(e,(async e=>(await t(e),e)));return new Ai(n)},Eh=async(e,t)=>{if(t<0)throw new vi("index");const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();if(t>=e.length)throw new vi("index");return e[t]}case 1:{const e=n.generator();if(t>=e.length)throw new vi("index");return await e[t]}case 2:{const e=await n.generator();if(t>=e.length)throw new vi("index");return await e[t]}}},bh=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();return t>=e.length?null:e[t]}case 1:{const e=n.generator();return t>=e.length?null:await e[t]}case 2:{const e=await n.generator();return t>=e.length?null:await e[t]}}},Gh=(e,t,n=wi)=>new Ai({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),s=[];for(const e of r){let t=!1;for(let r=0;r<o.length;r++){const s=o[r];if(!0===n(e,s)){t=!0;break}}!1===t&&s.push(e)}return s},type:0}),Nh=(e,t,n)=>new Ai({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),s=[];for(const e of r){let t=!1;for(let r=0;r<o.length;r++){const s=o[r];if(!0===await n(e,s)){t=!0;break}}!1===t&&s.push(e)}return s},type:0}),Rh=e=>hh(e.dataFunc),Ph=(e,t)=>t?Oh(e,t):Uh(e),Uh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new mi(yi.NoElements);return e[0]}case 1:{const e=t.generator();if(0===e.length)throw new mi(yi.NoElements);return await e[0]}case 2:{const e=await t.generator();if(0===e.length)throw new mi(yi.NoElements);return await e[0]}}},Oh=async(e,t)=>{const n=await Rh(e);for(const e of n)if(!0===t(e))return e;throw new mi(yi.NoMatch)},Mh=async(e,t)=>{const n=await Rh(e);for(const e of n)if(!0===await t(e))return e;throw new mi(yi.NoMatch)},xh=(e,t)=>t?Lh(e,t):Fh(e),Fh=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();return 0===e.length?null:e[0]}case 1:{const e=t.generator();return 0===e.length?null:await e[0]}case 2:{const e=await t.generator();return 0===e.length?null:await e[0]}}},Lh=async(e,t)=>{const n=await Rh(e);for(const e of n)if(!0===t(e))return e;return null},Bh=async(e,t)=>{const n=await Rh(e);for(const e of n)if(!0===await t(e))return e;return null},Wh=(e,t,n)=>n?Vh(e,t,n):$h(e,t),$h=(e,t)=>new Ai({generator:async()=>{const n={};for(const r of await e.toArray()){const e=t(r),o=n[e];o?o.push(r):n[e]=new ha(e,r)}const r=new Array;for(const e in n)r.push(n[e]);return r},type:0}),Vh=(e,t,n)=>new Ai({generator:async()=>{const r=new Array;for(const o of await e.toArray()){const e=t(o);let s=!1;for(let t=0;t<r.length;t++){const i=r[t];if(n(i.key,e)){i.push(o),s=!0;break}}!1===s&&r.push(new ha(e,o))}const o=new Array;for(const e of r)o.push(e);return o},type:0}),qh=(e,t,n)=>n?Hh(e,t,n):Kh(e,t),Hh=(e,t,n)=>new Ai({generator:async()=>{const r=oh(e,(async e=>[await t(e),e]));let o;switch(r.type){case 1:o=await Promise.all(r.generator());break;case 2:o=await Promise.all(await r.generator())}const s=new Array;for(const[e,t]of o){let r=!1;for(let o=0;o<s.length;o++){const i=s[o];if(!0===await n(i.key,e)){i.push(t),r=!0;break}}!1===r&&s.push(new ha(e,t))}const i=new Array;for(const e of s)i.push(e);return i},type:0}),Kh=(e,t)=>new Ai({generator:async()=>{const n=oh(e,(async e=>[await t(e),e]));let r;switch(n.type){case 1:r=await Promise.all(n.generator());break;case 2:r=await Promise.all(await n.generator())}const o={};for(const[e,t]of r){const n=o[e];n?n.push(t):o[e]=new ha(e,t)}const s=new Array;for(const e in o)s.push(o[e]);return s},type:0}),jh=(e,t,n,r)=>r?zh(e,t,n,r):Jh(e,t,n),zh=(e,t,n,r)=>new Ai({generator:async()=>{const o=new Array;for await(const s of e){const e=t(s);let i=!1;for(let t=0;t<o.length;t++){const a=o[t];if(r(a.key,e)){a.push(n(s)),i=!0;break}}if(!1===i){const t=n(s);o.push(new ha(e,t))}}const s=new Array;for(const e of o)s.push(e);return s},type:0}),Jh=(e,t,n)=>new Ai({generator:async()=>{const r={};for(const o of await e.toArray()){const e=t(o),s=r[e],i=n(o);s?s.push(i):r[e]=new ha(e,i)}const o=new Array;for(const e in r)o.push(r[e]);return o},type:0}),Xh=(e,t,n,r,o,s)=>{const i=s?Yh(e,t,n,r,o,s):Qh(e,t,n,r,o);return new Ai({generator:i,type:0})},Yh=(e,t,n,r,o,s)=>async()=>{const i=[];for await(const e of t){const t=r(e),n=i.find((e=>s(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}return(await e.toArray()).map((e=>{const t=n(e),r=i.find((e=>s(e.key,t)))??{key:t,values:[]};return o(e,r.values)}))},Qh=(e,t,n,r,o)=>async()=>{const s=new Map;for await(const e of t){const t=r(e),n=s.get(t);n?n.push(e):s.set(t,[e])}return(await e.toArray()).map((e=>{const t=n(e),r=s.get(t)??[];return o(e,r)}))},Zh=(e,t,n,r,o,s)=>{const i=s?ep(e,t,n,r,o,s):tp(e,t,n,r,o);return new Ai({generator:i,type:0})},ep=(e,t,n,r,o,s)=>async()=>{const i=[];for await(const e of t){const t=await r(e),n=i.find((e=>s(e.key,t)));n?n.values.push(e):i.push({key:t,values:[e]})}const a=(await e.toArray()).map((async e=>{const t=await n(e),r=i.find((e=>s(e.key,t)))??{key:t,values:[]};return o(e,r.values)}));return await Promise.all(a)},tp=(e,t,n,r,o)=>async()=>{const s=new Map;for await(const e of t){const t=await r(e),n=s.get(t);n?n.push(e):s.set(t,[e])}const i=(await e.toArray()).map((async e=>{const t=await n(e),r=s.get(t)??[];return o(e,r)}));return await Promise.all(i)},np=(e,t,n=wi)=>new Ai({generator:async()=>{const r=await e.distinct(n).toArray();if(0===r.length)return[];const o=await t.toArray(),s=new Array;for(let e=0;e<r.length;e++){const t=r[e];for(let e=0;e<o.length;e++){const r=o[e];if(!0===n(t,r)){s.push(t);break}}}return s},type:0}),rp=(e,t,n)=>new Ai({generator:async()=>{const r=await e.distinctAsync(n).toArray();if(0===r.length)return[];const o=await t.toArray(),s=new Array;for(let e=0;e<r.length;e++){const t=r[e];for(let e=0;e<o.length;e++){const r=o[e];if(!0===await n(t,r)){s.push(t);break}}}return s},type:0}),op=(e,t,n,r,o,s=wi)=>new Ai({generator:async()=>{const[i,a]=await Promise.all([t.toArray(),e.toArray()]),c=new Array;for(const e of a){const t=n(e);for(const n of i){const i=r(n);!0===s(t,i)&&c.push(o(e,n))}}return c},type:0}),sp=(e,t)=>t?ap(e,t):ip(e),ip=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new mi(yi.NoElements);return e[e.length-1]}case 1:{const e=t.generator();if(0===e.length)throw new mi(yi.NoElements);return await e[e.length-1]}case 2:{const e=await t.generator();if(0===e.length)throw new mi(yi.NoElements);return await e[e.length-1]}}},ap=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=e[n];if(t(r))return r}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(t(r))return r}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(t(r))return r}break}}throw new mi(yi.NoMatch)},cp=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=e[n];if(!0===await t(r))return r}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(!0===await t(r))return r}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(!0===await t(r))return r}break}}throw new mi(yi.NoMatch)},up=(e,t)=>t?dp(e,t):lp(e),lp=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();return 0===e.length?null:e[e.length-1]}case 1:{const e=t.generator();return 0===e.length?null:await e[e.length-1]}case 2:{const e=await t.generator();return 0===e.length?null:await e[e.length-1]}}},dp=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=e[n];if(t(r))return r}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(t(r))return r}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(t(r))return r}break}}return null},hp=async(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=e[n];if(!0===await t(r))return r}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(!0===await t(r))return r}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const r=await e[n];if(!0===await t(r))return r}break}}return null},pp=async(e,t)=>{let n;n=t?nh(e,t):e.dataFunc;const r=await hh(n);if(0===r.length)throw new mi(yi.NoElements);return Math.max.apply(null,r)},gp=async(e,t)=>{const n=oh(e,t),r=await hh(n);if(0===r.length)throw new mi(yi.NoElements);return Math.max.apply(null,r)},fp=async(e,t)=>{let n;n=t?nh(e,t):e.dataFunc;const r=await hh(n);if(0===r.length)throw new mi(yi.NoElements);return Math.min.apply(null,r)},vp=async(e,t)=>{const n=oh(e,t),r=await hh(n);if(0===r.length)throw new mi(yi.NoElements);return Math.min.apply(null,r)},yp=(e,t)=>{const n="string"==typeof t?e=>[typeof e===t,e]:e=>[e instanceof t,e];return new Ai({generator:async()=>{const t=nh(e,n),r=await hh(t),o=[];for(const[e,t]of r)e&&o.push(t);return o},type:0})};async function*mp(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for(const r of e){const e=await t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}async function*wp(e,t,n,r){const o=((e,t)=>{const n=new Map;for(const r of e){const e=t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}class Sp extends Ai{orderedPairs;constructor(e){super({generator:async()=>{const t=e(),n=[];for await(const e of t)n.push(...e);return n},type:0}),this.orderedPairs=e}static generateAsync(e,t,n,r){let o;return o=e instanceof Sp?async function*(){for await(const o of e.orderedPairs())yield*mp(o,t,n,r)}:()=>async function*(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for await(const r of e){const e=await t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}(e,t,n,r),new Sp(o)}static generate(e,t,n,r){let o;return o=e instanceof Sp?async function*(){for await(const o of e.orderedPairs())yield*wp(o,t,n,r)}:()=>async function*(e,t,n,r){const o=await(async(e,t)=>{const n=new Map;for await(const r of e){const e=t(r),o=n.get(e);o?o.push(r):n.set(e,[r])}return n})(e,t),s=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<s.length;e++)yield o.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield o.get(s[e])}(e,t,n,r),new Sp(o)}thenBy(e,t){return Sp.generate(this,e,!0,t)}thenByAsync(e,t){return Sp.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Sp.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Sp.generateAsync(this,e,!1,t)}}const Ap=(e,t)=>Sp.generate(e,(e=>e),!0,t),_p=(e,t,n)=>Sp.generate(e,t,!0,n),Cp=(e,t,n)=>Sp.generateAsync(e,t,!0,n),Dp=(e,t,n)=>Sp.generate(e,t,!1,n),Tp=(e,t,n)=>Sp.generateAsync(e,t,!1,n),kp=(e,t)=>Sp.generate(e,(e=>e),!1,t),Ip=async(e,t)=>{const n=nh(e,(e=>[t(e),e])),r=await hh(n),o=[],s=[];for(const[e,t]of r)e?s.push(t):o.push(t);return[s,o]},Ep=async(e,t)=>{const n=oh(e,(async e=>[await t(e),e])),r=await hh(n),o=[],s=[];for(const[e,t]of r)e?s.push(t):o.push(t);return[s,o]},bp=(e,t)=>{const n=e.dataFunc;switch(n.type){case 1:return new Ai({generator:()=>{const e=n.generator();return e.unshift(Promise.resolve(t)),e},type:n.type});case 2:return new Ai({generator:async()=>{const e=await n.generator();return e.unshift(Promise.resolve(t)),e},type:n.type});case 0:return new Ai({generator:async()=>{const e=await n.generator();return e.unshift(t),e},type:n.type})}},Gp=e=>{const t=e.dataFunc;switch(t.type){case 1:return new Ai({generator:()=>t.generator().reverse(),type:t.type});case 2:case 0:return new Ai({generator:async()=>(await t.generator()).reverse(),type:t.type})}},Np=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:()=>n.generator().then((e=>{const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=t(e[r],r);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n].then((e=>t(e,n)));return r},type:1};case 2:return{generator:async()=>{const e=await n.generator(),r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n].then((e=>t(e,n)));return r},type:2}}},Rp=(e,t)=>"function"==typeof t?1===t.length?new Ai(nh(e,t)):new Ai(Np(e,t)):new Ai(nh(e,(e=>e[t]))),Pp=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=t(e[n],n);return r},type:2};case 1:return{generator:()=>n.generator().map(((e,n)=>e.then((e=>t(e,n))))),type:1};case 2:return{generator:async()=>(await n.generator()).map(((e,n)=>e.then((e=>t(e,n))))),type:2}}},Up=(e,t)=>{let n;return n="function"==typeof t?1===t.length?oh(e,t):Pp(e,t):oh(e,(e=>e[t])),new Ai(n)},Op=(e,t)=>new Ai({generator:async()=>{let n;n="function"==typeof t?1===t.length?nh(e,t):Np(e,t):nh(e,(e=>e[t]));const r=[];switch(n.type){case 0:for(const e of await n.generator())for(const t of e)r.push(t);break;case 1:for(const e of n.generator())for(const t of await e)r.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)r.push(t)}return r},type:0}),Mp=(e,t)=>new Ai({generator:async()=>{let n;n=1===t.length?oh(e,t):Pp(e,t);const r=[];switch(n.type){case 1:for(const e of n.generator())for(const t of await e)r.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)r.push(t)}return r},type:0}),xp=async(e,t,n=wi)=>{const r=await e.toArray(),o=await t.toArray();if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++)if(!1===n(r[e],o[e]))return!1;return!0},Fp=async(e,t,n)=>{const r=await e.toArray(),o=await t.toArray();if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e],s=o[e];if(!1===await n(t,s))return!1}return!0},Lp=(e,t)=>t?Wp(e,t):Bp(e),Bp=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new mi(yi.MoreThanOneElement);if(0===e.length)throw new mi(yi.NoElements);return e[0]}case 1:{const e=t.generator();if(e.length>1)throw new mi(yi.MoreThanOneElement);if(0===e.length)throw new mi(yi.NoElements);return e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new mi(yi.MoreThanOneElement);if(0===e.length)throw new mi(yi.NoElements);return await e[0]}}},Wp=async(e,t)=>{const n=await Rh(e);let r=!1,o=null;for(const e of n)if(t(e)){if(!0===r)throw new mi(yi.MoreThanOneMatchingElement);r=!0,o=e}if(!1===r)throw new mi(yi.NoMatch);return o},$p=async(e,t)=>{const n=await Rh(e);let r=!1,o=null;for(const e of n)if(!0===await t(e)){if(!0===r)throw new mi(yi.MoreThanOneMatchingElement);r=!0,o=e}if(!1===r)throw new mi(yi.NoMatch);return o},Vp=(e,t)=>t?Hp(e,t):qp(e),qp=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new mi(yi.MoreThanOneElement);return 0===e.length?null:e[0]}case 1:{const e=t.generator();if(e.length>1)throw new mi(yi.MoreThanOneElement);return 0===e.length?null:e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new mi(yi.MoreThanOneElement);return 0===e.length?null:await e[0]}}},Hp=async(e,t)=>{const n=await Rh(e);let r=!1,o=null;for(const e of n)if(t(e)){if(!0===r)throw new mi(yi.MoreThanOneElement);r=!0,o=e}return o},Kp=async(e,t)=>{const n=await Rh(e);let r=!1,o=null;for(const e of n)if(!0===await t(e)){if(!0===r)throw new mi(yi.MoreThanOneElement);r=!0,o=e}return o},jp=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return new Ai({generator:async()=>(await n.generator()).slice(t),type:0});case 1:return new Ai({generator:()=>n.generator().slice(t),type:1});case 2:return new Ai({generator:async()=>(await n.generator()).slice(t),type:2})}},zp=(e,t)=>new Ai({generator:async()=>{const n=await e.toArray();let r=0;for(;r<n.length;r++){const e=n[r];if(!1===t(e,r))break}const o=[];for(;r<n.length;r++)o.push(n[r]);return o},type:0}),Jp=(e,t)=>new Ai({generator:async()=>{const n=await e.toArray();let r=0;for(;r<n.length;r++){const e=n[r];if(!1===await t(e,r))break}const o=[];for(;r<n.length;r++)o.push(n[r]);return o},type:0}),Xp=(e,t)=>t?Qp(e,t):Yp(e),Yp=async e=>{let t=0;for(const n of await e.toArray())t+=n;return t},Qp=async(e,t)=>{let n=0;for(const r of await e.toArray())n+=t(r);return n},Zp=async(e,t)=>{const n=oh(e,t),r=await hh(n);let o=0;for(const e of r)o+=e;return o},eg=(e,t)=>{const n=t>0?t:0,r=e.dataFunc;switch(r.type){case 1:return new Ai({generator:()=>r.generator().splice(0,n),type:1});case 2:return new Ai({generator:()=>r.generator().then((e=>e.splice(0,n))),type:2});default:return new Ai({generator:()=>r.generator().then((e=>e.splice(0,n))),type:0})}},tg=(e,t)=>new Ai({generator:async()=>{const n=await e.toArray(),r=new Array;if(1===t.length)for(const e of n){if(!0!==t(e))break;r.push(e)}else for(let e=0;e<n.length;e++){const o=n[e];if(!0!==t(o,e))break;r.push(o)}return r},type:0}),ng=(e,t)=>new Ai({generator:async()=>{const n=await e.toArray(),r=new Array;if(1===t.length){const e=t;for(const t of n){if(!0!==await e(t))break;r.push(t)}}else for(let e=0;e<n.length;e++){const o=n[e];if(!0!==await t(o,e))break;r.push(o)}return r},type:0}),rg=async(e,t)=>{const n=new Map,r=nh(e,(e=>[t(e),e])),o=await hh(r);for(const[e,t]of o){const r=n.get(e);void 0===r?n.set(e,[t]):r.push(t)}return n},og=async(e,t)=>{const n=new Map,r=oh(e,(async e=>[await t(e),e])),o=await hh(r);for(const[e,t]of o){const r=n.get(e);void 0===r?n.set(e,[t]):r.push(t)}return n},sg=async(e,t)=>{const n=e.dataFunc,r=await hh(n),o={};for(const e of r)o[t(e)]=e;return o},ig=async(e,t)=>{const n=oh(e,(async e=>[await t(e),e])),r=await hh(n),o={};for(const[e,t]of r)o[e]=t;return o},ag=async e=>{const t=e.dataFunc,n=await hh(t);return new Set(n)},cg=(e,t,n)=>n?lg(e,t,n):ug(e,t),ug=(e,t)=>new Ai({generator:async()=>{const n=new Set,r=t.toArray();for await(const t of e)!1===n.has(t)&&n.add(t);const o=await r;for(const e of o)!1===n.has(e)&&n.add(e);return[...n.keys()]},type:0}),lg=(e,t,n)=>new Ai({generator:async()=>{const r=[],o=await Promise.all([e.toArray(),t.toArray()]);for(const e of o)for(const t of e){let e=!1;for(const o of r)if(!0===n(t,o)){e=!0;break}!1===e&&r.push(t)}return r},type:0}),dg=(e,t,n)=>new Ai({generator:async()=>{const r=[],o=await Promise.all([e.toArray(),t.toArray()]);for(const e of o)for(const t of e){let e=!1;for(const o of r)if(!0===await n(t,o)){e=!0;break}!1===e&&r.push(t)}return r},type:0}),hg=(e,t)=>new Ai({generator:async()=>(await e.toArray()).filter(t),type:0}),pg=(e,t)=>new Ai({generator:async()=>{const n=Pp(e,(async(e,n)=>[await t(e,n),e])),r=await hh(n),o=[];for(const[e,t]of r)e&&o.push(t);return o},type:0}),gg=(e,t,n)=>n?vg(e,t,n):fg(e,t),fg=(e,t)=>new Ai({generator:async()=>{const[n,r]=await Promise.all([e.toArray(),t.toArray()]),o=n.length<r.length?n.length:r.length,s=new Array(o);for(let e=0;e<o;e++){const t=n[e],o=r[e];s[e]=[t,o]}return s},type:0}),vg=(e,t,n)=>new Ai({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),s=r.length<o.length?r.length:o.length,i=new Array(s);for(let e=0;e<s;e++){const t=r[e],s=o[e];i[e]=n(t,s)}return i},type:0}),yg=(e,t,n)=>new Ai({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),s=r.length<o.length?r.length:o.length,i=new Array(s);for(let e=0;e<s;e++){const t=r[e],s=o[e];i[e]=n(t,s)}return Promise.all(i)},type:0}),mg=e=>{const t=Ci.prototype,n=e.prototype,r=Object.getOwnPropertyNames(t);for(const e of r)n[e]=n[e]??t[e]};fu(_i),(e=>{const t=e.prototype,n=(e,n)=>{const r=function(...t){return e(this,...t)};Object.defineProperty(r,"length",{value:e.length-1}),t[n]=r};n(vu,"aggregate"),n(Su,"all"),n(Au,"allAsync"),n(_u,"append"),n(Cu,"any"),n(ku,"anyAsync"),n(Iu,"asParallel"),n(Eu,"average"),n(bu,"averageAsync"),n(Gu,"chunk"),n(Nu,"concatenate"),n(Ru,"contains"),n(Pu,"containsAsync"),n(Uu,"count"),n(xu,"countAsync"),n(Fu,"defaultIfEmpty"),n(Lu,"distinct"),n(Bu,"distinctAsync"),n(Wu,"each"),n($u,"eachAsync"),n(Vu,"elementAt"),n(qu,"elementAtOrDefault"),n(Hu,"except"),n(Ku,"exceptAsync"),n(ju,"first"),n(Xu,"firstAsync"),n(Yu,"firstOrDefault"),n(el,"firstOrDefaultAsync"),n(tl,"groupBy"),n(ol,"groupByAsync"),n(al,"groupByWithSel"),n(ll,"groupJoin"),n(pl,"groupJoinAsync"),n(vl,"intersect"),n(yl,"intersectAsync"),n(ml,"joinByKey"),n(wl,"last"),n(_l,"lastAsync"),n(Cl,"lastOrDefault"),n(kl,"lastOrDefaultAsync"),n(Il,"max"),n(Gl,"maxAsync"),n(Nl,"min"),n(Ul,"minAsync"),n(Ol,"ofType"),n(Ml,"order"),n(xl,"orderBy"),n(Fl,"orderByAsync"),n(Ll,"orderByDescending"),n(Bl,"orderByDescendingAsync"),n(Wl,"orderDescending"),n($l,"partition"),n(Vl,"partitionAsync"),n(ql,"prepend"),n(Hl,"reverse"),n(Kl,"select"),n(Xl,"selectAsync"),n(Zl,"selectMany"),n(rd,"selectManyAsync"),n(od,"sequenceEquals"),n(sd,"sequenceEqualsAsync"),n(id,"single"),n(ud,"singleAsync"),n(ld,"singleOrDefault"),n(pd,"singleOrDefaultAsync"),n(gd,"skip"),n(fd,"skipWhile"),n(md,"skipWhileAsync"),n(Ad,"sum"),n(Dd,"sumAsync"),n(Td,"take"),n(kd,"takeWhile"),n(bd,"takeWhileAsync"),n(Rd,"toArray"),n(Pd,"toMap"),n(Ud,"toMapAsync"),n(Od,"toObject"),n(Md,"toObjectAsync"),n(xd,"toSet"),n(Fd,"union"),n(Wd,"unionAsync"),n($d,"where"),n(Hd,"whereAsync"),n(zd,"zip"),n(Yd,"zipAsync")})(Si),(e=>{const t=e.prototype,n=(e,n)=>{const r=function(...t){return e(this,...t)};Object.defineProperty(r,"length",{value:e.length-1}),t[n]=r};n(Qd,"aggregate"),n(rh,"all"),n(sh,"allAsync"),n(ih,"append"),n(ah,"any"),n(lh,"anyAsync"),n(dh,"asAsync"),n(ph,"average"),n(gh,"averageAsync"),n(fh,"chunk"),n(vh,"concatenate"),n(yh,"contains"),n(mh,"containsAsync"),n(wh,"count"),n(_h,"countAsync"),n(Ch,"defaultIfEmpty"),n(Dh,"distinct"),n(Th,"distinctAsync"),n(kh,"each"),n(Ih,"eachAsync"),n(Eh,"elementAt"),n(bh,"elementAtOrDefault"),n(Gh,"except"),n(Nh,"exceptAsync"),n(Ph,"first"),n(Mh,"firstAsync"),n(xh,"firstOrDefault"),n(Bh,"firstOrDefaultAsync"),n(Wh,"groupBy"),n(qh,"groupByAsync"),n(jh,"groupByWithSel"),n(Xh,"groupJoin"),n(Zh,"groupJoinAsync"),n(Xh,"groupJoin"),n(Zh,"groupJoinAsync"),n(np,"intersect"),n(rp,"intersectAsync"),n(op,"joinByKey"),n(sp,"last"),n(cp,"lastAsync"),n(up,"lastOrDefault"),n(hp,"lastOrDefaultAsync"),n(pp,"max"),n(gp,"maxAsync"),n(fp,"min"),n(vp,"minAsync"),n(yp,"ofType"),n(Ap,"order"),n(_p,"orderBy"),n(Cp,"orderByAsync"),n(Dp,"orderByDescending"),n(Tp,"orderByDescendingAsync"),n(kp,"orderDescending"),n(Ip,"partition"),n(Ep,"partitionAsync"),n(bp,"prepend"),n(Gp,"reverse"),n(Rp,"select"),n(Up,"selectAsync"),n(Op,"selectMany"),n(Mp,"selectManyAsync"),n(xp,"sequenceEquals"),n(Fp,"sequenceEqualsAsync"),n(Lp,"single"),n($p,"singleAsync"),n(Vp,"singleOrDefault"),n(Kp,"singleOrDefaultAsync"),n(jp,"skip"),n(zp,"skipWhile"),n(Jp,"skipWhileAsync"),n(Xp,"sum"),n(Zp,"sumAsync"),n(eg,"take"),n(tg,"takeWhile"),n(ng,"takeWhileAsync"),n(Rh,"toArray"),n(rg,"toMap"),n(og,"toMapAsync"),n(sg,"toObject"),n(ig,"toObjectAsync"),n(ag,"toSet"),n(cg,"union"),n(dg,"unionAsync"),n(hg,"where"),n(pg,"whereAsync"),n(gg,"zip"),n(yg,"zipAsync")})(Ai),(()=>{const{prototype:e}=Ci,t=Object.getOwnPropertyNames(_i.prototype);for(const n of t)e[n]=e[n]??_i.prototype[n];e.all=function(e){return this.every(e)},e.any=function(e){return e?this.some(e):0!==this.length},e.count=function(e){if(e){let t=0;for(let n=0;n<this.length;n++)!0===e(this[n])&&t++;return t}return this.length},e.elementAt=function(e){if(e<0||e>=this.length)throw new vi("index");return this[e]},e.elementAtOrDefault=function(e){return this[e]??null},e.first=function(e){if(e){const t=this.find(e);if(void 0===t)throw new mi(yi.NoMatch);return t}if(0===this.length)throw new mi(yi.NoElements);return this[0]},e.firstOrDefault=function(e){if(e){const t=this.find(e);return void 0===t?null:t}return 0===this.length?null:this[0]},e.last=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}throw new mi(yi.NoMatch)}if(0===this.length)throw new mi(yi.NoElements);return this[this.length-1]},e.lastOrDefault=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[this.length-1]},e.max=function(e){if(0===this.length)throw new mi(yi.NoElements);if(e){let t=Number.NEGATIVE_INFINITY;for(let n=0;n<this.length;n++)t=Math.max(e(this[n]),t);return t}return Math.max.apply(null,this)},e.min=function(e){if(0===this.length)throw new mi(yi.NoElements);if(e){let t=Number.POSITIVE_INFINITY;for(let n=0;n<this.length;n++)t=Math.min(e(this[n]),t);return t}return Math.min.apply(null,this)},e.reverse=function(){return Array.prototype.reverse.apply(this),this}})();var wg,Sg;!function(e){e.Success="Success",e.GroupDoesNotExists="GroupDoesNotExists",e.ObjectDoesNotExists="ObjectDoesNotExists",e.FatalError="FatalError",e.FunctionNotSupported="FunctionNotSupported"}(wg||(wg={})),function(e){e.Success="Success",e.NoPermissions="NoPermissions",e.NameToShort="NameToShort",e.NameAlreadyExists="NameAlreadyExists",e.OtherError="OtherError",e.UnknownError="UnknownError"}(Sg||(Sg={}));class Ag{constructor(){this._guid="",this._name="",this._iconName="",this._position=0,this._objectsOrder={},null==Ag._devicesService&&(Ag._devicesService=hy.Get(Ys.ServiceName))}GetDevicesChannelsInGroupAsync(){return e=this,t=arguments,r=function*(e=!1){let t=[],n=[];const r=yield Ag._devicesService.GetDevicesAsync(e);if(void 0===this._objectsOrder||null===this._objectsOrder||0==Object.entries(this._objectsOrder).length){hy.Get(a.ServiceName).Error("Old controller API fallback to old groups API.");for(let e of r)for(let t of e.Channels.where((e=>e.ChannelGroups.any((e=>e===this._guid)))))n.push(t);return n}const o=Object.keys(this._objectsOrder).map(Number).sort(((e,t)=>e-t));Object.values(this._objectsOrder).forEach((e=>{const n=r.select((t=>t.Channels.where((t=>t.ChannelId===e))));if(null!==n)for(let e of n)for(let n of e)t.push(n)}));for(let e of o){const r=t.firstOrDefault((t=>t.ChannelId===this._objectsOrder[e]));null!==r&&n.push(r)}return n},new((n=void 0)||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}));var e,t,n,r}get Guid(){return this._guid}set Guid(e){this._guid=e}get Name(){return this._name}set Name(e){this._name=e}get IconName(){return this._iconName}set IconName(e){this._iconName=e}get OrderPosition(){return this._position}set OrderPosition(e){this._position=e}get ObjectsOrder(){return this._objectsOrder}set ObjectsOrder(e){this._objectsOrder=e}ChangeNameAsync(e){return hy.Get(Ug.ServiceName).ChangeGroupNameAsync(this,e)}ChangeIconNameAsync(e){return hy.Get(Ug.ServiceName).ChangeGroupIconNameAsync(this,e)}}var _g,Cg,Dg,Tg,kg,Ig,Eg,bg,Gg,Ng,Rg,Pg=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Ug{constructor(){this._connection=null,this._synchronized=!1,this._onSynchronized=new ke,this._groups=[],this._objectsGroupingSupported=!1,this._configurationService=hy.Get(ct.ServiceName),this._syncSemaphore=new et(1),this._connection=hy.Get(It.ServiceName),hy.Get(Xe.ServiceName).OnUserLoggedInEvent().Subscribe((e=>Pg(this,void 0,void 0,(function*(){yield this.ResyncGroupsAsync()}))))}ResyncGroupsAsync(){return Pg(this,void 0,void 0,(function*(){var e;const t=yield this._syncSemaphore.AcquireAsync();try{this._synchronized=!1,yield this.GetGroupsAsync(!0),this._synchronized=!0,this._onSynchronized.Invoke()}catch(t){null===(e=u.Log)||void 0===e||e.Error(Ug.ServiceName,`Failed to sync groups: ${t}`)}finally{t.Release()}}))}WaitForSynchronizationAsync(){return this._synchronized?Promise.resolve():new Promise((e=>{const t=window.setTimeout((()=>{this._onSynchronized.Unsubscribe(n),e()}),3e4),n=()=>{window.clearTimeout(t),this._onSynchronized.Unsubscribe(n),e()};this._onSynchronized.Subscribe(n)}))}SetObjectsInGroupAndOrderAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r;let o=[],s=[];for(let e of t)if(this.IsDevice(e)){for(let t of e.Channels)o.push(`${t.ChannelId}`);s.push(`${e.Guid}`)}else{if(!this.IsDeviceChannel(e))throw new Error("Passed object is not a device or device channel!");o.push(`${e.ChannelId}`),s.push(`${e.ChannelId}`)}const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new xg(e,s),15e3,!1);switch(null===(r=u.Log)||void 0===r||r.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! SetObjectsInGroupAndOrderAsync()"),this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),yield hy.Get(Ys.ServiceName).GetDevicesAsync(),null==i?void 0:i.Status){case ue.OK:return new Ee(wg.Success,"");case ue.NotSupportedMethod:case ue.ResourceDoesNotExists:case ue.ResourceIsNotAvailable:return new Ee(wg.FunctionNotSupported,"");case ue.WrongData:return"GroupDoesNotExists"===i.Data?new Ee(wg.GroupDoesNotExists,i.Data):new Ee(wg.FatalError,i.Data);case ue.Error:case ue.FatalError:default:return new Ee(wg.FatalError,"")}}))}IsDevice(e){return void 0!==e.Channels}IsDeviceChannel(e){return void 0!==e.GetDevice}LogGroupsOrder(e){const t=hy.Get(a.ServiceName);e.forEach(((e,n)=>{t.Debug(Ug.ServiceName,`Group ${e.Name} order position [on array]: ${n} set position: ${e.OrderPosition}`)}))}LogObjectsInGroupOrder(e,t){const n=hy.Get(a.ServiceName);n.Debug(Ug.ServiceName,`Group ${e.Name} objects order:`),t.forEach(((e,t)=>{n.Debug(Ug.ServiceName,`Channel ${e.Name} order position [on array]: ${t} channelId: ${e.ChannelId}`)}));for(const[t,r]of Object.entries(e.ObjectsOrder))n.Debug(`new order [GROUP ${e.Name}] Order: [${t}] = ${r}`)}ChangeGroupsOrderAsync(e){return Pg(this,void 0,void 0,(function*(){var t,n;const r=e.select((e=>e.Guid)).toArray(),o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Mg(r),15e3,!1);return null===(n=u.Log)||void 0===n||n.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! ChangeGroupsOrderAsync()"),this._configurationService.ExitConfigurationModeAsync(),(null==o?void 0:o.Status)===ue.OK?(yield this.GetGroupsAsync(!1),ue.OK):(hy.Get(a.ServiceName).Error(Ug.ServiceName,`Failed to change groups order, controller responded with error ${null==o?void 0:o.Status} data: ${null==o?void 0:o.Data}`),this.LogGroupsOrder(e),null==o?void 0:o.Status)}))}ChangeObjectsPositionsInGroupAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r,o;const s=t.select((e=>e.ChannelId)).toArray(),i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Wg(e.Guid,s),15e3,!1);return null===(r=u.Log)||void 0===r||r.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! ChangeObjectsPositionsInGroupAsync()"),this._configurationService.ExitConfigurationModeAsync(),(null==i?void 0:i.Status)===ue.OK?(yield this.GetGroupsAsync(!1),yield hy.Get(Ys.ServiceName).GetDevicesAsync(),ue.OK):(null===(o=u.Log)||void 0===o||o.Error(Ug.ServiceName,`Failed to change objects positions in group, controller responded with error ${null==i?void 0:i.Status} data: ${null==i?void 0:i.Data}`),this.LogObjectsInGroupOrder(e,t),null==i?void 0:i.Status)}))}IsGroupsAndObjectsOrderingAvailable(){return this._objectsGroupingSupported}MoveGroupPositionAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r,o;const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Og(e.Guid,t),15e3,!1);return null===(r=u.Log)||void 0===r||r.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! MoveGroupPositionAsync()"),this._configurationService.ExitConfigurationModeAsync(),(null==s?void 0:s.Status)===ue.OK?(yield this.GetGroupsAsync(!1),ue.OK):(null===(o=u.Log)||void 0===o||o.Error(Ug.ServiceName,`Failed to move group position, controller responded with error ${null==s?void 0:s.Status} data: ${null==s?void 0:s.Data}`),null==s?void 0:s.Status)}))}MoveObjectInGroupPositionAsync(e,t,n){return Pg(this,void 0,void 0,(function*(){var r,o,s;const i=`${t.GetDevice().Guid}_${t.Number}`,a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Bg(e.Guid,i,n),15e3,!1);return null===(o=u.Log)||void 0===o||o.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! MoveObjectInGroupPositionAsync()"),this._configurationService.ExitConfigurationModeAsync(),(null==a?void 0:a.Status)===ue.OK?(yield this.GetGroupsAsync(!1),yield hy.Get(Ys.ServiceName).GetDevicesAsync(),ue.OK):(null===(s=u.Log)||void 0===s||s.Error(Ug.ServiceName,`Failed to move object in group position, controller responded with error ${null==a?void 0:a.Status} data: ${null==a?void 0:a.Data}`),null==a?void 0:a.Status)}))}AddDeviceChannelToGroupByGuidAsync(e,t){return Pg(this,arguments,void 0,(function*(e,t,n=!1){var r,o,s,i;const a=new jg;if(a.Data.Channel=e.Number,null==e.GetDevice())throw new Error("Device is not set on this channel!");a.Data.DeviceGuid=null===(r=e.GetDevice())||void 0===r?void 0:r.Guid,a.Data.GroupGuid=t;const c=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(a,15e3,!1);return null===(s=u.Log)||void 0===s||s.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! AddDeviceChannelToGroupByGuidAsync()"),this._configurationService.ExitConfigurationModeAsync(),null!=c&&null!=c.Status?(c.Status==ue.OK?e.ChannelGroups.push(t):null===(i=u.Log)||void 0===i||i.Error(Ug.ServiceName,`Failed to add device channel ${e.Name} to group ${t}, controller responded with error ${c.Status} data: ${c.Data}`),n||(yield this.GetGroupsAsync(!1),yield hy.Get(Ys.ServiceName).GetDevicesAsync()),c.Status):(n||(yield this.GetGroupsAsync(!1),yield hy.Get(Ys.ServiceName).GetDevicesAsync()),ue.Error)}))}RemoveDeviceChannelFromGroupByGuidAsync(e,t){return Pg(this,arguments,void 0,(function*(e,t,n=!1){var r,o,s;const i=new zg;if(null==e.GetDevice())throw new Error("Device is not set on this channel!");i.Data.DeviceGuid=null===(r=e.GetDevice())||void 0===r?void 0:r.Guid,i.Data.Channel=e.Number,i.Data.GroupGuid=t;const a=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(i,15e3,!1);return n||this._configurationService.ExitConfigurationModeAsync(),null!=a&&null!=a.Status?(a.Status==ue.OK?e.ChannelGroups=e.ChannelGroups.where((e=>e!=t)).toArray():null===(s=u.Log)||void 0===s||s.Error(Ug.ServiceName,`Failed to remove device channel ${e.Name} from group ${t}, controller responded with error ${a.Status} data: ${a.Data}`),n||(yield this.GetGroupsAsync(!1)),yield hy.Get(Ys.ServiceName).GetDevicesAsync(),a.Status):(n||(yield this.GetGroupsAsync(!1)),yield hy.Get(Ys.ServiceName).GetDevicesAsync(),ue.Error)}))}UpsertGroupWithDevicesChannelsAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r,o;if(this._groups.all((t=>t.Guid!=e.Guid))){let t=yield this.AddNewGroupWithIconAsync(e.Name,e.IconName);if(!(t instanceof Ag))return t instanceof Ee?t:new Ee(Sg.UnknownError,"");e=t}for(let r of t.where((t=>t.ChannelGroups.all((t=>t!==e.Guid))))){let t=yield this.AddDeviceChannelToGroupAsync(r,e,!0);if(t!==ue.OK)return null===(n=u.Log)||void 0===n||n.Error(Ug.ServiceName,`Failed to add device channel ${r.Name} to group ${e.Name}, controller responded with error ${t}`),new Ee(Sg.UnknownError,`Failed to add device channel ${r.Name} to group ${e.Name}, controller responded with error ${t}`)}let s=yield hy.Get(Ys.ServiceName).GetDevicesAsync();for(let n of s)for(let s of n.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(let t of s.ChannelGroups.where((t=>e.Guid==t))){let t=yield this.RemoveDeviceChannelFromGroupAsync(s,e,!0);if(t!==ue.OK)return null===(r=u.Log)||void 0===r||r.Error(Ug.ServiceName,`Failed to remove device channel ${s.Name} from group ${e.Name}, controller responded with error ${t}`),null===(o=u.Log)||void 0===o||o.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! UpsertGroupWithDevicesChannelsAsync()"),this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),new Ee(Sg.UnknownError,`Failed to remove device channel ${s.Name} from group ${e.Name}, controller responded with error ${t}`)}return this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),e}))}UpdateGroupWithDevicesChannelsAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r,o,s;for(let o of t.where((t=>t.ChannelGroups.all((t=>t!==e))))){let t=yield this.AddDeviceChannelToGroupByGuidAsync(o,e,!0);if(t!==ue.OK)return null===(n=u.Log)||void 0===n||n.Error(Ug.ServiceName,`Failed to add device channel ${o.Name} to group ${e}, controller responded with error ${t}`),null===(r=u.Log)||void 0===r||r.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! UpdateGroupWithDevicesChannelsAsync()"),this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),ue.FatalError}let i=yield hy.Get(Ys.ServiceName).GetDevicesAsync();for(let n of i)for(let r of n.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(let t of r.ChannelGroups.where((t=>e==t))){let t=yield this.RemoveDeviceChannelFromGroupByGuidAsync(r,e,!0);if(t!==ue.OK)return null===(o=u.Log)||void 0===o||o.Error(Ug.ServiceName,`Failed to remove device channel ${r.Name} from group ${e}, controller responded with error ${t}`),null===(s=u.Log)||void 0===s||s.Error(Ug.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! UpdateGroupWithDevicesChannelsAsync()"),this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),ue.FatalError}return this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),ue.OK}))}ChangeGroupNameByGuidAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r;let o=new Kg,s=new Jg,i=this._groups.first((t=>t.Guid===e));s.Guid=e,s.Name=t,s.IconName=i.IconName,null===(n=o.Data)||void 0===n||n.push(s);const a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(this._configurationService.ExitConfigurationModeAsync(),this._groups=yield this.GetGroupsAsync(!1),null!=a&&null!=a.Status)switch(a.Status){case ue.OK:return new Ee(Sg.Success,"");case ue.WrongData:switch(a.Data){case"NameToShort":return new Ee(Sg.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ee(Sg.NameAlreadyExists,"Group with this name already exists");default:return new Ee(Sg.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new Ee(Sg.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new Ee(Sg.UnknownError,"")}))}ChangeGroupNameAndIconAsync(e,t,n){return this.ChangeGroupNameAndIconByGuidAsync(e.Guid,t,n)}ChangeGroupNameAndIconByGuidAsync(e,t,n){return Pg(this,void 0,void 0,(function*(){var r,o;let s=new Kg,i=new Jg,a=this._groups.first((t=>t.Guid===e));i.Guid=e,i.Name=t,i.IconName=n,i.ObjectsOrder=a.ObjectsOrder,null===(r=s.Data)||void 0===r||r.push(i);const c=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(s,15e3,!1);if(this._configurationService.ExitConfigurationModeAsync(),this._groups=yield this.GetGroupsAsync(!1),null!=c&&null!=c.Status)switch(c.Status){case ue.OK:return new Ee(Sg.Success,"");case ue.WrongData:switch(c.Data){case"NameToShort":return new Ee(Sg.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ee(Sg.NameAlreadyExists,"Group with this name already exists");default:return new Ee(Sg.OtherError,`Response error: ${c.Status} data: ${c.Data}`)}default:return new Ee(Sg.OtherError,`Response error: ${c.Status} data: ${c.Data}`)}return new Ee(Sg.UnknownError,"")}))}ChangeGroupIconNameByGuidAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r;let o=new Kg,s=new Jg,i=this._groups.first((t=>t.Guid===e));s.Guid=e,s.Name=i.Name,s.IconName=t,null===(n=o.Data)||void 0===n||n.push(s);const a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(this._configurationService.ExitConfigurationModeAsync(),this._groups=yield this.GetGroupsAsync(!1),null!=a&&null!=a.Status)switch(a.Status){case ue.OK:return new Ee(Sg.Success,"");case ue.WrongData:switch(a.Data){case"NameToShort":return new Ee(Sg.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ee(Sg.NameAlreadyExists,"Group with this name already exists");default:return new Ee(Sg.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new Ee(Sg.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new Ee(Sg.UnknownError,"")}))}GetServiceName(){return Ug.ServiceName}GetGroupByGuid(e){return this._groups.first((t=>t.Guid===e))}ChangeGroupNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}ChangeGroupIconNameAsync(e,t){return this.ChangeGroupIconNameByGuidAsync(e.Guid,t)}RemoveGroupAsync(e){return this.RemoveGroupByGuidAsync(e.Guid)}RemoveGroupByGuidAsync(e){return Pg(this,void 0,void 0,(function*(){var t;let n=new qg;n.Data=e;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,15e3,!1);return this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),null!=r&&null!=r.Status?null==r?void 0:r.Status:ue.Error}))}GetGroupsAsync(){return Pg(this,arguments,void 0,(function*(e=!0){var t,n;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Hg,15e3,e);let o=[];if((null==r?void 0:r.Status)===ue.OK){let t=0,s=hy.Get(a.ServiceName),i=yield hy.Get(Ys.ServiceName).GetDevicesAsync();return null===(n=r.Data)||void 0===n||n.forEach((n=>{t++;let r=new Ag;if(r.Guid=n.Guid,r.Name=n.Name,r.IconName=n.IconName,r.ObjectsOrder=n.ObjectsOrder,r.OrderPosition=n.OrderPosition,null==r.OrderPosition&&(r.OrderPosition=t),null==r.ObjectsOrder){this._objectsGroupingSupported=!1,r.ObjectsOrder={};let e=i.selectMany((e=>e.Channels.where((e=>e.ChannelGroups.any((e=>e==r.Guid)))))),t=0;for(let n of e)t++,r.ObjectsOrder[t]=n.ChannelId}else this._objectsGroupingSupported=!0;e||s.Info(Ug.ServiceName,`Got group: ${r.Name} ${r.Guid} order: ${r.OrderPosition} objects order: ${JSON.stringify(r.ObjectsOrder)}`),o.push(r)})),this._groups=o,o}throw new Error(`Failed to get groups, API responded with status ${null==r?void 0:r.Status} data: ${null==r?void 0:r.Data}`)}))}AddDeviceChannelToGroupAsync(e,t,n=!1){return this.AddDeviceChannelToGroupByGuidAsync(e,t.Guid,n)}RemoveDeviceChannelFromGroupAsync(e,t,n=!1){return this.RemoveDeviceChannelFromGroupByGuidAsync(e,t.Guid,n)}AddNewGroupAsync(e){return Pg(this,void 0,void 0,(function*(){var t,n,r;let o=new Kg,s=new Jg;s.Name=e,null===(t=o.Data)||void 0===t||t.push(s);const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(o,15e3,!1);if(this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),null!=i&&null!=i.Status)switch(i.Status){case ue.OK:return this._groups.first((t=>t.Name===e));case ue.WrongData:switch(null===(r=u.Log)||void 0===r||r.Error(Ug.ServiceName,`Failed to add new group, controller responded with error ${i.Status} data: ${i.Data}`),i.Data){case"NameToShort":return new Ee(Sg.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ee(Sg.NameAlreadyExists,"Group with this name already exists");default:return new Ee(Sg.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}default:return new Ee(Sg.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}return new Ee(Sg.UnknownError,"")}))}AddNewGroupWithIconAsync(e,t){return Pg(this,void 0,void 0,(function*(){var n,r,o;let s=new Kg,i=new Jg;i.Name=e,i.IconName=t,null===(n=s.Data)||void 0===n||n.push(i);const a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(s,15e3,!1);if(this._configurationService.ExitConfigurationModeAsync(),yield this.GetGroupsAsync(!1),null!=a&&null!=a.Status)switch(a.Status){case ue.OK:return this._groups.first((t=>t.Name===e));case ue.WrongData:switch(null===(o=u.Log)||void 0===o||o.Error(Ug.ServiceName,`Failed to add new group, controller responded with error ${a.Status} data: ${a.Data}`),a.Data){case"NameToShort":return new Ee(Sg.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ee(Sg.NameAlreadyExists,"Group with this name already exists");default:return new Ee(Sg.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}default:return new Ee(Sg.OtherError,`Response error: ${a.Status} data: ${a.Data}`)}return new Ee(Sg.UnknownError,"")}))}}Ug.ServiceName="ChannelsGroupsService";class Og extends ce{constructor(e,t){super(),this.Resource="/devices/groups/group/move",this.Method=le.Post,this.Data=new Lg,this.Data.GroupGuid=e,this.Data.NewPosition=t}}class Mg extends ce{constructor(e){super(),this.Resource="/devices/groups/move",this.Method=le.Post,this.Data=e}}class xg extends ce{constructor(e,t){super(),this.Resource="/devices/groups/group/objects/set",this.Method=le.Post,this.Data=new Fg,this.Data.GroupGuid=e.Guid,this.Data.ObjectsIds=t}}class Fg{constructor(){this.GroupGuid="",this.ObjectsIds=[]}}class Lg{constructor(){this.GroupGuid="",this.NewPosition=0}}class Bg extends ce{constructor(e,t,n){super(),this.Resource="/devices/groups/group/object/move",this.Method=le.Post,this.Data=new $g,this.Data.GroupGuid=e,this.Data.NewPosition=n,this.Data.ObjectId=t}}class Wg extends ce{constructor(e,t){super(),this.Resource="/devices/groups/group/objects/move",this.Method=le.Post,this.Data=new Vg,this.Data.GroupGuid=e,this.Data.OrderedObjectsIds=t}}class $g{constructor(){this.GroupGuid="",this.ObjectId="",this.NewPosition=0}}class Vg{constructor(){this.GroupGuid="",this.OrderedObjectsIds=[]}}class qg extends ce{constructor(){super(),this.Resource="/devices/groups/group",this.Method=le.Delete}}class Hg extends ce{constructor(){super(),this.Resource="/devices/groups/",this.Method=le.Get}}class Kg extends ce{constructor(){super(),this.Resource="/devices/groups/group",this.Method=le.Put,this.Data=[]}}class jg extends ce{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=le.Put,this.Data=new Xg}}class zg extends ce{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=le.Delete,this.Data=new Xg}}class Jg{constructor(){this.Id=0,this.Guid="",this.Name="",this.IconName="",this.OrderPosition=0,this.ObjectsOrder={}}}class Xg{constructor(){this.GroupGuid="",this.DeviceGuid="",this.Channel=0}}class Yg{constructor(){this.DeviceGuid="",this.CurrentVersion="",this.NewVersion=""}}class Qg{constructor(){this.UpdatesAvailable=[],this.UpdatesNotAvailable=[]}}class Zg{constructor(){this.UpdatedResourceName=new Map,this.UpdateDescription=new Map,this.UpdateCreationTime=null,this.Version="",this.UpdateChannel=""}}class ef{constructor(){this.Resource="",this.Version="",this.Type=null}}!function(e){e[e.RadioUpdate=0]="RadioUpdate",e[e.SoftwareUpdate=1]="SoftwareUpdate"}(_g||(_g={})),function(e){e[e.DownloadingFailure=-5]="DownloadingFailure",e[e.InstallationStopped=-4]="InstallationStopped",e[e.InstallationError=-3]="InstallationError",e[e.IncompatiblePackage=-2]="IncompatiblePackage",e[e.Error=-1]="Error",e[e.OK=0]="OK",e[e.DownloadingPackage=1]="DownloadingPackage",e[e.CheckingPackage=2]="CheckingPackage",e[e.PreparingForUpgrade=3]="PreparingForUpgrade",e[e.Upgrading=4]="Upgrading",e[e.MovingData=5]="MovingData",e[e.Reloading=6]="Reloading",e[e.Upgraded=7]="Upgraded"}(Cg||(Cg={})),(Rg=Dg||(Dg={}))[Rg.WaitingForUser=1]="WaitingForUser",Rg[Rg.Downloading=2]="Downloading",Rg[Rg.Unpackaging=3]="Unpackaging",Rg[Rg.CheckingApplicability=4]="CheckingApplicability",Rg[Rg.MigratingData=5]="MigratingData",Rg[Rg.CreatingBackup=6]="CreatingBackup",Rg[Rg.Deploying=7]="Deploying",Rg[Rg.Installing=8]="Installing",Rg[Rg.Removing=9]="Removing",Rg[Rg.Error=10]="Error",Rg[Rg.ReadyToDownload=11]="ReadyToDownload",Rg[Rg.PreparingSystem=12]="PreparingSystem",Rg[Rg.CheckingPackageIntegrity=13]="CheckingPackageIntegrity",Rg[Rg.CheckingIntegrity=14]="CheckingIntegrity",Rg[Rg.UndoingInstallation=15]="UndoingInstallation",Rg[Rg.Installed=16]="Installed",(Ng=Tg||(Tg={}))[Ng.Ignore=0]="Ignore",Ng[Ng.Cancel=1]="Cancel",Ng[Ng.Install=2]="Install";class tf{constructor(){this.UpdatedResourceName=new Map,this.Percentage=0,this.PercentageTotal=0,this.Status=Cg.Error,this.UpdateNumber=1,this.AvailableUpdates=1}}class nf{constructor(){this.UpdatedResourceName=new Map,this.Percentage=0,this.PercentageTotal=0,this.SpeedMbps=0,this.CurrentTask=Eg.Unknown,this.DownloadOnly=!1}}class rf{constructor(){this.BulkUpdateStatus=kg.Success,this.DevicesUpdateResults=new Map}}!function(e){e[e.Success=0]="Success",e[e.PartialSuccess=1]="PartialSuccess",e[e.UpdatesNotFound=2]="UpdatesNotFound",e[e.CannotUnpairRetransmitters=3]="CannotUnpairRetransmitters",e[e.CannotPairRetransmitters=4]="CannotPairRetransmitters"}(kg||(kg={})),function(e){e[e.Unknown=0]="Unknown",e[e.Updated=1]="Updated",e[e.InsufficientConnection=2]="InsufficientConnection",e[e.Error=3]="Error",e[e.UnknownError=4]="UnknownError",e[e.ControllerSoftwareTooOld=5]="ControllerSoftwareTooOld"}(Ig||(Ig={})),function(e){e[e.Unknown=0]="Unknown",e[e.DownloadingUpdate=1]="DownloadingUpdate",e[e.DownloadingInstaller=2]="DownloadingInstaller",e[e.CheckingUpdate=3]="CheckingUpdate",e[e.UpdateDownloadedAndChecked=4]="UpdateDownloadedAndChecked"}(Eg||(Eg={})),function(e){e[e.DeviceIsUpToDate=0]="DeviceIsUpToDate",e[e.CannotFindDevice=1]="CannotFindDevice",e[e.UnsupportedApiVersion=2]="UnsupportedApiVersion",e[e.UnsupportedDevice=3]="UnsupportedDevice",e[e.CannotGetFirmwareVersion=4]="CannotGetFirmwareVersion",e[e.CannotGetUpdates=5]="CannotGetUpdates",e[e.CannotProcessUpdate=6]="CannotProcessUpdate",e[e.UpdateActionsNotSupported=7]="UpdateActionsNotSupported",e[e.UnsupportedExtensionVersion=8]="UnsupportedExtensionVersion",e[e.UpdatesPartiallyInstalled=9]="UpdatesPartiallyInstalled",e[e.RetransmitterFound=10]="RetransmitterFound",e[e.ProtocolRadioUnsupported=11]="ProtocolRadioUnsupported",e[e.FeatureUnsupportedInCurrentVersion=12]="FeatureUnsupportedInCurrentVersion",e[e.CannotGetUpdatesBranch=13]="CannotGetUpdatesBranch",e[e.CannotSetUpdatesBranch=14]="CannotSetUpdatesBranch",e[e.UpdateAlreadyDownloaded=15]="UpdateAlreadyDownloaded",e[e.UpdateDownloadFailed=16]="UpdateDownloadFailed",e[e.UpdateAlreadyInstalled=17]="UpdateAlreadyInstalled",e[e.CannotGetCurrentControllerVersionTimeout=18]="CannotGetCurrentControllerVersionTimeout",e[e.CannotGetCurrentControllerVersion=19]="CannotGetCurrentControllerVersion",e[e.InstallerFileSignCheckFailed=20]="InstallerFileSignCheckFailed",e[e.UpdateFileSignCheckFailed=21]="UpdateFileSignCheckFailed",e[e.UpdateFileCheckFailed=22]="UpdateFileCheckFailed",e[e.UpdateInstallationFailed=23]="UpdateInstallationFailed"}(bg||(bg={})),function(e){e.Public="public",e.Beta="beta",e.Development="dev"}(Gg||(Gg={}));var of,sf,af,cf,uf,lf,df,hf,pf,gf=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class ff{constructor(){this._controllerUpdates=[],this._updateRequestTimeout=12e4,this._oldUpdateVersion=5,this._oldUpdateBuild=56,this._updateOfflineStageTime=15,this._updateProviders=hy.Get(cs.ServiceName),this._logger=hy.Get(a.ServiceName),this._connection=hy.Get(It.ServiceName),this._appStateService=hy.Get(_t.ServiceName),this._extensionService=hy.Get(nt.ServiceName)}IsBranchAndAutomaticUpdatesSettingSupportedAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof Ee)return!1;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);return!(t<this._oldUpdateVersion||t===this._oldUpdateVersion&&n<=this._oldUpdateBuild)}))}DownloadControllerUpdateAsync(e){return gf(this,void 0,void 0,(function*(){try{const t=yield this.getRuntimeInfoAsync();if(t instanceof Ee)return t;const n=parseInt(t.SoftwareVersion.toString().split(".")[0]),r=parseInt(t.SoftwareVersion.toString().split(".")[1]);return n<this._oldUpdateVersion||n===this._oldUpdateVersion&&r<=this._oldUpdateBuild?new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot download update, feature unsupported in current version. Current version: ${t}`):yield this.DownloadControllerUpdateUsingApiAsync((()=>{}),e,!0)}catch(e){return new Ee(bg.CannotProcessUpdate,`Failed to download controller update: ${e}`)}}))}InstallControllerOrRadioUpdateAsync(e,t,n){return gf(this,void 0,void 0,(function*(){const r=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"),o=this._controllerUpdates.length,s=yield this.getRuntimeInfoAsync();if(s instanceof Ee)return s;const i=parseInt(s.SoftwareVersion.toString().split(".")[0]),a=parseInt(s.SoftwareVersion.toString().split(".")[1]);if(0==this._controllerUpdates.length)return new Ee(bg.CannotGetUpdates,"Cannot find any updates, make sure you check for available updates by calling CheckControllerUpdateAsync().");if(void 0===n||"string"!=typeof n||!r.test(n)){const r=[1],s=t=>{t.UpdateNumber=r[0],t.AvailableUpdates=o,e(t)},c=e=>gf(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}));let u=this._controllerUpdates.where((e=>e.UpdateType==_g.RadioUpdate)).toArray(),l=[];this._appStateService.DisallowHibernation();for(let e=0;e<u.length;e++){const t=yield(yield this._updateProviders.GetUpdatesProviderAsync(u[e].ProviderName)).InstallRadioUpdateAsync(u[e],s);yield c(5e3),t==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((t=>t.UpdateIdentifier!=u[e].UpdateIdentifier))),l.push(t),r[0]++}const d=this._controllerUpdates.find((e=>e.UpdateType==_g.SoftwareUpdate));if(null!=d)if(i<this._oldUpdateVersion||i===this._oldUpdateVersion&&a<=this._oldUpdateBuild){const e=yield this.UpdateControllerUsingScriptAsync(d.Update,s);e==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=d.UpdateIdentifier))),l.push(e),r[0]++}else{const e=yield this.UpdateControllerUsingApiAsync(s,t,!1);this._appStateService.AllowHibernation(),e==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),l.push(e),r[0]++}const h=l.where((e=>e instanceof Ee)).toArray();if(null!=h&&0!=h.length){let e="";return h.forEach((t=>e+=`${t.Type}, `)),this._appStateService.AllowHibernation(),h.any((e=>e.Type==bg.UpdateDownloadFailed))?new Ee(bg.UpdateDownloadFailed,`Update download failed - not all updates were successfully downloaded. Installation error codes: ${e}`):new Ee(bg.UpdatesPartiallyInstalled,`Update installation finished - not all updates were successfully installed. Installation error codes: ${e}`)}return this._appStateService.AllowHibernation(),ue.OK}{let r;const o=this._controllerUpdates.find((e=>e.UpdateIdentifier==n));if(null==o)return new Ee(bg.CannotGetUpdates,`Update with requested guid (${n}) not found.`);switch(this._logger.Debug(`Installing single update type: ${o.Update.UpdateType}, resource: ${o.UpdatedResourceName}, version: ${o.Update.Version}`),this._appStateService.DisallowHibernation(),o.UpdateType){case _g.RadioUpdate:return r=yield(yield this._updateProviders.GetUpdatesProviderAsync(o.ProviderName)).InstallRadioUpdateAsync(o,e),this._appStateService.AllowHibernation(),this._logger.Debug(`Radio update result: ${r}`),r==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),r;case _g.SoftwareUpdate:return i<this._oldUpdateVersion||i===this._oldUpdateVersion&&a<=this._oldUpdateBuild?(r=yield this.UpdateControllerUsingScriptAsync(o.Update,e),this._appStateService.AllowHibernation(),r==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)))):(yield this.CheckControllerUpdatesAsync(),r=yield this.UpdateControllerUsingApiAsync(e,t,!1),this._appStateService.AllowHibernation(),r==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)))),r;default:return new Ee(bg.CannotProcessUpdate,`Update with type ${o.UpdateType} is not supported by UpdateService.`)}}}))}GetAutomaticControllerUpdateDownloadStatusAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof Ee)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<this._oldUpdateVersion||t===this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot get update branch, feature unsupported in current version. Current version: ${e}`);let r=yield this._connection.SendAndWaitForResponseAsync(new Nf,1e4,!1);return!(r.Status!=ue.OK||!r.Data)}))}GetServiceName(){return ff.ServiceName}CheckDeviceVersionAsync(e){return gf(this,void 0,void 0,(function*(){var t;let n;if("string"==typeof e){const t=yield hy.Get(Ys.ServiceName).GetDevice(e);if(null==t)return new Ee(bg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);n=t}else n=e;if(null==n.ProtocolGuid)return new Ee(bg.UnsupportedDevice,"Device does not contains data about protocol GUID.");const r=yield null===(t=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(n.ProtocolGuid,Po.Device)).first())||void 0===t?void 0:t.GetSoftwareVersionAsync(n);return r.Type,r}))}CheckDeviceUpdateAsync(e){return gf(this,void 0,void 0,(function*(){var t;let n;if("string"==typeof e){const t=yield hy.Get(Ys.ServiceName).GetDevice(e);if(null==t)return new Ee(bg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);n=t}else n=e;if(null==n.ProtocolGuid)return new Ee(bg.UnsupportedDevice,"Device does not contains data about protocol GUID.");const r=yield null===(t=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(n.ProtocolGuid,Po.Device)).first())||void 0===t?void 0:t.GetAvailableUpdateAsync(n);if(null!=r.Type)return r;const o=new mf;o.CurrentResourceVersion=r.CurrentResourceVersion,o.NewResourceVersion=r.Update.Version,o.UpdatedResourceName=r.UpdatedResourceName,o.UpdateResourceGuid=r.Update.ResourceGuid,o.UpdateDescription=new Map([["pl-PL",r.Update.Description]]);let s="n/a";try{s=(yield this._extensionService.GetProtocolInfoAsync(n.ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}return o.Protocol=s,o.ProtocolGuid=n.ProtocolGuid,(yield hy.Get(Ys.ServiceName).GetDevicesAsync()).any((e=>"952ddc14-76c4-4f47-b0bc-5d106c1f9b02"==e.ModelGuid))&&(o.IsUpdateSafe=!1),o}))}CheckDeviceUpdatesBulkAsync(e){return gf(this,void 0,void 0,(function*(){const t=yield yield this._updateProviders.GetUpdatesProvidersAsync(Po.Device),n=[];for(var r of t){const t=yield r.CheckUpdateBulkAsync(e);if(t instanceof Ee)return t;for(const e of t){const t=new mf;t.CurrentResourceVersion=e.CurrentResourceVersion,t.NewResourceVersion=e.Update.Version,t.UpdatedResourceName=e.UpdatedResourceName,t.UpdateDescription=e.UpdateDescription,t.IsUpdateSafe=!0;let o="n/a";try{o=(yield this._extensionService.GetProtocolInfoAsync(r.ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}t.Protocol=o,t.ProtocolGuid=r.ProtocolGuid,t.UpdateResourceGuid=e.Update.ResourceGuid,n.push(t)}}return n}))}InstallDeviceUpdateAsync(e,t,n){return gf(this,arguments,void 0,(function*(e,t,n,r=!1){var o;let s;if("string"==typeof e){const t=yield hy.Get(Ys.ServiceName).GetDevice(e);if(null==t)return new Ee(bg.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);s=t}else s=e;if(null==s.ProtocolGuid)return new Ee(bg.UnsupportedDevice,"Device does not contains data about protocol GUID.");const i=yield null===(o=(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(s.ProtocolGuid,Po.Device)).first())||void 0===o?void 0:o.GetAvailableUpdateAsync(s);if(null!=i.Type)return i;this._appStateService.DisallowHibernation();const a=yield(yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(s.ProtocolGuid,Po.Device)).first().InstallUpdateAsync(i,t,n,r);return null!=a.Type?(this._appStateService.AllowHibernation(),a):(this._appStateService.AllowHibernation(),ue.OK)}))}InstallDevicesUpdateBulkAsync(e,t,n){return gf(this,void 0,void 0,(function*(){const r=(yield hy.Get(Ys.ServiceName).GetDevicesAsync()).where((t=>e.includes(t.Guid))).groupBy((e=>e.ProtocolGuid)),o=[];this._appStateService.DisallowHibernation();const s=r.count();for(let e=0;e<s;e++){const i=r.elementAt(e),a=e*(100/s),c=(e+1)*(100/s),u=e=>{e.PercentageTotal=Math.floor(e.PercentageTotal/100*(c-a)+a),t(e)},l=yield yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(i.key,Po.Device),d=yield l.first().InstalUpdateBulkAsync(i.select((e=>e.Guid)).toArray(),u,n);if(d instanceof Ee)return d;o.push(d)}if(this._appStateService.AllowHibernation(),1==o.length)return o[0];{const e=new rf;o.some((e=>e.DevicesUpdateResults.count()>0))&&o.any((e=>e.BulkUpdateStatus!=kg.Success))?e.BulkUpdateStatus=kg.PartialSuccess:o.any((e=>e.BulkUpdateStatus!=kg.Success))?e.BulkUpdateStatus=o.first().BulkUpdateStatus:e.BulkUpdateStatus=kg.Success;for(const t of o)t.DevicesUpdateResults.forEach(((t,n)=>{e.DevicesUpdateResults.set(n,t)}));return e}}))}CheckControllerSoftwareUpdateAvailabilityAsync(){return gf(this,void 0,void 0,(function*(){const e=hy.Get(Xe.ServiceName).User;if(null==e)return!1;if(""==e.SoftwareVersion||null==e.SoftwareVersion)return!0;const[t,n]=e.SoftwareVersion.split(".");if(parseFloat(t)<this._oldUpdateVersion||parseFloat(t)==this._oldUpdateVersion&&parseFloat(n)<=this._oldUpdateBuild)return!0;const r=yield this._connection.SendAndWaitForResponseAsync(new If,1e4,!1);if(null==r||r.Status!=ue.OK||null==r.Data)return!1;const[o,s]=r.Data.Update.Version.ContainerSoftwareVersion.toString().split(".");return parseInt(o)>parseInt(t)||parseInt(o)==parseInt(t)&&parseInt(s)>parseInt(n)}))}CanCancelFailedControllerUpdateOrGetPendingUpdateProgress(){return hy.Get(ct.ServiceName).CheckIfControllerSoftwareVersionIsEnough(6,66)}CancelFailedControllerUpdateAsync(){return gf(this,void 0,void 0,(function*(){switch((yield this._connection.SendAndWaitForResponseAsync(new Tf,1e4,!1)).Status){case ue.OK:return ue.OK;case ue.OperationNotPermitted:return ue.OperationNotPermitted;case ue.Error:default:return ue.Error}}))}CheckControllerPendingUpdateProgressAsync(e,t){return gf(this,void 0,void 0,(function*(){return new Promise(((n,r)=>gf(this,void 0,void 0,(function*(){var o;const s=hy.Get(Xe.ServiceName).User;if(null==s)return n(new Ee(bg.UpdateActionsNotSupported,"No user data found, cannot check pending update progress."));if(""==s.SoftwareVersion||null==s.SoftwareVersion)return n(new Ee(bg.CannotGetCurrentControllerVersion,"No software version data found, cannot check pending update progress."));const[i,a]=s.SoftwareVersion.split(".");if(parseFloat(i)<this._oldUpdateVersion||parseFloat(i)==this._oldUpdateVersion&&parseFloat(a)<=this._oldUpdateBuild)return n(new Ee(bg.UnsupportedApiVersion,"Not supported API version, cannot check pending update progress."));const c=yield this._connection.SendAndWaitForResponseAsync(new If,1e4,!1);if(c.Status!=ue.OK)return n(new Ee(bg.CannotGetUpdates,"No pending updates found."));let u=null===(o=c.Data)||void 0===o?void 0:o.DownloadOnly,l=100;const d=60*this._updateOfflineStageTime*1e3;let h=0;const p=new tf;let g=50,f=new nf,v=new tf,y=!1;u||(f.DownloadOnly=u,g=100);let m=100/g;const w=n=>{let r=n.Data;switch(this._logger.Debug(`Update progress: ${r.UpdateStep}, ${r.StepProgressInPercentage}%, ${r.UpdateProgressInPercentage}% data frame status: ${n.Status}`),p.Percentage=Math.round(r.StepProgressInPercentage),p.PercentageTotal=Math.round(r.UpdateProgressInPercentage),f.SpeedMbps=r.DownloadSpeedInMbs,f.Percentage=Math.round(r.StepProgressInPercentage),f.PercentageTotal=Math.round(r.UpdateProgressInPercentage),f.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),v.AvailableUpdates=1,v.Percentage=r.StepProgressInPercentage,v.PercentageTotal=r.UpdateProgressInPercentage,v.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),h=r.StepProgressInPercentage,r.UpdateStep){case cf.DownloadingInstaller:f.CurrentTask=Eg.DownloadingInstaller,v.Status=Cg.DownloadingPackage,t(f);break;case cf.DownloadingUpdate:f.CurrentTask=Eg.DownloadingUpdate,v.Status=Cg.DownloadingPackage,t(f);break;case cf.CheckingUpdate:f.CurrentTask=Eg.CheckingUpdate,v.Status=Cg.CheckingPackage,e(v);break;case cf.PreparingUpdate:v.Status=Cg.PreparingForUpgrade,f.CurrentTask=Eg.CheckingUpdate,e(v);break;case cf.OfflineUpdateStep:case cf.InstallingUpdate:v.Status=Cg.Upgrading,e(v);break;case cf.InstallerFileSignCheckFailed:case cf.UpdateFileSignCheckFailed:v.Status=Cg.InstallationError,e(v);break;case cf.UpdateDownloadFailed:v.Status=Cg.InstallationStopped,e(v);break;case cf.UpdateInstallationFailed:v.Status=Cg.InstallationError,e(v);break;case cf.UpdateFileCheckFailed:v.Status=Cg.IncompatiblePackage,e(v);break;case cf.UpdateDownloaded:f.Percentage=100,f.PercentageTotal=u?Math.round(r.UpdateProgressInPercentage*m):Math.round(r.UpdateProgressInPercentage),f.SpeedMbps=0,f.CurrentTask=Eg.CheckingUpdate,t(f),f.CurrentTask=Eg.UpdateDownloadedAndChecked,t(f)}};let S=null;const A=t=>gf(this,void 0,void 0,(function*(){t==it.Connected&&(clearInterval(S),p.Status=Cg.Upgraded,p.Percentage=100,p.PercentageTotal=100,e(p),clearInterval(S),yield se.Delay(5e3),n(ue.OK),hy.Get(_t.ServiceName).OnAppStateChanged().Unsubscribe(A))}));yield this._connection.SendAndHandleResponseAsync(new kf,1e5,(o=>{var s,i,a,c,g;switch(o.Status){case ue.MultiDataResponseStart:y||(l=(null===(s=o.Data)||void 0===s?void 0:s.UpdateStep)==cf.UpdateDownloaded?100:50,y=!0),w(o);break;case ue.MultiDataResponse:w(o);break;case ue.MultiDataResponseStop:switch(null===(i=o.Data)||void 0===i?void 0:i.UpdateStep){case cf.UpdateInstallationFailed:v.Status=Cg.InstallationError,e(v),p.Percentage=0,p.PercentageTotal=0,e(p),n(new Ee(bg.CannotProcessUpdate,"Update installation failed!"));break;case cf.InstallerFileSignCheckFailed:case cf.UpdateFileSignCheckFailed:case cf.UpdateDownloadFailed:case cf.UpdateFileCheckFailed:v.Status=Cg.DownloadingFailure,e(v),p.Percentage=0,p.PercentageTotal=0,e(p),n(new Ee(bg.UpdateDownloadFailed,"Update download failed!"));break;case cf.OfflineUpdateStep:w(o),p.Percentage=Math.round(o.Data.StepProgressInPercentage),p.PercentageTotal=Math.round(o.Data.UpdateProgressInPercentage);let r=(100-p.PercentageTotal)/100,s=p.PercentageTotal;S=setInterval((()=>{h++,s+=r,s>100&&(s=100),h>=l?(p.Status=Cg.Upgraded,p.Percentage=100,p.PercentageTotal=100,e(p),clearInterval(S),n(ue.OK)):(p.Status=Cg.Upgrading,p.Percentage=Math.round(h),p.PercentageTotal=Math.round(s),e(p))}),d/(l-h)),hy.Get(_t.ServiceName).OnAppStateChanged().Subscribe(A);break;case cf.UpdateDownloaded:f.Percentage=100,f.PercentageTotal=u?Math.round((null===(a=o.Data)||void 0===a?void 0:a.UpdateProgressInPercentage)*m):Math.round(null===(c=o.Data)||void 0===c?void 0:c.UpdateProgressInPercentage),f.SpeedMbps=0,f.CurrentTask=Eg.CheckingUpdate,t(f),f.CurrentTask=Eg.UpdateDownloadedAndChecked,t(f),u&&n(ue.OK);break;default:w(o),n(new Ee(bg.CannotProcessUpdate,`Update installation failed, received UpdateStep code: ${null===(g=o.Data)||void 0===g?void 0:g.UpdateStep}!`))}break;default:r(new Ee(bg.CannotGetUpdates,`Cannot get pending update progress, response is empty or status is not OK. Status: ${null==o?void 0:o.Status}`))}}),!0)}))))}))}CheckDevicesUpdatesAvailabilityAsync(){return gf(this,void 0,void 0,(function*(){const e=hy.Get(Xe.ServiceName).User;if(null==e)return[];if(""==e.SoftwareVersion||null==e.SoftwareVersion)return[];const[t,n]=e.SoftwareVersion.split(".");if(parseFloat(t)<6||6==parseFloat(t)&&parseFloat(n)<=4)return[];const r=yield this._connection.SendAndWaitForResponseAsync(new Of,1e4,!1),o=[];return null==r||(null==r?void 0:r.Status)!=ue.OK||null==(null==r?void 0:r.Data)?[]:(null==r||r.Data.forEach((e=>{if(!e.IsAvailable)return;const t=new Yg;t.DeviceGuid=e.DeviceGuid,t.CurrentVersion=e.CurrentVersion,t.NewVersion=e.NewVersion,o.push(t)})),o)}))}CheckControllerUpdatesAsync(){return gf(this,void 0,void 0,(function*(){this._controllerUpdates=[];let e=[];const t=new Qg,n=yield this.getRuntimeInfoAsync();if(n instanceof Ee){const e=new vf;return e.UpdateType=_g.SoftwareUpdate,e.ResponseResult=n,t.UpdatesNotAvailable.push(e),t}const r=parseInt(n.SoftwareVersion.toString().split(".")[0]),o=parseInt(n.SoftwareVersion.toString().split(".")[1]);try{e=yield this._updateProviders.GetUpdatesProvidersAsync(Po.Controller)}catch(e){if(!(e instanceof $o))throw e;this._logger.Warning("Cannot get update providers for controller protocols! Avaliable only controller software updates!")}for(let n=0;n<e.length;n++){const r=yield e[n].GetAvailableRadioUpdateAsync();if(null!=r.Type){const o=new vf;o.ResponseResult=r,o.UpdateType=_g.RadioUpdate;let s="n/a";try{s=(yield this._extensionService.GetProtocolInfoAsync(e[n].ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}o.UpdatedResourceName=new Map([["pl-PL",s],["en-US",s]]),o.CurrentResourceVersion=yield e[n].GetCurrentRadioVersionAsync(),t.UpdatesNotAvailable.push(o)}else{const o=r,s=new yf;s.UpdatedResourceName=new Map([["pl-PL",o.UpdatedResourceName],["en-US",o.UpdatedResourceName]]),s.CurrentResourceVersion=o.CurrentResourceVersion,s.NewResourceVersion=o.Update.Version,s.UpdateDescription=new Map([["pl-PL",o.Update.Description]]),s.UpdateType=_g.RadioUpdate,s.UpdateIdentifier=oe.GenerateUUID(),s.UpdateIsDownloading=!1,s.DownloadProgress=100,s.UpdateCreationTime=null,t.UpdatesAvailable.push(s),this._controllerUpdates.push(Object.assign(Object.assign({},o),{UpdateIdentifier:s.UpdateIdentifier,ProviderName:e[n].GetUpdateProviderName(),UpdateType:_g.RadioUpdate}))}}let s=!0;if((r<this._oldUpdateVersion||r===this._oldUpdateVersion&&o<=this._oldUpdateBuild)&&(s=!1),s){const e=yield this._connection.SendAndWaitForResponseAsync(new If,15e3,!1);if(null==e||e.Status!=ue.OK&&e.Status!=ue.NoData)throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==e?void 0:e.Status}`);if(null!=e.Data){const r=new Wo;r.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,r.UpdateDescription=ie(e.Data.Update.UpdateDescription),r.UpdatedResourceName=ie(e.Data.Update.UpdateName).get("en-US");const o=new yf;o.UpdatedResourceName=ie(e.Data.Update.UpdateName),o.UpdateDescription=ie(e.Data.Update.UpdateDescription),o.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,o.NewResourceVersion=`${e.Data.Update.Version.BaseRuntime}.${e.Data.Update.Version.ContainerSoftwareVersion}`,o.UpdateType=_g.SoftwareUpdate,o.UpdateIdentifier=e.Data.Update.Guid,o.UpdateIsDownloading=e.Data.UpdateStep==cf.DownloadingInstaller||e.Data.UpdateStep==cf.DownloadingUpdate||e.Data.UpdateStep==cf.CheckingUpdate,o.DownloadProgress=e.Data.DownloadProgress,o.UpdateCreationTime=e.Data.Update.Creationtime,o.IsDownloadOnly=e.Data.DownloadOnly,t.UpdatesAvailable.push(o),this._controllerUpdates.push(Object.assign(Object.assign({},r),{UpdateIdentifier:o.UpdateIdentifier,ProviderName:ff.ServiceName,UpdateType:_g.SoftwareUpdate}))}else{const e=yield this._connection.SendAndWaitForResponseAsync(new Ef,15e3,!1);if(null==e)throw new Error("Cannot check updates! Response is empty.");switch(e.Status){case ue.NoData:const r=new vf;r.UpdateType=_g.SoftwareUpdate,r.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),r.ResponseResult=new Ee(bg.DeviceIsUpToDate,"Updates not found, controller is already up-to-date."),t.UpdatesNotAvailable.push(r);break;case ue.OK:if(null==e.Data)throw new Error("Cannot check updates! Response data is empty.");const o=new Wo;o.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,o.UpdateDescription=ie(e.Data.UpdateDescription),o.UpdatedResourceName=ie(e.Data.UpdateName).get("en-US");const s=new yf;s.UpdatedResourceName=ie(e.Data.UpdateName),s.UpdateDescription=ie(e.Data.UpdateDescription),s.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,s.UpdateType=_g.SoftwareUpdate,s.UpdateIdentifier=e.Data.Guid,s.NewResourceVersion=`${e.Data.Version.BaseRuntime}.${e.Data.Version.ContainerSoftwareVersion}`,s.UpdateIsDownloading=!1,s.DownloadProgress=0,s.UpdateCreationTime=e.Data.Creationtime,t.UpdatesAvailable.push(s),this._controllerUpdates.push(Object.assign(Object.assign({},o),{UpdateIdentifier:s.UpdateIdentifier,ProviderName:ff.ServiceName,UpdateType:_g.SoftwareUpdate}));break;default:throw new Error(`Cannot check updates! Response status is not OK. Status: ${e.Status}`)}}}else{const e=`https://exalus-updates.tr7.pl/software/${n.UpdateChannel}/${n.RuntimeVersion}/${n.SoftwareVersion}/update.json`;try{const r=yield fetch(e);let o,s=new Wo;const i=new vf;switch(i.UpdateType=_g.SoftwareUpdate,i.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),r.status){case 200:null!=r.body&&(o=yield r.json());break;case 404:i.ResponseResult=new Ee(bg.DeviceIsUpToDate,"Updates not found, controller is already up-to-date."),t.UpdatesNotAvailable.push(i);break;default:i.ResponseResult=new Ee(bg.CannotGetUpdates,`Response status code does not indicate success. Status: ${r.status}`),t.UpdatesNotAvailable.push(i)}if(null!=o){s.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,s.Update=o;const e=new yf;e.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),e.CurrentResourceVersion=s.CurrentResourceVersion,e.NewResourceVersion=s.Update.Version,e.UpdateDescription=new Map([["pl-PL",s.Update.Description]]),e.UpdateType=_g.SoftwareUpdate,e.UpdateIdentifier=oe.GenerateUUID(),e.DownloadProgress=100,e.UpdateIsDownloading=!1,e.UpdateCreationTime=null,t.UpdatesAvailable.push(e),this._controllerUpdates.push(Object.assign(Object.assign({},s),{UpdateIdentifier:e.UpdateIdentifier,ProviderName:ff.ServiceName,UpdateType:_g.SoftwareUpdate}))}else if(200==r.status)throw new Error(`Cannot get Update Data from response. Status: ${r.status}`)}catch(e){const n=yield this.getRuntimeInfoAsync();if(n instanceof Ee){const e=new vf;e.UpdateType=_g.SoftwareUpdate,e.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),e.ResponseResult=n,t.UpdatesNotAvailable.push(e)}else{const r=new vf;r.UpdateType=_g.SoftwareUpdate,r.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),r.ResponseResult=new Ee(bg.CannotGetUpdates,`Cannot get available updates! ${e}`),r.CurrentResourceVersion=`${n.RuntimeVersion}.${n.SoftwareVersion}`,t.UpdatesNotAvailable.push(r)}}}return t}))}CheckControllerVersionAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this._updateProviders.GetUpdatesProvidersAsync(Po.Controller),t=yield this.getRuntimeInfoAsync();if(t instanceof Ee)return t;const n=[];let r;r=new ef,r.Resource="Controller software",r.Type=_g.SoftwareUpdate,r.Version=`${t.RuntimeVersion}.${t.SoftwareVersion}`,n.push(r);for(let t=0;t<e.length;t++){r=new ef,r.Version=yield e[t].GetCurrentRadioVersionAsync(),r.Type=_g.RadioUpdate;let o="n/a";try{o=(yield this._extensionService.GetProtocolInfoAsync(e[t].ProtocolGuid)).first().Name}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}r.Resource=o,n.push(r)}return n}))}GetControllerUpdateBranchAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof Ee)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<this._oldUpdateVersion||t===this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot get update branch, feature unsupported in current version. Current version: ${e}`);const r=yield this._connection.SendAndWaitForResponseAsync(new Cf,1e4,!1);if(null==r||(null==r?void 0:r.Status)!=ue.OK)return new Ee(bg.CannotGetUpdatesBranch,`Cannot get update branch, response is empty or status is not OK. Status: ${null==r?void 0:r.Status}`);switch(r.Data){case 0:return Gg.Public;case 1:return Gg.Beta;case 2:return Gg.Development;default:return new Ee(bg.CannotGetUpdatesBranch,`Cannot get update branch, unknown branch number. Branch number: ${r.Data}`)}}))}SetControllerUpdateBranchAsync(e){return gf(this,void 0,void 0,(function*(){const t=yield this.getRuntimeInfoAsync();if(t instanceof Ee)return t;const n=parseInt(t.SoftwareVersion.toString().split(".")[0]),r=parseInt(t.SoftwareVersion.toString().split(".")[1]);if(n<this._oldUpdateVersion||n===this._oldUpdateVersion&&r<=this._oldUpdateBuild)return new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot set update branch, feature unsupported in current version. Current version: ${t}`);const o=yield this._connection.SendAndWaitForResponseAsync(new Df(e),1e4,!1);return null==o||(null==o?void 0:o.Status)!=ue.OK?new Ee(bg.CannotSetUpdatesBranch,`Cannot set update branch, response is empty or status is not OK. Status: ${null==o?void 0:o.Status}`):ue.OK}))}EnableAutomaticControllerUpdateDownloadAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof Ee)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<this._oldUpdateVersion||t===this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot enable automatic updates download, feature unsupported in current version. Current version: ${e}`);const r=yield this._connection.SendAndWaitForResponseAsync(new Rf,1e4,!1);return null==r||(null==r?void 0:r.Status)!=ue.OK?new Ee(bg.CannotSetUpdatesBranch,`Cannot enable automatic updates download, response is empty or status is not OK. Status: ${null==r?void 0:r.Status}`):ue.OK}))}DisableAutomaticControllerUpdateDownloadAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof Ee)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<this._oldUpdateVersion||t===this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot disable automatic update download, feature unsupported in current version. Current version: ${e}`);const r=yield this._connection.SendAndWaitForResponseAsync(new Pf,1e4,!1);return null==r||(null==r?void 0:r.Status)!=ue.OK?new Ee(bg.CannotSetUpdatesBranch,`Cannot disable automatic update download, response is empty or status is not OK. Status: ${null==r?void 0:r.Status}`):ue.OK}))}GetControllerUpdatesHistoryAsync(){return gf(this,void 0,void 0,(function*(){const e=yield this.getRuntimeInfoAsync();if(e instanceof Ee)return e;const t=parseInt(e.SoftwareVersion.toString().split(".")[0]),n=parseInt(e.SoftwareVersion.toString().split(".")[1]);if(t<this._oldUpdateVersion||t===this._oldUpdateVersion&&n<=this._oldUpdateBuild)return new Ee(bg.FeatureUnsupportedInCurrentVersion,`Cannot disable automatic update download, feature unsupported in current version. Current version: ${e}`);const r=yield this._connection.SendAndWaitForResponseAsync(new Uf,1e4,!1);if(null==r)return new Ee(bg.CannotGetUpdates,"Cannot get updates history, response is empty.");switch(r.Status){case ue.OK:return null!=r.Data?r.Data.map((e=>{const t=new Zg;return t.UpdatedResourceName=ie(e.UpdateName),t.UpdateDescription=ie(e.UpdateDescription),t.UpdateCreationTime=e.Creationtime,t.UpdateChannel=e.UpdateChannel,t.Version=`${e.Version.BaseRuntime}.${e.Version.ContainerSoftwareVersion}`,t})):new Ee(bg.CannotGetUpdates,"Cannot get updates history, response data is empty.");case ue.NoData:return[];default:return new Ee(bg.CannotGetUpdates,`Cannot get updates history, response status is not OK. Status: ${r.Status}`)}}))}InstallControllerUpdateAsync(e,t,n,r,o){return gf(this,void 0,void 0,(function*(){const s=new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"),i=this._controllerUpdates.length,a=yield this.getRuntimeInfoAsync();if(a instanceof Ee)return a;const c=parseInt(a.SoftwareVersion.toString().split(".")[0]),u=parseInt(a.SoftwareVersion.toString().split(".")[1]);if(0==this._controllerUpdates.length)return new Ee(bg.CannotGetUpdates,"Cannot find any updates, make sure you check for available updates by calling CheckControllerUpdateAsync().");if("string"!=typeof n||!s.test(n)){const o=[1],s=t=>{t.UpdateNumber=o[0],t.AvailableUpdates=i,e(t)},a=e=>gf(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}));let l=this._controllerUpdates.where((e=>e.UpdateType==_g.RadioUpdate)).toArray(),d=[];this._appStateService.DisallowHibernation();for(let e=0;e<l.length;e++){const t=yield(yield this._updateProviders.GetUpdatesProviderAsync(l[e].ProviderName)).InstallRadioUpdateAsync(l[e],s,n);yield a(5e3),t==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((t=>t.UpdateIdentifier!=l[e].UpdateIdentifier))),d.push(t),o[0]++}const h=this._controllerUpdates.find((e=>e.UpdateType==_g.SoftwareUpdate));if(null!=h)if(c<this._oldUpdateVersion||c===this._oldUpdateVersion&&u<=this._oldUpdateBuild){const e=yield this.UpdateControllerUsingScriptAsync(h.Update,s);e==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=h.UpdateIdentifier))),d.push(e),o[0]++}else{const e=yield this.UpdateControllerUsingApiAsync(s,t,r);this._appStateService.AllowHibernation(),e==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),d.push(e),o[0]++}const p=d.where((e=>e instanceof Ee)).toArray();if(null!=p&&0!=p.length){let e="";return p.forEach((t=>e+=`${t.Type}, `)),this._appStateService.AllowHibernation(),p.any((e=>e.Type==bg.UpdateDownloadFailed))?new Ee(bg.UpdateDownloadFailed,`Update download failed - not all updates were successfully downloaded. Installation error codes: ${e}`):new Ee(bg.UpdatesPartiallyInstalled,`Update installation finished - not all updates were successfully installed. Installation error codes: ${e}`)}return this._appStateService.AllowHibernation(),ue.OK}{let s;const i=this._controllerUpdates.find((e=>e.UpdateIdentifier==n));if(null==i)return new Ee(bg.CannotGetUpdates,`Update with requested guid (${n}) not found.`);switch(this._logger.Debug(`Installing single update type: ${i.Update.UpdateType}, resource: ${i.UpdatedResourceName}, version: ${i.Update.Version}`),this._appStateService.DisallowHibernation(),i.UpdateType){case _g.RadioUpdate:return r?new Ee(bg.UpdateAlreadyDownloaded,"Update already downloaded set flag downloadOnly to false to install it."):(s=yield(yield this._updateProviders.GetUpdatesProviderAsync(i.ProviderName)).InstallRadioUpdateAsync(i,e,o),this._appStateService.AllowHibernation(),s==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n))),s);case _g.SoftwareUpdate:if(c<this._oldUpdateVersion||c===this._oldUpdateVersion&&u<=this._oldUpdateBuild){if(r)return new Ee(bg.UpdateAlreadyDownloaded,"Update already downloaded set flag downloadOnly to false to install it.");s=yield this.UpdateControllerUsingScriptAsync(i.Update,e),this._appStateService.AllowHibernation(),s==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)))}else{let o=(yield this.CheckControllerUpdatesAsync()).UpdatesAvailable.any((e=>e.IsDownloadOnly));s=yield this.UpdateControllerUsingApiAsync(e,t,!o&&r),this._appStateService.AllowHibernation(),s==ue.OK&&(this._controllerUpdates=this._controllerUpdates.filter((e=>e.UpdateIdentifier!=n)))}return s;default:return new Ee(bg.CannotProcessUpdate,`Update with type ${i.UpdateType} is not supported by UpdateService.`)}}}))}UpdateControllerUsingScriptAsync(e,t){return gf(this,void 0,void 0,(function*(){var n,r,o,s,i,a;switch(e.UpdateType){case Uo.Container:case Uo.ContainerSoftware:try{return yield null===(n=this._connection)||void 0===n?void 0:n.SendAndHandleResponseAsync(new wf(e.DownloadUri),this._updateRequestTimeout,(n=>{const r=new tf;switch(r.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),n.Status){case ue.MultiDataResponseStart:r.Status=Cg.PreparingForUpgrade;break;case ue.MultiDataResponse:if(null==n.Data)return void this._logger.Warning(ff.ServiceName,`Recived update response without data! URI: ${e.DownloadUri}`);switch(r.Percentage=Math.round(n.Data.Progress),n.Data.State){case Dg.CheckingApplicability:case Dg.CheckingIntegrity:case Dg.CheckingPackageIntegrity:r.Status=Cg.CheckingPackage;break;case Dg.CreatingBackup:case Dg.MigratingData:case Dg.Removing:r.Status=Cg.MovingData;break;case Dg.Deploying:case Dg.Installing:r.Status=Cg.Upgrading;break;case Dg.Downloading:r.Status=Cg.DownloadingPackage;break;case Dg.Error:r.Status=Cg.Error;break;case Dg.Installed:r.Status=Cg.Upgraded;break;case Dg.PreparingSystem:case Dg.ReadyToDownload:r.Status=Cg.PreparingForUpgrade;break;case Dg.UndoingInstallation:r.Status=Cg.InstallationStopped;break;case Dg.Unpackaging:r.Status=Cg.MovingData;break;case Dg.WaitingForUser:r.Status=Cg.Upgrading}break;case ue.MultiDataResponseStop:r.Status=Cg.OK;break;case ue.Error:case ue.FatalError:r.Status=Cg.Error}t(r)}),!1),ue.OK}catch(e){return new Ee(bg.CannotProcessUpdate,`Cannot process update, error: ${e}`)}case Uo.RuntimeFixingScript:var c=10;let d="n/a";try{d=(yield this._extensionService.GetExtensionsInfoAsync()).first((e=>"f4f45dac-beda-441a-8d29-efc6dc977cd1"==e.ExtensionGuid)).ExtensionVersion}catch(e){this._logger.Warning(`Cannot get protocol name! error: ${e}`)}var u=d;const h=yield this.getRuntimeInfoAsync();if(h instanceof Ee)return h;var l=parseFloat(h.RuntimeVersion)>=2||parseFloat(u)>=1.2201125;try{c=(yield hy.Get(Ys.ServiceName).GetDevicesAsync()).length}catch(e){this._logger.Warning(ff.ServiceName,`Cannot get number of devices in system! Error: ${e}. Using default value of 10 devices.`)}if(l){let n,r=new tf;r.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),r.Percentage=1,r.Status=Cg.PreparingForUpgrade,t(r);let o=2;const s=Date.now(),i=900*c+16e5,a=i/100,u=s+i,l=new Promise(((s,c)=>gf(this,void 0,void 0,(function*(){var c;try{const l=()=>{if(this._appStateService.OnReturnedFromSuspension().Unsubscribe(l),Date.now()>u)clearInterval(n),this._logger.Debug("Update already finished!"),r.Percentage=100,r.PercentageTotal=Math.round(r.Percentage),r.Status=Cg.Upgraded,t(r),s(ue.OK);else{var e=u-Date.now();e<i?o=95-e/a:(clearInterval(n),n=setInterval((()=>{clearInterval(n),r.Percentage=100,r.PercentageTotal=Math.round(r.Percentage),r.Status=Cg.Upgraded,t(r),s(ue.OK)}),e))}};this._appStateService.OnReturnedFromSuspension().Subscribe(l),n=setInterval((()=>{if(o>99)clearInterval(n),r.Percentage=100,r.PercentageTotal=Math.round(r.Percentage),r.Status=Cg.Upgraded,t(r),s(ue.OK);else{var e=o;e<99&&(r.Percentage=Math.round(e),r.PercentageTotal=Math.round(r.Percentage),r.Status=Cg.Upgrading,t(r))}o++}),a);const d=yield null===(c=this._connection)||void 0===c?void 0:c.SendAndWaitForResponseAsync(new Sf(e.DownloadUri),this._updateRequestTimeout,!1);d.Status!=ue.OK&&(clearInterval(n),r.Percentage=0,r.PercentageTotal=Math.round(r.Percentage),r.Status=Cg.InstallationError,t(r),this._logger.Debug(ff.ServiceName,`Update failed with error. Update response status: ${d.Status}`),s(new Ee(bg.CannotProcessUpdate,`Update failed with error. Update response status: ${d.Status}`)))}catch(e){this._logger.Debug(ff.ServiceName,`Update failed with error. ${e}`),r.Percentage=0,r.PercentageTotal=Math.round(r.Percentage),r.Status=Cg.Error,t(r),clearInterval(n),s(new Ee(bg.CannotProcessUpdate,`Update failed with error. ${e}`))}}))));return yield l}{let n=new tf;n.UpdatedResourceName=new Map([["pl-PL","Oprogramowanie kontrolera"],["en-US","Controller software"]]),n.Percentage=1,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.PreparingForUpgrade,t(n);const u=this._connection.GetAuthorizationInfo();if(null==u)return new Ee(bg.CannotProcessUpdate,"Cannot process update. Cannot get current controller login credentials!");if((yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Af({Email:"support@support",Password:`support@${u.SerialNumber}:${u.PIN}`}),12e3,!1)).Status===ue.OK){n.Percentage=1,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.PreparingForUpgrade,t(n);let r=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new _f("rm /runtime/tmp/update.sh"),12e3,!1);if(r.Status==ue.OK){if(this._logger.Debug("Removed previous script"),n.Percentage=2,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.PreparingForUpgrade,t(n),r=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(new _f(`wget ${e.DownloadUri} -O /runtime/tmp/update.sh --no-check-certificate`),this._updateRequestTimeout,!1),r.Status==ue.OK){this._logger.Debug("Downloaded update script"),n.Percentage=5,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.PreparingForUpgrade,t(n);try{if(r=yield null===(i=this._connection)||void 0===i?void 0:i.SendAndWaitForResponseAsync(new _f("chmod a+x /runtime/tmp/update.sh"),12e3,!1),r.Status==ue.OK){this._logger.Debug("Executed update script"),n.Percentage=5,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.Upgrading,t(n);let e,r=0;const o=.95,s=Date.now(),i=900*c+15e5,a=i/95,u=s+i,l=new Promise(((s,c)=>gf(this,void 0,void 0,(function*(){var c;try{const l=()=>{if(this._appStateService.OnReturnedFromSuspension().Unsubscribe(l),Date.now()>u)clearInterval(e),this._logger.Debug("Update already finished!"),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.Upgraded,t(n),s(ue.OK);else{var o=u-Date.now();o<i?r=95-o/a:(clearInterval(e),e=setInterval((()=>{clearInterval(e),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.Upgraded,t(n),s(ue.OK)}),o))}};this._appStateService.OnReturnedFromSuspension().Subscribe(l),e=setInterval((()=>{if(r>99)clearInterval(e),n.Percentage=100,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.Upgraded,t(n),s(ue.OK);else{var i=5+r*o;i<99&&(n.Percentage=Math.round(i),n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.Upgrading,t(n))}r++}),a),null===(c=this._connection)||void 0===c||c.SendAndWaitForResponseAsync(new _f("/runtime/tmp/update.sh"),12e3,!1)}catch(e){s(new Ee(bg.CannotProcessUpdate,`Update failed with error. ${e}`))}}))));return yield l}return n.Percentage=0,n.PercentageTotal=Math.round(n.Percentage),n.Status=Cg.InstallationError,t(n),new Ee(bg.CannotProcessUpdate,"Execution failed!")}catch(e){return null===(a=this._connection)||void 0===a||a.SendAndWaitForResponseAsync(new _f("/runtime/scripts/restart_all.sh"),12e3,!1),new Ee(bg.CannotProcessUpdate,`Execution failed! Error ${e}`)}}return new Ee(bg.CannotProcessUpdate,"Execution failed! Cannot clear old update script!")}}return new Ee(bg.CannotProcessUpdate,"Execution failed! Cannot loggin using support account!")}default:return new Ee(bg.CannotProcessUpdate,`Not supported update type, type: ${e.UpdateType}`)}}))}DownloadControllerUpdateNewApiAsync(e,t,n,r){return gf(this,void 0,void 0,(function*(){return new Promise(((t,o)=>gf(this,void 0,void 0,(function*(){let o=50;r||(o=100);let s=100/o;yield this._connection.SendAndHandleResponseAsync(new bf,this._updateRequestTimeout,(o=>{var i,a,c,u,l,d;const h=new nf;switch(h.DownloadOnly=r,h.UpdatedResourceName=ie(e.Update.UpdateName),o.Status){case ue.MultiDataResponseStart:h.Percentage=0,h.SpeedMbps=0,h.PercentageTotal=0,h.CurrentTask=Eg.DownloadingInstaller,n(h);break;case ue.MultiDataResponse:if(null!=o.Data){switch(h.Percentage=o.Data.StepProgressInPercentage,h.SpeedMbps=o.Data.DownloadSpeedInMbs,h.PercentageTotal=r?Math.round((null===(i=o.Data)||void 0===i?void 0:i.UpdateProgressInPercentage)*s):Math.round(null===(a=o.Data)||void 0===a?void 0:a.UpdateProgressInPercentage),o.Data.UpdateStep){case cf.DownloadingInstaller:h.CurrentTask=Eg.DownloadingInstaller;break;case cf.DownloadingUpdate:h.CurrentTask=Eg.DownloadingUpdate;break;case cf.UpdateDownloaded:h.Percentage=100,h.PercentageTotal=r?Math.round((null===(c=o.Data)||void 0===c?void 0:c.UpdateProgressInPercentage)*s):Math.round(null===(u=o.Data)||void 0===u?void 0:u.UpdateProgressInPercentage),h.SpeedMbps=0,h.CurrentTask=Eg.CheckingUpdate,n(h),h.CurrentTask=Eg.UpdateDownloadedAndChecked,n(h),t(ue.OK);break;default:h.CurrentTask=Eg.CheckingUpdate}n(h)}break;case ue.MultiDataResponseStop:if(null!=o.Data)switch(o.Data.UpdateStep){case cf.UpdateDownloaded:h.Percentage=100,h.PercentageTotal=r?Math.round((null===(l=o.Data)||void 0===l?void 0:l.UpdateProgressInPercentage)*s):Math.round(null===(d=o.Data)||void 0===d?void 0:d.UpdateProgressInPercentage),h.SpeedMbps=0,h.CurrentTask=Eg.CheckingUpdate,n(h),h.CurrentTask=Eg.UpdateDownloadedAndChecked,n(h),t(ue.OK);break;case cf.UpdateDownloadFailed:h.Percentage=0,h.PercentageTotal=0,h.SpeedMbps=0,h.CurrentTask=Eg.Unknown,n(h),t(new Ee(bg.UpdateDownloadFailed,"Update download failed!"))}break;case ue.Error:case ue.FatalError:h.Percentage=0,h.PercentageTotal=0,h.SpeedMbps=0,h.CurrentTask=Eg.Unknown,n(h),t(new Ee(bg.CannotProcessUpdate,"Update download failed!"))}}),!1)}))))}))}InstallUpdateNewApiAsync(e,t,n,r){return gf(this,void 0,void 0,(function*(){return new Promise(((n,r)=>gf(this,void 0,void 0,(function*(){const r=60*this._updateOfflineStageTime*1e3;let o=0;const s=new tf;let i=null;e.DownloadOnly=!1;const a=e=>gf(this,void 0,void 0,(function*(){e==it.Connected&&(clearInterval(i),s.Status=Cg.Upgraded,s.Percentage=100,s.PercentageTotal=100,t(s),clearInterval(i),yield se.Delay(5e3),n(ue.OK),hy.Get(_t.ServiceName).OnAppStateChanged().Unsubscribe(a))}));yield this._connection.SendAndHandleResponseAsync(new Gf,this._updateRequestTimeout,(c=>{var u,l;switch(s.UpdatedResourceName=ie(e.Update.UpdateName),c.Status){case ue.MultiDataResponseStart:s.Status=Cg.PreparingForUpgrade,s.Percentage=null===(u=c.Data)||void 0===u?void 0:u.StepProgressInPercentage,s.PercentageTotal=null===(l=c.Data)||void 0===l?void 0:l.UpdateProgressInPercentage,t(s);break;case ue.MultiDataResponse:null!=c.Data&&(s.Status=Cg.Upgrading,s.Percentage=Math.round(c.Data.StepProgressInPercentage),s.PercentageTotal=Math.round(c.Data.UpdateProgressInPercentage),o=c.Data.StepProgressInPercentage,t(s));break;case ue.MultiDataResponseStop:if(null!=c.Data)switch(c.Data.UpdateStep){case cf.UpdateInstallationFailed:s.Status=Cg.InstallationError,s.Percentage=0,s.PercentageTotal=0,t(s),n(new Ee(bg.CannotProcessUpdate,"Update installation failed!"));break;case cf.OfflineUpdateStep:{s.Percentage=Math.round(c.Data.StepProgressInPercentage),s.PercentageTotal=Math.round(c.Data.UpdateProgressInPercentage);let e=(100-s.PercentageTotal)/100,u=s.PercentageTotal;i=setInterval((()=>{o++,u+=e,u>100&&(u=100),o>=100?(s.Status=Cg.Upgraded,s.Percentage=100,s.PercentageTotal=100,t(s),clearInterval(i),n(ue.OK)):(s.Status=Cg.Upgrading,s.Percentage=Math.round(o),s.PercentageTotal=Math.round(u),t(s))}),r/(100-o)),hy.Get(_t.ServiceName).OnAppStateChanged().Subscribe(a)}}break;case ue.Error:case ue.FatalError:s.Status=Cg.Error,s.Percentage=0,s.PercentageTotal=0,t(s),n(new Ee(bg.CannotProcessUpdate,"Update installation failed!"))}}),!1)}))))}))}InstallControllerUpdateUsingApiAsync(e,t){return gf(this,void 0,void 0,(function*(){const n=yield this._connection.SendAndWaitForResponseAsync(new If,1e4,!1);if((null==n?void 0:n.Status)==ue.NoData)return new Ee(bg.DeviceIsUpToDate,"No updates available!");if(null==n||(null==n?void 0:n.Status)!=ue.OK||null==(null==n?void 0:n.Data))throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==n?void 0:n.Status}`);switch(n.Data.UpdateStep){case cf.DownloadingInstaller:case cf.DownloadingUpdate:return new Ee(bg.UpdateAlreadyDownloaded,"Update already downloaded, or download in progress.");case cf.InstallingUpdate:case cf.PreparingUpdate:return new Ee(bg.UpdateAlreadyInstalled,"Update already installed, or installation in progress.");case cf.UpdateDownloaded:return n.Data.DownloadOnly=!1,yield this.InstallUpdateNewApiAsync(n.Data,e,t,!1);default:this._logger.Debug(ff.ServiceName,`Installing update using new API. Update step: ${n.Data.UpdateStep} downloadOnly: false`),n.Data.DownloadOnly=!1;var r=yield this.DownloadControllerUpdateNewApiAsync(n.Data,e,t,!1);return r!=ue.OK?r:yield this.InstallUpdateNewApiAsync(n.Data,e,t,!1)}}))}DownloadControllerUpdateUsingApiAsync(e,t,n){return gf(this,void 0,void 0,(function*(){const r=yield this._connection.SendAndWaitForResponseAsync(new If,1e4,!1);if((null==r?void 0:r.Status)==ue.NoData)return new Ee(bg.DeviceIsUpToDate,"No updates available!");if(null==r||(null==r?void 0:r.Status)!=ue.OK||null==(null==r?void 0:r.Data))throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${null==r?void 0:r.Status}`);switch(r.Data.UpdateStep){case cf.DownloadingInstaller:case cf.DownloadingUpdate:case cf.UpdateDownloaded:return new Ee(bg.UpdateAlreadyDownloaded,"Update already downloaded, or download is in progress.");case cf.InstallingUpdate:case cf.PreparingUpdate:return new Ee(bg.UpdateAlreadyInstalled,"Update already installed, or installation is in progress.");default:return yield this.DownloadControllerUpdateNewApiAsync(r.Data,e,t,n)}}))}UpdateControllerUsingApiAsync(e,t,n){return gf(this,void 0,void 0,(function*(){return n?yield this.DownloadControllerUpdateUsingApiAsync(e,t,!0):yield this.InstallControllerUpdateUsingApiAsync(e,t)}))}getRuntimeInfoAsync(){return gf(this,void 0,void 0,(function*(){try{return yield this._updateProviders.GetSoftwareRuntimeInfoAsync()}catch(e){return e instanceof ps&&e.code==Vo.Timeout?new Ee(bg.CannotGetCurrentControllerVersionTimeout,"Cannot get runtime info (current controller version), timeout error - please restart controller to fix issue."):new Ee(bg.CannotGetCurrentControllerVersion,`Cannot get runtime info (current controller version), error: ${e}`)}}))}}ff.ServiceName="UpdatesService";class vf{constructor(){this.UpdatedResourceName=new Map,this.CurrentResourceVersion="",this.UpdateType=null,this.ResponseResult=null}}class yf{constructor(){this._updateIdentifier="",this._updateResourceName=new Map,this._updateType=null,this._currentResourceVersion="",this._newResourceVersion="",this._updateDescription=new Map,this._updateIsDownloading=!1,this._updateCheckDownloadProgress=0,this._updateCreationTime=null,this._isDownloadOnly=!1}get IsDownloadOnly(){return this._isDownloadOnly}set IsDownloadOnly(e){this._isDownloadOnly=e}get UpdateCreationTime(){return this._updateCreationTime}get DownloadProgress(){return this._updateCheckDownloadProgress}get UpdateDescription(){return this._updateDescription}get UpdateIdentifier(){return this._updateIdentifier}get UpdatedResourceName(){return this._updateResourceName}get UpdateType(){return this._updateType}get CurrentResourceVersion(){return this._currentResourceVersion}get NewResourceVersion(){return this._newResourceVersion}get UpdateIsDownloading(){return this._updateIsDownloading}set UpdateCreationTime(e){this._updateCreationTime=e}set DownloadProgress(e){this._updateCheckDownloadProgress=e}set UpdateDescription(e){this._updateDescription=e}set UpdateIdentifier(e){this._updateIdentifier=e}set UpdatedResourceName(e){this._updateResourceName=e}set UpdateType(e){this._updateType=e}set CurrentResourceVersion(e){this._currentResourceVersion=e}set NewResourceVersion(e){this._newResourceVersion=e}set UpdateIsDownloading(e){this._updateIsDownloading=e}}class mf{constructor(){this._updatedResourceName="",this._updateResourceGuid="",this._protocol="",this._protocolGuid="",this._currentResourceVersion="",this._newResourceVersion="",this._isUpdateSafe=!0,this._updateDescription=new Map}get UpdateDescription(){return this._updateDescription}set UpdateDescription(e){this._updateDescription=e}get UpdatedResourceName(){return this._updatedResourceName}get UpdateResourceGuid(){return this._updateResourceGuid}get Protocol(){return this._protocol}get ProtocolGuid(){return this._protocolGuid}get CurrentResourceVersion(){return this._currentResourceVersion}get NewResourceVersion(){return this._newResourceVersion}get IsUpdateSafe(){return this._isUpdateSafe}set UpdatedResourceName(e){this._updatedResourceName=e}set UpdateResourceGuid(e){this._updateResourceGuid=e}set Protocol(e){this._protocol=e}set ProtocolGuid(e){this._protocolGuid=e}set CurrentResourceVersion(e){this._currentResourceVersion=e}set NewResourceVersion(e){this._newResourceVersion=e}set IsUpdateSafe(e){this._isUpdateSafe=e}}class wf extends ce{constructor(e){super(),this.Resource="/updates/update/from/uri",this.Method=le.Post,this.Data=e}}!function(e){e[e.Windows=0]="Windows",e[e.Linux=1]="Linux",e[e.Unix=2]="Unix",e[e.OSX=3]="OSX",e[e.Android=4]="Android",e[e.iOS=5]="iOS",e[e.WindowsMobile=6]="WindowsMobile"}(of||(of={})),function(e){e[e.Any=0]="Any",e[e.MIPS=1]="MIPS",e[e.ARM32=2]="ARM32",e[e.ARM64=3]="ARM64",e[e.IntelX86=4]="IntelX86",e[e.IntelX64=5]="IntelX64"}(sf||(sf={})),function(e){e[e.Unknown=0]="Unknown",e[e.Environment=1]="Environment",e[e.OperatingSystem=2]="OperatingSystem",e[e.Application=3]="Application",e[e.Extension=4]="Extension",e[e.HardwareFirmware=5]="HardwareFirmware",e[e.Script=6]="Script",e[e.Command=7]="Command"}(af||(af={})),function(e){e[e.InstallerFileSignCheckFailed=-5]="InstallerFileSignCheckFailed",e[e.UpdateFileSignCheckFailed=-4]="UpdateFileSignCheckFailed",e[e.UpdateInstallationFailed=-3]="UpdateInstallationFailed",e[e.UpdateDownloadFailed=-2]="UpdateDownloadFailed",e[e.UpdateFileCheckFailed=-1]="UpdateFileCheckFailed",e[e.Unknown=0]="Unknown",e[e.DownloadingUpdate=1]="DownloadingUpdate",e[e.CheckingUpdate=2]="CheckingUpdate",e[e.PreparingUpdate=3]="PreparingUpdate",e[e.InstallingUpdate=4]="InstallingUpdate",e[e.DownloadingInstaller=5]="DownloadingInstaller",e[e.UpdateDownloaded=6]="UpdateDownloaded",e[e.OfflineUpdateStep=7]="OfflineUpdateStep"}(cf||(cf={}));class Sf extends ce{constructor(e){super(),this.Resource="/updates/install/from/url",this.Method=le.Put,this.Data=e}}class Af extends ce{constructor(e){super(),this.Resource="/users/user/login",this.Method=le.Put,this.Data=e}}class _f extends ce{constructor(e){super(),this.Resource="/controller/runtime/execute",this.Method=le.Post,this.Data=e}}class Cf extends ce{constructor(){super(),this.Resource="/updates/branch",this.Method=le.Get}}class Df extends ce{constructor(e){super(),this.Resource="/updates/branch",this.Method=le.Put,this.Data=e}}class Tf extends ce{constructor(){super(),this.Resource="/updates/failed/cancel",this.Method=le.Put}}class kf extends ce{constructor(){super(),this.Resource="/updates/pending/progress",this.Method=le.Get}}class If extends ce{constructor(){super(),this.Resource="/updates/pending",this.Method=le.Get}}class Ef extends ce{constructor(){super(),this.Resource="/updates/check",this.Method=le.Get}}class bf extends ce{constructor(){super(),this.Resource="/updates/download",this.Method=le.Post}}class Gf extends ce{constructor(){super(),this.Resource="/updates/install",this.Method=le.Post}}class Nf extends ce{constructor(){super(),this.Resource="/updates/download/automatic/status",this.Method=le.Get}}class Rf extends ce{constructor(){super(),this.Resource="/updates/download/automatic/enable",this.Method=le.Put}}class Pf extends ce{constructor(){super(),this.Resource="/updates/download/automatic/disable",this.Method=le.Put}}class Uf extends ce{constructor(){super(),this.Resource="/updates/history",this.Method=le.Get}}class Of extends ce{constructor(){super(),this.Resource="/updates/devices/availability",this.Method=le.Get}}!function(e){e.CannotFindDevice="CannotFindDevice",e.ResponseTypeNotSupported="ResponseTypeNotSupported",e.InvalidChannelNumber="InvalidChannelNumber",e.IncorrectLimitValue="IncorrectLimitValue",e.IncorrectOffsetValue="IncorrectOffsetValue",e.OtherError="OtherError",e.FatalError="FatalError",e.NoData="NoData",e.FunctionalityNotSupported="FunctionalityNotSupported"}(uf||(uf={})),function(e){e[e.None=0]="None",e[e.DataRange=1]="DataRange",e[e.Hour=2]="Hour",e[e.Day=3]="Day",e[e.Week=4]="Week",e[e.Month=5]="Month",e[e.Year=6]="Year",e[e.ThisHour=7]="ThisHour",e[e.ThisDay=8]="ThisDay",e[e.ThisWeek=9]="ThisWeek",e[e.ThisMonth=10]="ThisMonth",e[e.ThisYear=11]="ThisYear"}(lf||(lf={})),function(e){e[e.Day=0]="Day",e[e.Week=1]="Week",e[e.Month=2]="Month",e[e.Year=3]="Year",e[e.Hour=4]="Hour"}(df||(df={})),function(e){e.Min="Min",e.Max="Max",e.Avg="Avg"}(hf||(hf={}));class Mf{constructor(){this._objectType="Unknown",this._stateInterfaceType="Unknown"}get StateObjectType(){return this._objectType}get StateInterfaceType(){return this._stateInterfaceType}get StateResponseType(){return this._stateInterfaceType}set StateObjectType(e){this._objectType=e}set StateInterfaceType(e){this._stateInterfaceType=e}}!function(e){e[e.Unknown=-1]="Unknown",e[e.PitchBlack=0]="PitchBlack",e[e.VeryDark=1]="VeryDark",e[e.DarkIndoors=2]="DarkIndoors",e[e.DimIndoors=3]="DimIndoors",e[e.NormalIndoors=4]="NormalIndoors",e[e.BrightIndoors=5]="BrightIndoors",e[e.DimOutdoors=6]="DimOutdoors",e[e.CloudyOutdoors=7]="CloudyOutdoors",e[e.DirectSunlight=8]="DirectSunlight"}(pf||(pf={}));var xf,Ff,Lf,Bf,Wf,$f,Vf,qf=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Hf{constructor(){this.DELIM=";",this._connection=null,this._connection=hy.Get(It.ServiceName)}numToCsv(e){const t="string"==typeof e?Number(e.replace(",",".")):e;return Number.isFinite(t)?t.toLocaleString("en-US",{useGrouping:!1}):""}quoteIfNeeded(e){return e.includes(this.DELIM)||e.includes('"')?`"${e.replace(/"/g,'""')}"`:e}ExportPressureToCsv(e,t,n){ae(this.ExportAveragingStateValuesToCsv(e,t,n),`PressureHistory_${e.Name}_${t}.csv`)}ExportBrightnessToCsv(e,t,n){var r;if(!(null===(r=null==n?void 0:n.Data)||void 0===r?void 0:r.length))return;const o=[],s=(n.Data[0],["Time","AggregatedBy"]);s.push("LuxValue","LuxToLinearScale","LightCondition"),o.push(s.join(this.DELIM)),n.Data.forEach((e=>{var t,n,r;const s=[this.quoteIfNeeded(e.Time),this.quoteIfNeeded(e.AggregatedBy)];null!==e.Values&&(s.push(this.numToCsv(null===(t=e.Values)||void 0===t?void 0:t.LuxValue)),s.push(this.numToCsv(null===(n=e.Values)||void 0===n?void 0:n.LuxToLinearScale)),s.push(this.numToCsv(null===(r=e.Values)||void 0===r?void 0:r.LightCondition))),o.push(s.join(this.DELIM))})),ae(o.join("\n"),`BrightnessHistory_${e.Name}_${t}.csv`)}ExportHumidityToCsv(e,t,n){ae(this.ExportAveragingStateValuesToCsv(e,t,n),`HumidityHistory_${e.Name}_${t}.csv`)}ExportWindSpeedToCsv(e,t,n){ae(this.ExportAveragingStateValuesToCsv(e,t,n),`WindSpeedHistory_${e.Name}_${t}.csv`)}ExportTemperatureToCsv(e,t,n){ae(this.ExportAveragingStateValuesToCsv(e,t,n),`TemperatureHistory_${e.Name}_${t}.csv`)}ExportAveragingStateValuesToCsv(e,t,n){var r;if(!(null===(r=null==n?void 0:n.Data)||void 0===r?void 0:r.length))return"";const o=[],s=(n.Data[0],["Time","AggregatedBy"]);return s.push("LastValue","Average","Mode","Min","Max"),o.push(s.join(this.DELIM)),n.Data.forEach((e=>{var t,n,r,s,i;const a=[this.quoteIfNeeded(e.Time),this.quoteIfNeeded(e.AggregatedBy)];null!==e.Values&&(a.push(this.numToCsv(null===(t=e.Values)||void 0===t?void 0:t.LastValue)),a.push(this.numToCsv(null===(n=e.Values)||void 0===n?void 0:n.Average)),a.push(this.numToCsv(null===(r=e.Values)||void 0===r?void 0:r.Mode)),a.push(this.numToCsv(null===(s=e.Values)||void 0===s?void 0:s.Min)),a.push(this.numToCsv(null===(i=e.Values)||void 0===i?void 0:i.Max))),o.push(a.join(this.DELIM))})),o.join("\n")}ExportEnergyToCsv(e,t,n){var r,o;let s=n.Data;if(!(null==s?void 0:s.length))return;const i=[],a=s[0],c=["Time","AggregatedBy"];null===(r=a.Values)||void 0===r||r.MeasurementAveragingParameters.forEach(((e,t)=>{c.push(`${t}:LastValue`,`${t}:Average`,`${t}:Mode`,`${t}:Min`,`${t}:Max`)})),null===(o=a.Values)||void 0===o||o.MeasurementNonAveragingParmeters.forEach(((e,t)=>c.push(`${t}`))),i.push(c.join(this.DELIM)),s.forEach((e=>{var t,n;const r=[this.quoteIfNeeded(e.Time),this.quoteIfNeeded(e.AggregatedBy)];null===(t=e.Values)||void 0===t||t.MeasurementAveragingParameters.forEach((e=>{r.push(this.numToCsv(e.LastValue),this.numToCsv(e.Average),this.numToCsv(e.Mode),this.numToCsv(e.Min),this.numToCsv(e.Max))})),null===(n=e.Values)||void 0===n||n.MeasurementNonAveragingParmeters.forEach((e=>r.push(this.numToCsv(e)))),i.push(r.join(this.DELIM))})),ae(i.join("\n"),`EnergyHistory_${e.Name}_${t}.csv`)}GetStatesByTimeRangeAsync(e,t,n,r,o,s,i){return qf(this,arguments,void 0,(function*(e,t,n,r,o,s,i,a=!1){var c;try{if(!(yield this.DoesSupportPreciseTimeFramesAsync()))return new Ee(uf.FunctionalityNotSupported,"State history data in time range is not supported with this version of controller software, update software to get this functionality.");let u;if("string"==typeof e){const t=yield hy.Get(Ys.ServiceName).GetDevice(e);if(null==t)return new Ee(uf.CannotFindDevice,`Device with specified GUID ${e} does not exist.`);u=t}else u=e;if(!u.Channels.any((e=>e.Number===t)))return new Ee(uf.InvalidChannelNumber,`Given channel not found in device with guid: ${u.Guid}.`);if(!u.Channels.any((e=>e.Number===t&&e.AvailableResponseTypes.any((e=>e.Type===n)))))return new Ee(uf.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");const l=new Jf;l.DeviceGuid=u.Guid,l.DeviceChannel=t,l.StateInterfaceType=n,l.ReverseOrder=a,l.DataRange=r,l.Time=o,l.Limit=s,l.Offset=i;const d=yield null===(c=this._connection)||void 0===c?void 0:c.SendAndWaitForResponseAsync(new zf(l),3e4,!1);if(null==d)return new Ee(uf.OtherError,"Cannot get state history data - response is null.");switch(d.Status){case ue.WrongData:switch(d.Data){case"IncorrectLimitValue":return new Ee(uf.IncorrectLimitValue,"Cannot get state history data - limit value is incorrect!");case"IncorrectOffsetValue":return new Ee(uf.IncorrectOffsetValue,"Cannot get state history data - offset value is incorrect!");case"IncorrectArguments":return new Ee(uf.OtherError,"Cannot get state history data - some parameters are incorrect!");case"UnsupportedRange":return new Ee(uf.OtherError,"Cannot get state history data - time range is incorrect!");default:return new Ee(uf.OtherError,"Cannot get state history data - unknown error!")}case ue.FatalError:return new Ee(uf.FatalError,"Cannot get state history data - an exception occurred in the controller while reading data!");case ue.ResourceDoesNotExists:return new Ee(uf.ResponseTypeNotSupported,`Device or channel not supporting requested DeviceResponseType or device/channel does not exist. ${d.Data}`);case ue.OK:if(null==d.Data)return new Ee(uf.NoData,"Controller responded with status OK, but response does not contain data!");if(d.Data.AggregateDataList=d.Data.AggregateDataList.map((e=>(e.AggregateData=ie(e.AggregateData),e))),n===Pt.MeasuredEnergy){const e=d.Data.Data.map((e=>{const t=e;return t.Values.MeasurementAveragingParameters=ie(e.Values.MeasurementAveragingParameters),t.Values.MeasurementNonAveragingParmeters=ie(e.Values.MeasurementNonAveragingParmeters),t}));return d.Data.Data=e,d.Data}return d.Data;default:return new Ee(uf.OtherError,`Cannot get state history data - controller responded with response code ${d.Status}`)}}catch(e){return new Ee(uf.FatalError,`Cannot get state history data - exception occurs! ${e}`)}}))}GetServiceName(){return Hf.ServiceName}DoesSupportPreciseTimeFramesAsync(){return qf(this,void 0,void 0,(function*(){let e=(yield hy.Get(cs.ServiceName).GetSoftwareRuntimeInfoAsync()).SoftwareVersion.split(".");return Number(e[0])>6||6===Number(e[0])&&Number(e[1])>=101}))}GetStatesByIntervalAsync(e,t,n,r,o,s){return qf(this,arguments,void 0,(function*(e,t,n,r,o,s,i=!1){var a;try{if(!(yield this.IsFunctionalitySupportedAsync()))return new Ee(uf.FunctionalityNotSupported,"State history data is not supported with this version of controller software, update software to get this functionality.");let c;if("string"==typeof e){const t=yield hy.Get(Ys.ServiceName).GetDevice(e);if(null==t)return new Ee(uf.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);c=t}else c=e;if(!c.Channels.any((e=>e.Number==t)))return new Ee(uf.InvalidChannelNumber,`Given channel not found in device with guid: ${c.Guid}.`);if(!c.Channels.any((e=>e.Number==t&&e.AvailableResponseTypes.any((e=>e.Type==n)))))return new Ee(uf.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");const u=new jf;u.DeviceGuid=c.Guid,u.DeviceChannel=t,u.StateInterfaceType=n,u.ReverseOrder=i,u.Limit=o,u.Offset=s;let l=(yield hy.Get(cs.ServiceName).GetSoftwareRuntimeInfoAsync()).SoftwareVersion.split(".");if(Number(l[0])>6||6===Number(l[0])&&Number(l[1])>=101)switch(r){case lf.ThisHour:u.Range=lf.Hour;break;case lf.ThisDay:u.Range=lf.Day;break;case lf.ThisWeek:u.Range=lf.Week;break;case lf.ThisMonth:u.Range=lf.Month;break;case lf.ThisYear:u.Range=lf.Year}else u.Range=r;const d=yield null===(a=this._connection)||void 0===a?void 0:a.SendAndWaitForResponseAsync(new Kf(u),3e4,!1);if(null==d)return new Ee(uf.OtherError,"Cannot get state history data - response is null.");switch(d.Status){case ue.WrongData:switch(d.Data){case"IncorrectLimitValue":return new Ee(uf.IncorrectLimitValue,"Cannot get state history data - limit value is incorrect!");case"IncorrectOffsetValue":return new Ee(uf.IncorrectOffsetValue,"Cannot get state history data - offset value is incorrect!");case"IncorrectArguments":return new Ee(uf.OtherError,"Cannot get state history data - some parameters are incorrect!");default:return new Ee(uf.OtherError,"Cannot get state history data - unknown error!")}case ue.FatalError:return new Ee(uf.FatalError,"Cannot get state history data - an exception occurred in the controller while reading data!");case ue.ResourceDoesNotExists:return new Ee(uf.ResponseTypeNotSupported,"Device or channel not supporting requested DeviceResponseType.");case ue.OK:if(null==d.Data)return new Ee(uf.NoData,"Controller responede with status OK, but response does not contain data!");if(d.Data.AggregateDataList=d.Data.AggregateDataList.map((e=>(e.AggregateData=ie(e.AggregateData),e))),n===Pt.MeasuredEnergy){const e=d.Data.Data.map((e=>{const t=e;return t.Values.MeasurementAveragingParameters=ie(e.Values.MeasurementAveragingParameters),t.Values.MeasurementNonAveragingParmeters=ie(e.Values.MeasurementNonAveragingParmeters),t}));return d.Data.Data=e,d.Data}return d.Data;default:return new Ee(uf.OtherError,`Cannot get state history data - controller responded with response code ${d.Status}`)}}catch(e){return new Ee(uf.FatalError,`Cannot get state history data - exeption occurs! ${e}`)}}))}GetAvailableStatesAsync(){return qf(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Xf,12e3,!1);return null==t?new Ee(uf.OtherError,"Cannot get available states - response is null."):t.Status!=ue.OK?new Ee(uf.OtherError,`Cannot get available states - controller responded with response code ${t.Status}.`):null==t.Data?new Ee(uf.NoData,"Cannot get available states - controller responede with status OK, but response does not contain data!"):t.Data.map((e=>{const t=new Mf;return t.StateInterfaceType=e.StateInterfaceType,t.StateObjectType=e.StateObjectType,t}))}catch(e){return new Ee(uf.FatalError,`Cannot get available states - exeption occurs! ${e}`)}}))}IsFunctionalitySupportedAsync(){return qf(this,void 0,void 0,(function*(){let e=(yield hy.Get(cs.ServiceName).GetSoftwareRuntimeInfoAsync()).SoftwareVersion.split(".");return Number(e[0])>3||3===Number(e[0])&&Number(e[1])>=42}))}GetAvailableStatesPerChannelAsync(e,t){return qf(this,void 0,void 0,(function*(){var n;let r;if("string"==typeof e){const t=yield hy.Get(Ys.ServiceName).GetDevice(e);if(null==t)return new Ee(uf.CannotFindDevice,`Device with specified GUID ${e} does not exists.`);r=t}else r=e;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Yf(new Qf(r.Guid,t)),8e3,!1);if(null==o)return new Ee(uf.OtherError,"Cannot get available states - response is null.");switch(o.Status){case ue.ResourceDoesNotExists:switch(o.Data){case"DeviceNotFound":return new Ee(uf.CannotFindDevice,"Cannot get available states - device does not exists!");case"ChannelNotFound":return new Ee(uf.InvalidChannelNumber,"Cannot get available states - wrong channel!");default:return new Ee(uf.OtherError,"Cannot get available states - unknown error!")}case ue.OK:{if(null==o.Data)return new Ee(uf.NoData,"Cannot get available states - controller responede with status OK, but response does not contain data!");const e=o.Data.AvailableStates.map((e=>{const t=new Mf;return t.StateInterfaceType=e.StateInterfaceType,t.StateObjectType=e.StateObjectType,t}));return o.Data.AvailableStates=e,o.Data}default:return new Ee(uf.OtherError,`Cannot get available states - controller responded with response code ${o.Status}`)}}))}}Hf.ServiceName="StatesHistoryService";class Kf extends ce{constructor(e){super(),this.Resource="/statehistory/states/get/last",this.Method=le.Get,this.Data=e}}class jf{constructor(){this.DeviceGuid="",this.DeviceChannel=0,this.StateInterfaceType="",this.Range=lf.Day,this.ReverseOrder=!1,this.Limit=0,this.Offset=0}}class zf extends ce{constructor(e){super(),this.Resource="/statehistory/states/get/timerange",this.Method=le.Get,this.Data=e}}class Jf{constructor(){this.DeviceGuid="",this.DeviceChannel=0,this.StateInterfaceType="",this.DataRange=df.Day,this.Time=new Date,this.ReverseOrder=!1,this.Limit=0,this.Offset=0}}class Xf extends ce{constructor(){super(),this.Resource="/statehistory/states/available",this.Method=le.Get}}class Yf extends ce{constructor(e){super(),this.Resource="/statehistory/states/available/per/channel",this.Method=le.Get,this.Data=e}}class Qf{constructor(e,t){this.DeviceGuid=e,this.Channel=t}}(Vf=xf||(xf={}))[Vf.User=0]="User",Vf[Vf.Controller=1]="Controller",Vf[Vf.Marketing=2]="Marketing",($f=Ff||(Ff={}))[$f.Notification=0]="Notification",$f[$f.Message=1]="Message",$f[$f.Alarm=2]="Alarm",$f[$f.Warning=3]="Warning",$f[$f.Info=4]="Info",(Wf=Lf||(Lf={}))[Wf.Other=0]="Other",Wf[Wf.UserLoggedIn=1]="UserLoggedIn",Wf[Wf.UserLoggedOut=2]="UserLoggedOut",Wf[Wf.FoundNewDevice=3]="FoundNewDevice",Wf[Wf.DoorBellPress=4]="DoorBellPress",Wf[Wf.AddedNewDevice=5]="AddedNewDevice",Wf[Wf.RemovedDevice=6]="RemovedDevice",Wf[Wf.RegisteredNewUser=7]="RegisteredNewUser",Wf[Wf.GotAccessToTheInternet=8]="GotAccessToTheInternet",Wf[Wf.LostAccessToTheInternet=9]="LostAccessToTheInternet",Wf[Wf.RemovedUser=10]="RemovedUser",Wf[Wf.NetworkChanged=11]="NetworkChanged",function(e){e.WeatherWidget="WeatherWidget"}(Bf||(Bf={}));var Zf=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class ev{constructor(){this._chatSubscriptions=[],this._connection=hy.Get(It.ServiceName),this._connection.SubscribeTo("/homemessaging/notify/message/new",(e=>{const t=e.Data;if(null==t.RecipientUserGuid&&t.MessageType==Ff.Message)return;const n=new tv;n.DateTime=t.DateTime,n.Guid=t.Guid,n.MessageSource=t.MessageSource,n.MessageText=t.MessageText,n.MessageType=t.MessageType,n.RecipientUserGuid=t.RecipientUserGuid?t.RecipientUserGuid:"n/a",n.Sender=t.Sender,n.SenderName=t.SenderName?t.SenderName:"n/a",n.SenderUserGuid=t.SenderUserGuid?t.SenderUserGuid:"n/a",n.TextToSpeechMessage=t.TextToSpeechMessage?t.TextToSpeechMessage:"";for(let[e,r]of Object.entries(t.MessageActions))n.MessageActions.set(Bf[e],r);for(let[e,r]of Object.entries(t.MessageActionsData))n.MessageActionsData.set(e,r);this._chatSubscriptions.forEach((e=>{e(n)}))}))}GetCachedMessagesAsync(){return Zf(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new nv,12e3,!1);if(null==e)return new Ee(pv.OtherError,"Cannot get messages - response is null.");if(e.Status!=ue.OK)return new Ee(pv.OtherError,`Cannot get messages - controller responded with response code ${e.Status}.`);if(null==e.Data)return new Ee(pv.NoData,"Cannot get messages - controller responded with status OK, but response does not contain data!");const t=[];return e.Data.forEach((e=>{if(null==e.RecipientUserGuid&&e.MessageType==Ff.Message)return;const n=new tv;n.DateTime=e.DateTime,n.Guid=e.Guid,n.MessageSource=e.MessageSource,n.MessageText=e.MessageText,n.MessageType=e.MessageType,n.RecipientUserGuid=e.RecipientUserGuid?e.RecipientUserGuid:"n/a",n.Sender=e.Sender,n.SenderName=e.SenderName?e.SenderName:"n/a",n.SenderUserGuid=e.SenderUserGuid?e.SenderUserGuid:"n/a",n.TextToSpeechMessage=e.TextToSpeechMessage?e.TextToSpeechMessage:"";for(let[t,r]of Object.entries(e.MessageActions))n.MessageActions.set(Bf[t],r);for(let[t,r]of Object.entries(e.MessageActionsData))n.MessageActionsData.set(t,r);t.push(n)})),t}catch(e){return new Ee(pv.FatalError,`Cannot get messages - exception occurred ${e}`)}}))}SendMessageAsync(e){return Zf(this,void 0,void 0,(function*(){var t;try{const t=yield this._connection.SendAndWaitForResponseAsync(new rv(`recipient:home ${e}`),8e3,!1);return null==t||null==t.Status?ue.FatalError:t.Status}catch(e){return null===(t=u.Log)||void 0===t||t.Error(Av.ServiceName,`Cannot send message! ${e}`),ue.FatalError}}))}SubscribeToMessages(e){this._chatSubscriptions.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class tv{constructor(){this._sender=xf.Controller,this._messageType=Ff.Info,this._messageSource=Lf.Other,this._senderUserGuid="",this._recipientUserGuid="",this._textToSpeechMessage="",this._messageActions=new Map,this._messageActionsData=new Map,this._guid="",this._senderName="",this._messageText="",this._dateTime=(new Date).toDateString()}get Sender(){return this._sender}get MessageType(){return this._messageType}get MessageSource(){return this._messageSource}get SenderUserGuid(){return this._senderUserGuid}get RecipientUserGuid(){return this._recipientUserGuid}get TextToSpeechMessage(){return this._textToSpeechMessage}get MessageActions(){return this._messageActions}get MessageActionsData(){return this._messageActionsData}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set Sender(e){this._sender=e}set MessageType(e){this._messageType=e}set MessageSource(e){this._messageSource=e}set SenderUserGuid(e){this._senderUserGuid=e}set RecipientUserGuid(e){this._recipientUserGuid=e}set TextToSpeechMessage(e){this._textToSpeechMessage=e}set MessageActions(e){this._messageActions=e}set MessageActionsData(e){this._messageActionsData=e}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}class nv extends ce{constructor(){super(),this.Resource="/homemessaging/messages",this.Method=le.Get}}class rv extends ce{constructor(e){super(),this.Resource="/homemessaging/message",this.Method=le.Put,this.Data=e}}var ov,sv,iv,av=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class cv{constructor(){this._chatSubscriptions=[],this._connection=hy.Get(It.ServiceName),this._connection.SubscribeTo("/homemessaging/notify/message/new",(e=>{if("/homemessaging/notify/message/new"===e.Resource){const t=e.Data;if(null==t.RecipientUserGuid&&t.MessageType==Ff.Message){const e=new uv;e.DateTime=t.DateTime,e.Guid=t.Guid,e.MessageText=t.MessageText,e.SenderName=t.SenderName?t.SenderName:"n/a",this._chatSubscriptions.forEach((t=>{t(e)}))}}}))}GetCachedMessagesAsync(){return av(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new dv,12e3,!1);if(null==e)return new Ee(pv.OtherError,"Cannot get messages - response is null.");if(e.Status!=ue.OK)return new Ee(pv.OtherError,`Cannot get messages - controller responded with response code ${e.Status}.`);if(null==e.Data)return new Ee(pv.NoData,"Cannot get messages - controller responded with status OK, but response does not contain data!");const t=[];return e.Data.forEach((e=>{if(null==e.RecipientUserGuid&&e.MessageType==Ff.Message){const n=new uv;n.DateTime=e.DateTime,n.Guid=e.Guid,n.MessageText=e.MessageText,n.SenderName=e.SenderName?e.SenderName:"n/a",t.push(n)}})),t}catch(e){return new Ee(pv.FatalError,`Cannot get messages - exception occurred ${e}`)}}))}SendMessageAsync(e){return av(this,void 0,void 0,(function*(){var t;try{const t=yield this._connection.SendAndWaitForResponseAsync(new lv(e),8e3,!1);return null==t||null==t.Status?ue.FatalError:t.Status}catch(e){return null===(t=u.Log)||void 0===t||t.Error(Av.ServiceName,`Cannot send message! ${e}`),ue.FatalError}}))}SubscribeToMessages(e){this._chatSubscriptions.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class uv{constructor(){this._guid="",this._senderName="",this._messageText="",this._dateTime=""}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}class lv extends ce{constructor(e){super(),this.Resource="/homemessaging/message",this.Method=le.Put,this.Data=e}}class dv extends ce{constructor(){super(),this.Resource="/homemessaging/messages",this.Method=le.Get}}!function(e){e[e.None=0]="None",e[e.ChangeDeviceState=1]="ChangeDeviceState"}(ov||(ov={})),function(e){e.GPT3_5_TURBO="gpt-3.5-turbo",e.GPT3_5_TURBO_16K="gpt-3.5-turbo-16k",e.GPT4="gpt-4"}(sv||(sv={})),function(e){e[e.UnknownError=0]="UnknownError",e[e.ChatNotConfigured=1]="ChatNotConfigured",e[e.MessageNotSend=2]="MessageNotSend",e[e.InvalidMessageResponseFormat=3]="InvalidMessageResponseFormat"}(iv||(iv={}));var hv,pv,gv,fv=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class vv{constructor(){this._chatSubscriptions=[],this._connection=hy.Get(It.ServiceName),this._connection.SubscribeTo("/homemessaging/gpt/notify/message/new",(e=>{const t=e.Data,n=new Sv;if(n.DateTime=t.DateTime,n.Guid=t.Guid,n.MessageText=t.MessageText?t.MessageText:"",n.SenderName=t.SenderName?t.SenderName:"n/a",null!=t.ControllerActivities)for(let[e,r]of Object.entries(t.ControllerActivities)){const t=ov[e],o=new Map;for(let[e,t]of Object.entries(r))o.set(e,t);n.ControllerActivities.set(t,o)}if(null!=t.Errors)for(let[e,r]of Object.entries(t.Errors))n.Errors.set(iv[e],r);this._chatSubscriptions.forEach((e=>{e(n)}))}))}IsGptChatAvailableAsync(){return fv(this,void 0,void 0,(function*(){return(yield hy.Get(nt.ServiceName).GetExtensionsInfoAsync()).any((e=>"80daeab9-104f-4c1b-9464-61f5fc9bf2bf"==e.ExtensionGuid))}))}GetChatConfigurationAsync(){return fv(this,void 0,void 0,(function*(){try{const e=yield this._connection.SendAndWaitForResponseAsync(new mv,8e3,!1);return null==e||null==e.Status?new Ee(pv.FatalError,"Cannot get chat configuration! No data in result"):e.Status!=ue.OK?new Ee(pv.Error,`Cannot get chat configuration! Controller responded with code: ${e.Status}`):null==e.Data?new Ee(pv.NoData,"Cannot get chat configuration! Controller responded with success, but no data in response!"):e.Data}catch(e){return new Ee(pv.FatalError,`Cannot get chat configuration! ${e}`)}}))}SetChatConfigurationAsync(e){return fv(this,void 0,void 0,(function*(){var t;try{const t=yield this._connection.SendAndWaitForResponseAsync(new wv(e),8e3,!1);return null==t||null==t.Status?ue.FatalError:t.Status}catch(e){return null===(t=u.Log)||void 0===t||t.Error(Av.ServiceName,`Cannot set chat configuration! ${e}`),ue.FatalError}}))}SendMessageAsync(e){return fv(this,void 0,void 0,(function*(){var t;try{const t=yield this._connection.SendAndWaitForResponseAsync(new yv(e),8e3,!1);return null==t||null==t.Status?ue.FatalError:t.Status}catch(e){return null===(t=u.Log)||void 0===t||t.Error(Av.ServiceName,`Cannot send message! ${e}`),ue.FatalError}}))}SubscribeToMessages(e){var t;null===(t=this._chatSubscriptions)||void 0===t||t.push(e)}UnsubscribeFromMessages(e){this._chatSubscriptions&&(this._chatSubscriptions=this._chatSubscriptions.filter((t=>t!==e)))}}class yv extends ce{constructor(e){super(),this.Resource="/homemessaging/gpt/message",this.Method=le.Put,this.Data=e}}class mv extends ce{constructor(){super(),this.Resource="/homemessaging/gpt/configuration",this.Method=le.Get}}class wv extends ce{constructor(e){super(),this.Resource="/homemessaging/gpt/configuration",this.Method=le.Put,this.Data=e}}class Sv{constructor(){this._messageActions=new Map,this._errors=new Map,this._guid="",this._senderName="",this._messageText="",this._dateTime=""}get ControllerActivities(){return this._messageActions}get Errors(){return this._errors}get Guid(){return this._guid}get SenderName(){return this._senderName}get MessageText(){return this._messageText}get DateTime(){return this._dateTime}set ControllerActivities(e){this._messageActions=e}set Errors(e){this._errors=e}set Guid(e){this._guid=e}set SenderName(e){this._senderName=e}set MessageText(e){this._messageText=e}set DateTime(e){this._dateTime=e}}!function(e){e[e.ControllerChat=0]="ControllerChat",e[e.FamilyChat=1]="FamilyChat",e[e.GptChat=2]="GptChat"}(hv||(hv={}));class Av{constructor(){this._services={ControllerChat:new ev,GptChat:new vv,FamillyChat:new cv}}GetServiceName(){return Av.ServiceName}GetChatImplementation(e){switch(e){case hv.ControllerChat:return this._services.ControllerChat;case hv.FamilyChat:return this._services.FamillyChat;case hv.GptChat:return this._services.GptChat;default:throw new _v(`Chat with type ${e} not implemented!`)}}}Av.ServiceName="ChatService",function(e){e.OtherError="OtherError",e.FatalError="FatalError",e.Error="Error",e.NoData="NoData"}(pv||(pv={}));class _v extends Error{constructor(e){super(e),this.message=e,this.name="ChatNotImplementedException"}}!function(e){e[e.ResourceIsNotAvailable=-11]="ResourceIsNotAvailable",e[e.AnotherAppWithGivenAccessTokenAlreadyExists=-10]="AnotherAppWithGivenAccessTokenAlreadyExists",e[e.AppGuidDoesNotExists=-7]="AppGuidDoesNotExists",e[e.AppUrlToShort=-6]="AppUrlToShort",e[e.AppUserNameToShort=-5]="AppUserNameToShort",e[e.AppUserIdToShort=-4]="AppUserIdToShort",e[e.AccessTokenToShort=-3]="AccessTokenToShort",e[e.AppNameToShort=-2]="AppNameToShort",e[e.UnkownError=0]="UnkownError",e[e.Changed=1]="Changed"}(gv||(gv={}));var Cv=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Dv{constructor(){this._connection=hy.Get(It.ServiceName),this._log=hy.Get(a.ServiceName),this._cache=hy.Get(Be.ServiceName)}GetServiceName(){return Dv.ServiceName}IsSupportedAsync(){return Cv(this,void 0,void 0,(function*(){let e=yield this._connection.SendAndWaitForResponseAsync(new Tv,2e3,!1);return this._log.Debug(Dv.ServiceName,`IsSupportedAsync: ${null==e?void 0:e.Status} resp: ${JSON.stringify(e)}`),null!=e&&e.Status==ue.WrongData}))}GetConnectedAppsAsync(){return Cv(this,void 0,void 0,(function*(){let e=yield this._connection.SendAndWaitForResponseAsync(new kv,2e3,!0);return(null==e?void 0:e.Status)===ue.OK?null==e?void 0:e.Data:null==e?void 0:e.Status}))}UpsertConnectedAppAsync(e){return Cv(this,void 0,void 0,(function*(){let t=yield this._connection.SendAndWaitForResponseAsync(new Ev(e),2e3,!1);switch(null==t?void 0:t.Status){case ue.OK:return this._cache.Remove(new kv),new Ee(gv.Changed,"");case ue.WrongData:switch(t.Data){case"AccessTokenToShort":return new Ee(gv.AccessTokenToShort,t.Data);case"AnotherAppWithGivenAccessTokenAlreadyExists":return new Ee(gv.AnotherAppWithGivenAccessTokenAlreadyExists,t.Data);case"AppGuidDoesNotExists":return new Ee(gv.AppGuidDoesNotExists,t.Data);case"AppNameToShort":return new Ee(gv.AppNameToShort,t.Data);case"AppUrlToShort":return new Ee(gv.AppUrlToShort,t.Data);case"AppUserIdToShort":return new Ee(gv.AppUserIdToShort,t.Data);case"AppUserNameToShort":return new Ee(gv.AppUserNameToShort,t.Data);default:return new Ee(gv.UnkownError,t.Data)}case ue.ResourceDoesNotExists:case ue.ResourceIsNotAvailable:return new Ee(gv.ResourceIsNotAvailable,t.Data);default:return new Ee(gv.UnkownError,t.Data)}}))}RemoveConnectedAppAsync(e){return Cv(this,void 0,void 0,(function*(){let t=yield this._connection.SendAndWaitForResponseAsync(new Iv(e.Guid),2e3,!1);return(null==t?void 0:t.Status)===ue.OK&&this._cache.Remove(new kv),null==t?void 0:t.Status}))}}Dv.ServiceName="ConnectedAppsService";class Tv extends ce{constructor(){super(),this.Resource="/applications/app/auth",this.Method=le.Put,this.Data=""}}class kv extends ce{constructor(){super(),this.Resource="/applications/get",this.Method=le.Get}}class Iv extends ce{constructor(e){super(),this.Resource="/applications/app/delete",this.Method=le.Delete,this.Data=e}}class Ev extends ce{constructor(e){super(),this.Resource="/applications/app/upsert",this.Method=le.Put,this.Data=e}}var bv=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Gv{constructor(){try{const e=window.location.href,t=new URL(e),n=new URLSearchParams(t.search),r=n.get("mig_c_enc"),o=n.get("mig_controllers"),s=n.get("mig_lang");if(null!==r){const e=decodeURIComponent(this.b64DecodeUnicode(decodeURIComponent(r)));localStorage.setItem(Gv.AppUserControllersKeyName,e)}null!==o&&localStorage.setItem(Gv.AppUserControllersKeyName,decodeURIComponent(o)),null!==s&&localStorage.setItem(Gv.AppSelectedLanguageKeyName,s)}catch(e){console.error(e)}}waitForNavigatorObject(e){return new Promise(((t,n)=>{setTimeout((()=>{n(new Error(`Timed out waiting for navigator.${e}`))}),1e4),function n(){navigator[e]?t(navigator[e]):requestAnimationFrame(n)}()}))}b64DecodeUnicode(e){return decodeURIComponent(Array.prototype.map.call(atob(e),(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))}decodeUriJsonData(e){return JSON.parse(decodeURIComponent(e))}encodeUriJsonData(e){return encodeURIComponent(JSON.stringify(e))}IsExalusNativeMigrationAvailable(){return void 0!==navigator.exalusMigration}GetServiceName(){return Gv.ServiceName}IsMigrationDataAvailableAsync(){return bv(this,void 0,void 0,(function*(){try{if(oe.IsIosNative()){var e=yield Gv.GetIosMigrationStatus();return null!==e&&e}if(!navigator.userAgent.endsWith("LavvaAndroidNative")||void 0!==navigator.exalusMigration&&null!==navigator.exalusMigration||(yield this.waitForNavigatorObject("exalusMigration")),this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.IsMigrationDataAvailableAsync();return null!=e&&e.DataMigrated}return null!==localStorage.getItem(Gv.AppSelectedLanguageKeyName)||null!==localStorage.getItem(Gv.AppUserControllersKeyName)}catch(e){return console.error(e),!1}}))}GetControllersDataAsync(){return bv(this,void 0,void 0,(function*(){try{if(oe.IsIosNative()){let e=yield Gv.GetIosControllerList();return void 0===e?null:e}{if(this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.GetControllersDataAsync();return void 0===e?null:e}let e=localStorage.getItem(Gv.AppUserControllersKeyName);return null!==e?JSON.parse(e):null}}catch(e){return console.error(e),null}}))}GetLanguageCodeAsync(){return bv(this,void 0,void 0,(function*(){try{if(oe.IsIosNative()){let e=yield Gv.GetIosDefaultLanguage();return void 0===e?null:e}{if(this.IsExalusNativeMigrationAvailable()){let e=yield navigator.exalusMigration.GetLanguageCodeAsync();return void 0===e?null:e}let e=localStorage.getItem(Gv.AppSelectedLanguageKeyName);return null!=e?e:null}}catch(e){return console.error(e),null}}))}static GetIosMigrationStatus(e=8e3){let t;return new Promise(((n,r)=>{t=setTimeout((()=>{r(null)}),e);try{window.nativeEvent.exalusControllerData.isMigrationAvaliable=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("IsMigrationAvaliable")}catch(e){r(e)}}))}static GetIosControllerList(e=8e3){let t;return new Promise(((n,r)=>{t=setTimeout((()=>{r(null)}),e);try{window.nativeEvent.exalusControllerData.handleControllers=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("GetControllers")}catch(e){r(e)}}))}static GetIosDefaultLanguage(e=8e3){let t;return new Promise(((n,r)=>{t=setTimeout((()=>{r(null)}),e);try{window.nativeEvent.exalusControllerData.handleLanguage=e=>{clearTimeout(t),n(e)},window.webkit.messageHandlers.exalusControllerData.postMessage("GetDefaultLanguage")}catch(e){r(e)}}))}}Gv.AppSelectedLanguageKeyName="App___SelectedLanguage",Gv.AppUserControllersKeyName="App___UserControllersListDatabase",Gv.ServiceName="DataMigrationService";var Nv=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Rv{constructor(){this._localIpAddress=null,this._publicIpAddress=null,this._gatewayIpAddress=null,this._macAddress=null,this._isInLocalNetwork=!1,this.nativeFindControllerApi=null,void 0!==navigator.findEfcController&&(this.nativeFindControllerApi=navigator.findEfcController),this._connection=hy.Get(It.ServiceName),this._logger=hy.Get(a.ServiceName),this._storage=hy.Get(l.ServiceName),hy.Get(Xe.ServiceName).OnUserLoggedInEvent().Subscribe((e=>Nv(this,void 0,void 0,(function*(){var e;try{yield se.Delay(5e3);const t=yield this.GetControllerNetworkConfigurationAsync();if(null!=t){this._localIpAddress=t.LocalIPv4,this._publicIpAddress=t.PublicIPv4,this._gatewayIpAddress=t.GatewayIPv4,this._macAddress=t.MAC,this._storage.Save(Rv.ServiceName,"LocalIpAddress",this._localIpAddress);const n=this.GetControllerHostName(this._connection.GetControllerSerialNumber());this._logger.Debug(`Looking for controller in local network with host name: ${n}`);let r=null;oe.IsIosNative()?r=yield this.getIosControllerIpAsync(n):null!==this.nativeFindControllerApi&&(r=yield null===(e=this.nativeFindControllerApi)||void 0===e?void 0:e.FindControllerAsync(n)),null!=r&&""!=r?(this._isInLocalNetwork=!0,this._logger.Debug(Rv.ServiceName,`Controller found in local network with ip address: ${r}`)):(this._isInLocalNetwork=!1,this._logger.Debug(Rv.ServiceName,"Controller not found in local network."))}else this._logger.Error(Rv.ServiceName,"Failed to get network configuration data.")}catch(e){this._logger.Error(Rv.ServiceName,`Failed to get network configuration data - ${e}`)}}))))}FindControllerInLocalNetworkAsync(e){return Nv(this,void 0,void 0,(function*(){if(oe.IsIosNative()){const t=yield this.getIosControllerIpAsync(e);return""==t?null:t}return null!==this.nativeFindControllerApi?this.nativeFindControllerApi.FindControllerAsync(e):Promise.resolve(null)}))}GetLastKnownControllerLocalIpAddress(){return null!==this._localIpAddress?this._localIpAddress:this._storage.Read(Rv.ServiceName,"LocalIpAddress")}GetControllerHostName(e){return`ExalusTR7-${e}`}GetMdnsHostName(){return`ExalusTR7-${this.GetControllerHostName(this._connection.GetControllerSerialNumber())}.local`.toLowerCase()}GetControllerNetworkConfigurationAsync(){return Nv(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Pv,2e4,!1);return null==t||null==t.Status||null==t.Data?(this._logger.Error(Rv.ServiceName,"Failed to get network configuration data - unknow error."),null):t.Data}))}GetServiceName(){return Rv.ServiceName}getIosControllerIpAsync(e,t=2e4){let n;return new Promise(((r,o)=>{n=setTimeout((()=>{this._logger.Error("Cannot find controller in local network, timeout!"),r("")}),t);try{window.nativeEvent.exalusFindController.handleFindController=e=>{clearTimeout(n),r(e)},window.webkit.messageHandlers.exalusFindController.postMessage(e)}catch(e){this._logger.Error(`Cannot find controller in local network, error: ${e}`),r("")}}))}}Rv.ServiceName="FindControllerService";class Pv extends ce{constructor(){super(),this.Resource="/network/lan/",this.Method=le.Get}}var Uv,Ov,Mv,xv=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Fv{SendAndHandleStreamAsync(e,t,n){return Promise.reject(new Error("Streams are not supported over local network connection."))}constructor(){this._errorOccuredEvent=new c,this._connectionStateChangedEvent=new c,this._dataReceivedEvent=new c,this._onMessageReceived=new c,this._log=hy.Get(a.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._logPackets=!0,this.socket=null,this._address=null,this._port="81",this._isOpen=!1,this._pin=void 0,this._serial=void 0,this._auth=null,this._initialized=!1,this._pingInterval=5e3,this._pingIntervalId=null,this._lastReceivedPacketTime=Date.now(),this._disconnectedOnPurpose=!1,this._restoreTask=null,hy.Get(_t.ServiceName).OnAppStateChanged().Subscribe((e=>xv(this,void 0,void 0,(function*(){var t;switch(e){case it.ExitedLowPowerMode:case it.ReturnedFromSuspension:(yield this.RestoreConnectionAsync())&&(null===(t=this._session)||void 0===t||t.RestoreSessionAsync())}}))))}Initialize(){this._initialized||(this._initialized=!0,this._controllerConfiguration=hy.Get(ct.ServiceName),this._cache=hy.Get(Be.ServiceName),this._session=hy.Get(Xe.ServiceName))}checkIfAuthInfoIsCorrectAsync(e){return xv(this,void 0,void 0,(function*(){const t=`http://${window.location.hostname}/controller_info`;let n=yield fetch(t,{method:"GET"});return!!n.ok&&(yield n.text())===`${e.SerialNumber}:${e.PIN}`}))}PingControllerAsync(){return xv(this,void 0,void 0,(function*(){var e;if((null===(e=this.socket)||void 0===e?void 0:e.readyState)!==WebSocket.OPEN)return!1;if(null!==this._lastReceivedPacketTime&&Date.now()-this._lastReceivedPacketTime<this._pingInterval)return!1;let t=new ce;return t.Resource="/system/ping",t.Method=le.Get,yield this.SendAndWaitForResponseAsync(t,2e3,!1,!1).then((()=>!0)).catch((()=>!1))}))}SubscribeTo(e,t){let n=n=>{n.Resource===e&&t(n)};return this.OnDataReceivedEvent().Subscribe(n),()=>this.OnDataReceivedEvent().Unsubscribe(n)}GetControllerSerialNumber(){return this._serial}GetControllerPin(){return this._pin}SetServersBrokerAddress(e){}SetDefaultPacketsBrokerAddress(e){}GetServerAddressAsync(){return hy.IsRunningFromLocalNetwork()&&(this._address=`${window.location.hostname}:${this._port}`),Promise.resolve(this._address)}ConnectAsync(e){return new Promise(((t,n)=>{this.Initialize(),this._disconnectedOnPurpose=!1,this._address=e;const r=this.socket,o=new WebSocket(`ws://${e}/api`);this.socket=o,null!==this._pingIntervalId&&(clearInterval(this._pingIntervalId),this._pingIntervalId=null),null==r||r.close(),this._log.Debug(Fv.ServiceName,`Connecting to the WebSockets server ${e}`),o.onerror=t=>{if(this.socket===o)return this._log.Debug(Fv.ServiceName,`Error occured in the WebSockets server ${e} info: \n${JSON.stringify(t)}`),this._isOpen=!1,this._errorOccuredEvent.Invoke(["WebSockets",t.toString()]),n(he.FailedToConnect)},o.onopen=n=>{if(this.socket===o)return this._log.Debug(Fv.ServiceName,`Connected to the WebSockets server ${e} info: \n${JSON.stringify(n)}`),this._isOpen=!0,this._connectionStateChangedEvent.Invoke(pe.Connected),this._pingIntervalId=setInterval((()=>xv(this,void 0,void 0,(function*(){yield this.PingControllerAsync()}))),this._pingInterval),t(he.Connected)},o.onclose=t=>{this.socket===o&&(this._log.Debug(Fv.ServiceName,`Disconnected from the WebSockets server ${e} info: \n${JSON.stringify(t)}`),this._isOpen=!1,null!==this._pingIntervalId&&(clearInterval(this._pingIntervalId),this._pingIntervalId=null),this._connectionStateChangedEvent.Invoke(pe.Disconnected))},o.onmessage=t=>{if(this.socket===o){this._log.Debug(Fv.ServiceName,`Message received from the WebSockets server ${e}: ${t.data}`),this._onMessageReceived.Invoke(t.data);try{let e=JSON.parse(t.data);this._log.Debug(Fv.ServiceName,`Received data frame: ${e.Status}`),this._dataReceivedEvent.Invoke(e)}catch(e){this._log.Error(Fv.ServiceName,`Failed to parse message: ${t.data}`)}}},this._connectionStateChangedEvent.Invoke(pe.Connecting)}))}AuthorizeAsync(e){return xv(this,void 0,void 0,(function*(){return hy.WorksInContextOf=e.SerialNumber,!!(yield this.checkIfAuthInfoIsCorrectAsync(e))&&(this._log.Debug(Fv.ServiceName,`Authorization successful for controller ${e.SerialNumber}`),this._pin=e.PIN,this._serial=e.SerialNumber,this._auth=e,this.IsConnected()&&this._connectionStateChangedEvent.Invoke(pe.ConnectedAndAuthorized),!0)}))}ConnectAndAuthorizeAsync(e){return xv(this,void 0,void 0,(function*(){var t;hy.WorksInContextOf=e.SerialNumber,this._log.Debug(Fv.ServiceName,`Connecting and authorizing to the controller ${e.SerialNumber}`);let n=yield this.GetServerAddressAsync();if(null==n)return he.FailedToConnectToServer;const r=yield this.ConnectAsync(n);return r!==he.Connected?r:(yield this.AuthorizeAsync(e))?he.Connected:(null===(t=this.socket)||void 0===t||t.close(),he.AuthorizationFailed)}))}DisconnectAsync(){var e;return this._log.Debug(Fv.ServiceName,`Disconnecting from the WebSockets server ${this._address}`),this._disconnectedOnPurpose=!0,this._connectionStateChangedEvent.Invoke(pe.Disconnecting),null!==this._pingIntervalId&&clearInterval(this._pingIntervalId),null===(e=this.socket)||void 0===e||e.close(),Promise.resolve()}IsConnected(){return this._isOpen}EnablePacketsLogging(){this._log.Debug(Fv.ServiceName,"Packets logging enabled"),this._logPackets=!0}DisablePacketsLogging(){this._log.Debug(Fv.ServiceName,"Packets logging disabled"),this._logPackets=!1}SendData(e,t){var n;let r=JSON.stringify(e);return t&&this._log.Debug(Fv.ServiceName,`Sending data frame: ${r}`),this._isOpen?null===(n=this.socket)||void 0===n||n.send(r):this._log.Error(Fv.ServiceName,`Failed to send data frame: ${r}`),this._isOpen}SendAsync(e){return this._isOpen?Promise.resolve(this.SendData(e,this._logPackets)):Promise.resolve(!1)}SendAndWaitForResponseAsync(e,t,n,r=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!0,r)}SendAndHandleResponseAsync(e,t,n,r){return xv(this,void 0,void 0,(function*(){var o;let s=0;const i=Date.now();if(!this.IsConnected()&&!(yield this.RestoreConnectionAsync()))throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(o=this._session)||void 0===o?void 0:o.WaitForSessionCreationAsync()),new Promise(((o,a)=>xv(this,void 0,void 0,(function*(){const c=()=>window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(u);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Fv.ServiceName,t),a(new Error(t))}),t);let u=l=>xv(this,void 0,void 0,(function*(){var d,h,p;if((null==l?void 0:l.TransactionId)==e.TransactionId){window.clearTimeout(s);const g=Date.now()-i;if((r||!0===window.packets)&&this._log.Debug(Fv.ServiceName,`Received response for: ${null==l?void 0:l.Resource} ${null==l?void 0:l.Method} id: ${null==l?void 0:l.TransactionId} in ${g}ms`),(null==l?void 0:l.Status)===ue.UserIsNotLoggedIn){this._dataReceivedEvent.Unsubscribe(u),(null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User);try{yield null===(p=this._session)||void 0===p?void 0:p.RestoreSessionAsync(),o(yield this.SendAndHandleResponseAsync(e,t,n,r))}catch(e){a(e)}return}switch(null==l?void 0:l.Status){case ue.MultiDataResponseStart:case ue.MultiDataResponse:n(l),s=c();break;case ue.MultiDataResponseStop:case ue.FatalError:case ue.Error:n(l),this._dataReceivedEvent.Unsubscribe(u),o();break;default:let t=`Failed to process MultiDataResponse - recived incorrect response status: ${null==l?void 0:l.Status} method: ${e.Method} transaction id: ${e.TransactionId}\n make sure that the requested endpoint uses MultiDataResponse, otherwise use SendAndWaitForResponseAsync<T> method.`;a(new Error(t))}}}));if(this._dataReceivedEvent.Subscribe(u),s=c(),!this.SendData(e,r)){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;a(new Error(t))}}))))}))}SendAndWaitForResponseWithRepeatAsync(e,t,n){return xv(this,arguments,void 0,(function*(e,t,n,r=!0,o=!0){var s,i,a;if(e.Method===le.Get&&n&&!(yield null===(s=this._controllerConfiguration)||void 0===s?void 0:s.DidCofigurationChangeAsync())){let t=null===(i=this._cache)||void 0===i?void 0:i.GetCache(e);if(null!=t)return Promise.resolve(t)}let c=0;const u=Date.now();if(!this.IsConnected()&&!(yield this.RestoreConnectionAsync()))throw new Error("Connection is not established");return"/users/user/login"!==e.Resource&&(yield null===(a=this._session)||void 0===a?void 0:a.WaitForSessionCreationAsync()),new Promise(((s,i)=>xv(this,void 0,void 0,(function*(){let a=l=>xv(this,void 0,void 0,(function*(){var d,h,p,g;if((null==l?void 0:l.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const f=Date.now()-u;if(o&&this._log.Debug(Fv.ServiceName,`Received response for: ${null==l?void 0:l.Resource} ${null==l?void 0:l.Method} id: ${null==l?void 0:l.TransactionId} in ${f}ms`),e.Method===le.Get&&n&&(null==l?void 0:l.Status)!==ue.UserIsNotLoggedIn&&(null===(d=this._cache)||void 0===d||d.Cache(l)),(null==l?void 0:l.Status)===ue.UserIsNotLoggedIn&&r){(null===(h=this._session)||void 0===h?void 0:h.OnUserLoggedOutEvent()).Invoke(null===(p=this._session)||void 0===p?void 0:p.User);try{yield null===(g=this._session)||void 0===g?void 0:g.RestoreSessionAsync(),s(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,o))}catch(e){i(e)}return}s(l)}}));if(this._dataReceivedEvent.Subscribe(a),c=window.setTimeout((()=>{this._dataReceivedEvent.Unsubscribe(a);let t=`Response timeout, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;this._log.Error(Fv.ServiceName,t),i(new Error(t))}),t),!this.SendData(e,o)){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;i(new Error(t))}}))))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}GetAuthorizationInfo(){return this._auth}GetServiceName(){return Fv.ServiceName}RestoreConnectionAsync(){return xv(this,void 0,void 0,(function*(){return!this._disconnectedOnPurpose&&(this._restoreTask||(this._restoreTask=(()=>xv(this,void 0,void 0,(function*(){const e=this._auth;if(null==e)return!1;if(this.IsConnected())return this.AuthorizeAsync(e);const t=yield this.GetServerAddressAsync();return null!=t&&((yield this.ConnectAsync(t))===he.Connected&&this.AuthorizeAsync(e))})))().finally((()=>{this._restoreTask=null}))),this._restoreTask)}))}}Fv.ServiceName="ExalusConnectionService";class Lv{constructor(){var e,t;this.OnEnteredPictureInPicture=new ke,this.OnExitedPictureInPicture=new ke,this._nativeApi=null,this.IsSupported()?(this._nativeApi=navigator.pip,null===(e=this._nativeApi)||void 0===e||e.OnEnteredPictureInPicture.Subscribe((()=>this.OnEnteredPictureInPicture.Invoke())),null===(t=this._nativeApi)||void 0===t||t.OnExitedPictureInPicture.Subscribe((()=>this.OnExitedPictureInPicture.Invoke()))):navigator.pip=null}IsSupported(){return void 0!==navigator.pip&&null!==navigator.pip}RequestPictureInPictureAsync(){return this.IsSupported()?this._nativeApi.RequestPictureInPictureAsync():Promise.resolve(!1)}GetServiceName(){return Lv.ServiceName}}Lv.ServiceName="PictureInPictureService",(Mv=Uv||(Uv={}))[Mv.Unknown=-1]="Unknown",Mv[Mv.Web=0]="Web",Mv[Mv.Android=1]="Android",Mv[Mv.iOS=2]="iOS";class Bv{constructor(){this.ClientName="",this.LavvaUserName="",this.ClientType=Uv.Unknown,this.TokenGuid="",this.Token="",this.RegistrationDate=new Date}}!function(e){e.FeatureUnsupported="FeatureUnsupported",e.UnknownError="UnknownError",e.NoData="NoData",e.IncorrectGuid="IncorrectGuid",e.IdentityIsEmpty="IdentityIsEmpty",e.DeviceTokenIsEmpty="DeviceTokenIsEmpty",e.ClientNameIsEmpty="ClientNameIsEmpty",e.LavvaUserNameIsEmpty="LavvaUserNameIsEmpty",e.TokenNotFound="TokenNotFound",e.TokensNotFoundForLavvaUser="TokensNotFoundForLavvaUser"}(Ov||(Ov={}));var Wv=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class $v{constructor(){this._connection=hy.Get(It.ServiceName),this._logger=hy.Get(a.ServiceName)}GetServiceName(){return $v.ServiceName}RegisterNotificationsClientAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{const n=new Vv({ClientName:e.ClientName,DeviceToken:e.DeviceToken,LavvaUserName:e.LavvaUserName,ClientType:this.getClientType(),NotificationsEnabledForToken:e.EnableNotifications}),r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,8e3,!1);if(null==r||null==r.Status)return new Ee(Ov.UnknownError,"Cannot register notifications client - unknown error!");switch(r.Status){case ue.WrongData:{const e=this.isValidErrorCode(r.Data)?r.Data:Ov.UnknownError;return new Ee(e,"Cannot register notifications client - wrong data!")}case ue.ResourceDoesNotExists:return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");case ue.OK:return"string"==typeof r.Data?r.Data:new Ee(Ov.NoData,"Cannot register notifications client - result status is OK, but no token guid presented in paylode, unknown error!");default:return new Ee(Ov.UnknownError,"Cannot register notifications client - unknown error!")}}catch(e){return new Ee(Ov.UnknownError,`Cannot register notifications client - error: ${e}`)}}))}UpdateNotificationsClientAsync(e,t){return Wv(this,void 0,void 0,(function*(){var n;try{const r=new qv({ClientName:t.ClientName,DeviceToken:t.DeviceToken,LavvaUserName:t.LavvaUserName,ClientType:this.getClientType(),NotificationsEnabledForToken:t.EnableNotifications,Guid:e}),o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(r,8e3,!1);if(null==o||null==o.Status)return new Ee(Ov.UnknownError,"Cannot update notifications client - unknown error!");switch(o.Status){case ue.WrongData:{const e=this.isValidErrorCode(o.Data)?o.Data:Ov.UnknownError;return new Ee(e,"Cannot update notifications client - wrong data!")}case ue.ResourceDoesNotExists:return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");case ue.OK:return"string"==typeof o.Data?o.Data==e?ue.OK:new Ee(Ov.UnknownError,`Cannot update notifications client - result status is OK, but token guid is different! request guid ${e}, response guid: ${o.Data}`):new Ee(Ov.NoData,"Cannot update notifications client - result status is OK, but no token guid presented in paylode, unknown error!");default:return new Ee(Ov.UnknownError,"Cannot update notifications client - unknown error!")}}catch(e){return this._logger.Error(`Cannot update notifications client - error: ${e}`),new Ee(Ov.UnknownError,`Cannot update notifications client - error: ${e}`)}}))}GetRegisteredNotificationsClientsMetadataAsync(e){return Wv(this,void 0,void 0,(function*(){var e;try{const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Hv,8e3,!1);return null==t||null==t.Status?new Ee(Ov.UnknownError,"Cannot get notifications clients metadata - unknown error!"):t.Status==ue.ResourceDoesNotExists?new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!"):t.Status!=ue.OK?new Ee(Ov.UnknownError,`Cannot get notifications clients metadata - response status: ${t.Status}}`):null==t.Data?new Ee(Ov.NoData,"Cannot get notifications clients metadata - response status is OK, but no data!"):t.Data.map((e=>{const t=new Bv;return t.ClientName=e.ClientName,t.LavvaUserName=e.LavvaUserName,t.ClientType=e.ClientType,t.TokenGuid=e.TokenGuid,t.Token=e.Token,t.RegistrationDate=new Date(e.RegistrationDate),t}))}catch(e){return this._logger.Error(`Cannot get notifications clients metadata - error: ${e}`),new Ee(Ov.UnknownError,`Cannot get notifications clients metadata - error: ${e}`)}}))}IsNotificationsEnabledForAllUserTokensAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Yv(e),8e3,!1);if(null==n||null==n.Status)return new Ee(Ov.UnknownError,"Cannot get notifications status - unknown error!");switch(n.Status){case ue.ResourceDoesNotExists:case ue.WrongData:if(null==n.Data)return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(n.Data)?n.Data:Ov.UnknownError;return new Ee(e,"Cannot get notifications status!")}case ue.OK:return"boolean"==typeof n.Data?n.Data:new Ee(Ov.NoData,"Cannot get notifications status - result status is OK, but no data, or data type is wrong!");default:return new Ee(Ov.UnknownError,`Cannot get notifications - response code ${n.Status}}!`)}}catch(e){return this._logger.Error(`Cannot get notifications status - error: ${e}`),new Ee(Ov.UnknownError,`Cannot get notifications status - error: ${e}`)}}))}IsNotificationsEnabledAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Kv(e),8e3,!1);if(null==n||null==n.Status)return new Ee(Ov.UnknownError,"Cannot get notifications status - unknown error!");switch(n.Status){case ue.ResourceDoesNotExists:if(null==n.Data)return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(n.Data)?n.Data:Ov.UnknownError;return new Ee(e,"Cannot get notifications status - resource not exists!")}case ue.OK:return"boolean"==typeof n.Data?n.Data:new Ee(Ov.NoData,"Cannot get notifications status - result status is OK, but no data, or data type is wrong!");default:return new Ee(Ov.UnknownError,`Cannot get notifications - response code ${n.Status}}!`)}}catch(e){return this._logger.Error(`Cannot get notifications status - error: ${e}`),new Ee(Ov.UnknownError,`Cannot get notifications status - error: ${e}`)}}))}EnableNotificationsAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{let n=null;null!=e&&""!=e&&(n=e);const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new jv(n),8e3,!1);if(null==r||null==r.Status)return new Ee(Ov.UnknownError,"Cannot enable notifications - unknown error!");switch(r.Status){case ue.ResourceDoesNotExists:if(null==r.Data)return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(r.Data)?r.Data:Ov.UnknownError;return new Ee(e,"Cannot enable notifications - resource not exists!")}case ue.OK:return ue.OK;default:return new Ee(Ov.UnknownError,`Cannot enable notifications - response code ${r.Status}}!`)}}catch(e){return this._logger.Error(`Cannot enable notifications - error: ${e}`),new Ee(Ov.UnknownError,`Cannot enable notifications - error: ${e}`)}}))}EnableNotificationsForAllUserTokensAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Jv(e),8e3,!1);if(null==n||null==n.Status)return new Ee(Ov.UnknownError,"Cannot enable notifications - unknown error!");switch(n.Status){case ue.ResourceDoesNotExists:case ue.WrongData:if(null==n.Data)return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(n.Data)?n.Data:Ov.UnknownError;return new Ee(e,"Cannot enable notifications!")}case ue.OK:return ue.OK;default:return new Ee(Ov.UnknownError,`Cannot enable notifications - response code ${n.Status}!`)}}catch(t){return this._logger.Error(`Cannot enable notifications for lavva user ${e} - error: ${t}`),new Ee(Ov.UnknownError,`Cannot disable notifications for lavva user ${e} - error: ${t}`)}}))}DisableNotificationsAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{let n=null;null!=e&&""!=e&&(n=e);const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new zv(n),8e3,!1);if(null==r||null==r.Status)return new Ee(Ov.UnknownError,"Cannot disable notifications - unknown error!");switch(r.Status){case ue.ResourceDoesNotExists:if(null==r.Data)return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(r.Data)?r.Data:Ov.UnknownError;return new Ee(e,"Cannot disable notifications - resource not exists!")}case ue.OK:return ue.OK;default:return new Ee(Ov.UnknownError,`Cannot disable notifications - response code ${r.Status}!`)}}catch(e){return this._logger.Error(`Cannot disable notifications - error: ${e}`),new Ee(Ov.UnknownError,`Cannot disable notifications - error: ${e}`)}}))}DisableNotificationsForAllUserTokensAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Xv(e),8e3,!1);if(null==n||null==n.Status)return new Ee(Ov.UnknownError,"Cannot disable notifications - unknown error!");switch(n.Status){case ue.ResourceDoesNotExists:case ue.WrongData:if(null==n.Data)return new Ee(Ov.FeatureUnsupported,"Notifications feature not supported in controller!");{const e=this.isValidErrorCode(n.Data)?n.Data:Ov.UnknownError;return new Ee(e,"Cannot disable notifications!")}case ue.OK:return ue.OK;default:return new Ee(Ov.UnknownError,`Cannot disable notifications - response code ${n.Status}!`)}}catch(t){return this._logger.Error(`Cannot disable notifications for lavva user ${e} - error: ${t}`),new Ee(Ov.UnknownError,`Cannot disable notifications for lavva user ${e} - error: ${t}`)}}))}DeleteNotificationsTokenAsync(e){return Wv(this,void 0,void 0,(function*(){var t;try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Qv(e),8e3,!1);return null==n||null==n.Status?new Ee(Ov.UnknownError,"Cannot delete notifications token - unknown error!"):n.Status==ue.OK?ue.OK:new Ee(Ov.UnknownError,`Cannot delete notifications token - response code ${n.Status}!`)}catch(e){return this._logger.Error(`Cannot delete notifications token - error: ${e}`),new Ee(Ov.UnknownError,`Cannot delete notifications token - error: ${e}`)}}))}getClientType(){return oe.IsIosNative()?Uv.iOS:navigator.userAgent.endsWith("LavvaAndroidNative")?Uv.Android:Uv.Web}isValidErrorCode(e){return Object.values(Ov).includes(e)}}$v.ServiceName="NotificationsService";class Vv extends ce{constructor(e){super(),this.Resource="/notifications/token",this.Method=le.Post,this.Data=e}}class qv extends ce{constructor(e){super(),this.Resource="/notifications/token",this.Method=le.Put,this.Data=e}}class Hv extends ce{constructor(){super(),this.Resource="/notifications/tokens/metadata",this.Method=le.Get}}class Kv extends ce{constructor(e){super(),this.Resource="/notifications/status",this.Method=le.Get,this.Data={TokenIdentity:e}}}class jv extends ce{constructor(e){super(),this.Resource="/notifications/enable",this.Method=le.Post,this.Data=e}}class zv extends ce{constructor(e){super(),this.Resource="/notifications/disable",this.Method=le.Post,this.Data=e}}class Jv extends ce{constructor(e){super(),this.Resource="/notifications/enable/for/lavva/user",this.Method=le.Post,this.Data=e}}class Xv extends ce{constructor(e){super(),this.Resource="/notifications/disable/for/lavva/user",this.Method=le.Post,this.Data=e}}class Yv extends ce{constructor(e){super(),this.Resource="/notifications/status/for/lavva/user",this.Method=le.Get,this.Data=e}}class Qv extends ce{constructor(e){super(),this.Resource="/notifications/token",this.Method=le.Delete,this.Data=e}}class Zv{CheckLocationPermissionAsync(){return this.IsAndroidLocationAvailable()?navigator.AndroidLocation.CheckLocationPermissionAsync():Promise.resolve(!1)}RequestLocationPermissionAsync(){return this.IsAndroidLocationAvailable()?navigator.AndroidLocation.RequestLocationPermissionAsync():Promise.resolve(!1)}IsAndroidLocationAvailable(){return void 0!==navigator.AndroidLocation}GetServiceName(){return Zv.ServiceName}}Zv.ServiceName="AndroidLocationService";class ey{IsAndroidNotificationsAvailable(){return void 0!==navigator.AndroidNotifications}CheckNotificationPermissionAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.CheckNotificationPermissionAsync():Promise.resolve(!1)}RequestNotificationPermissionAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.RequestNotificationPermissionAsync():Promise.resolve(!1)}GetDeviceFirebaseTokenAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.GetDeviceFirebaseTokenAsync():Promise.resolve(null)}GetNotificationsQueueAsync(){return this.IsAndroidNotificationsAvailable()?navigator.AndroidNotifications.GetNotificationsQueueAsync():Promise.resolve(null)}GetServiceName(){return ey.ServiceName}}ey.ServiceName="AndroidNotificationsService";class ty{OpenRateDialogAsync(){if(oe.IsIosNative())try{if(null!=window.webkit.messageHandlers.rateApp)return window.webkit.messageHandlers.rateApp.postMessage(!0),Promise.resolve()}catch(e){return Promise.reject(new Error(`Rate dialog is not available on this platform. Error: ${e}`))}else if(this.IsAvailable())return navigator.AndroidAppRate.OpenRateDialogAsync();return Promise.reject(new Error("AppRateService is not available on this platform."))}IsAvailable(){var e,t;return void 0!==navigator.AndroidAppRate||void 0!==(null===(t=null===(e=window.webkit)||void 0===e?void 0:e.messageHandlers)||void 0===t?void 0:t.rateApp)}GetServiceName(){return ty.ServiceName}}ty.ServiceName="AppRateService";class ny{GetCurrentLocalesAsync(){return this.IsAvailable()?navigator.AppLocales.GetCurrentLocalesAsync():Promise.resolve(void 0)}SetCurrentLocalesAsync(e){if(!this.IsAvailable())throw new Error("AppLocalesService is not available");return navigator.AppLocales.SetCurrentLocalesAsync(e)}IsAvailable(){var e,t;return void 0!==navigator.AppLocales||void 0!==(null===(t=null===(e=window.webkit)||void 0===e?void 0:e.messageHandlers)||void 0===t?void 0:t.appLocales)}GetServiceName(){return ny.ServiceName}}ny.ServiceName="AppLocalesService";var ry,oy=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};!function(e){e[e.Lavva=0]="Lavva",e[e.Wisniowski=1]="Wisniowski",e[e.ExalusHome=2]="ExalusHome"}(ry||(ry={}));class sy{GetServiceName(){return sy.ServiceName}SetInstallation(e){return oy(this,void 0,void 0,(function*(){if(void 0===e.BrokerUrl||void 0===e.InstallationId||void 0===e.InstallationType)return Promise.reject(new Error("Invalid installation info, all fields are required"));if(hy.Get(a.ServiceName).Info(sy.ServiceName,`Setting Android Auto/CarPlay installation: ${e.InstallationType} (${e.InstallationId}) broker: ${e.BrokerUrl}`),!(this.IsAndroidAutoAvailable()||oe.IsIosNative()&&null!=window.webkit.messageHandlers.carPlay))return hy.Get(a.ServiceName).Warning(sy.ServiceName,"Android Auto/CarPlay is not available on this platform!"),Promise.resolve();if(e.InstallationType===ry.ExalusHome){let t=hy.Get(It.ServiceName);e.ControllerSerial=t.GetControllerSerialNumber(),e.ControllerPin=t.GetControllerPin();let n=yield t.GetServerAddressAsync();null!==n&&(n.includes("dev-")?e.BrokerUrl="dev-broker.tr7.pl:4431":e.BrokerUrl="services-broker.tr7.pl");try{let t=yield this.GetTokenFromController();t?e.AuthToken=t:hy.Get(a.ServiceName).Warning(sy.ServiceName,"Failed to get auth token from controller, Android Auto/CarPlay integration might not work properly!")}catch(e){hy.Get(a.ServiceName).Error(sy.ServiceName,"Error while getting auth token from controller, Android Auto/CarPlay integration might not work properly! \n"+e)}}if(this.IsAndroidAutoAvailable())navigator.AndroidAuto.SetInstallation(e);else{if(!oe.IsIosNative()||null==window.webkit.messageHandlers.carPlay)return Promise.reject(new Error("Android Auto/CarPlay is not available"));window.webkit.messageHandlers.carPlay.postMessage(e)}return Promise.resolve()}))}GetTokenFromController(){return oy(this,void 0,void 0,(function*(){var e;if(this.IsAndroidAutoAvailable()||oe.IsIosNative()&&null!=window.webkit.messageHandlers.carPlay){let t=yield hy.Get(It.ServiceName).SendAndWaitForResponseAsync(new iy,12e3,!1);if((null==t?void 0:t.Status)===ue.OK)return Promise.resolve((null===(e=null==t?void 0:t.Data)||void 0===e?void 0:e.Token)||null)}return Promise.resolve(null)}))}IsAndroidAutoAvailable(){return void 0!==navigator.AndroidAuto}ClearInstallation(){return this.IsAndroidAutoAvailable()&&navigator.AndroidAuto.SetInstallation(null),oe.IsIosNative()&&null!=window.webkit.messageHandlers.carPlay?(window.webkit.messageHandlers.carPlay.postMessage(null),Promise.resolve()):Promise.reject(new Error("Android Auto/CarPlay is not available"))}}sy.ServiceName="AndroidAutoCarPlayService";class iy extends ce{constructor(){super(),this.Resource="/webapibridge/get-token",this.Method=le.Get}}var ay=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class cy{constructor(){this._connection=hy.Get(It.ServiceName)}GetServiceName(){return cy.ServiceName}isHomeKitPairingStatusResponse(e){return"object"==typeof e&&null!==e&&"Paired"in e&&"boolean"==typeof e.Paired}GetPairingStatusAsync(){return ay(this,void 0,void 0,(function*(){const e=new ly,t=yield this._connection.SendAndWaitForResponseAsync(e,5e3,!1);if(t.Status!==ue.OK)return t.Status;const n=new uy;return this.isHomeKitPairingStatusResponse(t.Data)&&(n.Paired=t.Data.Paired),n}))}IsPairedAsync(){return ay(this,void 0,void 0,(function*(){const e=yield this.GetPairingStatusAsync();return this.isHomeKitPairingStatusResponse(e)?e.Paired:e}))}ResetPairingAsync(){return ay(this,void 0,void 0,(function*(){const e=new dy;return(yield this._connection.SendAndWaitForResponseAsync(e,5e3,!1)).Status}))}}cy.ServiceName="HomeKitService";class uy{constructor(){this.Paired=!1}}class ly extends ce{constructor(){super(),this.Resource="/homekit/pairing/status",this.Method=le.Get}}class dy extends ce{constructor(){super(),this.Resource="/homekit/pairing/reset",this.Method=le.Post}}fu(Map),fu(Set),(()=>{const e=String.prototype,t=Object.getOwnPropertyNames(_i.prototype);for(const n of t)e[n]=e[n]??_i.prototype[n];e.first=function(e){if(e){for(let t=0;t<this.length;t++){const n=this[t];if(!0===e(n))return n}throw new mi(yi.NoMatch)}if(0===this.length)throw new mi(yi.NoElements);return this[0]},e.firstOrDefault=function(e){if(e){for(let t=0;t<this.length;t++){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[0]},e.count=function(e){if(e){let t=0;for(let n=0;n<this.length;n++)!0===e(this[n])&&t++;return t}return this.length},e.elementAt=function(e){if(e<0||e>=this.length)throw new vi("index");return this[e]},e.elementAtOrDefault=function(e){return this[e]||null},e.last=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}throw new mi(yi.NoMatch)}if(0===this.length)throw new mi(yi.NoElements);return this[this.length-1]},e.lastOrDefault=function(e){if(e){for(let t=this.length-1;t>=0;t--){const n=this[t];if(!0===e(n))return n}return null}return 0===this.length?null:this[this.length-1]},e.reverse=function(){const e=this;return new _i((function*(){for(let t=e.length-1;t>=0;t--)yield e[t]}))}})(),mg(Array),mg(Int8Array),mg(Int16Array),mg(Int32Array),mg(Uint8Array),mg(Uint8ClampedArray),mg(Uint16Array),mg(Uint32Array),mg(Float32Array),mg(Float64Array);class hy{static Init(){if(u.IsInitialized)return;console.log("Initializing DependencyContainer");let e=u.Instance;try{e.RegisterService(new Gv),e.RegisterService(new l),e.RegisterService(new _t),e.RegisterService(new Be),e.RegisterService(new Xe),e.RegisterService(new Lv),e.RegisterService(new ty),e.RegisterService(new ny),hy.IsRunningFromLocalNetwork()?(console.log("\n\nRunning from local network!\n\n"),e.RegisterService(new Fv)):e.RegisterService(new It),e.RegisterService(new Zv),e.RegisterService(new sy),e.RegisterService(new ey),e.RegisterService(new ko),e.RegisterService(new Mo),e.RegisterService(new ct),e.RegisterService(new Rv),e.RegisterService(new _o),e.RegisterService(new nt),e.RegisterService(new Ne),e.RegisterService(new $e),e.RegisterService(new Ys),e.RegisterService(new Ug),e.RegisterService(new cs),e.RegisterService(new ff),e.RegisterService(new Dv),e.RegisterService(new Hf),e.RegisterService(new Ls),e.RegisterService(new Av),e.RegisterService(new $v),e.RegisterService(new cy)}catch(e){console.error(e)}}static IsAppServedFromControllerAsync(){const e=`http://${window.location.hostname}/controller_info`;return fetch(e,{method:"GET"}).then((e=>!!e.ok)).catch((e=>!1))}static IsRunningFromLocalNetwork(e=window.location.hostname){return e.startsWith("192.168.")||e.startsWith("10.")||e.startsWith("172.16.")}static GetAsync(e,t){return u.Instance.GetServiceAsync(e,t)}static GetWithTimeoutAsync(e,t){return u.Instance.GetServiceWithTimeoutAsync(e,t)}static Get(e){return u.Instance.GetService(e)}static SleepForAsync(e){return new Promise((t=>setTimeout(t,e)))}static ExportStringAsFileToDownload(e,t){const n=new Blob([t],{type:"text/plain"}),r=document.createElement("a"),o=window.URL.createObjectURL(n);return r.href=o,r.download=e,r}}hy.WorksInContextOf="",hy.Version=1;var py=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class gy{constructor(e){this._protocolGuid=e.ExtensionGuid,this._protocolExtGuid=e.ExtensionGuid,this._connection=hy.Get(It.ServiceName)}get ProtocolExtensionGuid(){return this._protocolExtGuid}get ProtocolGuid(){return this._protocolGuid}GetServiceName(){return gy.ServiceName}GetDevicesForManualPairingAsync(){return py(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new vy,8e3,!1);return null==t||null==t.Data||t.Status!=ue.OK?[]:t.Data.map((e=>{const t=new fy;return t.Channels=e.Channels,t.Description=e.Description,t.Model=e.Model,t.ModelGuid=e.ModelGuid,t.ProtocolExtensionGuid=this._protocolExtGuid,t.IconType=e.IconType,t}))}))}AddManuallyPairedDeviceAsync(e){return py(this,void 0,void 0,(function*(){var t;const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new yy(e.ModelGuid),8e3,!1);return hy.Get(a.ServiceName).Error(gy.ServiceName,"EXIT CONFIGURATION MODE WILL BE FIRED! AddManuallyPairedDeviceAsync()"),yield hy.Get(ct.ServiceName).ExitConfigurationModeAsync(),null==n||null==n.Status||n.Status!=ue.OK?Ft.Failed:null==n.Data?Ft.Unknown:Ft.Executed}))}}gy.ServiceName="PortosManualDevicePairingService";class fy{constructor(){this._modelGuid="",this._model="",this._description="",this._channels=0,this._protocolExtGuid="",this._iconType=Nt.Unknown}get IconType(){return this._iconType}set IconType(e){this._iconType=e}get ModelGuid(){return this._modelGuid}set ModelGuid(e){this._modelGuid=e}get Model(){return this._model}set Model(e){this._model=e}get Description(){return this._description}set Description(e){this._description=e}get Channels(){return this._channels}set Channels(e){this._channels=e}set ProtocolExtensionGuid(e){this._protocolExtGuid=e}get ProtocolExtensionGuid(){return this._protocolExtGuid}}class vy extends ce{constructor(){super(),this.Resource="/portos/devices/manual/pair/available",this.Method=le.Get}}class yy extends ce{constructor(e){super(),this.Resource="/portos/devices/device/create",this.Method=le.Put,this.Data={DeviceModelGuid:e}}}class my{constructor(){this._connection=hy.Get(It.ServiceName),this._logger=hy.Get(a.ServiceName)}GetServiceName(){return my.ServiceName}SendP2PairingSignalAsync(e,t){return n=this,r=void 0,s=function*(){var n;try{if(!e.Channels.any((e=>e.Number===t)))return this._logger.Error(my.ServiceName,"Cannot pair channel. Wrong channel number."),ue.WrongData;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new wy(new Sy(e.Guid,t)),8e3,!1);return null==r||null==r.Status?(this._logger.Error(my.ServiceName,"Cannot pair channel. Controller response does not contain data."),ue.Error):(r.Status!==ue.OK&&this._logger.Error(my.ServiceName,`Cannot pair channel. Controller responede with status code: ${r.Status}`),r.Status)}catch(e){return this._logger.Error(my.ServiceName,`Cannot pair channel. ${e}`),ue.FatalError}},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{c(s.next(e))}catch(e){t(e)}}function a(e){try{c(s.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o((function(e){e(n)}))).then(i,a)}c((s=s.apply(n,r||[])).next())}));var n,r,o,s}}my.ServiceName="Portos433ConfigService";class wy extends ce{constructor(e){super(),this.Resource="/portos/devices/device/channel/pair",this.Method=le.Put,this.Data=e}}class Sy{constructor(e,t){this.DeviceGuid="",this.Channel=0,this.DeviceGuid=e,this.Channel=t}}var Ay=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class _y{constructor(e,t){this._apiVersion=e.APIVersion,this._extenstionVersion=e.ExtensionVersion,this._protocolExtGuid=e.ExtensionGuid,this._runtimeInfo=t}get ExtensionGuid(){return this._protocolExtGuid}get ProtocolGuid(){return Ey.PortosExtensionGuid}get AvailableExtensionVersion(){return this._extenstionVersion}get AvailableApiVersion(){return this._apiVersion}get ProviderType(){return Po.Device}GetUpdateProviderName(){return`${_y.ProviderName}_${this._apiVersion}_${this._extenstionVersion}`}GetAvailableUpdateAsync(e){throw new Error("Method not implemented.")}InstallUpdateAsync(e,t,n){throw new Error("Method not implemented.")}GetSoftwareVersionAsync(e){throw new Error("Method not implemented.")}CheckUpdateBulkAsync(e){return Ay(this,void 0,void 0,(function*(){return[]}))}InstalUpdateBulkAsync(e,t,n){return Ay(this,void 0,void 0,(function*(){throw new Error("Method not implemented.")}))}}_y.ProviderName="PortosDeviceUpdateProvider";var Cy=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Dy{constructor(e,t){this._apiVersion=e.APIVersion,this._extenstionVersion=e.ExtensionVersion,this._protocolExtGuid=e.ExtensionGuid,this._runtimeInfo=t,this._logger=hy.Get(a.ServiceName),this._connection=hy.Get(It.ServiceName)}get AvailableExtensionVersion(){return this._extenstionVersion}get AvailableApiVersion(){return this._apiVersion}get ExtensionGuid(){return this._protocolExtGuid}get ProtocolGuid(){return Ey.PortosProtocolGuid}get ProviderType(){return Po.Controller}GetUpdateProviderName(){return`${Dy.ProviderName}_${this._apiVersion}_${this._extenstionVersion}`}GetAvailableRadioUpdateAsync(){return Cy(this,void 0,void 0,(function*(){var e,t;if(this._logger.Debug(Dy.ProviderName,"Checking for Portos 433 MHz adio firmware upgrade..."),null===(e=(yield hy.Get(cs.ServiceName).GetHardwareInfoAsync()).GetAvailableHardware.first((e=>"/proc"==e.DevicePath)))||void 0===e?void 0:e.DisplayName.contains("AM3352"))return new Ee(bg.UnsupportedDevice,"Cannot get available updates! This Portos module does not support updates.");if(parseFloat(this._extenstionVersion)<.1200518)return new Ee(bg.UnsupportedExtensionVersion,`Cannot get available updates! Portos 433 MHz extension is too old for upgrade. Version: ${this._extenstionVersion}`);const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ty,8e3,!1);let r=.2;null!=n&&null!=n.Data&&(r=n.Data),this._logger.Debug(Dy.ProviderName,`Portos 433MHz radio firmware version: ${r}`);var o=`https://updates.tr7.pl/firmware/${this._runtimeInfo.UpdateChannel}/${r}/${Ey.PortosRadioModuleDeviceGuid}`;try{this._logger.Debug(`Looking for update at: ${o}/${r}/update.json`);let e,t=yield fetch(`${o}/${r}/update.json`),n=new Wo;if(200===t.status)null!=t.body&&(e=yield t.json());else switch(this._logger.Debug(`Looking for update at: ${o}/update.json`),t=yield fetch(`${o}/update.json`),t.status){case 200:null!=t.body&&(e=yield t.json());break;case 404:return new Ee(bg.DeviceIsUpToDate,"Updates not found, radio Portos 433MHz is already up-to-date.");default:return new Ee(bg.CannotGetUpdates,`Response status code does not indicate success. Status: ${t.status}`)}if(null!=e)return e.UpdateType=Uo.RadioFirmware,n.CurrentResourceVersion=r.toString(),n.UpdatedResourceName="Radio Portos 433MHz",n.UpdateDescription=new Map([["pl-PL",e.Description]]),n.Update=e,n;throw new Error(`Cannot get Update Data from response. Status: ${t.status}`)}catch(e){return new Ee(bg.CannotGetUpdates,`Cannot get available updates! ${e}`)}}))}InstallRadioUpdateAsync(e,t,n){return Cy(this,void 0,void 0,(function*(){var r;if(null!=n)return new Ee(bg.UpdateActionsNotSupported,`Update service for given resource: ${e.UpdatedResourceName} does not support custom update actions.`);const o=new tf;o.UpdatedResourceName=new Map([["pl-PL",e.UpdatedResourceName],["en-US",e.UpdatedResourceName]]);try{yield null===(r=this._connection)||void 0===r?void 0:r.SendAndHandleResponseAsync(new ky(e.Update.DownloadUri),12e3,(n=>{switch(n.Status){case ue.MultiDataResponseStart:o.Status=Cg.PreparingForUpgrade;break;case ue.MultiDataResponse:if(null==n.Data)return void this._logger.Warning(Dy.ProviderName,`Recived update response without data! URI: ${e.Update.DownloadUri}`);o.Percentage=n.Data,o.Status=Cg.Upgrading;break;case ue.MultiDataResponseStop:n.Data?(o.Percentage=100,o.Status=Cg.Upgraded):o.Status=Cg.InstallationError}this._logger.Debug(Dy.ProviderName,`Recived update progress response, percentage: ${o.Percentage}, status: ${o.Status}, resource name: ${e.UpdatedResourceName}`),t(o)}),!1)}catch(e){return o.Percentage=0,o.Status=Cg.Error,t(o),new Ee(bg.CannotProcessUpdate,`Cannot process update, error: ${e}`)}return ue.OK}))}GetCurrentRadioVersionAsync(){return Cy(this,void 0,void 0,(function*(){var e;const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ty,8e3,!1);return null!=t&&null!=t.Data?t.Data.toString():"n/a"}))}}Dy.ProviderName="PortosControllerUpdateProvider";class Ty extends ce{constructor(){super(),this.Resource="/portos/radio/version",this.Method=le.Get}}class ky extends ce{constructor(e){super(),this.Resource="/portos/radio/upgrade",this.Method=le.Put,this.Data=e}}var Iy=function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))};class Ey{constructor(){this._services={Portos433ConfigService:new my},this._servicesToDeviceMap=new Map([["080844eb-3ec1-4611-a327-757a634bd866",[this._services.Portos433ConfigService]],["179b750c-5c73-4a6c-865c-5cf85a27200b",[this._services.Portos433ConfigService]]])}GetServiceName(){return Ey.ServiceName}static Init(){u.Instance.RegisterService(new Ey),hy.Get(a.ServiceName).Debug(Ey.ServiceName,"Initialized PortosService"),Ey.RegisterManuallyPairedDeviceServiceAsync(),Ey.RegisterUpdateProviderAsync()}static RegisterManuallyPairedDeviceServiceAsync(){return Iy(this,void 0,void 0,(function*(){const e=(yield hy.Get(nt.ServiceName).GetExtensionsInfoAsync(Ey.PortosExtensionGuid)).first();null!=e?(hy.Get(a.ServiceName).Debug(Ey.ServiceName,"Registering Portos manually paired device service."),hy.Get(_o.ServiceName).RegisterManuallyPairedDevicesProtocol(new gy(e))):hy.Get(a.ServiceName).Warning(Ey.ServiceName,"Portos manually paired device service not registered - controller does not support Portos extension.")}))}static RegisterUpdateProviderAsync(){return Iy(this,void 0,void 0,(function*(){const e=yield hy.Get(cs.ServiceName),t=(yield hy.Get(nt.ServiceName).GetExtensionsInfoAsync(Ey.PortosExtensionGuid)).first(),n=yield e.GetSoftwareRuntimeInfoAsync();null!=t?(hy.Get(a.ServiceName).Debug(Ey.ServiceName,"Registering Portos update providers."),null==e||e.RegisterUpdatesProvider(new _y(t,n)),null==e||e.RegisterUpdatesProvider(new Dy(t,n))):hy.Get(a.ServiceName).Warning(Ey.ServiceName,"Portos device update provider not registered - controller does not support Portos extension.")}))}GetDeviceServiceByServiceType(e){return"Portos433ConfigService"===e?this._services.Portos433ConfigService:null}GetDeviceService(e,t){let n=this.GetAllDeviceServices(e);return null!==n?n.firstOrDefault((e=>e.GetServiceName()===t)):null}GetAllDeviceServices(e){if(null!==e.ModelGuid){const t=this._servicesToDeviceMap.get(e.ModelGuid);return void 0!==t?t:[]}return[]}IsDeviceServiceSupported(e,t){return null!==this.GetDeviceService(e,t)}}Ey.ServiceName="PortosService",Ey.PortosExtensionGuid="ca9c9dee-8bf6-4688-a04f-1ce35693405f",Ey.PortosProtocolGuid="cd25bdff-628c-4dbc-a16a-648c96a819d4",Ey.PortosRadioModuleDeviceGuid="b015ecf2-14c9-4b35-81f1-d008f3a75442"})();
//# sourceMappingURL=exalushome-portos-bundle.js.map