lavva.exalushome.extalife 1.0.607 → 1.0.637

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/build/exalushome-ExtaLife-bundle.js +1 -1
  2. package/build/exalushome-ExtaLife-bundle.js.map +1 -1
  3. package/build/js/Devices/DeviceServices/Common/BlindConfigurations/BlindConfigParameters.d.ts +48 -0
  4. package/build/js/Devices/DeviceServices/Common/BlindConfigurations/BlindConfigParameters.js +46 -0
  5. package/build/js/Devices/DeviceServices/Common/BlindConfigurations/BlindConfigParameters.js.map +1 -0
  6. package/build/js/Devices/DeviceServices/Common/BlindConfigurations/BlindConfigService.d.ts +40 -0
  7. package/build/js/Devices/DeviceServices/Common/BlindConfigurations/BlindConfigService.js +677 -0
  8. package/build/js/Devices/DeviceServices/Common/BlindConfigurations/BlindConfigService.js.map +1 -0
  9. package/build/js/Devices/DeviceServices/Common/OnOffSwitchConfigurations/OnOffSwitchParameters.d.ts +85 -0
  10. package/build/js/Devices/DeviceServices/Common/OnOffSwitchConfigurations/OnOffSwitchParameters.js +113 -0
  11. package/build/js/Devices/DeviceServices/Common/OnOffSwitchConfigurations/OnOffSwitchParameters.js.map +1 -0
  12. package/build/js/Devices/DeviceServices/Common/OnOffSwitchConfigurations/OnOffSwitchService.d.ts +32 -0
  13. package/build/js/Devices/DeviceServices/Common/OnOffSwitchConfigurations/OnOffSwitchService.js +443 -0
  14. package/build/js/Devices/DeviceServices/Common/OnOffSwitchConfigurations/OnOffSwitchService.js.map +1 -0
  15. package/build/js/Devices/DeviceServices/Dimmer/IRdp21ConfigService.d.ts +25 -0
  16. package/build/js/Devices/DeviceServices/Dimmer/IRdp21ConfigService.js +2 -0
  17. package/build/js/Devices/DeviceServices/Dimmer/IRdp21ConfigService.js.map +1 -0
  18. package/build/js/Devices/DeviceServices/Dimmer/Rdp21ConfigParameters.d.ts +13 -0
  19. package/build/js/Devices/DeviceServices/Dimmer/Rdp21ConfigParameters.js +13 -0
  20. package/build/js/Devices/DeviceServices/Dimmer/Rdp21ConfigParameters.js.map +1 -0
  21. package/build/js/Devices/DeviceServices/Dimmer/Rdp21ConfigService.d.ts +21 -0
  22. package/build/js/Devices/DeviceServices/Dimmer/Rdp21ConfigService.js +337 -0
  23. package/build/js/Devices/DeviceServices/Dimmer/Rdp21ConfigService.js.map +1 -0
  24. package/build/js/Devices/DeviceServices/FacadeBlindService/IZfBidiConfigService.d.ts +22 -0
  25. package/build/js/Devices/DeviceServices/FacadeBlindService/IZfBidiConfigService.js +2 -0
  26. package/build/js/Devices/DeviceServices/FacadeBlindService/IZfBidiConfigService.js.map +1 -0
  27. package/build/js/Devices/DeviceServices/FacadeBlindService/ZfBidiConfigParams.d.ts +39 -0
  28. package/build/js/Devices/DeviceServices/FacadeBlindService/ZfBidiConfigParams.js +27 -0
  29. package/build/js/Devices/DeviceServices/FacadeBlindService/ZfBidiConfigParams.js.map +1 -0
  30. package/build/js/Devices/DeviceServices/FacadeBlindService/ZfBidiConfigService.d.ts +36 -0
  31. package/build/js/Devices/DeviceServices/FacadeBlindService/ZfBidiConfigService.js +661 -0
  32. package/build/js/Devices/DeviceServices/FacadeBlindService/ZfBidiConfigService.js.map +1 -0
  33. package/build/js/Devices/DeviceServices/GateControler/IRob21ConfigService.d.ts +50 -0
  34. package/build/js/Devices/DeviceServices/GateControler/IRob21ConfigService.js +2 -0
  35. package/build/js/Devices/DeviceServices/GateControler/IRob21ConfigService.js.map +1 -0
  36. package/build/js/Devices/DeviceServices/GateControler/Rob21ConfigParams.d.ts +20 -0
  37. package/build/js/Devices/DeviceServices/GateControler/Rob21ConfigParams.js +26 -0
  38. package/build/js/Devices/DeviceServices/GateControler/Rob21ConfigParams.js.map +1 -0
  39. package/build/js/Devices/DeviceServices/GateControler/Rob21ConfigService.d.ts +24 -0
  40. package/build/js/Devices/DeviceServices/GateControler/Rob21ConfigService.js +427 -0
  41. package/build/js/Devices/DeviceServices/GateControler/Rob21ConfigService.js.map +1 -0
  42. package/build/js/Devices/DeviceServices/LedController/ISlr22ConfigService.d.ts +35 -0
  43. package/build/js/Devices/DeviceServices/LedController/ISlr22ConfigService.js +2 -0
  44. package/build/js/Devices/DeviceServices/LedController/ISlr22ConfigService.js.map +1 -0
  45. package/build/js/Devices/DeviceServices/LedController/Slr22ConfigService.d.ts +18 -0
  46. package/build/js/Devices/DeviceServices/LedController/Slr22ConfigService.js +197 -0
  47. package/build/js/Devices/DeviceServices/LedController/Slr22ConfigService.js.map +1 -0
  48. package/build/js/Devices/DeviceServices/MovementSensor/IRcr21ConfigService.d.ts +44 -0
  49. package/build/js/Devices/DeviceServices/MovementSensor/Rcr21ConfigService.d.ts +0 -44
  50. package/build/js/Devices/DeviceServices/MovementSensor/Rcr21ConfigService.js +0 -44
  51. package/build/js/Devices/DeviceServices/MovementSensor/Rcr21ConfigService.js.map +1 -1
  52. package/build/js/Devices/DeviceServices/MultiSensor/IRcm21ConfigService.d.ts +25 -0
  53. package/build/js/Devices/DeviceServices/MultiSensor/Rcm21ConfigService.d.ts +0 -6
  54. package/build/js/Devices/DeviceServices/MultiSensor/Rcm21ConfigService.js +1 -7
  55. package/build/js/Devices/DeviceServices/MultiSensor/Rcm21ConfigService.js.map +1 -1
  56. package/build/js/Devices/DeviceServices/MultiSensor/VersionedOptions/^0.0.0.0/Rcm21VersionedService.d.ts +0 -19
  57. package/build/js/Devices/DeviceServices/MultiSensor/VersionedOptions/^0.0.0.0/Rcm21VersionedService.js +0 -19
  58. package/build/js/Devices/DeviceServices/MultiSensor/VersionedOptions/^0.0.0.0/Rcm21VersionedService.js.map +1 -1
  59. package/build/js/Devices/DeviceServices/PowerPlugSwitch/IRog21ConfigService.d.ts +12 -0
  60. package/build/js/Devices/DeviceServices/PowerPlugSwitch/IRog21ConfigService.js +2 -0
  61. package/build/js/Devices/DeviceServices/PowerPlugSwitch/IRog21ConfigService.js.map +1 -0
  62. package/build/js/Devices/DeviceServices/PowerPlugSwitch/Rog21ConfigService.d.ts +7 -0
  63. package/build/js/Devices/DeviceServices/PowerPlugSwitch/Rog21ConfigService.js +11 -0
  64. package/build/js/Devices/DeviceServices/PowerPlugSwitch/Rog21ConfigService.js.map +1 -0
  65. package/build/js/Devices/DeviceServices/RomSwitches/IRomConfigService.d.ts +18 -0
  66. package/build/js/Devices/DeviceServices/RomSwitches/IRomConfigService.js +2 -0
  67. package/build/js/Devices/DeviceServices/RomSwitches/IRomConfigService.js.map +1 -0
  68. package/build/js/Devices/DeviceServices/RomSwitches/RomConfigService.d.ts +7 -0
  69. package/build/js/Devices/DeviceServices/RomSwitches/RomConfigService.js +11 -0
  70. package/build/js/Devices/DeviceServices/RomSwitches/RomConfigService.js.map +1 -0
  71. package/build/js/Devices/DeviceServices/RopSwitches/IRopConfigService.d.ts +18 -0
  72. package/build/js/Devices/DeviceServices/RopSwitches/IRopConfigService.js +2 -0
  73. package/build/js/Devices/DeviceServices/RopSwitches/IRopConfigService.js.map +1 -0
  74. package/build/js/Devices/DeviceServices/RopSwitches/RopConfigService.d.ts +7 -0
  75. package/build/js/Devices/DeviceServices/RopSwitches/RopConfigService.js +11 -0
  76. package/build/js/Devices/DeviceServices/RopSwitches/RopConfigService.js.map +1 -0
  77. package/build/js/Devices/DeviceServices/SrpConfigService/ISrp22ConfigService.d.ts +24 -0
  78. package/build/js/Devices/DeviceServices/SrpConfigService/ISrp22ConfigService.js +2 -0
  79. package/build/js/Devices/DeviceServices/SrpConfigService/ISrp22ConfigService.js.map +1 -0
  80. package/build/js/Devices/DeviceServices/SrpConfigService/ISrp30ConfigService.d.ts +18 -0
  81. package/build/js/Devices/DeviceServices/SrpConfigService/ISrp30ConfigService.js +2 -0
  82. package/build/js/Devices/DeviceServices/SrpConfigService/ISrp30ConfigService.js.map +1 -0
  83. package/build/js/Devices/DeviceServices/SrpConfigService/Srp22ConfigService.d.ts +7 -0
  84. package/build/js/Devices/DeviceServices/SrpConfigService/Srp22ConfigService.js +11 -0
  85. package/build/js/Devices/DeviceServices/SrpConfigService/Srp22ConfigService.js.map +1 -0
  86. package/build/js/Devices/DeviceServices/SrpConfigService/Srp30ConfigService.d.ts +7 -0
  87. package/build/js/Devices/DeviceServices/SrpConfigService/Srp30ConfigService.js +11 -0
  88. package/build/js/Devices/DeviceServices/SrpConfigService/Srp30ConfigService.js.map +1 -0
  89. package/build/js/Devices/DeviceServices/SsrConfigService/ISsrConfigService.d.ts +13 -0
  90. package/build/js/Devices/DeviceServices/SsrConfigService/ISsrConfigService.js +2 -0
  91. package/build/js/Devices/DeviceServices/SsrConfigService/ISsrConfigService.js.map +1 -0
  92. package/build/js/Devices/DeviceServices/SsrConfigService/SsrConfigService.d.ts +7 -0
  93. package/build/js/Devices/DeviceServices/SsrConfigService/SsrConfigService.js +11 -0
  94. package/build/js/Devices/DeviceServices/SsrConfigService/SsrConfigService.js.map +1 -0
  95. package/build/js/Devices/DeviceServices/WindSensor/IWszfBidiConfigService.d.ts +11 -0
  96. package/build/js/Devices/DeviceServices/WindSensor/IWszfBidiConfigService.js +2 -0
  97. package/build/js/Devices/DeviceServices/WindSensor/IWszfBidiConfigService.js.map +1 -0
  98. package/build/js/Devices/DeviceServices/WindSensor/WszfBidiConfigParams.d.ts +28 -0
  99. package/build/js/Devices/DeviceServices/WindSensor/WszfBidiConfigParams.js +33 -0
  100. package/build/js/Devices/DeviceServices/WindSensor/WszfBidiConfigParams.js.map +1 -0
  101. package/build/js/Devices/DeviceServices/WindSensor/WszfBidiConfigService.d.ts +17 -0
  102. package/build/js/Devices/DeviceServices/WindSensor/WszfBidiConfigService.js +133 -0
  103. package/build/js/Devices/DeviceServices/WindSensor/WszfBidiConfigService.js.map +1 -0
  104. package/build/js/ExtaLife.d.ts +3 -1
  105. package/build/js/ExtaLife.js +81 -1
  106. package/build/js/ExtaLife.js.map +1 -1
  107. package/build/tsconfig.tsbuildinfo +1 -1
  108. package/package.json +2 -2
@@ -1,2 +1,2 @@
1
- (()=>{"use strict";var e,t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.d({},{v:()=>Th});class n{constructor(){this.handlers=[]}Subscribe(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=r.Log)||void 0===n||n.Error(e)}}))}}!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(e||(e={}));class o{constructor(){this._blockedServices=[],this._logLevel=e.Debug}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(o.ServiceName,`Disabling logs from ${e}`)}EnableLogsFrom(e){this._blockedServices.any((t=>t==e))&&(this._blockedServices=this._blockedServices.where((t=>t!=e)).toArray()),this.Debug(o.ServiceName,`Enaabling logs from ${e}`)}get LogLevel(){return this._logLevel}set LogLevel(e){this._logLevel=e}GetServiceName(){return o.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;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(e,t){null!=e&&(null==t?console.error(`${this.GetTimeStamp()}[ERROR] ${e}`):console.error(`${this.GetTimeStamp()}[ERROR] [${e}] ${t}`))}Info(t,n){switch(this._logLevel){case e.Info:case e.Debug:break;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){this._logLevel===e.Debug&&(void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.debug(`${this.GetTimeStamp()}[DEBUG] ${t}`):console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n}`)))}Log(e,t){void 0===e||this.IsBlocked(e)||null!=e&&(null==t?console.log(`${this.GetTimeStamp()}[LOG] ${e}`):console.log(`${this.GetTimeStamp()}[LOG] [${e}] ${t}`))}}o.ServiceName="LoggerService";class r{constructor(){this._services={},this._serviceRegistrationEvent=new n}static get Instance(){return null!=r._instance||(r._instance=new r,this.Log=new o,this.Log.Warning("Initializing DependencyContainer"),r._instance.RegisterService(this.Log),this.IsInitialized=!0),r._instance}RegisterService(e){var t;null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Registering new service: ${e.GetServiceName()}`),this._services[e.GetServiceName()]=e}GetService(e){var t;return null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Getting service [${e}] by GetService<T>()`),this._services[e]}GetServiceAsync(e,t){var n,o;return null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service availability [${e}] by GetServiceAsync<T>()`),this._services.hasOwnProperty(e)?(null===(o=r.Log)||void 0===o||o.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,o)=>{var s=t=>{var o;(null==t?void 0:t.GetServiceName())===e&&(null===(o=r.Log)||void 0===o||o.Debug("DependencyContainer",`Got service [${name}] by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(s),n(t))},i=()=>{var e;this._serviceRegistrationEvent.Unsubscribe(s),null==t||t.CancellationEvent.Unsubscribe(i),null===(e=r.Log)||void 0===e||e.Debug("DependencyContainer",`Cancelled service [${name}] retrieval by GetServiceAsync<T>()`),o(new Error("Operation cancelled!"))};null==t||t.CancellationEvent.Subscribe(i),this._serviceRegistrationEvent.Subscribe(s)}))}GetServiceWithTimeoutAsync(e,t){var n,o;return null===(n=r.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service[${e}] availability by GetServiceWithTimeoutAsync<T>()`),this._services.hasOwnProperty(e)?(null===(o=r.Log)||void 0===o||o.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,o)=>{let s=0,i=e=>{var t;(null==e?void 0:e.GetClassName())===e&&(null===(t=r.Log)||void 0===t||t.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),window.clearTimeout(s),this._serviceRegistrationEvent.Unsubscribe(i),n(e))};s=window.setTimeout((()=>{var t;window.clearTimeout(s),this._serviceRegistrationEvent.Unsubscribe(i),null===(t=r.Log)||void 0===t||t.Error("DependencyContainer",`Failed to get service [${e}] in time by GetServiceWithTimeoutAsync<T>()`),o(new Error("Operation cancelled!"))}),t),this._serviceRegistrationEvent.Subscribe(i)}))}}r.IsInitialized=!1;class s{GetServiceName(){return s.ServiceName}GetResourceName(e,t){return`_exalus_${Hu.WorksInContextOf}_${e}_${t}`}Remove(e,t){localStorage.removeItem(this.GetResourceName(e,t))}DropStorage(e){let t=`_exalus_${e}`;for(const e in localStorage)(null==e?void 0:e.startsWith(t))&&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),o=localStorage.getItem(n);return null==o?null:JSON.parse(o)}catch(o){return null===(n=r.Log)||void 0===n||n.Error(s.ServiceName,`Exception has occurred while reading ${this.GetResourceName(e,t)}`),null}}}s.ServiceName="LocalStorageService";const i=[0,2e3,1e4,3e4,null];class a{constructor(e){this._retryDelays=void 0!==e?[...e,null]:i}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class c{}c.Authorization="Authorization",c.Cookie="Cookie";class l{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class u{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class h extends u{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const 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[c.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[c.Authorization]&&delete e.headers[c.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class d extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class f extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class g extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class v extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class y extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class p extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class w extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class m extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var S,_,A,E,C;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(S||(S={}));class b{constructor(){}log(e,t){}}b.instance=new b;class N{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 D{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function T(e,t){let n="";return k(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 k(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function I(e,t,n,o,r,s){const i={},[a,c]=G();i[a]=c,e.log(S.Trace,`(${t} transport) sending data. ${T(r,s.logMessageContent)}.`);const l=k(r)?"arraybuffer":"text",u=await n.post(o,{content:r,headers:{...i,...s.headers},responseType:l,timeout:s.timeout,withCredentials:s.withCredentials});e.log(S.Trace,`(${t} transport) request complete. Response status: ${u.statusCode}.`)}class P{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 R{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${S[e]}: ${t}`;switch(e){case S.Critical:case S.Error:this.out.error(n);break;case S.Warning:this.out.warn(n);break;case S.Information:this.out.info(n);break;default:this.out.log(n)}}}}function G(){let e="X-SignalR-User-Agent";return D.isNode&&(e="User-Agent"),[e,F("7.0.0",O(),D.isNode?"NodeJS":"Browser",x())]}function F(e,t,n,o){let r="Microsoft SignalR/";const s=e.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function O(){if(!D.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function x(){if(D.isNode)return process.versions.node}function M(e){return e.stack?e.stack:e.message?e.message:`${e}`}class $ extends u{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-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!==t.g)return t.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 g;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 g});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(S.Warning,"Timeout from HTTP request."),n=new f}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},k(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(S.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await L(o,"text");throw new d(e||o.statusText,o.status)}const s=L(o,e.responseType),i=await s;return new l(o.status,o.statusText,i)}getCookieString(e){let t="";return D.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function L(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 W extends u{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new g):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&&(k(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new g)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new l(o.status,o.statusText,o.response||o.responseText)):n(new d(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(S.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new d(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(S.Warning,"Timeout from HTTP request."),n(new f)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class B extends u{constructor(e){if(super(),"undefined"!=typeof fetch||D.isNode)this._httpClient=new $(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new W(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new g):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)}}!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(_||(_={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(A||(A={}));class U{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 H{constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new U,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(N.isRequired(e,"url"),N.isRequired(t,"transferFormat"),N.isIn(t,A,"transferFormat"),this._url=e,this._logger.log(S.Trace,"(LongPolling transport) Connecting."),t===A.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=G(),r={[n]:o,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===A.Binary&&(s.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,s);200!==a.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new d(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(S.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new d(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(S.Trace,`(LongPolling transport) data received. ${T(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof f?this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(S.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(S.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?I(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(S.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(S.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=G();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};await this._httpClient.delete(this._url,o),this._logger.log(S.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(S.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(S.Trace,e),this.onclose(this._closeError)}}}class j{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return N.isRequired(e,"url"),N.isRequired(t,"transferFormat"),N.isIn(t,A,"transferFormat"),this._logger.log(S.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,s=!1;if(t===A.Text){if(D.isBrowser||D.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,s]=G();n[o]=s,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(S.Trace,`(SSE transport) data received. ${T(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{s?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(S.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?I(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 z{constructor(e,t,n,o,r,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return N.isRequired(e,"url"),N.isRequired(t,"transferFormat"),N.isIn(t,A,"transferFormat"),this._logger.log(S.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let s;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(D.isNode||D.isReactNative){const t={},[o,r]=G();t[o]=r,n&&(t[c.Authorization]=`Bearer ${n}`),i&&(t[c.Cookie]=i),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===A.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(S.Information,`WebSocket connected to ${e}.`),this._webSocket=s,a=!0,o()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(S.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(S.Trace,`(WebSockets transport) data received. ${T(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(S.Trace,`(WebSockets transport) sending data. ${T(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(S.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class K{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,N.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new R(S.Information):null===n?b.instance:void 0!==n.log?n:new R(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,r=null;if(D.isNode){const e=require;o=e("ws"),r=e("eventsource")}D.isNode||"undefined"==typeof WebSocket||t.WebSocket?D.isNode&&!t.WebSocket&&o&&(t.WebSocket=o):t.WebSocket=WebSocket,D.isNode||"undefined"==typeof EventSource||t.EventSource?D.isNode&&!t.EventSource&&void 0!==r&&(t.EventSource=r):t.EventSource=EventSource,this._httpClient=new h(t.httpClient||new B(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||A.Binary,N.isIn(e,A,"transferFormat"),this._logger.log(S.Debug,`Starting connection with transfer format '${A[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(S.Error,e),await this._stopPromise,Promise.reject(new g(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(S.Error,e),Promise.reject(new g(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new q(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(S.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(S.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==_.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(_.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new g("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof H&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(S.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(S.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=G();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(S.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{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}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof d&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(S.Error,t),Promise.reject(new w(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(S.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const s=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,o);if(i instanceof Error)s.push(`${n.transport} failed:`),s.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(S.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,s.push(new p(`${n.transport} failed: ${e}`,_[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(S.Debug,e),Promise.reject(new g(e))}}}}return s.length>0?Promise.reject(new m(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case _.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new z(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case _.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new j(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case _.LongPolling:return new H(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const o=_[e.transport];if(null==o)return this._logger.log(S.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,o))return this._logger.log(S.Debug,`Skipping transport '${_[o]}' because it was disabled by the client.`),new y(`'${_[o]}' is disabled by the client.`,o);if(!(e.transferFormats.map((e=>A[e])).indexOf(n)>=0))return this._logger.log(S.Debug,`Skipping transport '${_[o]}' because it does not support the requested transfer format '${A[n]}'.`),new Error(`'${_[o]}' does not support ${A[n]}.`);if(o===_.WebSockets&&!this._options.WebSocket||o===_.ServerSentEvents&&!this._options.EventSource)return this._logger.log(S.Debug,`Skipping transport '${_[o]}' because it is not supported in your environment.'`),new v(`'${_[o]}' is not supported in your environment.`,o);this._logger.log(S.Debug,`Selecting transport '${_[o]}'.`);try{return this._constructTransport(o)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(S.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(S.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(S.Error,`Connection disconnected with error '${e}'.`):this._logger.log(S.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(S.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(S.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(S.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(!D.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(S.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}class q{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new V,this._transportResult=new V,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new V),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 V;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):q._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class V{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class J{static write(e){return`${e}${J.RecordSeparator}`}static parse(e){if(e[e.length-1]!==J.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(J.RecordSeparator);return t.pop(),t}}J.RecordSeparatorCode=30,J.RecordSeparator=String.fromCharCode(J.RecordSeparatorCode);class Y{writeHandshakeRequest(e){return J.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(k(e)){const o=new Uint8Array(e),r=o.indexOf(J.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,s))),n=o.byteLength>s?o.slice(s).buffer:null}else{const o=e,r=o.indexOf(J.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=o.substring(0,s),n=o.length>s?o.substring(s):null}const o=J.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}!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={}));class X{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 P(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(C||(C={}));class Q{constructor(e,t,n,o){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(S.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},N.isRequired(e,"connection"),N.isRequired(t,"logger"),N.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new Y,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=C.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:E.Ping})}static create(e,t,n,o){return new Q(e,t,n,o)}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!==C.Disconnected&&this._connectionState!==C.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!==C.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=C.Connecting,this._logger.log(S.Debug,"Starting HubConnection.");try{await this._startInternal(),D.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=C.Connected,this._connectionStarted=!0,this._logger.log(S.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=C.Disconnected,this._logger.log(S.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(S.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(S.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(S.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){return this._connectionState===C.Disconnected?(this._logger.log(S.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===C.Disconnecting?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=C.Disconnecting,this._logger.log(S.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(S.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new g("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let s;const i=new X;return i.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===E.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},s=this._sendWithProtocol(r).catch((e=>{i.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,s),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===E.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}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 o=n.indexOf(t);-1!==o&&(n.splice(o,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)switch(e.type){case E.Invocation:this._invokeClientMethod(e);break;case E.StreamItem:case E.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===E.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(S.Error,`Stream callback threw error: ${M(e)}`)}}break}case E.Ping:break;case E.Close:{this._logger.log(S.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(S.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(S.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(S.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(S.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===C.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(S.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let s,i,a;for(const n of o)try{const o=s;s=await n.apply(this,e.arguments),r&&s&&o&&(this._logger.log(S.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(S.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==s?a=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):s&&this._logger.log(S.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(S.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new g("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===C.Disconnecting?this._completeClose(e):this._connectionState===C.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===C.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=C.Disconnected,this._connectionStarted=!1,D.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(S.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=C.Reconnecting,e?this._logger.log(S.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(S.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==C.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(S.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==C.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=C.Connected,this._logger.log(S.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(S.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(S.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==C.Reconnecting)return this._logger.log(S.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===C.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(S.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(S.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(S.Error,`Stream 'error' callback called with '${e}' threw error: ${M(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:E.Invocation}:{arguments:t,target:e,type:E.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:E.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:E.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 o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o<e.length;o++){const r=e[o];if(this._isObservable(r)){const s=this._invocationId;this._invocationId++,t[s]=r,n.push(s.toString()),e.splice(o,1)}}return[t,n]}_isObservable(e){return e&&e.subscribe&&"function"==typeof e.subscribe}_createStreamInvocation(e,t,n){const o=this._invocationId;return this._invocationId++,0!==n.length?{arguments:t,invocationId:o.toString(),streamIds:n,target:e,type:E.StreamInvocation}:{arguments:t,invocationId:o.toString(),target:e,type:E.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:E.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:E.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:E.Completion}:{invocationId:e,result:n,type:E.Completion}}}class Z{constructor(){this.name="json",this.version=1,this.transferFormat=A.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=b.instance);const n=J.parse(e),o=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case E.Invocation:this._isInvocationMessage(n);break;case E.StreamItem:this._isStreamItemMessage(n);break;case E.Completion:this._isCompletionMessage(n);break;case E.Ping:case E.Close:break;default:t.log(S.Information,"Unknown message type '"+n.type+"' ignored.");continue}o.push(n)}return o}writeMessage(e){return J.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.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const ee={trace:S.Trace,debug:S.Debug,info:S.Information,information:S.Information,warn:S.Warning,warning:S.Warning,error:S.Error,critical:S.Critical,none:S.None};class te{configureLogging(e){if(N.isRequired(e,"logging"),void 0!==e.log)this.logger=e;else if("string"==typeof e){const t=function(e){const t=ee[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new R(t)}else this.logger=new R(e);return this}withUrl(e,t){return N.isRequired(e,"url"),N.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return N.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 a(e):this.reconnectPolicy=e:this.reconnectPolicy=new a,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 K(this.url,e);return Q.create(t,this.logger||b.instance,this.protocol||new Z,this.reconnectPolicy)}}class ne{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 o=16*Math.random();return e>0?(o=(e+o)%16|0,e=Math.floor(e/16)):(o=(t+o)%16|0,t=Math.floor(t/16)),("x"===n?o:3&o|8).toString(16)}))}}class oe{constructor(){this.TransactionId=ne.GenerateUUID()}}var re,se,ie,ae,ce,le,ue,he,de,fe,ge,ve;(fe=re||(re={}))[fe.OK=0]="OK",fe[fe.UnknownError=1]="UnknownError",fe[fe.FatalError=2]="FatalError",fe[fe.WrongData=3]="WrongData",fe[fe.ResourceDoesNotExists=4]="ResourceDoesNotExists",fe[fe.NoPermissionToPerformThisOperation=5]="NoPermissionToPerformThisOperation",fe[fe.SessionHasAlreadyLoggedOnUser=6]="SessionHasAlreadyLoggedOnUser",fe[fe.OperationNotPermitted=7]="OperationNotPermitted",fe[fe.NoPermissionsToCallGivenResource=8]="NoPermissionsToCallGivenResource",fe[fe.ResourceIsNotAvailable=9]="ResourceIsNotAvailable",fe[fe.Error=10]="Error",fe[fe.NoData=11]="NoData",fe[fe.NotSupportedMethod=12]="NotSupportedMethod",fe[fe.UserIsNotLoggedIn=13]="UserIsNotLoggedIn",fe[fe.MultiDataResponseStart=14]="MultiDataResponseStart",fe[fe.MultiDataResponse=15]="MultiDataResponse",fe[fe.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"}(se||(se={}));class ye{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"}(ie||(ie={})),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"}(ae||(ae={})),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"}(ce||(ce={}));class pe{constructor(){this._log=Hu.Get(o.ServiceName),this.handlers=[]}Subscribe(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)}}))}}(ve=le||(le={}))[ve.Any=0]="Any",ve[ve.Guest=10]="Guest",ve[ve.Standard=20]="Standard",ve[ve.Admin=30]="Admin",ve[ve.Installator=40]="Installator",ve[ve.Support=50]="Support",(ge=ue||(ue={}))[ge.Unknown=0]="Unknown",ge[ge.Men=1]="Men",ge[ge.Woman=2]="Woman",ge[ge.Other=3]="Other",function(e){e[e.En_Us=0]="En_Us",e[e.Pl_Pl=1]="Pl_Pl"}(he||(he={})),function(e){e[e.Unknown=0]="Unknown",e[e.WrongAuthData=1]="WrongAuthData",e[e.NoResponseFromController=2]="NoResponseFromController"}(de||(de={}));class we{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=ue.Unknown,this._accessLevel=le.Any,this._localization=he.En_Us}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}}var me=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Se{constructor(){this._onUserLoggedInEvent=new n,this._onUserLoggedOutEvent=new n,this._email="",this._password="",this._loginTaskCompletionSource=this.CreateSessionCompletionSourceAsync(),this._alreadySubsribedToNetworkEvents=!1,this._user=null}CreateSessionCompletionSourceAsync(){var e;return me(this,void 0,void 0,(function*(){null===(e=r.Log)||void 0===e||e.Debug(Se.ServiceName,"Creating _loginTaskCompletionSource"),this._loginTaskCompletionSource=new Promise((e=>{let t=n=>{var o;null===(o=r.Log)||void 0===o||o.Debug(Se.ServiceName,`Logged in as ${n.Name}, completing CreateSessionCompletionSourceAsync()`),e(),this.OnUserLoggedInEvent().Unsubscribe(t)};this.OnUserLoggedInEvent().Subscribe(t)}))}))}Subscribe(e){}RestoreSessionAsync(){var e;return me(this,void 0,void 0,(function*(){null===(e=r.Log)||void 0===e||e.Debug(Se.ServiceName,`Creating RestoreSessionAsync ${this._email} ${this._password}`),void 0!==this._user&&null!==this._user&&(yield this.UserLogInAsync(this._email,this._password))}))}WaitForSessionCreationAsync(){return me(this,void 0,void 0,(function*(){return this._loginTaskCompletionSource}))}OnUserLoggedInEvent(){return this._onUserLoggedInEvent}OnUserLoggedOutEvent(){return this._onUserLoggedOutEvent}get User(){return this._user}UserLogOutAsync(){var e,t;return me(this,void 0,void 0,(function*(){var n=new oe;n.Resource="/users/user/logout",n.Method=se.Put,this._email="",this._password="",(yield Hu.Get(Ie.ServiceName).SendAndWaitForResponseAsync(n,2e4,!1)).Status==re.OK?(this._onUserLoggedOutEvent.Invoke(this._user),null===(e=r.Log)||void 0===e||e.Debug(Se.ServiceName,"User has been logged out.")):null===(t=r.Log)||void 0===t||t.Debug(Se.ServiceName,"Failed to logout user!")}))}OnConnectionStateChanged(e){return me(this,void 0,void 0,(function*(){switch(e){case ce.Disconnected:case ce.Failed:break;case ce.Connected:Hu.Get(Se.ServiceName).RestoreSessionAsync()}}))}UserLogInAsync(e,t){var n,o;return me(this,void 0,void 0,(function*(){var s=Hu.Get(Ie.ServiceName);const i=yield s.SendAndWaitForResponseAsync(new Ae(e,t),2e4,!1);if(i.Status==re.OK&&null!=i.Data){this._email=e,this._password=t;var a=new we;return this._user=a,a.AccessLevel=i.Data.AccessLevel,a.Email=i.Data.Email,a.Gender=i.Data.Gender,a.Guid=i.Data.Guid,a.IsAccountOnline=i.Data.IsAccountOnline,a.Name=i.Data.Name,a.IsActive=i.Data.IsActive,a.IsBanned=i.Data.IsBanned,a.Phone=i.Data.Phone,a.Surname=i.Data.Surname,this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,s.OnConnectionStateChangedEvent().Subscribe(this.OnConnectionStateChanged)),null===(n=r.Log)||void 0===n||n.Debug(Se.ServiceName,`Did logging in succeded?: ${i.Status==re.OK}`),this._onUserLoggedInEvent.Invoke(this._user),a}return null===(o=r.Log)||void 0===o||o.Debug(Se.ServiceName,`User login response: ${i.Data}`),de.WrongAuthData}))}GetServiceName(){return Se.ServiceName}}Se.ServiceName="SessionService";class _e{constructor(e,t){this.Email="",this.Password="",this.Email=e,this.Password=t}}class Ae extends oe{constructor(e,t){super(),this.Data=new _e(e,t),this.Resource="/users/user/login",this.Method=se.Put}}var Ee=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Ce{constructor(){this._connection=null,this._session=null,this._localStorage=null,this._onEnteredConfigurationEvent=new pe,this._onExitedConfigurationEvent=new pe,this._onConfigurationTimeCheckedEvent=new n,this._configurationTime=new Date,this._appEnteredConfigurationMode=!1,this._didConfigurationChange=!1,this._synchronizationTaskCompletionSource=new Promise((e=>{Hu.Get(Se.ServiceName).OnUserLoggedInEvent().Subscribe((t=>Ee(this,void 0,void 0,(function*(){this._didConfigurationChange=yield this.CheckIfConfigurationHasChangedAsync(),e()}))))})),this._connection=Hu.Get(Ie.ServiceName),this._session=Hu.Get(Se.ServiceName),this._localStorage=Hu.Get(s.ServiceName),this._connection.OnDataReceivedEvent().Subscribe((e=>{"/info/configuration/mode/entry"==e.Resource?this._appEnteredConfigurationMode||this._onEnteredConfigurationEvent.Invoke():"/info/configuration/mode/exit"==e.Resource&&(this._appEnteredConfigurationMode||this._onExitedConfigurationEvent.Invoke())}))}GetServiceName(){return Ce.ServiceName}DidCofigurationChangeAsync(){return Ee(this,void 0,void 0,(function*(){return yield this._synchronizationTaskCompletionSource,Promise.resolve(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(){var e;return Ee(this,void 0,void 0,(function*(){this._appEnteredConfigurationMode=!0,yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new be,2e4,!1)}))}ExitConfigurationModeAsync(){var e;return Ee(this,void 0,void 0,(function*(){yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ne,2e4,!1),this._appEnteredConfigurationMode=!1}))}OnEnteredConfigurationEvent(){return this._onEnteredConfigurationEvent}OnExitedConfigurationEvent(){return this._onExitedConfigurationEvent}OnConfigurationTimeCheckedEvent(){return this._onConfigurationTimeCheckedEvent}GetLastConfigurationChangeTimeAsync(){var e;return Ee(this,void 0,void 0,(function*(){const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new De,2e4,!1);if(null==t||(null==t?void 0:t.Status)!=re.OK)throw new Error("Failed to get last configuration change time");return this._configurationTime=new Date(t.Data),this._configurationTime}))}CheckIfConfigurationHasChangedAsync(){return Ee(this,void 0,void 0,(function*(){const e=yield this.GetLastConfigurationChangeTimeAsync();return this.GetLastKnownConfigurationChangeTime().toString()!=e.toString()&&(this.SaveLastConfigurationChangeTime(e),this._onConfigurationTimeCheckedEvent.Invoke(e),!0)}))}}Ce.ServiceName="ControllerConfigurationService";class be extends oe{constructor(){super(),this.Resource="/system/configuration/mode/entry",this.Method=se.Put}}class Ne extends oe{constructor(){super(),this.Resource="/system/configuration/mode/exit",this.Method=se.Put}}class De extends oe{constructor(){super(),this.Resource="/system/configuration/change/time",this.Method=se.Get}}class Te{constructor(){this._log=Hu.Get(o.ServiceName),Te._localStorageService=Hu.Get(s.ServiceName)}GetServiceName(){return Te.ServiceName}GetResourceName(e){return`${e.Resource}_${e.Method}`}Cache(e){var t;e.Status===re.OK&&(this._log.Debug(Te.ServiceName,`Caching request: ${e.Resource} ${e.Method}`),null===(t=Te._localStorageService)||void 0===t||t.Save(this.GetServiceName(),this.GetResourceName(e),e))}GetCache(e){var t;let n=null===(t=Te._localStorageService)||void 0===t?void 0:t.Read(this.GetServiceName(),this.GetResourceName(e));return null!=n&&this._log.Debug(Te.ServiceName,`Got request response from cache: ${e.Resource} ${e.Method}`),n}ClearCache(){var e;null===(e=Te._localStorageService)||void 0===e||e.DropStorage(this.GetServiceName()),this._log.Debug(Te.ServiceName,`Clearing cache for ${this.GetServiceName()}`)}Remove(e){var t;null===(t=Te._localStorageService)||void 0===t||t.Remove(this.GetServiceName(),this.GetResourceName(e)),this._log.Debug(Te.ServiceName,`Clearing cache for cache: ${e.Resource} ${e.Method}`)}}Te._localStorageService=null,Te.ServiceName="WebApiCacheService";var ke=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Ie{constructor(){this._logPackets=!1,this._disconnectedOnPurpose=!1,this._defaultPacketsBrokerAddress="br1.tr7.pl",this._serversBrokerAddress="https://broker.tr7.pl",this._address="br1.tr7.pl",this._isEstabilished=!1,this._timeout=1e4,this._dataReceivedEvent=new n,this._pongReceivedEvent=new pe,this._authorizationReceivedEvent=new n,this._registrationReceivedEvent=new n,this._connectionStateChangedEvent=new n,this._errorOccuredEvent=new n,this._log=Hu.Get(o.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._packetsBrokerServers=["br1.tr7.pl","br1.exala.pl"]}GetServiceName(){return Ie.ServiceName}EnablePacketsLogging(){this._logPackets=!0}DisablePacketsLogging(){this._logPackets=!1}InitializeConnection(){if(this._controllerConfiguration=Hu.Get(Ce.ServiceName),this._cache=Hu.Get(Te.ServiceName),this._session=Hu.Get(Se.ServiceName),this._connection){try{this._connection.stop()}catch(e){}this._connection=void 0}if(!this._address)throw new Error("Domain is not set");if(!this._serialId)throw new Error("SerialId is not set");if(!this._PIN)throw new Error("PIN is not set");this._connection=(new te).withUrl(`https://${this._address}/broker`).build()}SetServersBrokerAddress(e){this._serversBrokerAddress=e}SetDefaultPacketsBrokerAddress(e){this._defaultPacketsBrokerAddress=e,this._address=e}GetServerAddressAsync(){return ke(this,void 0,void 0,(function*(){try{let e=yield fetch(`${this._serversBrokerAddress}/api/connections/broker/whichserver/${this._serialId}`);if(e.ok){let t=yield e.text();return t?(this._log.Debug(Ie.ServiceName,`Got server address: ${t}`),t):(this._log.Error(Ie.ServiceName,`Failed to get server address, status: ${e.status}`),null)}return this._log.Error(Ie.ServiceName,`Failed to get server address, status: ${e.status}`),null}catch(e){return this._log.Error(Ie.ServiceName,e),null}}))}ConnectAsync(e){return ke(this,void 0,void 0,(function*(){return this._address=e,yield this.connectAsync()}))}AuthorizeAsync(e){return new Promise(((t,n)=>ke(this,void 0,void 0,(function*(){var n;let o=0,r=e=>{window.clearTimeout(o),this._authorizationReceivedEvent.Unsubscribe(r),this._log.Debug(Ie.ServiceName,`Got authorization result: ${e}`),t(e)};o=window.setTimeout((()=>{window.clearTimeout(o),this._authorizationReceivedEvent.Unsubscribe(r),t(!1)}),2e3),this._log.Debug(Ie.ServiceName,`Authorizing to cloud using: ${e.SerialNumber} PIN: ${e.PIN}`),this._authorizationReceivedEvent.Subscribe(r),yield null===(n=this._connection)||void 0===n?void 0:n.send("AuthorizeTo",e.SerialNumber,e.PIN)}))))}ConnectAndAuthorizeAsync(e){return ke(this,void 0,void 0,(function*(){Hu.WorksInContextOf=e.SerialNumber,this._serialId=e.SerialNumber,this._PIN=e.PIN;var t=yield this.GetServerAddressAsync();if(t&&null!=t){this._log.Debug(Ie.ServiceName,`Got packets broker address: ${t}`),this.SetDefaultPacketsBrokerAddress(t);let n=yield this.connectAsync();return n!=ae.Connected?n:(yield this.AuthorizeAsync(e))?ae.Connected:ae.AuthorizationFailed}{let t=ae.ControllerIsNotConnected;this._log.Warning(Ie.ServiceName,"Server did not return packets broker address, trying to connect to known brokers.");for(let n of this._packetsBrokerServers){this._log.Warning(Ie.ServiceName,`Testing connection to ${n}`),this.SetDefaultPacketsBrokerAddress(n);try{yield this.DisconnectAsync()}catch(e){}this._log.Warning(Ie.ServiceName,`Connecting to server: ${n}`);let o=yield this.connectAsync();if(this._log.Warning(Ie.ServiceName,`Connection result: ${o}`),o==ae.Connected){if(yield this.AuthorizeAsync(e))return t=ae.Connected,t;this._log.Warning(Ie.ServiceName,`Failed to authorize in ${n}`)}}return t}}))}connectAsync(){var e,t,n,o,r,s,i,a,c;return ke(this,void 0,void 0,(function*(){if(ae.FailedToConnect,!this._address)return Promise.resolve(ae.ControllerIsNotConnected);this._disconnectedOnPurpose&&(this._disconnectedOnPurpose=!1),this._connectionStateChangedEvent,this.InitializeConnection(),null===(e=this._connection)||void 0===e||e.onclose((()=>ke(this,void 0,void 0,(function*(){var e,t;if(this._log.Error(Ie.ServiceName,"Connection closed"),Hu.Get(Se.ServiceName).CreateSessionCompletionSourceAsync(),this.FireConnectionStateChanged(),(null===(e=this._connection)||void 0===e?void 0:e.state)===C.Disconnected&&!this._disconnectedOnPurpose)return yield null===(t=this._connection)||void 0===t?void 0:t.start(),null!=this._connection?(yield this.AuthorizeAsync(new ye(this._serialId,this._PIN)),this._log.Info(Ie.ServiceName,"Reconnected from onClose"),this.FireConnectionStateChanged()):ae.FailedToConnect})))),null===(t=this._connection)||void 0===t||t.onreconnected((()=>ke(this,void 0,void 0,(function*(){return yield this.AuthorizeAsync(new ye(this._serialId,this._PIN)),this._log.Info(Ie.ServiceName,"Reconnected from onreconnected"),this.FireConnectionStateChanged()})))),null===(n=this._connection)||void 0===n||n.onreconnecting((()=>(this._log.Warning(Ie.ServiceName,"Reconnecting..."),this.FireConnectionStateChanged()))),yield null===(o=this._connection)||void 0===o?void 0:o.start(),null===(r=this._connection)||void 0===r||r.on("Pong",(()=>{this._log.Debug(Ie.ServiceName,"Pong received <-"),this._pongReceivedEvent.Invoke()})),null===(s=this._connection)||void 0===s||s.on("Registration",(e=>{var t;null===(t=this._registrationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(i=this._connection)||void 0===i||i.on("Authorization",(e=>{var t;null===(t=this._authorizationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(a=this._connection)||void 0===a||a.on("SendError",((e,t)=>ke(this,void 0,void 0,(function*(){e.startsWith("NotAuthorized:")?(this._log.Error(Ie.ServiceName,"Failed to authorize!"),yield this.AuthorizeAsync(new ye(this._serialId,this._PIN))):(this._log.Error(Ie.ServiceName,`Server returned error: ${e} ${t}`),this._errorOccuredEvent.Invoke([e,t]))}))));let l=this._dataReceivedEvent;return null===(c=this._connection)||void 0===c||c.on("Data",((e,t)=>{const n=JSON.parse(t);this._logPackets&&this._log.Debug(Ie.ServiceName,`Received data:\n${JSON.stringify(n,null,2)}`),l.Invoke(n)})),null!=this._connection?this.FireConnectionStateChanged():ae.FailedToConnect}))}FireConnectionStateChanged(){var e;const t=this._connectionStateChangedEvent;switch(null===(e=this._connection)||void 0===e?void 0:e.state){case C.Connected:return t.Invoke(ce.Connected),ae.Connected;case C.Connecting:return t.Invoke(ce.Connecting),ae.Connected;case C.Disconnected:return t.Invoke(ce.Disconnected),ae.FailedToConnect;case C.Disconnecting:return t.Invoke(ce.Disconnecting),ae.FailedToConnect;case C.Reconnecting:return t.Invoke(ce.Reconnecting),ae.FailedToConnect}return ae.FailedToConnect}DisconnectAsync(){var e;return ke(this,void 0,void 0,(function*(){this._disconnectedOnPurpose=!0,yield null===(e=this._connection)||void 0===e?void 0:e.stop()}))}IsConnected(){var e;return(null===(e=this._connection)||void 0===e?void 0:e.state)===C.Connected}SendAndWaitForResponseAsync(e,t,n,o=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,o)}SendAndWaitForResponseWithRepeatAsync(e,t,n,o=!0,r=!0){var s,i,a;return ke(this,void 0,void 0,(function*(){if(e.Method===se.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 l=Date.now();if(!this.IsConnected())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)=>ke(this,void 0,void 0,(function*(){let a=i=>ke(this,void 0,void 0,(function*(){var u,h;if((null==i?void 0:i.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const d=Date.now()-l;r&&this._log.Debug(Ie.ServiceName,`Received response for: ${null==i?void 0:i.Resource} ${null==i?void 0:i.Method} id: ${null==i?void 0:i.TransactionId} in ${d}ms`),e.Method===se.Get&&n&&(null===(u=this._cache)||void 0===u||u.Cache(i)),!n&&(null==i?void 0:i.Status)===re.UserIsNotLoggedIn&&o&&(yield null===(h=this._session)||void 0===h?void 0:h.RestoreSessionAsync(),s(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,r))),s(i)}}));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(Ie.ServiceName,t),i(new f(t))}),t),!(yield this.SendAsync(e,r))){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;i(new Error(t))}}))))}))}SendAsync(e,t=!1){if(!this.IsConnected())throw new Error("Connection is not established");return new Promise((n=>{var o;this._logPackets?this._log.Debug(Ie.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId} data:\n${JSON.stringify(e,null,2)}`):t&&this._log.Debug(Ie.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId}`),null===(o=this._connection)||void 0===o||o.invoke("SendTo",this._serialId,e).then((()=>{n(!0)})).catch((e=>{this._log.Error(Ie.ServiceName,`${e}`),n(!1)}))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}}Ie.ServiceName="ExalusConnectionService";var Pe,Re,Ge,Fe,Oe,xe,Me,$e,Le,We,Be,Ue,He,je,ze,Ke,qe,Ve,Je,Ye,Xe,Qe,Ze,et,tt,nt,ot,rt,st,it,at,ct,lt,ut,ht,dt,ft,gt;class vt{constructor(){this._connection=null,this._connection=Hu.Get(Ie.ServiceName)}GetServiceName(){return vt.ServiceName}GetUsersAsync(){var e,t,n,o,s,i;return n=this,o=void 0,i=function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new yt,2e4,!1);if(null==n)return Promise.resolve([]);if((null==n?void 0:n.Status)==re.OK){if(null!=n.Data){const e=[];return n.Data.forEach((t=>{var n=new we;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)==re.NoData)return Promise.resolve([]);throw null===(t=r.Log)||void 0===t||t.Debug(vt.ServiceName,`Failed to retrieve users, error: ${n.Status}`),new Error(`Failed to retrieve users, error: ${n.Status}`)},new((s=void 0)||(s=Promise))((function(e,t){function r(e){try{c(i.next(e))}catch(e){t(e)}}function a(e){try{c(i.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s((function(e){e(n)}))).then(r,a)}c((i=i.apply(n,o||[])).next())}))}GetUserAsync(e){return new Promise(((e,t)=>{e(null)}))}CreateUserAsync(e){return new Promise(((t,n)=>{t(e)}))}UpdateUserAsync(e){return new Promise(((t,n)=>{t(e)}))}DeleteUserAsync(e){return new Promise(((e,t)=>{e()}))}}vt.ServiceName="UsersService";class yt extends oe{constructor(){super(),this.Resource="/users/list",this.Method=se.Get}}!function(e){e[e.NoTasksExecuting=0]="NoTasksExecuting",e[e.ExecutingTasks=1]="ExecutingTasks"}(Pe||(Pe={})),(lt=Re||(Re={}))[lt.Default=0]="Default",lt[lt.Monostable=1]="Monostable",lt[lt.Bistable=2]="Bistable",lt[lt.Gate=3]="Gate",lt[lt.Gateway=4]="Gateway";class pt{constructor(){this._type=Ge.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}(ut=Ge||(Ge={})).Unknown="Unknown",ut.SetBlindPosition="IBlindPosition",ut.SetBlindPositionSimple="IBlindPositionSimple",ut.SetBlindMicroventilation="IMicroventilation",ut.TurnOff="IChannelOff",ut.TurnOn="IChannelOn",ut.TogleState="IChannelSwitchState",ut.SetLightBrightnessDynamicly="IDynamicLightBrightness",ut.SetLightBrightness="ILightBrightness",ut.SetLightColor="ILightColor",ut.SetLightTemperature="ILightTemperature",ut.PairDevice="IPair",ut.UnpairDevice="IUnpair",ut.IdentifyDevice="IIdentifyDevice",ut.GetChannelsState="IGetDeviceState",ut.GetPowerMeasurements="IGetPowerMeasurements",ut.GetAvailableData="IGetAvailableData",ut.MultipleDataRequest="IMultipleDataRequest",ut.SetBlindOpenCloseTime="ISetBlindOpenCloseTime",ut.SetTemperature="IChangeTemperature",ut.ChangeGatePositionPulse="IGatePulse",ut.ChangeGatewayPositionPulse="IGatewayPulse",ut.SetFacadePosition="IFacadePosition";class wt{constructor(){this._type=Fe.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.MeasuredBrightness="IBrightness",e.RemoteButtonState="IButtonState",e.ChannelOnOffState="IChannelOnOff",e.DoorBellState="IDoorBell",e.FacadeRemoteButtonState="IFacadeControlButton",e.FacadePosition="IFacadeState",e.FloodSensorState="IFloodSensor",e.GatePosition="IGatePosition",e.GatewayPosition="IGatewayPosition",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.ReedPosition="IReedPosition",e.SignalStrength="ISignalStrength",e.SmokeSensorState="ISmokeSensor",e.MeasuredTemperature="ITemperature",e.VibrationSensorState="IVibrationSensor",e.MeasuredWindSpeed="IWindSpeed",e.WindTreshold="IWindTreshold",e.MeasuredEnergy="IEnergy",e.MeasuredDistance="DistanceSensor",e.BlindCalibration="BlindCalibration",e.ConfigurationState="ConfigurationState",e.CurrentWindThreshold="CurrentWindThreshold",e.WindSpeedState="WindSpeed"}(Fe||(Fe={})),(ft=Oe||(Oe={}))[ft.NotResponding=0]="NotResponding",ft[ft.Working=1]="Working",ft[ft.Broken=2]="Broken",ft[ft.FirmareUpgradeMode=3]="FirmareUpgradeMode",(dt=xe||(xe={}))[dt.TwoWay=1]="TwoWay",dt[dt.OneWay=2]="OneWay",dt[dt.ConditionalTwoWay=3]="ConditionalTwoWay",(ht=Me||(Me={}))[ht.Unknown=-1]="Unknown",ht[ht.Multipurpose=0]="Multipurpose",ht[ht.Controller=1]="Controller",ht[ht.Driver=2]="Driver",ht[ht.Receiver=3]="Receiver",ht[ht.Remote=4]="Remote",ht[ht.Sensor=5]="Sensor",ht[ht.Scene=6]="Scene";class mt{constructor(){this.DeviceGuid="",this.Channel=0,this.Status=Pe.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"}($e||($e={})),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"}(Le||(Le={}));class St{constructor(){this.Device=null,this.Channel=0,this.Task=null,this.Result=Le.Unknown}}class _t{constructor(){this._type="",this._data=null,this._typeAsEnum=Fe.Unknown}get Data(){return this._data}set Data(e){this._data=e}get Type(){return this._type}set Type(e){this._type=e}get TypeAsEnum(){return this._typeAsEnum}set TypeAsEnum(e){this._typeAsEnum=e}}(gt=We||(We={}))[gt.Confident=0]="Confident",gt[gt.Unconfident=1]="Unconfident";class At extends _t{constructor(e){super(),this.TypeAsEnum=Fe.ChannelOnOffState,this.Type="ChannelOnOffState",this.Data=e.state}}!function(e){e[e.On=0]="On",e[e.Off=1]="Off",e[e.Unknown=2]="Unknown"}(Be||(Be={}));class Et extends _t{constructor(e){super(),this.TypeAsEnum=Fe.DoorBellState,this.Type="DoorBellState",this.Data=e.state}}!function(e){e[e.Pressed=0]="Pressed",e[e.Relased=1]="Relased",e[e.PressedAndRelased=2]="PressedAndRelased"}(Ue||(Ue={}));class Ct extends _t{constructor(e){super(),this.TypeAsEnum=Fe.ReedPosition,this.Type="ReedPostionState",this.Data=e.state}}class bt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.BlindPosition,this.Type="BlindPostionState",this.Data=e.state}GetBlindStatus(){switch(this.Data.Position){case 200:return He.UnableToMove;case 201:return He.MotorOverheatedPleaseWait;default:return He.Working}}}!function(e){e[e.Unknown=0]="Unknown",e[e.Working=1]="Working",e[e.UnableToMove=200]="UnableToMove",e[e.MotorOverheatedPleaseWait=201]="MotorOverheatedPleaseWait"}(He||(He={}));class Nt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.RemoteButtonState,this.Type="RemoteButtonState",this.Data=e.state}}!function(e){e[e.Pressed=1]="Pressed",e[e.Relased=2]="Relased",e[e.PressedAndRelased=3]="PressedAndRelased"}(je||(je={}));class Dt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.LightColor,this.Type="LightColorState",this.Data=e.state}}class Tt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.LightWarmth,this.Type="LightWarmthState",this.Data=e.state}}class kt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.LightBrightness,this.Type="LightBrightnessState",this.Data=e.state}}class It extends _t{constructor(e){super(),this.TypeAsEnum=Fe.MeasuredTemperature,this.Type="MeasuredTemperatureState",this.Data=e.state}}!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"}(ze||(ze={}));class Pt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.BatteryState,this.Type="BatteryState",this.Data=e.state}}!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"}(Ke||(Ke={}));class Rt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.MeasuredBrightness,this.Type="MeasuredBrightnessState",this.Data=e.state}}class Gt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.MeasuredEnergy,this.Type="MeasuredEnergyState",this.Data=e.state}}class Ft extends _t{constructor(e){super(),this.TypeAsEnum=Fe.MeasuredDistance,this.Type="MeasuredDistanceState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(qe||(qe={}));class Ot extends _t{constructor(e){super(),this.TypeAsEnum=Fe.MovementSensorState,this.Type="MovementSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(Ve||(Ve={}));class xt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.BlindRemoteButtonState,this.Type="BlindRemoteButtonState",this.Data=e.state}}!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"}(Je||(Je={}));class Mt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.FacadeRemoteButtonState,this.Type="FacadeRemoteButtonState",this.Data=e.state}}!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"}(Ye||(Ye={}));class $t extends _t{constructor(e){super(),this.TypeAsEnum=Fe.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"}(Xe||(Xe={}));class Lt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.GatePosition,this.Type="GatePositionState",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"}(Qe||(Qe={}));class Wt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.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"}(Ze||(Ze={}));class Bt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.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"}(et||(et={}));class Ut extends _t{constructor(e){super(),this.TypeAsEnum=Fe.HumiditySensorState,this.Type="HumiditySensorState",this.Data=e.state}}!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"}(tt||(tt={}));class Ht extends _t{constructor(e){super(),this.TypeAsEnum=Fe.VibrationSensorState,this.Type="VibrationSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(nt||(nt={}));class jt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.BinarySensorState,this.Type="BinarySensorState",this.Data=e.state}}!function(e){e[e.High=1]="High",e[e.Low=0]="Low"}(ot||(ot={}));class zt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.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"}(rt||(rt={}));class Kt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.BlindOpenCloseTime,this.Type="BlindOpenCloseTimeState",this.Data=e.state}}class qt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.OvercurrentProtectionState,this.Type="OvercurrentProtectionState",this.Data=e.state}}class Vt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.OvercurrentProtectionThreshold,this.Type="OvercurrentProtectionThresholdState",this.Data=e.state}}class Jt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.FacadePosition,this.Type="FacadePositionState",this.Data=e.state}}class Yt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.CurrentWindThreshold,this.Type="CurrentWindThresholdState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded",e[e.Inactive=3]="Inactive"}(st||(st={}));class Xt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.CurrentWindThreshold,this.Type="CurrentLightThresholdState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded"}(it||(it={}));class Qt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.WindSpeedState,this.Type="WindSpeedState",this.Data=e.state}}class Zt extends _t{constructor(e){super(),this.TypeAsEnum=Fe.FloodSensorState,this.Type="FloodSensorState",this.Data=e.state}}!function(e){e[e.FloodDetected=1]="FloodDetected",e[e.NoFloodDetected=0]="NoFloodDetected"}(at||(at={}));class en{constructor(e,t){this._type=ct.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 tn{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.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"}(ct||(ct={}));class nn{constructor(){this._onDeviceStateChangedEvent=new n,this._onDeviceTasksExecutionChangedOnChannelsEvent=new n,this._serialNumber=null,this._model=null,this._modelGuid=null,this._manufacturerGuid=null,this._isVirtual=!1,this._isEnabled=!1,this._deviceState=Oe.Working,this._deviceType=Me.Unknown,this._communicationWay=xe.OneWay,this._availableTasksTypes=[],this._availableResponseTypes=[],this._channels=[];const e=Hu.Get(yn.ServiceName),t=this._onDeviceStateChangedEvent,o=this._onDeviceTasksExecutionChangedOnChannelsEvent;e.OnDeviceStateChangedEvent().Subscribe((e=>{e.Device.Guid==this._guid&&t.Invoke(e.State)})),e.OnDevicesTasksExecutionChangeEvent().Subscribe((e=>{o.Invoke(e.filter((e=>e.DeviceGuid==this._guid)).map((e=>e.Channel)))}))}RemoveDeviceAsync(){return Hu.Get(yn.ServiceName).RemoveDeviceAsync(this)}ExecuteDeviceTaskAsync(e){return Hu.Get(yn.ServiceName).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 Name(){return null==this._name?"":this._name}set Name(e){this._name=e}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}ChangeDeviceNameAsync(e){return t=this,n=void 0,r=function*(){try{const t=yield Hu.Get(Ie.ServiceName).SendAndWaitForResponseAsync(new on(this,e),2e4,!1);switch(t.Status){case re.OK:return new en(ct.Changed,"");case re.WrongData:if("DeviceNotFound"==t.Data)return new en(ct.Failed,"DeviceNotFound");break;case re.NoPermissionsToCallGivenResource:return new en(ct.NoPermissions,"")}}catch(e){return e.message.includes("timeout")?new en(ct.ControllerResponseTimeout,""):new en(ct.UnknownError,"")}return new en(ct.Unknown,"")},new((o=void 0)||(o=Promise))((function(e,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(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((r=r.apply(t,n||[])).next())}));var t,n,o,r}ExecuteTaskAsync(e){return Hu.Get(yn.ServiceName).ExecuteDeviceTaskAsync(this,e)}}class on extends oe{constructor(e,t){super(),this.Resource="/devices/device/name",this.Method=se.Put;const n=new rn;n.DeviceGuid=e.Guid,n.Name=t,this.Data=n}}class rn{constructor(){this.DeviceGuid="",this.Name=""}}var sn,an,cn,ln,un;class hn{constructor(){this._device=new nn,this._number=0,this._name="",this._iconName="",this._states=[],this._mode=Re.Default,this._channelGroups=[],this._isHidden=!1,this._availableTasksTypes=[],this._availableResponseTypes=[],this._onTasksExecutionChangedEvent=new n}SetDevice(e){this._device=e,this._device.OnDeviceStateChangedEvent().Subscribe((e=>{e.Data.Channel==this._number&&(this._states=this._states.where((t=>t.TypeAsEnum!=e.TypeAsEnum)).toArray(),this._states.push(e))}))}GetDevice(){return this._device}GetChannelConfigurationData(){const e=new dn;return e.Channel=this._number,e.ChannelName=this._name,e.Configuration=this._mode,e.GroupsGuids=this._channelGroups,e.Hidden=this._isHidden,e.IconName=this._iconName,e}HideAsync(){const e=this.GetChannelConfigurationData();return e.Hidden=!0,this.ChangeConfigurationAsync(e)}ShowAsync(){const e=this.GetChannelConfigurationData();return e.Hidden=!1,this.ChangeConfigurationAsync(e)}ChangeNameAsync(e){const t=this.GetChannelConfigurationData();return t.ChannelName=e,this.ChangeConfigurationAsync(t)}ChangeIconNameAsync(e){const t=this.GetChannelConfigurationData();return t.IconName=e,this.ChangeConfigurationAsync(t)}ChangeGroupsAsync(e){const t=this.GetChannelConfigurationData();return t.GroupsGuids=e,this.ChangeConfigurationAsync(t)}ChangeConfigurationAsync(e){var t,n,o,s,i;return n=this,o=void 0,i=function*(){try{const n=yield Hu.Get(Ie.ServiceName).SendAndWaitForResponseAsync(new fn(e),2e4,!1);switch(n.Status){case re.OK:return new en(ct.Changed,"");case re.WrongData:if("DeviceNotFound"===n.Data)return null===(t=r.Log)||void 0===t||t.Error("Failed to change channel configuration, referenced device does not exist!"),new en(ct.WrongData,"DeviceNotFound");break;case re.FatalError:return new en(ct.UnknownError,"")}}catch(e){if(e.message.includes("timeout"))return new en(ct.ControllerResponseTimeout,"")}return new en(ct.Unknown,"")},new((s=void 0)||(s=Promise))((function(e,t){function r(e){try{c(i.next(e))}catch(e){t(e)}}function a(e){try{c(i.throw(e))}catch(e){t(e)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s((function(e){e(n)}))).then(r,a)}c((i=i.apply(n,o||[])).next())}))}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 this._states}set States(e){this._states=e}set State(e){throw new Error("Method not implemented.")}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,Hu.Get(yn.ServiceName).ExecuteDeviceTaskAsync(this._device,e)):Promise.resolve(Le.Failed)}}class dn{constructor(){this.Channel=0,this.ChannelName="",this.Configuration=Re.Default,this.GroupsGuids=[],this.IconName="",this.Hidden=!1}}class fn extends oe{constructor(e){super(),this.Resource="/devices/device/channel/configuration",this.Method=se.Put,this.Data=e}}(un=sn||(sn={}))[un.TurnOn=0]="TurnOn",un[un.TurnOff=1]="TurnOff",un[un.ToggleState=2]="ToggleState",un[un.SetBlindPosition=3]="SetBlindPosition",un[un.SetLightColor=4]="SetLightColor",un[un.SetLightTemperature=5]="SetLightTemperature",un[un.SetLightBrightness=6]="SetLightBrightness",un[un.SetTemperature=7]="SetTemperature",un[un.GetState=8]="GetState",un[un.TurnOnWithTimeout=9]="TurnOnWithTimeout",un[un.SetLightBrightnessDynamicly=10]="SetLightBrightnessDynamicly",un[un.IdentifyDevice=11]="IdentifyDevice",un[un.SetBlindOpenCloseTime=12]="SetBlindOpenCloseTime",un[un.SetBlindMicroventilation=13]="SetBlindMicroventilation",un[un.GatewayPulse=25]="GatewayPulse",un[un.GatePulse=26]="GatePulse",un[un.SetFacadePositionAndTilt=29]="SetFacadePositionAndTilt",function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(an||(an={})),function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop"}(cn||(cn={})),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"}(ln||(ln={}));var gn,vn=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class yn{constructor(){this._devices=[],this._onDevicesTasksChangedEvent=new n,this._onDeviceFoundEvent=new n,this._onDeviceRegisteredEvent=new n,this._onDeviceRemovedEvent=new n,this._onDeviceStateChangedEvent=new n,this._connection=null,this._session=null,this._controllerConfiguration=null,this._fastStatesSync=!1,this._synchronized=!1,this._synchronizationTaskCompletionSource=null,this._connection=Hu.Get(Ie.ServiceName),this._session=Hu.Get(Se.ServiceName),this._controllerConfiguration=Hu.Get(Ce.ServiceName),this._synchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>vn(this,void 0,void 0,(function*(){this._devices=yield this.GetPairedDevicesAsync(),e(),this._synchronized=!0}))))})),this._connection.OnDataReceivedEvent().Subscribe((e=>{if("/info/devices/tasks"===e.Resource)this.ParseDeviceTaskInfo(e.Data);else if("/devices/blinds/times"===e.Resource);else if("/info/devices/device/found"===e.Resource)this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(yn.ServiceName,`Found device: ${e.Name} guid: ${e.Guid}`),this._onDeviceFoundEvent.Invoke(e)}));else if("/info/devices/device/state/changed"===e.Resource){const t=e.Data,n=this._devices.filter((e=>e.Guid==t.DeviceGuid));if(n.length>0){const e=n[0],o=this.MapApiDeviceStateToDeviceState(e,t);null!=o&&this._onDeviceStateChangedEvent.Invoke({Device:e,State:o})}}else"/info/devices/device/registered"===e.Resource?this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(yn.ServiceName,`Registered device: ${e.Name} guid: ${e.Guid}`),this._onDeviceRegisteredEvent.Invoke(e)})):"/info/devices/device/removed"===e.Resource&&this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=r.Log)||void 0===t||t.Debug(yn.ServiceName,`Removed device: ${e.Name} guid: ${e.Guid}`),this._onDeviceRemovedEvent.Invoke(e)}))}))}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}GetCurrentlyRunningTaksAsync(){var e;return vn(this,void 0,void 0,(function*(){const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new An,15e3,!1);(null==t?void 0:t.Status)==re.OK&&null!=t.Data&&this.ParseDeviceTaskInfo(t.Data)}))}ParseDeviceTaskInfo(e){const t=[];e.forEach((e=>{const n=e.split(";"),o=new mt;o.DeviceGuid=n[0],o.Channel=Number(n[1]),o.Status=Pe.ExecutingTasks,t.push(o)})),this._onDevicesTasksChangedEvent.Invoke(t)}MapApiDeviceStateToDeviceState(e,t){var n;switch(t.state,t.DataType){case"ChannelOnOff":return new At(t);case"DoorBell":return new Et(t);case"ReedPosition":return new Ct(t);case"BlindPosition":return new bt(t);case"ButtonState":return new Nt(t);case"LightColor":return new Dt(t);case"LightTemperature":return new Tt(t);case"LightBrightness":return new kt(t);case"TemperatureSensor":case"TemperatureState":case"MeasuredTemperature":return new It(t);case"BatteryState":return new Pt(t);case"MeasuredBrightness":case"DeviceBrightnessState":return new Rt(t);case"EnergyMeasuredPower":case"EnergyMeasuredCurrent":case"EnergyMeasuredVoltage":break;case"Energy":return new Gt(t);case"DistanceSensor":return new Ft(t);case"MovementSensor":return new Ot(t);case"BlindsControlButton":return new xt(t);case"FacadeControlButton":return new Mt(t);case"SignalStrength":return new $t(t);case"GatePosition":return new Lt(t);case"GatewayPosition":return new Wt(t);case"IBlindCalibrationStatus":case"BlindCalibration":return new Bt(t);case"HumiditySensor":return new Ut(t);case"VibrationSensor":return new Ht(t);case"DigitalInputSensor":return new jt(t);case"ConfigurationState":return new zt(t);case"BlindOpenCloseTime":case"IBlindOpenCloseTime":return new Kt(t);case"IOvercurrentProtection":case"OvercurrentProtection":return new qt(t);case"IOvercurrentProtectionThreshold":case"OvercurrentProtectionThreshold":return new Vt(t);case"FacadePosition":case"FacadeState":return new Jt(t);case"CurrentWindThreshold":return new Yt(t);case"CurrentLightThreshold":return new Xt(t);case"WindSpeed":return new Qt(t);case"FloodSensor":return new Zt(t);default:null===(n=r.Log)||void 0===n||n.Debug(yn.ServiceName,`Not supported device state ${t.DataType}`)}return null}GetServiceName(){return yn.ServiceName}SyncDevicesStatesAsync(){var e;return vn(this,void 0,void 0,(function*(){if(this._fastStatesSync){const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new wn,15e3,!1);return(null==t?void 0:t.Status)==re.OK}throw new Error("Precise, slow states synchronization is not implemented yet")}))}OnDevicesTasksExecutionChangeEvent(){return this._onDevicesTasksChangedEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}OnDeviceRegisteredEvent(){return this._onDeviceRegisteredEvent}OnDeviceRemovedEvent(){return this._onDeviceRemovedEvent}OnDeviceFoundEvent(){return this._onDeviceFoundEvent}MapApiDevices(e){const t=[];return null==e?[]:(e.forEach((e=>{var n,o,s,i,a=new nn;a.Guid=e.Guid,a.Name=e.DeviceName,a.ChannelsAmount=e.ChannelsNumber,a.DeviceType=e.DeviceType,a.CommunicationWay=e.CommunicationWay,a.DeviceState=e.DeviceState,a.IsEnabled=e.IsEnabled,a.IsVirtual=e.IsVirtual,a.SerialNumber=e.DeviceSerialNumber,a.ManufacturerGuid=e.ManufacturerGuid,a.ModelGuid=e.DeviceModelGuid,a.Model=e.DeviceModel,a.Name=e.DeviceName;try{null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new pt;if(a.CommunicationWay==xe.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}a.AvailableTaskTypes.push(t)})),null===(o=e.AvailableResponses)||void 0===o||o.forEach((e=>{var t=new wt;t.InterfaceType=e,a.AvailableResponseTypes.push(t)})),null===(s=e.ChannelsConfiguration)||void 0===s||s.forEach((e=>{var t,n,o;try{var s=new hn;s.SetDevice(a),a.Channels.push(s),s.Number=e.Channel,s.Name=e.ChannelName,s.ChannelGroups=e.GroupsGuids,s.IconName=e.IconName,s.IsHidden=e.Hidden,null===(t=e.AvailableResponses)||void 0===t||t.forEach((e=>{var t=new wt;t.InterfaceType=e,s.AvailableResponseTypes.push(t)})),null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new pt;t.InterfaceType=e,s.AvailableTaskTypes.push(t)}))}catch(e){null===(o=r.Log)||void 0===o||o.Error(e)}}))}catch(e){null===(i=r.Log)||void 0===i||i.Error(e)}t.push(a)})),this._devices=t,t)}GetPairedDevicesAsync(){var e,t,n;return vn(this,void 0,void 0,(function*(){if(this._synchronized&&!(yield null===(e=this._controllerConfiguration)||void 0===e?void 0:e.DidCofigurationChangeAsync()))return Promise.resolve(this._devices);const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new pn,15e3,!0);return null==o||void 0===o?[]:o.Status==re.OK&&null!=o.Data?this.MapApiDevices(o.Data):(null===(n=r.Log)||void 0===n||n.Error(yn.ServiceName,`Failed to get devices. ${o.Status} ${o.Data}`),[])}))}GetDevicesAsync(){return vn(this,void 0,void 0,(function*(){return yield this.WaitForSynchronizationAsync(),this.GetPairedDevicesAsync()}))}GetFoundDevicesAsync(){var e,t;return vn(this,void 0,void 0,(function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new _n,15e3,!1);return null==n?[]:n.Status==re.OK&&null!=n.Data?this.MapApiDevices(n.Data):(null===(t=r.Log)||void 0===t||t.Error(yn.ServiceName,`Failed to get found devices. ${n.Status} ${n.Data}`),[])}))}GetDevice(e){return this._devices.find((t=>t.Guid===e))}FindDevicesAsync(){var e;return vn(this,void 0,void 0,(function*(){yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new mn,35e3,!1)}))}StopSearchingForDevices(){var e;return vn(this,void 0,void 0,(function*(){yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Sn,2e4,!1)}))}RegisterDeviceAsync(e){var t;return vn(this,void 0,void 0,(function*(){const n=new En;n.Data=e.Guid;const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,2e4,!1);return(null==o?void 0:o.Status)==re.OK?(this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e),Le.Executed):Le.Failed}))}RemoveDeviceAsync(e){var t;return vn(this,void 0,void 0,(function*(){var n=new Cn;n.Data=e.Guid;const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,35e3,!1);return(null==o?void 0:o.Status)==re.OK?(this._devices=this._devices.where((t=>t.Guid==e.Guid)).toArray(),this._onDeviceRemovedEvent.Invoke(e),Le.Executed):Le.Failed}))}MapDeviceTaskToDeviceTaskInfo(e,t){let n=new Dn;const o=t;switch(o.FeatureType){case sn.SetTemperature:n.Data=o.Temperature;break;case sn.SetLightBrightness:n.Data=o.Brightness;break;case sn.SetLightColor:n=new Tn;const e=o;n.R=e.R,n.G=e.G,n.B=e.B;break;case sn.SetLightTemperature:n.Data=o.Temperature;break;case sn.SetBlindPosition:switch(o.Action){case an.Open:n.Data=101;break;case an.Close:n.Data=102;break;case an.Stop:n.Data=103;break;case an.Percentage:n.Data=o.Position}break;case sn.SetLightBrightnessDynamicly:n.Data=o.Brightness;break;case sn.SetBlindOpenCloseTime:n.Data=o.Data;break;case sn.SetBlindMicroventilation:n.Data=o.Position;break;case sn.SetFacadePositionAndTilt:n=new kn;const t=o;n.FacadeAction=t.FacadeAction,n.Tilt=t.Tilt,n.Position=t.Position}return n.Channel=o.Channel,n.DeviceGuid=e.Guid,n.ControlFeature=o.FeatureType,n}ExecuteDeviceTaskAsync(e,t){var n,o,s,i,a,c,l,u;return vn(this,void 0,void 0,(function*(){try{null===(n=r.Log)||void 0===n||n.Debug(yn.ServiceName,`Preparing device task execution, device: ${e.Guid} task: ${t.TaskType} channel: ${t.Channel}`);let u=this.MapDeviceTaskToDeviceTaskInfo(e,t);try{const e=new bn(u);null===(o=r.Log)||void 0===o||o.Debug(yn.ServiceName,`Sending device task for execution, device: ${u.DeviceGuid} task: ${u.ControlFeature} channel: ${u.Channel} request: ${JSON.stringify(e)}`);const t=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(e,15e3,!1);switch(null==t?void 0:t.Status){case re.OK:return Le.Executed;case re.FatalError:return null===(i=r.Log)||void 0===i||i.Error(yn.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),Le.Failed;case re.WrongData:if("DeviceNotFound"===t.Data)return Le.DeviceNotFound;break;case re.Error:return"DeviceResponseTimeout"===t.Data?Le.DeviceResponseTimeout:(null===(a=r.Log)||void 0===a||a.Error(yn.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${t.Data}`),Le.Failed)}}catch(e){return e.message.includes("timeout")?(null===(c=r.Log)||void 0===c||c.Error(yn.ServiceName,`Failed to get controller response in time.\n${e}`),Le.ControllerResponseTimeout):(null===(l=r.Log)||void 0===l||l.Error(yn.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),Le.Failed)}return Le.Unknown}catch(e){return null===(u=r.Log)||void 0===u||u.Error(yn.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),Le.Failed}}))}ExecuteDevicesTasksAsync(e){var t,n,o,s;return vn(this,void 0,void 0,(function*(){let i=[],a=[],c=0;for(const[t,n]of e){const e=this.MapDeviceTaskToDeviceTaskInfo(t,n);e.SequnceExecutionOrder=c,c++,a.push(e)}const l=new Nn(a);try{const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(l,12e4,!1);let s=-1;null===(n=null==o?void 0:o.Data)||void 0===n||n.forEach((t=>{var n,a;s++;let c=Le.Unknown;switch(t.Status){case re.OK:return Le.Executed;case re.FatalError:null===(n=r.Log)||void 0===n||n.Error(yn.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),c=Le.Failed;break;case re.WrongData:"DeviceNotFound"===t.Data&&(c=Le.DeviceNotFound);break;case re.Error:"DeviceResponseTimeout"===t.Data?c=Le.DeviceResponseTimeout:(null===(a=r.Log)||void 0===a||a.Error(yn.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${o.Data}`),c=Le.Failed)}let l=0,u=new St;for(const[t,n]of e){if(l==s){u.Device=t,u.Task=n,u.Channel=n.Channel,i.push(u);break}l++}}))}catch(t){if(t.message.includes("timeout")){null===(o=r.Log)||void 0===o||o.Error(yn.ServiceName,`Failed to get controller response in time.\n${t}`);for(const[t,n]of e){let e=new St;i.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=Le.ControllerResponseTimeout}}else{null===(s=r.Log)||void 0===s||s.Error(yn.ServiceName,`Unknown error occured when tried to execute task on device.\n${t}`);for(const[t,n]of e){let e=new St;i.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=Le.Failed}}}return i}))}}yn.ServiceName="DevicesService";class pn extends oe{constructor(){super(),this.Resource="/devices/list",this.Method=se.Get}}class wn extends oe{constructor(){super(),this.Resource="/devices/channels/states",this.Method=se.Get}}class mn extends oe{constructor(){super(),this.Resource="/devices/search",this.Method=se.Post}}class Sn extends oe{constructor(){super(),this.Resource="/devices/search/stop",this.Method=se.Post}}class _n extends oe{constructor(){super(),this.Resource="/devices/found/list",this.Method=se.Get}}class An extends oe{constructor(){super(),this.Resource="/devices/tasks",this.Method=se.Get}}class En extends oe{constructor(){super(),this.Resource="/devices/device/pair",this.Method=se.Put}}class Cn extends oe{constructor(){super(),this.Resource="/devices/device/unpair",this.Method=se.Put}}class bn extends oe{constructor(e){super(),this.Resource="/devices/device/control",this.Method=se.Post,this.Data=e}}class Nn extends oe{constructor(e){super(),this.Resource="/devices/devices/control",this.Method=se.Post,this.Data=e}}class Dn{constructor(){this.DeviceGuid="",this.Channel=0,this.ControlFeature=sn.GetState,this.SequnceExecutionOrder=0}}class Tn extends Dn{constructor(){super(...arguments),this.R=0,this.G=0,this.B=0}}class kn extends Dn{constructor(){super(...arguments),this.FacadeAction=ln.Stop,this.Tilt=0,this.Position=0}}class In{constructor(){this.Longitude=0,this.Latitude=0}}class Pn{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"}(gn||(gn={}));var Rn=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Gn{IsControllerGeolocationSetAsync(){return Rn(this,void 0,void 0,(function*(){let e=new Fn,t=yield Hu.Get(Ie.ServiceName).SendAndWaitForResponseAsync(e,15e3,!0);return(null==t?void 0:t.Status)===re.OK?null==t?void 0:t.Data:null==t?void 0:t.Status}))}GetCurrentGeolocationAsync(){return Rn(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Rn(this,void 0,void 0,(function*(){window.navigator.geolocation.getCurrentPosition((t=>{e(t)}),(t=>{e(t)}))}))))}))}SetControllerGeolocationAsync(e){var t,n;return Rn(this,void 0,void 0,(function*(){let o=new xn;o.Data.Latitude=e.Latitude,o.Data.Longitude=e.Longitude,null===(t=r.Log)||void 0===t||t.Warning(Gn.ServiceName,`SetControllerGeolocationAsync() ${JSON.stringify(o)}`);let s=yield Hu.Get(Ie.ServiceName).SendAndWaitForResponseAsync(o,15e3,!1);switch(null===(n=r.Log)||void 0===n||n.Warning(Gn.ServiceName,`${JSON.stringify(s)}`),null==s?void 0:s.Status){case re.OK:return new tn(gn.OK,"");case re.NoPermissionToPerformThisOperation:case re.NoPermissionsToCallGivenResource:return new tn(gn.NoPermissions,"");case re.UserIsNotLoggedIn:return new tn(gn.UserIsNotLoggedIn,"");default:return new tn(gn.UnknownError,"")}}))}GetControlllerGeolocationAsync(){var e,t;return Rn(this,void 0,void 0,(function*(){let n=new On;null===(e=r.Log)||void 0===e||e.Warning(Gn.ServiceName,`GetControlllerGeolocationAsync(): ${JSON.stringify(n)}`);let o=yield Hu.Get(Ie.ServiceName).SendAndWaitForResponseAsync(n,15e3,!0);if(null===(t=r.Log)||void 0===t||t.Warning(Gn.ServiceName,`${JSON.stringify(o)}`),(null==o?void 0:o.Status)===re.OK){let e=new Pn;return e.IsNetworkBased=(null==o?void 0:o.Data).IsNetworkBased,e.Latitude=(null==o?void 0:o.Data).Latitude,e.Longitude=(null==o?void 0:o.Data).Longitude,e}return null==o?void 0:o.Status}))}GetServiceName(){return Gn.ServiceName}}Gn.ServiceName="GeolocationService";class Fn extends oe{constructor(){super(),this.Resource="/geolocation/isset",this.Method=se.Get}}class On extends oe{constructor(){super(),this.Resource="/geolocation/get",this.Method=se.Get}}class xn extends oe{constructor(){super(),this.Data=new In,this.Resource="/geolocation/save",this.Method=se.Put}}class Mn extends RangeError{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 $n=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 Ln extends Error{constructor(e){super(e),this.name="InvalidOperationException",this.stack=this.stack||(new Error).stack}}const Wn=(e,t)=>e===t;class Bn extends Array{}class Un{constructor(e){this.iterator=e}[Symbol.asyncIterator](){return this.iterator()}}class Hn{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 jn{constructor(e){this.iterator=e}[Symbol.iterator](){return this.iterator()}}const zn=e=>{var t;const n=Bn.prototype,o=e.prototype,r=Object.getOwnPropertyNames(n);for(const e of r)o[e]=null!==(t=o[e])&&void 0!==t?t:n[e]},Kn=(e,t,n,o)=>{if(o){if(!n)throw new ReferenceError("TAccumulate function is undefined");return Jn(e,t,n,o)}return n?Vn(e,t,n):qn(e,t)},qn=(e,t)=>{let n;for(const o of e)n=n?t(n,o):o;if(void 0===n)throw new Ln($n.NoElements);return n},Vn=(e,t,n)=>{let o=t;for(const t of e)o=n(o,t);return o},Jn=(e,t,n,o)=>{let r=t;for(const t of e)r=n(r,t);return o(r)},Yn=(e,t)=>{for(const n of e)if(!1===t(n))return!1;return!0},Xn=async(e,t)=>{for(const n of e)if(!1===await t(n))return!1;return!0},Qn=(e,t)=>t?eo(e,t):Zn(e),Zn=e=>{for(const t of e)return!0;return!1},eo=(e,t)=>{for(const n of e)if(!0===t(n))return!0;return!1},to=async(e,t)=>{for(const n of e)if(!0===await t(n))return!0;return!1},no=e=>{if(Array.isArray(e)){if(0===e.length)throw new Ln($n.NoElements);return new Un((async function*(){for await(const t of e)yield t}))}return new Un(e)},oo=e=>no((async function*(){for(const t of e)yield t})),ro=(e,t)=>new Hn({generator:t,type:e}),so=e=>ro(0,(async()=>{const t=[];for(const n of e)t.push(n);return t})),io=(e,t)=>{let n=0,o=0;if(t)for(const r of e)n+=t(r),o+=1;else for(const t of e)n+=t,o+=1;if(0===o)throw new Ln($n.NoElements);return n/o},ao=async(e,t)=>{let n=0,o=0;for(const r of e)n+=await t(r),o+=1;if(0===o)throw new Ln($n.NoElements);return n/o},co=(e,t)=>{if(t<1)throw new Mn("index");return new jn((function*(){let n=[];for(const o of e)n.push(o),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},lo=(e,t)=>new jn((function*(){yield*e,yield*t})),uo=(e,t,n=Wn)=>{for(const o of e)if(n(t,o))return!0;return!1},ho=async(e,t,n)=>{for(const o of e)if(await n(t,o))return!0;return!1},fo=(e,t)=>t?vo(e,t):go(e),go=e=>{let t=0;for(const n of e)t++;return t},vo=(e,t)=>{let n=0;for(const o of e)!0===t(o)&&n++;return n},yo=async(e,t)=>{let n=0;for(const o of e)!0===await t(o)&&n++;return n},po=(e,t)=>new jn((function*(){let n=!1;for(const t of e)n=!0,yield t;n||(yield t)})),wo=(e,t=Wn)=>new jn((function*(){const n=[];for(const o of e)n.find((e=>t(e,o)))||(n.push(o),yield o)})),mo=(e,t)=>no((async function*(){const n=[];e:for(const o of e){for(const e of n)if(await t(e,o))continue e;n.push(o),yield o}})),So=(e,t)=>new jn((function*(){for(const n of e)t(n),yield n})),_o=(e,t)=>no((async function*(){for(const n of e)await t(n),yield n})),Ao=(e,t)=>{if(t<0)throw new Mn("index");let n=0;for(const o of e)if(t===n++)return o;throw new Mn("index")},Eo=(e,t)=>{let n=0;for(const o of e)if(t===n++)return o;return null},Co=(e,t,n=Wn)=>new jn((function*(){const o=[...t];for(const t of e){let e=!1;for(let r=0;r<o.length;r++)if(!0===n(t,o[r])){e=!0;break}!1===e&&(yield t)}})),bo=(e,t,n)=>no((async function*(){const o=[...t];for(const t of e){let e=!1;for(let r=0;r<o.length;r++){const s=o[r];if(!0===await n(t,s)){e=!0;break}}!1===e&&(yield t)}})),No=(e,t)=>t?To(e,t):Do(e),Do=e=>{const t=e[Symbol.iterator]().next();if(!0===t.done)throw new Ln($n.NoElements);return t.value},To=(e,t)=>{for(const n of e)if(!0===t(n))return n;throw new Ln($n.NoMatch)},ko=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;throw new Ln($n.NoMatch)},Io=(e,t)=>t?Ro(e,t):Po(e),Po=e=>e[Symbol.iterator]().next().value||null,Ro=(e,t)=>{for(const n of e)if(!0===t(n))return n;return null},Go=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;return null};class Fo extends Bn{constructor(e,t){super(1),this.key=e,this[0]=t}}const Oo=(e,t,n)=>{let o;return o=n?((e,t,n)=>function*(){const o=new Array;for(const r of e){const e=t(r);let s=!1;for(let t=0;t<o.length;t++){const i=o[t];if(n(i.key,e)){i.push(r),s=!0;break}}!1===s&&o.push(new Fo(e,r))}for(const e of o)yield e})(e,t,n):((e,t)=>function*(){const n={};for(const o of e){const e=t(o),r=n[e];r?r.push(o):n[e]=new Fo(e,o)}for(const e in n)yield n[e]})(e,t),new jn(o)},xo=(e,t,n)=>n?$o(e,t,n):Mo(e,t),Mo=(e,t)=>no((async function*(){const n={};for(const o of e){const e=await t(o),r=n[e];r?r.push(o):n[e]=new Fo(e,o)}for(const e in n)yield n[e]})),$o=(e,t,n)=>no((async function*(){const o=new Array;for(const r of e){const e=await t(r);let s=!1;for(let t=0;t<o.length;t++){const i=o[t];if(!0===await n(i.key,e)){i.push(r),s=!0;break}}!1===s&&o.push(new Fo(e,r))}for(const e of o)yield e})),Lo=(e,t,n,o)=>o?((e,t,n,o)=>new jn((function*(){const r=new Array;for(const s of e){const e=t(s);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(o(a.key,e)){a.push(n(s)),i=!0;break}}if(!1===i){const t=n(s);r.push(new Fo(e,t))}}for(const e of r)yield e})))(e,t,n,o):((e,t,n)=>new jn((function*(){const o={};for(const r of e){const e=t(r),s=o[e],i=n(r);s?s.push(i):o[e]=new Fo(e,i)}for(const e in o)yield o[e]})))(e,t,n),Wo=(e,t,n,o,r,s)=>{const i=s?Bo(e,t,n,o,r,s):Uo(e,t,n,o,r);return new jn(i)},Bo=(e,t,n,o,r,s)=>function*(){var i;const a=[];for(const e of t){const t=o(e),n=a.find((e=>s(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for(const t of e){const e=n(t),o=null!==(i=a.find((t=>s(t.key,e))))&&void 0!==i?i:{key:e,values:[]};yield r(t,o.values)}},Uo=(e,t,n,o,r)=>function*(){var s;const i=new Map;for(const e of t){const t=o(e),n=i.get(t);n?n.push(e):i.set(t,[e])}for(const t of e){const e=n(t),o=null!==(s=i.get(e))&&void 0!==s?s:[];yield r(t,o)}},Ho=(e,t,n,o,r,s)=>{const i=s?jo(e,t,n,o,r,s):zo(e,t,n,o,r);return no(i)},jo=(e,t,n,o,r,s)=>async function*(){var i;const a=[];for(const e of t){const t=await o(e),n=a.find((e=>s(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for(const t of e){const e=await n(t),o=null!==(i=a.find((t=>s(t.key,e))))&&void 0!==i?i:{key:e,values:[]};yield r(t,o.values)}},zo=(e,t,n,o,r)=>async function*(){var s;const i=new Map;for(const e of t){const t=await o(e),n=i.get(t);n?n.push(e):i.set(t,[e])}for(const t of e){const e=await n(t),o=null!==(s=i.get(e))&&void 0!==s?s:[];yield r(t,o)}},Ko=(e,t,n=Wn)=>new jn((function*(){const o=[...e.distinct(n)];if(0===o.length)return;const r=[...t];for(let e=0;e<o.length;e++){const t=o[e];for(let e=0;e<r.length;e++)if(!0===n(t,r[e])){yield t;break}}})),qo=(e,t,n)=>no((async function*(){const o=[];for await(const t of e.distinctAsync(n))o.push(t);if(0===o.length)return;const r=[...t];for(let e=0;e<o.length;e++){const t=o[e];for(let e=0;e<r.length;e++){const o=r[e];if(!0===await n(t,o)){yield t;break}}}})),Vo=(e,t,n,o,r,s=Wn)=>new jn((function*(){const i=[...t];for(const t of e){const e=n(t);for(const n of i){const i=o(n);!0===s(e,i)&&(yield r(t,n))}}})),Jo=(e,t)=>t?Xo(e,t):Yo(e),Yo=e=>{let t;for(const n of e)t=n;if(!t)throw new Ln($n.NoElements);return t},Xo=(e,t)=>{let n;for(const o of e)!0===t(o)&&(n=o);if(!n)throw new Ln($n.NoMatch);return n},Qo=async(e,t)=>{let n;for(const o of e)!0===await t(o)&&(n=o);if(!n)throw new Ln($n.NoMatch);return n},Zo=(e,t)=>t?tr(e,t):er(e),er=e=>{let t=null;for(const n of e)t=n;return t},tr=(e,t)=>{let n=null;for(const o of e)!0===t(o)&&(n=o);return n},nr=async(e,t)=>{let n=null;for(const o of e)!0===await t(o)&&(n=o);return n},or=(e,t)=>t?sr(e,t):rr(e),rr=e=>{let t=null;for(const n of e)t=Math.max(t||Number.NEGATIVE_INFINITY,n);if(null===t)throw new Ln($n.NoElements);return t},sr=(e,t)=>{let n=null;for(const o of e)n=Math.max(n||Number.NEGATIVE_INFINITY,t(o));if(null===n)throw new Ln($n.NoElements);return n},ir=async(e,t)=>{let n=null;for(const o of e)n=Math.max(n||Number.NEGATIVE_INFINITY,await t(o));if(null===n)throw new Ln($n.NoElements);return n},ar=(e,t)=>t?lr(e,t):cr(e),cr=e=>{let t=null;for(const n of e)t=Math.min(t||Number.POSITIVE_INFINITY,n);if(null===t)throw new Ln($n.NoElements);return t},lr=(e,t)=>{let n=null;for(const o of e)n=Math.min(n||Number.POSITIVE_INFINITY,t(o));if(null===n)throw new Ln($n.NoElements);return n},ur=async(e,t)=>{let n=null;for(const o of e)n=Math.min(n||Number.POSITIVE_INFINITY,await t(o));if(null===n)throw new Ln($n.NoElements);return n},hr=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new jn((function*(){for(const t of e)n(t)&&(yield t)}))};async function*dr(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for(const o of e){const e=await t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}function*fr(e,t,n,o){const r=((e,t)=>{const n=new Map;for(const o of e){const e=t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}class gr extends Un{constructor(e){super((async function*(){for await(const t of e())yield*t})),this.orderedPairs=e}static generateAsync(e,t,n,o){let r;return r=e instanceof gr?async function*(){for await(const r of e.orderedPairs())yield*dr(r,t,n,o)}:()=>async function*(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for await(const o of e){const e=await t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}(e,t,n,o),new gr(r)}static generate(e,t,n,o){let r;return r=e instanceof gr?async function*(){for await(const r of e.orderedPairs())yield*fr(r,t,n,o)}:()=>async function*(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for await(const o of e){const e=t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}(e,t,n,o),new gr(r)}thenBy(e,t){return gr.generate(this,e,!0,t)}thenByAsync(e,t){return gr.generateAsync(this,e,!0,t)}thenByDescending(e,t){return gr.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return gr.generateAsync(this,e,!1,t)}}function*vr(e,t,n,o){const r=((e,t)=>{const n=new Map;for(const o of e){const e=t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}async function*yr(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for(const o of e){const e=await t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}class pr extends jn{constructor(e){super((function*(){for(const t of e())yield*t})),this.orderedPairs=e}static generate(e,t,n,o){let r;return r=e instanceof pr?function*(){for(const r of e.orderedPairs())yield*vr(r,t,n,o)}:()=>vr(e,t,n,o),new pr(r)}static generateAsync(e,t,n,o){let r;return r=e instanceof pr?async function*(){for(const r of e.orderedPairs())yield*yr(r,t,n,o)}:()=>yr(e,t,n,o),new gr(r)}thenBy(e,t){return pr.generate(this,e,!0,t)}thenByAsync(e,t){return pr.generateAsync(this,e,!0,t)}thenByDescending(e,t){return pr.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return pr.generateAsync(this,e,!1,t)}}const wr=(e,t,n)=>pr.generate(e,t,!0,n),mr=(e,t,n)=>pr.generateAsync(e,t,!0,n),Sr=(e,t,n)=>pr.generate(e,t,!1,n),_r=(e,t,n)=>pr.generateAsync(e,t,!1,n),Ar=(e,t)=>{const n=[],o=[];for(const r of e)!0===t(r)?o.push(r):n.push(r);return[o,n]},Er=async(e,t)=>{const n=[],o=[];for(const r of e)!0===await t(r)?o.push(r):n.push(r);return[o,n]},Cr=e=>new jn((function*(){const t=[...e];for(let e=t.length-1;e>=0;e--)yield t[e]})),br=(e,t)=>{if("function"==typeof t){const{length:n}=t;return 1===n?Nr(e,t):Dr(e,t)}return Tr(e,t)},Nr=(e,t)=>new jn((function*(){for(const n of e)yield t(n)})),Dr=(e,t)=>new jn((function*(){let n=0;for(const o of e)yield t(o,n),n++})),Tr=(e,t)=>new jn((function*(){for(const n of e)yield n[t]})),kr=(e,t)=>"function"==typeof t?1===t.length?Ir(e,t):Pr(e,t):Rr(e,t),Ir=(e,t)=>no((async function*(){for(const n of e)yield t(n)})),Pr=(e,t)=>no((async function*(){let n=0;for(const o of e)yield t(o,n),n++})),Rr=(e,t)=>no((async function*(){for(const n of e)yield n[t]})),Gr=(e,t)=>"function"==typeof t?1===t.length?Fr(e,t):Or(e,t):xr(e,t),Fr=(e,t)=>new jn((function*(){for(const n of e)for(const e of t(n))yield e})),Or=(e,t)=>new jn((function*(){let n=0;for(const o of e){for(const e of t(o,n))yield e;n++}})),xr=(e,t)=>new jn((function*(){for(const n of e)for(const e of n[t])yield e})),Mr=(e,t)=>1===t.length?$r(e,t):Lr(e,t),$r=(e,t)=>no((async function*(){for(const n of e){const e=await t(n);for(const t of e)yield t}})),Lr=(e,t)=>no((async function*(){let n=0;for(const o of e){const e=await t(o,n);for(const t of e)yield t;n++}})),Wr=(e,t,n=Wn)=>{const o=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=o.next(),i=r.next();for(;!s.done&&!i.done;){if(!n(s.value,i.value))return!1;s=o.next(),i=r.next()}return!0===s.done&&!0===i.done},Br=async(e,t,n)=>{const o=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=o.next(),i=r.next();for(;!s.done&&!i.done;){if(!1===await n(s.value,i.value))return!1;s=o.next(),i=r.next()}return!0===s.done&&!0===i.done},Ur=(e,t)=>t?jr(e,t):Hr(e),Hr=e=>{let t=!1,n=null;for(const o of e){if(!0===t)throw new Ln($n.MoreThanOneElement);t=!0,n=o}if(!1===t)throw new Ln($n.NoElements);return n},jr=(e,t)=>{let n=!1,o=null;for(const r of e)if(t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}if(!1===n)throw new Ln($n.NoMatch);return o},zr=async(e,t)=>{let n=!1,o=null;for(const r of e)if(await t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}if(!1===n)throw new Ln($n.NoMatch);return o},Kr=(e,t)=>t?Vr(e,t):qr(e),qr=e=>{let t=!1,n=null;for(const o of e){if(!0===t)throw new Ln($n.MoreThanOneElement);t=!0,n=o}return n},Vr=(e,t)=>{let n=!1,o=null;for(const r of e)if(t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}return o},Jr=async(e,t)=>{let n=!1,o=null;for(const r of e)if(await t(r)){if(!0===n)throw new Ln($n.MoreThanOneElement);n=!0,o=r}return o},Yr=(e,t)=>new jn((function*(){let n=0;for(const o of e)n++>=t&&(yield o)})),Xr=(e,t)=>1===t.length?Qr(e,t):Zr(e,t),Qr=(e,t)=>new jn((function*(){let n=!0;for(const o of e)!1===n?yield o:!1===t(o)&&(n=!1,yield o)})),Zr=(e,t)=>new jn((function*(){let n=0,o=!0;for(const r of e)!1===o?yield r:!1===t(r,n)&&(o=!1,yield r),n++})),es=(e,t)=>1===t.length?ts(e,t):ns(e,t),ts=(e,t)=>no((async function*(){let n=!0;for(const o of e)!1===n?yield o:!1===await t(o)&&(n=!1,yield o)})),ns=(e,t)=>no((async function*(){let n=0,o=!0;for(const r of e)!1===o?yield r:!1===await t(r,n)&&(o=!1,yield r),n++})),os=(e,t)=>t?ss(e,t):rs(e),rs=e=>{let t=0;for(const n of e)t+=n;return t},ss=(e,t)=>{let n=0;for(const o of e)n+=t(o);return n},is=async(e,t)=>{let n=0;for(const o of e)n+=await t(o);return n},as=(e,t)=>new jn((function*(){let n=t>0?t:0;for(const t of e){if(0==n--)break;yield t}})),cs=(e,t)=>1===t.length?ls(e,t):us(e,t),ls=(e,t)=>new jn((function*(){for(const n of e){if(!t(n))break;yield n}})),us=(e,t)=>new jn((function*(){let n=0;for(const o of e){if(!t(o,n++))break;yield o}})),hs=(e,t)=>1===t.length?ds(e,t):fs(e,t),ds=(e,t)=>no((async function*(){for(const n of e){if(!await t(n))break;yield n}})),fs=(e,t)=>no((async function*(){let n=0;for(const o of e){if(!await t(o,n++))break;yield o}})),gs=e=>[...e],vs=(e,t)=>{const n=new Map;for(const o of e){const e=t(o),r=n.get(e);void 0===r?n.set(e,[o]):r.push(o)}return n},ys=async(e,t)=>{const n=new Map;for(const o of e){const e=await t(o),r=n.get(e);void 0===r?n.set(e,[o]):r.push(o)}return n},ps=(e,t)=>{const n={};for(const o of e)n[t(o)]=o;return n},ws=async(e,t)=>{const n={};for(const o of e)n[await t(o)]=o;return n},ms=e=>new Set(e),Ss=(e,t,n)=>n?As(e,t,n):_s(e,t),_s=(e,t)=>new jn((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))})),As=(e,t,n)=>new jn((function*(){const o=[];for(const r of[e,t])for(const e of r){let t=!1;for(const r of o)if(!0===n(e,r)){t=!0;break}!1===t&&(yield e,o.push(e))}})),Es=(e,t,n)=>no((async function*(){const o=[];for(const r of[e,t])for(const e of r){let t=!1;for(const r of o)if(!0===await n(e,r)){t=!0;break}!1===t&&(yield e,o.push(e))}})),Cs=(e,t)=>1===t.length?bs(e,t):Ns(e,t),bs=(e,t)=>new jn((function*(){for(const n of e)!0===t(n)&&(yield n)})),Ns=(e,t)=>new jn((function*(){let n=0;for(const o of e)!0===t(o,n++)&&(yield o)})),Ds=(e,t)=>1===t.length?Ts(e,t):ks(e,t),Ts=(e,t)=>no((async function*(){for(const n of e)!0===await t(n)&&(yield n)})),ks=(e,t)=>no((async function*(){let n=0;for(const o of e)!0===await t(o,n++)&&(yield o)})),Is=(e,t,n)=>n?Rs(e,t,n):Ps(e,t),Ps=(e,t)=>new jn((function*(){const n=e[Symbol.iterator](),o=t[Symbol.iterator]();for(;;){const e=n.next(),t=o.next();if(e.done||t.done)break;yield[e.value,t.value]}})),Rs=(e,t,n)=>new jn((function*(){const o=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=o.next(),t=r.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),Gs=(e,t,n)=>no((async function*(){const o=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=o.next(),t=r.next();if(e.done||t.done)break;yield n(e.value,t.value)}})),Fs=e=>{const t=e.prototype,n=(e,n)=>{const o=function(...t){return e(this,...t)};Object.defineProperty(o,"length",{value:e.length-1}),t[n]=o};n(Kn,"aggregate"),n(Yn,"all"),n(Xn,"allAsync"),n(Qn,"any"),n(to,"anyAsync"),n(oo,"asAsync"),n(so,"asParallel"),n(io,"average"),n(ao,"averageAsync"),n(co,"chunk"),n(lo,"concatenate"),n(uo,"contains"),n(ho,"containsAsync"),n(fo,"count"),n(yo,"countAsync"),n(po,"defaultIfEmpty"),n(wo,"distinct"),n(mo,"distinctAsync"),n(So,"each"),n(_o,"eachAsync"),n(Ao,"elementAt"),n(Eo,"elementAtOrDefault"),n(Co,"except"),n(bo,"exceptAsync"),n(No,"first"),n(ko,"firstAsync"),n(Io,"firstOrDefault"),n(Go,"firstOrDefaultAsync"),n(Oo,"groupBy"),n(xo,"groupByAsync"),n(Lo,"groupByWithSel"),n(Wo,"groupJoin"),n(Ho,"groupJoinAsync"),n(Ko,"intersect"),n(qo,"intersectAsync"),n(Vo,"joinByKey"),n(Jo,"last"),n(Qo,"lastAsync"),n(Zo,"lastOrDefault"),n(nr,"lastOrDefaultAsync"),n(or,"max"),n(ir,"maxAsync"),n(ar,"min"),n(ur,"minAsync"),n(hr,"ofType"),n(wr,"orderBy"),n(mr,"orderByAsync"),n(Sr,"orderByDescending"),n(_r,"orderByDescendingAsync"),n(Cr,"reverse"),n(br,"select"),n(kr,"selectAsync"),n(Gr,"selectMany"),n(Mr,"selectManyAsync"),n(Wr,"sequenceEquals"),n(Br,"sequenceEqualsAsync"),n(Ur,"single"),n(zr,"singleAsync"),n(Kr,"singleOrDefault"),n(Jr,"singleOrDefaultAsync"),n(Yr,"skip"),n(Xr,"skipWhile"),n(es,"skipWhileAsync"),n(os,"sum"),n(is,"sumAsync"),n(as,"take"),n(cs,"takeWhile"),n(hs,"takeWhileAsync"),n(gs,"toArray"),n(vs,"toMap"),n(ys,"toMapAsync"),n(ps,"toObject"),n(ws,"toObjectAsync"),n(Ar,"partition"),n(Er,"partitionAsync"),n(ms,"toSet"),n(Ss,"union"),n(Es,"unionAsync"),n(Cs,"where"),n(Ds,"whereAsync"),n(Is,"zip"),n(Gs,"zipAsync")},Os=(e,t,n,o)=>{if(o){if(!n)throw new ReferenceError("TAccumulate function is undefined");return $s(e,t,n,o)}return n?Ms(e,t,n):xs(e,t)},xs=async(e,t)=>{let n;for await(const o of e)n=n?t(n,o):o;if(void 0===n)throw new Ln($n.NoElements);return n},Ms=async(e,t,n)=>{let o=t;for await(const t of e)o=n(o,t);return o},$s=async(e,t,n,o)=>{let r=t;for await(const t of e)r=n(r,t);return o(r)},Ls=async(e,t)=>{for await(const n of e)if(!1===t(n))return!1;return!0},Ws=async(e,t)=>{for await(const n of e)if(!1===await t(n))return!1;return!0},Bs=(e,t)=>t?Hs(e,t):Us(e),Us=async e=>{for await(const t of e)return!0;return!1},Hs=async(e,t)=>{for await(const n of e)if(!0===t(n))return!0;return!1},js=async(e,t)=>{for await(const n of e)if(!0===await t(n))return!0;return!1},zs=e=>ro(0,(async()=>{const t=[];for await(const n of e)t.push(n);return t})),Ks=async(e,t)=>{let n=0,o=0;if(t)for await(const r of e)n+=t(r),o+=1;else for await(const t of e)n+=t,o+=1;if(0===o)throw new Ln($n.NoElements);return n/o},qs=async(e,t)=>{let n=0,o=0;for await(const r of e)n+=await t(r),o+=1;if(0===o)throw new Ln($n.NoElements);return n/o},Vs=(e,t)=>{if(t<1)throw new Mn("index");return new Un((async function*(){let n=[];for await(const o of e)n.push(o),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},Js=(e,t)=>new Un((async function*(){yield*e,yield*t})),Ys=async(e,t,n=Wn)=>{for await(const o of e)if(n(t,o))return!0;return!1},Xs=async(e,t,n)=>{for await(const o of e)if(await n(t,o))return!0;return!1},Qs=(e,t)=>t?ei(e,t):Zs(e),Zs=async e=>{let t=0;for await(const n of e)t++;return t},ei=async(e,t)=>{let n=0;for await(const o of e)!0===t(o)&&n++;return n},ti=async(e,t)=>{let n=0;for await(const o of e)!0===await t(o)&&n++;return n},ni=(e,t)=>new Un((async function*(){let n=!1;for await(const t of e)n=!0,yield t;n||(yield t)})),oi=(e,t=Wn)=>new Un((async function*(){const n=[];for await(const o of e)n.find((e=>t(e,o)))||(n.push(o),yield o)})),ri=(e,t)=>new Un((async function*(){const n=[];e:for await(const o of e){for(const e of n)if(await t(e,o))continue e;n.push(o),yield o}})),si=(e,t)=>new Un((async function*(){for await(const n of e)t(n),yield n})),ii=(e,t)=>new Un((async function*(){for await(const n of e)await t(n),yield n})),ai=async(e,t)=>{if(t<0)throw new Mn("index");let n=0;for await(const o of e)if(t===n++)return o;throw new Mn("index")},ci=async(e,t)=>{let n=0;for await(const o of e)if(t===n++)return o;return null},li=(e,t,n=Wn)=>new Un((async function*(){const o=[];for await(const e of t)o.push(e);for await(const t of e){let e=!1;for(let r=0;r<o.length;r++){const s=o[r];if(!0===n(t,s)){e=!0;break}}!1===e&&(yield t)}})),ui=(e,t,n)=>new Un((async function*(){const o=[];for await(const e of t)o.push(e);for await(const t of e){let e=!1;for(let r=0;r<o.length;r++){const s=o[r];if(!0===await n(t,s)){e=!0;break}}!1===e&&(yield t)}})),hi=(e,t)=>t?fi(e,t):di(e),di=async e=>{const t=await e[Symbol.asyncIterator]().next();if(!0===t.done)throw new Ln($n.NoElements);return t.value},fi=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;throw new Ln($n.NoMatch)},gi=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;throw new Ln($n.NoMatch)},vi=(e,t)=>t?pi(e,t):yi(e),yi=async e=>(await e[Symbol.asyncIterator]().next()).value||null,pi=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;return null},wi=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;return null},mi=(e,t,n)=>n?Si(e,t,n):_i(e,t),Si=(e,t,n)=>new Un((async function*(){const o=new Array;for await(const r of e){const e=t(r);let s=!1;for(let t=0;t<o.length;t++){const i=o[t];if(n(i.key,e)){i.push(r),s=!0;break}}!1===s&&o.push(new Fo(e,r))}for(const e of o)yield e})),_i=(e,t)=>new Un((async function*(){const n={};for await(const o of e){const e=t(o),r=n[e];r?r.push(o):n[e]=new Fo(e,o)}for(const e in n)yield n[e]})),Ai=(e,t,n)=>n?Ci(e,t,n):Ei(e,t),Ei=(e,t)=>new Un((async function*(){const n={};for await(const o of e){const e=await t(o),r=n[e];r?r.push(o):n[e]=new Fo(e,o)}for(const e in n)yield n[e]})),Ci=(e,t,n)=>new Un((async function*(){const o=new Array;for await(const r of e){const e=await t(r);let s=!1;for(let t=0;t<o.length;t++){const i=o[t];if(!0===await n(i.key,e)){i.push(r),s=!0;break}}!1===s&&o.push(new Fo(e,r))}for(const e of o)yield e})),bi=(e,t,n,o)=>o?Di(e,t,n,o):Ni(e,t,n),Ni=(e,t,n)=>new Un((async function*(){const o={};for await(const r of e){const e=t(r),s=o[e],i=n(r);s?s.push(i):o[e]=new Fo(e,i)}for(const e in o)yield o[e]})),Di=(e,t,n,o)=>new Un((async function*(){const r=new Array;for await(const s of e){const e=t(s);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(o(a.key,e)){a.push(n(s)),i=!0;break}}if(!1===i){const t=n(s);r.push(new Fo(e,t))}}for(const e of r)yield e})),Ti=(e,t,n,o,r,s)=>{const i=s?ki(e,t,n,o,r,s):Ii(e,t,n,o,r);return new Un(i)},ki=(e,t,n,o,r,s)=>async function*(){var i;const a=[];for await(const e of t){const t=o(e),n=a.find((e=>s(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for await(const t of e){const e=n(t),o=null!==(i=a.find((t=>s(t.key,e))))&&void 0!==i?i:{key:e,values:[]};yield r(t,o.values)}},Ii=(e,t,n,o,r)=>async function*(){var s;const i=new Map;for await(const e of t){const t=o(e),n=i.get(t);n?n.push(e):i.set(t,[e])}for await(const t of e){const e=n(t),o=null!==(s=i.get(e))&&void 0!==s?s:[];yield r(t,o)}},Pi=(e,t,n,o,r,s)=>{const i=s?Ri(e,t,n,o,r,s):Gi(e,t,n,o,r);return new Un(i)},Ri=(e,t,n,o,r,s)=>async function*(){var i;const a=[];for await(const e of t){const t=await o(e),n=a.find((e=>s(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for await(const t of e){const e=await n(t),o=null!==(i=a.find((t=>s(t.key,e))))&&void 0!==i?i:{key:e,values:[]};yield r(t,o.values)}},Gi=(e,t,n,o,r)=>async function*(){var s;const i=new Map;for await(const e of t){const t=await o(e),n=i.get(t);n?n.push(e):i.set(t,[e])}for await(const t of e){const e=await n(t),o=null!==(s=i.get(e))&&void 0!==s?s:[];yield r(t,o)}},Fi=(e,t,n=Wn)=>new Un((async function*(){const o=await e.distinct(n).toArray();if(0===o.length)return;const r=await t.toArray();for(let e=0;e<o.length;e++){const t=o[e];for(let e=0;e<r.length;e++){const o=r[e];if(!0===n(t,o)){yield t;break}}}})),Oi=(e,t,n)=>new Un((async function*(){const o=await e.distinctAsync(n).toArray();if(0===o.length)return;const r=await t.toArray();for(let e=0;e<o.length;e++){const t=o[e];for(let e=0;e<r.length;e++){const o=r[e];if(!0===await n(t,o)){yield t;break}}}})),xi=(e,t,n,o,r,s=Wn)=>new Un((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=o(n);!0===s(e,i)&&(yield r(t,n))}}})),Mi=(e,t)=>t?Li(e,t):$i(e),$i=async e=>{let t=null;for await(const n of e)t=n;if(!t)throw new Ln($n.NoElements);return t},Li=async(e,t)=>{let n=null;for await(const o of e)!0===t(o)&&(n=o);if(!n)throw new Ln($n.NoMatch);return n},Wi=async(e,t)=>{let n=null;for await(const o of e)!0===await t(o)&&(n=o);if(!n)throw new Ln($n.NoMatch);return n},Bi=(e,t)=>t?Hi(e,t):Ui(e),Ui=async e=>{let t=null;for await(const n of e)t=n;return t},Hi=async(e,t)=>{let n=null;for await(const o of e)!0===t(o)&&(n=o);return n},ji=async(e,t)=>{let n=null;for await(const o of e)!0===await t(o)&&(n=o);return n},zi=(e,t)=>t?qi(e,t):Ki(e),Ki=async e=>{let t=null;for await(const n of e)t=Math.max(t||Number.NEGATIVE_INFINITY,n);if(null===t)throw new Ln($n.NoElements);return t},qi=async(e,t)=>{let n=null;for await(const o of e)n=Math.max(n||Number.NEGATIVE_INFINITY,t(o));if(null===n)throw new Ln($n.NoElements);return n},Vi=async(e,t)=>{let n=null;for await(const o of e)n=Math.max(n||Number.NEGATIVE_INFINITY,await t(o));if(null===n)throw new Ln($n.NoElements);return n},Ji=(e,t)=>t?Xi(e,t):Yi(e),Yi=async e=>{let t=null;for await(const n of e)t=Math.min(t||Number.POSITIVE_INFINITY,n);if(null===t)throw new Ln($n.NoElements);return t},Xi=async(e,t)=>{let n=null;for await(const o of e)n=Math.min(n||Number.POSITIVE_INFINITY,t(o));if(null===n)throw new Ln($n.NoElements);return n},Qi=async(e,t)=>{let n=null;for await(const o of e)n=Math.min(n||Number.POSITIVE_INFINITY,await t(o));if(null===n)throw new Ln($n.NoElements);return n},Zi=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new Un((async function*(){for await(const t of e)n(t)&&(yield t)}))},ea=(e,t,n)=>gr.generate(e,t,!0,n),ta=(e,t,n)=>gr.generateAsync(e,t,!0,n),na=(e,t,n)=>gr.generate(e,t,!1,n),oa=(e,t,n)=>gr.generateAsync(e,t,!1,n),ra=async(e,t)=>{const n=[],o=[];for await(const r of e)!0===t(r)?o.push(r):n.push(r);return[o,n]},sa=async(e,t)=>{const n=[],o=[];for await(const r of e)!0===await t(r)?o.push(r):n.push(r);return[o,n]},ia=e=>new Un((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]})),aa=(e,t)=>"function"==typeof t?1===t.length?ca(e,t):la(e,t):ua(e,t),ca=(e,t)=>new Un((async function*(){for await(const n of e)yield t(n)})),la=(e,t)=>new Un((async function*(){let n=0;for await(const o of e)yield t(o,n),n++})),ua=(e,t)=>new Un((async function*(){for await(const n of e)yield n[t]})),ha=(e,t)=>"string"==typeof t?fa(e,t):da(e,t),da=(e,t)=>new Un((async function*(){for await(const n of e)yield t(n)})),fa=(e,t)=>new Un((async function*(){for await(const n of e)yield n[t]})),ga=(e,t)=>"function"==typeof t?1===t.length?va(e,t):ya(e,t):pa(e,t),va=(e,t)=>new Un((async function*(){for await(const n of e)for(const e of t(n))yield e})),ya=(e,t)=>new Un((async function*(){let n=0;for await(const o of e){for(const e of t(o,n))yield e;n++}})),pa=(e,t)=>new Un((async function*(){for await(const n of e)for(const e of n[t])yield e})),wa=(e,t)=>1===t.length?new Un((async function*(){for await(const n of e){const e=await t(n);for(const t of e)yield t}})):new Un((async function*(){let n=0;for await(const o of e){const e=await t(o,n);for(const t of e)yield t;n++}})),ma=async(e,t,n=Wn)=>{const o=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();let s=await Promise.all([o.next(),r.next()]),i=s[0],a=s[1];for(;!i.done&&!a.done;){if(!n(i.value,a.value))return!1;s=await Promise.all([o.next(),r.next()]),i=s[0],a=s[1]}return!0===i.done&&!0===a.done},Sa=async(e,t,n)=>{const o=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();let s=await Promise.all([o.next(),r.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([o.next(),r.next()]),i=s[0],a=s[1]}return!0===i.done&&!0===a.done},_a=(e,t)=>t?Ea(e,t):Aa(e),Aa=async e=>{let t=!1,n=null;for await(const o of e){if(!0===t)throw new Ln($n.MoreThanOneElement);t=!0,n=o}if(!1===t)throw new Ln($n.NoElements);return n},Ea=async(e,t)=>{let n=!1,o=null;for await(const r of e)if(t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}if(!1===n)throw new Ln($n.NoMatch);return o},Ca=async(e,t)=>{let n=!1,o=null;for await(const r of e)if(await t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}if(!1===n)throw new Ln($n.NoMatch);return o},ba=(e,t)=>t?Da(e,t):Na(e),Na=async e=>{let t=!1,n=null;for await(const o of e){if(!0===t)throw new Ln($n.MoreThanOneElement);t=!0,n=o}return n},Da=async(e,t)=>{let n=!1,o=null;for await(const r of e)if(t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}return o},Ta=async(e,t)=>{let n=!1,o=null;for await(const r of e)if(await t(r)){if(!0===n)throw new Ln($n.MoreThanOneMatchingElement);n=!0,o=r}return o},ka=(e,t)=>new Un((async function*(){let n=0;for await(const o of e)n++>=t&&(yield o)})),Ia=(e,t)=>1===t.length?Pa(e,t):Ra(e,t),Pa=(e,t)=>new Un((async function*(){let n=!0;for await(const o of e)!1===n?yield o:!1===t(o)&&(n=!1,yield o)})),Ra=(e,t)=>new Un((async function*(){let n=0,o=!0;for await(const r of e)!1===o?yield r:!1===t(r,n)&&(o=!1,yield r),n++})),Ga=(e,t)=>1===t.length?Fa(e,t):Oa(e,t),Fa=(e,t)=>new Un((async function*(){let n=!0;for await(const o of e)!1===n?yield o:!1===await t(o)&&(n=!1,yield o)})),Oa=(e,t)=>new Un((async function*(){let n=0,o=!0;for await(const r of e)!1===o?yield r:!1===await t(r,n)&&(o=!1,yield r),n++})),xa=(e,t)=>t?$a(e,t):Ma(e),Ma=async e=>{let t=0;for await(const n of e)t+=n;return t},$a=async(e,t)=>{let n=0;for await(const o of e)n+=t(o);return n},La=async(e,t)=>{let n=0;for await(const o of e)n+=await t(o);return n},Wa=(e,t)=>new Un((async function*(){let n=t>0?t:0;for await(const t of e){if(0==n--)break;yield t}})),Ba=(e,t)=>1===t.length?Ua(e,t):Ha(e,t),Ua=(e,t)=>new Un((async function*(){for await(const n of e){if(!t(n))break;yield n}})),Ha=(e,t)=>new Un((async function*(){let n=0;for await(const o of e){if(!t(o,n++))break;yield o}})),ja=(e,t)=>1===t.length?za(e,t):Ka(e,t),za=(e,t)=>new Un((async function*(){for await(const n of e){if(!await t(n))break;yield n}})),Ka=(e,t)=>new Un((async function*(){let n=0;for await(const o of e){if(!await t(o,n++))break;yield o}})),qa=async e=>{const t=[];for await(const n of e)t.push(n);return t},Va=async(e,t)=>{const n=new Map;for await(const o of e){const e=t(o),r=n.get(e);void 0===r?n.set(e,[o]):r.push(o)}return n},Ja=async(e,t)=>{const n=new Map;for await(const o of e){const e=await t(o),r=n.get(e);void 0===r?n.set(e,[o]):r.push(o)}return n},Ya=async(e,t)=>{const n={};for await(const o of e)n[t(o)]=o;return n},Xa=async(e,t)=>{const n={};for await(const o of e)n[await t(o)]=o;return n},Qa=async e=>{const t=new Set;for await(const n of e)t.add(n);return t},Za=(e,t,n)=>n?tc(e,t,n):ec(e,t),ec=(e,t)=>new Un((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))})),tc=(e,t,n)=>new Un((async function*(){const o=[];for(const r of[e,t])for await(const e of r){let t=!1;for(const r of o)if(!0===n(e,r)){t=!0;break}!1===t&&(yield e,o.push(e))}})),nc=(e,t,n)=>new Un((async function*(){const o=[];for(const r of[e,t])for await(const e of r){let t=!1;for(const r of o)if(!0===await n(e,r)){t=!0;break}!1===t&&(yield e,o.push(e))}})),oc=(e,t)=>1===t.length?rc(e,t):sc(e,t),rc=(e,t)=>new Un((async function*(){for await(const n of e)!0===t(n)&&(yield n)})),sc=(e,t)=>new Un((async function*(){let n=0;for await(const o of e)!0===t(o,n++)&&(yield o)})),ic=(e,t)=>1===t.length?ac(e,t):cc(e,t),ac=(e,t)=>new Un((async function*(){for await(const n of e)!0===await t(n)&&(yield n)})),cc=(e,t)=>new Un((async function*(){let n=0;for await(const o of e)!0===await t(o,n++)&&(yield o)})),lc=(e,t,n)=>n?hc(e,t,n):uc(e,t),uc=(e,t)=>new Un((async function*(){const n=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([n.next(),o.next()]);if(e.done||t.done)break;yield[e.value,t.value]}})),hc=(e,t,n)=>new Un((async function*(){const o=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const[e,t]=await Promise.all([o.next(),r.next()]);if(e.done||t.done)break;yield n(e.value,t.value)}})),dc=(e,t,n)=>new Un((async function*(){const o=e[Symbol.asyncIterator](),r=t[Symbol.asyncIterator]();for(;;){const e=await Promise.all([o.next(),r.next()]),t=e[0],s=e[1];if(t.done||s.done)break;yield n(t.value,s.value)}})),fc=(e,t,n,o)=>{if(o){if(!n)throw new ReferenceError("TAccumulate function is undefined");return yc(e,t,n,o)}return n?vc(e,t,n):gc(e,t)},gc=async(e,t)=>{let n;for await(const o of e)n=n?t(n,o):o;if(void 0===n)throw new Ln($n.NoElements);return n},vc=async(e,t,n)=>{let o=t;for await(const t of e)o=n(o,t);return o},yc=async(e,t,n,o)=>{let r=t;for await(const t of e)r=n(r,t);return o(r)},pc=(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 o=0;o<e.length;o++)n[o]=t(e[o]);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),o=new Array(e.length);for(let n=0;n<e.length;n++)o[n]=e[n].then(t);return o},type:1};case 2:return{generator:async()=>{const e=await n.generator(),o=new Array(e.length);for(let n=0;n<e.length;n++)o[n]=e[n].then(t);return o},type:2}}},wc=(e,t)=>{const n=pc(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))}},mc=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),o=new Array(e.length);for(let n=0;n<e.length;n++)o[n]=t(e[n]);return o},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}}},Sc=(e,t)=>{const n=mc(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))}},_c=(e,t)=>t?Ec(e,t):Ac(e),Ac=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}},Ec=async(e,t)=>{const n=pc(e,t);let o;switch(n.type){case 0:return o=await n.generator(),o.includes(!0);case 1:return o=await Promise.all(n.generator()),o.includes(!0);case 2:return o=await Promise.all(await n.generator()),o.includes(!0)}},Cc=async(e,t)=>{const n=mc(e,t);let o;switch(n.type){case 1:return o=n.generator(),0!==o.length&&new Promise(((e,t)=>{let n=0;for(const r of o)r.then((t=>{n++,t?e(!0):n===o.length&&e(!1)}),t)}));case 2:return o=await n.generator(),0===Promise.length?!1:(await Promise.all(o)).includes(!0)}},bc=e=>no((async function*(){for await(const t of e)yield t})),Nc=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)}},Dc=async(e,t)=>{let n;n=t?pc(e,t):e.dataFunc;const o=await Nc(n);if(0===o.length)throw new Ln($n.NoElements);let r=0;for(const e of o)r+=e;return r/o.length},Tc=async(e,t)=>{const n=mc(e,t),o=await Nc(n);if(0===o.length)throw new Ln($n.NoElements);let r=0;for(const e of o)r+=e;return r/o.length},kc=(e,t)=>{if(t<1)throw new Mn("index");let n;switch(e.dataFunc.type){case 1:const o=e.dataFunc.generator;n={type:1,generator:()=>{const e=[];let n=[];for(const r of o())n.push(r),n.length===t&&(e.push(Promise.all(n)),n=[]);return n.length&&e.push(Promise.all(n)),e}};break;case 2:const r=e.dataFunc.generator;n={type:2,generator:async()=>{const e=[];let n=[];for(const o of await r())n.push(o),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 o of await s())n.push(o),n.length===t&&(e.push(n),n=[]);return n.length&&e.push(n),e}}}return new Hn(n)},Ic=(e,t)=>new Hn({generator:async()=>{const[n,o]=await Promise.all([e.toArray(),t.toArray()]);return[...n,...o]},type:0}),Pc=async(e,t,n=Wn)=>{let o;switch(o=pc(e,n?e=>n(t,e):e=>e===t),o.type){case 0:return(await o.generator()).some((e=>e));case 1:return(await Promise.all(o.generator())).some((e=>e));case 2:return(await Promise.all(await o.generator())).some((e=>e))}},Rc=async(e,t,n)=>{const o=mc(e,(e=>n(t,e)));switch(o.type){case 1:return(await Promise.all(o.generator())).some((e=>e));case 2:return(await Promise.all(await o.generator())).some((e=>e))}},Gc=(e,t)=>t?Oc(e,t):Fc(e),Fc=async e=>{const t=e.dataFunc;switch(t.type){case 0:case 2:return(await e.toArray()).length;case 1:return t.generator().length}},Oc=async(e,t)=>{const n=await e.toArray();let o=0;for(let e=0;e<n.length;e++)!0===t(n[e])&&o++;return o},xc=async(e,t)=>{const n=mc(e,t);let o;switch(n.type){case 1:o=Promise.all(n.generator());break;case 2:o=Promise.all(await n.generator())}let r=0;for(const e of await o)e&&r++;return r},Mc=(e,t)=>{const n=e.dataFunc,o=t instanceof Promise;let r;switch(n.type){case 0:r={generator:()=>n.generator().then((e=>e.length?e:o?t.then((e=>[e])):[t])),type:n.type};break;case 1:r={generator:()=>{const e=n.generator();return e.length?e:o?[t]:[Promise.resolve(t)]},type:n.type};break;case 2:r={generator:async()=>{const e=await n.generator();return e.length?e:o?[t]:[Promise.resolve(t)]},type:n.type}}return new Hn(r)},$c=(e,t=Wn)=>new Hn({generator:async()=>{const n=[];for(const o of await e.toArray())n.find((e=>t(e,o)))||n.push(o);return n},type:0}),Lc=(e,t)=>new Hn({generator:async()=>{const n=[];e:for(const o of await e.toArray()){for(const e of n)if(await t(e,o))continue e;n.push(o)}return n},type:0}),Wc=(e,t)=>new Hn(pc(e,(e=>(t(e),e)))),Bc=(e,t)=>{const n=mc(e,(async e=>(await t(e),e)));return new Hn(n)},Uc=async(e,t)=>{if(t<0)throw new Mn("index");const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();if(t>=e.length)throw new Mn("index");return e[t]}case 1:{const e=n.generator();if(t>=e.length)throw new Mn("index");return await e[t]}case 2:{const e=await n.generator();if(t>=e.length)throw new Mn("index");return await e[t]}}},Hc=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]}}},jc=(e,t,n=Wn)=>new Hn({generator:async()=>{const[o,r]=await Promise.all([e.toArray(),t.toArray()]),s=[];for(const e of o){let t=!1;for(let o=0;o<r.length;o++){const s=r[o];if(!0===n(e,s)){t=!0;break}}!1===t&&s.push(e)}return s},type:0}),zc=(e,t,n)=>new Hn({generator:async()=>{const[o,r]=await Promise.all([e.toArray(),t.toArray()]),s=[];for(const e of o){let t=!1;for(let o=0;o<r.length;o++){const s=r[o];if(!0===await n(e,s)){t=!0;break}}!1===t&&s.push(e)}return s},type:0}),Kc=e=>Nc(e.dataFunc),qc=(e,t)=>t?Jc(e,t):Vc(e),Vc=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new Ln($n.NoElements);return e[0]}case 1:{const e=t.generator();if(0===e.length)throw new Ln($n.NoElements);return await e[0]}case 2:{const e=await t.generator();if(0===e.length)throw new Ln($n.NoElements);return await e[0]}}},Jc=async(e,t)=>{const n=await Kc(e);for(const e of n)if(!0===t(e))return e;throw new Ln($n.NoMatch)},Yc=async(e,t)=>{const n=await Kc(e);for(const e of n)if(!0===await t(e))return e;throw new Ln($n.NoMatch)},Xc=(e,t)=>t?Zc(e,t):Qc(e),Qc=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]}}},Zc=async(e,t)=>{const n=await Kc(e);for(const e of n)if(!0===t(e))return e;return null},el=async(e,t)=>{const n=await Kc(e);for(const e of n)if(!0===await t(e))return e;return null},tl=(e,t,n)=>n?ol(e,t,n):nl(e,t),nl=(e,t)=>new Hn({generator:async()=>{const n={};for(const o of await e.toArray()){const e=t(o),r=n[e];r?r.push(o):n[e]=new Fo(e,o)}const o=new Array;for(const e in n)o.push(n[e]);return o},type:0}),ol=(e,t,n)=>new Hn({generator:async()=>{const o=new Array;for(const r of await e.toArray()){const e=t(r);let s=!1;for(let t=0;t<o.length;t++){const i=o[t];if(n(i.key,e)){i.push(r),s=!0;break}}!1===s&&o.push(new Fo(e,r))}const r=new Array;for(const e of o)r.push(e);return r},type:0}),rl=(e,t,n)=>n?sl(e,t,n):il(e,t),sl=(e,t,n)=>new Hn({generator:async()=>{const o=mc(e,(async e=>[await t(e),e]));let r;switch(o.type){case 1:r=await Promise.all(o.generator());break;case 2:r=await Promise.all(await o.generator())}const s=new Array;for(const[e,t]of r){let o=!1;for(let r=0;r<s.length;r++){const i=s[r];if(!0===await n(i.key,e)){i.push(t),o=!0;break}}!1===o&&s.push(new Fo(e,t))}const i=new Array;for(const e of s)i.push(e);return i},type:0}),il=(e,t)=>new Hn({generator:async()=>{const n=mc(e,(async e=>[await t(e),e]));let o;switch(n.type){case 1:o=await Promise.all(n.generator());break;case 2:o=await Promise.all(await n.generator())}const r={};for(const[e,t]of o){const n=r[e];n?n.push(t):r[e]=new Fo(e,t)}const s=new Array;for(const e in r)s.push(r[e]);return s},type:0}),al=(e,t,n,o)=>o?cl(e,t,n,o):ll(e,t,n),cl=(e,t,n,o)=>new Hn({generator:async()=>{const r=new Array;for await(const s of e){const e=t(s);let i=!1;for(let t=0;t<r.length;t++){const a=r[t];if(o(a.key,e)){a.push(n(s)),i=!0;break}}if(!1===i){const t=n(s);r.push(new Fo(e,t))}}const s=new Array;for(const e of r)s.push(e);return s},type:0}),ll=(e,t,n)=>new Hn({generator:async()=>{const o={};for(const r of await e.toArray()){const e=t(r),s=o[e],i=n(r);s?s.push(i):o[e]=new Fo(e,i)}const r=new Array;for(const e in o)r.push(o[e]);return r},type:0}),ul=(e,t,n,o,r,s)=>{const i=s?hl(e,t,n,o,r,s):dl(e,t,n,o,r);return new Hn({generator:i,type:0})},hl=(e,t,n,o,r,s)=>async()=>{const i=[];for await(const e of t){const t=o(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=>{var t;const o=n(e),a=null!==(t=i.find((e=>s(e.key,o))))&&void 0!==t?t:{key:o,values:[]};return r(e,a.values)}))},dl=(e,t,n,o,r)=>async()=>{const s=new Map;for await(const e of t){const t=o(e),n=s.get(t);n?n.push(e):s.set(t,[e])}return(await e.toArray()).map((e=>{var t;const o=n(e),i=null!==(t=s.get(o))&&void 0!==t?t:[];return r(e,i)}))},fl=(e,t,n,o,r,s)=>{const i=s?gl(e,t,n,o,r,s):vl(e,t,n,o,r);return new Hn({generator:i,type:0})},gl=(e,t,n,o,r,s)=>async()=>{const i=[];for await(const e of t){const t=await o(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=>{var t;const o=await n(e),a=null!==(t=i.find((e=>s(e.key,o))))&&void 0!==t?t:{key:o,values:[]};return r(e,a.values)}));return await Promise.all(a)},vl=(e,t,n,o,r)=>async()=>{const s=new Map;for await(const e of t){const t=await o(e),n=s.get(t);n?n.push(e):s.set(t,[e])}const i=(await e.toArray()).map((async e=>{var t;const o=await n(e),i=null!==(t=s.get(o))&&void 0!==t?t:[];return r(e,i)}));return await Promise.all(i)},yl=(e,t,n=Wn)=>new Hn({generator:async()=>{const o=await e.distinct(n).toArray();if(0===o.length)return[];const r=await t.toArray(),s=new Array;for(let e=0;e<o.length;e++){const t=o[e];for(let e=0;e<r.length;e++){const o=r[e];if(!0===n(t,o)){s.push(t);break}}}return s},type:0}),pl=(e,t,n)=>new Hn({generator:async()=>{const o=await e.distinctAsync(n).toArray();if(0===o.length)return[];const r=await t.toArray(),s=new Array;for(let e=0;e<o.length;e++){const t=o[e];for(let e=0;e<r.length;e++){const o=r[e];if(!0===await n(t,o)){s.push(t);break}}}return s},type:0}),wl=(e,t,n,o,r,s=Wn)=>new Hn({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=o(n);!0===s(t,i)&&c.push(r(e,n))}}return c},type:0}),ml=(e,t)=>t?_l(e,t):Sl(e),Sl=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new Ln($n.NoElements);return e[e.length-1]}case 1:{const e=t.generator();if(0===e.length)throw new Ln($n.NoElements);return await e[e.length-1]}case 2:{const e=await t.generator();if(0===e.length)throw new Ln($n.NoElements);return await e[e.length-1]}}},_l=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 o=e[n];if(t(o))return o}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(t(o))return o}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(t(o))return o}break}}throw new Ln($n.NoMatch)},Al=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 o=e[n];if(!0===await t(o))return o}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(!0===await t(o))return o}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(!0===await t(o))return o}break}}throw new Ln($n.NoMatch)},El=(e,t)=>t?bl(e,t):Cl(e),Cl=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]}}},bl=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 o=e[n];if(t(o))return o}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(t(o))return o}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(t(o))return o}break}}return null},Nl=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 o=e[n];if(!0===await t(o))return o}break}case 1:{const e=n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(!0===await t(o))return o}break}case 2:{const e=await n.generator();for(let n=e.length-1;n>=0;n--){const o=await e[n];if(!0===await t(o))return o}break}}return null},Dl=async(e,t)=>{let n;n=t?pc(e,t):e.dataFunc;const o=await Nc(n);if(0===o.length)throw new Ln($n.NoElements);return Math.max.apply(null,o)},Tl=async(e,t)=>{const n=mc(e,t),o=await Nc(n);if(0===o.length)throw new Ln($n.NoElements);return Math.max.apply(null,o)},kl=async(e,t)=>{let n;n=t?pc(e,t):e.dataFunc;const o=await Nc(n);if(0===o.length)throw new Ln($n.NoElements);return Math.min.apply(null,o)},Il=async(e,t)=>{const n=mc(e,t),o=await Nc(n);if(0===o.length)throw new Ln($n.NoElements);return Math.min.apply(null,o)},Pl=(e,t)=>{const n="string"==typeof t?e=>[typeof e===t,e]:e=>[e instanceof t,e];return new Hn({generator:async()=>{const t=pc(e,n),o=await Nc(t),r=[];for(const[e,t]of o)e&&r.push(t);return r},type:0})};async function*Rl(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for(const o of e){const e=await t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}async function*Gl(e,t,n,o){const r=((e,t)=>{const n=new Map;for(const o of e){const e=t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}class Fl extends Hn{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,o){let r;return r=e instanceof Fl?async function*(){for await(const r of e.orderedPairs())yield*Rl(r,t,n,o)}:()=>async function*(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for await(const o of e){const e=await t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}(e,t,n,o),new Fl(r)}static generate(e,t,n,o){let r;return r=e instanceof Fl?async function*(){for await(const r of e.orderedPairs())yield*Gl(r,t,n,o)}:()=>async function*(e,t,n,o){const r=await(async(e,t)=>{const n=new Map;for await(const o of e){const e=t(o),r=n.get(e);r?r.push(o):n.set(e,[o])}return n})(e,t),s=[...r.keys()].sort(o||void 0);if(n)for(let e=0;e<s.length;e++)yield r.get(s[e]);else for(let e=s.length-1;e>=0;e--)yield r.get(s[e])}(e,t,n,o),new Fl(r)}thenBy(e,t){return Fl.generate(this,e,!0,t)}thenByAsync(e,t){return Fl.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Fl.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Fl.generateAsync(this,e,!1,t)}}const Ol=(e,t,n)=>Fl.generate(e,t,!0,n),xl=(e,t,n)=>Fl.generateAsync(e,t,!0,n),Ml=(e,t,n)=>Fl.generate(e,t,!1,n),$l=(e,t,n)=>Fl.generateAsync(e,t,!1,n),Ll=async(e,t)=>{const n=pc(e,(e=>[t(e),e])),o=await Nc(n),r=[],s=[];for(const[e,t]of o)e?s.push(t):r.push(t);return[s,r]},Wl=async(e,t)=>{const n=mc(e,(async e=>[await t(e),e])),o=await Nc(n),r=[],s=[];for(const[e,t]of o)e?s.push(t):r.push(t);return[s,r]},Bl=e=>{const t=e.dataFunc;switch(t.type){case 1:return new Hn({generator:()=>t.generator().reverse(),type:t.type});case 2:case 0:return new Hn({generator:async()=>(await t.generator()).reverse(),type:t.type})}},Ul=(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 o=0;o<e.length;o++)n[o]=t(e[o],o);return n})),type:0};case 1:return{generator:()=>{const e=n.generator(),o=new Array(e.length);for(let n=0;n<e.length;n++)o[n]=e[n].then((e=>t(e,n)));return o},type:1};case 2:return{generator:async()=>{const e=await n.generator(),o=new Array(e.length);for(let n=0;n<e.length;n++)o[n]=e[n].then((e=>t(e,n)));return o},type:2}}},Hl=(e,t)=>"function"==typeof t?1===t.length?new Hn(pc(e,t)):new Hn(Ul(e,t)):new Hn(pc(e,(e=>e[t]))),jl=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return{generator:async()=>{const e=await n.generator(),o=new Array(e.length);for(let n=0;n<e.length;n++)o[n]=t(e[n],n);return o},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}}},zl=(e,t)=>{let n;return n="function"==typeof t?1===t.length?mc(e,t):jl(e,t):mc(e,(e=>e[t])),new Hn(n)},Kl=(e,t)=>new Hn({generator:async()=>{let n;n="function"==typeof t?1===t.length?pc(e,t):Ul(e,t):pc(e,(e=>e[t]));const o=[];switch(n.type){case 0:for(const e of await n.generator())for(const t of e)o.push(t);break;case 1:for(const e of n.generator())for(const t of await e)o.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)o.push(t)}return o},type:0}),ql=(e,t)=>new Hn({generator:async()=>{let n;n=1===t.length?mc(e,t):jl(e,t);const o=[];switch(n.type){case 1:for(const e of n.generator())for(const t of await e)o.push(t);break;case 2:for(const e of await n.generator())for(const t of await e)o.push(t)}return o},type:0}),Vl=async(e,t,n=Wn)=>{const o=await e.toArray(),r=await t.toArray();if(o.length!==r.length)return!1;for(let e=0;e<o.length;e++)if(!1===n(o[e],r[e]))return!1;return!0},Jl=async(e,t,n)=>{const o=await e.toArray(),r=await t.toArray();if(o.length!==r.length)return!1;for(let e=0;e<o.length;e++){const t=o[e],s=r[e];if(!1===await n(t,s))return!1}return!0},Yl=(e,t)=>t?Ql(e,t):Xl(e),Xl=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new Ln($n.MoreThanOneElement);if(0===e.length)throw new Ln($n.NoElements);return e[0]}case 1:{const e=t.generator();if(e.length>1)throw new Ln($n.MoreThanOneElement);if(0===e.length)throw new Ln($n.NoElements);return e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new Ln($n.MoreThanOneElement);if(0===e.length)throw new Ln($n.NoElements);return await e[0]}}},Ql=async(e,t)=>{const n=await Kc(e);let o=!1,r=null;for(const e of n)if(t(e)){if(!0===o)throw new Ln($n.MoreThanOneMatchingElement);o=!0,r=e}if(!1===o)throw new Ln($n.NoMatch);return r},Zl=async(e,t)=>{const n=await Kc(e);let o=!1,r=null;for(const e of n)if(!0===await t(e)){if(!0===o)throw new Ln($n.MoreThanOneMatchingElement);o=!0,r=e}if(!1===o)throw new Ln($n.NoMatch);return r},eu=(e,t)=>t?nu(e,t):tu(e),tu=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new Ln($n.MoreThanOneElement);return 0===e.length?null:e[0]}case 1:{const e=t.generator();if(e.length>1)throw new Ln($n.MoreThanOneElement);return 0===e.length?null:e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new Ln($n.MoreThanOneElement);return 0===e.length?null:await e[0]}}},nu=async(e,t)=>{const n=await Kc(e);let o=!1,r=null;for(const e of n)if(t(e)){if(!0===o)throw new Ln($n.MoreThanOneElement);o=!0,r=e}return r},ou=async(e,t)=>{const n=await Kc(e);let o=!1,r=null;for(const e of n)if(!0===await t(e)){if(!0===o)throw new Ln($n.MoreThanOneElement);o=!0,r=e}return r},ru=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return new Hn({generator:async()=>(await n.generator()).slice(t),type:0});case 1:return new Hn({generator:()=>n.generator().slice(t),type:1});case 2:return new Hn({generator:async()=>(await n.generator()).slice(t),type:2})}},su=(e,t)=>new Hn({generator:async()=>{const n=await e.toArray();let o=0;for(;o<n.length;o++){const e=n[o];if(!1===t(e,o))break}const r=[];for(;o<n.length;o++)r.push(n[o]);return r},type:0}),iu=(e,t)=>new Hn({generator:async()=>{const n=await e.toArray();let o=0;for(;o<n.length;o++){const e=n[o];if(!1===await t(e,o))break}const r=[];for(;o<n.length;o++)r.push(n[o]);return r},type:0}),au=(e,t)=>t?lu(e,t):cu(e),cu=async e=>{let t=0;for(const n of await e.toArray())t+=n;return t},lu=async(e,t)=>{let n=0;for(const o of await e.toArray())n+=t(o);return n},uu=async(e,t)=>{const n=mc(e,t),o=await Nc(n);let r=0;for(const e of o)r+=e;return r},hu=(e,t)=>{const n=t>0?t:0,o=e.dataFunc;switch(o.type){case 1:return new Hn({generator:()=>o.generator().splice(0,n),type:1});case 2:return new Hn({generator:()=>o.generator().then((e=>e.splice(0,n))),type:2});default:return new Hn({generator:()=>o.generator().then((e=>e.splice(0,n))),type:0})}},du=(e,t)=>new Hn({generator:async()=>{const n=await e.toArray(),o=new Array;if(1===t.length)for(const e of n){if(!0!==t(e))break;o.push(e)}else for(let e=0;e<n.length;e++){const r=n[e];if(!0!==t(r,e))break;o.push(r)}return o},type:0}),fu=(e,t)=>new Hn({generator:async()=>{const n=await e.toArray(),o=new Array;if(1===t.length){const e=t;for(const t of n){if(!0!==await e(t))break;o.push(t)}}else for(let e=0;e<n.length;e++){const r=n[e];if(!0!==await t(r,e))break;o.push(r)}return o},type:0}),gu=async(e,t)=>{const n=new Map,o=pc(e,(e=>[t(e),e])),r=await Nc(o);for(const[e,t]of r){const o=n.get(e);void 0===o?n.set(e,[t]):o.push(t)}return n},vu=async(e,t)=>{const n=new Map,o=mc(e,(async e=>[await t(e),e])),r=await Nc(o);for(const[e,t]of r){const o=n.get(e);void 0===o?n.set(e,[t]):o.push(t)}return n},yu=async(e,t)=>{const n=e.dataFunc,o=await Nc(n),r={};for(const e of o)r[t(e)]=e;return r},pu=async(e,t)=>{const n=mc(e,(async e=>[await t(e),e])),o=await Nc(n),r={};for(const[e,t]of o)r[e]=t;return r},wu=async e=>{const t=e.dataFunc,n=await Nc(t);return new Set(n)},mu=(e,t,n)=>n?_u(e,t,n):Su(e,t),Su=(e,t)=>new Hn({generator:async()=>{const n=new Set,o=t.toArray();for await(const t of e)!1===n.has(t)&&n.add(t);const r=await o;for(const e of r)!1===n.has(e)&&n.add(e);return[...n.keys()]},type:0}),_u=(e,t,n)=>new Hn({generator:async()=>{const o=[],r=await Promise.all([e.toArray(),t.toArray()]);for(const e of r)for(const t of e){let e=!1;for(const r of o)if(!0===n(t,r)){e=!0;break}!1===e&&o.push(t)}return o},type:0}),Au=(e,t,n)=>new Hn({generator:async()=>{const o=[],r=await Promise.all([e.toArray(),t.toArray()]);for(const e of r)for(const t of e){let e=!1;for(const r of o)if(!0===await n(t,r)){e=!0;break}!1===e&&o.push(t)}return o},type:0}),Eu=(e,t)=>new Hn({generator:async()=>(await e.toArray()).filter(t),type:0}),Cu=(e,t)=>new Hn({generator:async()=>{const n=jl(e,(async(e,n)=>[await t(e,n),e])),o=await Nc(n),r=[];for(const[e,t]of o)e&&r.push(t);return r},type:0}),bu=(e,t,n)=>n?Du(e,t,n):Nu(e,t),Nu=(e,t)=>new Hn({generator:async()=>{const[n,o]=await Promise.all([e.toArray(),t.toArray()]),r=n.length<o.length?n.length:o.length,s=new Array(r);for(let e=0;e<r;e++){const t=n[e],r=o[e];s[e]=[t,r]}return s},type:0}),Du=(e,t,n)=>new Hn({generator:async()=>{const[o,r]=await Promise.all([e.toArray(),t.toArray()]),s=o.length<r.length?o.length:r.length,i=new Array(s);for(let e=0;e<s;e++){const t=o[e],s=r[e];i[e]=n(t,s)}return i},type:0}),Tu=(e,t,n)=>new Hn({generator:async()=>{const[o,r]=await Promise.all([e.toArray(),t.toArray()]),s=o.length<r.length?o.length:r.length,i=new Array(s);for(let e=0;e<s;e++){const t=o[e],s=r[e];i[e]=n(t,s)}return Promise.all(i)},type:0});Fs(jn),(e=>{const t=e.prototype,n=(e,n)=>{const o=function(...t){return e(this,...t)};Object.defineProperty(o,"length",{value:e.length-1}),t[n]=o};n(Os,"aggregate"),n(Ls,"all"),n(Ws,"allAsync"),n(Bs,"any"),n(js,"anyAsync"),n(zs,"asParallel"),n(Ks,"average"),n(qs,"averageAsync"),n(Vs,"chunk"),n(Js,"concatenate"),n(Ys,"contains"),n(Xs,"containsAsync"),n(Qs,"count"),n(ti,"countAsync"),n(ni,"defaultIfEmpty"),n(oi,"distinct"),n(ri,"distinctAsync"),n(si,"each"),n(ii,"eachAsync"),n(ai,"elementAt"),n(ci,"elementAtOrDefault"),n(li,"except"),n(ui,"exceptAsync"),n(hi,"first"),n(gi,"firstAsync"),n(vi,"firstOrDefault"),n(wi,"firstOrDefaultAsync"),n(mi,"groupBy"),n(Ai,"groupByAsync"),n(bi,"groupByWithSel"),n(Ti,"groupJoin"),n(Pi,"groupJoinAsync"),n(Fi,"intersect"),n(Oi,"intersectAsync"),n(xi,"joinByKey"),n(Mi,"last"),n(Wi,"lastAsync"),n(Bi,"lastOrDefault"),n(ji,"lastOrDefaultAsync"),n(zi,"max"),n(Vi,"maxAsync"),n(Ji,"min"),n(Qi,"minAsync"),n(Zi,"ofType"),n(ea,"orderBy"),n(ta,"orderByAsync"),n(na,"orderByDescending"),n(oa,"orderByDescendingAsync"),n(ra,"partition"),n(sa,"partitionAsync"),n(ia,"reverse"),n(aa,"select"),n(ha,"selectAsync"),n(ga,"selectMany"),n(wa,"selectManyAsync"),n(ma,"sequenceEquals"),n(Sa,"sequenceEqualsAsync"),n(_a,"single"),n(Ca,"singleAsync"),n(ba,"singleOrDefault"),n(Ta,"singleOrDefaultAsync"),n(ka,"skip"),n(Ia,"skipWhile"),n(Ga,"skipWhileAsync"),n(xa,"sum"),n(La,"sumAsync"),n(Wa,"take"),n(Ba,"takeWhile"),n(ja,"takeWhileAsync"),n(qa,"toArray"),n(Va,"toMap"),n(Ja,"toMapAsync"),n(Ya,"toObject"),n(Xa,"toObjectAsync"),n(Qa,"toSet"),n(Za,"union"),n(nc,"unionAsync"),n(oc,"where"),n(ic,"whereAsync"),n(lc,"zip"),n(dc,"zipAsync")})(Un),(e=>{const t=e.prototype,n=(e,n)=>{const o=function(...t){return e(this,...t)};Object.defineProperty(o,"length",{value:e.length-1}),t[n]=o};n(fc,"aggregate"),n(wc,"all"),n(Sc,"allAsync"),n(_c,"any"),n(Cc,"anyAsync"),n(bc,"asAsync"),n(Dc,"average"),n(Tc,"averageAsync"),n(kc,"chunk"),n(Ic,"concatenate"),n(Pc,"contains"),n(Rc,"containsAsync"),n(Gc,"count"),n(xc,"countAsync"),n(Mc,"defaultIfEmpty"),n($c,"distinct"),n(Lc,"distinctAsync"),n(Wc,"each"),n(Bc,"eachAsync"),n(Uc,"elementAt"),n(Hc,"elementAtOrDefault"),n(jc,"except"),n(zc,"exceptAsync"),n(qc,"first"),n(Yc,"firstAsync"),n(Xc,"firstOrDefault"),n(el,"firstOrDefaultAsync"),n(tl,"groupBy"),n(rl,"groupByAsync"),n(al,"groupByWithSel"),n(ul,"groupJoin"),n(fl,"groupJoinAsync"),n(ul,"groupJoin"),n(fl,"groupJoinAsync"),n(yl,"intersect"),n(pl,"intersectAsync"),n(wl,"joinByKey"),n(ml,"last"),n(Al,"lastAsync"),n(El,"lastOrDefault"),n(Nl,"lastOrDefaultAsync"),n(Dl,"max"),n(Tl,"maxAsync"),n(kl,"min"),n(Il,"minAsync"),n(Pl,"ofType"),n(Ol,"orderBy"),n(xl,"orderByAsync"),n(Ml,"orderByDescending"),n($l,"orderByDescendingAsync"),n(Ll,"partition"),n(Wl,"partitionAsync"),n(Bl,"reverse"),n(Hl,"select"),n(zl,"selectAsync"),n(Kl,"selectMany"),n(ql,"selectManyAsync"),n(Vl,"sequenceEquals"),n(Jl,"sequenceEqualsAsync"),n(Yl,"single"),n(Zl,"singleAsync"),n(eu,"singleOrDefault"),n(ou,"singleOrDefaultAsync"),n(ru,"skip"),n(su,"skipWhile"),n(iu,"skipWhileAsync"),n(au,"sum"),n(uu,"sumAsync"),n(hu,"take"),n(du,"takeWhile"),n(fu,"takeWhileAsync"),n(Kc,"toArray"),n(gu,"toMap"),n(vu,"toMapAsync"),n(yu,"toObject"),n(pu,"toObjectAsync"),n(wu,"toSet"),n(mu,"union"),n(Au,"unionAsync"),n(Eu,"where"),n(Cu,"whereAsync"),n(bu,"zip"),n(Tu,"zipAsync")})(Hn),(()=>{var e;const{prototype:t}=Bn,n=Object.getOwnPropertyNames(jn.prototype);for(const o of n)t[o]=null!==(e=t[o])&&void 0!==e?e:jn.prototype[o];t.all=function(e){return this.every(e)},t.any=function(e){return e?this.some(e):0!==this.length},t.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},t.elementAt=function(e){if(e<0||e>=this.length)throw new Mn("index");return this[e]},t.elementAtOrDefault=function(e){return this[e]||null},t.first=function(e){if(e){const t=this.find(e);if(void 0===t)throw new Ln($n.NoMatch);return t}if(0===this.length)throw new Ln($n.NoElements);return this[0]},t.firstOrDefault=function(e){if(e){const t=this.find(e);return void 0===t?null:t}return 0===this.length?null:this[0]},t.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 Ln($n.NoMatch)}if(0===this.length)throw new Ln($n.NoElements);return this[this.length-1]},t.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]},t.max=function(e){if(0===this.length)throw new Ln($n.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)},t.min=function(e){if(0===this.length)throw new Ln($n.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)},t.reverse=function(){return Array.prototype.reverse.apply(this),this}})();var ku;!function(e){e.Success="Success",e.NoPermissions="NoPermissions",e.NameToShort="NameToShort",e.NameAlreadyExists="NameAlreadyExists",e.OtherError="OtherError",e.UnknownError="UnknownError"}(ku||(ku={}));class Iu{constructor(){this._guid="",this._name=""}GetDevicesChannelsInGroupAsync(){return e=this,t=void 0,o=function*(){let e=[];for(let t of yield Hu.Get(yn.ServiceName).GetDevicesAsync())for(let n of t.Channels.where((e=>e.ChannelGroups.any((e=>e===this._guid)))))e.push(n);return e},new((n=void 0)||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}));var e,t,n,o}get Guid(){return this._guid}set Guid(e){this._guid=e}get Name(){return this._name}set Name(e){this._name=e}ChangeNameAsync(e){return Hu.Get(Ru.ServiceName).ChangeGroupNameAsync(this,e)}}var Pu=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Ru{constructor(){this._connection=null,this._synchronized=!1,this._synchronizationTaskCompletionSource=null,this._groups=[],this._connection=Hu.Get(Ie.ServiceName),this._synchronizationTaskCompletionSource=new Promise((e=>{Hu.Get(Se.ServiceName).OnUserLoggedInEvent().Subscribe((t=>Pu(this,void 0,void 0,(function*(){yield this.SyncGroups(),e(),this._synchronized=!0}))))}))}SyncGroups(){return Pu(this,void 0,void 0,(function*(){this._groups=yield this.GetGroupsAsync()}))}AddDeviceChannelToGroupByGuidAsync(e,t){var n,o;return Pu(this,void 0,void 0,(function*(){const r=new xu;if(r.Data.Channel=e.Number,null==e.GetDevice())throw new Error("Device is not set on this channel!");r.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,r.Data.GroupGuid=t;const s=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(r,15e3,!1);return Hu.Get(Te.ServiceName).ClearCache(),null!=s&&null!=s.Status?(s.Status==re.OK&&e.ChannelGroups.push(t),s.Status):re.Error}))}RemoveDeviceChannelFromGroupByGuidAsync(e,t){var n,o;return Pu(this,void 0,void 0,(function*(){const r=new Mu;if(null==e.GetDevice())throw new Error("Device is not set on this channel!");r.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,r.Data.Channel=e.Number,r.Data.GroupGuid=t;const s=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(r,15e3,!1);return Hu.Get(Te.ServiceName).ClearCache(),null!=s&&null!=s.Status?(s.Status==re.OK&&(e.ChannelGroups=e.ChannelGroups.where((e=>e!=t)).toArray()),s.Status):re.Error}))}UpsertGroupWithDevicesChannelsAsync(e,t){return Pu(this,void 0,void 0,(function*(){if(this._groups.all((t=>t.Guid!=e.Guid))){let t=yield this.AddNewGroupAsync(e.Name);if(!(t instanceof Iu))return t instanceof tn?t:new tn(ku.UnknownError,"");e=t}for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e.Guid))))){let t=yield this.AddDeviceChannelToGroupAsync(n,e);if(t!==re.OK)return Hu.Get(o.ServiceName).Error(Ru.ServiceName,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`),new tn(ku.UnknownError,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`)}let n=yield Hu.Get(yn.ServiceName).GetDevicesAsync();for(let s of n)for(let n of s.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var r of n.ChannelGroups.where((t=>e.Guid==t))){let t=yield this.RemoveDeviceChannelFromGroupAsync(n,e);if(t!==re.OK)return Hu.Get(o.ServiceName).Error(Ru.ServiceName,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`),new tn(ku.UnknownError,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`)}return e}))}UpdateGroupWithDevicesChannelsAsync(e,t){return Pu(this,void 0,void 0,(function*(){for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e))))){let t=yield this.AddDeviceChannelToGroupByGuidAsync(n,e);if(t!==re.OK)return Hu.Get(o.ServiceName).Error(Ru.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),re.FatalError}let n=yield Hu.Get(yn.ServiceName).GetDevicesAsync();for(let s of n)for(let n of s.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var r of n.ChannelGroups.where((t=>e==t))){let t=yield this.RemoveDeviceChannelFromGroupByGuidAsync(n,e);if(t!==re.OK)return Hu.Get(o.ServiceName).Error(Ru.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),re.FatalError}return re.OK}))}ChangeGroupNameByGuidAsync(e,t){var n,o;return Pu(this,void 0,void 0,(function*(){let r=new Ou,s=new $u;s.Guid=e,s.Name=t,null===(n=r.Data)||void 0===n||n.push(s);const i=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(r,15e3,!1);if(Hu.Get(Te.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),null!=i&&null!=i.Status)switch(i.Status){case re.OK:return new tn(ku.Success,"");case re.WrongData:switch(i.Data){case"NameToShort":return new tn(ku.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new tn(ku.NameAlreadyExists,"Group with this name already exists");default:return new tn(ku.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}default:return new tn(ku.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}return new tn(ku.UnknownError,"")}))}GetServiceName(){return Ru.ServiceName}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}GetGroupByGuid(e){return this._groups.first((t=>t.Guid===e))}ChangeGroupNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}RemoveGroupAsync(e){return this.RemoveGroupByGuidAsync(e.Guid)}RemoveGroupByGuidAsync(e){var t;return Pu(this,void 0,void 0,(function*(){let n=new Gu;n.Data=e;const o=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,15e3,!1);Hu.Get(Te.ServiceName).ClearCache(),yield this.SyncGroups();for(let t of yield Hu.Get(yn.ServiceName).GetDevicesAsync())for(let n of t.Channels)n.ChannelGroups.any((t=>t===e))&&(n.ChannelGroups=n.ChannelGroups.except(e,((e,t)=>e===t)).toArray());return null!=o&&null!=o.Status?null==o?void 0:o.Status:re.Error}))}GetGroupsAsync(){var e,t;return Pu(this,void 0,void 0,(function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Fu,15e3,!1);let r=[];if((null==n?void 0:n.Status)===re.OK){let e=Hu.Get(o.ServiceName);return null===(t=n.Data)||void 0===t||t.forEach((t=>{let n=new Iu;n.Guid=t.Guid,n.Name=t.Name,e.Info(Ru.ServiceName,`Got group: ${t.Name} ${t.Guid}`),r.push(n)})),r}throw new Error(`Failed to get groups, API responded with status ${null==n?void 0:n.Status} data: ${null==n?void 0:n.Data}`)}))}AddDeviceChannelToGroupAsync(e,t){return this.AddDeviceChannelToGroupByGuidAsync(e,t.Guid)}RemoveDeviceChannelFromGroupAsync(e,t){return this.RemoveDeviceChannelFromGroupByGuidAsync(e,t.Guid)}AddNewGroupAsync(e){var t,n;return Pu(this,void 0,void 0,(function*(){let o=new Ou,r=new $u;r.Name=e,null===(t=o.Data)||void 0===t||t.push(r);const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(o,15e3,!1);if(Hu.Get(Te.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),null!=s&&null!=s.Status)switch(s.Status){case re.OK:return this._groups.first((t=>t.Name===e));case re.WrongData:switch(s.Data){case"NameToShort":return new tn(ku.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new tn(ku.NameAlreadyExists,"Group with this name already exists");default:return new tn(ku.OtherError,`Response error: ${s.Status} data: ${s.Data}`)}default:return new tn(ku.OtherError,`Response error: ${s.Status} data: ${s.Data}`)}return new tn(ku.UnknownError,"")}))}}Ru.ServiceName="ChannelsGroupsService";class Gu extends oe{constructor(){super(),this.Resource="/devices/groups/group",this.Method=se.Delete}}class Fu extends oe{constructor(){super(),this.Resource="/devices/groups/",this.Method=se.Get}}class Ou extends oe{constructor(){super(),this.Resource="/devices/groups/group",this.Method=se.Put,this.Data=[]}}class xu extends oe{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=se.Put,this.Data=new Lu}}class Mu extends oe{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=se.Delete,this.Data=new Lu}}class $u{constructor(){this.Id=0,this.Guid="",this.Name=""}}class Lu{constructor(){this.GroupGuid="",this.DeviceGuid="",this.Channel=0}}class Wu{constructor(){this._promise=Promise.resolve(),this._disable=()=>{}}Lock(){this._promise=new Promise((e=>this._disable=e))}Unlock(){this._disable()}WaitForLockAsync(){return this._promise}}var Bu;class Uu{constructor(){this._syncLock=new Wu,this._isInFouces=!0,this._canHibernate=!0,this._returnedFromSuspension=!1,this._onReturnedFromSuspensionEvent=new pe,this._onSuspendedEvent=new pe,this._onEnterLowPowerModeEvent=new pe,this._onExitLowPowerModeEvent=new pe,this._onBackButtonPressedEvent=new pe,this._onForwardButtonPressedEvent=new pe}_constructor(){null==navigator.userAgent.match(/Safari/i)||navigator.mediaDevices?window.addEventListener("visibilitychange",(()=>{return e=this,t=void 0,o=function*(){yield this._syncLock.WaitForLockAsync(),this._syncLock.Lock(),this.IsHidden()?this.Suspend():this.ReturnFromSuspension(),this._syncLock.Unlock()},new((n=void 0)||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}));var e,t,n,o})):(window.addEventListener("onblur",(()=>{this._isInFouces&&(this._isInFouces=!1,this.Suspend())})),window.addEventListener("onfocus",(()=>{this._isInFouces||(this._isInFouces=!0,this.ReturnFromSuspension())})))}Suspend(){var e;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!1,this._onSuspendedEvent.Invoke(),null===(e=r.Log)||void 0===e||e.Warning(Uu.ServiceName,"App switched to background"))}ReturnFromSuspension(){var e;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!0,this._onReturnedFromSuspensionEvent.Invoke(),null===(e=r.Log)||void 0===e||e.Warning(Uu.ServiceName,"App switched to foreground"))}EnterLowPowerMode(){this._onEnterLowPowerModeEvent.Invoke()}ExitLowPowerMode(){this._onExitLowPowerModeEvent.Invoke()}IsWorkingInWebView(){return null!=navigator.userAgent.match(/Safari/i)?!navigator.mediaDevices:!!window.hasOwnProperty("Android ")}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 Uu.ServiceName}}Uu.ServiceName="AppStateService",Fs(Map),Fs(Set),(()=>{var e;const t=String.prototype,n=Object.getOwnPropertyNames(jn.prototype);for(const o of n)t[o]=null!==(e=t[o])&&void 0!==e?e:jn.prototype[o];t.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 Ln($n.NoMatch)}if(0===this.length)throw new Ln($n.NoElements);return this[0]},t.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]},t.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},t.elementAt=function(e){if(e<0||e>=this.length)throw new Mn("index");return this[e]},t.elementAtOrDefault=function(e){return this[e]||null},t.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 Ln($n.NoMatch)}if(0===this.length)throw new Ln($n.NoElements);return this[this.length-1]},t.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]},t.reverse=function(){const e=this;return new jn((function*(){for(let t=e.length-1;t>=0;t--)yield e[t]}))}})(),zn(Array),zn(Int8Array),zn(Int16Array),zn(Int32Array),zn(Uint8Array),zn(Uint8ClampedArray),zn(Uint16Array),zn(Uint32Array),zn(Float32Array),zn(Float64Array);class Hu{static Init(){if(r.IsInitialized)return;let e=r.Instance;try{e.RegisterService(new s),e.RegisterService(new Uu),e.RegisterService(new Te),e.RegisterService(new Se),e.RegisterService(new Ie),e.RegisterService(new Gn),e.RegisterService(new Ce),e.RegisterService(new vt),e.RegisterService(new yn),e.RegisterService(new Ru)}catch(e){console.error(e)}}static GetAsync(e,t){return r.Instance.GetServiceAsync(e,t)}static GetWithTimeoutAsync(e,t){return r.Instance.GetServiceWithTimeoutAsync(e,t)}static Get(e){return r.Instance.GetService(e)}static SleepForAsync(e){return new Promise((t=>setTimeout(t,e)))}}Hu.WorksInContextOf="",Hu.Version=1;class ju{constructor(){this.DeviceGuid=""}}class zu extends ju{constructor(){super(...arguments),this.ReedSwitchMode=Bu.ShortingOnOpeningOff,this.SyncTime=720,this.LogicNegation=!1}}!function(e){e[e.TimeConditionMode=1]="TimeConditionMode",e[e.ShortingSwitchOpeningNoResp=2]="ShortingSwitchOpeningNoResp",e[e.ShortingOnOpeningOff=3]="ShortingOnOpeningOff",e[e.ShortingOffOpeningOn=4]="ShortingOffOpeningOn",e[e.ShortingOnOpeningNoResp=5]="ShortingOnOpeningNoResp",e[e.ShortingOffOpeningNoResp=6]="ShortingOffOpeningNoResp",e[e.ShortingNoRespOpeningOn=7]="ShortingNoRespOpeningOn",e[e.ShortingNoRespOpeningOff=8]="ShortingNoRespOpeningOff",e[e.ShortingNoRespOpeningSwitch=9]="ShortingNoRespOpeningSwitch",e[e.RevertTimeConditionMode=10]="RevertTimeConditionMode"}(Bu||(Bu={}));class Ku{constructor(e){this.DeviceGuid="",this.DeviceGuid=e}}class qu{constructor(e,t){this.DeviceGuid="",this.Channel=0,this.DeviceGuid=e,this.Channel=t}}var Vu,Ju,Yu=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Xu{constructor(){this._connection=null,this._connection=Hu.Get(Ie.ServiceName)}GetServiceName(){return Xu.ServiceName}GetAllParamsAsync(e){var t;return Yu(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Qu(e.Guid),35e3,!1);if(null==n)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetAllParamsAsync(e){var t,n,o;return Yu(this,void 0,void 0,(function*(){const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Zu(e),35e3,!1);return null==s||null==s.Status?(null===(n=r.Log)||void 0===n||n.Error(Xu.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(s.Status!==re.OK&&(null===(o=r.Log)||void 0===o||o.Error(Xu.ServiceName,`Failed to change device parameters, response status: ${s.Status}`)),s.Status)}))}SetReedSwitchOperationModeAsync(e,t){var n,o,s,i,a;return Yu(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new zu;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(Xu.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.LogicNegation=a.LogicNegation,c.SyncTime=a.SyncTime,c.ReedSwitchMode=t;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new Zu(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(Xu.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(Xu.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(Xu.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetSynchronizationTimeAsync(e,t){var n,o,s,i,a;return Yu(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new zu;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(Xu.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.LogicNegation=a.LogicNegation,c.SyncTime=t,c.ReedSwitchMode=a.ReedSwitchMode;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new Zu(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(Xu.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(Xu.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(Xu.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetLogicNegationAsync(e,t){var n,o,s,i,a;return Yu(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new zu;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(Xu.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.LogicNegation=t,c.SyncTime=a.SyncTime,c.ReedSwitchMode=a.ReedSwitchMode;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new Zu(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(Xu.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(Xu.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(Xu.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}GetCurrentConfig(e){var t;return Yu(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Qu(e),35e3,!1);if(null==n)return null;switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device! No data in response.")}))}}Xu.ServiceName="Rck21ConfigService";class Qu extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/reedswitch",this.Method=se.Get,this.Data=new Ku(e)}}class Zu extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/reedswitch",this.Method=se.Put,this.Data=e}}class eh extends ju{constructor(){super(...arguments),this.AlertMode=Vu.AlarmAndLed,this.RepeatFloodEvent=!1,this.RepeatFloodEventTime=900,this.WorkingMode=Ju.FloodSensor,this.SyncTime=720}}!function(e){e[e.None=0]="None",e[e.Alarm=1]="Alarm",e[e.Led=2]="Led",e[e.AlarmAndLed=3]="AlarmAndLed"}(Vu||(Vu={})),function(e){e[e.FloodSensor=0]="FloodSensor",e[e.PulseSensor=1]="PulseSensor"}(Ju||(Ju={}));var th,nh=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class oh{constructor(){this._connection=null,this._connection=Hu.Get(Ie.ServiceName)}GetServiceName(){return oh.ServiceName}GetAllParamsAsync(e){var t;return nh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new rh(e.Guid),35e3,!1);if(null==n)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetAllParamsAsync(e){var t,n,o;return nh(this,void 0,void 0,(function*(){const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new sh(e),35e3,!1);return null==s||null==s.Status?(null===(n=r.Log)||void 0===n||n.Error(oh.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(s.Status!==re.OK&&(null===(o=r.Log)||void 0===o||o.Error(oh.ServiceName,`Failed to change device parameters, response status: ${s.Status}`)),s.Status)}))}SetFloodAlertModeAsync(e,t){var n,o,s,i,a;return nh(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new eh;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(oh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.AlertMode=t,c.RepeatFloodEvent=a.RepeatFloodEvent,c.RepeatFloodEventTime=a.RepeatFloodEventTime,c.SyncTime=a.SyncTime,c.WorkingMode=a.WorkingMode;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new sh(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(oh.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(oh.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(oh.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetFloodEventRepetitionAsync(e,t){var n,o,s,i,a;return nh(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new eh;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(oh.ServiceName,"Failed to change device parameters - cannot read current configuration of device."),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.RepeatFloodEvent=t,c.AlertMode=a.AlertMode,c.RepeatFloodEventTime=a.RepeatFloodEventTime,c.SyncTime=a.SyncTime,c.WorkingMode=a.WorkingMode;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new sh(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(oh.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(oh.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(oh.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetFloodEventRepetitionTimeAsync(e,t){var n,o,s,i,a;return nh(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new eh;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(oh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.RepeatFloodEventTime=t,c.AlertMode=a.AlertMode,c.RepeatFloodEvent=a.RepeatFloodEvent,c.SyncTime=a.SyncTime,c.WorkingMode=a.WorkingMode;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new sh(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(oh.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(oh.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(oh.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetSynchronizationTimeAsync(e,t){var n,o,s,i,a;return nh(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new eh;if(null===a)return null===(n=r.Log)||void 0===n||n.Error(oh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.SyncTime=t,c.AlertMode=a.AlertMode,c.RepeatFloodEvent=a.RepeatFloodEvent,c.RepeatFloodEventTime=a.RepeatFloodEventTime,c.WorkingMode=a.WorkingMode;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new sh(c),35e3,!1);return null==l||null==l.Status?(null===(s=r.Log)||void 0===s||s.Error(oh.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(l.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(oh.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(oh.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}GetCurrentConfig(e){var t;return nh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new rh(e),35e3,!1);if(null==n)return null;switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device!")}))}}oh.ServiceName="Rcz21ConfigService";class rh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/floodsensor",this.Method=se.Get,this.Data=new Ku(e)}}class sh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/floodsensor",this.Method=se.Put,this.Data=e}}class ih extends ju{constructor(){super(...arguments),this.Channel=th.Unknow,this.Threshold=0,this.Hysteresis=!1,this.IsHysteresisOptionAvailable=!1,this.IsOffsetOptionAvailable=!1}}class ah extends ju{constructor(){super(...arguments),this.Interval=0}}class ch extends ju{constructor(){super(...arguments),this.Channel=th.Unknow,this.Offset=0}}!function(e){e[e.Unknow=0]="Unknow",e[e.TemperatureChannel=1]="TemperatureChannel",e[e.HuminidityChannel=2]="HuminidityChannel",e[e.PressureChannel=3]="PressureChannel",e[e.BrightnessChannel=4]="BrightnessChannel"}(th||(th={}));var lh=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class uh{constructor(){this._connection=null,this._connection=Hu.Get(Ie.ServiceName)}GetDetectionThresholdDataAsync(e,t){var n;return lh(this,void 0,void 0,(function*(){const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new dh(e.Guid,t.valueOf()),35e3,!1);if(null==o)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(o.Status){case re.OK:if(null!=o.Data)return o.Data.Threshold=o.Data.Threshold/1e3,o.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${o.Status} data: ${o.Data}`)}))}SetDetectionThresholdAsync(e,t,n){var o,s,i,a,c;return lh(this,void 0,void 0,(function*(){try{switch(t){case th.PressureChannel:if(n<.3||n>30||n*Math.pow(10,1)%1!=0)return re.WrongData;break;case th.HuminidityChannel:if(n<1||n>99||!Number.isInteger(n))return re.WrongData;break;case th.PressureChannel:case th.BrightnessChannel:if(n<1||n>100||!Number.isInteger(n))return re.WrongData;break;default:return re.WrongData}const c=yield this.GetCurrentDetectionThresholdConfigAsync(e.Guid,t.valueOf()),l=new ih;if(null===c)return null===(o=r.Log)||void 0===o||o.Error(_h.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;l.DeviceGuid=e.Guid,l.Channel=t,l.Hysteresis=c.Hysteresis,l.Threshold=1e3*n;const u=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(new fh(l),35e3,!1);return null==u||null==u.Status?(null===(i=r.Log)||void 0===i||i.Error(_h.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(u.Status!==re.OK&&(null===(a=r.Log)||void 0===a||a.Error(_h.ServiceName,`Failed to change device parameters, response status: ${u.Status}`)),u.Status)}catch(e){return null===(c=r.Log)||void 0===c||c.Error(_h.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}GetFramesIntervalAsync(e){var t;return lh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new hh(e.Guid),35e3,!1);if(null==n)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetFramesIntervalAsync(e,t){var n,o,s,i;return lh(this,void 0,void 0,(function*(){try{if(t<1||t>6480)return re.WrongData;const i=new ah;i.DeviceGuid=e.Guid,i.Interval=t;const a=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new gh(i),35e3,!1);return null==a||null==a.Status?(null===(o=r.Log)||void 0===o||o.Error(_h.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(a.Status!==re.OK&&(null===(s=r.Log)||void 0===s||s.Error(_h.ServiceName,`Failed to change device parameters, response status: ${a.Status}`)),a.Status)}catch(e){return null===(i=r.Log)||void 0===i||i.Error(_h.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}GetCurrentDetectionThresholdConfigAsync(e,t){var n;return lh(this,void 0,void 0,(function*(){const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new dh(e,t),35e3,!1);if(null==o)return null;switch(o.Status){case re.OK:if(null!=o.Data)return o.Data;break;case re.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device!")}))}}class hh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/interval",this.Method=se.Get,this.Data=new Ku(e)}}class dh extends oe{constructor(e,t){super(),this.Resource="/extalife/device/parameters/multisensor/detectionthreshold",this.Method=se.Get,this.Data=new qu(e,t)}}class fh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/detectionthreshold",this.Method=se.Put,this.Data=e}}class gh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/interval",this.Method=se.Put,this.Data=e}}var vh=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class yh extends uh{GetHysteresisAsync(e,t){var n;return vh(this,void 0,void 0,(function*(){const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new dh(e.Guid,t.valueOf()),35e3,!1);if(null==o)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(o.Status){case re.OK:if(null!=o.Data)return o.Data.Hysteresis;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${o.Status} data: ${o.Data}`)}))}SetHysteresisAsync(e,t,n){var o,s,i,a,c;return vh(this,void 0,void 0,(function*(){try{if(t==th.Unknow)return re.WrongData;const c=yield this.GetCurrentDetectionThresholdConfigAsync(e.Guid,t);let l=new ih;if(null===c)return null===(o=r.Log)||void 0===o||o.Error(_h.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;l.DeviceGuid=e.Guid,l.Channel=t,l.Hysteresis=n,l.Threshold=c.Threshold;const u=yield null===(s=this._connection)||void 0===s?void 0:s.SendAndWaitForResponseAsync(new fh(l),35e3,!1);return null==u||null==u.Status?(null===(i=r.Log)||void 0===i||i.Error(_h.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(u.Status!==re.OK&&(null===(a=r.Log)||void 0===a||a.Error(_h.ServiceName,`Failed to change device parameters, response status: ${u.Status}`)),u.Status)}catch(e){return null===(c=r.Log)||void 0===c||c.Error(_h.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}}var ph=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class wh extends yh{GetChannelOffsetAsync(e,t){var n;return ph(this,void 0,void 0,(function*(){if(t!=th.TemperatureChannel)return new tn(Th.InvalidChannelNumber,"Failed to retrieve parameters - function not available on selected channel");const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new mh(e.Guid,t.valueOf()),35e3,!1);if(null==o)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(o.Status){case re.OK:if(null!=o.Data)return o.Data.Offset=o.Data.Offset/10,o.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${o.Status} data: ${o.Data}`)}))}SetChannelOffsetAsync(e,t,n){var o,s,i,a;return ph(this,void 0,void 0,(function*(){try{if(t!==th.TemperatureChannel)return re.WrongData;if(n<-5||n>5||n*Math.pow(10,1)%1!=0)return re.WrongData;const a=new ch;a.DeviceGuid=e.Guid,a.Channel=t,a.Offset=10*n;const c=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new Sh(a),35e3,!1);return null==c||null==c.Status?(null===(s=r.Log)||void 0===s||s.Error(_h.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(c.Status!==re.OK&&(null===(i=r.Log)||void 0===i||i.Error(_h.ServiceName,`Failed to change device parameters, response status: ${c.Status}`)),c.Status)}catch(e){return null===(a=r.Log)||void 0===a||a.Error(_h.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}}class mh extends oe{constructor(e,t){super(),this.Resource="/extalife/device/parameters/multisensor/channeloffset",this.Method=se.Get,this.Data=new qu(e,t)}}class Sh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/channeloffset",this.Method=se.Put,this.Data=e}}class _h extends uh{constructor(){super(...arguments),this._services={Rcm21v1_5_0_30:new yh,Rcm21v1_6_0_34:new wh}}GetServiceName(){return _h.ServiceName}VersionedConfigurationOptions(){return{"^1.5.0.30":this._services.Rcm21v1_5_0_30,"^1.6.0.34":this._services.Rcm21v1_6_0_34}}}_h.ServiceName="Rcz21ConfigService";var Ah,Eh,Ch;class bh{constructor(){this._connection=null,this._connection=Hu.Get(Ie.ServiceName)}GetServiceName(){return bh.ServiceName}GetFirmwareVersionAsync(e){var t,n,o,r,s;return n=this,o=void 0,s=function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Dh(e.Guid),35e3,!1);if(null==n)return new tn(Th.UnknownError,"Failed to retrieve firmware version - unknow error.");switch(n.Status){case re.OK:if(null!=n.Data){const e=new Nh;return e.Major=n.Data.Major,e.Minor=n.Data.Minor,e.Revision=n.Data.Revision,e.Build=n.Data.Build,e}break;case re.Error:return new tn(Th.UnknownError,"Failed to retrieve firmware version - unknow error.")}return new tn(Th.OtherError,`Failed to retrieve firmware version, response error: ${n.Status} data: ${n.Data}`)},new((r=void 0)||(r=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 r?n:new r((function(e){e(n)}))).then(i,a)}c((s=s.apply(n,o||[])).next())}))}}bh.ServiceName="FirmwareService";class Nh{constructor(){this.Revision=0,this.Build=0,this.Minor=0,this.Major=0}ToString(){return`${this.Major}.${this.Minor}.${this.Build}.${this.Revision}`}}class Dh extends oe{constructor(e){super(),this.Resource="/extalife/device/firmware/version/complete",this.Method=se.Get,this.Data=e}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(Ah||(Ah={})),function(e){e[e.NoBrightnessSensor=0]="NoBrightnessSensor",e[e.NightMode=1]="NightMode",e[e.DayMode=2]="DayMode"}(Eh||(Eh={})),function(e){e[e.NO=0]="NO",e[e.NC=1]="NC",e[e.Disable=2]="Disable"}(Ch||(Ch={}));var Th,kh=function(e,t,n,o){return new(n||(n=Promise))((function(r,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(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))};class Ih{constructor(){this._connection=null,this._connection=Hu.Get(Ie.ServiceName)}GetServiceName(){return Ih.ServiceName}GetPirSensorParamsAsync(e){var t;return kh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ph(e.Guid),35e3,!1);if(null==n)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetDetectionThresholdAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;if(0!=o.PredefinedSettings)return re.OperationNotPermitted;const s=Object.assign({},o);return s.DetectionThreshold=t,this.SetPirSensorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetWindowTimeAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;if(0!=o.PredefinedSettings)return re.OperationNotPermitted;const s=Object.assign({},o);return s.WindowTime=t,this.SetPirSensorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetDetectionAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;if(0!=o.PredefinedSettings)return re.OperationNotPermitted;const s=Object.assign({},o);return s.Detection=t,this.SetPirSensorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetPredefinedSettingsAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.PredefinedSettings=t,0===t&&(s.DetectionThreshold>=1?s.DetectionThreshold--:s.DetectionThreshold++),this.SetPirSensorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}GetMovementDetectorParamsAsync(e){var t;return kh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Gh(e.Guid),35e3,!1);if(null==n)return new tn(Th.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case re.OK:if(null!=n.Data)return n.Data.SensorMode==Eh.DayMode&&(n.Data.CurrentLuxValue-=65),n.Data;break;case re.ResourceIsNotAvailable:return new tn(Th.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new tn(Th.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetOffTimeAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;if(t<10||t>3600)return re.WrongData;const s=Object.assign({},o);return s.OffTime=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetLuxSettingAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.LuxSetting=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetSynchronizationTimeAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.SyncTime=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetAccTamperEventAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.AccEvent=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetAccLevelAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.AccLevel=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetSensorModeAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.SensorMode=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetExternalOutModeAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.ExternalOutMode=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetOpticalLEDSignalizationAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.OpticalLEDSignalization=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}SetMoveLEDSignalizationAsync(e,t){var n,o;return kh(this,void 0,void 0,(function*(){try{const o=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===o)return null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),re.ResourceIsNotAvailable;const s=Object.assign({},o);return s.MoveLEDSignalization=t,this.SetMovementDetectorParamsAsync(s)}catch(e){return null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Cannot change device parameters. ${e}`),re.FatalError}}))}GetCurrentPirParamsAsync(e){var t;return kh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ph(e),35e3,!1);if(null==n)return null;switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device! No data in response.")}))}GetCurrentMovementDetectorParamsAsync(e){var t;return kh(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Gh(e),35e3,!1);if(null==n)return null;switch(n.Status){case re.OK:if(null!=n.Data)return n.Data;break;case re.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device! No data in response.")}))}SetPirSensorParamsAsync(e){var t,n,o;return kh(this,void 0,void 0,(function*(){const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Rh(e),35e3,!1);return null==s||null==s.Status?(null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(s.Status!==re.OK&&(null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Failed to change device parameters, response status: ${s.Status}`)),s.Status)}))}SetMovementDetectorParamsAsync(e){var t,n,o;return kh(this,void 0,void 0,(function*(){const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Fh(e),35e3,!1);return null==s||null==s.Status?(null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to change device parameters - unknow error."),re.FatalError):(s.Status!==re.OK&&(null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Failed to change device parameters, response status: ${s.Status}`)),s.Status)}))}ClearTamperAlarmAsync(e){var t,n,o;return kh(this,void 0,void 0,(function*(){const s=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Oh(e.Guid),35e3,!1);return null==s||null==s.Status?(null===(n=r.Log)||void 0===n||n.Error(Ih.ServiceName,"Failed to clear tamper alarm - unknow error."),re.FatalError):(s.Status!==re.OK&&(null===(o=r.Log)||void 0===o||o.Error(Ih.ServiceName,`Failed to clear tamper alarm, response status: ${s.Status}`)),s.Status)}))}}Ih.ServiceName="Rcr21ConfigService";class Ph extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/pir",this.Method=se.Get,this.Data=new Ku(e)}}class Rh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/pir",this.Method=se.Put,this.Data=e}}class Gh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/movementdetector",this.Method=se.Get,this.Data=new Ku(e)}}class Fh extends oe{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/movementdetector",this.Method=se.Put,this.Data=e}}class Oh extends oe{constructor(e){super(),this.Resource="/extalife/device/movementsensor/tamper/clear",this.Method=se.Post,this.Data=new Ku(e)}}class xh{constructor(){this._services={Rck21ConfigService:new Xu,Rcz21ConfigService:new oh,Rcm21ConfigService:new _h,Rcr21ConfigService:new Ih,FirmwareService:new bh},this._servicesToDeviceMap=new Map([["becbb229-1637-4b0f-a9f0-d43fa38ef76b",[this._services.Rck21ConfigService,this._services.FirmwareService]],["98d309e4-0986-4dd8-bcb6-fa31541c82be",[this._services.Rcz21ConfigService,this._services.FirmwareService]],["d7f88fcb-19f7-469b-b489-a239762023e5",[this._services.Rcm21ConfigService,this._services.FirmwareService]],["4688be64-c07c-4508-8e7a-b49bc4bbc78e",[this._services.Rcr21ConfigService,this._services.FirmwareService]]])}static Init(){r.Instance.RegisterService(new xh),Hu.Get(o.ServiceName).Debug("Initialized ExtaLifeService")}GetServiceName(){return xh.ServiceName}GetDeviceServiceByServiceType(e){switch(e){case"Rck21ConfigService":return this._services.Rck21ConfigService;case"Rcz21ConfigService":return this._services.Rcz21ConfigService;case"Rcm21ConfigService":return this._services.Rcm21ConfigService;case"Rcr21ConfigService":return this._services.Rcr21ConfigService;case"FirmwareService":return this._services.FirmwareService;default:return 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)}}xh.ServiceName="ExtaLifeService",function(e){e.Success="Success",e.ResourceIsNotAvailable="ResourceIsNotAvailable",e.UnknownError="UnknownError",e.OtherError="OtherError",e.InvalidChannelNumber="InvalidChannelNumber"}(Th||(Th={}))})();
1
+ (()=>{"use strict";var e,t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.d({},{v:()=>wg});class n{constructor(){this.handlers=[]}Subscribe(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=o.Log)||void 0===n||n.Error(e)}}))}}!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(e||(e={}));class r{constructor(){this._blockedServices=[],this._logLevel=e.Debug}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(r.ServiceName,`Disabling logs from ${e}`)}EnableLogsFrom(e){this._blockedServices.any((t=>t==e))&&(this._blockedServices=this._blockedServices.where((t=>t!=e)).toArray()),this.Debug(r.ServiceName,`Enaabling logs from ${e}`)}get LogLevel(){return this._logLevel}set LogLevel(e){this._logLevel=e}GetServiceName(){return r.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;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(e,t){null!=e&&(null==t?console.error(`${this.GetTimeStamp()}[ERROR] ${e}`):console.error(`${this.GetTimeStamp()}[ERROR] [${e}] ${t}`))}Info(t,n){switch(this._logLevel){case e.Info:case e.Debug:break;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){this._logLevel===e.Debug&&(void 0===t||this.IsBlocked(t)||null!=t&&(null==n?console.debug(`${this.GetTimeStamp()}[DEBUG] ${t}`):console.debug(`${this.GetTimeStamp()}[DEBUG] [${t}] ${n}`)))}Log(e,t){void 0===e||this.IsBlocked(e)||null!=e&&(null==t?console.log(`${this.GetTimeStamp()}[LOG] ${e}`):console.log(`${this.GetTimeStamp()}[LOG] [${e}] ${t}`))}}r.ServiceName="LoggerService";class o{constructor(){this._services={},this._serviceRegistrationEvent=new n}static get Instance(){return null!=o._instance||(o._instance=new o,this.Log=new r,this.Log.Warning("Initializing DependencyContainer"),o._instance.RegisterService(this.Log),this.IsInitialized=!0),o._instance}RegisterService(e){var t;null===(t=o.Log)||void 0===t||t.Debug("DependencyContainer",`Registering new service: ${e.GetServiceName()}`),this._services[e.GetServiceName()]=e,this._serviceRegistrationEvent.Invoke(e)}GetService(e){var t;return null===(t=o.Log)||void 0===t||t.Debug("DependencyContainer",`Getting service [${e}] by GetService<T>()`),this._services[e]}GetServiceAsync(e,t){var n,r;return null===(n=o.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service availability [${e}] by GetServiceAsync<T>()`),this._services.hasOwnProperty(e)?(null===(r=o.Log)||void 0===r||r.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,r)=>{var i=t=>{var r;(null==t?void 0:t.GetServiceName())===e&&(null===(r=o.Log)||void 0===r||r.Debug("DependencyContainer",`Got service [${e}] by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(i),n(t))},s=()=>{var n;null===(n=o.Log)||void 0===n||n.Debug("DependencyContainer",`Cancelled service [${e}] retrieval by GetServiceAsync<T>()`),this._serviceRegistrationEvent.Unsubscribe(i),null==t||t.CancellationEvent.Unsubscribe(s),r(new Error("Operation cancelled!"))};null==t||t.CancellationEvent.Subscribe(s),this._serviceRegistrationEvent.Subscribe(i)}))}GetServiceWithTimeoutAsync(e,t){var n,r;return null===(n=o.Log)||void 0===n||n.Debug("DependencyContainer",`Waiting for service[${e}] availability by GetServiceWithTimeoutAsync<T>()`),this._services.hasOwnProperty(e)?(null===(r=o.Log)||void 0===r||r.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),Promise.resolve(this._services[e])):new Promise(((n,r)=>{let i=0,s=e=>{var t;(null==e?void 0:e.GetClassName())===e&&(null===(t=o.Log)||void 0===t||t.Debug("DependencyContainer",`Got service [${e}] by GetServiceWithTimeoutAsync<T>()`),window.clearTimeout(i),this._serviceRegistrationEvent.Unsubscribe(s),n(e))};i=window.setTimeout((()=>{var t;window.clearTimeout(i),this._serviceRegistrationEvent.Unsubscribe(s),null===(t=o.Log)||void 0===t||t.Error("DependencyContainer",`Failed to get service [${e}] in time by GetServiceWithTimeoutAsync<T>()`),r(new Error("Operation cancelled!"))}),t),this._serviceRegistrationEvent.Subscribe(s)}))}}o.IsInitialized=!1;class i{GetServiceName(){return i.ServiceName}GetResourceName(e,t){return`_exalus_${hd.WorksInContextOf}_${e}_${t}`}Remove(e,t){localStorage.removeItem(this.GetResourceName(e,t))}DropStorage(e){let t=`_exalus_${e}`;for(const e in localStorage)(null==e?void 0:e.startsWith(t))&&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=o.Log)||void 0===n||n.Error(i.ServiceName,`Exception has occurred while reading ${this.GetResourceName(e,t)}`),null}}}i.ServiceName="LocalStorageService";const s=[0,2e3,1e4,3e4,null];class a{constructor(e){this._retryDelays=void 0!==e?[...e,null]:s}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class c{}c.Authorization="Authorization",c.Cookie="Cookie";class l{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class u{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class d extends u{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const 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[c.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[c.Authorization]&&delete e.headers[c.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class h extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class v extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class g extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class f extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class p extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class m extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class y extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class w extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var S,_,C,b,A;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(S||(S={}));class E{constructor(){}log(e,t){}}E.instance=new E;class D{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 N{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function T(e,t){let n="";return k(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 k(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function F(e,t,n,r,o,i){const s={},[a,c]=G();s[a]=c,e.log(S.Trace,`(${t} transport) sending data. ${T(o,i.logMessageContent)}.`);const l=k(o)?"arraybuffer":"text",u=await n.post(r,{content:o,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(S.Trace,`(${t} transport) request complete. Response status: ${u.statusCode}.`)}class I{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 R{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${S[e]}: ${t}`;switch(e){case S.Critical:case S.Error:this.out.error(n);break;case S.Warning:this.out.warn(n);break;case S.Information:this.out.info(n);break;default:this.out.log(n)}}}}function G(){let e="X-SignalR-User-Agent";return N.isNode&&(e="User-Agent"),[e,O("7.0.0",P(),N.isNode?"NodeJS":"Browser",x())]}function O(e,t,n,r){let o="Microsoft SignalR/";const i=e.split(".");return o+=`${i[0]}.${i[1]}`,o+=` (${e}; `,o+=t&&""!==t?`${t}; `:"Unknown OS; ",o+=`${n}`,o+=r?`; ${r}`:"; Unknown Runtime Version",o+=")",o}function P(){if(!N.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function x(){if(N.isNode)return process.versions.node}function M(e){return e.stack?e.stack:e.message?e.message:`${e}`}class $ extends u{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e=require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-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!==t.g)return t.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 g;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 g});let r,o=null;if(e.timeout){const r=e.timeout;o=setTimeout((()=>{t.abort(),this._logger.log(S.Warning,"Timeout from HTTP request."),n=new v}),r)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},k(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(S.Warning,`Error from HTTP request. ${e}.`),e}finally{o&&clearTimeout(o),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await L(r,"text");throw new h(e||r.statusText,r.status)}const i=L(r,e.responseType),s=await i;return new l(r.status,r.statusText,s)}getCookieString(e){let t="";return N.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function L(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 W extends u{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new g):e.method?e.url?new Promise(((t,n)=>{const r=new XMLHttpRequest;r.open(e.method,e.url,!0),r.withCredentials=void 0===e.withCredentials||e.withCredentials,r.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(k(e.content)?r.setRequestHeader("Content-Type","application/octet-stream"):r.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const o=e.headers;o&&Object.keys(o).forEach((e=>{r.setRequestHeader(e,o[e])})),e.responseType&&(r.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{r.abort(),n(new g)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new l(r.status,r.statusText,r.response||r.responseText)):n(new h(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(S.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),n(new h(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(S.Warning,"Timeout from HTTP request."),n(new v)},r.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class B extends u{constructor(e){if(super(),"undefined"!=typeof fetch||N.isNode)this._httpClient=new $(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new W(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new g):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)}}!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(_||(_={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(C||(C={}));class U{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class K{constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new U,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(D.isRequired(e,"url"),D.isRequired(t,"transferFormat"),D.isIn(t,C,"transferFormat"),this._url=e,this._logger.log(S.Trace,"(LongPolling transport) Connecting."),t===C.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=G(),o={[n]:r,...this._options.headers},i={abortSignal:this._pollAbort.signal,headers:o,timeout:1e5,withCredentials:this._options.withCredentials};t===C.Binary&&(i.responseType="arraybuffer");const s=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${s}.`);const a=await this._httpClient.get(s,i);200!==a.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new h(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(S.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this._httpClient.get(n,t);204===r.statusCode?(this._logger.log(S.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(S.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new h(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(S.Trace,`(LongPolling transport) data received. ${T(r.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof v?this._logger.log(S.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(S.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(S.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?F(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(S.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(S.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=G();e[t]=n;const r={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};await this._httpClient.delete(this._url,r),this._logger.log(S.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(S.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(S.Trace,e),this.onclose(this._closeError)}}}class H{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 D.isRequired(e,"url"),D.isRequired(t,"transferFormat"),D.isIn(t,C,"transferFormat"),this._logger.log(S.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,r)=>{let o,i=!1;if(t===C.Text){if(N.isBrowser||N.isWebWorker)o=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[r,i]=G();n[r]=i,o=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{o.onmessage=e=>{if(this.onreceive)try{this._logger.log(S.Trace,`(SSE transport) data received. ${T(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},o.onerror=e=>{i?this._close():r(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."))},o.onopen=()=>{this._logger.log(S.Information,`SSE connected to ${this._url}`),this._eventSource=o,i=!0,n()}}catch(e){return void r(e)}}else r(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?F(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 z{constructor(e,t,n,r,o,i){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=r,this._webSocketConstructor=o,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=i}async connect(e,t){let n;return D.isRequired(e,"url"),D.isRequired(t,"transferFormat"),D.isIn(t,C,"transferFormat"),this._logger.log(S.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((r,o)=>{let i;e=e.replace(/^http/,"ws");const s=this._httpClient.getCookieString(e);let a=!1;if(N.isNode||N.isReactNative){const t={},[r,o]=G();t[r]=o,n&&(t[c.Authorization]=`Bearer ${n}`),s&&(t[c.Cookie]=s),i=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);i||(i=new this._webSocketConstructor(e)),t===C.Binary&&(i.binaryType="arraybuffer"),i.onopen=t=>{this._logger.log(S.Information,`WebSocket connected to ${e}.`),this._webSocket=i,a=!0,r()},i.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(S.Information,`(WebSockets transport) ${t}.`)},i.onmessage=e=>{if(this._logger.log(S.Trace,`(WebSockets transport) data received. ${T(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",o(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(S.Trace,`(WebSockets transport) sending data. ${T(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(S.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class j{constructor(e,t={}){var n;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,D.isRequired(e,"url"),this._logger=void 0===(n=t.logger)?new R(S.Information):null===n?E.instance:void 0!==n.log?n:new R(n),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let r=null,o=null;if(N.isNode){const e=require;r=e("ws"),o=e("eventsource")}N.isNode||"undefined"==typeof WebSocket||t.WebSocket?N.isNode&&!t.WebSocket&&r&&(t.WebSocket=r):t.WebSocket=WebSocket,N.isNode||"undefined"==typeof EventSource||t.EventSource?N.isNode&&!t.EventSource&&void 0!==o&&(t.EventSource=o):t.EventSource=EventSource,this._httpClient=new d(t.httpClient||new B(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||C.Binary,D.isIn(e,C,"transferFormat"),this._logger.log(S.Debug,`Starting connection with transfer format '${C[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(S.Error,e),await this._stopPromise,Promise.reject(new g(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(S.Error,e),Promise.reject(new g(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new q(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(S.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(S.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==_.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(_.WebSockets),await this._startTransport(t,e)}else{let n=null,r=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new g("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}r++}while(n.url&&r<100);if(100===r&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof K&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(S.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(S.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,r]=G();t[n]=r;const o=this._resolveNegotiateUrl(e);this._logger.log(S.Debug,`Sending negotiation request: ${o}.`);try{const e=await this._httpClient.post(o,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof h&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(S.Error,t),Promise.reject(new y(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,r){let o=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(S.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(o,r),void(this.connectionId=n.connectionId);const i=[],s=n.availableTransports||[];let a=n;for(const n of s){const s=this._resolveTransportOrError(n,t,r);if(s instanceof Error)i.push(`${n.transport} failed:`),i.push(s);else if(this._isITransport(s)){if(this.transport=s,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}o=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(o,r),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(S.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(new m(`${n.transport} failed: ${e}`,_[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(S.Debug,e),Promise.reject(new g(e))}}}}return i.length>0?Promise.reject(new w(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`,i)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case _.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new z(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case _.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new H(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case _.LongPolling:return new K(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const r=_[e.transport];if(null==r)return this._logger.log(S.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(S.Debug,`Skipping transport '${_[r]}' because it was disabled by the client.`),new p(`'${_[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>C[e])).indexOf(n)>=0))return this._logger.log(S.Debug,`Skipping transport '${_[r]}' because it does not support the requested transfer format '${C[n]}'.`),new Error(`'${_[r]}' does not support ${C[n]}.`);if(r===_.WebSockets&&!this._options.WebSocket||r===_.ServerSentEvents&&!this._options.EventSource)return this._logger.log(S.Debug,`Skipping transport '${_[r]}' because it is not supported in your environment.'`),new f(`'${_[r]}' is not supported in your environment.`,r);this._logger.log(S.Debug,`Selecting transport '${_[r]}'.`);try{return this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(S.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(S.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(S.Error,`Connection disconnected with error '${e}'.`):this._logger.log(S.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(S.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(S.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(S.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(!N.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(S.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}class q{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new V,this._transportResult=new V,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new V),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 V;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):q._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),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 V{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class J{static write(e){return`${e}${J.RecordSeparator}`}static parse(e){if(e[e.length-1]!==J.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(J.RecordSeparator);return t.pop(),t}}J.RecordSeparatorCode=30,J.RecordSeparator=String.fromCharCode(J.RecordSeparatorCode);class Y{writeHandshakeRequest(e){return J.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(k(e)){const r=new Uint8Array(e),o=r.indexOf(J.RecordSeparatorCode);if(-1===o)throw new Error("Message is incomplete.");const i=o+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(r.slice(0,i))),n=r.byteLength>i?r.slice(i).buffer:null}else{const r=e,o=r.indexOf(J.RecordSeparator);if(-1===o)throw new Error("Message is incomplete.");const i=o+1;t=r.substring(0,i),n=r.length>i?r.substring(i):null}const r=J.parse(t),o=JSON.parse(r[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[n,o]}}!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"}(b||(b={}));class X{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 I(this,e)}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(A||(A={}));class Q{constructor(e,t,n,r){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(S.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},D.isRequired(e,"connection"),D.isRequired(t,"logger"),D.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new Y,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=A.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:b.Ping})}static create(e,t,n,r){return new Q(e,t,n,r)}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==A.Disconnected&&this._connectionState!==A.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==A.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=A.Connecting,this._logger.log(S.Debug,"Starting HubConnection.");try{await this._startInternal(),N.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=A.Connected,this._connectionStarted=!0,this._logger.log(S.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=A.Disconnected,this._logger.log(S.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(S.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(S.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(S.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){return this._connectionState===A.Disconnected?(this._logger.log(S.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===A.Disconnecting?(this._logger.log(S.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=A.Disconnecting,this._logger.log(S.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(S.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new g("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,r]=this._replaceStreamingParams(t),o=this._createStreamInvocation(e,t,r);let i;const s=new X;return s.cancelCallback=()=>{const e=this._createCancelInvocation(o.invocationId);return delete this._callbacks[o.invocationId],i.then((()=>this._sendWithProtocol(e)))},this._callbacks[o.invocationId]=(e,t)=>{t?s.error(t):e&&(e.type===b.Completion?e.error?s.error(new Error(e.error)):s.complete():s.next(e.item))},i=this._sendWithProtocol(o).catch((e=>{s.error(e),delete this._callbacks[o.invocationId]})),this._launchStreams(n,i),s}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return 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),o=this._createInvocation(e,t,!1,r);return new Promise(((e,t)=>{this._callbacks[o.invocationId]=(n,r)=>{r?t(r):n&&(n.type===b.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const r=this._sendWithProtocol(o).catch((e=>{t(e),delete this._callbacks[o.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)switch(e.type){case b.Invocation:this._invokeClientMethod(e);break;case b.StreamItem:case b.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===b.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(S.Error,`Stream callback threw error: ${M(e)}`)}}break}case b.Ping:break;case b.Close:{this._logger.log(S.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(S.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(S.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(S.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(S.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===A.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(S.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const r=n.slice(),o=!!e.invocationId;let i,s,a;for(const n of r)try{const r=i;i=await n.apply(this,e.arguments),o&&i&&r&&(this._logger.log(S.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),s=void 0}catch(e){s=e,this._logger.log(S.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):o?(s?a=this._createCompletionMessage(e.invocationId,`${s}`,null):void 0!==i?a=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(S.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):i&&this._logger.log(S.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(S.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new g("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===A.Disconnecting?this._completeClose(e):this._connectionState===A.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===A.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=A.Disconnected,this._connectionStarted=!1,N.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,r=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),o=this._getNextRetryDelay(n++,0,r);if(null===o)return this._logger.log(S.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=A.Reconnecting,e?this._logger.log(S.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(S.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(S.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==A.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==o;){if(this._logger.log(S.Information,`Reconnect attempt number ${n} will start in ${o} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,o)})),this._reconnectDelayHandle=void 0,this._connectionState!==A.Reconnecting)return void this._logger.log(S.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=A.Connected,this._logger.log(S.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(S.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(S.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==A.Reconnecting)return this._logger.log(S.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===A.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),o=this._getNextRetryDelay(n++,Date.now()-t,r)}}this._logger.log(S.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(S.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const r=t[n];try{r(null,e)}catch(t){this._logger.log(S.Error,`Stream 'error' callback called with '${e}' threw error: ${M(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:b.Invocation}:{arguments:t,target:e,type:b.Invocation};{const n=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:n.toString(),streamIds:r,target:e,type:b.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:b.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 i=this._invocationId;this._invocationId++,t[i]=o,n.push(i.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:b.StreamInvocation}:{arguments:t,invocationId:r.toString(),target:e,type:b.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:b.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:b.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:b.Completion}:{invocationId:e,result:n,type:b.Completion}}}class Z{constructor(){this.name="json",this.version=1,this.transferFormat=C.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=E.instance);const n=J.parse(e),r=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case b.Invocation:this._isInvocationMessage(n);break;case b.StreamItem:this._isStreamItemMessage(n);break;case b.Completion:this._isCompletionMessage(n);break;case b.Ping:case b.Close:break;default:t.log(S.Information,"Unknown message type '"+n.type+"' ignored.");continue}r.push(n)}return r}writeMessage(e){return J.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.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const ee={trace:S.Trace,debug:S.Debug,info:S.Information,information:S.Information,warn:S.Warning,warning:S.Warning,error:S.Error,critical:S.Critical,none:S.None};class te{configureLogging(e){if(D.isRequired(e,"logging"),void 0!==e.log)this.logger=e;else if("string"==typeof e){const t=function(e){const t=ee[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new R(t)}else this.logger=new R(e);return this}withUrl(e,t){return D.isRequired(e,"url"),D.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return D.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 a(e):this.reconnectPolicy=e:this.reconnectPolicy=new a,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 j(this.url,e);return Q.create(t,this.logger||E.instance,this.protocol||new Z,this.reconnectPolicy)}}class ne{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)}))}}class re{constructor(){this.TransactionId=ne.GenerateUUID()}}var oe,ie,se,ae,ce,le,ue,de,he,ve,ge,fe;(ve=oe||(oe={}))[ve.OK=0]="OK",ve[ve.UnknownError=1]="UnknownError",ve[ve.FatalError=2]="FatalError",ve[ve.WrongData=3]="WrongData",ve[ve.ResourceDoesNotExists=4]="ResourceDoesNotExists",ve[ve.NoPermissionToPerformThisOperation=5]="NoPermissionToPerformThisOperation",ve[ve.SessionHasAlreadyLoggedOnUser=6]="SessionHasAlreadyLoggedOnUser",ve[ve.OperationNotPermitted=7]="OperationNotPermitted",ve[ve.NoPermissionsToCallGivenResource=8]="NoPermissionsToCallGivenResource",ve[ve.ResourceIsNotAvailable=9]="ResourceIsNotAvailable",ve[ve.Error=10]="Error",ve[ve.NoData=11]="NoData",ve[ve.NotSupportedMethod=12]="NotSupportedMethod",ve[ve.UserIsNotLoggedIn=13]="UserIsNotLoggedIn",ve[ve.MultiDataResponseStart=14]="MultiDataResponseStart",ve[ve.MultiDataResponse=15]="MultiDataResponse",ve[ve.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"}(ie||(ie={}));class pe{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"}(se||(se={})),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"}(ae||(ae={})),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"}(ce||(ce={}));class me{constructor(){this._log=hd.Get(r.ServiceName),this.handlers=[]}Subscribe(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)}}))}}(fe=le||(le={}))[fe.Any=0]="Any",fe[fe.Guest=10]="Guest",fe[fe.Standard=20]="Standard",fe[fe.Admin=30]="Admin",fe[fe.Installator=40]="Installator",fe[fe.Support=50]="Support",(ge=ue||(ue={}))[ge.Unknown=0]="Unknown",ge[ge.Men=1]="Men",ge[ge.Woman=2]="Woman",ge[ge.Other=3]="Other",function(e){e[e.En_Us=0]="En_Us",e[e.Pl_Pl=1]="Pl_Pl"}(de||(de={})),function(e){e[e.Unknown=0]="Unknown",e[e.WrongAuthData=1]="WrongAuthData",e[e.NoResponseFromController=2]="NoResponseFromController"}(he||(he={}));class ye{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=ue.Unknown,this._accessLevel=le.Any,this._localization=de.En_Us}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}}var we=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Se{constructor(){this._onUserLoggedInEvent=new n,this._onUserLoggedOutEvent=new n,this._email="",this._password="",this._loginTaskCompletionSource=this.CreateSessionCompletionSourceAsync(),this._alreadySubsribedToNetworkEvents=!1,this._user=null}CreateSessionCompletionSourceAsync(){var e;return we(this,void 0,void 0,(function*(){null===(e=o.Log)||void 0===e||e.Debug(Se.ServiceName,"Creating _loginTaskCompletionSource"),this._loginTaskCompletionSource=new Promise((e=>{let t=n=>{var r;null===(r=o.Log)||void 0===r||r.Debug(Se.ServiceName,`Logged in as ${n.Name}, completing CreateSessionCompletionSourceAsync()`),e(),this.OnUserLoggedInEvent().Unsubscribe(t)};this.OnUserLoggedInEvent().Subscribe(t)}))}))}Subscribe(e){}RestoreSessionAsync(){var e;return we(this,void 0,void 0,(function*(){null===(e=o.Log)||void 0===e||e.Debug(Se.ServiceName,`Creating RestoreSessionAsync ${this._email} ${this._password}`),void 0!==this._user&&null!==this._user&&(yield this.UserLogInAsync(this._email,this._password))}))}WaitForSessionCreationAsync(){return we(this,void 0,void 0,(function*(){return this._loginTaskCompletionSource}))}OnUserLoggedInEvent(){return this._onUserLoggedInEvent}OnUserLoggedOutEvent(){return this._onUserLoggedOutEvent}get User(){return this._user}UserLogOutAsync(){var e,t;return we(this,void 0,void 0,(function*(){var n=new re;n.Resource="/users/user/logout",n.Method=ie.Put,this._email="",this._password="",(yield hd.Get(Ie.ServiceName).SendAndWaitForResponseAsync(n,2e4,!1)).Status==oe.OK?(this._onUserLoggedOutEvent.Invoke(this._user),null===(e=o.Log)||void 0===e||e.Debug(Se.ServiceName,"User has been logged out.")):null===(t=o.Log)||void 0===t||t.Debug(Se.ServiceName,"Failed to logout user!")}))}OnConnectionStateChanged(e){return we(this,void 0,void 0,(function*(){switch(e){case ce.Disconnected:case ce.Failed:break;case ce.Connected:hd.Get(Se.ServiceName).RestoreSessionAsync()}}))}UserLogInAsync(e,t){var n,r;return we(this,void 0,void 0,(function*(){var i=hd.Get(Ie.ServiceName);const s=yield i.SendAndWaitForResponseAsync(new Ce(e,t),2e4,!1);if(s.Status==oe.OK&&null!=s.Data){this._email=e,this._password=t;var a=new ye;return this._user=a,a.AccessLevel=s.Data.AccessLevel,a.Email=s.Data.Email,a.Gender=s.Data.Gender,a.Guid=s.Data.Guid,a.IsAccountOnline=s.Data.IsAccountOnline,a.Name=s.Data.Name,a.IsActive=s.Data.IsActive,a.IsBanned=s.Data.IsBanned,a.Phone=s.Data.Phone,a.Surname=s.Data.Surname,this._alreadySubsribedToNetworkEvents||(this._alreadySubsribedToNetworkEvents=!0,i.OnConnectionStateChangedEvent().Subscribe(this.OnConnectionStateChanged)),null===(n=o.Log)||void 0===n||n.Debug(Se.ServiceName,`Did logging in succeded?: ${s.Status==oe.OK}`),this._onUserLoggedInEvent.Invoke(this._user),a}return null===(r=o.Log)||void 0===r||r.Debug(Se.ServiceName,`User login response: ${s.Data}`),he.WrongAuthData}))}GetServiceName(){return Se.ServiceName}}Se.ServiceName="SessionService";class _e{constructor(e,t){this.Email="",this.Password="",this.Email=e,this.Password=t}}class Ce extends re{constructor(e,t){super(),this.Data=new _e(e,t),this.Resource="/users/user/login",this.Method=ie.Put}}var be=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Ae{constructor(){this._connection=null,this._session=null,this._localStorage=null,this._onEnteredConfigurationEvent=new me,this._onExitedConfigurationEvent=new me,this._onConfigurationTimeCheckedEvent=new n,this._configurationTime=new Date,this._appEnteredConfigurationMode=!1,this._didConfigurationChange=!1,this._synchronizationTaskCompletionSource=new Promise((e=>{hd.Get(Se.ServiceName).OnUserLoggedInEvent().Subscribe((t=>be(this,void 0,void 0,(function*(){this._didConfigurationChange=yield this.CheckIfConfigurationHasChangedAsync(),e()}))))})),this._connection=hd.Get(Ie.ServiceName),this._session=hd.Get(Se.ServiceName),this._localStorage=hd.Get(i.ServiceName),this._connection.OnDataReceivedEvent().Subscribe((e=>{"/info/configuration/mode/entry"==e.Resource?this._appEnteredConfigurationMode||this._onEnteredConfigurationEvent.Invoke():"/info/configuration/mode/exit"==e.Resource&&(this._appEnteredConfigurationMode||this._onExitedConfigurationEvent.Invoke())}))}GetServiceName(){return Ae.ServiceName}DidCofigurationChangeAsync(){return be(this,void 0,void 0,(function*(){return yield this._synchronizationTaskCompletionSource,Promise.resolve(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(){var e;return be(this,void 0,void 0,(function*(){this._appEnteredConfigurationMode=!0,yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ee,2e4,!1)}))}ExitConfigurationModeAsync(){var e;return be(this,void 0,void 0,(function*(){yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new De,2e4,!1),this._appEnteredConfigurationMode=!1}))}OnEnteredConfigurationEvent(){return this._onEnteredConfigurationEvent}OnExitedConfigurationEvent(){return this._onExitedConfigurationEvent}OnConfigurationTimeCheckedEvent(){return this._onConfigurationTimeCheckedEvent}GetLastConfigurationChangeTimeAsync(){var e;return be(this,void 0,void 0,(function*(){const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Ne,2e4,!1);if(null==t||(null==t?void 0:t.Status)!=oe.OK)throw new Error("Failed to get last configuration change time");return this._configurationTime=new Date(t.Data),this._configurationTime}))}CheckIfConfigurationHasChangedAsync(){return be(this,void 0,void 0,(function*(){const e=yield this.GetLastConfigurationChangeTimeAsync();return this.GetLastKnownConfigurationChangeTime().toString()!=e.toString()&&(this.SaveLastConfigurationChangeTime(e),this._onConfigurationTimeCheckedEvent.Invoke(e),!0)}))}}Ae.ServiceName="ControllerConfigurationService";class Ee extends re{constructor(){super(),this.Resource="/system/configuration/mode/entry",this.Method=ie.Put}}class De extends re{constructor(){super(),this.Resource="/system/configuration/mode/exit",this.Method=ie.Put}}class Ne extends re{constructor(){super(),this.Resource="/system/configuration/change/time",this.Method=ie.Get}}class Te{constructor(){this._log=hd.Get(r.ServiceName),Te._localStorageService=hd.Get(i.ServiceName)}GetServiceName(){return Te.ServiceName}GetResourceName(e){return`${e.Resource}_${e.Method}`}Cache(e){var t;e.Status===oe.OK&&(this._log.Debug(Te.ServiceName,`Caching request: ${e.Resource} ${e.Method}`),null===(t=Te._localStorageService)||void 0===t||t.Save(this.GetServiceName(),this.GetResourceName(e),e))}GetCache(e){var t;let n=null===(t=Te._localStorageService)||void 0===t?void 0:t.Read(this.GetServiceName(),this.GetResourceName(e));return null!=n&&this._log.Debug(Te.ServiceName,`Got request response from cache: ${e.Resource} ${e.Method}`),n}ClearCache(){var e;null===(e=Te._localStorageService)||void 0===e||e.DropStorage(this.GetServiceName()),this._log.Debug(Te.ServiceName,`Clearing cache for ${this.GetServiceName()}`)}Remove(e){var t;null===(t=Te._localStorageService)||void 0===t||t.Remove(this.GetServiceName(),this.GetResourceName(e)),this._log.Debug(Te.ServiceName,`Clearing cache for cache: ${e.Resource} ${e.Method}`)}}Te._localStorageService=null,Te.ServiceName="WebApiCacheService";var ke,Fe=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Ie{constructor(){this._logPackets=!1,this._pingInterval=5e3,this._disconnectedOnPurpose=!1,this._defaultPacketsBrokerAddress="br1.tr7.pl",this._serversBrokerAddress="https://broker.tr7.pl",this._address="br1.tr7.pl",this._isEstabilished=!1,this._timeout=1e4,this._dataReceivedEvent=new n,this._pongReceivedEvent=new me,this._authorizationReceivedEvent=new n,this._registrationReceivedEvent=new n,this._connectionStateChangedEvent=new n,this._errorOccuredEvent=new n,this._log=hd.Get(r.ServiceName),this._controllerConfiguration=null,this._cache=null,this._session=null,this._packetsBrokerServers=["br1.tr7.pl","br1.exala.pl"],this._lastReceivedPacketTime=Date.now()}GetServiceName(){return Ie.ServiceName}EnablePacketsLogging(){this._logPackets=!0}DisablePacketsLogging(){this._logPackets=!1}InitializeConnection(){if(this._controllerConfiguration=hd.Get(Ae.ServiceName),this._cache=hd.Get(Te.ServiceName),this._session=hd.Get(Se.ServiceName),this._connection){try{this._connection.stop()}catch(e){}this._connection=void 0}if(!this._address)throw new Error("Domain is not set");if(!this._serialId)throw new Error("SerialId is not set");if(!this._PIN)throw new Error("PIN is not set");this._connection=(new te).withUrl(`https://${this._address}/broker`).build(),this._dataReceivedEvent.Subscribe((e=>{this._lastReceivedPacketTime=Date.now()})),setInterval((()=>Fe(this,void 0,void 0,(function*(){yield this.PingControllerAsync()}))),this._pingInterval)}SetServersBrokerAddress(e){this._serversBrokerAddress=e}SetDefaultPacketsBrokerAddress(e){this._defaultPacketsBrokerAddress=e,this._address=e}GetServerAddressAsync(){return Fe(this,void 0,void 0,(function*(){try{let e=yield fetch(`${this._serversBrokerAddress}/api/connections/broker/whichserver/${this._serialId}`);if(e.ok){let t=yield e.text();return t?(this._log.Debug(Ie.ServiceName,`Got server address: ${t}`),t):(this._log.Error(Ie.ServiceName,`Failed to get server address, status: ${e.status}`),null)}return this._log.Error(Ie.ServiceName,`Failed to get server address, status: ${e.status}`),null}catch(e){return this._log.Error(Ie.ServiceName,e),null}}))}ConnectAsync(e){return Fe(this,void 0,void 0,(function*(){return this._address=e,yield this.connectAsync()}))}AuthorizeAsync(e){return new Promise(((t,n)=>Fe(this,void 0,void 0,(function*(){var n;let r=0,o=e=>{window.clearTimeout(r),this._authorizationReceivedEvent.Unsubscribe(o),this._log.Debug(Ie.ServiceName,`Got authorization result: ${e}`),t(e)};r=window.setTimeout((()=>{window.clearTimeout(r),this._authorizationReceivedEvent.Unsubscribe(o),t(!1)}),2e3),this._log.Debug(Ie.ServiceName,`Authorizing to cloud using: ${e.SerialNumber} PIN: ${e.PIN}`),this._authorizationReceivedEvent.Subscribe(o),yield null===(n=this._connection)||void 0===n?void 0:n.send("AuthorizeTo",e.SerialNumber,e.PIN)}))))}ConnectAndAuthorizeAsync(e){return Fe(this,void 0,void 0,(function*(){hd.WorksInContextOf=e.SerialNumber,this._serialId=e.SerialNumber,this._PIN=e.PIN;var t=yield this.GetServerAddressAsync();if(t&&null!=t){this._log.Debug(Ie.ServiceName,`Got packets broker address: ${t}`),this.SetDefaultPacketsBrokerAddress(t);let n=yield this.connectAsync();return n!=ae.Connected?n:(yield this.AuthorizeAsync(e))?ae.Connected:ae.AuthorizationFailed}{let t=ae.ControllerIsNotConnected;this._log.Warning(Ie.ServiceName,"Server did not return packets broker address, trying to connect to known brokers.");for(let n of this._packetsBrokerServers){this._log.Warning(Ie.ServiceName,`Testing connection to ${n}`),this.SetDefaultPacketsBrokerAddress(n);try{yield this.DisconnectAsync()}catch(e){}this._log.Warning(Ie.ServiceName,`Connecting to server: ${n}`);let r=yield this.connectAsync();if(this._log.Warning(Ie.ServiceName,`Connection result: ${r}`),r==ae.Connected){if(yield this.AuthorizeAsync(e))return t=ae.Connected,t;this._log.Warning(Ie.ServiceName,`Failed to authorize in ${n}`)}}return t}}))}connectAsync(){var e,t,n,r,o,i,s,a,c;return Fe(this,void 0,void 0,(function*(){if(ae.FailedToConnect,!this._address)return Promise.resolve(ae.ControllerIsNotConnected);this._disconnectedOnPurpose&&(this._disconnectedOnPurpose=!1),this._connectionStateChangedEvent,this.InitializeConnection(),null===(e=this._connection)||void 0===e||e.onclose((()=>Fe(this,void 0,void 0,(function*(){var e,t;if(this._log.Error(Ie.ServiceName,"Connection closed"),hd.Get(Se.ServiceName).CreateSessionCompletionSourceAsync(),this.FireConnectionStateChanged(),(null===(e=this._connection)||void 0===e?void 0:e.state)===A.Disconnected&&!this._disconnectedOnPurpose)return yield null===(t=this._connection)||void 0===t?void 0:t.start(),null!=this._connection?(yield this.AuthorizeAsync(new pe(this._serialId,this._PIN)),this._log.Info(Ie.ServiceName,"Reconnected from onClose"),this.FireConnectionStateChanged()):ae.FailedToConnect})))),null===(t=this._connection)||void 0===t||t.onreconnected((()=>Fe(this,void 0,void 0,(function*(){return yield this.AuthorizeAsync(new pe(this._serialId,this._PIN)),this._log.Info(Ie.ServiceName,"Reconnected from onreconnected"),this.FireConnectionStateChanged()})))),null===(n=this._connection)||void 0===n||n.onreconnecting((()=>(this._log.Warning(Ie.ServiceName,"Reconnecting..."),this.FireConnectionStateChanged()))),yield null===(r=this._connection)||void 0===r?void 0:r.start(),null===(o=this._connection)||void 0===o||o.on("Pong",(()=>{this._log.Debug(Ie.ServiceName,"Pong received <-"),this._pongReceivedEvent.Invoke()})),null===(i=this._connection)||void 0===i||i.on("Registration",(e=>{var t;null===(t=this._registrationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(s=this._connection)||void 0===s||s.on("Authorization",(e=>{var t;null===(t=this._authorizationReceivedEvent)||void 0===t||t.Invoke(e)})),null===(a=this._connection)||void 0===a||a.on("SendError",((e,t)=>Fe(this,void 0,void 0,(function*(){e.startsWith("NotAuthorized:")?(this._log.Error(Ie.ServiceName,"Failed to authorize!"),yield this.AuthorizeAsync(new pe(this._serialId,this._PIN))):(this._log.Error(Ie.ServiceName,`Server returned error: ${e} ${t}`),this._errorOccuredEvent.Invoke([e,t]))}))));let l=this._dataReceivedEvent;return null===(c=this._connection)||void 0===c||c.on("Data",((e,t)=>{const n=JSON.parse(t);this._logPackets&&this._log.Debug(Ie.ServiceName,`Received data:\n${JSON.stringify(n,null,2)}`),l.Invoke(n)})),null!=this._connection?this.FireConnectionStateChanged():ae.FailedToConnect}))}FireConnectionStateChanged(){var e;const t=this._connectionStateChangedEvent;switch(null===(e=this._connection)||void 0===e?void 0:e.state){case A.Connected:return t.Invoke(ce.Connected),ae.Connected;case A.Connecting:return t.Invoke(ce.Connecting),ae.Connected;case A.Disconnected:return t.Invoke(ce.Disconnected),ae.FailedToConnect;case A.Disconnecting:return t.Invoke(ce.Disconnecting),ae.FailedToConnect;case A.Reconnecting:return t.Invoke(ce.Reconnecting),ae.FailedToConnect}return ae.FailedToConnect}DisconnectAsync(){var e;return Fe(this,void 0,void 0,(function*(){this._disconnectedOnPurpose=!0,yield null===(e=this._connection)||void 0===e?void 0:e.stop()}))}IsConnected(){var e;return(null===(e=this._connection)||void 0===e?void 0:e.state)===A.Connected}SendAndWaitForResponseAsync(e,t,n,r=!0){return this.SendAndWaitForResponseWithRepeatAsync(e,t,n,r)}SendAndWaitForResponseWithRepeatAsync(e,t,n,r=!0,o=!0){var i,s,a;return Fe(this,void 0,void 0,(function*(){if(e.Method===ie.Get&&n&&!(yield null===(i=this._controllerConfiguration)||void 0===i?void 0:i.DidCofigurationChangeAsync())){let t=null===(s=this._cache)||void 0===s?void 0:s.GetCache(e);if(null!==t)return Promise.resolve(t)}let c=0;const l=Date.now();if(!this.IsConnected())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(((i,s)=>Fe(this,void 0,void 0,(function*(){let a=s=>Fe(this,void 0,void 0,(function*(){var u,d,h,v;if((null==s?void 0:s.TransactionId)==e.TransactionId){window.clearTimeout(c),this._dataReceivedEvent.Unsubscribe(a);const g=Date.now()-l;o&&this._log.Debug(Ie.ServiceName,`Received response for: ${null==s?void 0:s.Resource} ${null==s?void 0:s.Method} id: ${null==s?void 0:s.TransactionId} in ${g}ms`),e.Method===ie.Get&&n&&(null===(u=this._cache)||void 0===u||u.Cache(s)),!n&&(null==s?void 0:s.Status)===oe.UserIsNotLoggedIn&&r&&((null===(d=this._session)||void 0===d?void 0:d.OnUserLoggedOutEvent()).Invoke(null===(h=this._session)||void 0===h?void 0:h.User),yield null===(v=this._session)||void 0===v?void 0:v.RestoreSessionAsync(),i(yield this.SendAndWaitForResponseWithRepeatAsync(e,t,n,!1,o))),i(s)}}));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(Ie.ServiceName,t),s(new v(t))}),t),!(yield this.SendAsync(e,o))){let t=`Failed to send request, resource: ${e.Resource} method: ${e.Method} transaction id: ${e.TransactionId}`;s(new Error(t))}}))))}))}PingControllerAsync(){var e;return Fe(this,void 0,void 0,(function*(){if((null===(e=this._connection)||void 0===e?void 0:e.state)!==A.Connected)return!1;if(null!==this._lastReceivedPacketTime&&Date.now()-this._lastReceivedPacketTime<this._pingInterval)return!1;let t=new re;return t.Resource="/system/ping",t.Method=ie.Get,yield this.SendAndWaitForResponseAsync(t,2e3,!1,!1).then((()=>!0)).catch((()=>!1))}))}SendAsync(e,t=!1){if(!this.IsConnected())throw new Error("Connection is not established");return new Promise((n=>{var r;this._logPackets?this._log.Debug(Ie.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId} data:\n${JSON.stringify(e,null,2)}`):t&&this._log.Debug(Ie.ServiceName,`Sent DataFrame ${e.Resource} ${e.Method} transaction id: ${e.TransactionId}`),null===(r=this._connection)||void 0===r||r.invoke("SendTo",this._serialId,e).then((()=>{n(!0)})).catch((e=>{this._log.Error(Ie.ServiceName,`${e}`),n(!1)}))}))}OnDataReceivedEvent(){return this._dataReceivedEvent}OnConnectionStateChangedEvent(){return this._connectionStateChangedEvent}OnErrorOccuredEvent(){return this._errorOccuredEvent}}Ie.ServiceName="ExalusConnectionService";class Re{constructor(e,t){this._type=ke.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 Ge{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.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"}(ke||(ke={}));var Oe,Pe,xe,Me,$e,Le,We,Be,Ue,Ke,He,ze,je,qe,Ve,Je,Ye,Xe,Qe,Ze,et,tt,nt,rt,ot,it,st,at,ct,lt,ut,dt,ht,vt,gt,ft,pt,mt,yt,wt,St,_t=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Ct{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName)}GetServiceName(){return Ct.ServiceName}GetUsersAsync(){var e,t;return _t(this,void 0,void 0,(function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Dt,2e4,!1);if(null==n)return Promise.resolve([]);if((null==n?void 0:n.Status)==oe.OK){if(null!=n.Data){const e=[];return n.Data.forEach((t=>{var n=new ye;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)==oe.NoData)return Promise.resolve([]);throw null===(t=o.Log)||void 0===t||t.Debug(Ct.ServiceName,`Failed to retrieve users, error: ${n.Status}`),new Error(`Failed to retrieve users, error: ${n.Status}`)}))}GetUserAsync(e){var t,n;return _t(this,void 0,void 0,(function*(){if(""===e)return Promise.resolve(null);null==e&&(e="");const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new bt(e),2e4,!1);if(null==r||null==r.Data)return Promise.resolve(null);if(r.Status!=oe.OK)return null===(n=o.Log)||void 0===n||n.Debug(Ct.ServiceName,`Failed to retrieve user, error: ${r.Status}`),Promise.resolve(null);const i=new ye;return i.AccessLevel=r.Data.AccessLevel,i.Email=r.Data.Email,i.Gender=r.Data.Gender,i.Guid=r.Data.Guid,i.IsAccountOnline=r.Data.IsAccountOnline,i.Name=r.Data.Name,i.IsActive=r.Data.IsActive,i.IsBanned=r.Data.IsBanned,i.Phone=r.Data.Phone,i.Surname=r.Data.Surname,i}))}CreateUserAsync(e,t){var n;return _t(this,void 0,void 0,(function*(){if(null!=e.Guid&&""!=e.Guid)return new Ge(oe.WrongData,"GuidMustBeEmpty");const r=new At;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 Et(r),2e4,!1);return null==o||null==o.Status?new Ge(oe.FatalError,"UnknownError"):(null==o.Data&&(o.Data=""),new Ge(o.Status,o.Data))}))}UpdateUserAsync(e){var t;return _t(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new Ge(oe.WrongData,"GuidCannotBeEmpty");const n=new At;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 Et(n),2e4,!1);return null==r||null==r.Status?new Ge(oe.FatalError,"UnknownError"):(null==r.Data&&(r.Data=""),new Ge(r.Status,r.Data))}))}ChangePasswordAsync(e,t){var n;return _t(this,void 0,void 0,(function*(){if(null==e.Guid||""==e.Guid)return new Ge(oe.WrongData,"GuidCannotBeEmpty");const r=yield this.GetUserAsync(e.Guid);if(null==r)return new Ge(oe.ResourceIsNotAvailable,"CannotGetUser");const o=new At;o.Guid=e.Guid,o.Password=t,o.AccessLevel=r.AccessLevel,o.Email=r.Email;const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Et(o),2e4,!1);return null==i||null==i.Status?new Ge(oe.FatalError,"UnknownError"):(null==i.Data&&(i.Data=""),new Ge(i.Status,i.Data))}))}DeleteUserAsync(e){var t,n;return _t(this,void 0,void 0,(function*(){if(""===e)return oe.WrongData;null==e&&(e="");const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Nt(e),2e4,!1);return null==r||null==r.Status?oe.FatalError:(r.Status!=oe.OK&&(null===(n=o.Log)||void 0===n||n.Debug(Ct.ServiceName,`Failed to delete user, error: ${r.Status}`)),r.Status)}))}}Ct.ServiceName="UsersService";class bt extends re{constructor(e){super(),this.Resource="/users/user",this.Method=ie.Get,this.Data=e}}class At{constructor(){this.Guid="",this.Name="",this.Surname="",this.Email="",this.Password="",this.Phone="",this.Gender=ue.Unknown,this.AccessLevel=le.Any}}class Et extends re{constructor(e){super(),this.Resource="/users/user",this.Method=ie.Put,this.Data=e}}class Dt extends re{constructor(){super(),this.Resource="/users/list",this.Method=ie.Get}}class Nt extends re{constructor(e){super(),this.Resource="/users/user",this.Method=ie.Delete,this.Data=e}}!function(e){e[e.NoTasksExecuting=0]="NoTasksExecuting",e[e.ExecutingTasks=1]="ExecutingTasks"}(Oe||(Oe={})),(ft=Pe||(Pe={}))[ft.Default=0]="Default",ft[ft.Monostable=1]="Monostable",ft[ft.Bistable=2]="Bistable",ft[ft.Gate=3]="Gate",ft[ft.Gateway=4]="Gateway";class Tt{constructor(){this._type=xe.Unknown,this._interfaceType=""}get Type(){return this._type}get InterfaceType(){return this._interfaceType}set InterfaceType(e){this._interfaceType=e,this._type=e}}(pt=xe||(xe={})).Unknown="Unknown",pt.SetBlindPosition="IBlindPosition",pt.SetBlindPositionSimple="IBlindPositionSimple",pt.SetBlindMicroventilation="IMicroventilation",pt.TurnOff="IChannelOff",pt.TurnOn="IChannelOn",pt.TogleState="IChannelSwitchState",pt.SetLightBrightnessDynamicly="IDynamicLightBrightness",pt.SetLightBrightness="ILightBrightness",pt.SetLightColor="ILightColor",pt.SetLightTemperature="ILightTemperature",pt.PairDevice="IPair",pt.UnpairDevice="IUnpair",pt.IdentifyDevice="IIdentifyDevice",pt.GetChannelsState="IGetDeviceState",pt.GetPowerMeasurements="IGetPowerMeasurements",pt.GetAvailableData="IGetAvailableData",pt.MultipleDataRequest="IMultipleDataRequest",pt.SetBlindOpenCloseTime="ISetBlindOpenCloseTime",pt.SetTemperature="IChangeTemperature",pt.ChangeGatePositionPulse="IGatePulse",pt.ChangeGatewayPositionPulse="IGatewayPulse",pt.SetFacadePosition="IFacadePosition",pt.GetFacadeType="IGetFacadeType";class kt{constructor(){this._type=Me.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.MeasuredBrightness="IBrightness",e.RemoteButtonState="IButtonState",e.ChannelOnOffState="IChannelOnOff",e.DoorBellState="IDoorBell",e.FacadeRemoteButtonState="IFacadeControlButton",e.FacadePosition="IFacadeState",e.FacadeType="IFacadeType",e.FloodSensorState="IFloodSensor",e.GatePosition="IGatePosition",e.GatewayPosition="IGatewayPosition",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"}(Me||(Me={})),(wt=$e||($e={}))[wt.NotResponding=0]="NotResponding",wt[wt.Working=1]="Working",wt[wt.Broken=2]="Broken",wt[wt.FirmareUpgradeMode=3]="FirmareUpgradeMode",(yt=Le||(Le={}))[yt.TwoWay=1]="TwoWay",yt[yt.OneWay=2]="OneWay",yt[yt.ConditionalTwoWay=3]="ConditionalTwoWay",(mt=We||(We={}))[mt.Unknown=-1]="Unknown",mt[mt.Multipurpose=0]="Multipurpose",mt[mt.Controller=1]="Controller",mt[mt.Driver=2]="Driver",mt[mt.Receiver=3]="Receiver",mt[mt.Remote=4]="Remote",mt[mt.Sensor=5]="Sensor",mt[mt.Scene=6]="Scene";class Ft{constructor(){this.DeviceGuid="",this.Channel=0,this.Status=Oe.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"}(Be||(Be={})),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"}(Ue||(Ue={}));class It{constructor(){this.Device=null,this.Channel=0,this.Task=null,this.Result=Ue.Unknown}}class Rt{constructor(){this._type="",this._data=null,this._typeAsEnum=Me.Unknown}get Data(){return this._data}set Data(e){this._data=e}get Type(){return this._type}set Type(e){this._type=e}get TypeAsEnum(){return this._typeAsEnum}set TypeAsEnum(e){this._typeAsEnum=e}}(St=Ke||(Ke={}))[St.Confident=0]="Confident",St[St.Unconfident=1]="Unconfident";class Gt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.ChannelOnOffState,this.Type="ChannelOnOffState",this.Data=e.state}}!function(e){e[e.On=0]="On",e[e.Off=1]="Off",e[e.Unknown=2]="Unknown"}(He||(He={}));class Ot extends Rt{constructor(e){super(),this.TypeAsEnum=Me.DoorBellState,this.Type="DoorBellState",this.Data=e.state}}!function(e){e[e.Pressed=0]="Pressed",e[e.Relased=1]="Relased",e[e.PressedAndRelased=2]="PressedAndRelased"}(ze||(ze={}));class Pt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.ReedState,this.Type="ReedState",this.Data=e.state}}class xt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.BlindPosition,this.Type="BlindPostionState",this.Data=e.state}GetBlindStatus(){switch(this.Data.Position){case 200:return je.UnableToMove;case 201:return je.MotorOverheatedPleaseWait;default:return je.Working}}}!function(e){e[e.Unknown=0]="Unknown",e[e.Working=1]="Working",e[e.UnableToMove=200]="UnableToMove",e[e.MotorOverheatedPleaseWait=201]="MotorOverheatedPleaseWait"}(je||(je={}));class Mt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.RemoteButtonState,this.Type="RemoteButtonState",this.Data=e.state}}!function(e){e[e.Pressed=1]="Pressed",e[e.Relased=2]="Relased",e[e.PressedAndRelased=3]="PressedAndRelased"}(qe||(qe={}));class $t extends Rt{constructor(e){super(),this.TypeAsEnum=Me.LightColor,this.Type="LightColorState",this.Data=e.state}}class Lt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.LightWarmth,this.Type="LightWarmthState",this.Data=e.state}}class Wt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.LightBrightness,this.Type="LightBrightnessState",this.Data=e.state}}class Bt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.MeasuredTemperature,this.Type="MeasuredTemperatureState",this.Data=e.state}}!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"}(Ve||(Ve={}));class Ut extends Rt{constructor(e){super(),this.TypeAsEnum=Me.BatteryState,this.Type="BatteryState",this.Data=e.state}}!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"}(Je||(Je={}));class Kt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.MeasuredBrightness,this.Type="MeasuredBrightnessState",this.Data=e.state}}class Ht extends Rt{constructor(e){super(),this.TypeAsEnum=Me.MeasuredEnergy,this.Type="MeasuredEnergyState",this.Data=e.state}}class zt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.MeasuredDistance,this.Type="MeasuredDistanceState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(Ye||(Ye={}));class jt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.MovementSensorState,this.Type="MovementSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(Xe||(Xe={}));class qt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.BlindRemoteButtonState,this.Type="BlindRemoteButtonState",this.Data=e.state}}!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"}(Qe||(Qe={}));class Vt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.FacadeRemoteButtonState,this.Type="FacadeRemoteButtonState",this.Data=e.state}}!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"}(Ze||(Ze={}));class Jt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.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"}(et||(et={}));class Yt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.GatePosition,this.Type="GatePositionState",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"}(tt||(tt={}));class Xt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.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"}(nt||(nt={}));class Qt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.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"}(rt||(rt={}));class Zt extends Rt{constructor(e){super(),this.TypeAsEnum=Me.HumiditySensorState,this.Type="HumiditySensorState",this.Data=e.state}}!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"}(ot||(ot={}));class en extends Rt{constructor(e){super(),this.TypeAsEnum=Me.VibrationSensorState,this.Type="VibrationSensorState",this.Data=e.state}}!function(e){e[e.No=0]="No",e[e.Yes=1]="Yes"}(it||(it={}));class tn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.BinarySensorState,this.Type="BinarySensorState",this.Data=e.state}}!function(e){e[e.High=1]="High",e[e.Low=0]="Low"}(st||(st={}));class nn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.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"}(at||(at={}));class rn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.BlindOpenCloseTime,this.Type="BlindOpenCloseTimeState",this.Data=e.state}}class on extends Rt{constructor(e){super(),this.TypeAsEnum=Me.OvercurrentProtectionState,this.Type="OvercurrentProtectionState",this.Data=e.state}}class sn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.OvercurrentProtectionThreshold,this.Type="OvercurrentProtectionThresholdState",this.Data=e.state}}class an extends Rt{constructor(e){super(),this.TypeAsEnum=Me.FacadePosition,this.Type="FacadePositionState",this.Data=e.state}}class cn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.FacadeType,this.Type="FacadeTypeState",this.Data=e.state}}class ln extends Rt{constructor(e){super(),this.TypeAsEnum=Me.CurrentWindThreshold,this.Type="CurrentWindThresholdState",this.Data=e.state}}!function(e){e[e.Unknown=0]="Unknown",e[e.Below=1]="Below",e[e.Exceeded=2]="Exceeded",e[e.Inactive=3]="Inactive"}(ct||(ct={}));class un extends Rt{constructor(e){super(),this.TypeAsEnum=Me.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"}(lt||(lt={}));class dn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.WindSpeedState,this.Type="WindSpeedState",this.Data=e.state}}class hn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.FloodSensorState,this.Type="FloodSensorState",this.Data=e.state}}!function(e){e[e.FloodDetected=1]="FloodDetected",e[e.NoFloodDetected=0]="NoFloodDetected"}(ut||(ut={})),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"}(dt||(dt={}));class vn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.PressureSensorState,this.Type="PressureSensorState",this.Data=e.state}}!function(e){e[e.InsidePressure=0]="InsidePressure",e[e.OutsidePressure=1]="OutsidePressure",e[e.SetPressure=2]="SetPressure"}(ht||(ht={})),function(e){e[e.Facade90=0]="Facade90",e[e.Facade180=1]="Facade180"}(vt||(vt={}));class gn extends Rt{constructor(e){super(),this.TypeAsEnum=Me.TamperProtectionState,this.Type="TamperProtection",this.Data=e.state}}!function(e){e[e.OK=0]="OK",e[e.Breach=1]="Breach"}(gt||(gt={}));class fn{constructor(){this._onDeviceStateChangedEvent=new n,this._onDeviceTasksExecutionChangedOnChannelsEvent=new n,this._serialNumber=null,this._model=null,this._modelGuid=null,this._manufacturerGuid=null,this._isVirtual=!1,this._isEnabled=!1,this._deviceState=$e.Working,this._deviceType=We.Unknown,this._communicationWay=Le.OneWay,this._availableTasksTypes=[],this._availableResponseTypes=[],this._channels=[];const e=hd.Get(Pn.ServiceName),t=this._onDeviceStateChangedEvent,r=this._onDeviceTasksExecutionChangedOnChannelsEvent;e.OnDeviceStateChangedEvent().Subscribe((e=>{e.Device.Guid==this._guid&&t.Invoke(e.State)})),e.OnDevicesTasksExecutionChangeEvent().Subscribe((e=>{r.Invoke(e.filter((e=>e.DeviceGuid==this._guid)).map((e=>e.Channel)))}))}get States(){return hd.Get(Pn.ServiceName).GetDeviceStates(this).selectMany((e=>e.States)).toArray()}RemoveDeviceAsync(){return hd.Get(Pn.ServiceName).RemoveDeviceAsync(this)}ExecuteDeviceTaskAsync(e){return hd.Get(Pn.ServiceName).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 Name(){return null==this._name?"":this._name}set Name(e){this._name=e}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}ChangeDeviceNameAsync(e){return t=this,n=void 0,o=function*(){try{const t=yield hd.Get(Ie.ServiceName).SendAndWaitForResponseAsync(new pn(this,e),2e4,!1);switch(t.Status){case oe.OK:return new Re(ke.Changed,"");case oe.WrongData:if("DeviceNotFound"==t.Data)return new Re(ke.Failed,"DeviceNotFound");break;case oe.NoPermissionsToCallGivenResource:return new Re(ke.NoPermissions,"")}}catch(e){return e.message.includes("timeout")?new Re(ke.ControllerResponseTimeout,""):new Re(ke.UnknownError,"")}return new Re(ke.Unknown,"")},new((r=void 0)||(r=Promise))((function(e,i){function s(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(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(s,a)}c((o=o.apply(t,n||[])).next())}));var t,n,r,o}ExecuteTaskAsync(e){return hd.Get(Pn.ServiceName).ExecuteDeviceTaskAsync(this,e)}}class pn extends re{constructor(e,t){super(),this.Resource="/devices/device/name",this.Method=ie.Put;const n=new mn;n.DeviceGuid=e.Guid,n.Name=t,this.Data=n}}class mn{constructor(){this.DeviceGuid="",this.Name=""}}var yn,wn,Sn,_n,Cn;class bn{constructor(){this._device=new fn,this._number=0,this._name="",this._iconName="",this._mode=Pe.Default,this._channelGroups=[],this._isHidden=!1,this._availableTasksTypes=[],this._availableResponseTypes=[],this._onTasksExecutionChangedEvent=new n}SetDevice(e){this._device=e}GetDevice(){return this._device}GetChannelConfigurationData(){const e=new An;return e.Channel=this._number,e.ChannelName=this._name,e.Configuration=this._mode,e.GroupsGuids=this._channelGroups,e.Hidden=this._isHidden,e.IconName=this._iconName,e}HideAsync(){const e=this.GetChannelConfigurationData();return e.Hidden=!0,this.ChangeConfigurationAsync(e)}ShowAsync(){const e=this.GetChannelConfigurationData();return e.Hidden=!1,this.ChangeConfigurationAsync(e)}ChangeNameAsync(e){const t=this.GetChannelConfigurationData();return t.ChannelName=e,this.ChangeConfigurationAsync(t)}ChangeIconNameAsync(e){const t=this.GetChannelConfigurationData();return t.IconName=e,this.ChangeConfigurationAsync(t)}ChangeGroupsAsync(e){const t=this.GetChannelConfigurationData();return t.GroupsGuids=e,this.ChangeConfigurationAsync(t)}ChangeConfigurationAsync(e){var t,n,r,i,s;return n=this,r=void 0,s=function*(){try{const n=yield hd.Get(Ie.ServiceName).SendAndWaitForResponseAsync(new En(e),2e4,!1);switch(n.Status){case oe.OK:return new Re(ke.Changed,"");case oe.WrongData:if("DeviceNotFound"===n.Data)return null===(t=o.Log)||void 0===t||t.Error("Failed to change channel configuration, referenced device does not exist!"),new Re(ke.WrongData,"DeviceNotFound");break;case oe.FatalError:return new Re(ke.UnknownError,"")}}catch(e){if(e.message.includes("timeout"))return new Re(ke.ControllerResponseTimeout,"")}return new Re(ke.Unknown,"")},new((i=void 0)||(i=Promise))((function(e,t){function o(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 i?n:new i((function(e){e(n)}))).then(o,a)}c((s=s.apply(n,r||[])).next())}))}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 hd.Get(Pn.ServiceName).GetDeviceStates(this.GetDevice()).selectMany((e=>e.States)).where((e=>e.Data.Channel==this.Number)).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,hd.Get(Pn.ServiceName).ExecuteDeviceTaskAsync(this._device,e)):Promise.resolve(Ue.Failed)}}class An{constructor(){this.Channel=0,this.ChannelName="",this.Configuration=Pe.Default,this.GroupsGuids=[],this.IconName="",this.Hidden=!1}}class En extends re{constructor(e){super(),this.Resource="/devices/device/channel/configuration",this.Method=ie.Put,this.Data=e}}(Cn=yn||(yn={}))[Cn.TurnOn=0]="TurnOn",Cn[Cn.TurnOff=1]="TurnOff",Cn[Cn.ToggleState=2]="ToggleState",Cn[Cn.SetBlindPosition=3]="SetBlindPosition",Cn[Cn.SetLightColor=4]="SetLightColor",Cn[Cn.SetLightTemperature=5]="SetLightTemperature",Cn[Cn.SetLightBrightness=6]="SetLightBrightness",Cn[Cn.SetTemperature=7]="SetTemperature",Cn[Cn.GetState=8]="GetState",Cn[Cn.TurnOnWithTimeout=9]="TurnOnWithTimeout",Cn[Cn.SetLightBrightnessDynamicly=10]="SetLightBrightnessDynamicly",Cn[Cn.IdentifyDevice=11]="IdentifyDevice",Cn[Cn.SetBlindOpenCloseTime=12]="SetBlindOpenCloseTime",Cn[Cn.SetBlindMicroventilation=13]="SetBlindMicroventilation",Cn[Cn.GatewayPulse=25]="GatewayPulse",Cn[Cn.GatePulse=26]="GatePulse",Cn[Cn.SetFacadePositionAndTilt=29]="SetFacadePositionAndTilt",Cn[Cn.GetFacadeType=30]="GetFacadeType";class Dn{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 Nn{constructor(){this._taskType=xe.GetChannelsState,this._featureType=yn.GetState,this._channel=0,this._guid=Dn.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 Tn extends Nn{constructor(){super(),this.Action=wn.Stop,this.Position=0,this.FeatureType=yn.SetBlindPosition,this.TaskType=xe.SetBlindPosition}}!function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop",e[e.Percentage=3]="Percentage"}(wn||(wn={})),function(e){e[e.Open=0]="Open",e[e.Close=1]="Close",e[e.Stop=2]="Stop"}(Sn||(Sn={}));class kn extends Nn{constructor(){super(),this.Data=new Fn,this.FeatureType=yn.SetBlindOpenCloseTime,this.TaskType=xe.SetBlindOpenCloseTime}}class Fn{constructor(){this.Channel=0,this.CloseTime=0,this.OpenTime=0}}class In extends Nn{constructor(){super(),this.FeatureType=yn.GetState,this.TaskType=xe.GetChannelsState}}class Rn extends Nn{constructor(){super(),this.FacadeAction=_n.Stop,this.Tilt=0,this.Position=0,this.FeatureType=yn.SetFacadePositionAndTilt,this.TaskType=xe.SetFacadePosition}}!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"}(_n||(_n={}));var Gn,On=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Pn{constructor(){this._devices=[],this._onDevicesTasksChangedEvent=new n,this._onDeviceFoundEvent=new n,this._onDeviceRegisteredEvent=new n,this._onDeviceRemovedEvent=new n,this._onDeviceStateChangedEvent=new n,this._connection=null,this._session=null,this._controllerConfiguration=null,this._fastStatesSync=!1,this._synchronized=!1,this._synchronizedDevicesStates=!1,this._devicesChannelsStates=[],this._synchronizationTaskCompletionSource=null,this._deviceStatesSynchronizationTaskCompletionSource=null,this._connection=hd.Get(Ie.ServiceName),this._session=hd.Get(Se.ServiceName),this._controllerConfiguration=hd.Get(Ae.ServiceName),this._onDeviceStateChangedEvent.Subscribe((e=>On(this,void 0,void 0,(function*(){return this.PutDeviceStateOnList(e.Device,e.State)})))),this._synchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>On(this,void 0,void 0,(function*(){var t;try{this._devices=yield this.GetPairedDevicesAsync()}catch(e){null===(t=o.Log)||void 0===t||t.Error(Pn.ServiceName,`Failed to get paired devices: ${e}`)}this._synchronized=!0,e()}))))})),this._deviceStatesSynchronizationTaskCompletionSource=new Promise((e=>{var t;null===(t=this._session)||void 0===t||t.OnUserLoggedInEvent().Subscribe((t=>On(this,void 0,void 0,(function*(){var t;try{yield this.WaitForSynchronizationAsync(),yield this.SyncDevicesStatesAsync()}catch(e){null===(t=o.Log)||void 0===t||t.Error(Pn.ServiceName,`Failed to sync devices states: ${e}`)}this._synchronizedDevicesStates=!0,e()}))))})),this._connection.OnDataReceivedEvent().Subscribe((e=>{if("/info/devices/tasks"===e.Resource)this.ParseDeviceTaskInfo(e.Data);else if("/devices/blinds/times"===e.Resource);else if("/info/devices/device/found"===e.Resource)this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=o.Log)||void 0===t||t.Debug(Pn.ServiceName,`Found device: ${e.Name} guid: ${e.Guid}`),this._onDeviceFoundEvent.Invoke(e)}));else if("/info/devices/device/state/changed"===e.Resource){const t=e.Data,n=this._devices.filter((e=>e.Guid==t.DeviceGuid));if(n.length>0){const e=n[0],r=this.MapApiDeviceStateToDeviceState(e,t);null!=r&&(this._onDeviceStateChangedEvent.Invoke({Device:e,State:r}),r.TypeAsEnum==Me.SignalStrength?e.Channels.forEach((n=>{let o=new Jt(Object.assign({},t));r.Data.Channel=n.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:o})})):r.TypeAsEnum==Me.BatteryState&&e.Channels.forEach((n=>{let o=new Ut(Object.assign({},t));r.Data.Channel=n.Number,this._onDeviceStateChangedEvent.Invoke({Device:e,State:o})})))}}else"/info/devices/device/registered"===e.Resource?this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=o.Log)||void 0===t||t.Debug(Pn.ServiceName,`Registered device: ${e.Name} guid: ${e.Guid}`),this._onDeviceRegisteredEvent.Invoke(e)})):"/info/devices/device/removed"===e.Resource&&this.MapApiDevices(e.Data).forEach((e=>{var t;null===(t=o.Log)||void 0===t||t.Debug(Pn.ServiceName,`Removed device: ${e.Name} guid: ${e.Guid}`),this._onDeviceRemovedEvent.Invoke(e)}))}))}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 xn;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));null==e?(e=new xn,e.Channel=t.Data.Channel,e.States=[t],n.ChannelsStates.push(e)):(null!=e.States.firstOrDefault((e=>e.TypeAsEnum==t.TypeAsEnum))&&(e.States=e.States.where((e=>e.TypeAsEnum!=t.TypeAsEnum)).toArray()),e.States.push(t))}}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}WaitForDevicesStatesSynchronizationAsync(){return this._deviceStatesSynchronizationTaskCompletionSource}GetCurrentlyRunningTaksAsync(){var e;return On(this,void 0,void 0,(function*(){const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Kn,15e3,!1);(null==t?void 0:t.Status)==oe.OK&&null!=t.Data&&this.ParseDeviceTaskInfo(t.Data)}))}ParseDeviceTaskInfo(e){const t=[];e.forEach((e=>{const n=e.split(";"),r=new Ft;r.DeviceGuid=n[0],r.Channel=Number(n[1]),r.Status=Oe.ExecutingTasks,t.push(r)})),this._onDevicesTasksChangedEvent.Invoke(t)}MapApiDeviceStateToDeviceState(e,t){var n;switch(t.state,t.DataType){case"ChannelOnOff":return new Gt(t);case"DoorBell":return new Ot(t);case"ReedPosition":return new Pt(t);case"BlindPosition":return new xt(t);case"ButtonState":return new Mt(t);case"LightColor":return new $t(t);case"LightTemperature":return new Lt(t);case"LightBrightness":return new Wt(t);case"TemperatureSensor":case"TemperatureState":case"MeasuredTemperature":return new Bt(t);case"BatteryState":return new Ut(t);case"MeasuredBrightness":case"DeviceBrightnessState":return new Kt(t);case"EnergyMeasuredPower":case"EnergyMeasuredCurrent":case"EnergyMeasuredVoltage":break;case"Energy":return new Ht(t);case"DistanceSensor":return new zt(t);case"MovementSensor":return new jt(t);case"BlindsControlButton":return new qt(t);case"FacadeControlButton":return new Vt(t);case"SignalStrength":return new Jt(t);case"GatePosition":return new Yt(t);case"GatewayPosition":return new Xt(t);case"IBlindCalibrationStatus":case"BlindCalibration":return new Qt(t);case"HumiditySensor":case"HumidityState":return new Zt(t);case"VibrationSensor":return new en(t);case"DigitalInputSensor":return new tn(t);case"ConfigurationState":return new nn(t);case"BlindOpenCloseTime":case"IBlindOpenCloseTime":return new rn(t);case"IOvercurrentProtection":case"OvercurrentProtection":return new on(t);case"IOvercurrentProtectionThreshold":case"OvercurrentProtectionThreshold":return new sn(t);case"FacadePosition":case"FacadeState":return new an(t);case"FacadeTypeState":return new cn(t);case"CurrentWindThreshold":return new ln(t);case"CurrentLightThreshold":return new un(t);case"WindSpeed":return new dn(t);case"FloodSensor":return new hn(t);case"PressureState":return new vn(t);case"ITamperProtection":case"TamperProtection":return new gn(t);default:null===(n=o.Log)||void 0===n||n.Debug(Pn.ServiceName,`Not supported device state ${t.DataType}`)}return null}GetServiceName(){return Pn.ServiceName}SyncDevicesStatesAsync(){var e,t;return On(this,void 0,void 0,(function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new $n,15e3,!1);if(this._fastStatesSync)return(null==n?void 0:n.Status)==oe.OK;{let e=new Ln;e.Data=!0;const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(e,35e3,!1);return(null==n?void 0:n.Status)==oe.OK}}))}OnDevicesTasksExecutionChangeEvent(){return this._onDevicesTasksChangedEvent}OnDeviceStateChangedEvent(){return this._onDeviceStateChangedEvent}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,i,s,a=new fn;a.Guid=e.Guid,a.Name=e.DeviceName,a.ChannelsAmount=e.ChannelsNumber,a.DeviceType=e.DeviceType,a.CommunicationWay=e.CommunicationWay,a.DeviceState=e.DeviceState,a.IsEnabled=e.IsEnabled,a.IsVirtual=e.IsVirtual,a.SerialNumber=e.DeviceSerialNumber,a.ManufacturerGuid=e.ManufacturerGuid,a.ModelGuid=e.DeviceModelGuid,a.Model=e.DeviceModel,a.Name=e.DeviceName;try{null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new Tt;if(a.CommunicationWay==Le.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}a.AvailableTaskTypes.push(t)})),null===(r=e.AvailableResponses)||void 0===r||r.forEach((e=>{var t=new kt;t.InterfaceType=e,a.AvailableResponseTypes.push(t)})),null===(i=e.ChannelsConfiguration)||void 0===i||i.forEach((e=>{var t,n,r;try{var i=new bn;i.SetDevice(a),a.Channels.push(i),i.Number=e.Channel,i.Name=e.ChannelName,i.ChannelGroups=e.GroupsGuids,i.IconName=e.IconName,i.IsHidden=e.Hidden,null===(t=e.AvailableResponses)||void 0===t||t.forEach((e=>{var t=new kt;t.InterfaceType=e,i.AvailableResponseTypes.push(t)})),null===(n=e.AvailableTasks)||void 0===n||n.forEach((e=>{var t=new Tt;t.InterfaceType=e,i.AvailableTaskTypes.push(t)}))}catch(e){null===(r=o.Log)||void 0===r||r.Error(e)}}))}catch(e){null===(s=o.Log)||void 0===s||s.Error(e)}t.push(a)})),this._devices=t,t)}GetPairedDevicesAsync(){var e,t,n;return On(this,void 0,void 0,(function*(){if(this._synchronized&&!(yield null===(e=this._controllerConfiguration)||void 0===e?void 0:e.DidCofigurationChangeAsync()))return Promise.resolve(this._devices);const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Mn,15e3,!0);return null==r||void 0===r?[]:r.Status==oe.OK&&null!=r.Data?this.MapApiDevices(r.Data):(null===(n=o.Log)||void 0===n||n.Error(Pn.ServiceName,`Failed to get devices. ${r.Status} ${r.Data}`),[])}))}GetDevicesAsync(){return On(this,void 0,void 0,(function*(){return yield this.WaitForSynchronizationAsync(),this.GetPairedDevicesAsync()}))}GetFoundDevicesAsync(){var e,t;return On(this,void 0,void 0,(function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Un,15e3,!1);return null==n?[]:n.Status==oe.OK&&null!=n.Data?this.MapApiDevices(n.Data):(null===(t=o.Log)||void 0===t||t.Error(Pn.ServiceName,`Failed to get found devices. ${n.Status} ${n.Data}`),[])}))}GetDevice(e){return this._devices.find((t=>t.Guid===e))}FindDevicesAsync(){var e;return On(this,void 0,void 0,(function*(){yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Wn,35e3,!1)}))}StopSearchingForDevices(){var e;return On(this,void 0,void 0,(function*(){yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Bn,2e4,!1)}))}RegisterDeviceAsync(e){var t;return On(this,void 0,void 0,(function*(){const n=new Hn;n.Data=e.Guid;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,2e4,!1);return(null==r?void 0:r.Status)==oe.OK?(this._devices.push(e),this._onDeviceRegisteredEvent.Invoke(e),Ue.Executed):Ue.Failed}))}RemoveDeviceAsync(e){var t;return On(this,void 0,void 0,(function*(){var n=new zn;n.Data=e.Guid;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,35e3,!1);return(null==r?void 0:r.Status)==oe.OK?(this._devices=this._devices.where((t=>t.Guid==e.Guid)).toArray(),this._onDeviceRemovedEvent.Invoke(e),Ue.Executed):Ue.Failed}))}MapDeviceTaskToDeviceTaskInfo(e,t){let n=new Vn;const r=t;switch(r.FeatureType){case yn.SetTemperature:n.Data=r.Temperature;break;case yn.SetLightBrightness:n.Data=r.Brightness;break;case yn.SetLightColor:n=new Jn;const e=r;n.R=e.R,n.G=e.G,n.B=e.B;break;case yn.SetLightTemperature:n.Data=r.Temperature;break;case yn.SetBlindPosition:switch(r.Action){case wn.Open:n.Data=101;break;case wn.Close:n.Data=102;break;case wn.Stop:n.Data=103;break;case wn.Percentage:n.Data=r.Position}break;case yn.SetLightBrightnessDynamicly:n.Data=r.Brightness;break;case yn.SetBlindOpenCloseTime:n.Data=r.Data;break;case yn.SetBlindMicroventilation:n.Data=r.Position;break;case yn.SetFacadePositionAndTilt:n=new Yn;const t=r;n.FacadeAction=t.FacadeAction,n.Tilt=t.Tilt,n.Position=t.Position}return n.Channel=r.Channel,n.DeviceGuid=e.Guid,n.ControlFeature=r.FeatureType,n}ExecuteDeviceTaskAsync(e,t){var n,r,i,s,a,c,l,u;return On(this,void 0,void 0,(function*(){try{null===(n=o.Log)||void 0===n||n.Debug(Pn.ServiceName,`Preparing device task execution, device: ${e.Guid} task: ${t.TaskType} channel: ${t.Channel}`);let u=this.MapDeviceTaskToDeviceTaskInfo(e,t);try{const e=new jn(u);null===(r=o.Log)||void 0===r||r.Debug(Pn.ServiceName,`Sending device task for execution, device: ${u.DeviceGuid} task: ${u.ControlFeature} channel: ${u.Channel} request: ${JSON.stringify(e)}`);const t=yield null===(i=this._connection)||void 0===i?void 0:i.SendAndWaitForResponseAsync(e,15e3,!1);switch(null==t?void 0:t.Status){case oe.OK:return Ue.Executed;case oe.FatalError:return null===(s=o.Log)||void 0===s||s.Error(Pn.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),Ue.Failed;case oe.WrongData:if("DeviceNotFound"===t.Data)return Ue.DeviceNotFound;break;case oe.Error:return"DeviceResponseTimeout"===t.Data?Ue.DeviceResponseTimeout:(null===(a=o.Log)||void 0===a||a.Error(Pn.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${t.Data}`),Ue.Failed)}}catch(e){return e.message.includes("timeout")?(null===(c=o.Log)||void 0===c||c.Error(Pn.ServiceName,`Failed to get controller response in time.\n${e}`),Ue.ControllerResponseTimeout):(null===(l=o.Log)||void 0===l||l.Error(Pn.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),Ue.Failed)}return Ue.Unknown}catch(e){return null===(u=o.Log)||void 0===u||u.Error(Pn.ServiceName,`Unknown error occured when tried to execute task on device.\n${e}`),Ue.Failed}}))}ExecuteDevicesTasksAsync(e){var t,n,r,i;return On(this,void 0,void 0,(function*(){let s=[],a=[],c=0;for(const[t,n]of e){const e=this.MapDeviceTaskToDeviceTaskInfo(t,n);e.SequnceExecutionOrder=c,c++,a.push(e)}const l=new qn(a);try{const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(l,12e4,!1);let i=-1;null===(n=null==r?void 0:r.Data)||void 0===n||n.forEach((t=>{var n,a;i++;let c=Ue.Unknown;switch(t.Status){case oe.OK:return Ue.Executed;case oe.FatalError:null===(n=o.Log)||void 0===n||n.Error(Pn.ServiceName,`Fatal error occured when tried to execute task on device. Error code: ${t.Data}`),c=Ue.Failed;break;case oe.WrongData:"DeviceNotFound"===t.Data&&(c=Ue.DeviceNotFound);break;case oe.Error:"DeviceResponseTimeout"===t.Data?c=Ue.DeviceResponseTimeout:(null===(a=o.Log)||void 0===a||a.Error(Pn.ServiceName,`Unknown error occured when trying to execute task on device. Error code: ${r.Data}`),c=Ue.Failed)}let l=0,u=new It;for(const[t,n]of e){if(l==i){u.Device=t,u.Task=n,u.Channel=n.Channel,s.push(u);break}l++}}))}catch(t){if(t.message.includes("timeout")){null===(r=o.Log)||void 0===r||r.Error(Pn.ServiceName,`Failed to get controller response in time.\n${t}`);for(const[t,n]of e){let e=new It;s.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=Ue.ControllerResponseTimeout}}else{null===(i=o.Log)||void 0===i||i.Error(Pn.ServiceName,`Unknown error occured when tried to execute task on device.\n${t}`);for(const[t,n]of e){let e=new It;s.push(e),e.Device=t,e.Task=n,e.Channel=n.Channel,e.Result=Ue.Failed}}}return s}))}}Pn.ServiceName="DevicesService";class xn{constructor(){this.Channel=0,this.States=[]}}class Mn extends re{constructor(){super(),this.Resource="/devices/list",this.Method=ie.Get}}class $n extends re{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states",this.Method=ie.Get}}class Ln extends re{constructor(){super(),this.Data=!1,this.Resource="/devices/channels/states/sync",this.Method=ie.Get}}class Wn extends re{constructor(){super(),this.Resource="/devices/search",this.Method=ie.Post}}class Bn extends re{constructor(){super(),this.Resource="/devices/search/stop",this.Method=ie.Post}}class Un extends re{constructor(){super(),this.Resource="/devices/found/list",this.Method=ie.Get}}class Kn extends re{constructor(){super(),this.Resource="/devices/tasks",this.Method=ie.Get}}class Hn extends re{constructor(){super(),this.Resource="/devices/device/pair",this.Method=ie.Put}}class zn extends re{constructor(){super(),this.Resource="/devices/device/unpair",this.Method=ie.Put}}class jn extends re{constructor(e){super(),this.Resource="/devices/device/control",this.Method=ie.Post,this.Data=e}}class qn extends re{constructor(e){super(),this.Resource="/devices/devices/control",this.Method=ie.Post,this.Data=e}}class Vn{constructor(){this.DeviceGuid="",this.Channel=0,this.ControlFeature=yn.GetState,this.SequnceExecutionOrder=0}}class Jn extends Vn{constructor(){super(...arguments),this.R=0,this.G=0,this.B=0}}class Yn extends Vn{constructor(){super(...arguments),this.FacadeAction=_n.Stop,this.Tilt=0,this.Position=0}}class Xn{constructor(){this.Longitude=0,this.Latitude=0}}class Qn{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"}(Gn||(Gn={}));var Zn=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class er{IsControllerGeolocationSetAsync(){return Zn(this,void 0,void 0,(function*(){let e=new tr,t=yield hd.Get(Ie.ServiceName).SendAndWaitForResponseAsync(e,15e3,!0);return(null==t?void 0:t.Status)===oe.OK?null==t?void 0:t.Data:null==t?void 0:t.Status}))}GetCurrentGeolocationAsync(){return Zn(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Zn(this,void 0,void 0,(function*(){window.navigator.geolocation.getCurrentPosition((t=>{e(t)}),(t=>{e(t)}))}))))}))}SetControllerGeolocationAsync(e){var t,n;return Zn(this,void 0,void 0,(function*(){let r=new rr;r.Data.Latitude=e.Latitude,r.Data.Longitude=e.Longitude,null===(t=o.Log)||void 0===t||t.Warning(er.ServiceName,`SetControllerGeolocationAsync() ${JSON.stringify(r)}`);let i=yield hd.Get(Ie.ServiceName).SendAndWaitForResponseAsync(r,15e3,!1);switch(null===(n=o.Log)||void 0===n||n.Warning(er.ServiceName,`${JSON.stringify(i)}`),null==i?void 0:i.Status){case oe.OK:return new Ge(Gn.OK,"");case oe.NoPermissionToPerformThisOperation:case oe.NoPermissionsToCallGivenResource:return new Ge(Gn.NoPermissions,"");case oe.UserIsNotLoggedIn:return new Ge(Gn.UserIsNotLoggedIn,"");default:return new Ge(Gn.UnknownError,"")}}))}GetControlllerGeolocationAsync(){var e,t;return Zn(this,void 0,void 0,(function*(){let n=new nr;null===(e=o.Log)||void 0===e||e.Warning(er.ServiceName,`GetControlllerGeolocationAsync(): ${JSON.stringify(n)}`);let r=yield hd.Get(Ie.ServiceName).SendAndWaitForResponseAsync(n,15e3,!0);if(null===(t=o.Log)||void 0===t||t.Warning(er.ServiceName,`${JSON.stringify(r)}`),(null==r?void 0:r.Status)===oe.OK){let e=new Qn;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 er.ServiceName}}er.ServiceName="GeolocationService";class tr extends re{constructor(){super(),this.Resource="/geolocation/isset",this.Method=ie.Get}}class nr extends re{constructor(){super(),this.Resource="/geolocation/get",this.Method=ie.Get}}class rr extends re{constructor(){super(),this.Data=new Xn,this.Resource="/geolocation/save",this.Method=ie.Put}}class or extends RangeError{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 ir=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 sr extends Error{constructor(e){super(e),this.name="InvalidOperationException",this.stack=this.stack||(new Error).stack}}const ar=(e,t)=>e===t;class cr extends Array{}class lr{constructor(e){this.iterator=e}[Symbol.asyncIterator](){return this.iterator()}}class ur{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 dr{constructor(e){this.iterator=e}[Symbol.iterator](){return this.iterator()}}const hr=e=>{var t;const n=cr.prototype,r=e.prototype,o=Object.getOwnPropertyNames(n);for(const e of o)r[e]=null!==(t=r[e])&&void 0!==t?t:n[e]},vr=(e,t,n,r)=>{if(r){if(!n)throw new ReferenceError("TAccumulate function is undefined");return pr(e,t,n,r)}return n?fr(e,t,n):gr(e,t)},gr=(e,t)=>{let n;for(const r of e)n=n?t(n,r):r;if(void 0===n)throw new sr(ir.NoElements);return n},fr=(e,t,n)=>{let r=t;for(const t of e)r=n(r,t);return r},pr=(e,t,n,r)=>{let o=t;for(const t of e)o=n(o,t);return r(o)},mr=(e,t)=>{for(const n of e)if(!1===t(n))return!1;return!0},yr=async(e,t)=>{for(const n of e)if(!1===await t(n))return!1;return!0},wr=(e,t)=>t?_r(e,t):Sr(e),Sr=e=>{for(const t of e)return!0;return!1},_r=(e,t)=>{for(const n of e)if(!0===t(n))return!0;return!1},Cr=async(e,t)=>{for(const n of e)if(!0===await t(n))return!0;return!1},br=e=>{if(Array.isArray(e)){if(0===e.length)throw new sr(ir.NoElements);return new lr((async function*(){for await(const t of e)yield t}))}return new lr(e)},Ar=e=>br((async function*(){for(const t of e)yield t})),Er=(e,t)=>new ur({generator:t,type:e}),Dr=e=>Er(0,(async()=>{const t=[];for(const n of e)t.push(n);return t})),Nr=(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 sr(ir.NoElements);return n/r},Tr=async(e,t)=>{let n=0,r=0;for(const o of e)n+=await t(o),r+=1;if(0===r)throw new sr(ir.NoElements);return n/r},kr=(e,t)=>{if(t<1)throw new or("index");return new dr((function*(){let n=[];for(const r of e)n.push(r),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},Fr=(e,t)=>new dr((function*(){yield*e,yield*t})),Ir=(e,t,n=ar)=>{for(const r of e)if(n(t,r))return!0;return!1},Rr=async(e,t,n)=>{for(const r of e)if(await n(t,r))return!0;return!1},Gr=(e,t)=>t?Pr(e,t):Or(e),Or=e=>{let t=0;for(const n of e)t++;return t},Pr=(e,t)=>{let n=0;for(const r of e)!0===t(r)&&n++;return n},xr=async(e,t)=>{let n=0;for(const r of e)!0===await t(r)&&n++;return n},Mr=(e,t)=>new dr((function*(){let n=!1;for(const t of e)n=!0,yield t;n||(yield t)})),$r=(e,t=ar)=>new dr((function*(){const n=[];for(const r of e)n.find((e=>t(e,r)))||(n.push(r),yield r)})),Lr=(e,t)=>br((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}})),Wr=(e,t)=>new dr((function*(){for(const n of e)t(n),yield n})),Br=(e,t)=>br((async function*(){for(const n of e)await t(n),yield n})),Ur=(e,t)=>{if(t<0)throw new or("index");let n=0;for(const r of e)if(t===n++)return r;throw new or("index")},Kr=(e,t)=>{let n=0;for(const r of e)if(t===n++)return r;return null},Hr=(e,t,n=ar)=>new dr((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)}})),zr=(e,t,n)=>br((async function*(){const r=[...t];for(const t of e){let e=!1;for(let o=0;o<r.length;o++){const i=r[o];if(!0===await n(t,i)){e=!0;break}}!1===e&&(yield t)}})),jr=(e,t)=>t?Vr(e,t):qr(e),qr=e=>{const t=e[Symbol.iterator]().next();if(!0===t.done)throw new sr(ir.NoElements);return t.value},Vr=(e,t)=>{for(const n of e)if(!0===t(n))return n;throw new sr(ir.NoMatch)},Jr=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;throw new sr(ir.NoMatch)},Yr=(e,t)=>t?Qr(e,t):Xr(e),Xr=e=>e[Symbol.iterator]().next().value||null,Qr=(e,t)=>{for(const n of e)if(!0===t(n))return n;return null},Zr=async(e,t)=>{for(const n of e)if(!0===await t(n))return n;return null};class eo extends cr{constructor(e,t){super(1),this.key=e,this[0]=t}}const to=(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 i=!1;for(let t=0;t<r.length;t++){const s=r[t];if(n(s.key,e)){s.push(o),i=!0;break}}!1===i&&r.push(new eo(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 eo(e,r)}for(const e in n)yield n[e]})(e,t),new dr(r)},no=(e,t,n)=>n?oo(e,t,n):ro(e,t),ro=(e,t)=>br((async function*(){const n={};for(const r of e){const e=await t(r),o=n[e];o?o.push(r):n[e]=new eo(e,r)}for(const e in n)yield n[e]})),oo=(e,t,n)=>br((async function*(){const r=new Array;for(const o of e){const e=await t(o);let i=!1;for(let t=0;t<r.length;t++){const s=r[t];if(!0===await n(s.key,e)){s.push(o),i=!0;break}}!1===i&&r.push(new eo(e,o))}for(const e of r)yield e})),io=(e,t,n,r)=>r?((e,t,n,r)=>new dr((function*(){const o=new Array;for(const i of e){const e=t(i);let s=!1;for(let t=0;t<o.length;t++){const a=o[t];if(r(a.key,e)){a.push(n(i)),s=!0;break}}if(!1===s){const t=n(i);o.push(new eo(e,t))}}for(const e of o)yield e})))(e,t,n,r):((e,t,n)=>new dr((function*(){const r={};for(const o of e){const e=t(o),i=r[e],s=n(o);i?i.push(s):r[e]=new eo(e,s)}for(const e in r)yield r[e]})))(e,t,n),so=(e,t,n,r,o,i)=>{const s=i?ao(e,t,n,r,o,i):co(e,t,n,r,o);return new dr(s)},ao=(e,t,n,r,o,i)=>function*(){var s;const a=[];for(const e of t){const t=r(e),n=a.find((e=>i(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for(const t of e){const e=n(t),r=null!==(s=a.find((t=>i(t.key,e))))&&void 0!==s?s:{key:e,values:[]};yield o(t,r.values)}},co=(e,t,n,r,o)=>function*(){var i;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=null!==(i=s.get(e))&&void 0!==i?i:[];yield o(t,r)}},lo=(e,t,n,r,o,i)=>{const s=i?uo(e,t,n,r,o,i):ho(e,t,n,r,o);return br(s)},uo=(e,t,n,r,o,i)=>async function*(){var s;const a=[];for(const e of t){const t=await r(e),n=a.find((e=>i(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for(const t of e){const e=await n(t),r=null!==(s=a.find((t=>i(t.key,e))))&&void 0!==s?s:{key:e,values:[]};yield o(t,r.values)}},ho=(e,t,n,r,o)=>async function*(){var i;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=null!==(i=s.get(e))&&void 0!==i?i:[];yield o(t,r)}},vo=(e,t,n=ar)=>new dr((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}}})),go=(e,t,n)=>br((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}}}})),fo=(e,t,n,r,o,i=ar)=>new dr((function*(){const s=[...t];for(const t of e){const e=n(t);for(const n of s){const s=r(n);!0===i(e,s)&&(yield o(t,n))}}})),po=(e,t)=>t?yo(e,t):mo(e),mo=e=>{let t;for(const n of e)t=n;if(!t)throw new sr(ir.NoElements);return t},yo=(e,t)=>{let n;for(const r of e)!0===t(r)&&(n=r);if(!n)throw new sr(ir.NoMatch);return n},wo=async(e,t)=>{let n;for(const r of e)!0===await t(r)&&(n=r);if(!n)throw new sr(ir.NoMatch);return n},So=(e,t)=>t?Co(e,t):_o(e),_o=e=>{let t=null;for(const n of e)t=n;return t},Co=(e,t)=>{let n=null;for(const r of e)!0===t(r)&&(n=r);return n},bo=async(e,t)=>{let n=null;for(const r of e)!0===await t(r)&&(n=r);return n},Ao=(e,t)=>t?Do(e,t):Eo(e),Eo=e=>{let t=null;for(const n of e)t=Math.max(t||Number.NEGATIVE_INFINITY,n);if(null===t)throw new sr(ir.NoElements);return t},Do=(e,t)=>{let n=null;for(const r of e)n=Math.max(n||Number.NEGATIVE_INFINITY,t(r));if(null===n)throw new sr(ir.NoElements);return n},No=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 sr(ir.NoElements);return n},To=(e,t)=>t?Fo(e,t):ko(e),ko=e=>{let t=null;for(const n of e)t=Math.min(t||Number.POSITIVE_INFINITY,n);if(null===t)throw new sr(ir.NoElements);return t},Fo=(e,t)=>{let n=null;for(const r of e)n=Math.min(n||Number.POSITIVE_INFINITY,t(r));if(null===n)throw new sr(ir.NoElements);return n},Io=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 sr(ir.NoElements);return n},Ro=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new dr((function*(){for(const t of e)n(t)&&(yield t)}))};async function*Go(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}function*Oo(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}class Po extends lr{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 Po?async function*(){for await(const o of e.orderedPairs())yield*Go(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}(e,t,n,r),new Po(o)}static generate(e,t,n,r){let o;return o=e instanceof Po?async function*(){for await(const o of e.orderedPairs())yield*Oo(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}(e,t,n,r),new Po(o)}thenBy(e,t){return Po.generate(this,e,!0,t)}thenByAsync(e,t){return Po.generateAsync(this,e,!0,t)}thenByDescending(e,t){return Po.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return Po.generateAsync(this,e,!1,t)}}function*xo(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}async function*Mo(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}class $o extends dr{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 $o?function*(){for(const o of e.orderedPairs())yield*xo(o,t,n,r)}:()=>xo(e,t,n,r),new $o(o)}static generateAsync(e,t,n,r){let o;return o=e instanceof $o?async function*(){for(const o of e.orderedPairs())yield*Mo(o,t,n,r)}:()=>Mo(e,t,n,r),new Po(o)}thenBy(e,t){return $o.generate(this,e,!0,t)}thenByAsync(e,t){return $o.generateAsync(this,e,!0,t)}thenByDescending(e,t){return $o.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return $o.generateAsync(this,e,!1,t)}}const Lo=(e,t,n)=>$o.generate(e,t,!0,n),Wo=(e,t,n)=>$o.generateAsync(e,t,!0,n),Bo=(e,t,n)=>$o.generate(e,t,!1,n),Uo=(e,t,n)=>$o.generateAsync(e,t,!1,n),Ko=(e,t)=>{const n=[],r=[];for(const o of e)!0===t(o)?r.push(o):n.push(o);return[r,n]},Ho=async(e,t)=>{const n=[],r=[];for(const o of e)!0===await t(o)?r.push(o):n.push(o);return[r,n]},zo=e=>new dr((function*(){const t=[...e];for(let e=t.length-1;e>=0;e--)yield t[e]})),jo=(e,t)=>{if("function"==typeof t){const{length:n}=t;return 1===n?qo(e,t):Vo(e,t)}return Jo(e,t)},qo=(e,t)=>new dr((function*(){for(const n of e)yield t(n)})),Vo=(e,t)=>new dr((function*(){let n=0;for(const r of e)yield t(r,n),n++})),Jo=(e,t)=>new dr((function*(){for(const n of e)yield n[t]})),Yo=(e,t)=>"function"==typeof t?1===t.length?Xo(e,t):Qo(e,t):Zo(e,t),Xo=(e,t)=>br((async function*(){for(const n of e)yield t(n)})),Qo=(e,t)=>br((async function*(){let n=0;for(const r of e)yield t(r,n),n++})),Zo=(e,t)=>br((async function*(){for(const n of e)yield n[t]})),ei=(e,t)=>"function"==typeof t?1===t.length?ti(e,t):ni(e,t):ri(e,t),ti=(e,t)=>new dr((function*(){for(const n of e)for(const e of t(n))yield e})),ni=(e,t)=>new dr((function*(){let n=0;for(const r of e){for(const e of t(r,n))yield e;n++}})),ri=(e,t)=>new dr((function*(){for(const n of e)for(const e of n[t])yield e})),oi=(e,t)=>1===t.length?ii(e,t):si(e,t),ii=(e,t)=>br((async function*(){for(const n of e){const e=await t(n);for(const t of e)yield t}})),si=(e,t)=>br((async function*(){let n=0;for(const r of e){const e=await t(r,n);for(const t of e)yield t;n++}})),ai=(e,t,n=ar)=>{const r=e[Symbol.iterator](),o=t[Symbol.iterator]();let i=r.next(),s=o.next();for(;!i.done&&!s.done;){if(!n(i.value,s.value))return!1;i=r.next(),s=o.next()}return!0===i.done&&!0===s.done},ci=async(e,t,n)=>{const r=e[Symbol.iterator](),o=t[Symbol.iterator]();let i=r.next(),s=o.next();for(;!i.done&&!s.done;){if(!1===await n(i.value,s.value))return!1;i=r.next(),s=o.next()}return!0===i.done&&!0===s.done},li=(e,t)=>t?di(e,t):ui(e),ui=e=>{let t=!1,n=null;for(const r of e){if(!0===t)throw new sr(ir.MoreThanOneElement);t=!0,n=r}if(!1===t)throw new sr(ir.NoElements);return n},di=(e,t)=>{let n=!1,r=null;for(const o of e)if(t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new sr(ir.NoMatch);return r},hi=async(e,t)=>{let n=!1,r=null;for(const o of e)if(await t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new sr(ir.NoMatch);return r},vi=(e,t)=>t?fi(e,t):gi(e),gi=e=>{let t=!1,n=null;for(const r of e){if(!0===t)throw new sr(ir.MoreThanOneElement);t=!0,n=r}return n},fi=(e,t)=>{let n=!1,r=null;for(const o of e)if(t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}return r},pi=async(e,t)=>{let n=!1,r=null;for(const o of e)if(await t(o)){if(!0===n)throw new sr(ir.MoreThanOneElement);n=!0,r=o}return r},mi=(e,t)=>new dr((function*(){let n=0;for(const r of e)n++>=t&&(yield r)})),yi=(e,t)=>1===t.length?wi(e,t):Si(e,t),wi=(e,t)=>new dr((function*(){let n=!0;for(const r of e)!1===n?yield r:!1===t(r)&&(n=!1,yield r)})),Si=(e,t)=>new dr((function*(){let n=0,r=!0;for(const o of e)!1===r?yield o:!1===t(o,n)&&(r=!1,yield o),n++})),_i=(e,t)=>1===t.length?Ci(e,t):bi(e,t),Ci=(e,t)=>br((async function*(){let n=!0;for(const r of e)!1===n?yield r:!1===await t(r)&&(n=!1,yield r)})),bi=(e,t)=>br((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++})),Ai=(e,t)=>t?Di(e,t):Ei(e),Ei=e=>{let t=0;for(const n of e)t+=n;return t},Di=(e,t)=>{let n=0;for(const r of e)n+=t(r);return n},Ni=async(e,t)=>{let n=0;for(const r of e)n+=await t(r);return n},Ti=(e,t)=>new dr((function*(){let n=t>0?t:0;for(const t of e){if(0==n--)break;yield t}})),ki=(e,t)=>1===t.length?Fi(e,t):Ii(e,t),Fi=(e,t)=>new dr((function*(){for(const n of e){if(!t(n))break;yield n}})),Ii=(e,t)=>new dr((function*(){let n=0;for(const r of e){if(!t(r,n++))break;yield r}})),Ri=(e,t)=>1===t.length?Gi(e,t):Oi(e,t),Gi=(e,t)=>br((async function*(){for(const n of e){if(!await t(n))break;yield n}})),Oi=(e,t)=>br((async function*(){let n=0;for(const r of e){if(!await t(r,n++))break;yield r}})),Pi=e=>[...e],xi=(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},Mi=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},$i=(e,t)=>{const n={};for(const r of e)n[t(r)]=r;return n},Li=async(e,t)=>{const n={};for(const r of e)n[await t(r)]=r;return n},Wi=e=>new Set(e),Bi=(e,t,n)=>n?Ki(e,t,n):Ui(e,t),Ui=(e,t)=>new dr((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))})),Ki=(e,t,n)=>new dr((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))}})),Hi=(e,t,n)=>br((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))}})),zi=(e,t)=>1===t.length?ji(e,t):qi(e,t),ji=(e,t)=>new dr((function*(){for(const n of e)!0===t(n)&&(yield n)})),qi=(e,t)=>new dr((function*(){let n=0;for(const r of e)!0===t(r,n++)&&(yield r)})),Vi=(e,t)=>1===t.length?Ji(e,t):Yi(e,t),Ji=(e,t)=>br((async function*(){for(const n of e)!0===await t(n)&&(yield n)})),Yi=(e,t)=>br((async function*(){let n=0;for(const r of e)!0===await t(r,n++)&&(yield r)})),Xi=(e,t,n)=>n?Zi(e,t,n):Qi(e,t),Qi=(e,t)=>new dr((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]}})),Zi=(e,t,n)=>new dr((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)}})),es=(e,t,n)=>br((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)}})),ts=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(vr,"aggregate"),n(mr,"all"),n(yr,"allAsync"),n(wr,"any"),n(Cr,"anyAsync"),n(Ar,"asAsync"),n(Dr,"asParallel"),n(Nr,"average"),n(Tr,"averageAsync"),n(kr,"chunk"),n(Fr,"concatenate"),n(Ir,"contains"),n(Rr,"containsAsync"),n(Gr,"count"),n(xr,"countAsync"),n(Mr,"defaultIfEmpty"),n($r,"distinct"),n(Lr,"distinctAsync"),n(Wr,"each"),n(Br,"eachAsync"),n(Ur,"elementAt"),n(Kr,"elementAtOrDefault"),n(Hr,"except"),n(zr,"exceptAsync"),n(jr,"first"),n(Jr,"firstAsync"),n(Yr,"firstOrDefault"),n(Zr,"firstOrDefaultAsync"),n(to,"groupBy"),n(no,"groupByAsync"),n(io,"groupByWithSel"),n(so,"groupJoin"),n(lo,"groupJoinAsync"),n(vo,"intersect"),n(go,"intersectAsync"),n(fo,"joinByKey"),n(po,"last"),n(wo,"lastAsync"),n(So,"lastOrDefault"),n(bo,"lastOrDefaultAsync"),n(Ao,"max"),n(No,"maxAsync"),n(To,"min"),n(Io,"minAsync"),n(Ro,"ofType"),n(Lo,"orderBy"),n(Wo,"orderByAsync"),n(Bo,"orderByDescending"),n(Uo,"orderByDescendingAsync"),n(zo,"reverse"),n(jo,"select"),n(Yo,"selectAsync"),n(ei,"selectMany"),n(oi,"selectManyAsync"),n(ai,"sequenceEquals"),n(ci,"sequenceEqualsAsync"),n(li,"single"),n(hi,"singleAsync"),n(vi,"singleOrDefault"),n(pi,"singleOrDefaultAsync"),n(mi,"skip"),n(yi,"skipWhile"),n(_i,"skipWhileAsync"),n(Ai,"sum"),n(Ni,"sumAsync"),n(Ti,"take"),n(ki,"takeWhile"),n(Ri,"takeWhileAsync"),n(Pi,"toArray"),n(xi,"toMap"),n(Mi,"toMapAsync"),n($i,"toObject"),n(Li,"toObjectAsync"),n(Ko,"partition"),n(Ho,"partitionAsync"),n(Wi,"toSet"),n(Bi,"union"),n(Hi,"unionAsync"),n(zi,"where"),n(Vi,"whereAsync"),n(Xi,"zip"),n(es,"zipAsync")},ns=(e,t,n,r)=>{if(r){if(!n)throw new ReferenceError("TAccumulate function is undefined");return is(e,t,n,r)}return n?os(e,t,n):rs(e,t)},rs=async(e,t)=>{let n;for await(const r of e)n=n?t(n,r):r;if(void 0===n)throw new sr(ir.NoElements);return n},os=async(e,t,n)=>{let r=t;for await(const t of e)r=n(r,t);return r},is=async(e,t,n,r)=>{let o=t;for await(const t of e)o=n(o,t);return r(o)},ss=async(e,t)=>{for await(const n of e)if(!1===t(n))return!1;return!0},as=async(e,t)=>{for await(const n of e)if(!1===await t(n))return!1;return!0},cs=(e,t)=>t?us(e,t):ls(e),ls=async e=>{for await(const t of e)return!0;return!1},us=async(e,t)=>{for await(const n of e)if(!0===t(n))return!0;return!1},ds=async(e,t)=>{for await(const n of e)if(!0===await t(n))return!0;return!1},hs=e=>Er(0,(async()=>{const t=[];for await(const n of e)t.push(n);return t})),vs=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 sr(ir.NoElements);return n/r},gs=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 sr(ir.NoElements);return n/r},fs=(e,t)=>{if(t<1)throw new or("index");return new lr((async function*(){let n=[];for await(const r of e)n.push(r),n.length===t&&(yield n,n=[]);n.length&&(yield n)}))},ps=(e,t)=>new lr((async function*(){yield*e,yield*t})),ms=async(e,t,n=ar)=>{for await(const r of e)if(n(t,r))return!0;return!1},ys=async(e,t,n)=>{for await(const r of e)if(await n(t,r))return!0;return!1},ws=(e,t)=>t?_s(e,t):Ss(e),Ss=async e=>{let t=0;for await(const n of e)t++;return t},_s=async(e,t)=>{let n=0;for await(const r of e)!0===t(r)&&n++;return n},Cs=async(e,t)=>{let n=0;for await(const r of e)!0===await t(r)&&n++;return n},bs=(e,t)=>new lr((async function*(){let n=!1;for await(const t of e)n=!0,yield t;n||(yield t)})),As=(e,t=ar)=>new lr((async function*(){const n=[];for await(const r of e)n.find((e=>t(e,r)))||(n.push(r),yield r)})),Es=(e,t)=>new lr((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}})),Ds=(e,t)=>new lr((async function*(){for await(const n of e)t(n),yield n})),Ns=(e,t)=>new lr((async function*(){for await(const n of e)await t(n),yield n})),Ts=async(e,t)=>{if(t<0)throw new or("index");let n=0;for await(const r of e)if(t===n++)return r;throw new or("index")},ks=async(e,t)=>{let n=0;for await(const r of e)if(t===n++)return r;return null},Fs=(e,t,n=ar)=>new lr((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 i=r[o];if(!0===n(t,i)){e=!0;break}}!1===e&&(yield t)}})),Is=(e,t,n)=>new lr((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 i=r[o];if(!0===await n(t,i)){e=!0;break}}!1===e&&(yield t)}})),Rs=(e,t)=>t?Os(e,t):Gs(e),Gs=async e=>{const t=await e[Symbol.asyncIterator]().next();if(!0===t.done)throw new sr(ir.NoElements);return t.value},Os=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;throw new sr(ir.NoMatch)},Ps=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;throw new sr(ir.NoMatch)},xs=(e,t)=>t?$s(e,t):Ms(e),Ms=async e=>(await e[Symbol.asyncIterator]().next()).value||null,$s=async(e,t)=>{for await(const n of e)if(!0===t(n))return n;return null},Ls=async(e,t)=>{for await(const n of e)if(!0===await t(n))return n;return null},Ws=(e,t,n)=>n?Bs(e,t,n):Us(e,t),Bs=(e,t,n)=>new lr((async function*(){const r=new Array;for await(const o of e){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const s=r[t];if(n(s.key,e)){s.push(o),i=!0;break}}!1===i&&r.push(new eo(e,o))}for(const e of r)yield e})),Us=(e,t)=>new lr((async function*(){const n={};for await(const r of e){const e=t(r),o=n[e];o?o.push(r):n[e]=new eo(e,r)}for(const e in n)yield n[e]})),Ks=(e,t,n)=>n?zs(e,t,n):Hs(e,t),Hs=(e,t)=>new lr((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 eo(e,r)}for(const e in n)yield n[e]})),zs=(e,t,n)=>new lr((async function*(){const r=new Array;for await(const o of e){const e=await t(o);let i=!1;for(let t=0;t<r.length;t++){const s=r[t];if(!0===await n(s.key,e)){s.push(o),i=!0;break}}!1===i&&r.push(new eo(e,o))}for(const e of r)yield e})),js=(e,t,n,r)=>r?Vs(e,t,n,r):qs(e,t,n),qs=(e,t,n)=>new lr((async function*(){const r={};for await(const o of e){const e=t(o),i=r[e],s=n(o);i?i.push(s):r[e]=new eo(e,s)}for(const e in r)yield r[e]})),Vs=(e,t,n,r)=>new lr((async function*(){const o=new Array;for await(const i of e){const e=t(i);let s=!1;for(let t=0;t<o.length;t++){const a=o[t];if(r(a.key,e)){a.push(n(i)),s=!0;break}}if(!1===s){const t=n(i);o.push(new eo(e,t))}}for(const e of o)yield e})),Js=(e,t,n,r,o,i)=>{const s=i?Ys(e,t,n,r,o,i):Xs(e,t,n,r,o);return new lr(s)},Ys=(e,t,n,r,o,i)=>async function*(){var s;const a=[];for await(const e of t){const t=r(e),n=a.find((e=>i(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for await(const t of e){const e=n(t),r=null!==(s=a.find((t=>i(t.key,e))))&&void 0!==s?s:{key:e,values:[]};yield o(t,r.values)}},Xs=(e,t,n,r,o)=>async function*(){var i;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=null!==(i=s.get(e))&&void 0!==i?i:[];yield o(t,r)}},Qs=(e,t,n,r,o,i)=>{const s=i?Zs(e,t,n,r,o,i):ea(e,t,n,r,o);return new lr(s)},Zs=(e,t,n,r,o,i)=>async function*(){var s;const a=[];for await(const e of t){const t=await r(e),n=a.find((e=>i(e.key,t)));n?n.values.push(e):a.push({key:t,values:[e]})}for await(const t of e){const e=await n(t),r=null!==(s=a.find((t=>i(t.key,e))))&&void 0!==s?s:{key:e,values:[]};yield o(t,r.values)}},ea=(e,t,n,r,o)=>async function*(){var i;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=null!==(i=s.get(e))&&void 0!==i?i:[];yield o(t,r)}},ta=(e,t,n=ar)=>new lr((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}}}})),na=(e,t,n)=>new lr((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}}}})),ra=(e,t,n,r,o,i=ar)=>new lr((async function*(){const s=[];for await(const e of t)s.push(e);for await(const t of e){const e=n(t);for(const n of s){const s=r(n);!0===i(e,s)&&(yield o(t,n))}}})),oa=(e,t)=>t?sa(e,t):ia(e),ia=async e=>{let t=null;for await(const n of e)t=n;if(!t)throw new sr(ir.NoElements);return t},sa=async(e,t)=>{let n=null;for await(const r of e)!0===t(r)&&(n=r);if(!n)throw new sr(ir.NoMatch);return n},aa=async(e,t)=>{let n=null;for await(const r of e)!0===await t(r)&&(n=r);if(!n)throw new sr(ir.NoMatch);return n},ca=(e,t)=>t?ua(e,t):la(e),la=async e=>{let t=null;for await(const n of e)t=n;return t},ua=async(e,t)=>{let n=null;for await(const r of e)!0===t(r)&&(n=r);return n},da=async(e,t)=>{let n=null;for await(const r of e)!0===await t(r)&&(n=r);return n},ha=(e,t)=>t?ga(e,t):va(e),va=async e=>{let t=null;for await(const n of e)t=Math.max(t||Number.NEGATIVE_INFINITY,n);if(null===t)throw new sr(ir.NoElements);return t},ga=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 sr(ir.NoElements);return n},fa=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 sr(ir.NoElements);return n},pa=(e,t)=>t?ya(e,t):ma(e),ma=async e=>{let t=null;for await(const n of e)t=Math.min(t||Number.POSITIVE_INFINITY,n);if(null===t)throw new sr(ir.NoElements);return t},ya=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 sr(ir.NoElements);return n},wa=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 sr(ir.NoElements);return n},Sa=(e,t)=>{const n="string"==typeof t?e=>typeof e===t:e=>e instanceof t;return new lr((async function*(){for await(const t of e)n(t)&&(yield t)}))},_a=(e,t,n)=>Po.generate(e,t,!0,n),Ca=(e,t,n)=>Po.generateAsync(e,t,!0,n),ba=(e,t,n)=>Po.generate(e,t,!1,n),Aa=(e,t,n)=>Po.generateAsync(e,t,!1,n),Ea=async(e,t)=>{const n=[],r=[];for await(const o of e)!0===t(o)?r.push(o):n.push(o);return[r,n]},Da=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]},Na=e=>new lr((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]})),Ta=(e,t)=>"function"==typeof t?1===t.length?ka(e,t):Fa(e,t):Ia(e,t),ka=(e,t)=>new lr((async function*(){for await(const n of e)yield t(n)})),Fa=(e,t)=>new lr((async function*(){let n=0;for await(const r of e)yield t(r,n),n++})),Ia=(e,t)=>new lr((async function*(){for await(const n of e)yield n[t]})),Ra=(e,t)=>"string"==typeof t?Oa(e,t):Ga(e,t),Ga=(e,t)=>new lr((async function*(){for await(const n of e)yield t(n)})),Oa=(e,t)=>new lr((async function*(){for await(const n of e)yield n[t]})),Pa=(e,t)=>"function"==typeof t?1===t.length?xa(e,t):Ma(e,t):$a(e,t),xa=(e,t)=>new lr((async function*(){for await(const n of e)for(const e of t(n))yield e})),Ma=(e,t)=>new lr((async function*(){let n=0;for await(const r of e){for(const e of t(r,n))yield e;n++}})),$a=(e,t)=>new lr((async function*(){for await(const n of e)for(const e of n[t])yield e})),La=(e,t)=>1===t.length?new lr((async function*(){for await(const n of e){const e=await t(n);for(const t of e)yield t}})):new lr((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++}})),Wa=async(e,t,n=ar)=>{const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();let i=await Promise.all([r.next(),o.next()]),s=i[0],a=i[1];for(;!s.done&&!a.done;){if(!n(s.value,a.value))return!1;i=await Promise.all([r.next(),o.next()]),s=i[0],a=i[1]}return!0===s.done&&!0===a.done},Ba=async(e,t,n)=>{const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();let i=await Promise.all([r.next(),o.next()]),s=i[0],a=i[1];for(;!s.done&&!a.done;){if(!1===await n(s.value,a.value))return!1;i=await Promise.all([r.next(),o.next()]),s=i[0],a=i[1]}return!0===s.done&&!0===a.done},Ua=(e,t)=>t?Ha(e,t):Ka(e),Ka=async e=>{let t=!1,n=null;for await(const r of e){if(!0===t)throw new sr(ir.MoreThanOneElement);t=!0,n=r}if(!1===t)throw new sr(ir.NoElements);return n},Ha=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new sr(ir.NoMatch);return r},za=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(await t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}if(!1===n)throw new sr(ir.NoMatch);return r},ja=(e,t)=>t?Va(e,t):qa(e),qa=async e=>{let t=!1,n=null;for await(const r of e){if(!0===t)throw new sr(ir.MoreThanOneElement);t=!0,n=r}return n},Va=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}return r},Ja=async(e,t)=>{let n=!1,r=null;for await(const o of e)if(await t(o)){if(!0===n)throw new sr(ir.MoreThanOneMatchingElement);n=!0,r=o}return r},Ya=(e,t)=>new lr((async function*(){let n=0;for await(const r of e)n++>=t&&(yield r)})),Xa=(e,t)=>1===t.length?Qa(e,t):Za(e,t),Qa=(e,t)=>new lr((async function*(){let n=!0;for await(const r of e)!1===n?yield r:!1===t(r)&&(n=!1,yield r)})),Za=(e,t)=>new lr((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++})),ec=(e,t)=>1===t.length?tc(e,t):nc(e,t),tc=(e,t)=>new lr((async function*(){let n=!0;for await(const r of e)!1===n?yield r:!1===await t(r)&&(n=!1,yield r)})),nc=(e,t)=>new lr((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++})),rc=(e,t)=>t?ic(e,t):oc(e),oc=async e=>{let t=0;for await(const n of e)t+=n;return t},ic=async(e,t)=>{let n=0;for await(const r of e)n+=t(r);return n},sc=async(e,t)=>{let n=0;for await(const r of e)n+=await t(r);return n},ac=(e,t)=>new lr((async function*(){let n=t>0?t:0;for await(const t of e){if(0==n--)break;yield t}})),cc=(e,t)=>1===t.length?lc(e,t):uc(e,t),lc=(e,t)=>new lr((async function*(){for await(const n of e){if(!t(n))break;yield n}})),uc=(e,t)=>new lr((async function*(){let n=0;for await(const r of e){if(!t(r,n++))break;yield r}})),dc=(e,t)=>1===t.length?hc(e,t):vc(e,t),hc=(e,t)=>new lr((async function*(){for await(const n of e){if(!await t(n))break;yield n}})),vc=(e,t)=>new lr((async function*(){let n=0;for await(const r of e){if(!await t(r,n++))break;yield r}})),gc=async e=>{const t=[];for await(const n of e)t.push(n);return t},fc=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},pc=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},mc=async(e,t)=>{const n={};for await(const r of e)n[t(r)]=r;return n},yc=async(e,t)=>{const n={};for await(const r of e)n[await t(r)]=r;return n},wc=async e=>{const t=new Set;for await(const n of e)t.add(n);return t},Sc=(e,t,n)=>n?Cc(e,t,n):_c(e,t),_c=(e,t)=>new lr((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))})),Cc=(e,t,n)=>new lr((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))}})),bc=(e,t,n)=>new lr((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))}})),Ac=(e,t)=>1===t.length?Ec(e,t):Dc(e,t),Ec=(e,t)=>new lr((async function*(){for await(const n of e)!0===t(n)&&(yield n)})),Dc=(e,t)=>new lr((async function*(){let n=0;for await(const r of e)!0===t(r,n++)&&(yield r)})),Nc=(e,t)=>1===t.length?Tc(e,t):kc(e,t),Tc=(e,t)=>new lr((async function*(){for await(const n of e)!0===await t(n)&&(yield n)})),kc=(e,t)=>new lr((async function*(){let n=0;for await(const r of e)!0===await t(r,n++)&&(yield r)})),Fc=(e,t,n)=>n?Rc(e,t,n):Ic(e,t),Ic=(e,t)=>new lr((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]}})),Rc=(e,t,n)=>new lr((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)}})),Gc=(e,t,n)=>new lr((async function*(){const r=e[Symbol.asyncIterator](),o=t[Symbol.asyncIterator]();for(;;){const e=await Promise.all([r.next(),o.next()]),t=e[0],i=e[1];if(t.done||i.done)break;yield n(t.value,i.value)}})),Oc=(e,t,n,r)=>{if(r){if(!n)throw new ReferenceError("TAccumulate function is undefined");return Mc(e,t,n,r)}return n?xc(e,t,n):Pc(e,t)},Pc=async(e,t)=>{let n;for await(const r of e)n=n?t(n,r):r;if(void 0===n)throw new sr(ir.NoElements);return n},xc=async(e,t,n)=>{let r=t;for await(const t of e)r=n(r,t);return r},Mc=async(e,t,n,r)=>{let o=t;for await(const t of e)o=n(o,t);return r(o)},$c=(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}}},Lc=(e,t)=>{const n=$c(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))}},Wc=(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}}},Bc=(e,t)=>{const n=Wc(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))}},Uc=(e,t)=>t?Hc(e,t):Kc(e),Kc=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}},Hc=async(e,t)=>{const n=$c(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)}},zc=async(e,t)=>{const n=Wc(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)}},jc=e=>br((async function*(){for await(const t of e)yield t})),qc=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)}},Vc=async(e,t)=>{let n;n=t?$c(e,t):e.dataFunc;const r=await qc(n);if(0===r.length)throw new sr(ir.NoElements);let o=0;for(const e of r)o+=e;return o/r.length},Jc=async(e,t)=>{const n=Wc(e,t),r=await qc(n);if(0===r.length)throw new sr(ir.NoElements);let o=0;for(const e of r)o+=e;return o/r.length},Yc=(e,t)=>{if(t<1)throw new or("index");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 i=e.dataFunc.generator;n={type:0,generator:async()=>{const e=[];let n=[];for(const r of await i())n.push(r),n.length===t&&(e.push(n),n=[]);return n.length&&e.push(n),e}}}return new ur(n)},Xc=(e,t)=>new ur({generator:async()=>{const[n,r]=await Promise.all([e.toArray(),t.toArray()]);return[...n,...r]},type:0}),Qc=async(e,t,n=ar)=>{let r;switch(r=$c(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))}},Zc=async(e,t,n)=>{const r=Wc(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))}},el=(e,t)=>t?nl(e,t):tl(e),tl=async e=>{const t=e.dataFunc;switch(t.type){case 0:case 2:return(await e.toArray()).length;case 1:return t.generator().length}},nl=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},rl=async(e,t)=>{const n=Wc(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},ol=(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 ur(o)},il=(e,t=ar)=>new ur({generator:async()=>{const n=[];for(const r of await e.toArray())n.find((e=>t(e,r)))||n.push(r);return n},type:0}),sl=(e,t)=>new ur({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}),al=(e,t)=>new ur($c(e,(e=>(t(e),e)))),cl=(e,t)=>{const n=Wc(e,(async e=>(await t(e),e)));return new ur(n)},ll=async(e,t)=>{if(t<0)throw new or("index");const n=e.dataFunc;switch(n.type){case 0:{const e=await n.generator();if(t>=e.length)throw new or("index");return e[t]}case 1:{const e=n.generator();if(t>=e.length)throw new or("index");return await e[t]}case 2:{const e=await n.generator();if(t>=e.length)throw new or("index");return await e[t]}}},ul=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]}}},dl=(e,t,n=ar)=>new ur({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),i=[];for(const e of r){let t=!1;for(let r=0;r<o.length;r++){const i=o[r];if(!0===n(e,i)){t=!0;break}}!1===t&&i.push(e)}return i},type:0}),hl=(e,t,n)=>new ur({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),i=[];for(const e of r){let t=!1;for(let r=0;r<o.length;r++){const i=o[r];if(!0===await n(e,i)){t=!0;break}}!1===t&&i.push(e)}return i},type:0}),vl=e=>qc(e.dataFunc),gl=(e,t)=>t?pl(e,t):fl(e),fl=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new sr(ir.NoElements);return e[0]}case 1:{const e=t.generator();if(0===e.length)throw new sr(ir.NoElements);return await e[0]}case 2:{const e=await t.generator();if(0===e.length)throw new sr(ir.NoElements);return await e[0]}}},pl=async(e,t)=>{const n=await vl(e);for(const e of n)if(!0===t(e))return e;throw new sr(ir.NoMatch)},ml=async(e,t)=>{const n=await vl(e);for(const e of n)if(!0===await t(e))return e;throw new sr(ir.NoMatch)},yl=(e,t)=>t?Sl(e,t):wl(e),wl=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]}}},Sl=async(e,t)=>{const n=await vl(e);for(const e of n)if(!0===t(e))return e;return null},_l=async(e,t)=>{const n=await vl(e);for(const e of n)if(!0===await t(e))return e;return null},Cl=(e,t,n)=>n?Al(e,t,n):bl(e,t),bl=(e,t)=>new ur({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 eo(e,r)}const r=new Array;for(const e in n)r.push(n[e]);return r},type:0}),Al=(e,t,n)=>new ur({generator:async()=>{const r=new Array;for(const o of await e.toArray()){const e=t(o);let i=!1;for(let t=0;t<r.length;t++){const s=r[t];if(n(s.key,e)){s.push(o),i=!0;break}}!1===i&&r.push(new eo(e,o))}const o=new Array;for(const e of r)o.push(e);return o},type:0}),El=(e,t,n)=>n?Dl(e,t,n):Nl(e,t),Dl=(e,t,n)=>new ur({generator:async()=>{const r=Wc(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 i=new Array;for(const[e,t]of o){let r=!1;for(let o=0;o<i.length;o++){const s=i[o];if(!0===await n(s.key,e)){s.push(t),r=!0;break}}!1===r&&i.push(new eo(e,t))}const s=new Array;for(const e of i)s.push(e);return s},type:0}),Nl=(e,t)=>new ur({generator:async()=>{const n=Wc(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 eo(e,t)}const i=new Array;for(const e in o)i.push(o[e]);return i},type:0}),Tl=(e,t,n,r)=>r?kl(e,t,n,r):Fl(e,t,n),kl=(e,t,n,r)=>new ur({generator:async()=>{const o=new Array;for await(const i of e){const e=t(i);let s=!1;for(let t=0;t<o.length;t++){const a=o[t];if(r(a.key,e)){a.push(n(i)),s=!0;break}}if(!1===s){const t=n(i);o.push(new eo(e,t))}}const i=new Array;for(const e of o)i.push(e);return i},type:0}),Fl=(e,t,n)=>new ur({generator:async()=>{const r={};for(const o of await e.toArray()){const e=t(o),i=r[e],s=n(o);i?i.push(s):r[e]=new eo(e,s)}const o=new Array;for(const e in r)o.push(r[e]);return o},type:0}),Il=(e,t,n,r,o,i)=>{const s=i?Rl(e,t,n,r,o,i):Gl(e,t,n,r,o);return new ur({generator:s,type:0})},Rl=(e,t,n,r,o,i)=>async()=>{const s=[];for await(const e of t){const t=r(e),n=s.find((e=>i(e.key,t)));n?n.values.push(e):s.push({key:t,values:[e]})}return(await e.toArray()).map((e=>{var t;const r=n(e),a=null!==(t=s.find((e=>i(e.key,r))))&&void 0!==t?t:{key:r,values:[]};return o(e,a.values)}))},Gl=(e,t,n,r,o)=>async()=>{const i=new Map;for await(const e of t){const t=r(e),n=i.get(t);n?n.push(e):i.set(t,[e])}return(await e.toArray()).map((e=>{var t;const r=n(e),s=null!==(t=i.get(r))&&void 0!==t?t:[];return o(e,s)}))},Ol=(e,t,n,r,o,i)=>{const s=i?Pl(e,t,n,r,o,i):xl(e,t,n,r,o);return new ur({generator:s,type:0})},Pl=(e,t,n,r,o,i)=>async()=>{const s=[];for await(const e of t){const t=await r(e),n=s.find((e=>i(e.key,t)));n?n.values.push(e):s.push({key:t,values:[e]})}const a=(await e.toArray()).map((async e=>{var t;const r=await n(e),a=null!==(t=s.find((e=>i(e.key,r))))&&void 0!==t?t:{key:r,values:[]};return o(e,a.values)}));return await Promise.all(a)},xl=(e,t,n,r,o)=>async()=>{const i=new Map;for await(const e of t){const t=await r(e),n=i.get(t);n?n.push(e):i.set(t,[e])}const s=(await e.toArray()).map((async e=>{var t;const r=await n(e),s=null!==(t=i.get(r))&&void 0!==t?t:[];return o(e,s)}));return await Promise.all(s)},Ml=(e,t,n=ar)=>new ur({generator:async()=>{const r=await e.distinct(n).toArray();if(0===r.length)return[];const o=await t.toArray(),i=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)){i.push(t);break}}}return i},type:0}),$l=(e,t,n)=>new ur({generator:async()=>{const r=await e.distinctAsync(n).toArray();if(0===r.length)return[];const o=await t.toArray(),i=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)){i.push(t);break}}}return i},type:0}),Ll=(e,t,n,r,o,i=ar)=>new ur({generator:async()=>{const[s,a]=await Promise.all([t.toArray(),e.toArray()]),c=new Array;for(const e of a){const t=n(e);for(const n of s){const s=r(n);!0===i(t,s)&&c.push(o(e,n))}}return c},type:0}),Wl=(e,t)=>t?Ul(e,t):Bl(e),Bl=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(0===e.length)throw new sr(ir.NoElements);return e[e.length-1]}case 1:{const e=t.generator();if(0===e.length)throw new sr(ir.NoElements);return await e[e.length-1]}case 2:{const e=await t.generator();if(0===e.length)throw new sr(ir.NoElements);return await e[e.length-1]}}},Ul=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 sr(ir.NoMatch)},Kl=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 sr(ir.NoMatch)},Hl=(e,t)=>t?jl(e,t):zl(e),zl=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]}}},jl=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},ql=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},Vl=async(e,t)=>{let n;n=t?$c(e,t):e.dataFunc;const r=await qc(n);if(0===r.length)throw new sr(ir.NoElements);return Math.max.apply(null,r)},Jl=async(e,t)=>{const n=Wc(e,t),r=await qc(n);if(0===r.length)throw new sr(ir.NoElements);return Math.max.apply(null,r)},Yl=async(e,t)=>{let n;n=t?$c(e,t):e.dataFunc;const r=await qc(n);if(0===r.length)throw new sr(ir.NoElements);return Math.min.apply(null,r)},Xl=async(e,t)=>{const n=Wc(e,t),r=await qc(n);if(0===r.length)throw new sr(ir.NoElements);return Math.min.apply(null,r)},Ql=(e,t)=>{const n="string"==typeof t?e=>[typeof e===t,e]:e=>[e instanceof t,e];return new ur({generator:async()=>{const t=$c(e,n),r=await qc(t),o=[];for(const[e,t]of r)e&&o.push(t);return o},type:0})};async function*Zl(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}async function*eu(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}class tu extends ur{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 tu?async function*(){for await(const o of e.orderedPairs())yield*Zl(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}(e,t,n,r),new tu(o)}static generate(e,t,n,r){let o;return o=e instanceof tu?async function*(){for await(const o of e.orderedPairs())yield*eu(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),i=[...o.keys()].sort(r||void 0);if(n)for(let e=0;e<i.length;e++)yield o.get(i[e]);else for(let e=i.length-1;e>=0;e--)yield o.get(i[e])}(e,t,n,r),new tu(o)}thenBy(e,t){return tu.generate(this,e,!0,t)}thenByAsync(e,t){return tu.generateAsync(this,e,!0,t)}thenByDescending(e,t){return tu.generate(this,e,!1,t)}thenByDescendingAsync(e,t){return tu.generateAsync(this,e,!1,t)}}const nu=(e,t,n)=>tu.generate(e,t,!0,n),ru=(e,t,n)=>tu.generateAsync(e,t,!0,n),ou=(e,t,n)=>tu.generate(e,t,!1,n),iu=(e,t,n)=>tu.generateAsync(e,t,!1,n),su=async(e,t)=>{const n=$c(e,(e=>[t(e),e])),r=await qc(n),o=[],i=[];for(const[e,t]of r)e?i.push(t):o.push(t);return[i,o]},au=async(e,t)=>{const n=Wc(e,(async e=>[await t(e),e])),r=await qc(n),o=[],i=[];for(const[e,t]of r)e?i.push(t):o.push(t);return[i,o]},cu=e=>{const t=e.dataFunc;switch(t.type){case 1:return new ur({generator:()=>t.generator().reverse(),type:t.type});case 2:case 0:return new ur({generator:async()=>(await t.generator()).reverse(),type:t.type})}},lu=(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}}},uu=(e,t)=>"function"==typeof t?1===t.length?new ur($c(e,t)):new ur(lu(e,t)):new ur($c(e,(e=>e[t]))),du=(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}}},hu=(e,t)=>{let n;return n="function"==typeof t?1===t.length?Wc(e,t):du(e,t):Wc(e,(e=>e[t])),new ur(n)},vu=(e,t)=>new ur({generator:async()=>{let n;n="function"==typeof t?1===t.length?$c(e,t):lu(e,t):$c(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}),gu=(e,t)=>new ur({generator:async()=>{let n;n=1===t.length?Wc(e,t):du(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}),fu=async(e,t,n=ar)=>{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},pu=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],i=o[e];if(!1===await n(t,i))return!1}return!0},mu=(e,t)=>t?wu(e,t):yu(e),yu=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new sr(ir.MoreThanOneElement);if(0===e.length)throw new sr(ir.NoElements);return e[0]}case 1:{const e=t.generator();if(e.length>1)throw new sr(ir.MoreThanOneElement);if(0===e.length)throw new sr(ir.NoElements);return e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new sr(ir.MoreThanOneElement);if(0===e.length)throw new sr(ir.NoElements);return await e[0]}}},wu=async(e,t)=>{const n=await vl(e);let r=!1,o=null;for(const e of n)if(t(e)){if(!0===r)throw new sr(ir.MoreThanOneMatchingElement);r=!0,o=e}if(!1===r)throw new sr(ir.NoMatch);return o},Su=async(e,t)=>{const n=await vl(e);let r=!1,o=null;for(const e of n)if(!0===await t(e)){if(!0===r)throw new sr(ir.MoreThanOneMatchingElement);r=!0,o=e}if(!1===r)throw new sr(ir.NoMatch);return o},_u=(e,t)=>t?bu(e,t):Cu(e),Cu=async e=>{const t=e.dataFunc;switch(t.type){case 0:{const e=await t.generator();if(e.length>1)throw new sr(ir.MoreThanOneElement);return 0===e.length?null:e[0]}case 1:{const e=t.generator();if(e.length>1)throw new sr(ir.MoreThanOneElement);return 0===e.length?null:e[0]}case 2:{const e=await t.generator();if(e.length>1)throw new sr(ir.MoreThanOneElement);return 0===e.length?null:await e[0]}}},bu=async(e,t)=>{const n=await vl(e);let r=!1,o=null;for(const e of n)if(t(e)){if(!0===r)throw new sr(ir.MoreThanOneElement);r=!0,o=e}return o},Au=async(e,t)=>{const n=await vl(e);let r=!1,o=null;for(const e of n)if(!0===await t(e)){if(!0===r)throw new sr(ir.MoreThanOneElement);r=!0,o=e}return o},Eu=(e,t)=>{const n=e.dataFunc;switch(n.type){case 0:return new ur({generator:async()=>(await n.generator()).slice(t),type:0});case 1:return new ur({generator:()=>n.generator().slice(t),type:1});case 2:return new ur({generator:async()=>(await n.generator()).slice(t),type:2})}},Du=(e,t)=>new ur({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}),Nu=(e,t)=>new ur({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}),Tu=(e,t)=>t?Fu(e,t):ku(e),ku=async e=>{let t=0;for(const n of await e.toArray())t+=n;return t},Fu=async(e,t)=>{let n=0;for(const r of await e.toArray())n+=t(r);return n},Iu=async(e,t)=>{const n=Wc(e,t),r=await qc(n);let o=0;for(const e of r)o+=e;return o},Ru=(e,t)=>{const n=t>0?t:0,r=e.dataFunc;switch(r.type){case 1:return new ur({generator:()=>r.generator().splice(0,n),type:1});case 2:return new ur({generator:()=>r.generator().then((e=>e.splice(0,n))),type:2});default:return new ur({generator:()=>r.generator().then((e=>e.splice(0,n))),type:0})}},Gu=(e,t)=>new ur({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}),Ou=(e,t)=>new ur({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}),Pu=async(e,t)=>{const n=new Map,r=$c(e,(e=>[t(e),e])),o=await qc(r);for(const[e,t]of o){const r=n.get(e);void 0===r?n.set(e,[t]):r.push(t)}return n},xu=async(e,t)=>{const n=new Map,r=Wc(e,(async e=>[await t(e),e])),o=await qc(r);for(const[e,t]of o){const r=n.get(e);void 0===r?n.set(e,[t]):r.push(t)}return n},Mu=async(e,t)=>{const n=e.dataFunc,r=await qc(n),o={};for(const e of r)o[t(e)]=e;return o},$u=async(e,t)=>{const n=Wc(e,(async e=>[await t(e),e])),r=await qc(n),o={};for(const[e,t]of r)o[e]=t;return o},Lu=async e=>{const t=e.dataFunc,n=await qc(t);return new Set(n)},Wu=(e,t,n)=>n?Uu(e,t,n):Bu(e,t),Bu=(e,t)=>new ur({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}),Uu=(e,t,n)=>new ur({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}),Ku=(e,t,n)=>new ur({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}),Hu=(e,t)=>new ur({generator:async()=>(await e.toArray()).filter(t),type:0}),zu=(e,t)=>new ur({generator:async()=>{const n=du(e,(async(e,n)=>[await t(e,n),e])),r=await qc(n),o=[];for(const[e,t]of r)e&&o.push(t);return o},type:0}),ju=(e,t,n)=>n?Vu(e,t,n):qu(e,t),qu=(e,t)=>new ur({generator:async()=>{const[n,r]=await Promise.all([e.toArray(),t.toArray()]),o=n.length<r.length?n.length:r.length,i=new Array(o);for(let e=0;e<o;e++){const t=n[e],o=r[e];i[e]=[t,o]}return i},type:0}),Vu=(e,t,n)=>new ur({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),i=r.length<o.length?r.length:o.length,s=new Array(i);for(let e=0;e<i;e++){const t=r[e],i=o[e];s[e]=n(t,i)}return s},type:0}),Ju=(e,t,n)=>new ur({generator:async()=>{const[r,o]=await Promise.all([e.toArray(),t.toArray()]),i=r.length<o.length?r.length:o.length,s=new Array(i);for(let e=0;e<i;e++){const t=r[e],i=o[e];s[e]=n(t,i)}return Promise.all(s)},type:0});ts(dr),(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(ns,"aggregate"),n(ss,"all"),n(as,"allAsync"),n(cs,"any"),n(ds,"anyAsync"),n(hs,"asParallel"),n(vs,"average"),n(gs,"averageAsync"),n(fs,"chunk"),n(ps,"concatenate"),n(ms,"contains"),n(ys,"containsAsync"),n(ws,"count"),n(Cs,"countAsync"),n(bs,"defaultIfEmpty"),n(As,"distinct"),n(Es,"distinctAsync"),n(Ds,"each"),n(Ns,"eachAsync"),n(Ts,"elementAt"),n(ks,"elementAtOrDefault"),n(Fs,"except"),n(Is,"exceptAsync"),n(Rs,"first"),n(Ps,"firstAsync"),n(xs,"firstOrDefault"),n(Ls,"firstOrDefaultAsync"),n(Ws,"groupBy"),n(Ks,"groupByAsync"),n(js,"groupByWithSel"),n(Js,"groupJoin"),n(Qs,"groupJoinAsync"),n(ta,"intersect"),n(na,"intersectAsync"),n(ra,"joinByKey"),n(oa,"last"),n(aa,"lastAsync"),n(ca,"lastOrDefault"),n(da,"lastOrDefaultAsync"),n(ha,"max"),n(fa,"maxAsync"),n(pa,"min"),n(wa,"minAsync"),n(Sa,"ofType"),n(_a,"orderBy"),n(Ca,"orderByAsync"),n(ba,"orderByDescending"),n(Aa,"orderByDescendingAsync"),n(Ea,"partition"),n(Da,"partitionAsync"),n(Na,"reverse"),n(Ta,"select"),n(Ra,"selectAsync"),n(Pa,"selectMany"),n(La,"selectManyAsync"),n(Wa,"sequenceEquals"),n(Ba,"sequenceEqualsAsync"),n(Ua,"single"),n(za,"singleAsync"),n(ja,"singleOrDefault"),n(Ja,"singleOrDefaultAsync"),n(Ya,"skip"),n(Xa,"skipWhile"),n(ec,"skipWhileAsync"),n(rc,"sum"),n(sc,"sumAsync"),n(ac,"take"),n(cc,"takeWhile"),n(dc,"takeWhileAsync"),n(gc,"toArray"),n(fc,"toMap"),n(pc,"toMapAsync"),n(mc,"toObject"),n(yc,"toObjectAsync"),n(wc,"toSet"),n(Sc,"union"),n(bc,"unionAsync"),n(Ac,"where"),n(Nc,"whereAsync"),n(Fc,"zip"),n(Gc,"zipAsync")})(lr),(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(Oc,"aggregate"),n(Lc,"all"),n(Bc,"allAsync"),n(Uc,"any"),n(zc,"anyAsync"),n(jc,"asAsync"),n(Vc,"average"),n(Jc,"averageAsync"),n(Yc,"chunk"),n(Xc,"concatenate"),n(Qc,"contains"),n(Zc,"containsAsync"),n(el,"count"),n(rl,"countAsync"),n(ol,"defaultIfEmpty"),n(il,"distinct"),n(sl,"distinctAsync"),n(al,"each"),n(cl,"eachAsync"),n(ll,"elementAt"),n(ul,"elementAtOrDefault"),n(dl,"except"),n(hl,"exceptAsync"),n(gl,"first"),n(ml,"firstAsync"),n(yl,"firstOrDefault"),n(_l,"firstOrDefaultAsync"),n(Cl,"groupBy"),n(El,"groupByAsync"),n(Tl,"groupByWithSel"),n(Il,"groupJoin"),n(Ol,"groupJoinAsync"),n(Il,"groupJoin"),n(Ol,"groupJoinAsync"),n(Ml,"intersect"),n($l,"intersectAsync"),n(Ll,"joinByKey"),n(Wl,"last"),n(Kl,"lastAsync"),n(Hl,"lastOrDefault"),n(ql,"lastOrDefaultAsync"),n(Vl,"max"),n(Jl,"maxAsync"),n(Yl,"min"),n(Xl,"minAsync"),n(Ql,"ofType"),n(nu,"orderBy"),n(ru,"orderByAsync"),n(ou,"orderByDescending"),n(iu,"orderByDescendingAsync"),n(su,"partition"),n(au,"partitionAsync"),n(cu,"reverse"),n(uu,"select"),n(hu,"selectAsync"),n(vu,"selectMany"),n(gu,"selectManyAsync"),n(fu,"sequenceEquals"),n(pu,"sequenceEqualsAsync"),n(mu,"single"),n(Su,"singleAsync"),n(_u,"singleOrDefault"),n(Au,"singleOrDefaultAsync"),n(Eu,"skip"),n(Du,"skipWhile"),n(Nu,"skipWhileAsync"),n(Tu,"sum"),n(Iu,"sumAsync"),n(Ru,"take"),n(Gu,"takeWhile"),n(Ou,"takeWhileAsync"),n(vl,"toArray"),n(Pu,"toMap"),n(xu,"toMapAsync"),n(Mu,"toObject"),n($u,"toObjectAsync"),n(Lu,"toSet"),n(Wu,"union"),n(Ku,"unionAsync"),n(Hu,"where"),n(zu,"whereAsync"),n(ju,"zip"),n(Ju,"zipAsync")})(ur),(()=>{var e;const{prototype:t}=cr,n=Object.getOwnPropertyNames(dr.prototype);for(const r of n)t[r]=null!==(e=t[r])&&void 0!==e?e:dr.prototype[r];t.all=function(e){return this.every(e)},t.any=function(e){return e?this.some(e):0!==this.length},t.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},t.elementAt=function(e){if(e<0||e>=this.length)throw new or("index");return this[e]},t.elementAtOrDefault=function(e){return this[e]||null},t.first=function(e){if(e){const t=this.find(e);if(void 0===t)throw new sr(ir.NoMatch);return t}if(0===this.length)throw new sr(ir.NoElements);return this[0]},t.firstOrDefault=function(e){if(e){const t=this.find(e);return void 0===t?null:t}return 0===this.length?null:this[0]},t.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 sr(ir.NoMatch)}if(0===this.length)throw new sr(ir.NoElements);return this[this.length-1]},t.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]},t.max=function(e){if(0===this.length)throw new sr(ir.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)},t.min=function(e){if(0===this.length)throw new sr(ir.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)},t.reverse=function(){return Array.prototype.reverse.apply(this),this}})();var Yu;!function(e){e.Success="Success",e.NoPermissions="NoPermissions",e.NameToShort="NameToShort",e.NameAlreadyExists="NameAlreadyExists",e.OtherError="OtherError",e.UnknownError="UnknownError"}(Yu||(Yu={}));class Xu{constructor(){this._guid="",this._name=""}GetDevicesChannelsInGroupAsync(){return e=this,t=void 0,r=function*(){let e=[];for(let t of yield hd.Get(Pn.ServiceName).GetDevicesAsync())for(let n of t.Channels.where((e=>e.ChannelGroups.any((e=>e===this._guid)))))e.push(n);return e},new((n=void 0)||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,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}ChangeNameAsync(e){return hd.Get(ed.ServiceName).ChangeGroupNameAsync(this,e)}}var Qu,Zu=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class ed{constructor(){this._connection=null,this._synchronized=!1,this._synchronizationTaskCompletionSource=null,this._groups=[],this._connection=hd.Get(Ie.ServiceName),this._synchronizationTaskCompletionSource=new Promise((e=>{hd.Get(Se.ServiceName).OnUserLoggedInEvent().Subscribe((t=>Zu(this,void 0,void 0,(function*(){yield this.SyncGroups(),e(),this._synchronized=!0}))))}))}SyncGroups(){return Zu(this,void 0,void 0,(function*(){this._groups=yield this.GetGroupsAsync()}))}AddDeviceChannelToGroupByGuidAsync(e,t){var n,r;return Zu(this,void 0,void 0,(function*(){const o=new od;if(o.Data.Channel=e.Number,null==e.GetDevice())throw new Error("Device is not set on this channel!");o.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,o.Data.GroupGuid=t;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);return hd.Get(Te.ServiceName).ClearCache(),null!=i&&null!=i.Status?(i.Status==oe.OK&&e.ChannelGroups.push(t),i.Status):oe.Error}))}RemoveDeviceChannelFromGroupByGuidAsync(e,t){var n,r;return Zu(this,void 0,void 0,(function*(){const o=new id;if(null==e.GetDevice())throw new Error("Device is not set on this channel!");o.Data.DeviceGuid=null===(n=e.GetDevice())||void 0===n?void 0:n.Guid,o.Data.Channel=e.Number,o.Data.GroupGuid=t;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);return hd.Get(Te.ServiceName).ClearCache(),null!=i&&null!=i.Status?(i.Status==oe.OK&&(e.ChannelGroups=e.ChannelGroups.where((e=>e!=t)).toArray()),i.Status):oe.Error}))}UpsertGroupWithDevicesChannelsAsync(e,t){return Zu(this,void 0,void 0,(function*(){if(this._groups.all((t=>t.Guid!=e.Guid))){let t=yield this.AddNewGroupAsync(e.Name);if(!(t instanceof Xu))return t instanceof Ge?t:new Ge(Yu.UnknownError,"");e=t}for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e.Guid))))){let t=yield this.AddDeviceChannelToGroupAsync(n,e);if(t!==oe.OK)return hd.Get(r.ServiceName).Error(ed.ServiceName,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`),new Ge(Yu.UnknownError,`Failed to add device channel ${n.Name} to group ${e.Name}, controller responded with error ${t}`)}let n=yield hd.Get(Pn.ServiceName).GetDevicesAsync();for(let i of n)for(let n of i.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var o of n.ChannelGroups.where((t=>e.Guid==t))){let t=yield this.RemoveDeviceChannelFromGroupAsync(n,e);if(t!==oe.OK)return hd.Get(r.ServiceName).Error(ed.ServiceName,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`),new Ge(Yu.UnknownError,`Failed to remove device channel ${n.Name} from group ${e.Name}, controller responded with error ${t}`)}return e}))}UpdateGroupWithDevicesChannelsAsync(e,t){return Zu(this,void 0,void 0,(function*(){for(let n of t.where((t=>t.ChannelGroups.all((t=>t!==e))))){let t=yield this.AddDeviceChannelToGroupByGuidAsync(n,e);if(t!==oe.OK)return hd.Get(r.ServiceName).Error(ed.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),oe.FatalError}let n=yield hd.Get(Pn.ServiceName).GetDevicesAsync();for(let i of n)for(let n of i.Channels.except(t,((e,t)=>e.GetDevice().Guid==t.GetDevice().Guid&&e.Number==t.Number)))for(var o of n.ChannelGroups.where((t=>e==t))){let t=yield this.RemoveDeviceChannelFromGroupByGuidAsync(n,e);if(t!==oe.OK)return hd.Get(r.ServiceName).Error(ed.ServiceName,`Failed to add device channel ${n.Name} to group ${e}, controller responded with error ${t}`),oe.FatalError}return oe.OK}))}ChangeGroupNameByGuidAsync(e,t){var n,r;return Zu(this,void 0,void 0,(function*(){let o=new rd,i=new sd;i.Guid=e,i.Name=t,null===(n=o.Data)||void 0===n||n.push(i);const s=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(o,15e3,!1);if(hd.Get(Te.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),null!=s&&null!=s.Status)switch(s.Status){case oe.OK:return new Ge(Yu.Success,"");case oe.WrongData:switch(s.Data){case"NameToShort":return new Ge(Yu.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ge(Yu.NameAlreadyExists,"Group with this name already exists");default:return new Ge(Yu.OtherError,`Response error: ${s.Status} data: ${s.Data}`)}default:return new Ge(Yu.OtherError,`Response error: ${s.Status} data: ${s.Data}`)}return new Ge(Yu.UnknownError,"")}))}GetServiceName(){return ed.ServiceName}WaitForSynchronizationAsync(){return this._synchronizationTaskCompletionSource}GetGroupByGuid(e){return this._groups.first((t=>t.Guid===e))}ChangeGroupNameAsync(e,t){return this.ChangeGroupNameByGuidAsync(e.Guid,t)}RemoveGroupAsync(e){return this.RemoveGroupByGuidAsync(e.Guid)}RemoveGroupByGuidAsync(e){var t;return Zu(this,void 0,void 0,(function*(){let n=new td;n.Data=e;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(n,15e3,!1);hd.Get(Te.ServiceName).ClearCache(),yield this.SyncGroups();for(let t of yield hd.Get(Pn.ServiceName).GetDevicesAsync())for(let n of t.Channels)n.ChannelGroups.any((t=>t===e))&&(n.ChannelGroups=n.ChannelGroups.except(e,((e,t)=>e===t)).toArray());return null!=r&&null!=r.Status?null==r?void 0:r.Status:oe.Error}))}GetGroupsAsync(){var e,t;return Zu(this,void 0,void 0,(function*(){const n=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new nd,15e3,!1);let o=[];if((null==n?void 0:n.Status)===oe.OK){let e=hd.Get(r.ServiceName);return null===(t=n.Data)||void 0===t||t.forEach((t=>{let n=new Xu;n.Guid=t.Guid,n.Name=t.Name,e.Info(ed.ServiceName,`Got group: ${t.Name} ${t.Guid}`),o.push(n)})),o}throw new Error(`Failed to get groups, API responded with status ${null==n?void 0:n.Status} data: ${null==n?void 0:n.Data}`)}))}AddDeviceChannelToGroupAsync(e,t){return this.AddDeviceChannelToGroupByGuidAsync(e,t.Guid)}RemoveDeviceChannelFromGroupAsync(e,t){return this.RemoveDeviceChannelFromGroupByGuidAsync(e,t.Guid)}AddNewGroupAsync(e){var t,n;return Zu(this,void 0,void 0,(function*(){let r=new rd,o=new sd;o.Name=e,null===(t=r.Data)||void 0===t||t.push(o);const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(r,15e3,!1);if(hd.Get(Te.ServiceName).ClearCache(),this._groups=yield this.GetGroupsAsync(),null!=i&&null!=i.Status)switch(i.Status){case oe.OK:return this._groups.first((t=>t.Name===e));case oe.WrongData:switch(i.Data){case"NameToShort":return new Ge(Yu.NameToShort,"At least 3 characters required");case"NameAlreadyExists":return new Ge(Yu.NameAlreadyExists,"Group with this name already exists");default:return new Ge(Yu.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}default:return new Ge(Yu.OtherError,`Response error: ${i.Status} data: ${i.Data}`)}return new Ge(Yu.UnknownError,"")}))}}ed.ServiceName="ChannelsGroupsService";class td extends re{constructor(){super(),this.Resource="/devices/groups/group",this.Method=ie.Delete}}class nd extends re{constructor(){super(),this.Resource="/devices/groups/",this.Method=ie.Get}}class rd extends re{constructor(){super(),this.Resource="/devices/groups/group",this.Method=ie.Put,this.Data=[]}}class od extends re{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=ie.Put,this.Data=new ad}}class id extends re{constructor(){super(),this.Resource="/devices/device/channel/groups/group/",this.Method=ie.Delete,this.Data=new ad}}class sd{constructor(){this.Id=0,this.Guid="",this.Name=""}}class ad{constructor(){this.GroupGuid="",this.DeviceGuid="",this.Channel=0}}class cd{constructor(){this._promise=Promise.resolve(),this._disable=()=>{}}Lock(){this._promise=new Promise((e=>this._disable=e))}Unlock(){this._disable()}WaitForLockAsync(){return this._promise}}!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"}(Qu||(Qu={}));var ld,ud=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class dd{constructor(){this._syncLock=new cd,this._isInFouces=!0,this._canHibernate=!0,this._session=null,this._connection=null,this._currentAppState=Qu.Disconnected,this._returnedFromSuspension=!1,this._onReturnedFromSuspensionEvent=new me,this._onSuspendedEvent=new me,this._onEnterLowPowerModeEvent=new me,this._onExitLowPowerModeEvent=new me,this._onBackButtonPressedEvent=new me,this._onForwardButtonPressedEvent=new me,this._onAppStateChanged=new n,this.MonitorAppState(),this._onAppStateChanged.Subscribe((e=>this._currentAppState=e)),null==navigator.userAgent.match(/Safari/i)||navigator.mediaDevices?window.addEventListener("visibilitychange",(()=>ud(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,i;document.location,e.state&&("forward"==e.state.direction?(null===(t=o.Log)||void 0===t||t.Warning(dd.ServiceName,"Forward button pressed"),null===(n=this._onForwardButtonPressedEvent)||void 0===n||n.Invoke()):(null===(r=o.Log)||void 0===r||r.Warning(dd.ServiceName,"Back button pressed"),null===(i=this._onBackButtonPressedEvent)||void 0===i||i.Invoke()))}))}MonitorAppState(){return ud(this,void 0,void 0,(function*(){this._session=yield hd.GetAsync("SessionService"),this._connection=yield hd.GetAsync("ExalusConnectionService"),this._session.OnUserLoggedInEvent().Subscribe((e=>{var t;null===(t=o.Log)||void 0===t||t.Warning(dd.ServiceName,"App state changed to: logged in"),this._onAppStateChanged.Invoke(Qu.LoggedIn)})),this._session.OnUserLoggedOutEvent().Subscribe((e=>{var t;null===(t=o.Log)||void 0===t||t.Warning(dd.ServiceName,"App state changed to: logged out"),this._onAppStateChanged.Invoke(Qu.LoggedOut)})),this._connection.OnConnectionStateChangedEvent().Subscribe((e=>{var t,n,r,i,s,a;switch(e){case ce.Connected:null===(t=o.Log)||void 0===t||t.Warning(dd.ServiceName,"App state changed to: connected"),this._onAppStateChanged.Invoke(Qu.Connected);break;case ce.Disconnected:null===(n=o.Log)||void 0===n||n.Warning(dd.ServiceName,"App state changed to: disconnected"),this._onAppStateChanged.Invoke(Qu.Disconnected);break;case ce.Connecting:null===(r=o.Log)||void 0===r||r.Warning(dd.ServiceName,"App state changed to: connecting"),this._onAppStateChanged.Invoke(Qu.Connecting);break;case ce.Disconnecting:null===(i=o.Log)||void 0===i||i.Warning(dd.ServiceName,"App state changed to: disconnecting"),this._onAppStateChanged.Invoke(Qu.Disconnecting);break;case ce.Reconnecting:null===(s=o.Log)||void 0===s||s.Warning(dd.ServiceName,"App state changed to: reconnecting"),this._onAppStateChanged.Invoke(Qu.Reconnecting);break;case ce.Failed:null===(a=o.Log)||void 0===a||a.Warning(dd.ServiceName,"App state changed to: failed"),this._onAppStateChanged.Invoke(Qu.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(Qu.Suspended),null===(e=o.Log)||void 0===e||e.Warning(dd.ServiceName,"App state changed to: suspended"),null===(t=o.Log)||void 0===t||t.Warning(dd.ServiceName,"App switched to background"))}ReturnFromSuspension(){var e,t;this.IsHibernationAllowed()&&(this._returnedFromSuspension=!0,this._onReturnedFromSuspensionEvent.Invoke(),this._onAppStateChanged.Invoke(Qu.ReturnedFromSuspension),null===(e=o.Log)||void 0===e||e.Warning(dd.ServiceName,"App state changed to: returned from suspension"),null===(t=o.Log)||void 0===t||t.Warning(dd.ServiceName,"App switched to foreground"))}EnterLowPowerMode(){this._onEnterLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(Qu.EnteredLowPowerMode)}ExitLowPowerMode(){this._onExitLowPowerModeEvent.Invoke(),this._onAppStateChanged.Invoke(Qu.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 dd.ServiceName}}dd.ServiceName="AppStateService",ts(Map),ts(Set),(()=>{var e;const t=String.prototype,n=Object.getOwnPropertyNames(dr.prototype);for(const r of n)t[r]=null!==(e=t[r])&&void 0!==e?e:dr.prototype[r];t.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 sr(ir.NoMatch)}if(0===this.length)throw new sr(ir.NoElements);return this[0]},t.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]},t.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},t.elementAt=function(e){if(e<0||e>=this.length)throw new or("index");return this[e]},t.elementAtOrDefault=function(e){return this[e]||null},t.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 sr(ir.NoMatch)}if(0===this.length)throw new sr(ir.NoElements);return this[this.length-1]},t.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]},t.reverse=function(){const e=this;return new dr((function*(){for(let t=e.length-1;t>=0;t--)yield e[t]}))}})(),hr(Array),hr(Int8Array),hr(Int16Array),hr(Int32Array),hr(Uint8Array),hr(Uint8ClampedArray),hr(Uint16Array),hr(Uint32Array),hr(Float32Array),hr(Float64Array);class hd{static Init(){if(o.IsInitialized)return;let e=o.Instance;try{e.RegisterService(new i),e.RegisterService(new dd),e.RegisterService(new Te),e.RegisterService(new Se),e.RegisterService(new Ie),e.RegisterService(new er),e.RegisterService(new Ae),e.RegisterService(new Ct),e.RegisterService(new Pn),e.RegisterService(new ed)}catch(e){console.error(e)}}static GetAsync(e,t){return o.Instance.GetServiceAsync(e,t)}static GetWithTimeoutAsync(e,t){return o.Instance.GetServiceWithTimeoutAsync(e,t)}static Get(e){return o.Instance.GetService(e)}static SleepForAsync(e){return new Promise((t=>setTimeout(t,e)))}}hd.WorksInContextOf="",hd.Version=1;class vd{constructor(){this.DeviceGuid=""}}class gd extends vd{constructor(){super(...arguments),this.ReedSwitchMode=ld.ShortingOnOpeningOff,this.SyncTime=720,this.LogicNegation=!1}}!function(e){e[e.TimeConditionMode=1]="TimeConditionMode",e[e.ShortingSwitchOpeningNoResp=2]="ShortingSwitchOpeningNoResp",e[e.ShortingOnOpeningOff=3]="ShortingOnOpeningOff",e[e.ShortingOffOpeningOn=4]="ShortingOffOpeningOn",e[e.ShortingOnOpeningNoResp=5]="ShortingOnOpeningNoResp",e[e.ShortingOffOpeningNoResp=6]="ShortingOffOpeningNoResp",e[e.ShortingNoRespOpeningOn=7]="ShortingNoRespOpeningOn",e[e.ShortingNoRespOpeningOff=8]="ShortingNoRespOpeningOff",e[e.ShortingNoRespOpeningSwitch=9]="ShortingNoRespOpeningSwitch",e[e.RevertTimeConditionMode=10]="RevertTimeConditionMode"}(ld||(ld={}));class fd{constructor(e){this.DeviceGuid="",this.DeviceGuid=e}}class pd{constructor(e,t){this.DeviceGuid="",this.Channel=0,this.DeviceGuid=e,this.Channel=t}}var md,yd,wd=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Sd{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName)}GetServiceName(){return Sd.ServiceName}GetAllParamsAsync(e){var t;return wd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new _d(e.Guid),35e3,!1);if(null==n)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetAllParamsAsync(e){var t,n,r;return wd(this,void 0,void 0,(function*(){const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Cd(e),35e3,!1);return null==i||null==i.Status?(null===(n=o.Log)||void 0===n||n.Error(Sd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(i.Status!==oe.OK&&(null===(r=o.Log)||void 0===r||r.Error(Sd.ServiceName,`Failed to change device parameters, response status: ${i.Status}`)),i.Status)}))}SetReedSwitchOperationModeAsync(e,t){var n,r,i,s,a;return wd(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new gd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Sd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.LogicNegation=a.LogicNegation,c.SyncTime=a.SyncTime,c.ReedSwitchMode=t;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Cd(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Sd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Sd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Sd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetSynchronizationTimeAsync(e,t){var n,r,i,s,a;return wd(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new gd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Sd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.LogicNegation=a.LogicNegation,c.SyncTime=t,c.ReedSwitchMode=a.ReedSwitchMode;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Cd(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Sd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Sd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Sd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetLogicNegationAsync(e,t){var n,r,i,s,a;return wd(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new gd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Sd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.LogicNegation=t,c.SyncTime=a.SyncTime,c.ReedSwitchMode=a.ReedSwitchMode;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Cd(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Sd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Sd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Sd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}GetCurrentConfig(e){var t;return wd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new _d(e),35e3,!1);if(null==n)return null;switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device! No data in response.")}))}}Sd.ServiceName="Rck21ConfigService";class _d extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/reedswitch",this.Method=ie.Get,this.Data=new fd(e)}}class Cd extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/reedswitch",this.Method=ie.Put,this.Data=e}}class bd extends vd{constructor(){super(...arguments),this.AlertMode=md.AlarmAndLed,this.RepeatFloodEvent=!1,this.RepeatFloodEventTime=900,this.WorkingMode=yd.FloodSensor,this.SyncTime=720}}!function(e){e[e.None=0]="None",e[e.Alarm=1]="Alarm",e[e.Led=2]="Led",e[e.AlarmAndLed=3]="AlarmAndLed"}(md||(md={})),function(e){e[e.FloodSensor=0]="FloodSensor",e[e.PulseSensor=1]="PulseSensor"}(yd||(yd={}));var Ad,Ed=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Dd{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName)}GetServiceName(){return Dd.ServiceName}GetAllParamsAsync(e){var t;return Ed(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Nd(e.Guid),35e3,!1);if(null==n)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetAllParamsAsync(e){var t,n,r;return Ed(this,void 0,void 0,(function*(){const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Td(e),35e3,!1);return null==i||null==i.Status?(null===(n=o.Log)||void 0===n||n.Error(Dd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(i.Status!==oe.OK&&(null===(r=o.Log)||void 0===r||r.Error(Dd.ServiceName,`Failed to change device parameters, response status: ${i.Status}`)),i.Status)}))}SetFloodAlertModeAsync(e,t){var n,r,i,s,a;return Ed(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new bd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Dd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.AlertMode=t,c.RepeatFloodEvent=a.RepeatFloodEvent,c.RepeatFloodEventTime=a.RepeatFloodEventTime,c.SyncTime=a.SyncTime,c.WorkingMode=a.WorkingMode;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Td(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Dd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Dd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Dd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetFloodEventRepetitionAsync(e,t){var n,r,i,s,a;return Ed(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new bd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Dd.ServiceName,"Failed to change device parameters - cannot read current configuration of device."),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.RepeatFloodEvent=t,c.AlertMode=a.AlertMode,c.RepeatFloodEventTime=a.RepeatFloodEventTime,c.SyncTime=a.SyncTime,c.WorkingMode=a.WorkingMode;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Td(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Dd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Dd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Dd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetFloodEventRepetitionTimeAsync(e,t){var n,r,i,s,a;return Ed(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new bd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Dd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.RepeatFloodEventTime=t,c.AlertMode=a.AlertMode,c.RepeatFloodEvent=a.RepeatFloodEvent,c.SyncTime=a.SyncTime,c.WorkingMode=a.WorkingMode;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Td(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Dd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Dd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Dd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetSynchronizationTimeAsync(e,t){var n,r,i,s,a;return Ed(this,void 0,void 0,(function*(){try{const a=yield this.GetCurrentConfig(e.Guid);let c=new bd;if(null===a)return null===(n=o.Log)||void 0===n||n.Error(Dd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;c.DeviceGuid=e.Guid,c.SyncTime=t,c.AlertMode=a.AlertMode,c.RepeatFloodEvent=a.RepeatFloodEvent,c.RepeatFloodEventTime=a.RepeatFloodEventTime,c.WorkingMode=a.WorkingMode;const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Td(c),35e3,!1);return null==l||null==l.Status?(null===(i=o.Log)||void 0===i||i.Error(Dd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(l.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Dd.ServiceName,`Failed to change device parameters, response status: ${l.Status}`)),l.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Dd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}GetCurrentConfig(e){var t;return Ed(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Nd(e),35e3,!1);if(null==n)return null;switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device!")}))}}Dd.ServiceName="Rcz21ConfigService";class Nd extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/floodsensor",this.Method=ie.Get,this.Data=new fd(e)}}class Td extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/floodsensor",this.Method=ie.Put,this.Data=e}}class kd extends vd{constructor(){super(...arguments),this.Channel=Ad.Unknow,this.Threshold=0,this.Hysteresis=!1,this.IsHysteresisOptionAvailable=!1,this.IsOffsetOptionAvailable=!1}}class Fd extends vd{constructor(){super(...arguments),this.Interval=0}}class Id extends vd{constructor(){super(...arguments),this.Channel=Ad.Unknow,this.Offset=0}}!function(e){e[e.Unknow=0]="Unknow",e[e.TemperatureChannel=1]="TemperatureChannel",e[e.HuminidityChannel=2]="HuminidityChannel",e[e.PressureChannel=3]="PressureChannel",e[e.BrightnessChannel=4]="BrightnessChannel"}(Ad||(Ad={}));var Rd=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Gd{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName)}GetDetectionThresholdDataAsync(e,t){var n;return Rd(this,void 0,void 0,(function*(){const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Pd(e.Guid,t.valueOf()),35e3,!1);if(null==r)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(r.Status){case oe.OK:if(null!=r.Data)return r.Data.Threshold=r.Data.Threshold/1e3,r.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${r.Status} data: ${r.Data}`)}))}SetDetectionThresholdAsync(e,t,n){var r,i,s,a,c;return Rd(this,void 0,void 0,(function*(){try{switch(t){case Ad.PressureChannel:if(n<.3||n>30||n*Math.pow(10,1)%1!=0)return oe.WrongData;break;case Ad.HuminidityChannel:if(n<1||n>99||!Number.isInteger(n))return oe.WrongData;break;case Ad.PressureChannel:case Ad.BrightnessChannel:if(n<1||n>100||!Number.isInteger(n))return oe.WrongData;break;default:return oe.WrongData}const c=yield this.GetCurrentDetectionThresholdConfigAsync(e.Guid,t.valueOf()),l=new kd;if(null===c)return null===(r=o.Log)||void 0===r||r.Error(Hd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;l.DeviceGuid=e.Guid,l.Channel=t,l.Hysteresis=c.Hysteresis,l.Threshold=1e3*n;const u=yield null===(i=this._connection)||void 0===i?void 0:i.SendAndWaitForResponseAsync(new xd(l),35e3,!1);return null==u||null==u.Status?(null===(s=o.Log)||void 0===s||s.Error(Hd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(u.Status!==oe.OK&&(null===(a=o.Log)||void 0===a||a.Error(Hd.ServiceName,`Failed to change device parameters, response status: ${u.Status}`)),u.Status)}catch(e){return null===(c=o.Log)||void 0===c||c.Error(Hd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}GetFramesIntervalAsync(e){var t;return Rd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Od(e.Guid),35e3,!1);if(null==n)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetFramesIntervalAsync(e,t){var n,r,i,s;return Rd(this,void 0,void 0,(function*(){try{if(t<1||t>6480)return oe.WrongData;const s=new Fd;s.DeviceGuid=e.Guid,s.Interval=t;const a=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Md(s),35e3,!1);return null==a||null==a.Status?(null===(r=o.Log)||void 0===r||r.Error(Hd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(a.Status!==oe.OK&&(null===(i=o.Log)||void 0===i||i.Error(Hd.ServiceName,`Failed to change device parameters, response status: ${a.Status}`)),a.Status)}catch(e){return null===(s=o.Log)||void 0===s||s.Error(Hd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}GetCurrentDetectionThresholdConfigAsync(e,t){var n;return Rd(this,void 0,void 0,(function*(){const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Pd(e,t),35e3,!1);if(null==r)return null;switch(r.Status){case oe.OK:if(null!=r.Data)return r.Data;break;case oe.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device!")}))}}class Od extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/interval",this.Method=ie.Get,this.Data=new fd(e)}}class Pd extends re{constructor(e,t){super(),this.Resource="/extalife/device/parameters/multisensor/detectionthreshold",this.Method=ie.Get,this.Data=new pd(e,t)}}class xd extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/detectionthreshold",this.Method=ie.Put,this.Data=e}}class Md extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/interval",this.Method=ie.Put,this.Data=e}}var $d=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Ld extends Gd{GetHysteresisAsync(e,t){var n;return $d(this,void 0,void 0,(function*(){const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Pd(e.Guid,t.valueOf()),35e3,!1);if(null==r)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(r.Status){case oe.OK:if(null!=r.Data)return r.Data.Hysteresis;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${r.Status} data: ${r.Data}`)}))}SetHysteresisAsync(e,t,n){var r,i,s,a,c;return $d(this,void 0,void 0,(function*(){try{if(t==Ad.Unknow)return oe.WrongData;const c=yield this.GetCurrentDetectionThresholdConfigAsync(e.Guid,t);let l=new kd;if(null===c)return null===(r=o.Log)||void 0===r||r.Error(Hd.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;l.DeviceGuid=e.Guid,l.Channel=t,l.Hysteresis=n,l.Threshold=c.Threshold;const u=yield null===(i=this._connection)||void 0===i?void 0:i.SendAndWaitForResponseAsync(new xd(l),35e3,!1);return null==u||null==u.Status?(null===(s=o.Log)||void 0===s||s.Error(Hd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(u.Status!==oe.OK&&(null===(a=o.Log)||void 0===a||a.Error(Hd.ServiceName,`Failed to change device parameters, response status: ${u.Status}`)),u.Status)}catch(e){return null===(c=o.Log)||void 0===c||c.Error(Hd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}}var Wd=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Bd extends Ld{GetChannelOffsetAsync(e,t){var n;return Wd(this,void 0,void 0,(function*(){if(t!=Ad.TemperatureChannel)return new Ge(wg.InvalidChannelNumber,"Failed to retrieve parameters - function not available on selected channel");const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Ud(e.Guid,t.valueOf()),35e3,!1);if(null==r)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(r.Status){case oe.OK:if(null!=r.Data)return r.Data.Offset=r.Data.Offset/10,r.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${r.Status} data: ${r.Data}`)}))}SetChannelOffsetAsync(e,t,n){var r,i,s,a;return Wd(this,void 0,void 0,(function*(){try{if(t!==Ad.TemperatureChannel)return oe.WrongData;if(n<-5||n>5||n*Math.pow(10,1)%1!=0)return oe.WrongData;const a=new Id;a.DeviceGuid=e.Guid,a.Channel=t,a.Offset=10*n;const c=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Kd(a),35e3,!1);return null==c||null==c.Status?(null===(i=o.Log)||void 0===i||i.Error(Hd.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(c.Status!==oe.OK&&(null===(s=o.Log)||void 0===s||s.Error(Hd.ServiceName,`Failed to change device parameters, response status: ${c.Status}`)),c.Status)}catch(e){return null===(a=o.Log)||void 0===a||a.Error(Hd.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}}class Ud extends re{constructor(e,t){super(),this.Resource="/extalife/device/parameters/multisensor/channeloffset",this.Method=ie.Get,this.Data=new pd(e,t)}}class Kd extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/multisensor/channeloffset",this.Method=ie.Put,this.Data=e}}class Hd extends Gd{constructor(){super(...arguments),this._services={Rcm21v1_5_0_30:new Ld,Rcm21v1_6_0_34:new Bd}}GetServiceName(){return Hd.ServiceName}VersionedConfigurationOptions(){return{"^1.5.0.30":this._services.Rcm21v1_5_0_30,"^1.6.0.34":this._services.Rcm21v1_6_0_34}}}Hd.ServiceName="Rcm21ConfigService";var zd,jd,qd;class Vd{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName)}GetServiceName(){return Vd.ServiceName}GetFirmwareVersionAsync(e){var t,n,r,o,i;return n=this,r=void 0,i=function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Yd(e.Guid),35e3,!1);if(null==n)return new Ge(wg.UnknownError,"Failed to retrieve firmware version - unknow error.");switch(n.Status){case oe.OK:if(null!=n.Data){const e=new Jd;return e.Major=n.Data.Major,e.Minor=n.Data.Minor,e.Revision=n.Data.Revision,e.Build=n.Data.Build,e}break;case oe.Error:return new Ge(wg.UnknownError,"Failed to retrieve firmware version - unknow error.")}return new Ge(wg.OtherError,`Failed to retrieve firmware version, response error: ${n.Status} data: ${n.Data}`)},new((o=void 0)||(o=Promise))((function(e,t){function s(e){try{c(i.next(e))}catch(e){t(e)}}function a(e){try{c(i.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(s,a)}c((i=i.apply(n,r||[])).next())}))}}Vd.ServiceName="FirmwareService";class Jd{constructor(){this.Revision=0,this.Build=0,this.Minor=0,this.Major=0}ToString(){return`${this.Major}.${this.Minor}.${this.Build}.${this.Revision}`}}class Yd extends re{constructor(e){super(),this.Resource="/extalife/device/firmware/version/complete",this.Method=ie.Get,this.Data=e}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(zd||(zd={})),function(e){e[e.NoBrightnessSensor=0]="NoBrightnessSensor",e[e.NightMode=1]="NightMode",e[e.DayMode=2]="DayMode"}(jd||(jd={})),function(e){e[e.NO=0]="NO",e[e.NC=1]="NC",e[e.Disable=2]="Disable"}(qd||(qd={}));var Xd,Qd,Zd=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class eh{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName)}GetServiceName(){return eh.ServiceName}GetPirSensorParamsAsync(e){var t;return Zd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new th(e.Guid),35e3,!1);if(null==n)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetDetectionThresholdAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;if(0!=r.PredefinedSettings)return oe.OperationNotPermitted;const i=Object.assign({},r);return i.DetectionThreshold=t,this.SetPirSensorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetWindowTimeAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;if(0!=r.PredefinedSettings)return oe.OperationNotPermitted;const i=Object.assign({},r);return i.WindowTime=t,this.SetPirSensorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetDetectionAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;if(0!=r.PredefinedSettings)return oe.OperationNotPermitted;const i=Object.assign({},r);return i.Detection=t,this.SetPirSensorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetPredefinedSettingsAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentPirParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.PredefinedSettings=t,0===t&&(i.DetectionThreshold>=1?i.DetectionThreshold--:i.DetectionThreshold++),this.SetPirSensorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}GetMovementDetectorParamsAsync(e){var t;return Zd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new rh(e.Guid),35e3,!1);if(null==n)return new Ge(wg.UnknownError,"Failed to retrieve parameters - unknow error.");switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data.SensorMode==jd.DayMode&&(n.Data.CurrentLuxValue-=65),n.Data;break;case oe.ResourceIsNotAvailable:return new Ge(wg.ResourceIsNotAvailable,"Failed to retrieve parameters - cannot communicate with the device.")}return new Ge(wg.OtherError,`Failed to retrieve parameters, response error: ${n.Status} data: ${n.Data}`)}))}SetOffTimeAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;if(t<10||t>3600)return oe.WrongData;const i=Object.assign({},r);return i.OffTime=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetLuxSettingAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.LuxSetting=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetSynchronizationTimeAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.SyncTime=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetAccTamperEventAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.AccEvent=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetAccLevelAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.AccLevel=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetSensorModeAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.SensorMode=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetExternalOutModeAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.ExternalOutMode=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetOpticalLEDSignalizationAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.OpticalLEDSignalization=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}SetMoveLEDSignalizationAsync(e,t){var n,r;return Zd(this,void 0,void 0,(function*(){try{const r=yield this.GetCurrentMovementDetectorParamsAsync(e.Guid);if(null===r)return null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - cannot read current configuration of device"),oe.ResourceIsNotAvailable;const i=Object.assign({},r);return i.MoveLEDSignalization=t,this.SetMovementDetectorParamsAsync(i)}catch(e){return null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Cannot change device parameters. ${e}`),oe.FatalError}}))}GetCurrentPirParamsAsync(e){var t;return Zd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new th(e),35e3,!1);if(null==n)return null;switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device! No data in response.")}))}GetCurrentMovementDetectorParamsAsync(e){var t;return Zd(this,void 0,void 0,(function*(){const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new rh(e),35e3,!1);if(null==n)return null;switch(n.Status){case oe.OK:if(null!=n.Data)return n.Data;break;case oe.ResourceIsNotAvailable:return null}throw new Error("Failed to read current configuration of device! No data in response.")}))}SetPirSensorParamsAsync(e){var t,n,r;return Zd(this,void 0,void 0,(function*(){const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new nh(e),35e3,!1);return null==i||null==i.Status?(null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(i.Status!==oe.OK&&(null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Failed to change device parameters, response status: ${i.Status}`)),i.Status)}))}SetMovementDetectorParamsAsync(e){var t,n,r;return Zd(this,void 0,void 0,(function*(){const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new oh(e),35e3,!1);return null==i||null==i.Status?(null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(i.Status!==oe.OK&&(null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Failed to change device parameters, response status: ${i.Status}`)),i.Status)}))}ClearTamperAlarmAsync(e){var t,n,r;return Zd(this,void 0,void 0,(function*(){const i=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new ih(e.Guid),35e3,!1);return null==i||null==i.Status?(null===(n=o.Log)||void 0===n||n.Error(eh.ServiceName,"Failed to clear tamper alarm - unknow error."),oe.FatalError):(i.Status!==oe.OK&&(null===(r=o.Log)||void 0===r||r.Error(eh.ServiceName,`Failed to clear tamper alarm, response status: ${i.Status}`)),i.Status)}))}}eh.ServiceName="Rcr21ConfigService";class th extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/pir",this.Method=ie.Get,this.Data=new fd(e)}}class nh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/pir",this.Method=ie.Put,this.Data=e}}class rh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/movementdetector",this.Method=ie.Get,this.Data=new fd(e)}}class oh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/movementsensor/movementdetector",this.Method=ie.Put,this.Data=e}}class ih extends re{constructor(e){super(),this.Resource="/extalife/device/movementsensor/tamper/clear",this.Method=ie.Post,this.Data=new fd(e)}}!function(e){e[e.Disabled=0]="Disabled",e[e.MovementTimeCalibration=1]="MovementTimeCalibration",e[e.LamellaTiltCalibration=2]="LamellaTiltCalibration"}(Xd||(Xd={})),function(e){e[e.Automatic=0]="Automatic",e[e.ForceType90=1]="ForceType90",e[e.ForceType180=2]="ForceType180"}(Qd||(Qd={}));var sh,ah,ch,lh,uh=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class dh{constructor(){this._connection=null,this._lamelaCalibrationContext=new _h,this._connection=hd.Get(Ie.ServiceName),this._controllerConfigurationService=hd.Get(Ae.ServiceName),this._logger=hd.Get(r.ServiceName)}GetServiceName(){return dh.ServiceName}RunAutomaticLamelaPositionCalibrationAsync(e,t){var n,r,o,i;return uh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(sh.InvalidChannelNumber,`Cannot calibrate facade blind - invalid channel number: ${t}`);const i=yield this.GetCalibrationStatusAsync(e,t);if(null!=i.Type)return new Ge(sh.OtherError,"Cannot calibrate facade blind - unable to get current calibration status.");if(i.CalibrationProgress!=Xd.Disabled)return new Ge(sh.CalibrationsIsCurrentlyRunning,"Cannot calibrate facade blind - calibration of device is currently running.");const s=new Tn;if(s.Action=wn.Stop,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(s))!==Ue.Executed)return new Ge(sh.DeviceNotResponding,"Cannot calibrate facade blind - device is not responding.");yield null===(n=this._controllerConfigurationService)||void 0===n?void 0:n.EnterConfigurationModeAsync();const a=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new gh(new pd(e.Guid,t)),8e3,!1);if(null==a||null==a.Status)return new Ge(sh.OtherError,"Cannot calibrate facade blind - calibration request failed for an unknown reason.");if(a.Status!==oe.OK)return new Ge(sh.OtherError,`Cannot calibrate facade blind - calibration request failed - request status code: ${a.Status}`);const c=new Promise(((n,r)=>{let o=0;const i=setInterval((()=>uh(this,void 0,void 0,(function*(){var r=yield this.GetCalibrationStatusAsync(e,t);if(null!=r.Type)o++,o>6&&(clearInterval(i),n(sh.DeviceNotResponding));else switch(r.CalibrationProgress){case Xd.MovementTimeCalibration:this._logger.Debug("Facade blind calibration in progress..."),o=0;break;case Xd.LamellaTiltCalibration:n(sh.CalibrationsIsCurrentlyRunning);break;default:this._logger.Debug("Facade blind calibration finished!"),clearInterval(i),n(r)}}))),2e3)})),l=yield c;if(null===(o=this._controllerConfigurationService)||void 0===o||o.ExitConfigurationModeAsync(),null==l.CalibrationProgress)switch(l){case sh.DeviceNotResponding:return new Ge(sh.DeviceNotResponding,"Facade calibration canceled - device not responding!");case sh.CalibrationsIsCurrentlyRunning:return new Ge(sh.CalibrationsIsCurrentlyRunning,"Cannot calibrate facade blind - calibration of device is currently running.")}return l}catch(e){return null===(i=this._controllerConfigurationService)||void 0===i||i.ExitConfigurationModeAsync(),this._logger.Error(dh.ServiceName,`Cannot calibrate facade blind. ${e}`),new Ge(sh.OtherError,"Cannot calibrate facade blind - unknown error.")}}))}StopCalibrationAsync(e,t){var n,r;return uh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return oe.WrongData;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new fh(new pd(e.Guid,t)),8e3,!1);return null==o||null==o.Status?(this._logger.Error("Failed to stop calibration - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(`Failed to stop calibration - response status: ${o.Status}`),null===(r=this._controllerConfigurationService)||void 0===r||r.ExitConfigurationModeAsync(),o.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot stop facade blind calibration. ${e}`),oe.FatalError}}))}LamelaTiltCalibration(e,t){try{return e.Channels.any((e=>e.Number===t))?{InitCalibrationAsync:()=>uh(this,void 0,void 0,(function*(){var n,r;const o=e.Channels.first((e=>e.Number==t)),i=yield this.GetCalibrationStatusAsync(e,t);if(this._lamelaCalibrationContext=new _h,null!=i.Type)return new Ge(sh.OtherError,"Cannot calibrate facade blind - unable to get current calibration status.");if(i.CalibrationProgress!=Xd.Disabled)return new Ge(sh.CalibrationsIsCurrentlyRunning,"Cannot calibrate facade blind - calibration of device is currently running.");const s=new Rn;if(s.FacadeAction=_n.Stop,(yield o.ExecuteTaskAsync(s))!=Ue.Executed)return new Ge(sh.OtherError,"Cannot calibrate facade blind - unable to stop blind.");const a=new Rn;if(a.FacadeAction=_n.Percentage,a.Position=80,(yield o.ExecuteTaskAsync(a))!=Ue.Executed)return new Ge(sh.OtherError,"Cannot calibrate facade blind - unable to set correct position.");const c=new Promise(((t,n)=>{const r=Date.now()+12e4,i=setInterval((()=>{this._logger.Debug(dh.ServiceName,"Lamela tilt calibration initialization - seting blind to calibration position..."),Date.now()>r?(e.OnDeviceStateChangedEvent().Unsubscribe(s),n(new Ge(sh.DeviceNotResponding,"Cannot calibrate facade blind - unable to get correct blind position for calibration."))):o.ExecuteTaskAsync(new In)}),2e3),s=n=>{n.TypeAsEnum==Me.FacadePosition&&80==n.Data.Position&&(this._logger.Debug(dh.ServiceName,"Lamela tilt calibration initialization - correct position was set, position: 80%"),e.OnDeviceStateChangedEvent().Unsubscribe(s),clearInterval(i),t(n.Data))};e.OnDeviceStateChangedEvent().Subscribe(s)}));try{yield c}catch(e){return e}yield null===(n=this._controllerConfigurationService)||void 0===n?void 0:n.EnterConfigurationModeAsync();const l=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new ph(new pd(e.Guid,t)),8e3,!1);return null==l||null==l.Status?new Ge(sh.OtherError,"Cannot calibrate facade blind - unable to start calibration."):l.Status!==oe.OK?new Ge(sh.OtherError,`Cannot calibrate facade blind - unable to start calibration - response status: ${l.Status}`):void(this._lamelaCalibrationContext.CalibrationInitialized=!0)})),LamelaManualCalibration:{MoveOneStepDownAsync:()=>uh(this,void 0,void 0,(function*(){var n;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new yh(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?oe.FatalError:r.Status})),MoveOneStepUpAsync:()=>uh(this,void 0,void 0,(function*(){var n;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new mh(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?oe.FatalError:r.Status}))},ConfirmFirstPositionAsync:()=>uh(this,void 0,void 0,(function*(){var n;try{if(!this._lamelaCalibrationContext.CalibrationInitialized)return oe.OperationNotPermitted;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new wh(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?oe.FatalError:(r.Status==oe.OK&&(this._lamelaCalibrationContext.FirstPositionConfirmed=!0),r.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot confirm first tilt lamela position. ${e}`),oe.FatalError}})),ConfirmSecondPositionAsync:()=>uh(this,void 0,void 0,(function*(){var n;try{if(!this._lamelaCalibrationContext.CalibrationInitialized||!this._lamelaCalibrationContext.FirstPositionConfirmed)return oe.OperationNotPermitted;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Sh(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?oe.FatalError:(r.Status==oe.OK&&(this._lamelaCalibrationContext.FirstPositionConfirmed=!0),r.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot confirm second tilt lamela position. ${e}`),oe.FatalError}})),EndCalibrationAsync:()=>uh(this,void 0,void 0,(function*(){try{if(this._lamelaCalibrationContext=new _h,(yield this.StopCalibrationAsync(e,t))!=oe.OK)return oe.Error;const n=new Rn;return n.FacadeAction=_n.Open,e.ExecuteDeviceTaskAsync(n),oe.OK}catch(e){return this._logger.Error(dh.ServiceName,`Cannot finish lamela tilt calibration. ${e}`),oe.FatalError}}))}:new Ge(sh.InvalidChannelNumber,`Cannot get lamela tilt calibration functions - invalid channel number, channel: ${t}`)}catch(e){return new Ge(sh.OtherError,"Cannot get lamela tilt calibration functions - unknown error.")}}GetCalibrationStatusAsync(e,t){var n;return uh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(sh.InvalidChannelNumber,`Cannot get facade calibration status - invalid channel number: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new vh(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(sh.OtherError,"Cannot get facade calibration status - unknown error."):r.Status!==oe.OK?new Ge(sh.OtherError,`Cannot get facade calibration status - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(sh.NoData,"Cannot get facade calibration status - no data in response."):r.Data}catch(e){return this._logger.Error(dh.ServiceName,`Cannot get facade calibration status. ${e}`),new Ge(sh.OtherError,"Cannot get facade calibration status - unknown error.")}}))}ChangeMovementDirectionAsync(e,t){var n;return uh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return oe.WrongData;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new hh(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?(this._logger.Error("Failed to change movement direction - unknow error."),oe.FatalError):(r.Status!==oe.OK&&this._logger.Error(`Failed to change movement direction - response status: ${r.Status}`),r.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot change movement direction. ${e}`),oe.FatalError}}))}IsWindSensorsPairedAsync(e){var t;return uh(this,void 0,void 0,(function*(){try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ch(e.Guid),8e3,!1);return null==n||null==n.Status?new Ge(sh.OtherError,"Cannot check if any wind sensor is paired - unknown error."):n.Status===oe.OK&&null!=n.Data&&n.Data.IsPaired}catch(e){return this._logger.Error(dh.ServiceName,`Cannot check if any wind sensor is paired. ${e}`),new Ge(sh.OtherError,"Cannot check if any wind sensor is paired - unknown error.")}}))}GetWindSensorActiveAsync(e){var t;return uh(this,void 0,void 0,(function*(){try{if(!(yield this.IsWindSensorsPairedAsync(e)))return new Ge(sh.WindSensorNotPaired,"Cannot get wind sensor lock time - wind sensor not paired.");const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new bh(e.Guid),8e3,!1);return null==n||null==n.Status?new Ge(sh.OtherError,"Cannot check if 'wind detection lock' functionality is active - unknown error."):n.Status!==oe.OK?new Ge(sh.OtherError,`Cannot check if 'wind detection lock' functionality is active - response status: ${n.Status}.`):null==n.Data?new Ge(sh.NoData,"Cannot check if 'wind detection lock' - no data in response."):n.Data}catch(e){return this._logger.Error(dh.ServiceName,`Cannot check if 'wind detection lock' functionality is active. ${e}`),new Ge(sh.OtherError,"Cannot check if 'wind detection lock' functionality is active - unknown error.")}}))}SetWindSensorActiveAsync(e,t){var n;return uh(this,void 0,void 0,(function*(){if(!(yield this.IsWindSensorsPairedAsync(e)))return oe.ResourceIsNotAvailable;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Ah(e.Guid,t),8e3,!1);return null==r||null==r.Status?(this._logger.Error(dh.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(r.Status!==oe.OK&&this._logger.Error(dh.ServiceName,`Failed to change device parameters, response status: ${r.Status}`),r.Status)}))}GetWindSensorLockTimeAsync(e){var t;return uh(this,void 0,void 0,(function*(){try{if(!(yield this.IsWindSensorsPairedAsync(e)))return new Ge(sh.WindSensorNotPaired,"Cannot get wind sensor lock time - wind sensor not paired.");const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Eh(e.Guid),8e3,!1);return null==n||null==n.Status?new Ge(sh.OtherError,"Cannot get wind sensor lock time - unknown error."):n.Status!==oe.OK?new Ge(sh.OtherError,`Cannot get wind sensor lock time - response status: ${n.Status}.`):null==n.Data?new Ge(sh.NoData,"Cannot get wind sensor lock time - no data in response."):n.Data}catch(e){return this._logger.Error(dh.ServiceName,`Cannot get wind sensor lock time. ${e}`),new Ge(sh.OtherError,"Cannot get wind sensor lock time - unknown error.")}}))}SetWindSensorLockTimeAsync(e,t){var n;return uh(this,void 0,void 0,(function*(){try{if(!(yield this.IsWindSensorsPairedAsync(e)))return oe.ResourceIsNotAvailable;const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Nh(new Dh(e.Guid,t)),8e3,!1);return null==r||null==r.Status?(this._logger.Error(dh.ServiceName,"Failed to set wind sensor lock time - unknow error."),oe.FatalError):(r.Status!==oe.OK&&this._logger.Error(dh.ServiceName,`Failed to set wind sensor lock time, response status: ${r.Status}`),r.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot set wind sensor lock time. ${e}`),oe.FatalError}}))}IsBlindLockedByWindSensorAsync(e){var t;return uh(this,void 0,void 0,(function*(){try{if(!(yield this.IsWindSensorsPairedAsync(e)))return new Ge(sh.WindSensorNotPaired,"Cannot check if blind is blocked - wind sensor not paired.");const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Th(e.Guid),8e3,!1);return null==n||null==n.Status?new Ge(sh.OtherError,"Cannot check if blind is blocked - unknown error."):n.Status!==oe.OK?new Ge(sh.OtherError,`Cannot check if blind is blocked - response status: ${n.Status}.`):null==n.Data?new Ge(sh.NoData,"Cannot check if blind is blocked - no data in response."):n.Data}catch(e){return this._logger.Error(dh.ServiceName,`Cannot check if blind is blocked. ${e}`),new Ge(sh.OtherError,"Cannot check if blind is blocked - unknown error.")}}))}ClearBlindLockByWindSensorAsync(e){var t;return uh(this,void 0,void 0,(function*(){try{(yield this.IsWindSensorsPairedAsync(e))||oe.ResourceIsNotAvailable;const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new kh(e.Guid),8e3,!1);return null==n||null==n.Status?(this._logger.Error(dh.ServiceName,"Failed to change device parameters - unknow error."),oe.FatalError):(n.Status!==oe.OK&&this._logger.Error(dh.ServiceName,`Failed to change device parameters, response status: ${n.Status}`),n.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot clear wind blockade state. ${e}`),oe.FatalError}}))}GetFacadeTypeDetectionAsync(e){var t;return uh(this,void 0,void 0,(function*(){try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Ih(new fd(e.Guid)),8e3,!1);return null==n||null==n.Status?new Ge(sh.OtherError,"Cannot get facade detection settings - unknown error."):n.Status!==oe.OK?new Ge(sh.OtherError,`Cannot get facade detection settings - controller responded with error code: ${n.Status}.`):null==n.Data?new Ge(sh.NoData,"Cannot get facade detection settings - no data in response."):n.Data.FacadeDetection}catch(e){return this._logger.Error(dh.ServiceName,`Cannot get facade detection settings. ${e}`),new Ge(sh.OtherError,"Cannot get facade detection settings - unknown error.")}}))}SetFacadeTypeDetectionAsync(e,t){var n;return uh(this,void 0,void 0,(function*(){try{const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Rh(new Fh(e.Guid,t)),8e3,!1);return null==r||null==r.Status?(this._logger.Error(dh.ServiceName,"Failed to facade detection settings - unknow error."),oe.FatalError):(r.Status!==oe.OK&&this._logger.Error(dh.ServiceName,`Failed to facade detection settings, response status: ${r.Status}`),r.Status)}catch(e){return this._logger.Error(dh.ServiceName,`Cannot facade detection settings. ${e}`),oe.FatalError}}))}}dh.ServiceName="ZfBidiConfigService",function(e){e.InvalidChannelNumber="InvalidChannelNumber",e.OtherError="OtherError",e.CalibrationsIsCurrentlyRunning="CalibrationsIsCurrentlyRunning",e.DeviceNotResponding="DeviceNotResponding",e.WindSensorNotPaired="WindSensorNotPaired",e.NoData="NoData"}(sh||(sh={}));class hh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/direction/reverse",this.Method=ie.Post,this.Data=e}}class vh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/status",this.Method=ie.Get,this.Data=e}}class gh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/start",this.Method=ie.Post,this.Data=e}}class fh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/stop",this.Method=ie.Post,this.Data=e}}class ph extends re{constructor(e){super(),this.Resource="/extalife/device/facade/lamella/tilt/calibration/start",this.Method=ie.Post,this.Data=e}}class mh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/step/up",this.Method=ie.Post,this.Data=e}}class yh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/step/down",this.Method=ie.Post,this.Data=e}}class wh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/lamella/position/first/confirm",this.Method=ie.Post,this.Data=e}}class Sh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/calibration/lamella/position/second/confirm",this.Method=ie.Post,this.Data=e}}class _h{constructor(){this.CalibrationInitialized=!1,this.FirstPositionConfirmed=!1,this.SeconfPositionConfirmed=!1}}class Ch extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/facade/sensor/paired",this.Method=ie.Get,this.Data=e}}class bh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/wind/sensor/status",this.Method=ie.Get,this.Data=e}}class Ah extends re{constructor(e,t){super(),this.Resource=t?"/extalife/device/parameters/wind/activate/":"/extalife/device/parameters/wind/deactivate/",this.Method=ie.Post,this.Data=e}}class Eh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/wind/blockade/time",this.Method=ie.Get,this.Data=e}}class Dh{constructor(e,t){this.DeviceGuid="",this.Minutes=0,this.DeviceGuid=e,this.Minutes=t}}class Nh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/wind/blockade/time",this.Method=ie.Put,this.Data=e}}class Th extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/wind/blockade/",this.Method=ie.Get,this.Data=e}}class kh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/wind/blockade/",this.Method=ie.Delete,this.Data=e}}class Fh{constructor(e,t){this.DeviceGuid="",this.FacadeDetection=Qd.Automatic,this.DeviceGuid=e,this.FacadeDetection=t}}class Ih extends re{constructor(e){super(),this.Resource="/extalife/device/facade/type/detection",this.Method=ie.Get,this.Data=e}}class Rh extends re{constructor(e){super(),this.Resource="/extalife/device/facade/type/detection",this.Method=ie.Put,this.Data=e}}class Gh{constructor(){this.Correction=0,this.AvaliableCorrections=[],this.CorrectionType="LOWER"}}class Oh{constructor(){this.Channel=0,this.Position1=0,this.Position2=0}}class Ph{constructor(){this.Channel=0,this.InputModeBlind=ah.Local,this.ButtonTypeBlind=ch.SingleButton}}!function(e){e[e.Local=0]="Local",e[e.Central=1]="Central"}(ah||(ah={})),function(e){e[e.SingleButton=0]="SingleButton",e[e.DoubleButton=1]="DoubleButton"}(ch||(ch={}));class xh{constructor(){this.Channel=0,this.State=lh.DoNothing,this.BlindPosition=0}}!function(e){e[e.OpenBlind=0]="OpenBlind",e[e.CloseBlind=1]="CloseBlind",e[e.DoNothing=2]="DoNothing",e[e.OpenPercentage=3]="OpenPercentage"}(lh||(lh={}));var Mh,$h,Lh,Wh=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Bh{constructor(){this._connection=null,this._controllerConfigurationService=null,this._manualCalibrationContext=new zh,this._connection=hd.Get(Ie.ServiceName),this._controllerConfigurationService=hd.Get(Ae.ServiceName),this._logger=hd.Get(r.ServiceName)}static Init(){o.Instance.RegisterService(new Bh),hd.Get(r.ServiceName).Debug("Initialized BlindConfigService")}GetServiceName(){return Bh.ServiceName}ManualCalibration(e,t){try{return e.Channels.any((e=>e.Number===t))?{StepAOpenBlindAsync:()=>Wh(this,void 0,void 0,(function*(){const n=new kn;return n.Data.Channel=t,n.Data.CloseTime=65535,n.Data.OpenTime=65535,this._logger.Debug("Manual calibration start, STEP A - clearing context data."),this._manualCalibrationContext=new zh,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))!==Ue.Executed?oe.Error:((new Tn).Action=wn.Open,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))!==Ue.Executed?oe.Error:(this._manualCalibrationContext.StepAFinished=!0,oe.OK))})),StepBCalibrateOpeningTime:()=>this._manualCalibrationContext.StepAFinished?{StepAInitBlindMoveAsync:()=>Wh(this,void 0,void 0,(function*(){const n=new Tn;return n.Action=wn.Close,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))===Ue.Executed?(this._manualCalibrationContext.OpeningStartTime=Date.now(),this._manualCalibrationContext.StepBAFinished=!0,oe.OK):oe.Error})),StepBConfirmBlindPositionAsync:()=>Wh(this,void 0,void 0,(function*(){if(!this._manualCalibrationContext.StepBAFinished)return oe.NoPermissionToPerformThisOperation;const n=new Tn;return n.Action=wn.Stop,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))===Ue.Executed?(this._manualCalibrationContext.OpeningEndTime=Date.now(),this._manualCalibrationContext.StepBFinished=!0,oe.OK):oe.Error}))}:oe.NoPermissionToPerformThisOperation,StepCCalibrateClosingTime:()=>this._manualCalibrationContext.StepAFinished&&this._manualCalibrationContext.StepBFinished?{StepAInitBlindMoveAsync:()=>Wh(this,void 0,void 0,(function*(){const n=new Tn;return n.Action=wn.Open,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))===Ue.Executed?(this._manualCalibrationContext.ClosingStartTime=Date.now(),this._manualCalibrationContext.StepCAFinished=!0,oe.OK):oe.Error})),StepBConfirmBlindPositionAsync:()=>Wh(this,void 0,void 0,(function*(){if(!this._manualCalibrationContext.StepCAFinished)return oe.NoPermissionToPerformThisOperation;const n=new Tn;return n.Action=wn.Stop,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))===Ue.Executed?(this._manualCalibrationContext.ClosingEndTime=Date.now(),this._manualCalibrationContext.StepCFinished=!0,oe.OK):oe.Error}))}:oe.NoPermissionToPerformThisOperation,StepDSaveCalibrationAsync:()=>Wh(this,void 0,void 0,(function*(){if(!this._manualCalibrationContext.StepAFinished||!this._manualCalibrationContext.StepBFinished||!this._manualCalibrationContext.StepCFinished)return oe.NoPermissionToPerformThisOperation;const n=new kn;return n.Data.Channel=t,n.Data.OpenTime=Math.ceil((this._manualCalibrationContext.OpeningEndTime-this._manualCalibrationContext.OpeningStartTime)/10),n.Data.CloseTime=Math.ceil((this._manualCalibrationContext.ClosingEndTime-this._manualCalibrationContext.ClosingStartTime)/10),this._logger.Debug(`Mamual calibration finished - OpenTime: ${n.Data.OpenTime}, CloseTime: ${n.Data.CloseTime}.`),(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(n))===Ue.Executed?(this._manualCalibrationContext=new zh,this._logger.Debug("Manual calibration - clearing context data."),oe.OK):(this._manualCalibrationContext=new zh,this._logger.Debug("Manual calibration - clearing context data."),oe.Error)}))}:new Ge(Mh.InvalidChannelNumber,`Cannot get manual calibration functions - invalid channel number, channel: ${t}`)}catch(e){return new Ge(Mh.OtherError,"Failed to get manual calibration functions - unknown error.")}}RunAutomaticCalibrationAsync(e,t){var n,r,o,i,s,a;return Wh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Mh.InvalidChannelNumber,`Cannot calibrate blind - invalid channel number: ${t}`);const a=yield this.IsCalibrationRunningAsync();if(a.Type==Mh.CannotCheckIfCalibrationsIsRunning)return a;if(a)return new Ge(Mh.CalibrationsIsCurrentlyRunning,"Cannot calibrate blind - calibration is currently running - make sure no blind is currently calibrated and try again.");yield null===(n=this._controllerConfigurationService)||void 0===n?void 0:n.EnterConfigurationModeAsync();const c=new Tn;if(c.Action=wn.Stop,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(c))!==Ue.Executed)return null===(r=this._controllerConfigurationService)||void 0===r||r.ExitConfigurationModeAsync(),new Ge(Mh.DeviceNotResponding,"Cannot calibrate blind - device is not responding.");const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new Uh(e.Guid),8e3,!1);if(null==l||null==l.Status)return new Ge(Mh.OtherError,"Cannot calibrate blind - calibration request failed for an unknown reason.");if(l.Status!==oe.OK)return new Ge(Mh.OtherError,`Cannot calibrate blind - calibration request failed - request status code: ${l.Status}`);const u=new Promise(((t,n)=>{let r,o=!1;const i=s=>{if(s.TypeAsEnum==Me.BlindCalibration)switch(s.Data.CalibrationStatus){case rt.AutoLernCancelled:e.OnDeviceStateChangedEvent().Unsubscribe(i),o=!1,clearTimeout(r),n(new Ge(Mh.CalibrationCancelled,"Calibration canceled - recived AutoLernCancelled message."));break;case rt.AutoLernSuccessfull:this._logger.Debug("Calibration finished - recived AutoLernSuccessfull message."),e.OnDeviceStateChangedEvent().Unsubscribe(i),o=!1,clearTimeout(r),t(s.Data);break;case rt.AutoLernInProgress:this._logger.Debug("Calibration start - recived AutoLernInProgress message."),o=!0,r=setTimeout((()=>{e.OnDeviceStateChangedEvent().Unsubscribe(i),n(new Ge(Mh.Timeout,"Calibration failed - calibration status message timeout has been reached."))}),8e3);break;case rt.AutoLernIdle:o=!1,e.OnDeviceStateChangedEvent().Unsubscribe(i),clearTimeout(r),n(new Ge(Mh.IncorrectResponse,"Calibration failed - recived AutoLernIdle message received before completion of calibration."))}else o&&s.TypeAsEnum==Me.BlindPosition&&(this._logger.Debug("Calibration in progress - recived BlindPosition message."),clearTimeout(r),r=setTimeout((()=>{e.OnDeviceStateChangedEvent().Unsubscribe(i),n(new Ge(Mh.Timeout,"Calibration failed - calibration status message timeout has been reached."))}),8e3))};e.OnDeviceStateChangedEvent().Subscribe(i)}));try{const e=yield u;return null===(i=this._controllerConfigurationService)||void 0===i||i.ExitConfigurationModeAsync(),e}catch(e){return null===(s=this._controllerConfigurationService)||void 0===s||s.ExitConfigurationModeAsync(),e}}catch(e){return null===(a=this._controllerConfigurationService)||void 0===a||a.ExitConfigurationModeAsync(),new Ge(Mh.OtherError,"Cannot calibrate blind - unknown error.")}}))}StopAutomaticCalibrationAsync(e){var t;return Wh(this,void 0,void 0,(function*(){try{const n=yield this.IsCalibrationRunningAsync();if(n.Type==Mh.CannotCheckIfCalibrationsIsRunning)return oe.Error;if(!n)return oe.OperationNotPermitted;const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new Kh(e.Guid),8e3,!1);return null==r||null==r.Status?(this._logger.Error("Failed to stop calibration - unknow error."),oe.FatalError):(r.Status!==oe.OK&&this._logger.Error(`Failed to stop calibration - response status: ${r.Status}`),r.Status)}catch(e){return oe.FatalError}}))}GetCorrectionStepAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new qh(e.Guid,t),8e3,!1);if(null==r)return new Ge(Mh.OtherError,"Failed to retrieve parameters - unknow error.");if(r.Status!==oe.OK)return new Ge(Mh.OtherError,`Failed to retrieve parameters - controller responded with error code: ${r.Status}.`);if(null!=r.Data){const e=r.Data,n=new Gh;n.Correction=e.Correction,n.CorrectionType=t;for(var o=e.Min;o<=e.Max;o+=e.Step)n.AvaliableCorrections.push(o);return n}return new Ge(Mh.OtherError,"Failed to retrieve parameters - unknown error.")}))}SetCorrectionStepAsync(e,t,n){var r,o;return Wh(this,void 0,void 0,(function*(){const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new qh(e.Guid,n),8e3,!1);if(null==i)return oe.ResourceIsNotAvailable;if(i.Status!==oe.OK)return null!=i.Status?i.Status:oe.UnknownError;if(null!=i.Data){const r=i.Data;let a=!1;for(var s=r.Min;s<=r.Max;s+=r.Step)if(t==s){a=!0;break}if(!a)return oe.WrongData;const c=new jh;c.Correction=t,c.DeviceGuid=e.Guid;const l=yield null===(o=this._connection)||void 0===o?void 0:o.SendAndWaitForResponseAsync(new Vh(c,n),8e3,!1);return null==l?oe.FatalError:null!=l.Status?l.Status:oe.UnknownError}return i.Status}))}GetComfortPositionsAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Mh.InvalidChannelNumber,`Cannot get comfort position - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Yh(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Mh.OtherError,"Cannot get comfort position - unknown error.");if(r.Status!==oe.OK)return new Ge(Mh.OtherError,`Cannot get comfort position - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Mh.NoData,"Cannot get comfort position - no data in response.");const o=new Oh;return o.Channel=r.Data.Channel,o.Position1=r.Data.Position1,o.Position2=r.Data.Position2,o}catch(e){return new Ge(Mh.OtherError,"Failed to retrieve comfort position - unknown error.")}}))}SetComfortPositionAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{if(null!=(yield this.GetComfortPositionsAsync(e,t.Channel)).Type)return oe.ResourceIsNotAvailable;const r=new Jh;r.Channel=t.Channel,r.DeviceGuid=e.Guid,r.Position1=t.Position1,r.Position2=t.Position2;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Xh(r),8e3,!1);return null==o||null==o.Status?(this._logger.Error("Failed to set comfort position - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(`Failed to set comfort position, response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}SwapRelaysAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{const r=new Tn;if(r.Action=wn.Stop,(yield e.Channels.first((e=>e.Number==t)).ExecuteTaskAsync(r))!==Ue.Executed)return this._logger.Error("Failed to swap relays - cannot execute 'blind stop' task."),oe.Error;yield new Promise((e=>setTimeout(e,500)));const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Qh(e.Guid),8e3,!1);return null==o||null==o.Status?(this._logger.Error("Failed to swap relays - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(`Failed to swap relays - response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}GetBlindInputOutputParamAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Mh.InvalidChannelNumber,`Cannot get input/output parameters - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Zh(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Mh.OtherError,"Cannot get input/output parameters - unknown error.");if(r.Status!==oe.OK)return new Ge(Mh.OtherError,`Cannot get input/output parameters - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Mh.NoData,"Cannot get input/output parameters - no data in response.");const o=r.Data.firstOrDefault();if(null==o)return new Ge(Mh.InputOutputNotFound,"Cannot get input/output parameters - input/output not exists.");const i=new Ph;return i.Channel=o.Channel,i.ButtonTypeBlind=o.ButtonTypeBlind,i.InputModeBlind=o.InputModeBlind,i}catch(e){return new Ge(Mh.OtherError,"Failed to retrieve input/output parameters - unknown error.")}}))}SetBlindInputOutputParamAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{const r=new ev;r.DeviceGuid=e.Guid,r.ButtonTypeBlind=t.ButtonTypeBlind,r.InputModeBlind=t.InputModeBlind,r.Channel=t.Channel;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new tv(r),8e3,!1);return null==o||null==o.Status?(this._logger.Error("Failed to set input/output parameters - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(`Failed to set input/output parameters, response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}GetTurnOnBehaviourAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Mh.InvalidChannelNumber,`Cannot get turn on behaviour - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new nv(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Mh.OtherError,"Cannot get turn on behaviour - unknown error.");if(r.Status!==oe.OK)return new Ge(Mh.OtherError,`Cannot get turn on behaviour - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Mh.NoData,"Cannot get turn on behaviour - no data in response.");const o=new xh;return o.BlindPosition=r.Data.BlindPosition,o.Channel=r.Data.Channel,o.State=r.Data.State,o}catch(e){return new Ge(Mh.OtherError,"Failed to retrieve turn on behaviour - unknown error.")}}))}SetTurnOnBehaviourAsync(e,t){var n;return Wh(this,void 0,void 0,(function*(){try{const r=new ov;r.DeviceGuid=e.Guid,r.Channel=t.Channel,r.BlindPosition=t.BlindPosition,r.State=t.State;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new rv(r),8e3,!1);return null==o||null==o.Status?(this._logger.Error("Failed to set turn on behaviour - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(`Failed to set turn on behaviour, response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}IsCalibrationRunningAsync(){var e;return Wh(this,void 0,void 0,(function*(){const t=yield null===(e=this._connection)||void 0===e?void 0:e.SendAndWaitForResponseAsync(new Hh,8e3,!1);return null==t||null==t.Status||t.Status!==oe.OK||null==t.Data?new Ge(Mh.CannotCheckIfCalibrationsIsRunning,"Calibration failed - it is not possible to check whether any cabling is running."):t.Data}))}}Bh.ServiceName="BlindConfigService",function(e){e.OtherError="OtherError",e.InvalidChannelNumber="InvalidChannelNumber",e.DeviceNotResponding="DeviceNotResponding",e.CalibrationCancelled="CalibrationCancelled",e.Timeout="Timeout",e.IncorrectResponse="IncorrectResponse",e.CannotCheckIfCalibrationsIsRunning="CannotCheckIfCalibrationsIsRunning",e.CalibrationsIsCurrentlyRunning="CalibrationsIsCurrentlyRunning",e.InputOutputNotFound="InputOutputNotFound",e.NoData="NoData"}(Mh||(Mh={}));class Uh extends re{constructor(e){super(),this.Resource="/extafree2/blind/calibration/auto",this.Method=ie.Get,this.Data=e}}class Kh extends re{constructor(e){super(),this.Resource="/extafree2/blind/calibration/stop",this.Method=ie.Get,this.Data=e}}class Hh extends re{constructor(){super(),this.Resource="/extafree2/blind/calibration/isrunning",this.Method=ie.Get,this.Data=null}}class zh{constructor(){this.StepAFinished=!1,this.StepBFinished=!1,this.StepCFinished=!1,this.StepBAFinished=!1,this.StepCAFinished=!1,this.OpeningStartTime=0,this.OpeningEndTime=0,this.ClosingStartTime=0,this.ClosingEndTime=0}}class jh{constructor(){this.DeviceGuid="",this.Correction=0}}class qh extends re{constructor(e,t){super(),this.Resource="LOWER"==t?"/extalife/device/blind/correction/lower":"/extalife/device/blind/correction/upper",this.Method=ie.Get,this.Data=e}}class Vh extends re{constructor(e,t){super(),this.Resource="LOWER"==t?"/extalife/device/blind/correction/lower":"/extalife/device/blind/correction/upper",this.Method=ie.Put,this.Data=e}}class Jh extends Oh{constructor(){super(...arguments),this.DeviceGuid=""}}class Yh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/comfort/position",this.Method=ie.Get,this.Data=e}}class Xh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/comfort/position",this.Method=ie.Put,this.Data=e}}class Qh extends re{constructor(e){super(),this.Resource="/extalife/device/blind/relays/swap",this.Method=ie.Get,this.Data=e}}class Zh extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/input/output",this.Method=ie.Get,this.Data=e}}class ev extends Ph{constructor(){super(...arguments),this.DeviceGuid=""}}class tv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/input/output",this.Method=ie.Put,this.Data=e}}class nv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/state/turnon",this.Method=ie.Get,this.Data=e}}class rv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/state/turnon",this.Method=ie.Put,this.Data=e}}class ov extends xh{constructor(){super(...arguments),this.DeviceGuid=""}}class iv extends Bh{constructor(){super()}GetServiceName(){return iv.ServiceName}}iv.ServiceName="SsrConfigService";class sv extends Bh{constructor(){super()}GetServiceName(){return sv.ServiceName}}sv.ServiceName="Srp30ConfigService";class av extends Bh{constructor(){super()}GetServiceName(){return av.ServiceName}}av.ServiceName="Srp22ConfigService";class cv{constructor(){this.WindThreshold=$h.Disabled,this.BrightnessThreshold=Lh.Disabled}}!function(e){e[e.Disabled=0]="Disabled",e[e.Speed15km_h=1]="Speed15km_h",e[e.Speed21km_h=2]="Speed21km_h",e[e.Speed28km_h=3]="Speed28km_h",e[e.Speed36km_h=4]="Speed36km_h",e[e.Speed45km_h=5]="Speed45km_h",e[e.Speed55km_h=6]="Speed55km_h",e[e.Speed66km_h=7]="Speed66km_h",e[e.Speed78km_h=8]="Speed78km_h",e[e.Speed91km_h=9]="Speed91km_h"}($h||($h={})),function(e){e[e.Disabled=0]="Disabled",e[e.Brightness2000lux=1]="Brightness2000lux",e[e.Brightness5000lux=2]="Brightness5000lux",e[e.Brightness10000lux=3]="Brightness10000lux",e[e.Brightness20000lux=4]="Brightness20000lux",e[e.Brightness40000lux=5]="Brightness40000lux",e[e.Brightness60000lux=6]="Brightness60000lux",e[e.Brightness70000lux=7]="Brightness70000lux",e[e.Brightness80000lux=8]="Brightness80000lux",e[e.Brightness90000lux=9]="Brightness90000lux"}(Lh||(Lh={}));var lv,uv,dv,hv=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class vv{constructor(){this._connection=hd.Get(Ie.ServiceName),this._logger=hd.Get(r.ServiceName),this._controllerConfigurationService=hd.Get(Ae.ServiceName)}GetServiceName(){return vv.ServiceName}GetBrightnessAndWindThresholdAsync(e){var t;return hv(this,void 0,void 0,(function*(){try{const n=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new fv(e.Guid),8e3,!1);if(null==n||null==n.Status||null==n.Data)return new Ge(wg.OtherError,"Cannot get brightness threshold - unknown error.");if(n.Status!==oe.OK)return new Ge(wg.OtherError,`Cannot get brightness threshold - controller responded with error code: ${n.Status}.`);const r=new cv;return r.BrightnessThreshold=n.Data.BrightnessThreshold,r.WindThreshold=n.Data.WindThreshold,r}catch(e){return new Ge(wg.OtherError,"Cannot get brightness threshold - unknown error.")}}))}SetBrightnessThresholdAsync(e,t){var n;return hv(this,void 0,void 0,(function*(){try{const r=yield this.GetBrightnessAndWindThresholdAsync(e);if(null!=r.Type)return this._logger.Error(vv.ServiceName,"Failed to set brightness threshold parameter - cannot get current configuration."),oe.Error;yield this._controllerConfigurationService.EnterConfigurationModeAsync();const o=new gv;o.DeviceGuid=e.Guid,o.BrightnessThreshold=t,o.WindThreshold=r.WindThreshold;const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new pv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(vv.ServiceName,"Failed to set brightness threshold parameter- unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(vv.ServiceName,`Failed to set brightness threshold parameter, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}SetWindThresholdAsync(e,t){var n;return hv(this,void 0,void 0,(function*(){try{const r=yield this.GetBrightnessAndWindThresholdAsync(e);if(null!=r.Type)return this._logger.Error(vv.ServiceName,"Failed to set wind threshold parameter - cannot get current configuration."),oe.Error;yield this._controllerConfigurationService.EnterConfigurationModeAsync();const o=new gv;o.DeviceGuid=e.Guid,o.BrightnessThreshold=r.BrightnessThreshold,o.WindThreshold=t;const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new pv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(vv.ServiceName,"Failed to set wind threshold parameter- unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(vv.ServiceName,`Failed to set wind threshold parameter, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}}vv.ServiceName="WszfBidiConfigService";class gv extends cv{constructor(){super(...arguments),this.DeviceGuid=""}}class fv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/threshold/windbrightness/",this.Method=ie.Get,this.Data=e}}class pv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/threshold/windbrightness/",this.Method=ie.Put,this.Data=e}}class mv{constructor(){this._hours=0,this._minutes=0,this._seconds=0,this._raw=0}get Raw(){return this._raw}get Hours(){return this._hours}set Hours(e){this._hours=e}get Minutes(){return this._minutes}set Minutes(e){this._minutes=e}get Seconds(){return this._seconds}set Seconds(e){this._seconds=e}}class yv{constructor(){this.Channel=0,this.State=lv.Disabled}}!function(e){e[e.Disabled=0]="Disabled",e[e.Enabled=1]="Enabled",e[e.PreviousState=2]="PreviousState"}(lv||(lv={}));class wv{constructor(){this.Channel=0,this.Time=new mv}}!function(e){e[e.Monostable=0]="Monostable",e[e.Bistable=1]="Bistable"}(uv||(uv={})),function(e){e[e.None=0]="None",e[e.Off=1]="Off",e[e.On=2]="On",e[e.Time=3]="Time",e[e.Mono=4]="Mono",e[e.Bi=5]="Bi",e[e.OnOff=6]="OnOff"}(dv||(dv={}));var Sv,_v,Cv=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class bv{constructor(){this._connection=null,this._connection=hd.Get(Ie.ServiceName),this._logger=hd.Get(r.ServiceName)}GetTurnOnBehaviourAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get turn on behaviour - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Av(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Sv.OtherError,"Cannot get turn on behaviour - unknown error.");if(r.Status!==oe.OK)return new Ge(Sv.OtherError,`Cannot get turn on behaviour - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Sv.NoData,"Cannot get turn on behaviour - no data in response.");const o=new yv;return o.Channel=r.Data.Channel,o.State=r.Data.State,16===o.State&&(o.State=lv.Disabled),o}catch(e){return new Ge(Sv.OtherError,"Failed to retrieve turn on behaviour - unknown error.")}}))}SetTurnOnBehaviourAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{const r=new Ev;r.DeviceGuid=e.Guid,r.Channel=t.Channel,r.State=t.State;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Dv(r),8e3,!1);return null==o||null==o.Status?(this._logger.Error(bv.ServiceName,"Failed to set turn on behaviour - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set turn on behaviour, response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}GetGlobalTimeSettingsAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get global time settings - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Tv(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Sv.OtherError,"Cannot get global time settings - unknown error.");if(r.Status!==oe.OK)return new Ge(Sv.OtherError,`Cannot get global time settings - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Sv.NoData,"Cannot get global time settings - no data in response.");const o=new wv;return o.Channel=r.Data.Channel,o.Time=this.ParseNumberToTime(r.Data.Time),o}catch(e){return new Ge(Sv.OtherError,"Cannot get global time settings - unknown error.")}}))}SetGlobalTimeSettingsAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{const r=3600*t.Time.Hours+60*t.Time.Minutes+t.Time.Seconds,o=new Fv;o.Channel=t.Channel,o.DeviceGuid=e.Guid,o.Time=r;const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new kv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set global time settings - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set global time settings, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}GetTurnOnTimeAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get turn on time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Iv(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Sv.OtherError,"Cannot get turn on time - unknown error.");if(r.Status!==oe.OK)return new Ge(Sv.OtherError,`Cannot get turn on time - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Sv.NoData,"Cannot get turn on time - no data in response.");const o=new wv;return o.Channel=r.Data.Channel,o.Time=this.ParseNumberToTime(r.Data.Time),o}catch(e){return new Ge(Sv.OtherError,"Cannot get turn on time - unknown error.")}}))}SetTurnOnTimeAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{const r=3600*t.Time.Hours+60*t.Time.Minutes+t.Time.Seconds,o=new Fv;o.Channel=t.Channel,o.DeviceGuid=e.Guid,o.Time=r;const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Rv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set turn on time settings - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set turn on time settings, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}GetSwitchInputOutputParamAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get input/output parameters - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Pv(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(Sv.OtherError,"Cannot get input/output parameters - unknown error."):r.Status!==oe.OK?new Ge(Sv.OtherError,`Cannot get input/output parameters - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(Sv.NoData,"Cannot get input/output parameter - no data in response."):r.Data.map((e=>{const t=new Gv;return t.Channel=e.Channel,t.InputMode=e.InputMode,t.InputsNumber=e.InputsNumber,t.ReactionToInput=e.ReactionToInput,t.InputChannel=e.InputChannel,t}))}catch(e){return new Ge(Sv.OtherError,"Cannot get input/output parameters - unknown error.")}}))}SetSwitchInputOutputParamAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{if(t.InputMode==uv.Bistable&&t.ReactionToInput==dv.Bi)return this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - reaction to input cannot be 'bistable' when mode is set to 'bistable', switch mode to 'monostable' and call fucntion again."),oe.WrongData;const r=new Ov;r.DeviceGuid=e.Guid,r.Channel=t.Channel,r.InputChannel=t.InputChannel,r.ReactionToInput=t.ReactionToInput,r.InputMode=t.InputMode;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new xv(r),8e3,!1);return null==o||null==o.Status?(this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set input/output parameters, response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}SetSwitchInputOutputInputModeParamAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{const r=yield this.GetSwitchInputOutputParamAsync(e,t.Channel);if(null!=r.Type)return this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - cannot get current configuration."),oe.Error;const o=r.firstOrDefault((e=>e.Channel==t.Channel&&e.InputChannel==t.InputChannel));if(null==o)return this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - channel or inputChannel params may be incorrect."),oe.WrongData;const i=new Ov;i.DeviceGuid=e.Guid,i.Channel=t.Channel,i.InputChannel=t.InputChannel,i.InputMode=t.InputMode,i.ReactionToInput=o.ReactionToInput;const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new xv(i),8e3,!1);return null==s||null==s.Status?(this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - unknow error."),oe.FatalError):(s.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set input/output parameters, response status: ${s.Status}`),s.Status)}catch(e){return oe.FatalError}}))}SetSwitchInputOutputReactionToInputParamAsync(e,t){var n;return Cv(this,void 0,void 0,(function*(){try{const r=yield this.GetSwitchInputOutputParamAsync(e,t.Channel);if(null!=r.Type)return this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - cannot get current configuration."),oe.Error;const o=r.firstOrDefault((e=>e.Channel==t.Channel&&e.InputChannel==t.InputChannel));if(null==o)return this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - channel or inputChannel params may be incorrect."),oe.WrongData;if(o.InputMode==uv.Bistable&&t.ReactionToInput==dv.Bi)return this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - reaction to input cannot be 'bistable' when mode is set to 'bistable', switch mode to 'monostable' and call fucntion again."),oe.WrongData;const i=new Ov;i.DeviceGuid=e.Guid,i.Channel=t.Channel,i.InputChannel=t.InputChannel,i.ReactionToInput=t.ReactionToInput,i.InputMode=o.InputMode;const s=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new xv(i),8e3,!1);return null==s||null==s.Status?(this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - unknow error."),oe.FatalError):(s.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set input/output parameters, response status: ${s.Status}`),s.Status)}catch(e){return oe.FatalError}}))}ParseNumberToTime(e){const t=new Nv;return t.Hours=Math.floor(e/3600),t.Minutes=Math.floor(e%3600/60),t.Seconds=Math.floor(e%3600%60),t.Raw=e,t}}bv.ServiceName="OnOffSwitchService",function(e){e.InvalidChannelNumber="InvalidChannelNumber",e.OtherError="OtherError",e.NoData="NoData"}(Sv||(Sv={}));class Av extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/state/turnon",this.Method=ie.Get,this.Data=e}}class Ev extends yv{constructor(){super(...arguments),this.DeviceGuid=""}}class Dv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/state/turnon",this.Method=ie.Put,this.Data=e}}class Nv extends mv{set Raw(e){this._raw=e}}class Tv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/global/time",this.Method=ie.Get,this.Data=e}}class kv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/global/time",this.Method=ie.Put,this.Data=e}}class Fv{constructor(){this.Channel=0,this.DeviceGuid="",this.Time=0}}class Iv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/device/on/time",this.Method=ie.Get,this.Data=e}}class Rv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/device/on/time",this.Method=ie.Put,this.Data=e}}class Gv{constructor(){this._channel=0,this._inputsNumber=0,this._inputMode=uv.Monostable,this._reactionToInput=dv.None,this._inputChannel=0}get Channel(){return this._channel}set Channel(e){this._channel=e}get InputsNumber(){return this._inputsNumber}set InputsNumber(e){this._inputsNumber=e}get InputMode(){return this._inputMode}set InputMode(e){this._inputMode=e}get ReactionToInput(){return this._reactionToInput}set ReactionToInput(e){this._reactionToInput=e}get InputChannel(){return this._inputChannel}set InputChannel(e){this._inputChannel=e}}class Ov{constructor(){this.DeviceGuid="",this.Channel=0,this.InputChannel=0,this.InputMode=uv.Bistable,this.ReactionToInput=dv.None}}class Pv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/input/output",this.Method=ie.Get,this.Data=e}}class xv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/input/output",this.Method=ie.Put,this.Data=e}}class Mv{constructor(){this.Channel=0,this.InputModeDimmer=_v.Monostable}}!function(e){e[e.Monostable=0]="Monostable",e[e.Time=1]="Time",e[e.Bistable=2]="Bistable"}(_v||(_v={}));var $v,Lv,Wv,Bv=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class Uv extends bv{constructor(){super()}GetServiceName(){return Uv.ServiceName}GetDimmerInputOutputParamAsync(e,t){var n;return Bv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get input/output parameters - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new zv(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Sv.OtherError,"Cannot get input/output parameters - unknown error.");if(r.Status!==oe.OK)return new Ge(Sv.OtherError,`Cannot get input/output parameters - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Sv.NoData,"Cannot get input/output parameters - no data in response.");const o=r.Data.first(),i=new Mv;return i.Channel=o.Channel,i.InputModeDimmer=o.InputModeDimmer,i}catch(e){return new Ge(Sv.OtherError,"Cannot get input/output parameters - unknown error.")}}))}SetDimmerInputOutputParamAsync(e,t){var n;return Bv(this,void 0,void 0,(function*(){try{const r=new Hv;r.DeviceGuid=e.Guid,r.Channel=t.Channel,r.InputModeDimmer=t.InputModeDimmer;const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new jv(r),8e3,!1);return null==o||null==o.Status?(this._logger.Error(bv.ServiceName,"Failed to set input/output parameters - unknow error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set input/output parameters, response status: ${o.Status}`),o.Status)}catch(e){return oe.FatalError}}))}GetBrighteningTimeAsync(e,t){var n;return Bv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get brightening time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new qv(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(Sv.OtherError,"Cannot get brightening time - unknown error."):r.Status!==oe.OK?new Ge(Sv.OtherError,`Cannot get brightening time - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(Sv.NoData,"Cannot get brightening time - no data in response."):r.Data.State}catch(e){return new Ge(Sv.OtherError,"Cannot get brightening time - unknown error.")}}))}SetBrighteningTimeAsync(e,t,n){var r;return Bv(this,void 0,void 0,(function*(){try{const o=new Kv;o.DeviceGuid=e.Guid,o.Channel=t,o.State=n;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Vv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set brightening time - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set brightening time, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}GetDimmingTimeAsync(e,t){var n;return Bv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get dimming time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Jv(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(Sv.OtherError,"Cannot get dimming time - unknown error."):r.Status!==oe.OK?new Ge(Sv.OtherError,`Cannot get dimming time - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(Sv.NoData,"Cannot get dimming time - no data in response."):r.Data.State}catch(e){return new Ge(Sv.OtherError,"Cannot get dimming time - unknown error.")}}))}SetDimmingTimeAsync(e,t,n){var r;return Bv(this,void 0,void 0,(function*(){try{const o=new Kv;o.DeviceGuid=e.Guid,o.Channel=t,o.State=n;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Yv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set dimming time - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set dimming time, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}GetMinLevelAsync(e,t){var n;return Bv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get mimimum light level - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Xv(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(Sv.OtherError,"Cannot get mimimum light level - unknown error."):r.Status!==oe.OK?new Ge(Sv.OtherError,`Cannot get mimimum light level - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(Sv.NoData,"Cannot get mimimum light level - no data in response."):r.Data.State}catch(e){return new Ge(Sv.OtherError,"Cannot get mimimum light level - unknown error.")}}))}SetMinLevelAsync(e,t,n){var r;return Bv(this,void 0,void 0,(function*(){try{const o=new Kv;o.DeviceGuid=e.Guid,o.Channel=t,o.State=n;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Qv(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set mimimum light level - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set mimimum light level, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}GetMaxLevelAsync(e,t){var n;return Bv(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get maximum light level - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Zv(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(Sv.OtherError,"Cannot get maximum light level - unknown error."):r.Status!==oe.OK?new Ge(Sv.OtherError,`Cannot get maximum light level - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(Sv.NoData,"Cannot get maximum light level - no data in response."):r.Data.State}catch(e){return new Ge(Sv.OtherError,"Cannot get maximum light level - unknown error.")}}))}SetMaxLevelAsync(e,t,n){var r;return Bv(this,void 0,void 0,(function*(){try{const o=new Kv;o.DeviceGuid=e.Guid,o.Channel=t,o.State=n;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new eg(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set maximum light level - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set maximum light level, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}}Uv.ServiceName="Rdp21ConfigService";class Kv{constructor(){this.Channel=0,this.DeviceGuid="",this.State=0,this.StateOptional=0}}class Hv extends Mv{constructor(){super(...arguments),this.DeviceGuid=""}}class zv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/input/output",this.Method=ie.Get,this.Data=e}}class jv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/input/output",this.Method=ie.Put,this.Data=e}}class qv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/brightening/time",this.Method=ie.Get,this.Data=e}}class Vv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/brightening/time",this.Method=ie.Put,this.Data=e}}class Jv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/dimming/time",this.Method=ie.Get,this.Data=e}}class Yv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/dimming/time",this.Method=ie.Put,this.Data=e}}class Xv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/min/level",this.Method=ie.Get,this.Data=e}}class Qv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/min/level",this.Method=ie.Put,this.Data=e}}class Zv extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/max/level",this.Method=ie.Get,this.Data=e}}class eg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/max/level",this.Method=ie.Put,this.Data=e}}class tg extends bv{constructor(){super()}GetServiceName(){return bv.ServiceName}}tg.ServiceName="RopConfigService";class ng extends bv{constructor(){super()}GetServiceName(){return bv.ServiceName}}ng.ServiceName="RomConfigService";class rg extends bv{constructor(){super()}GetServiceName(){return bv.ServiceName}}rg.ServiceName="Rog21ConfigService",function(e){e[e.Gate=1]="Gate",e[e.Gateway=2]="Gateway",e[e.Monostable=3]="Monostable"}($v||($v={})),function(e){e[e.LimitSwitchDisabled=0]="LimitSwitchDisabled",e[e.LimitSwitchClosed=1]="LimitSwitchClosed",e[e.LimitSwitchOpened=2]="LimitSwitchOpened"}(Lv||(Lv={})),function(e){e[e.NormallyOpened=1]="NormallyOpened",e[e.NormallyClosed=2]="NormallyClosed"}(Wv||(Wv={}));class og{constructor(){this.Channel=0,this.Input=0,this.Function=Lv.LimitSwitchDisabled,this.Type=Wv.NormallyClosed}}var ig=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class sg{constructor(){this._connection=hd.Get(Ie.ServiceName),this._logger=hd.Get(r.ServiceName),this._controllerConfigurationService=hd.Get(Ae.ServiceName)}GetServiceName(){return sg.ServiceName}GetGateModeAsync(e,t){var n;return ig(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(wg.InvalidChannelNumber,`Cannot get gate working mode - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new cg(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(wg.OtherError,"Cannot get gate working mode - unknown error."):r.Status!==oe.OK?new Ge(wg.OtherError,`Cannot get gate working mode - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(wg.NoData,"Cannot get gate working mode - no data in response."):r.Data.TypeOfGateChannel}catch(e){return new Ge(wg.OtherError,"Cannot get gate working mode - unknown error.")}}))}SetGateModeAsync(e,t,n){var r;return ig(this,void 0,void 0,(function*(){try{const o=new ag;o.DeviceGuid=e.Guid,o.Channel=t,o.TypeOfGateChannel=n,yield this._controllerConfigurationService.EnterConfigurationModeAsync();const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new lg(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(sg.ServiceName,"Failed to set working mode parameter - unknown error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(sg.ServiceName,`Failed to set working mode parameter, response status: ${i.Status}`),i.Status)}catch(e){return this._logger.Error(sg.ServiceName,"Failed to set working mode parameter - unknown error."),oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}GetPulseTimeAsync(e,t){var n;return ig(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(wg.InvalidChannelNumber,`Cannot get pulse time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new ug(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(wg.OtherError,"Cannot get pulse time - unknown error."):r.Status!==oe.OK?new Ge(wg.OtherError,`Cannot get pulse time - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(wg.NoData,"Cannot get pulse time - no data in response."):r.Data.PulseTime/10}catch(e){return new Ge(wg.OtherError,"Cannot get pulse time - unknown error.")}}))}SetPulseTimeAsync(e,t,n){var r;return ig(this,void 0,void 0,(function*(){try{if(n<.1||n>300||n*Math.pow(10,1)%1!=0)return this._logger.Error(sg.ServiceName,"Failed to set pulse time - value is out of range!"),oe.WrongData;const o=yield this.GetGateModeAsync(e,t);if(null!=o.Type)return this._logger.Error(sg.ServiceName,"Failed to set pulse time - cannot get current mode of gate controller."),oe.Error;if(o==$v.Monostable)return this._logger.Error(sg.ServiceName,"Failed to set pulse time - cannot set pulse time when channel mode is 'monostable'."),oe.OperationNotPermitted;const i=new ag;i.DeviceGuid=e.Guid,i.Channel=t,i.PulseTime=10*n,yield this._controllerConfigurationService.EnterConfigurationModeAsync();const s=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new dg(i),8e3,!1);return null==s||null==s.Status?(this._logger.Error(sg.ServiceName,"Failed to set pulse time - unknown error."),oe.FatalError):(s.Status!==oe.OK&&this._logger.Error(sg.ServiceName,`Failed to set pulse time, response status: ${s.Status}`),s.Status)}catch(e){return this._logger.Error(sg.ServiceName,"Failed to set pulse time - unknown error."),oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}GetLimitingSwitchesConfigurationsAsync(e){var t,n;return ig(this,void 0,void 0,(function*(){try{const r=yield null===(t=this._connection)||void 0===t?void 0:t.SendAndWaitForResponseAsync(new vg(new hg(e.Guid,1)),8e3,!1),o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new vg(new hg(e.Guid,2)),8e3,!1);if(null==r||null==r.Status||null==r.Data||null==o||null==o.Status||null==o.Data)return new Ge(wg.OtherError,"Cannot get limiting switch configuration - unknown error.");if(r.Status!==oe.OK||o.Status!==oe.OK)return new Ge(wg.OtherError,`Cannot get limiting switch configuration - controller responded with error code: ${r.Status!=oe.OK?r.Status:o.Status}.`);const i=[];return i.push(r.Data),i.push(o.Data),i.map((e=>{const t=new og;return t.Channel=e.Channel,t.Function=e.Function,t.Input=e.Input,t.Type=e.Type,t}))}catch(e){return new Ge(wg.OtherError,"Cannot get limiting switch configuration - unknown error.")}}))}SetLimitingSwitchConfigurationAsync(e,t){var n;return ig(this,void 0,void 0,(function*(){try{const r=yield this.GetGateModeAsync(e,t.Channel);if(null!=r.Type)return this._logger.Error(sg.ServiceName,"Failed to set limiting switch parameters - cannot get current mode of gate controller."),oe.Error;if(r==$v.Monostable)return this._logger.Error(sg.ServiceName,"Failed to set limiting switch parameters - cannot set this params when channel mode is 'monostable'."),oe.OperationNotPermitted;yield this._controllerConfigurationService.EnterConfigurationModeAsync();const o=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new gg(Object.assign(Object.assign({},t),{DeviceGuid:e.Guid})),8e3,!1);return null==o||null==o.Status?(this._logger.Error(sg.ServiceName,"Failed to set limiting switch parameters - unknown error."),oe.FatalError):(o.Status!==oe.OK&&this._logger.Error(sg.ServiceName,`Failed to set limiting switch parameters, response status: ${o.Status}`),o.Status)}catch(e){return this._logger.Error(sg.ServiceName,"Failed to set limiting switch parameters - unknown error."),oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}GetTimeBetweenPulsesAsync(e,t){var n;return ig(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(wg.InvalidChannelNumber,`Cannot get time between pulses - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new fg(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(wg.OtherError,"Cannot get time between pulses - unknown error."):r.Status!==oe.OK?new Ge(wg.OtherError,`Cannot get time between pulses - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(wg.NoData,"Cannot get time between pulses - no data in response."):r.Data.TimeBetwenPulse/10}catch(e){return new Ge(wg.OtherError,"Cannot get time between pulses - unknown error.")}}))}SetTimeBetweenPulsesAsync(e,t,n){var r;return ig(this,void 0,void 0,(function*(){try{if(n<1||n>300||n%1!=0)return this._logger.Error(sg.ServiceName,"Failed to set time between pulses - value is out of range!"),oe.WrongData;const o=yield this.GetGateModeAsync(e,t);if(null!=o.Type)return this._logger.Error(sg.ServiceName,"Failed to set time between pulses - cannot get current mode of gate controller."),oe.Error;if(o!=$v.Gateway)return this._logger.Error(sg.ServiceName,"Failed to set time between pulses - cannot set this parameter when channel mode is 'monostable' or 'gate'."),oe.OperationNotPermitted;const i=new ag;i.DeviceGuid=e.Guid,i.Channel=t,i.TimeBetwenPulse=10*n,yield this._controllerConfigurationService.EnterConfigurationModeAsync();const s=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new pg(i),8e3,!1);return null==s||null==s.Status?(this._logger.Error(sg.ServiceName,"Failed to set time between pulses - unknown error."),oe.FatalError):(s.Status!==oe.OK&&this._logger.Error(sg.ServiceName,`Failed to set time between pulses, response status: ${s.Status}`),s.Status)}catch(e){return this._logger.Error(sg.ServiceName,"Failed to set time between pulses - unknown error."),oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}GetOpeningTime(e,t){var n;return ig(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(wg.InvalidChannelNumber,`Cannot get gate opening time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new mg(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(wg.OtherError,"Cannot get gate opening time - unknown error."):r.Status!==oe.OK?new Ge(wg.OtherError,`Cannot get gate opening time - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(wg.NoData,"Cannot get gate opening time - no data in response."):r.Data.GateOpenTime}catch(e){return new Ge(wg.OtherError,"Cannot get gate opening time - unknown error.")}}))}SetOpeningTimeAsync(e,t,n){var r;return ig(this,void 0,void 0,(function*(){try{if(n<1||n>300||n%1!=0)return this._logger.Error(sg.ServiceName,"Failed to set opening time - value is out of range!"),oe.WrongData;const o=yield this.GetGateModeAsync(e,t);if(null!=o.Type)return this._logger.Error(sg.ServiceName,"Failed to set opening time - cannot get current mode of gate controller."),oe.Error;if(o!=$v.Gateway)return this._logger.Error(sg.ServiceName,"Failed to set opening time - cannot set this parameter when channel mode is 'monostable' or 'gate'."),oe.OperationNotPermitted;const i=new ag;i.DeviceGuid=e.Guid,i.Channel=t,i.GateOpenTime=n,yield this._controllerConfigurationService.EnterConfigurationModeAsync();const s=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new yg(i),8e3,!1);return null==s||null==s.Status?(this._logger.Error(sg.ServiceName,"Failed to set opening time - unknown error."),oe.FatalError):(s.Status!==oe.OK&&this._logger.Error(sg.ServiceName,`Failed to set opening time, response status: ${s.Status}`),s.Status)}catch(e){return this._logger.Error(sg.ServiceName,"Failed to set opening time - unknown error."),oe.FatalError}finally{yield this._controllerConfigurationService.ExitConfigurationModeAsync()}}))}}sg.ServiceName="Rob21ConfigService";class ag{constructor(){this.Channel=0,this.DeviceGuid="",this.PulseTime=0,this.TimeBetwenPulse=0,this.GateOpenTime=0,this.TypeOfGateChannel=$v.Gate}}class cg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/channel/type",this.Method=ie.Get,this.Data=e}}class lg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/channel/type",this.Method=ie.Put,this.Data=e}}class ug extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/time/pulse",this.Method=ie.Get,this.Data=e}}class dg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/time/pulse",this.Method=ie.Put,this.Data=e}}class hg{constructor(e,t){this.DeviceGuid="",this.Input=0,this.DeviceGuid=e,this.Input=t}}class vg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/inputs/configuration",this.Method=ie.Get,this.Data=e}}class gg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/inputs/configuration",this.Method=ie.Put,this.Data=e}}class fg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/time/between/pulse",this.Method=ie.Get,this.Data=e}}class pg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/time/between/pulse",this.Method=ie.Put,this.Data=e}}class mg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/time/gate/opening",this.Method=ie.Get,this.Data=e}}class yg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/time/gate/opening",this.Method=ie.Put,this.Data=e}}var wg,Sg=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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(s,a)}c((r=r.apply(e,t||[])).next())}))};class _g extends bv{constructor(){super()}GetServiceName(){return _g.ServiceName}GetDimmingAndBrighteningTimeAsync(e,t){var n;return Sg(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get dimming and brightening time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new bg(new pd(e.Guid,t)),8e3,!1);return null==r||null==r.Status?new Ge(Sv.OtherError,"Cannot get dimming and brightening time - unknown error."):r.Status!==oe.OK?new Ge(Sv.OtherError,`Cannot get dimming and brightening time - controller responded with error code: ${r.Status}.`):null==r.Data?new Ge(Sv.NoData,"Cannot get dimming and brightening time - no data in response."):r.Data.State}catch(e){return new Ge(Sv.OtherError,"Cannot get dimming and brightening time - unknown error.")}}))}SetDimmingAndBrighteningTimeAsync(e,t,n){var r;return Sg(this,void 0,void 0,(function*(){try{const o=new Cg;o.DeviceGuid=e.Guid,o.Channel=t,o.State=n;const i=yield null===(r=this._connection)||void 0===r?void 0:r.SendAndWaitForResponseAsync(new Ag(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to set dimming and brightening time - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to set dimming and brightening time, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}SetTurnOnTimeAsync(e,t){const n=Object.create(null,{SetTurnOnTimeAsync:{get:()=>super.SetTurnOnTimeAsync}});return Sg(this,void 0,void 0,(function*(){return t.Time.Hours>0||t.Time.Minutes>4||t.Time.Minutes>=4&&t.Time.Seconds>0?(this._logger.Error(bv.ServiceName,"Failed to turn on time - time must be in range between 0 and 240 seconds."),oe.WrongData):n.SetTurnOnTimeAsync.call(this,e,t)}))}GetTurnOffTimeAsync(e,t){var n;return Sg(this,void 0,void 0,(function*(){try{if(!e.Channels.any((e=>e.Number===t)))return new Ge(Sv.InvalidChannelNumber,`Cannot get turn off time - invalid channel number, channel: ${t}`);const r=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Eg(new pd(e.Guid,t)),8e3,!1);if(null==r||null==r.Status)return new Ge(Sv.OtherError,"Cannot get turn off time - unknown error.");if(r.Status!==oe.OK)return new Ge(Sv.OtherError,`Cannot get turn off time - controller responded with error code: ${r.Status}.`);if(null==r.Data)return new Ge(Sv.NoData,"Cannot get turn off time - no data in response.");const o=new wv;return o.Channel=r.Data.Channel,o.Time=this.ParseNumberToTime(r.Data.Time),o}catch(e){return new Ge(Sv.OtherError,"Cannot get turn off time - unknown error.")}}))}SetTurnOffTimeAsync(e,t){var n;return Sg(this,void 0,void 0,(function*(){try{const r=3600*t.Time.Hours+60*t.Time.Minutes+t.Time.Seconds;if(r>240)return this._logger.Error(bv.ServiceName,"Failed to turn off time - time must be in range between 0 and 240 seconds."),oe.WrongData;const o=new Ng;o.Channel=t.Channel,o.DeviceGuid=e.Guid,o.Time=r;const i=yield null===(n=this._connection)||void 0===n?void 0:n.SendAndWaitForResponseAsync(new Dg(o),8e3,!1);return null==i||null==i.Status?(this._logger.Error(bv.ServiceName,"Failed to turn off time - unknow error."),oe.FatalError):(i.Status!==oe.OK&&this._logger.Error(bv.ServiceName,`Failed to turn off time, response status: ${i.Status}`),i.Status)}catch(e){return oe.FatalError}}))}SetSwitchInputOutputReactionToInputParamAsync(e,t){const n=Object.create(null,{SetSwitchInputOutputReactionToInputParamAsync:{get:()=>super.SetSwitchInputOutputReactionToInputParamAsync}});return Sg(this,void 0,void 0,(function*(){return t.ReactionToInput==dv.Off||t.ReactionToInput==dv.On||t.ReactionToInput==dv.OnOff?(this._logger.Error(bv.ServiceName,"Failed to set reaction to input, SLR-22 allows to set: On, Off or OnOff"),oe.WrongData):n.SetSwitchInputOutputReactionToInputParamAsync.call(this,e,t)}))}}_g.ServiceName="Slr22ConfigService";class Cg{constructor(){this.Channel=0,this.DeviceGuid="",this.State=0,this.StateOptional=0}}class bg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/brightening/time",this.Method=ie.Get,this.Data=e}}class Ag extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/brightening/time",this.Method=ie.Put,this.Data=e}}class Eg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/device/off/time",this.Method=ie.Get,this.Data=e}}class Dg extends re{constructor(e){super(),this.Resource="/extalife/device/parameters/device/off/time",this.Method=ie.Put,this.Data=e}}class Ng{constructor(){this.Channel=0,this.DeviceGuid="",this.Time=0}}class Tg{constructor(){this._services={Rck21ConfigService:new Sd,Rcz21ConfigService:new Dd,Rcm21ConfigService:new Hd,Rcr21ConfigService:new eh,ZfBidiConfigService:new dh,SsrConfigService:new iv,Srp22ConfigService:new av,Srp30ConfigService:new sv,WszfBidiConfigService:new vv,Rdp21ConfigService:new Uv,RopConfigService:new tg,RomConfigService:new ng,Rog21ConfigService:new rg,Rob21ConfigService:new sg,Slr22ConfigService:new _g,FirmwareService:new Vd},this._servicesToDeviceMap=new Map([["becbb229-1637-4b0f-a9f0-d43fa38ef76b",[this._services.Rck21ConfigService,this._services.FirmwareService]],["98d309e4-0986-4dd8-bcb6-fa31541c82be",[this._services.Rcz21ConfigService,this._services.FirmwareService]],["d7f88fcb-19f7-469b-b489-a239762023e5",[this._services.Rcm21ConfigService,this._services.FirmwareService]],["42015ac8-4a84-47b2-855d-795ee8edc06f",[this._services.ZfBidiConfigService,this._services.FirmwareService]],["4688be64-c07c-4508-8e7a-b49bc4bbc78e",[this._services.Rcr21ConfigService,this._services.FirmwareService]],["84c1bb42-1a27-46bb-ae1e-14a790e96a53",[this._services.SsrConfigService,this._services.FirmwareService]],["e7e6b193-0144-4550-93f0-9050bbbaf91d",[this._services.SsrConfigService,this._services.FirmwareService]],["d57de594-768b-4745-97bd-56b70b8be253",[this._services.Srp22ConfigService,this._services.FirmwareService]],["d1b4cfc7-e92c-47d1-9c7c-9c9dd3351832",[this._services.Srp30ConfigService,this._services.FirmwareService]],["f48eab61-047a-4241-a1e6-aee89062cd69",[this._services.WszfBidiConfigService,this._services.FirmwareService]],["db54c107-b406-4c99-8cfa-0455c9089d44",[this._services.Rdp21ConfigService,this._services.FirmwareService]],["e3fbfa59-2e57-465d-a46c-44b5ce30e475",[this._services.RopConfigService,this._services.FirmwareService]],["2520103f-5622-4015-be85-e6dea8640829",[this._services.RopConfigService,this._services.FirmwareService]],["d4638681-2fac-4f3c-a520-281573e431fa",[this._services.RopConfigService,this._services.FirmwareService]],["1f599666-be23-49c1-b42d-17a8db54e11",[this._services.RomConfigService,this._services.FirmwareService]],["554f0414-df02-4525-94e9-47f36015c5d6",[this._services.RomConfigService,this._services.FirmwareService]],["f4cc5043-2198-47df-9361-4cd130ed0323",[this._services.Rog21ConfigService,this._services.FirmwareService]],["7b794533-a040-4637-90d2-17b410a16efa",[this._services.Rob21ConfigService,this._services.FirmwareService]],["13538389-988f-4327-93d3-518e757c8cc9",[this._services.Slr22ConfigService,this._services.FirmwareService]]])}static Init(){o.Instance.RegisterService(new Tg),hd.Get(r.ServiceName).Debug("Initialized ExtaLifeService")}GetServiceName(){return Tg.ServiceName}GetDeviceServiceByServiceType(e){switch(e){case"Rck21ConfigService":return this._services.Rck21ConfigService;case"Rcz21ConfigService":return this._services.Rcz21ConfigService;case"Rcm21ConfigService":return this._services.Rcm21ConfigService;case"Rcr21ConfigService":return this._services.Rcr21ConfigService;case"ZfBidiConfigService":return this._services.ZfBidiConfigService;case"SsrConfigService":return this._services.SsrConfigService;case"Srp22ConfigService":return this._services.Srp22ConfigService;case"Srp30ConfigService":return this._services.Srp30ConfigService;case"WszfBidiConfigService":return this._services.WszfBidiConfigService;case"RopConfigService":return this._services.RopConfigService;case"RomConfigService":return this._services.RomConfigService;case"Rdp21ConfigService":return this._services.Rdp21ConfigService;case"Rog21ConfigService":return this._services.Rog21ConfigService;case"Rob21ConfigService":return this._services.Rob21ConfigService;case"Slr22ConfigService":return this._services.Slr22ConfigService;case"FirmwareService":return this._services.FirmwareService;default:return 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)}}Tg.ServiceName="ExtaLifeService",function(e){e.Success="Success",e.ResourceIsNotAvailable="ResourceIsNotAvailable",e.UnknownError="UnknownError",e.OtherError="OtherError",e.InvalidChannelNumber="InvalidChannelNumber",e.DeviceNotResponding="DeviceNotResponding",e.NoData="NoData"}(wg||(wg={}))})();
2
2
  //# sourceMappingURL=exalushome-ExtaLife-bundle.js.map