@interopio/desktop 6.17.0 → 6.18.0

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).desktop=e.desktop||{},e.desktop.browser=e.desktop.browser||{},e.desktop.browser.min=t())}(this,function(){"use strict";var e=1,t=2,n=3,i=4;function r(r){return r.type===n?"timestamp":r.type===t?"number":r.type===e?"string":r.type===i?"object":"unknown"}function o(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function s(e){const t={},n=r(e);if("object"===n){const n=Object.keys(e.value).reduce((t,n)=>{const i=o(e.value[n]);if("object"===i){const i=a(e.value[n]);t[n]={type:"object",description:"",context:{},composite:i}}else t[n]={type:i,description:"",context:{}};return t},{});t.composite=n}return t.name=c(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function a(e){return Object.keys(e).reduce((t,n)=>{const i=o(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:a(e[n])}:{type:i,description:"",context:{}},t},{})}function c(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function d(e){return"timestamp"===r(e)?Date.now():h(e.value)}function h(e){return"object"!=typeof e?e:Object.keys(e).reduce((t,n)=>{const i=e[n];return"object"==typeof i&&i.constructor!==Date?t[n]=h(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t},{})}function u(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?u(t):t),[])}function l(e){const t=u(e.root.getAggregateState()),n=t.sort((e,t)=>e.state?t.state?t.state-e.state:-1:1)[0];const i=function(e){let t="";return e.forEach((e,n,i)=>{const r=e.path.join(".");n===i.length-1?t+=r+"."+e.name+": "+e.description:t+=r+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var p=(e,t,n)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===n||"object"!=typeof n)throw new Error("Missing transport")};class g{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,n,i,r){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=r,p(e,t,n),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,n.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class f extends g{constructor(e,n,i,r){super(e,n,i,r,t)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class m extends g{constructor(e,t,n,r){super(e,t,n,r,i)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach(t=>{void 0!==e[t]&&(this.value[t]=e[t])})}}class y extends g{constructor(t,n,i,r){super(t,n,i,r,e)}}class w extends g{constructor(e,t,i,r){super(e,t,i,r,n)}now(){this.update(new Date)}}function v(r,o,s,a,c){if(!o)throw new Error("Repository is required");if(!s)throw new Error("Transport is required");const d=s,h=r,u=c||"",l=o,p=a,g=function e(t){if(!t||!t.parent)return[];const n=e(t.parent);return n.push(t.name),n}(a);let b={};const _=(C="/",((I=g)&&I.length>0?I.join(C):"")+r);var I,C;const A=o.root,T=[],S=[];function k(e,t,n,i){let r={name:""};r="string"==typeof e?{name:e}:e;const o=S.filter(e=>e.name===r.name);if(o.length>0){const e=o[0];if(e.type!==t)throw new Error(`A metric named ${r.name} is already defined with different type.`);return void 0!==n&&e.update(n).catch(()=>{}),e}const s=i(r);return S.push(s),s}const x={get name(){return h},get description(){return u},get repo(){return l},get parent(){return p},path:g,id:_,root:A,get subSystems(){return T},get metrics(){return S},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=T.filter(t=>t.name===e);if(n.length>0)return n[0];const i=v(e,l,d,x,t);return T.push(i),i},getState:()=>b,setState:function(e,t){b={state:e,description:t},d.updateSystem(x,b)},stringMetric:function(t,n){return k(t,e,n,e=>new y(e,x,d,n))},timestampMetric:function(e,t){return k(e,n,t,e=>new w(e,x,d,t))},objectMetric:function(e,t){return k(e,i,t,e=>new m(e,x,d,t))},numberMetric:function(e,n){return k(e,t,n,e=>new f(e,x,d,n))},getAggregateState:function(){const e=[];return Object.keys(b).length>0&&e.push({name:h,path:g,state:b.state,description:b.description}),T.forEach(t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)}),e}};return d.createSystem(x),x}class b{root;constructor(e,t){t.init(this),this.root=v("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),n=e=>{if(!e.target)return;const n=e.target,i=n?n.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:i,id:n.id,type:"<"+n.tagName.toLowerCase()+">",href:n.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",n):document.attachEvent("onclick",n)}e.stringMetric("StartTime",(new Date).toString());const n=e.stringMetric("StartURL",""),i=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;n.update(e)}void 0!==window.glue42gd&&i.update(window.glue42gd.appName)}}}class _{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class I{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,n){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=n??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout(()=>{this.collect(),setInterval(()=>{this.collect()},this.publishInterval)},this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map(e=>e.toJSON());this.system.stringMetric("entries",JSON.stringify(t))}}var C=e=>{let t;t=e.connection&&"object"==typeof e.connection?function(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let n,i;const r=e=>{o(e.root)},o=e=>{a(e),e.metrics.forEach(e=>{h(e)}),e.subSystems.forEach(e=>{o(e)})},a=async e=>{if(void 0===e.parent)return;await n;const r={type:"define",metrics:[{name:c(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(n)}`)})},h=async e=>{const r=p(e);await n;const o={type:"define",metrics:[s(r)]};i.sendFireAndForget(o).catch(n=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(n)}`)}),void 0!==r.value&&u(r)},u=e=>{if(g()){const n=d(e),r={type:"publish",values:[{name:c(e.path.join("/")+"/"+e.name),value:n,timestamp:Date.now()}]};return i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(n)}`)})}return Promise.resolve()},p=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},g=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:o=>{let s;n=new Promise(e=>{s=e}),i=e.domain("metrics"),i.onJoined(e=>{!e&&s&&(s(),s=void 0);const n={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(n).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&r(o)}),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:a,updateSystem:async(r,o)=>{await n;const s={type:"publish",values:[{name:c(r.path.join("/")+"/"+r.name+"/State"),value:{Description:o.description,Value:o.state},timestamp:Date.now()}]};i.sendFireAndForget(s).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${r.name}: ${JSON.stringify(e)}`)});const a=l(r),d={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};i.sendFireAndForget(d).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${r.name}: ${JSON.stringify(e)}`)})},createMetric:h,updateMetric:async e=>{const t=p(e);await n,u(t)}}}(e.connection,e):new _;let n=new b(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));const i=function(e){const t=e.subSystem("reporting"),n={name:"features"};let i;const r=(e,r,o)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===r||""===r)throw new Error("action is mandatory");if(void 0===o||""===o)throw new Error("payload is mandatory");i?i.update({name:e,action:r,payload:o}):i=t.objectMetric(n,{name:e,action:r,payload:o})};return e.featureMetric=r,e}(n);return function(e,t){if("undefined"==typeof window)return;const n=window?.glue42gd?.metrics?.pagePerformanceMetrics;n&&(t=n);t?.enabled&&new I(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function T(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function S(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var r=n instanceof Error?n:new Error(n);if(t)t(r);else{var o='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,r){var o=n[e];return o||(o=[],n[e]=o),o.push(t),r&&setTimeout(function(){r.forEach(function(r){var o;if(null===(o=n[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}catch(t){i(t,e)}})},0),function(){var i=n[e];i&&(0===(i=i.reduce(function(e,n,i){return n===t&&e.length===i||e.push(n),e},[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var o=n[e];if(!o||0===o.length)return[];var s=[];return o.forEach(function(n){try{var r=n.apply(void 0,t);s.push(r)}catch(t){s.push(void 0),i(t,e)}}),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}S.default=S;var k=T(S);class x{gw;registry=k();client;constructor(e,t){this.gw=e.facade,this.gw.connect((e,t)=>{this.messageHandler(t)}).then(e=>{this.client=e})}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class E{logger;worker;registry=k();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}let P=class e{static isNode(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode}static _isNode},M=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};const R={};function N(e){const t=R[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const r=i();let o,s;function a(e,t){const r=t??i();let o=0;n.length>0&&(o=r-n[n.length-1].time),n.push({name:e,time:r,diff:o})}a("start",r);const c={get startTime(){return r},get endTime(){return o},get period(){return s},stop:function(){return o=i(),a("end",o),s=o-r,s},mark:a,marks:n};return R[e]=c,c}const O=P.isNode()?null:window.WebSocket;class j{ws;logger;settings;startupTimer=N("connection");_running=!0;_registry=k();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise((t,n)=>{this.waitForSocketConnection(()=>{try{this.ws?.send(e),t()}catch(e){n(e)}},n)})}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise((e,t)=>{this.waitForSocketConnection(e,t)})}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new M;return this.waitForSocketConnection(()=>{e.resolve()}),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout(()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)},e)}}initiateSocket(){const e=new M;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new O(this.settings.ws??"");let t=!1;return this.ws.onerror=n=>{let i;try{i=JSON.stringify(n)}catch(e){const t=new WeakSet,r=(e,n)=>{if("object"==typeof n&&null!==n){if(t.has(n))return;t.add(n)}return n};i=JSON.stringify(n,r)}this.logger.info(`ws error - reason: ${i}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error")),this.notifyStatusChanged(!1,i)},this.ws.onclose=n=>{this.logger.info(`ws closed - code: ${n?.code} reason: ${n?.reason}`),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach(t=>{e?t.failed&&t.failed(e):t.callback()}),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class ${specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const n of this.specs[t].types){let t=this.subsRefCount[n];if(t||(t=0),t+=1,this.subsRefCount[n]=t,t>1)continue;const i=e.on(n,e=>this.processMessage(n,e));this.subs[n]=i}}processMessage(e,t){if(!this.isDone&&t)for(const n of this.specsNames)if(-1!==this.specs[n].types.indexOf(e)){const e=this.messages[n]||[];this.messages[n]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let W=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const D=(e,t,n)=>new Promise((i,r)=>{const o=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),i(e)}).catch(e=>{clearTimeout(o),r(e)})});class F{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=k();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:()=>{}},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,n){this.settings=e,this.logger=t,this.identity=n,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=n=>{if(this.iAmConnected&&!n.data?.glue42core)return void this.registry.execute("onMessage",n.data);const i=n.data?.glue42core;i&&(i.type===this.messages.gatewayInternalConnect.name&&i.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),i.type===this.messages.gatewayInternalConnect.name&&i.error&&t(i.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))})}initiateRemoteConnection(e){return D((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??W(10);const i=this.getMyWindowId()||W(10),r={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:i,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug("sending connection request"),this.extContentConnecting)return r.glue42core.clientType="child",r.glue42core.bridgeInstanceId=this.myClientId,r.glue42core.parentWindowId=this.parentWindowId,window.postMessage(r,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(r,this.defaultTargetString)},this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const n=this.settings.allowedOrigins||[];if(n.length&&!n.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const i=t.type;this.logger.debug(`received valid glue42core message of type: ${i}`),this.messages[i].handle(e)})}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):(window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent?.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId!==t.clientId?this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||W(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",e=>{const t=e.data?.glue42ExtInc;if(!t)return;const n=this.settings.allowedOrigins||[];!n.length||n.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)}),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleConnectionRejected(e){if(this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),!this.connectionReject)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const n=e.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>D((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},window.origin)},this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out"))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():D(e=>{window.addEventListener("Glue42EXTReady",()=>{e()})},this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),n=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),i=new Set([...t,...n]);if(!i.size&&!this.extContentAvailable)throw new Error(e);if(!i.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(i)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=D(t=>{this.parentPingResolve=t;const n={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval(()=>{e.forEach(e=>{e.postMessage(n,this.defaultTargetString)})},1e3)},this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch(()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)}),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${W(10)}`,this.selfAssignedWindowId):void 0}}class L{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,n)=>{this.queue.push({action:e,resolve:t,reject:n}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}}function G(e,t,n,i,r){null==e&&(e="global"),i=i??["success"],r=r??["error"];let o,s="global"===e,a=!1,c=!1;const d=k();t.disconnected(function(){n.debug("connection is down"),c=!1,s=!1,a=!0,Object.keys(h).forEach(e=>{const t=h[e];t&&(n.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),d.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){n.debug("connection is now up - trying to reconnect...");try{await u(o)}catch{n.trace("failed to reconnect")}}}),t.on("success",e=>g(e)),t.on("error",e=>p(e)),t.on("result",e=>g(e)),i&&i.forEach(e=>{t.on(e,e=>g(e))}),r&&r.forEach(e=>{t.on(e,e=>p(e))});const h={};function u(t){return o=t,new Promise((i,r)=>{if(s)return void i({});let o;if("global"===e)o=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);o=y({type:"join",destination:e,domain:"global",options:t})}o.then(()=>{!function(){n.debug("did join "+e),s=!0;const t=a;a=!1,d.execute("onJoined",t)}(),i({})}).catch(t=>{n.debug("error joining "+e+" domain: "+JSON.stringify(t)),r(t)})})}function l(e){return s&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const n=t.request_id;if(!n)return;const i=h[n];i&&i.error(t)}function g(t){if(t.domain!==e)return;const n=t.request_id;if(!n)return;const i=h[n];i&&i.success(t)}function f(){return W(10)}let m=[];function y(i,r,o){if(i.type&&-1===["hello","join"].indexOf(i.type)&&!s){console.warn(`trying to send a message (${i.domain} ${i.type}) but not connected, will queue`);const e=new M;if(m.push({msg:i,tag:r,options:o,pw:e}),1===m.length){const e=l(()=>{n.info(`joined - will now send queued messages (${m.length} -> [${m.map(e=>e.msg.type)}])`),m.forEach(e=>{y(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),m=[],e()})}return e.promise}o=o??{},i.request_id=i.request_id??f(),i.domain=i.domain??e,o.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise((e,n)=>{h[a]={success:t=>{delete h[a],t._tag=r,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete h[a],e._tag=r,n(e)}},t.send(i,o).catch(e=>{h[a]?.error({err:e})})})}return{join:u,leave:function(){return"global"===e?Promise.resolve():(n.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then(()=>{s=!1,d.execute("onLeft")}).catch(()=>{s=!1,d.execute("onLeft")}))},onJoined:l,onLeft:function(e){return s||e(),d.add("onLeft",e)},send:y,sendFireAndForget:function(n){return n.request_id=n.request_id?n.request_id:f(),n.domain=n.domain??e,n.peer_id=t.peerId,t.send(n)},on:(i,r)=>{t.on(i,t=>{if(t.domain===e)try{r(t)}catch(e){n.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}})},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class U{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=k();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new L;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;loginRetryInProgress=!1;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new x(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new E(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new F(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new j(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const n=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),i=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(n),this._transportSubscriptions.push(i),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue(async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const n=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await n;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}})}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const n=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(n)}`),this.transport.sendObject(n,t)}{const n=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${n}`),this.transport.send(n,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const n=this.ids++;return this.messageHandlers[e][n]=t,{type:e,id:n}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn(()=>{const t=this.transport.name();e(t)})}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),N("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(n)}`),N("connection").mark("protocol-logged-in"),n}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,n){let i=this.sessions.find(t=>t.domain===e);return i||(i=G(e,this,this.logger.subLogger(`domain=${e}`),t,n),this.sessions.push(i)),i}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then(e=>e.token):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,this.registry.execute("onLoggedIn"))}distributeMessage(e,t){const n=this.messageHandlers[t.toLowerCase()];void 0!==n&&Object.keys(n).forEach(t=>{const i=n[t];if(void 0!==i)try{i(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new $(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&this.attemptLoginWithRetry(),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3)}finally{this.loginRetryInProgress=!1}}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return D(e=>{let t;const n=((e,t)=>{let n=e;return()=>{n--,0===n&&t()}})(2,()=>{t&&t(),e()});t=this.onLibReAnnounced(e=>"interop"===e.name||"contexts"===e.name?n():void 0)},1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new j(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport.close().catch(e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`)),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,(e,t)=>{if("string"!=typeof t)return t;if(t.length<this.dateMinLen)return t;if(!t.startsWith(this.datePrefixFirstChar))return t;if(t.substring(0,this.datePrefixLen)!==this.datePrefix)return t;try{const e=parseInt(t.substring(this.datePrefixLen,t.length),10);return isNaN(e)?t:new Date(e)}catch(e){return t}});return{msg:t,msgType:t.type}}createStringMessage(e){const t=Date.prototype.toJSON;try{const t=this.datePrefix;Date.prototype.toJSON=function(){return t+this.getTime()};return JSON.stringify(e)}finally{Date.prototype.toJSON=t}}processObjectMessage(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}}createObjectMessage(e){return e}async loginCore(e,t){this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0;const n=await this.setupAuthConfig(e,t),i={type:"hello",identity:this.settings.identity,authentication:n};e.sessionId&&(i.request_id=e.sessionId),this.globalDomain||(this.globalDomain=G("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]));const r={skipPeerId:!0};this.initialLogin&&(r.retryInterval=this.settings.reconnectInterval,r.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,i,r,e);return this.logger.info("login successful with peerId "+t.peer_id),this.peerId=t.peer_id,this.resolvedIdentity=t.resolved_identity,this.availableDomains=t.available_domains,t.options&&(this.token=t.options.access_token,this.info=t.options.info),this.setLoggedIn(!0),t.resolved_identity}catch(e){throw this.logger.error("error sending hello message - "+(e.message||e.msg||e.reason||e),e),e}finally{e?.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null)}}async tryAuthenticate(e,t,n,i){let r;for(;;){const o=await e.send(t,void 0,n);if("authentication-request"!==o.type){if("welcome"===o.type){r=o;break}throw"error"===o.type?new Error("Authentication failed: "+o.reason):new Error("Unexpected message type during authentication: "+o.type)}{const e=Buffer.from(o.authentication.token,"base64");i.flowCallback&&i.sessionId&&(t.authentication.token=(await i.flowCallback(i.sessionId,e)).data.toString("base64")),t.request_id=i.sessionId}}return r}async setupAuthConfig(e,t){const n={};if(this.gatewayToken=e.gatewayToken,e.gatewayToken){if(t)try{e.gatewayToken=await this.getNewGWToken()}catch(e){this.logger.warn(`failed to get GW token when reconnecting ${e?.message||e}`)}n.method="gateway-token",n.token=e.gatewayToken,this.gatewayToken=e.gatewayToken}else if("sspi"===e.flowName){if(n.provider="win",n.method="access-token",!e.flowCallback||!e.sessionId)throw new Error("Invalid SSPI config");n.token=(await e.flowCallback(e.sessionId,null)).data.toString("base64")}else if(e.token)n.method="access-token",n.token=e.token;else if(e.username)n.method="secret",n.login=e.username,n.secret=e.password;else{if(!e.provider)throw new Error("invalid auth message"+JSON.stringify(e));n.provider=e.provider,n.providerContext=e.providerContext}return n}async logoutCore(){this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer);const e=this.sessions.map(e=>e.leave());await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout(()=>{this.ping()},3e4))}}const H=["trace","debug","info","warn","error","off"];let B=class e{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,n){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}subLogger(t){const n=this.subLoggers.filter(e=>e.name===t)[0];if(void 0!==n)return n;Object.keys(this).forEach(e=>{if(e===t)throw new Error("This sub logger name is not allowed.")});const i=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(i),i}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,n){this.publishMessage(t||"info",e,n)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return H.indexOf(e)>=H.indexOf(t||this.consoleLevel()||"trace")}publishMessage(t,n,i){const r=this.loggerFullName;if("error"===t&&!i){const e=new Error;e.stack&&(n=n+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(t,this.publishLevel())){const o=e.Interop;if(o)try{if(o.methods({name:e.InteropMethodName}).length>0){const s={msg:n,logger:r,level:t};i&&i instanceof Error&&(s.error={message:i.message,stack:i.stack??""}),o.invoke(e.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(t)){let e="";if(this.includeTimeAndLevel){const n=new Date;e=`[${`${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}:${n.getMilliseconds()}`}] [${t}] `}const o=`${e}${r}: ${n}`;switch(t){case"trace":this.logFn.debug(o);break;case"debug":this.logFn.debug?this.logFn.debug(o):this.logFn.log(o);break;case"info":this.logFn.info(o);break;case"warn":this.logFn.warn(o);break;case"error":i?this.logFn.error(o,i):this.logFn.error(o)}}}};const J="create-context",q="created",V="destroyed",z="context-created",K="context-added",Q="subscribe-context",Z="subscribed-context",X="unsubscribe-context",Y="destroy-context",ee="context-destroyed",te="update-context",ne="context-updated",ie="joined",re={get name(){return"context"},get types(){return[J,q,V,z,K,Q,Z,X,Y,ee,te,ne,ie]}};var oe="6.7.3";class se{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new M}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,n,i){this.contextId=e,this.name=t,this.isAnnounced=n,this.activityId=i,this.context={},this.snapshotPromiseWrapper=new M}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var ae={exports:{}};!function(e,t){var n="__lodash_hash_undefined__",i=9007199254740991,r="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",h="[object Number]",u="[object Object]",l="[object Promise]",p="[object RegExp]",g="[object Set]",f="[object String]",m="[object Symbol]",y="[object WeakMap]",w="[object ArrayBuffer]",v="[object DataView]",b="[object Float32Array]",_="[object Float64Array]",I="[object Int8Array]",C="[object Int16Array]",T="[object Int32Array]",S="[object Uint8Array]",k="[object Uint8ClampedArray]",x="[object Uint16Array]",E="[object Uint32Array]",P=/\w*$/,M=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,N={};N[r]=N["[object Array]"]=N[w]=N[v]=N[o]=N[s]=N[b]=N[_]=N[I]=N[C]=N[T]=N[d]=N[h]=N[u]=N[p]=N[g]=N[f]=N[m]=N[S]=N[k]=N[x]=N[E]=!0,N["[object Error]"]=N[a]=N[y]=!1;var O="object"==typeof A&&A&&A.Object===Object&&A,j="object"==typeof self&&self&&self.Object===Object&&self,$=O||j||Function("return this")(),W=t&&!t.nodeType&&t,D=W&&e&&!e.nodeType&&e,F=D&&D.exports===W;function L(e,t){return e.set(t[0],t[1]),e}function G(e,t){return e.add(t),e}function U(e,t,n,i){for(var r=-1,o=e?e.length:0;++r<o;)n=t(n,e[r],r,e);return n}function H(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function B(e){var t=-1,n=Array(e.size);return e.forEach(function(e,i){n[++t]=[i,e]}),n}function J(e,t){return function(n){return e(t(n))}}function q(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}var V,z=Array.prototype,K=Function.prototype,Q=Object.prototype,Z=$["__core-js_shared__"],X=(V=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+V:"",Y=K.toString,ee=Q.hasOwnProperty,te=Q.toString,ne=RegExp("^"+Y.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ie=F?$.Buffer:void 0,re=$.Symbol,oe=$.Uint8Array,se=J(Object.getPrototypeOf,Object),ae=Object.create,ce=Q.propertyIsEnumerable,de=z.splice,he=Object.getOwnPropertySymbols,ue=ie?ie.isBuffer:void 0,le=J(Object.keys,Object),pe=De($,"DataView"),ge=De($,"Map"),fe=De($,"Promise"),me=De($,"Set"),ye=De($,"WeakMap"),we=De(Object,"create"),ve=He(pe),be=He(ge),_e=He(fe),Ie=He(me),Ce=He(ye),Ae=re?re.prototype:void 0,Te=Ae?Ae.valueOf:void 0;function Se(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function ke(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function xe(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Ee(e){this.__data__=new ke(e)}function Pe(e,t){var n=Je(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&qe(e)}(e)&&ee.call(e,"callee")&&(!ce.call(e,"callee")||te.call(e)==r)}(e)?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],i=n.length,o=!!i;for(var s in e)!ee.call(e,s)||o&&("length"==s||Ge(s,i))||n.push(s);return n}function Me(e,t,n){var i=e[t];ee.call(e,t)&&Be(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Re(e,t){for(var n=e.length;n--;)if(Be(e[n][0],t))return n;return-1}function Ne(e,t,n,i,l,y,A){var M;if(i&&(M=y?i(e,l,y,A):i(e)),void 0!==M)return M;if(!Ke(e))return e;var R=Je(e);if(R){if(M=function(e){var t=e.length,n=e.constructor(t);t&&"string"==typeof e[0]&&ee.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!t)return function(e,t){var n=-1,i=e.length;t||(t=Array(i));for(;++n<i;)t[n]=e[n];return t}(e,M)}else{var O=Le(e),j=O==a||O==c;if(Ve(e))return function(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}(e,t);if(O==u||O==r||j&&!y){if(H(e))return y?e:{};if(M=function(e){return"function"!=typeof e.constructor||Ue(e)?{}:(t=se(e),Ke(t)?ae(t):{});var t}(j?{}:e),!t)return function(e,t){return $e(e,Fe(e),t)}(e,function(e,t){return e&&$e(t,Qe(t),e)}(M,e))}else{if(!N[O])return y?e:{};M=function(e,t,n,i){var r=e.constructor;switch(t){case w:return je(e);case o:case s:return new r(+e);case v:return function(e,t){var n=t?je(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case b:case _:case I:case C:case T:case S:case k:case x:case E:return function(e,t){var n=t?je(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}(e,i);case d:return function(e,t,n){var i=t?n(B(e),!0):B(e);return U(i,L,new e.constructor)}(e,i,n);case h:case f:return new r(e);case p:return function(e){var t=new e.constructor(e.source,P.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(q(e),!0):q(e);return U(i,G,new e.constructor)}(e,i,n);case m:return a=e,Te?Object(Te.call(a)):{}}var a}(e,O,Ne,t)}}A||(A=new Ee);var $=A.get(e);if($)return $;if(A.set(e,M),!R)var W=n?function(e){return function(e,t,n){var i=t(e);return Je(e)?i:function(e,t){for(var n=-1,i=t.length,r=e.length;++n<i;)e[r+n]=t[n];return e}(i,n(e))}(e,Qe,Fe)}(e):Qe(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(W||e,function(r,o){W&&(r=e[o=r]),Me(M,o,Ne(r,t,n,i,o,e,A))}),M}function Oe(e){return!(!Ke(e)||(t=e,X&&X in t))&&(ze(e)||H(e)?ne:M).test(He(e));var t}function je(e){var t=new e.constructor(e.byteLength);return new oe(t).set(new oe(e)),t}function $e(e,t,n,i){n||(n={});for(var r=-1,o=t.length;++r<o;){var s=t[r];Me(n,s,e[s])}return n}function We(e,t){var n,i,r=e.__data__;return("string"==(i=typeof(n=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?r["string"==typeof t?"string":"hash"]:r.map}function De(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Oe(n)?n:void 0}Se.prototype.clear=function(){this.__data__=we?we(null):{}},Se.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},Se.prototype.get=function(e){var t=this.__data__;if(we){var i=t[e];return i===n?void 0:i}return ee.call(t,e)?t[e]:void 0},Se.prototype.has=function(e){var t=this.__data__;return we?void 0!==t[e]:ee.call(t,e)},Se.prototype.set=function(e,t){return this.__data__[e]=we&&void 0===t?n:t,this},ke.prototype.clear=function(){this.__data__=[]},ke.prototype.delete=function(e){var t=this.__data__,n=Re(t,e);return!(n<0)&&(n==t.length-1?t.pop():de.call(t,n,1),!0)},ke.prototype.get=function(e){var t=this.__data__,n=Re(t,e);return n<0?void 0:t[n][1]},ke.prototype.has=function(e){return Re(this.__data__,e)>-1},ke.prototype.set=function(e,t){var n=this.__data__,i=Re(n,e);return i<0?n.push([e,t]):n[i][1]=t,this},xe.prototype.clear=function(){this.__data__={hash:new Se,map:new(ge||ke),string:new Se}},xe.prototype.delete=function(e){return We(this,e).delete(e)},xe.prototype.get=function(e){return We(this,e).get(e)},xe.prototype.has=function(e){return We(this,e).has(e)},xe.prototype.set=function(e,t){return We(this,e).set(e,t),this},Ee.prototype.clear=function(){this.__data__=new ke},Ee.prototype.delete=function(e){return this.__data__.delete(e)},Ee.prototype.get=function(e){return this.__data__.get(e)},Ee.prototype.has=function(e){return this.__data__.has(e)},Ee.prototype.set=function(e,t){var n=this.__data__;if(n instanceof ke){var i=n.__data__;if(!ge||i.length<199)return i.push([e,t]),this;n=this.__data__=new xe(i)}return n.set(e,t),this};var Fe=he?J(he,Object):function(){return[]},Le=function(e){return te.call(e)};function Ge(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e<t}function Ue(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Q)}function He(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Be(e,t){return e===t||e!=e&&t!=t}(pe&&Le(new pe(new ArrayBuffer(1)))!=v||ge&&Le(new ge)!=d||fe&&Le(fe.resolve())!=l||me&&Le(new me)!=g||ye&&Le(new ye)!=y)&&(Le=function(e){var t=te.call(e),n=t==u?e.constructor:void 0,i=n?He(n):void 0;if(i)switch(i){case ve:return v;case be:return d;case _e:return l;case Ie:return g;case Ce:return y}return t});var Je=Array.isArray;function qe(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}(e.length)&&!ze(e)}var Ve=ue||function(){return!1};function ze(e){var t=Ke(e)?te.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Qe(e){return qe(e)?Pe(e):function(e){if(!Ue(e))return le(e);var t=[];for(var n in Object(e))ee.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Ne(e,!0,!0)}}(ae,ae.exports);var ce=T(ae.exports);function de(e,t,n){try{if(n?.canPublish("trace")&&n?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=he(e,void 0),t.commands){for(const n of t.commands)"remove"===n.type?fe(e,n.path):"set"===n.type&&pe(e,n.value,n.path);return e}const i=t.added,r=t.updated,o=t.removed;return i&&Object.keys(i).forEach(t=>{e[t]=i[t]}),r&&Object.keys(r).forEach(t=>{ue(t,e,r)}),o&&o.forEach(t=>{delete e[t]}),e}catch(i){return n?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,i),e}}function he(e,t){return ce(e)}const ue=(e,t,n)=>{const i=n[e];if(void 0===i)return t;const r=t[e];return r&&i?"string"==typeof r||"number"==typeof r||"boolean"==typeof r||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(r)||Array.isArray(i)?(t[e]=i,t):(t[e]=Object.assign({},r,i),t):(t[e]=i,t)};function le(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(e[n]!==t[n]){if("object"!=typeof e[n])return!1;if(!le(e[n],t[n]))return!1}}for(const n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function pe(e,t,n){const i=n.split("."),r=["__proto__","constructor","prototype"];let o;for(o=0;o<i.length-1;o++){const t=i[o];if(r.includes(t))throw new Error(`The provided path ${n} is invalid. It cannot contain segment/key that is equal to one of the following values: ${r}.`);e[t]||(e[t]={}),"object"!=typeof e[t]&&(e[t]={}),e=e[t]}e[i[o]]=t}function ge(e,t){return Object.keys(t).every(n=>"object"==typeof t[n]?ge(e?.[n]||{},t[n]||{}):t[n]===e?.[n])}function fe(e,t){const n=t.split(".");let i;for(i=0;i<n.length-1;i++){if(!e[n[i]])return;e=e[n[i]]}delete e[n[i]]}let me=class{ERROR_URI_FAILURE="global.errors.failure";ERROR_URI_INVALID_CONTEXT="global.errors.invalid_context";_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_subscribeOnUpdate;_subscribeOnGet;_onlyReAnnounceSubscribedContexts;_gw3Session;_contextNameToData={};_gw3Subscriptions=[];_nextCallbackSubscriptionNumber=0;_creationPromises={};_contextNameToId={};_contextIdToName={};_protocolVersion=void 0;_contextsTempCache={};_contextsSubscriptionsCache=[];_systemContextsSubKey;get protocolVersion(){if(!this._protocolVersion){const e=this._connection.availableDomains.find(e=>"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[z,Z,ee,ne]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(re.name,e=>{const t=e.type;t&&(t===z||t===K||t===q?this.handleContextCreatedMessage(e):t===Z||t===ne||t===ie?this.handleContextUpdatedMessage(e):t!==ee&&t!==V||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:J,domain:"global",name:e,data:t,lifetime:"retained"}).then(n=>{this._contextNameToId[e]=n.context_id,this._contextIdToName[n.context_id]=e;const i=this._contextNameToData[e]||new se(n.context_id,e,!0,void 0);return i.isAnnounced=!0,i.name=e,i.contextId=n.context_id,i.context=n.data||he(t),i.hasReceivedSnapshot=!0,this._contextNameToData[e]=i,delete this._creationPromises[e],i.sentExplicitSubscription=!0,i.createdByUs=!0,this.subscribe(e,()=>{}),n.context_id})),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=he(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return void await this.createContext(e,t);const i=await this.get(n.name),r=this.setPathSupported?this.calculateContextDeltaV2(i,t):this.calculateContextDeltaV1(i,t);if(!(Object.keys(r.added).length||Object.keys(r.updated).length||r.removed.length||r.commands?.length))return Promise.resolve();const o=await this._gw3Session.send({type:te,domain:"global",context_id:n.contextId,delta:r},{},{skipPeerId:!1});!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,this.handleUpdated(n,r,{updaterId:o.peer_id}))}async set(e,t){t&&(t=he(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return this.createContext(e,t);const i=await this._gw3Session.send({type:te,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1});!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&this.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:i.peer_id})}setPath(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=he(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced){const n={};for(const e of t)pe(n,e.value,e.path);return this.createContext(e,n)}const i=[];for(const e of t)null===e.value?i.push({type:"remove",path:e.path}):i.push({type:"set",path:e.path,value:e.value});const r=await this._gw3Session.send({type:te,domain:"global",context_id:n.contextId,delta:{commands:i}},{},{skipPeerId:!1});!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,this.handleUpdated(n,{added:{},removed:[],updated:{},commands:i},{updaterId:r.peer_id}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return!t&&this._subscribeOnGet&&this.subscribe(e,()=>{}),Promise.resolve({});if(t&&!t.sentExplicitSubscription)return new Promise((t,n)=>{this.subscribe(e,(e,n,i,r)=>{this._subscribeOnGet||this.unsubscribe(r),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):n(e)})});await t.snapshotPromise;const n=t?.context??{};return Promise.resolve(he(n))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribe(e,t,n){e in this._creationPromises&&await this._creationPromises[e];const i=void 0===n?this._nextCallbackSubscriptionNumber:n;void 0===n&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t}));let r=this._contextNameToData[e];if(!r||!r.isAnnounced)return r=r||new se(void 0,e,!1,void 0),this._contextNameToData[e]=r,r.updateCallbacks[i]=t,Promise.resolve(i);const o=r.hasCallbacks();if(r.updateCallbacks[i]=t,o){if(r.hasReceivedSnapshot&&!n){const e=he(r.context);t(e,e,[],i)}return Promise.resolve(i)}if(r.joinedActivity||r.createdByUs){if(r.hasReceivedSnapshot&&!n){const e=he(r.context);t(e,e,[],i)}return Promise.resolve(i)}if(r.context&&r.sentExplicitSubscription){if(r.hasReceivedSnapshot&&!n){const e=he(r.context);t(e,e,[],i)}return Promise.resolve(i)}return this.sendSubscribe(r).then(()=>i,()=>(this.unsubscribe(i,!0),i))}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const n=this._contextNameToData[t];if(!n)continue;const i=n.hasCallbacks();delete n.updateCallbacks[e],n.isAnnounced&&i&&!n.hasCallbacks()&&n.sentExplicitSubscription&&(n.hasReceivedSnapshot=!1,n.context={},this.sendUnsubscribe(n).catch(()=>{})),n.isAnnounced||n.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],n.contextId&&delete this._contextIdToName[n.contextId])}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e],n=t?.contextId;return t&&n?this._gw3Session.send({type:Y,domain:"global",context_id:t.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,n){const i=e.context;e.context=de(e.context,t,this._logger),this._contextNameToData[e.name]!==e||le(i,e.context)||this.invokeUpdateCallbacks(e,t,n)}subscribeToContextCreatedMessages(){const e=[K,z,q];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===q?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===K&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const n=this._contextIdToName[e.context_id];if(!n)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[n])throw new Error("Received created event for context with unknown id: "+e.context_id);let i=this._contextNameToData[n];if(i){if(i.isAnnounced)return;if(!i.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");i.isAnnounced=!0,i.contextId=e.context_id,i.activityId=e.activity_id,i.sentExplicitSubscription||this.sendSubscribe(i).catch(()=>{})}else this._contextNameToData[n]=i=new se(e.context_id,n,!0,e.activity_id),this._trackAllContexts&&this.subscribe(n,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[ne,Z,ie];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,n=e.context_id;let i=this._contextNameToData[this._contextIdToName[n]];const r=!i||!i.isAnnounced;if(t===ie)i||(i=this._contextNameToData[e.activity_id]||new se(n,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=i,this._contextIdToName[n]=e.activity_id,this._contextNameToId[e.activity_id]=n,i.contextId=n,i.isAnnounced=!0,i.activityId=e.activity_id,i.joinedActivity=!0;else if(!i||!i.isAnnounced)return void(t===Z?(i=i||new se(n,e.name,!0,void 0),i.sentExplicitSubscription=!0,this._contextNameToData[e.name]=i,this._contextIdToName[n]=e.name,this._contextNameToId[e.name]=n):this._logger.error(`Received 'update' for unknown context: ${n}`));const o=i.context;if(i.hasReceivedSnapshot=!0,t===Z)i.context=e.data??{};else if(t===ie)i.context=e.context_snapshot??{};else{if(t!==ne)throw new Error("Unrecognized context update message "+t);i.context=de(i.context,e.delta,this._logger)}!r&&le(i.context,o)&&t!==Z||this.invokeUpdateCallbacks(i,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,n){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),pe(t.updated,null,e.path)):"set"===e.type&&pe(t.updated,e.value,e.path)}for(const i in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(i))try{(0,e.updateCallbacks[i])(he(e.context),he(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(i,10),n)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[ee,V];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,n;if(e.type===V){if(n=e.activity_id,t=this._contextNameToId[n],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,n=this._contextIdToName[t],!n)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[n];const i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:Q,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:X,domain:"global",context_id:e.contextId})}catch(n){throw e.sentExplicitSubscription=t,n}}calculateContextDeltaV1(e,t){const n={added:{},updated:{},removed:[],reset:void 0};if(e)for(const i of Object.keys(e))-1===Object.keys(t).indexOf(i)||null===t[i]||le(e[i],t[i])||(n.updated[i]=t[i]);for(const i of Object.keys(t))e&&-1!==Object.keys(e).indexOf(i)?null===t[i]&&n.removed.push(i):null!==t[i]&&(n.added[i]=t[i]);return n}calculateContextDeltaV2(e,t){const n={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const i of Object.keys(t))if(null!==t[i]){le(e?e[i]:null,t[i])||n.commands?.push({type:"set",path:i,value:t[i]})}else n.commands?.push({type:"remove",path:i});return n}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const n=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||n.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(re.name,e=>{const t=e.type;t&&(t===z||t===K||t===q?this.handleContextCreatedMessage(e):t===Z||t===ne||t===ie?this.handleContextUpdatedMessage(e):t!==ee&&t!==V||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}};class ye{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new me(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,n){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(n),this.set(e,n)):this._bridge.setPath(e,t,n)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:n}of t){this.checkPath(e);""===e&&this.checkData(n)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,n,i,r,o)=>t(e,n,i,()=>this._bridge.unsubscribe(r),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function we(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n))}function ve(e=0,t,n){let i;const r=()=>{i&&clearTimeout(i)};return t.then(()=>{r()}).catch(()=>{r()}),new Promise((t,r)=>{i=setTimeout(()=>r(n),e)})}var be=function(e){return{ok:!0,result:e}},_e=function(e){return{ok:!1,error:e}},Ie=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:be(e(t.result,n.result))},Ce=function(e,t){return!0===t.ok?t:_e(e(t.error))},Ae=function(){return Ae=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},Ae.apply(this,arguments)};function Te(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!Te(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!Te(e[i[n]],t[i[n]]))return!1}return!0}}var Se=function(e){return Array.isArray(e)},ke=function(e){return"object"==typeof e&&null!==e&&!Se(e)},xe=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},Ee=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},Pe=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return Ae({at:e+(n||"")},i)},Me=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return Ce(function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}},n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e(function(e){return function(e,t){return!0===t.ok?be(e(t.result)):t}(t,n.decode(e))})},this.andThen=function(t){return new e(function(e){return function(e,t){return!0===t.ok?e(t.result):t}(function(n){return t(n).decode(e)},n.decode(e))})},this.where=function(t,i){return n.andThen(function(n){return t(n)?e.succeed(n):e.fail(i)})}}return e.string=function(){return new e(function(e){return"string"==typeof e?be(e):_e({message:xe("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?be(e):_e({message:xe("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?be(e):_e({message:xe("a boolean",e)})})},e.constant=function(t){return new e(function(e){return Te(e,t)?be(t):_e({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ke(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?_e({message:"the key '"+i+"' is required but was not present"}):_e(Pe("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return be(n)}return ke(e)?be(e):_e({message:xe("an object",e)})})},e.array=function(t){return new e(function(e){if(Se(e)&&t){return e.reduce(function(e,n,i){return Ie(function(e,t){return e.concat([t])},e,function(e,n){return Ce(function(e){return Pe("["+n+"]",e)},t.decode(e))}(n,i))},be([]))}return Se(e)?be(e):_e({message:xe("an array",e)})})},e.tuple=function(t){return new e(function(e){if(Se(e)){if(e.length!==t.length)return _e({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return _e(Pe("["+i+"]",r.error));n[i]=r.result}return be(n)}return _e({message:xe("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return Ie(Object.assign,t,n.decode(e))},be({}))})},e.anyJson=function(){return new e(function(e){return be(e)})},e.unknownJson=function(){return new e(function(e){return be(e)})},e.dict=function(t){return new e(function(e){if(ke(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return _e(Pe("."+i,r.error));n[i]=r.result}return be(n)}return _e({message:xe("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?be(void 0):t.decode(e)})},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e(function(e){for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var o=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return _e({message:'expected a value matching one of the decoders, got the errors ["'+o+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return be(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))})},e.valueAt=function(t,n){return new e(function(e){for(var i=e,r=0;r<t.length;r++){if(void 0===i)return _e({at:Ee(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ke(i))return _e({at:Ee(t.slice(0,r+1)),message:xe("an object",i)});if("number"==typeof t[r]&&!Se(i))return _e({at:Ee(t.slice(0,r+1)),message:xe("an array",i)});i=i[t[r]]}return Ce(function(e){return void 0===i?{at:Ee(t),message:"path does not exist"}:Pe(Ee(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return be(t)})},e.fail=function(t){return new e(function(e){return _e({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),Re=Me.string,Ne=Me.number,Oe=Me.boolean,je=Me.anyJson;Me.unknownJson;var $e=Me.constant,We=Me.object,De=Me.array;Me.tuple,Me.dict;var Fe=Me.optional;Me.oneOf;var Le=Me.union;Me.intersection,Me.withDefault,Me.valueAt,Me.succeed;var Ge=Me.fail;Me.lazy;const Ue=(e,t)=>{const n=typeof e;return"function"===n?je():Ge(`The provided argument as ${t} should be of type function, provided: ${typeof n}`)},He=Re().where(e=>e.length>0,"Expected a non-empty string"),Be=Ne().where(e=>e>=0,"Expected a non-negative number or 0"),Je=Ne().where(e=>e>0,"Expected a positive number"),qe=Le(He,We({name:He,objectTypes:Fe(De(He)),displayName:Fe(He),accepts:Fe(He),returns:Fe(He),description:Fe(He),version:Fe(Be),supportsStreaming:Fe(Oe()),flags:Fe(We()),getServers:Fe(je().andThen(e=>Ue(e,"method definition getServers")))})),Ve=We({application:Fe(He),applicationName:Fe(He),pid:Fe(Be),machine:Fe(He),user:Fe(He),environment:Fe(He),region:Fe(He),service:Fe(He),instance:Fe(He),windowId:Fe(He),peerId:Fe(He),isLocal:Fe(Oe()),api:Fe(He),getMethods:Fe(je().andThen(e=>Ue(e,"instance getMethods"))),getStreams:Fe(je().andThen(e=>Ue(e,"instance getStreams")))}),ze=Le($e("best"),$e("all"),$e("skipMine"),Ve,De(Ve)),Ke=We({waitTimeoutMs:Fe(Je),methodResponseTimeoutMs:Fe(Je)});var Qe;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Qe||(Qe={}));class Ze{protocol;repo;instance;configuration;constructor(e,t,n,i){this.protocol=e,this.repo=t,this.instance=n,this.configuration=i}subscribe(e,t,n,i,r){const o=(e,n,i,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(n,t,e,i,o,r)},s=new Promise((n,i)=>{const r=e=>{n(e)},s=e=>{i(e)};if(!e)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void i(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let d=0,h=this.getServerMethodsByFilterAndTarget(a,c);if(h.length>0)o(h,h[0].methods[0],r,s);else{const n=()=>{if(c&&t.waitTimeoutMs)if(d+=500,h=this.getServerMethodsByFilterAndTarget(a,c),h.length>0){const e=h[0].methods[0];o(h,e,r,s)}else if(d>=t.waitTimeoutMs){o(h,"string"==typeof e?{name:e}:e,r,s)}else setTimeout(n,500)};setTimeout(n,500)}});return we(s,n,i)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,n)=>{e(t,n)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,n)=>{e({server:t,method:n})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,n)=>{e({server:t,method:n})})}async invoke(e,t,n,i,r,o){return we((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),n||(n="best"),i||(i={});const a=qe.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=ze.run(n);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const d=Ke.run(i);if(!d.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(d.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(r&&"function"!=typeof r){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=i.method_response_timeout,void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=i.wait_for_method_timeout,void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=this.configuration.waitTimeoutMs));let h=this.getServerMethodsByFilterAndTarget(s,n);if(0===h.length)try{h=await this.tryToAwaitForMethods(s,n,i)}catch(i){const r=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(n)}`;return Promise.reject(this.generateInvalidInputInvocationResult(r,s,t))}const u=i.methodResponseTimeoutMs,l=i,p=h.map(e=>{const n=W(10),i=e.methods[0],r=e.server,o=this.protocol.client.invoke(n,i,t,r,l);return Promise.race([o,ve(u,o,{invocationId:n,message:`Invocation timeout (${u} ms) reached for method name: ${i?.name}, target instance: ${JSON.stringify(r.instance)}, options: ${JSON.stringify(l)}`,status:Qe.Error})])}),g=await Promise.all(p),f=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===Qe.Error)?Promise.reject(f):f})(),r,o)}generateInvalidInputInvocationResult(e,t,n){const i={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},r={invocationId:W(10),status:Qe.Error,message:e};return this.getInvocationResultObj([r],i,n)}getInvocationResultObj(e,t,n){const i=e.filter(e=>e.status===Qe.Success).reduce((e,i)=>e=[...e,{executed_by:i.instance,returned:i.result,called_with:n,method:t,message:i.message,status:i.status}],[]),r=e.filter(e=>e.status===Qe.Error).reduce((e,i)=>e=[...e,{executed_by:i.instance,called_with:n,name:t.name,message:i.message}],[]),o=e[0];return{method:t,called_with:n,returned:o.result,executed_by:o.instance,all_return_values:i,all_errors:r,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,n){return new Promise((i,r)=>{if(0===n.waitTimeoutMs)return void r();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),i(a);else if(o>=(n.waitTimeoutMs||1e4))return clearInterval(s),void r()},500)})}filterByTarget(e,t){if("string"!=typeof e){let n;n=Array.isArray(e)?e:[e];return n.reduce((e,n)=>{const i=t.filter(e=>this.instanceMatch(n,e.server.instance));return e.concat(i)},[])}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(n=>{let i;const r=e[n],o=t[n];switch(n){case"objectTypes":i=(r||[]).every(e=>(o||[]).includes(e));break;case"flags":i=ge(o||{},r||{});break;default:i=String(r).toLowerCase()===String(o).toLowerCase()}return i})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let n={};return 1===t.length?n=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const i=e.methods[t];n[i.identifier]=i})}),Object.keys(n).map(e=>n[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,n)=>{const i=Object.values(n.methods).filter(t=>this.methodMatch(e,t));return i.length>0&&t.push({server:n,methods:i}),t},[])}getServerMethodsByFilterAndTarget(e,t){const n=this.getServers(e);return this.filterByTarget(t,n)}}class Xe{protocol;repoMethod;subscription;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.subscription=n}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}class Ye{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}}let et=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const n=new Ye(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const n=new Xe(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const n=new Xe(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}};class tt{key;protocol;repoMethod;constructor(e,t,n){this.key=e,this.protocol=t,this.repoMethod=n}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new Xe(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class nt{_protocol;_repoMethod;_server;name;constructor(e,t,n){this._protocol=e,this._repoMethod=t,this._server=n,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new tt(e,this._protocol,this._repoMethod):void 0:t.map(e=>new tt(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new Xe(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class it{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new et(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,n,i,r){const o=new Promise((n,i)=>{if(!e)return void i("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return i(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return i(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;r?(e=r,r.updateRepoMethod(s)):e=new nt(this.protocol,s,this),s.stream=e,n(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),i(e)})});return we(o,n,i)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{const i=t(e.args,e.instance);if(i&&"function"==typeof i.then){n(void 0,await i)}else n(void 0,i)}catch(e){n(e??"",e??"")}};return n.userCallback=t,this.registerCore(e,n)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{let i=!1;const r=e=>{i||n(void 0,e),i=!0},o=e=>{i||(e||(e=""),n(e,e)),i=!0},s=t(e.args,e.instance,r,o);s&&"function"==typeof s.then&&s.then(r).catch(o)}catch(e){n(e,void 0)}};return n.userCallbackAsync=t,this.registerCore(e,n)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let n;if(n="string"==typeof e?{name:e}:e,void 0===n.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const i=this.serverRepository.getList().find(e=>e.definition.name===n.name&&(e.definition.supportsStreaming||!1)===t);if(!i)return Promise.reject(`Method with a name "${n.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([i])}async unregisterWithPredicate(e,t){const n=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!n||0===n.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(n)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const n=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(n),this.addAsCurrentlyUnregistering(e.definition.name,n)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const n=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,n]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let n;if(n="string"==typeof e?{name:""+e}:{...e},!n.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const i=this.currentlyUnregistering[n.name];void 0!==i&&await i;if(this.serverRepository.getList().some(e=>e.definition.name===n.name))return Promise.reject(`A method with the name "${n.name}" already exists! Please, provide a unique name for the method.`);if(n.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${n.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const r=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}});return this.protocol.server.register(r).catch(e=>{throw r?.repoId&&this.serverRepository.remove(r.repoId),e})}onMethodInvoked(e,t,n){e&&e.theFunction&&e.theFunction(n,(n,i)=>{if(null!=n)if(n.message&&"string"==typeof n.message)n=n.message;else if("string"!=typeof n)try{n=JSON.stringify(n)}catch(e){n=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(n)}`}i?("object"!=typeof i||Array.isArray(i))&&(i={_value:i}):i={},this.protocol.server.methodInvocationResult(e,t,n,i)})}}class rt{wrapped={};constructor(e,t,n){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),n&&(n.loggedIn(()=>{this.refresh(n)}),this.refresh(n))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,n=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(n)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??W(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const ot=e=>({...e,flags:e.flags.metadata||{}});class st{logger;API;servers={};myServer;methodsCount={};callbacks=k();constructor(e,t){this.logger=e,this.API=t;const n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const n=this.servers[t];if(n)return n.id;const i=new rt(this.API,e),r={id:t,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[t]=r,this.callbacks.execute("onServerAdded",r.instance),t}removeServerById(e,t){const n=this.servers[e];n?(this.logger.debug(`removing server ${e}`),Object.keys(n.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",n.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");if(n.methods[t.id])return;const i=this.createMethodIdentifier(t),r=this,o={identifier:i,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>r.getServersByMethod(i)};o.object_types=o.objectTypes,o.display_name=o.displayName,o.version=o.version,n.methods[t.id]=o;const s=ot(o);return this.methodsCount[i]||(this.methodsCount[i]=0,this.callbacks.execute("onMethodAdded",s)),this.methodsCount[i]=this.methodsCount[i]+1,this.callbacks.execute("onServerMethodAdded",n.instance,s),o}removeServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");const i=n.methods[t];delete n.methods[t];const r=ot(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",r),this.callbacks.execute("onServerMethodRemoved",n.instance,r)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(ot)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),n=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,n,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),n=this.getMethods();return this.returnUnsubWithDelayedReplay(t,n,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let n=!1;const i=this.getServers();return setTimeout(()=>{i.forEach(t=>{const i=t.methods;Object.keys(i).forEach(r=>{n||e(t.instance,i[r])})})},0),()=>{n=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",n=e.result_signature??"";return(e.name+t+n).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(n=>{Object.values(n.methods).forEach(i=>{i.identifier===e&&t.push(n.instance)})}),t}returnUnsubWithDelayedReplay(e,t,n){let i=!1;return setTimeout(()=>{t.forEach(e=>{i||n(e)})},0),()=>{i=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,n])=>{t[e]=ot(n)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class at{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}}const ct="onSubscriptionRequest",dt="onSubscriptionAdded",ht="onSubscriptionRemoved";class ut{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=k();nextStreamId=0;constructor(e,t,n,i){this.session=e,this.repository=t,this.serverRepository=n,this.logger=i,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,n){if("string"!=typeof n&&(n=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const i=this.getStreamId(t,n),r=e.msg.subscription_id,o={id:r,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[r]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:r,stream_id:i}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${r}: ${JSON.stringify(e)}`)}),this.callbacks.execute(dt,o,t)}rejectRequest(e,t,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,e.msg.subscription_id)}pushData(e,t,n){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof n?n=[n]:(!Array.isArray(n)||n.length<=0)&&(n=[]);e.protocolState.branchKeyToStreamIdMap.filter(e=>!n||0===n.length||n.indexOf(e.key)>=0).map(e=>e.streamId).forEach(e=>{const n={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(n).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");const i={type:"post",subscription_id:t.id,data:n};this.session.sendFireAndForget(i).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const n={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),t.instance,this.callbacks.execute(ht,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const n=e.protocolState.subscriptionsMap;let i=Object.keys(n).map(e=>n[e]);"string"==typeof t&&(i=i.filter(e=>e.branchKey===t)),i.forEach(e=>{delete n[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let n=[];if(!e.protocolState.subscriptionsMap)return[];const i=e.protocolState.subscriptionsMap,r=Object.keys(i).map(e=>i[e]);return n="string"!=typeof t?r:r.filter(e=>e.branchKey===t),n}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,n=Object.keys(t).map(e=>t[e]),i=[];return n.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===i.indexOf(t)&&i.push(t)}),i}onSubAdded(e){this.onSubscriptionLifetimeEvent(dt,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(ct,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(ht,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const n=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(ht,n,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),n=t?.instance??{},i={msg:e,arguments:e.arguments_kv||{},instance:n},r=this.serverRepository.getById(e.method_id);if(void 0===r){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}r.protocolState.subscriptionsMap&&r.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(ct,i,r)}sendSubscriptionFailed(e,t){const n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:i})),i}}class lt{session;clientRepository;serverRepository;logger;callbacks=k();streaming;constructor(e,t,n,i){this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.streaming=new ut(e,t,n,i.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const n=e.definition,i=Object.assign({},{metadata:n.flags??{}},{streaming:t||!1}),r={type:"register",methods:[{id:e.repoId,name:n.name,display_name:n.displayName,description:n.description,version:n.version,flags:i,object_types:n.objectTypes||n.object_types,input_signature:n.accepts,result_signature:n.returns,restrictions:void 0}]};return this.session.send(r,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,n,i){let r;r=n||""===n?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:n,context:i,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:i,request_id:void 0},this.session.sendFireAndForget(r).catch(n=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(n)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,n){this.streaming.pushData(e,t,n)}pushDataToSingle(e,t,n){this.streaming.pushDataToSingle(e,t,n)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,n){this.streaming.acceptRequestOnBranch(e,t,n)}rejectRequest(e,t,n){this.streaming.rejectRequest(e,t,n)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,n=e.caller_id,i=e.method_id,r=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===i)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(n)?.instance,a={args:r,instance:s};this.callbacks.execute("onInvoked",o,t,a)}}class pt{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const n=this.repository.getServerById(t.serverId)?.instance;n&&e.push(n)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class gt{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=W(10);this.cache.push({id:t,element:e});const n=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(n)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}}const ft="awaitingAccept",mt="subscribed",yt="Subscription failed.",wt="ClientInitiated";class vt{session;repository;logger;subscriptionsList={};timedCache=new gt({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,n,i,r,o){if(0===n.length)return void r({method:e,called_with:t.arguments,message:yt+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,i,r,t.methodResponseTimeout||1e4,o);"object"==typeof a?n.forEach(n=>{const i=n.server.id,r=n.methods.find(t=>t.name===e.name);if(!r)return void this.logger.error(`can not find method ${e.name} for target ${n.server.id}`);a.trackedServers.push({serverId:i,subscriptionId:void 0});const o={type:"subscribe",server_id:i,method_id:r.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:i,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):r({method:e,called_with:t.arguments,message:yt+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,n,i,r,o,s){const a={localKey:e,status:ft,method:t,params:n,success:i,error:r,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(n.onData&&a.handlers.onData.push(n.onData),n.onClosed&&a.handlers.onClosed.push(n.onClosed),n.onConnected&&a.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const i=this.subscriptionsList[e];i.status===ft?(r({method:t,called_with:n.arguments,message:yt+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):i.status===mt&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter(e=>void 0!==e.subscriptionId),delete i.timeoutId,i.trackedServers.length<=0&&(this.callOnClosedHandlers(i),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,n=t.subLocalKey,i=this.subscriptionsList[n];if("object"==typeof i&&(i.trackedServers=i.trackedServers.filter(e=>e.serverId!==t.serverId),i.trackedServers.length<=0)){if(clearTimeout(i.timeoutId),i.status===ft){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",n="object"==typeof i.params.arguments?JSON.stringify(i.params.arguments):"{}";i.error({message:"Subscription rejected."+t+" Called with:"+n,called_with:i.params.arguments,method:i.method})}else i.status===mt&&this.callOnClosedHandlers(i);delete this.subscriptionsList[n]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=e._tag.serverId,r=n.trackedServers.filter(e=>e.serverId===i)[0];if("object"!=typeof r)return;r.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=n.status===ft;if(n.status=mt,o){let e=!1,t=n.subscription;t?(t.setNewSubscription(n),n.success(t),e=!0):(t=new pt(this.repository,n),n.subscription=t,n.success(t));for(const i of n.handlers.onConnected)try{i(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==i.length)return;const r=e.oob,o=i[0].serverId,s=this.repository.getServerById(o),a=()=>({data:e.data,server:s?.instance??{},requestArguments:n.params.arguments,message:void 0,private:r}),c=n.handlers.onData,d=n.queued.data;c.length>0?c.forEach(e=>{"function"==typeof e&&e(a())}):d.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(n.queued.closers.push(t.serverId),!1)),n.trackedServers.length===i&&(n.trackedServers.length<=0&&(this.timedCache.add(n),clearTimeout(n.timeoutId),this.callOnClosedHandlers(n),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const n=e.queued.closers.length,i=n>0?e.queued.closers[n-1]:null;let r;void 0!==i&&"string"==typeof i&&(r=this.repository.getServerById(i)?.instance??{}),e.handlers.onClosed.forEach(n=>{"function"==typeof n&&n({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:r,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:wt}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,wt),delete this.subscriptionsList[e])}}class bt{session;repository;logger;streaming;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new vt(e,t,n)}subscribe(e,t,n,i,r,o){this.streaming.subscribe(e,t,n,i,r,o)}invoke(e,t,n,i){const r=i.id,o={type:"call",server_id:r,method_id:t.gatewayId,arguments_kv:n};return this.session.send(o,{invocationId:e,serverId:r}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,n=e.identity,i=!e.meta||e.meta.local,r=Number(n.process),o={machine:n.machine,pid:isNaN(r)?n.process:r,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:t,api:n.api,isLocal:i};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,n=e.reason;this.repository.removeServerById(t,n)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,n=e.methods,i=this.repository.getServerById(t);if(i){Object.keys(i.methods).forEach(e=>{const r=i.methods[e];n.indexOf(r.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,n=e.result,i=e._tag.serverId,r=this.repository.getServerById(i);return{invocationId:t,result:n,instance:r?.instance,status:Qe.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,n=e._tag.serverId,i=this.repository.getServerById(n),r=e.reason;return{invocationId:t,result:e.context,instance:i?.instance,status:Qe.Error,message:r}}return{invocationId:"",message:e.message,status:Qe.Error,error:e}}}function _t(e,t,n,i,r,o){const s=r.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),d=t.domain("agm",["subscribed"]),h=new lt(d,n,i,s.subLogger("server")),u=new bt(d,n,s.subLogger("client"));return d.onJoined(r=>{n.addServer(e,t.peerId),r?async function(){s.info("reconnected - will replay registered methods and subscriptions"),u.drainSubscriptionsCache().forEach(e=>{const t=e.method,n=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),o.client.subscribe(t,n,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=u.drainSubscriptions();for(const n of t){const t=n.method,i=Object.assign({},n.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),e.push(o.client.subscribe(t,i,void 0,void 0,n).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const n=i.getList();i.reset();for(const t of n){const n=t.definition;t.stream?e.push(o.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${n.name} DONE`)).catch(()=>s.warn(`subscribing to method ${n.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(n,t.theFunction.userCallback).then(()=>s.info(`registering method ${n.name} DONE`)).catch(()=>s.warn(`registering method ${n.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(n,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${n.name} DONE`)).catch(()=>s.warn(`registering method ${n.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:u,server:h}),a=void 0)}),d.onLeft(()=>{n.reset()}),d.join(),c}class It{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let n;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new rt(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new st(e.logger.subLogger("cRep"),this),this.serverRepository=new at,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);n=_t(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then(t=>(this.protocol=t,this.client=new Ze(this.protocol,this.clientRepository,this.instance,e),this.server=new it(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,n,i){return this.client.subscribe(e,t,n,i)}createStream(e,t,n,i){return this.server.createStream(e,t,n,i)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,n,i,r,o){return this.client.invoke(e,t,n,i,r,o)}waitForMethod(e){const t=new M,n=this.client.methodAdded(i=>{i.name===e&&(n(),t.resolve(i))});return t.promise}}const Ct=["subscribed","success"];class At{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",Ct),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()})}ready(){return this.readyPromise}publish=(e,t,n)=>{const{routingKey:i,target:r}=n||{},o=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:i,target_identity:r});this.session.send(o).catch(t=>{this.logger.error(`Failed to publish message to topic ${e} with routing key ${i} for ${JSON.stringify(r)}: ${JSON.stringify(t)}`)})};subscribe=(e,t,n)=>new Promise((i,r)=>{const{routingKey:o,target:s}=n||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:o,source:s});this.session.send(a).then(n=>{const{subscription_id:r}=n;this.subscriptions.push({subscription_id:r,topic:e,callback:t,source:s}),i({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:r,peer_id:this.peerId}).then(()=>{this.subscriptions=this.subscriptions.filter(e=>e.subscription_id!==r)}).catch(e=>{this.logger.warn(`Failed to send unsubscribe request for ${r}: ${JSON.stringify(e)}`)}),Promise.resolve())})}).catch(e=>r(e))});watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:n}=e,i=e["publisher-identity"],r=this.subscriptions.find(e=>e.subscription_id===n);r&&(r.source?this.keysMatch(r.source,i)&&r.callback(t,r.topic,i):r.callback(t,r.topic,i))})};removeEmptyValues(e){const t={};return Object.keys(e).forEach(n=>{void 0!==e[n]&&null!==e[n]&&(t[n]=e[n])}),t}keysMatch(e,t){const n=Object.keys(e);let i=!0;return n.forEach(n=>{e[n]!==t[n]&&(i=!1)}),i}}const Tt=(e,t)=>{const n="object"==typeof window?window.iodesktop??window.glue42gd:void 0,i="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),r=N("glue"),o=function(e,t,n){let i;if(P.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{i=JSON.parse(e)}catch{}}function r(){if(e.application)return e.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=W(10);return P.isNode()?i?i.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let d=o?.ws;const h=o?.sharedWorker,u=o?.inproc,l=o?.webPlatform??void 0;let p,g,f,m,y;n&&(d=n.gwURL),P.isNode()&&i&&i.gwURL&&(d=i.gwURL),d||h||u||(d="ws://localhost:8385");const w=r();let v=w;void 0!==n?(g=n.windowId,f=n.pid,n.env&&(m=n.env.env,y=n.env.region),v=n.application??"glue-app",p=n.appInstanceId):P.isNode()?(f=process.pid,i&&(m=i.env,y=i.region,p=i.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,f=window?.glue42electron.pid,m=window?.glue42electron.env,y=window?.glue42electron.region,v=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const b=e.gateway?.replaySpecs??[];b.push(re);let _={application:v,applicationName:w,windowId:g,instance:p,process:f,region:y,environment:m,api:t.version||oe};return e.identity&&(_=Object.assign(_,e.identity)),{identity:_,reconnectInterval:a,ws:d,sharedWorker:h,webPlatform:l,inproc:u,protocolVersion:s,reconnectAttempts:c,replaySpecs:b}}();let s=r();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:P.isNode()&&i&&i.gwToken?{gatewayToken:i.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const i="warn";let r;return t||(t=i),n&&(r=n.consoleLogLevel),"string"==typeof t?{console:r??t,publish:i}:{console:r??t.console??i,publish:t.publish??i}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||oe,libs:t.libs??[],customLogger:e.customLogger}}(e=e||{},t=t||{},n);let s,a,c,d,h,u,l;const p={};function g(e,t,n){l=c.canPublish("trace"),l&&c.trace(`registering ${e} module`);const i=i=>{if(t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,!l)return;const r=i?`${e} failed - ${i.message}`:`${e} is ready - ${n.endTime-n.startTime}`;c.trace(r)};t.initStartTime=n.startTime,t.ready?t.ready().then(()=>{i()}).catch(e=>{const t="string"==typeof e?new Error(e):e;i(t)}):i(),Array.isArray(e)||(e=[e]),e.forEach(e=>{p[e]=t,Tt[e]=t})}function f(){const e=N("metrics"),t=o.metrics,i=n?.getMetricsPublishingEnabled,r=o.connection.identity,a=i||(()=>!0),h=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return d=C({connection:t?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:r?.service??n?.applicationName??o.application,instance:r?.instance??r?.windowId??W(10),disableAutoAppSystem:h,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",d,e),Promise.resolve()}function m(){const e=N("interop"),t={connection:s,logger:c.subLogger("interop")};return a=new It(t),B.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=o.activities&&3===s.protocolVersion;if(o.contexts||e){const e=N("contexts");h=new ye({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof o.contexts&&o.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof o.contexts&&o.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof o.contexts||o.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof o.contexts||o.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof o.contexts||o.contexts.onlyReAnnounceSubscribedContexts}),g("contexts",h,e)}else{const e=s.replayer;e&&e.drain(re.name)}return Promise.resolve()}async function w(){if(!o.bus)return Promise.resolve();const e=N("bus");return u=new At(s,c.subLogger("bus")),g("bus",u,e),Promise.resolve()}function v(e){try{return e.forEach(e=>{!function(e,t){const n=N(e),i=t(p);i&&g(e,i,n)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return i.then(function(){const e=N("logger");return c=new B(`${o.connection.identity?.application}`,void 0,o.customLogger),c.consoleLevel(o.logger.console),c.publishLevel(o.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)}).then(function(){const e=N("connection");s=new U(o.connection,c.subLogger("connection"));let t=Promise.resolve(o.auth);return o.connection&&!o.auth&&(n?t=n.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let n;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return n=t,s.login(n)}).then(()=>(g("connection",s,e),o)).catch(e=>{throw s&&s.logout(),e})}).then(()=>Promise.all([f(),m(),y(),w()])).then(()=>a.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(P.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>v(o.libs||[])).then(function(){const e=Object.keys(p).map(e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const i={coreVersion:oe,version:o.version};r.stop();const l={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:i,logger:c,interop:a,agm:a,connection:s,metrics:d,contexts:h,bus:u,version:o.version,userConfig:e,done:()=>(c?.info("done called by user..."),s.logout())};if(l.performance={get glueVer(){return o.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=R;return Object.keys(e).map(t=>{const n=e[t];return{name:t,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}})}},Object.keys(p).forEach(e=>{const t=p[e];l[e]=t}),l.config={},Object.keys(o).forEach(e=>{l.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{l.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(l),n&&n.updatePerfData&&n.updatePerfData(l.performance),l.agm){const e=(e,t,n)=>function(){return l.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${n}' instead.`),e.apply(l.agm,arguments)},t=l.agm;t.method_added=e(l.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(l.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(l.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(l.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(l.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return l}).catch(e=>Promise.reject({err:e,libs:p}))};"undefined"!=typeof window&&(window.IOConnectCore=Tt),Tt.version=oe,Tt.default=Tt;class St{constructor(e){this._id=e}get id(){return this._id}_update(e){if(e._id!==this._id)throw Error("Can not update from entity with different id.");this._updateCore(e)}_updateCore(e){}_beforeDelete(e){}}function kt(e){return"number"==typeof e}function xt(e){return"string"==typeof e}function Et(e){return"object"==typeof e&&!Array.isArray(e)&&null!==e}function Pt(e){return Array.isArray?Array.isArray(e):"[object Array]"===toString.call(e)}function Mt(e){return void 0===e}function Rt(e){return null==e}function Nt(e){return"string"!=typeof e||!e||0===e.length||/^\s*$/.test(e)}function Ot(e){return!0===e||!1===e||"[object Boolean]"===toString.call(e)}function jt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function $t(e,t){void 0!==e&&t(e)}class Wt extends St{constructor(e,t,n,i){super(e),this._name=e,this._description=i,this._ownerWindow=t,this._helperWindows=n||[]}get name(){return this._name}get description(){return this._description}get helperWindows(){return this._helperWindows.map(e=>this.covertToWindowDef(e))}get ownerWindow(){return this.covertToWindowDef(this._ownerWindow)}initiate(e,t,n){return this._manager.initiate(this._name,e,t,n)}_updateCore(e){super._updateCore(e),$t(e._description,e=>this._description=e),$t(e._ownerWindow,e=>this._ownerWindow=e),$t(e._helperWindows,e=>this._helperWindows=e)}covertToWindowDef(e){var t,n;return{type:null===(t=null==e?void 0:e.id)||void 0===t?void 0:t.type,name:null===(n=null==e?void 0:e.id)||void 0===n?void 0:n.name}}}class Dt extends St{constructor(e,t){super(e),this._name=e,this._appByWindowTypeGetter=t}get name(){return this._name}get config(){return this._appByWindowTypeGetter(this._name)}get windows(){return this._manager.getWindows({type:this._name})}create(e,t){const n=Object.assign({type:this.name,name:this.name,isIndependent:!1},t);return this._manager.createWindow(e,n)}}class Ft{constructor(e,t){this.entity=e,this.context=t}}class Lt{constructor(e){this.type=e}}class Gt extends Lt{constructor(e,t){super(Ht.StatusChange),this.newStatus=e,this.oldStatus=t}}class Ut extends Lt{constructor(e,t,n){super(Ht.ActivityContextChange),this.context="string"==typeof e?JSON.parse(e):e,this.updated=t,this.removed=n}}class Ht{}Ht.Added="added",Ht.Removed="removed",Ht.Updated="updated",Ht.Closed="closed",Ht.StatusChange="statusChange",Ht.ActivityContextChange="activityContextUpdate",Ht.ActivityWindowEvent="activityWindowEvent",Ht.ActivityWindowJoinedActivity="joined",Ht.ActivityWindowLeftActivity="left";class Bt{}Bt.Created="created",Bt.Started="started",Bt.Destroyed="destroyed";class Jt{constructor(e){this._activity=e}register(e,t){this._ensureHasAgm(),Jt.AGM.register(e,t)}servers(){return this._ensureHasAgm(),Rt(this._activity)?[]:this._activity.windows.map(e=>e.instance)}methods(){if(this._ensureHasAgm(),Rt(this._activity))return[];const e=this._activity.windows,t=[],n=[];return e.forEach(e=>{this.methodsForWindow(e).forEach(e=>{-1===t.indexOf(e.name)&&(t.push(e.name),n.push(e))})}),n}methodsForWindow(e){return this._ensureHasAgm(),e.instance?Jt.AGM.methodsForInstance(e.instance):[]}invoke(e,t,n,i,r,o){this._ensureHasAgm();const s=this.servers();if(Rt(n)&&(n="activity.all"),xt(n))if("activity.all"===n);else{if("activity.best"!==n){if("all"===n||"best"===n)return function(e,t,n){if("function"!=typeof t&&"function"!=typeof n)return e;"function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n)}(Jt.AGM.invoke(e,t,n,i),r,o);throw new Error("Invalid invoke target "+n)}{const t=s.filter(t=>Jt.AGM.methodsForInstance(t).filter(t=>t.name===e).length>0);t.length>0&&t[0]}}else if(Pt(n)){if(n.length>=0){const e=n[0];if(this._isInstance(e))n.map(e=>e);else{if(!this._isActivityWindow(e))throw new Error("Unknown target object");n.map(e=>e.instance)}}}else if(this._isInstance(n));else{if(!this._isActivityWindow(n))throw new Error("Unknown target object");n.instance}throw new Error("Not implemented")}unregister(e){return this._ensureHasAgm(),Jt.AGM.unregister(e)}createStream(e,t,n){this._ensureHasAgm(),Jt.AGM.createStream(e,{subscriptionAddedHandler:t,subscriptionRemovedHandler:n,subscriptionRequestHandler:void 0})}subscribe(e,t,n){return this._ensureHasAgm(),Jt.AGM.subscribe(e,t)}_ensureHasAgm(){if(Rt(Jt.AGM))throw new Error("Agm should be configured to be used in activity")}_isInstance(e){return void 0!==e.application}_isActivityWindow(e){return void 0!==e.instance}}class qt{constructor(e,t,n){this._manager=e,this._ownerActivityId=t,this._state=n}get ownerId(){return this._state.ownerId}get windowIds(){return this._state.windowIds}get frameColor(){return this._state.frameColor}get context(){return this._state.context}get tag(){return this._state.tag}detach(e){e=e||{};const t={};return Object.keys(this._state).forEach(e=>{t[e]=this._state[e]}),t.context=e.context||t.context,t.frameColor=e.frameColor||t.frameColor,this._manager.detachActivities(this._ownerActivityId,t)}}const Vt=e=>{setTimeout(e,0)};function zt(e,t){if(!jt(t))return e;e.then(e=>{Vt(()=>{t(null,e)})},e=>{Vt(()=>{t(e,null)})})}class Kt extends St{constructor(e,t,n,i,r){super(e),this._id=e,this._actType=t,this._status=n,this._context=i,this._ownerId=r,this._agm=new Jt(this)}get type(){if(this._manager)return this._manager.getActivityType(this._actType)}get context(){return this._context}get status(){return this._status}get owner(){return this._ownerId?this._manager.getWindows({id:this._ownerId})[0]:null}get windows(){return this._manager.getWindows({activityId:this._id})}get agm(){return this._agm}addWindow(e,t){return this._manager.addWindowToActivity(this,e,t)}createWindow(e,t){return this._manager.createWindow(this,e,t)}createStackedWindows(e,t,n){return this._manager.createStackedWindows(this,e,t,n)}leave(e,t){return this._manager.leaveWindowFromActivity(this,e,t)}getWindowsByType(e){const t={activityId:this._id,type:e};return this._manager.getWindows(t)}setContext(e,t){return this._manager.setActivityContext(this,e,t)}updateContext(e,t){return this._manager.updateActivityContext(this,e,t)}onStatusChange(e){return this._manager.subscribeActivityEvents((t,n,i)=>{t.id===this.id&&e(t,n,i)})}onWindowEvent(e){return this._manager.subscribeWindowEvents((t,n,i)=>{t.id===this.id&&e(t,n,i)})}onContextChanged(e){this._manager.subscribeActivityContextChanged((t,n,i,r)=>{t.id===this.id&&e(n,i,r,t)});try{e(this.context,this.context,[],this)}catch(e){return}}stop(){this._manager.stopActivity(this)}clone(e){return this._manager.clone(this,e)}attach(e,t){let n;return n="string"==typeof e?e:e.id,this._manager.attachActivities(n,this.id,t)}onActivityAttached(e){this._manager.subscribeActivitiesAttached((t,n,i)=>{t===this._id&&e(i)})}onDetached(e){this._manager.subscribeActivitiesDetached((t,n,i)=>{n.id===this._id&&e(t,i)})}_updateCore(e){super._updateCore(e),$t(e._actType,e=>this._actType=e),$t(e._context,e=>this._context=e),$t(e._ownerId,e=>this._ownerId=e),!e._status||this._status&&this._status.state===e._status.state||(this._status=e._status)}_updateDescriptors(e){this._attached=e.map(e=>new qt(this._manager,this._id,e))}get attached(){return this._attached}setFrameColor(e,t){return zt(new Promise((t,n)=>{let i=this.windows.length;0===i&&t(this),this.windows.forEach(n=>{n.underlyingWindow.setFrameColor(e,()=>{i--,i<=0&&t(this)})}),setTimeout(()=>{i>0&&n(this.id+" - timed out waiting for setFrameColor with"+e)},5e3)}),t)}getFrameColor(){return this.windows&&0!==this.windows.length?this.windows[0].underlyingWindow.frameColor:""}}class Qt{}Qt.Trace="trace",Qt.Debug="debug",Qt.Info="info",Qt.Warn="warn",Qt.Error="error";class Zt{static GetNamed(e){return new Zt(e)}static Get(e){return new Zt(Zt.GetTypeName(e))}constructor(e){this._name=e,Rt(Zt.GlueLogger)||(this._glueLogger=Zt.GlueLogger.subLogger(e))}trace(e){Rt(this._glueLogger)?Zt.Level===Qt.Trace&&console.info(this._getMessage(e,Qt.Trace)):this._glueLogger.trace(e)}debug(e){Rt(this._glueLogger)?Zt.Level!==Qt.Debug&&Zt.Level!==Qt.Trace||console.info(this._getMessage(e,Qt.Debug)):this._glueLogger.debug(e)}info(e){Rt(this._glueLogger)?Zt.Level!==Qt.Debug&&Zt.Level!==Qt.Trace&&Zt.Level!==Qt.Info||console.info(this._getMessage(e,Qt.Info)):this._glueLogger.info(e)}warn(e){Rt(this._glueLogger)?Zt.Level!==Qt.Debug&&Zt.Level!==Qt.Trace&&Zt.Level!==Qt.Info&&Zt.Level!==Qt.Warn||console.info(this._getMessage(e,Qt.Info)):this._glueLogger.warn(e)}error(e){Rt(this._glueLogger)?(console.error(this._getMessage(e,Qt.Error)),console.trace()):this._glueLogger.error(e)}_getMessage(e,t){return"["+t+"] "+this._name+" - "+e}static GetTypeName(e){const t=/function (.{1,})\(/.exec(e.constructor.toString());return t&&t.length>1?t[1]:""}}Zt.Level=Qt.Info;class Xt extends St{constructor(e,t,n,i,r,o,s,a){super(e),this._logger=Zt.Get("window"),this._type=n,this._activityId=i,this._name=t,this._instance=r,this._isIndependent=o,this._windowGetter=s,this._hcWindowId=a}getBounds(){return this._manager.getWindowBounds(this.id)}get name(){return this._name}get isIndependent(){return this._isIndependent}get type(){if(this._manager)return this._manager.getWindowType(this._type)}get activity(){if(!Mt(this._activityId))return this._manager.getActivityById(this._activityId)}get isOwner(){const e=this.activity;return!Mt(e)&&e.owner.id===this.id}setVisible(e,t){return this._manager.setWindowVisibility(this.id,e)}activate(e){return this._manager.activateWindow(this.id,e)}setBounds(e,t){return this._manager.setWindowBounds(this.id,e,t)}close(){return this._manager.closeWindow(this.id)}get instance(){return this._instance}get underlyingWindow(){const e=this._windowGetter();return e||{id:this._hcWindowId}}onActivityJoined(e){this._subscribeForActivityWindowEvent(Ht.ActivityWindowJoinedActivity,e)}onActivityRemoved(e){this._subscribeForActivityWindowEvent(Ht.ActivityWindowLeftActivity,e)}_updateCore(e){$t(e._activityId,e=>this._activityId=e),$t(e._isIndependent,e=>this._isIndependent=e),$t(e._hcWindowId,e=>this._hcWindowId=e),$t(e._type,e=>this._type=e),$t(e._name,e=>this._name=e),Rt(e._instance)||(this._instance=e._instance)}_subscribeForActivityWindowEvent(e,t){this._manager.subscribeWindowEvents((n,i,r)=>{i.id===this.id&&r===e&&t(n)})}_beforeDelete(e){this._hcWindowId=e._hcWindowId}}class Yt{constructor(e,t,n){this.state=e,this.message=t,this.time=n}getState(){return this.state}getMessage(){return this.message}getTime(){return this.time}}const en="error",tn="add-types",nn="created",rn="destroyed",on="initiated",sn="joined",an="activity-joined",cn="left",dn="owner-changed",hn="add-peer-factories",un="peer-factories-added",ln="peer-factories-removed",pn="peer-created";class gn{static activityTypeGwMessageEntityToActivityType(e,t){const n=e=>new Dt(e,void 0);return new Wt(e.name,e.owner_type&&n(e.owner_type),e.helper_types&&e.helper_types.map(n),t)}static peerFactoryGwMessageEntityToWindowType(e){return new Dt(e.peer_type,e=>{})}static activityGwMessageToActivity(e,t){const n=void 0!==e.owner?e.owner.peer_id:e.owner_id;return new Kt(e.activity_id,e.activity_type,t,e.context_snapshot,n)}static activityToActivityStatusChangeEvent(e){return new Ft(e,new Gt(e.status,void 0))}constructor(e){if(this._activityChangeCallbacks=[],this._activityTypeStatusChangeCallbacks=[],this._activityWindowChangeCallbacks=[],this._windowTypeStatusChangeCallbacks=[],this._peerIdAndFactoryIdToPeerType={},this._peerFactoriesRegisteredByUs={},this._gw3Subscriptions=[],this._contextSubscriptions={},this._activityTypesInitiatedFromMe={},this._config=e,this._connection=e.connection,this._logger=e.logger,this._contexts=e.contexts,this._windows=e.windows,this._sessionJoinedPromise=new Promise(e=>{this._sessionJoinedPromiseResolve=e}),this._activityJoinedPromise=new Promise(e=>{this._activityJoinedPromiseResolve=e}),this._config.activityId||this._activityJoinedPromiseResolve({}),this._gw3Session=this._connection.domain("activity",["joined","initiated","peer-created","token"]),"undefined"!=typeof window){const e=window.glue42gd;e&&e.activityInfo&&("function"==typeof e.addRefreshHandler&&e.addRefreshHandler((t,n)=>{this._gw3Session.send({type:"reload"}).then(i=>{if(i.token){try{e.setGWToken(i.token)}catch(e){return void n(e.message||e)}t()}else n("Expected gateway token for refreshing.")},n)}),e&&"function"==typeof e.addWillNavigateHandler&&e.addWillNavigateHandler((t,n)=>{this._gw3Session.send({type:"reload"}).then(i=>{if(i.token){try{e.setGWToken(i.token)}catch(e){return void n(e.message||e)}t()}else n("Expected gateway token for refreshing.")},n)}))}}get bridgeType(){return"GW3"}init(){this.forwardActivityTypeMessagesToStatusEventHandlers(),this.subscribe(nn,this.handleActivityCreatedMessage),this.subscribe(rn,this.handleActivityDestroyedMessage),this.forwardActivityMessagesToStatusEventHandlers(),this.forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(),this.forwardPeerFactoryMessagesToStatusEventHandlers(),this.forwardPeerFactoryMessagesToPeerFactoryRequests(),this.subscribe(un,this.handlePeerFactoriesAdded),this.subscribe(ln,this.handlePeerFactoriesRemoved),this.forwardActivityWindowMessagesToEventHandlers(),this.subscribe("dispose-peer",()=>{if("dispose"!==this._config.disposeRequestHandling){if("exit"===this._config.disposeRequestHandling){if(this._windows&&void 0!==this._windows.my())return void this._windows.my().close();if("undefined"!=typeof window&&"function"==typeof window.close)return void window.close();if("undefined"!=typeof process&&"function"==typeof process.exit)return void process.exit()}}else this.dispose()}),this._gw3Session.onJoined(()=>{"trackMyOnly"===this._config.mode||"trackMyTypeAndInitiatedFromMe"===this._config.mode?this._sessionJoinedPromiseResolve(this):this._gw3Session.send({type:"subscribe",activity_types:"trackAll"===this._config.mode?[]:"trackTypes"===this._config.mode?this._config.typesToTrack:[]}).then(()=>{this._sessionJoinedPromiseResolve(this)})}),this._gw3Session.join()}dispose(){this._gw3Subscriptions.forEach(e=>e&&this._connection.off(e)),this._gw3Subscriptions.length=0}ready(){return Promise.all([this._sessionJoinedPromise,this._activityJoinedPromise])}initReady(){return this._sessionJoinedPromise}onActivityTypeStatusChange(e){this._activityTypeStatusChangeCallbacks.push(e)}registerActivityType(e,t,n,i,r){const o={};o.name=e;const s=e=>({type:e.type,name:e.name,configuration:e});return o.owner_type=s(t),o.helper_types=n.map(s),this._gw3Session.send({type:tn,types:[o]}).then(()=>{const e=gn.activityTypeGwMessageEntityToActivityType(o,r);return this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new Ft(e,new Lt(Ht.Added)),tn),e})}unregisterActivityType(e){return this._gw3Session.send({type:"remove-types",types:[e]}).then(()=>{const t=new Wt(e,void 0,void 0,void 0);this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new Ft(t,new Lt(Ht.Removed)),tn)})}onWindowTypeStatusChange(e){this._windowTypeStatusChangeCallbacks.push(e)}registerWindowFactory(e,t,n){if(this._peerFactoriesRegisteredByUs[e])return Promise.reject(new Error(`Factory for windowType ${e} already registered.`));this._peerFactoriesRegisteredByUs[e]=t;const i={id:e,peer_type:e,configuration:n};return this._gw3Session.send({type:hn,factories:[i]}).then(()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new Ft(gn.peerFactoryGwMessageEntityToWindowType(i),new Lt(Ht.Added)),hn)}).catch(()=>{delete this._peerFactoriesRegisteredByUs[e]})}unregisterWindowFactory(e){return this._peerFactoriesRegisteredByUs[e]?(delete this._peerFactoriesRegisteredByUs[e],this._gw3Session.send({type:"remove-peer-factories",factory_ids:[e]}).then(()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new Ft(new Dt(e,void 0),new Lt(Ht.Removed)),hn)})):Promise.reject(new Error(`Factory for windowType ${e} not registered.`))}onActivityStatusChange(e){this._activityChangeCallbacks.push(e)}initiateActivity(e,t,n){const i={type:"create",activity_type:e,initial_context:t};return this.isOverrideTypeDefinition(n)?i.types_override={owner_type:{type:n.owner.type,name:n.owner.name,configuration:n.owner},helper_types:n.helpers&&n.helpers.map(e=>({type:e.type,name:e.name,configuration:e}))}:i.configuration=n&&n.map(e=>({type:e.type,name:e.name,configuration:e})),this.sendCreateAndMapResultingMessagesToPromise(i,on,(e,t)=>e.request_id===t,nn,(e,t,n)=>e.activity_id===n.activity_id,rn,(e,t,n)=>e.activity_id===n.activity_id,e=>e.activity_id,null).then(t=>"trackMyTypeAndInitiatedFromMe"!==this._config.mode||this._activityTypesInitiatedFromMe[e]?t:(this._activityTypesInitiatedFromMe[e]=!0,this._gw3Session.send({type:"subscribe",activity_types:[e]}).then(()=>t)))}stopActivity(e){return this._gw3Session.send({type:"destroy",activity_id:e.id,reason_uri:"com.tick42.glue.activity.constants.destroyReason.general",reason:"Destroying activity"}).then(e=>!0)}updateActivityContext(e,t,n,i){if(n)return this._contexts.set(e.id,t);i=i||[];for(const e of i)t[e]=null;return this._contexts.update(e.id,t)}announceWindow(e,t){throw new Error("Invalid operation 'announceWindow' for GW3 protocol")}registerWindow(e,t,n){let i=void 0!==this._connection.gatewayToken;const r=this._connection.peerId;if("undefined"!=typeof window){const e=window.glue42gd;e&&(i=void 0!==e.activityInfo)}return i&&this._gw3Session.send({type:"ready"}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new Ft(new Xt(r,t,e,void 0,this.getAgmInstance(r),n,this.generateWindowGetter(r),void 0),new Lt(Ht.Added)),"register window"),Promise.resolve(r)}onActivityWindowChange(e){this._activityWindowChangeCallbacks.push(e)}createWindow(e,t){t.layout||(t.left||t.width||t.height||t.top)&&(t.layout={mode:"pixels",cellSize:1});const n=n=>{if(e)return this.joinActivity(e,n,t.name).then(()=>n)};return this.sendCreateAndMapResultingMessagesToPromise({type:"create-peer",peer_type:t.type,peer_name:t.name||t.type,configuration:t,activity_id:e},void 0,void 0,pn,(e,t)=>e.request_id===t,void 0,void 0,e=>e.created_id,n).then(n)}async closeWindow(e){await this._gw3Session.send({type:"destroy-peer",destroy_peer_id:e})}getAnnouncementInfo(){let e=this._config.activityId||this._config.announcementInfo&&this._config.announcementInfo.activityId,t=this._config.announcementInfo&&this._config.announcementInfo.activityWindowType,n=this._config.announcementInfo&&this._config.announcementInfo.activityWindowIndependent,i=this._config.announcementInfo&&this._config.announcementInfo.activityWindowName;if("undefined"!=typeof window&&void 0!==window.location&&window.location.search&&"function"==typeof URLSearchParams){const r=new URLSearchParams(location.search.slice(1));t=t||r.get("t42PeerType"),t=t||r.get("t42ActivityWindowType"),void 0===n&&(n=r.get("t42ActivityWindowIndependent")),i=i||r.get("t42ActivityWindowName"),e=e||r.get("t42ActivityId")}return t=t||"unknown",n=n||!1,i=i||this._connection.peerId,{activityWindowId:void 0,activityId:e,activityWindowType:t,activityWindowIndependent:n,activityWindowName:i}}joinActivity(e,t,n){const i=n&&{name:n}||{};return this._gw3Session.send({type:"join-activity",target_id:t,activity_id:e,...i}).then(()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new Ft(new Xt(t,void 0,void 0,e,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new Lt(Ht.ActivityWindowJoinedActivity)),"activity joined - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new Ft(new Kt(e,void 0,new Yt("created",void 0,void 0),void 0,void 0),new Lt(Ht.Updated)),"activity joined - Activity")})}leaveActivity(e,t){return this._gw3Session.send({type:"leave-activity",target_id:t,activity_id:e}).then(()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new Ft(new Xt(t,void 0,void 0,null,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new Lt(Ht.ActivityWindowLeftActivity)),"activity left - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new Ft(new Kt(e,void 0,new Yt("created",void 0,void 0),void 0,void 0),new Lt(Ht.Updated)),"activity left - Activity")})}getActivityTypes(){return Promise.resolve([])}getWindowTypes(){return Promise.resolve([])}getActivities(){return Promise.resolve([])}getActivityWindows(){return Promise.resolve([])}createStackedWindows(e,t,n){}getWindowBounds(e){}setWindowBounds(e,t){}activateWindow(e,t){}setWindowVisibility(e,t){}cloneActivity(e,t){}attachActivities(e,t,n){return this._gw3Session.send({type:"merge",into:t,merge:e})}detachActivities(e,t){return this._gw3Session.send({type:"split",from:e}).then(()=>"")}onActivitiesAttached(e){}onActivitiesDetached(e){}onActivityAttachedDescriptorsRefreshed(e){}getAttachedDescriptors(){return Promise.resolve([])}getRandomRequestId(){return this._connection.peerId+":"+Math.floor(1e9*Math.random())}forwardAddedAndRemovedMessagesToEventHandler(e,t,n,i){const r=e=>t=>new Ft(t,new Lt(e?Ht.Added:Ht.Removed));return[e&&this.forwardMessageToEventHandler(e,e=>n(e,!0),r(!0),i),t&&this.forwardMessageToEventHandler(t,e=>n(e,!1),r(!1),i)].filter(e=>e)}forwardMessageToEventHandler(e,t,n,i){return this.subscribe(e,e=>{t(e).forEach(t=>i.forEach(i=>i(n(t,e))))})}sendCreateAndMapResultingMessagesToPromise(e,t,n,i,r,o,s,a,c){const d=this.getRandomRequestId();let h,u;const l=new Promise((e,t)=>{h=e,u=t});let p,g,f,m,y=null;const w=()=>{this.dropSubscription(p),c||this.dropSubscription(g),this.dropSubscription(f),this.dropSubscription(m)};p=t&&this.subscribe(t,e=>{n(e,d)&&(y=e,this.dropSubscription(p))});let v=!1;g=this.subscribe(i,e=>{r(e,d,y)&&(v?c&&c(a(e)):(v=!0,h(a(e))))}),f=o&&this.subscribe(o,e=>{s(e,d,y)&&u(e)}),m=o&&this.subscribe(en,e=>{e.request_id===d&&u(e)}),e.request_id=d;const b=this._gw3Session.send(e).then(()=>l);return b.then(w,w),b}peerFactoryIdAndOwnerIdToWindowType(e,t){const n=this._peerIdAndFactoryIdToPeerType[t+":"+e];return n?new Dt(n,void 0):null}subscribe(e,t){const n=this._connection.on(e,e=>t.bind(this)(e));return this._gw3Subscriptions.push(n),n}dropSubscription(e){e&&(this._connection.off(e),delete this._gw3Subscriptions[this._gw3Subscriptions.indexOf(e)])}invokeCallbacks(e,t,n){e.forEach(e=>{try{e(t)}catch(e){this._logger.error(`Error in ${n||t.context.type} callback: `+JSON.stringify(e))}})}handleActivityCreatedMessage(e){e.context_id?this._contextSubscriptions[e.activity_id]||this.subscribeToContext(e):this._logger.error("Activity created with unknown context_id: "+e.activity_id)}async subscribeToContext(e){const t=e.activity_id;this._contextSubscriptions[t]=await this._contexts.subscribe(t,(e,n,i)=>{const r=new Ft(new Kt(t,void 0,void 0,e,void 0),new Ut(e,n,i));this.invokeCallbacks(this._activityChangeCallbacks,r,"context updated")})}handleActivityDestroyedMessage(e){const t=this._contextSubscriptions[e.activity_id];"function"==typeof t&&t(),delete this._contextSubscriptions[e.activity_id]}handlePeerFactoriesAdded(e){e.factories.forEach(t=>{this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t.id]=t.peer_type})}handlePeerFactoriesRemoved(e){e.factory_ids.forEach(t=>{delete this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t]})}forwardActivityTypeMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler("types-added","types-removed",(e,t)=>t?e.types.map(e=>gn.activityTypeGwMessageEntityToActivityType(e,void 0)):e.types.map(e=>new Wt(e.name,void 0,void 0,void 0)),this._activityTypeStatusChangeCallbacks)}forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(){for(const e of[nn,sn,dn])this.forwardMessageToEventHandler(e,e=>[e.owner||{...e,type:e.peer_type,name:e.peer_name,peer_id:e.owner_id}].concat(e.participants||[]).map(t=>new Xt(t.peer_id,t.name,t.type,e.activity_id,this.getAgmInstance(t.peer_id),void 0,this.generateWindowGetter(t.peer_id),void 0)),(e,t)=>new Ft(e,new Lt(Ht.ActivityWindowJoinedActivity)),this._activityWindowChangeCallbacks)}forwardActivityMessagesToStatusEventHandlers(){for(const e of[nn,sn])this.forwardMessageToEventHandler(e,e=>[gn.activityGwMessageToActivity(e,new Yt("started","",new Date))],(e,t)=>gn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks);this.forwardMessageToEventHandler(rn,e=>[gn.activityGwMessageToActivity(e,new Yt("destroyed",e.reason,new Date))],(e,t)=>gn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks),this.forwardMessageToEventHandler(on,e=>[gn.activityGwMessageToActivity(e,new Yt("created","",new Date))],(e,t)=>gn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks),this.forwardMessageToEventHandler(dn,e=>[gn.activityGwMessageToActivity(e,new Yt("created","",new Date))],(e,t)=>gn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks)}forwardPeerFactoryMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler(un,ln,(e,t)=>t?e.factories.map(gn.peerFactoryGwMessageEntityToWindowType):e.factory_ids.map(t=>this.peerFactoryIdAndOwnerIdToWindowType(t,e.owner_id)).filter(e=>null!=e),this._windowTypeStatusChangeCallbacks)}forwardPeerFactoryMessagesToPeerFactoryRequests(){this.subscribe("peer-requested",e=>{const t=this._peerFactoriesRegisteredByUs[e.peer_factory];if(t)try{const n=e.configuration||{};n.gateway_token=n.gateway_token||e.gateway_token,n.peer_factory=n.peer_factory||e.peer_factory;const i=t({activityId:e.activity&&e.activity.id,activityType:e.activity&&e.activity.type,type:e.configuration&&e.configuration.type,gwToken:n.gateway_token,configuration:n});i&&i.then&&i.catch&&i.catch(t=>this._gw3Session.send({type:en,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))}))}catch(t){this._gw3Session.send({type:en,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))})}else this._gw3Session.send({type:en,request_id:e.request_id,reason:`Unknown peer factory ${e.peer_factory}`})})}forwardActivityWindowMessagesToEventHandlers(){for(const e of[an,sn])this.subscribe(e,t=>{const n=e===an?t.joined_id:t.peer_id,i=e===an?t.joined_type:t.peer_type,r=e===an?t.joined_name:t.peer_name,o=new Xt(n,r,i,t.activity_id,this.getAgmInstance(n),void 0,this.generateWindowGetter(n),void 0);this._contextSubscriptions[t.activity_id]?e===sn&&this._activityJoinedPromiseResolve({}):this.subscribeToContext(t).then(()=>{e===sn&&this._activityJoinedPromiseResolve({})}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new Ft(o,new Lt(Ht.ActivityWindowJoinedActivity)),e)});this.subscribe(cn,e=>{const t=new Xt(e.left_id,void 0,void 0,null,this.getAgmInstance(e.left_id),void 0,this.generateWindowGetter(e.left_id),void 0);this.invokeCallbacks(this._activityWindowChangeCallbacks,new Ft(t,new Lt(Ht.ActivityWindowLeftActivity)),cn)}),this.forwardAddedAndRemovedMessagesToEventHandler(pn,void 0,e=>[new Xt(e.created_id,void 0,void 0,void 0,void 0,void 0,this.generateWindowGetter(e.created_id),void 0)],this._activityWindowChangeCallbacks)}getAgmInstance(e){return this._config.agm.servers().find(t=>t.peerId===e||t.windowId===e)}generateWindowGetter(e){return()=>{const t=this.getAgmInstance(e);if(!t)return;const n=t.windowId;return this._config.windows.list().filter(e=>e.id===n)[0]}}isOverrideTypeDefinition(e){return void 0!==e&&!!e.owner}}class fn{constructor(e,t){this._myAttached=[],this._myDetached=[],this._myAttachedTo=[],this._myDetachedFrom=[],this._myActivityFrameColorChanged=[],this._myActivityJoinedCallbacks=[],this._myActivityRemovedCallbacks=[],this._myContextUpdateCallbacks=[],this._logger=Zt.Get(this),this._m=e,e.ready().then(e=>{e.subscribeActivityContextChanged(this._subscribeMyContextChanged.bind(this)),e.subscribeWindowEvents(this._subscribeMyWindowEvent.bind(this)),e.subscribeActivitiesAttached(this._subscribeActivitiesAttached.bind(this)),e.subscribeActivitiesDetached(this._subscribeActivitiesDetached.bind(this)),t&&t.onWindowFrameColorChanged(this._subscribeWindowFrameColorChanged.bind(this))})}get window(){if(Rt(this._w)){const e=this._m.announcedWindows;e.length>0&&(this._w=e[0])}return this._w}get activity(){const e=this.window;if(!Rt(e))return e.activity}createWindow(e){return this._m.createWindow(this.activity,e)}createStackedWindows(e,t){return this._m.createStackedWindows(this.activity,e,t)}get context(){const e=this.activity;return Mt(e)?{}:e.context}updateContext(e,t){const n=this.activity;return Mt(n)?new Promise((e,t)=>{t("Not in activity")}):n.updateContext(e,t)}setContext(e,t){const n=this.activity;return Mt(n)?new Promise((e,t)=>{t("Not in activity")}):n.setContext(e,t)}onActivityJoined(e){this._myActivityJoinedCallbacks.push(e);const t=this.window;Rt(t)||Rt(t.activity)||e(t.activity)}onActivityLeft(e){this._myActivityRemovedCallbacks.push(e)}onContextChanged(e){this._myContextUpdateCallbacks.push(e);const t=this.window;if(Rt(t))return;const n=t.activity;Rt(n)||e(n.context,n.context,[],n)}clone(e,t){const n=this.activity;return this._m.clone(n,e,t)}attach(e,t){let n;return n="string"==typeof e?e:e.id,this._m.attachActivities(n,this.activity.id,t)}onActivityAttached(e){this._myAttached.push(e)}onActivityDetached(e){this._myDetached.push(e)}onAttachedToActivity(e){this._myAttachedTo.push(e)}onDetachedFromActivity(e){this._myDetachedFrom.push(e)}get attached(){return this.activity?this.activity.attached:[]}setFrameColor(e,t){return this.activity?this.activity.setFrameColor(e,t):Promise.resolve(null)}getFrameColor(){return this.activity?this.activity.getFrameColor():""}onFrameColorChanged(e){this._myActivityFrameColorChanged.push(e)}_subscribeMyContextChanged(e,t,n,i){const r=this.window;if(Rt(r))return;const o=r.activity;Rt(o)||e.id===o.id&&this._notifyMyContextChanged(e,t,n,i)}_subscribeMyWindowEvent(e,t,n){Rt(this.window)||this.window.id===t.id&&(n===Ht.ActivityWindowJoinedActivity?(this._notifyMyWindowEvent(e,this._myActivityJoinedCallbacks),this._notifyMyContextChanged(e,e.context,null,null)):n===Ht.ActivityWindowLeftActivity&&this._notifyMyWindowEvent(e,this._myActivityRemovedCallbacks))}_notifyMyWindowEvent(e,t){t.forEach(t=>{try{t(e,event)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyMyContextChanged(e,t,n,i){n=n||{},i=i||[],this._myContextUpdateCallbacks.forEach(r=>{try{r(t,n,i,e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyAttached(e){this._myAttached.forEach(t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyDetached(e){this._myDetached.forEach(t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyAttachedTo(e){this._myAttachedTo.forEach(t=>{try{t(this.activity,e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyDetachedFrom(e,t,n){this._myDetachedFrom.forEach(i=>{try{i(e,t,n)}catch(e){this._logger.warn("error in user callback "+e)}})}_subscribeActivitiesAttached(e,t){const n=this.window;if(Rt(n))return;const i=n.activity;Rt(i)||e.id===i.id&&(t.windowIds.indexOf(n.id)>=0?this._notifyAttachedTo(t):this._notifyAttached(t))}_subscribeActivitiesDetached(e,t,n){const i=this.window;if(Rt(i))return;const r=i.activity;Rt(r)||(t.id===r.id&&this._notifyDetached(n),e.id===r.id&&this._notifyDetachedFrom(e,t,n))}_subscribeWindowFrameColorChanged(e){const t=this.activity;t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._myActivityFrameColorChanged.forEach(t=>{t(e.frameColor)})}}class mn{constructor(e,t){if(this._logger=Zt.Get("ReadyMarker ["+e+"]"),this._logger.debug("Initializing ready marker for '"+e+"' with "+t+" signals to wait"),t<=0)throw new Error("Invalid signal number. Should be > 0");this._signals=t,this._callbacks=[],this._name=e}setCallback(e){this.isSet()?e(void 0):this.isError()?e(this._error):this._callbacks.push(e)}signal(e){if(this._logger.debug("Signaled - "+e+" - signals left "+(this._signals-1)),this._signals--,this._signals<0)throw new Error("Error in ready marker '"+this._name+" - signals are "+this._signals);this.isSet()&&this._callbacks.forEach(e=>{e(void 0)})}error(e){this._error=e,this._callbacks.forEach(t=>{t(e)})}isSet(){return!this.isError()&&0===this._signals}isError(){return!Mt(this._error)}getError(){return this._error}}class yn{constructor(e){this._items={},this._listeners=[],this._processNew=e}addOne(e){this.add([e])}add(e){e.forEach(e=>{this.process(new Ft(e,new Lt(Ht.Added)))})}process(e){const t=e.context,n=t.type,i=e.entity;if(n===Ht.StatusChange&&!t.oldStatus){const e=this._items[i.id];e&&(t.oldStatus=e.status)}n===Ht.StatusChange&&t.oldStatus&&t.newStatus&&t.oldStatus.state===t.newStatus.state&&(t.type=Ht.Updated),"undefined"==typeof htmlContainer&&(n===Ht.ActivityWindowJoinedActivity&&this._items[i.id]&&this._items[i.id].activity&&(t.type=Ht.Updated),n===Ht.ActivityWindowLeftActivity&&this._items[i.id]&&!this._items[i.id].activity&&(t.type=Ht.Updated));const r=this._updateInternalCollections(i,n,t);return this._notifyListeners(r,t),r}get(){const e=[];for(const t in this._items)if(this._items.hasOwnProperty(t)){const n=this._items[t];e.push(n)}return e}getByName(e){for(const t in this._items)if(t===e)return this._items[t]}getOrWait(e){return new Promise(t=>{const n=i=>{i.id===e&&(t(i),this.unsubscribe(n))};this.subscribe(n);const i=this.getByName(e);if(i)return this.unsubscribe(n),void t(i)})}subscribe(e){return this._listeners.push(e),Object.keys(this._items).forEach(t=>{const n=this._items[t];e(n,new Lt(Ht.Added.toString()))}),()=>{this.unsubscribe(e)}}unsubscribe(e){const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}_notifyListeners(e,t){this._listeners.forEach(n=>{try{n(e,t)}catch(e){return}})}_updateInternalCollections(e,t,n){const i=e,r=t===Ht.StatusChange&&i.status&&i.status.state===Bt.Destroyed||t===Ht.StatusChange&&n&&n.newStatus&&n.newStatus.state===Bt.Destroyed,o=t===Ht.Closed;if(t===Ht.Removed&&void 0===i.isIndependent||o||r){const t=this._items[e.id];return delete this._items[e.id],this._processNew(e),t&&e._beforeDelete(t),e}{const t=e.id;this._items.hasOwnProperty(t)?this._items[e.id]._update(e):(this._processNew(e),this._items[e.id]=e)}return this._items[e.id]}}class wn{get usingHc(){return"HC"===this._bridge.bridgeType}get announcedWindows(){return this._announcedWindows}set announcedWindows(e){throw new Error("not allowed")}constructor(e,t,n){this._logger=Zt.Get("activityManager"),this._announcedWindows=[],this._attachedCallbacks=[],this._detachedCallbacks=[],this._frameColorChangesCallbacks=[],this._windowHandlers=[],this._bridge=e,this._activityTypes=new yn(e=>this._grabEntity(e)),this._windowTypes=new yn(e=>this._grabEntity(e)),this._activities=new yn(e=>this._grabEntity(e)),this._windows=new yn(e=>this._grabEntity(e)),this._dataReadyMarker=new mn("Activity Manager Data",4),this._descriptorsMarker=new mn("Attached Activities Descriptors",1),t?(this._readyMarker=new mn("Activity Manager Announce",1),this._dataReadyMarker.setCallback(e=>{e&&this._readyMarker.error(e),this._descriptorsMarker.setCallback(e=>{e&&this._readyMarker.error(e),this._logger.debug("Auto announcing window"),this.announceWindow().then(e=>{this._announcedWindows.push(e),this._readyMarker.signal("Successfully announced window with id '"+e.id+"'")}).catch(e=>{this._logger.debug("Will not announce window - "+e),this._readyMarker.signal()})}),this.refreshDescriptors()})):this._readyMarker=this._dataReadyMarker,this._bridge.onActivitiesAttached(e=>{this._handleActivitiesAttached(e)}),this._bridge.onActivitiesDetached(e=>{this._handleActivitiesDetached(e)}),this._bridge.onActivityAttachedDescriptorsRefreshed(e=>{this._handleActivityDescriptorsRefreshed(e)}),n&&n.onWindowFrameColorChanged(this._handleWindowFrameColorChanged.bind(this)),this._bridge.init(),this._subscribeForData(),this._bridge.initReady().then(e=>{this._getInitialData()}).catch(e=>{console.log(e)})}ready(e){const t=new Promise((e,t)=>{this._readyMarker.setCallback(n=>{n?t(this._readyMarker.getError()):e(this)})});return zt(Promise.all([this._bridge.ready(),t]).then(()=>this),e)}getActivityTypes(){return this._activityTypes.get()}getActivityType(e){return this._activityTypes.getByName(e)}registerActivityType(e,t,n,i,r,o){return zt(new Promise((o,s)=>{if(Rt(e))return void s("activityTypeName argument can not be undefined");if(!xt(e))return void s("activityTypeName should be string");if(!Rt(this.getActivityType(e)))return void s("Activity type '"+e+"' already exists");let a;if(Mt(t))return void s("Owner window type can not be undefined");a=xt(t)?{type:t,name:"",isIndependent:!1,arguments:{}}:t;const c=[];if(!Mt(n)&&Pt(n))for(const e in n){const t=n[e];if(xt(t)){const e={type:t,name:"",isIndependent:!1,arguments:{},relativeTo:"",relativeDirection:"",windowStyleAttributes:{}};c.push(e)}else c.push(t)}this._bridge.registerActivityType(e,a,c,i,r).then(e=>{this._grabEntity(e),o(e)}).catch(e=>{s(e)})}),o)}unregisterActivityType(e,t){return zt(new Promise((t,n)=>{const i=this.getActivityType(e);Mt(i)?n("Activity type '"+e+"' does not exists"):this._bridge.unregisterActivityType(e).then(()=>t(i),n)}),t)}initiate(e,t,n,i){const r=new Promise((n,r)=>{Mt(this.getActivityType(e))?r("Activity type '"+e+"' does not exists"):this._bridge.initiateActivity(e,t,i).then(e=>{this._activities.getOrWait(e).then(e=>{n(e)}).catch(e=>r(e))}).catch(e=>{r(e)})});return zt(r,n)}subscribeActivityTypeEvents(e){this._activityTypes.subscribe((t,n)=>{e(t,n.type)})}getWindowTypes(){return this._windowTypes.get()}getWindowType(e){return this._windowTypes.getByName(e)}registerWindowFactory(e,t,n){const i=new Promise((n,i)=>{if(Rt(e))i("no windowType specified");else{if(Et(e))e=e.getName();else if(!xt(e))return void i("windowType should be string or object that has getName method");this._bridge.registerWindowFactory(e,t).then(e=>{n(e)}).catch(e=>{i(e)})}});return zt(i,n)}unregisterWindowFactory(e,t){const n=new Promise((t,n)=>{Rt(e)?n("no windowType specified"):xt(e)?this._bridge.unregisterWindowFactory(e).then(e=>{t(e)}).catch(e=>{n(e)}):n("windowType should be a string")});return zt(n,t)}getActivities(e){let t=this._activities.get();if(t=t.filter(e=>e._ownerId),!e)return t;let n=e;if(xt(e))n=[e];else if(e instanceof Wt)n=[e.name];else if(!(e instanceof Array))throw new Error("Invalid input argument 'activityType' = "+e);return t.filter(e=>{const t=e.type;return function(e,t){for(let n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1}(n,e=>t.id===e.id)})}getActivityById(e){return this._activities.getByName(e)}announceWindow(e,t){const n=new Promise((n,i)=>{const r=this._bridge.getAnnouncementInfo();if(Mt(e)&&(e=r.activityWindowId),Mt(t)&&(t=r.activityWindowType),Rt(t))throw new Error("Can not announce - unknown windowType");const o=r&&r.activityId;if(Rt(e))this._logger.debug("Registering window with type:'"+t+"', name:'"+r.activityWindowName+"', ind.:'"+r.activityWindowIndependent+"'"),this._bridge.registerWindow(t,r.activityWindowName,r.activityWindowIndependent).then(this._windows.getOrWait.bind(this._windows)).then(e=>o?this._activities.getOrWait(o).then(t=>e):e).then(e=>{n(e)}).catch(e=>{this._logger.error(e)});else{this._logger.debug("Announcing window with id '"+e+"' and type '"+t+"'");const r=this._windows.getByName(e);if(!Rt(r))return this._logger.debug("Window with id '"+e+"' already announced - reusing the window"),void n(r);const o=(t,r,s)=>{if(e===r.id&&s===Ht.ActivityWindowJoinedActivity){Mt(r.activity)&&i("UNDEFINED ACTIVITY"),this._logger.trace("Got joined event for id '"+e+"'"),n(r),this.unsubscribeWindowEvents(o)}};this.subscribeWindowEvents(o),this._logger.trace("Waiting for joined event for id '"+e+"'"),this._bridge.announceWindow(t,e)}});return n}subscribeWindowTypeEvents(e){this._windowTypes.subscribe((t,n)=>{e(t,n.type)})}subscribeActivityEvents(e){return this._activities.subscribe((t,n)=>{if(n.type===Ht.StatusChange){const i=n;e(t,i.newStatus,i.oldStatus)}if(n.type===Ht.Removed||n.type===Ht.StatusChange&&n.newStatus.getState()===Bt.Destroyed)for(const e of this._windows.get())e.activity&&e.activity.id===t.id&&this._windows.process(new Ft(e,new Lt(Ht.ActivityWindowLeftActivity)))})}subscribeWindowEvents(e){const t=(t,n)=>{let i=n.type;i===Ht.Added&&(i="opened"),e(t.activity,t,i)};return this._windowHandlers.push([e,t]),this._windows.subscribe(t)}unsubscribeWindowEvents(e){const t=this._windowHandlers.find(t=>t[0]===e);t&&(this._windowHandlers.splice(this._windowHandlers.indexOf(t),1),this._windows.unsubscribe(t[1]))}createWindow(e,t,n){const i=new Promise((n,i)=>{let r,o;if(Rt(t)&&i("windowType is undefined"),xt(t))r={type:t,name:"",isIndependent:!1,arguments:{}};else if(t instanceof Dt)r={type:t.type||t.id,name:t.name||t.type||t.id,isIndependent:!1};else{const e=["url"],n={};Object.keys(t).forEach(i=>{-1===e.indexOf(i)&&(n[i]=t[i])}),r=n}if(!Rt(r.relativeTo))if(o=r.relativeTo,"string"==typeof o){const e=this.getWindows({type:o});!Rt(e)&&e.length>0&&(r.relativeTo=e[0].id)}else if(Rt(o.type))Rt(o.windowId)||(r.relativeTo=o.windowId);else{const e=this.getWindows({type:o.type});!Rt(e)&&e.length>0&&(r.relativeTo=e[0].id)}this._bridge.createWindow(e&&e.id,r).then(t=>{this._logger.debug("Window created, waiting for window entity with id "+t);const i=(r,o)=>{r.id!==t||e&&!r.activity||(this._logger.debug("Got entity window with id "+t),n(r),this._windows.unsubscribe(i))};this._windows.subscribe(i)}).catch(e=>{i(e)})});return zt(i,n)}createStackedWindows(e,t,n,i){return zt(new Promise((i,r)=>{Rt(e)&&r("activity is undefined"),Rt(t)&&r("relativeWindowTypes is undefined"),Array.isArray(t)||r("relativeWindowTypes has to be an array"),Rt(n)&&(n=2e4);const o=[];t.forEach(e=>{let t,i;if(t=xt(e)?{type:e,name:"",isIndependent:!1,arguments:{}}:e,t.stackedWindow=!0,t.timeout=n,!Rt(t.relativeTo))if(i=t.relativeTo,Rt(i.type)){if(!Rt(i.windowId)){const e=this.getWindows({id:i.windowId});!Rt(e)&&e.length>0&&(t.relativeTo=e[0].type.name)}}else t.relativeTo=i.type;o.push(t)});const s=[];o.forEach(t=>s.push(this.createWindow(e,t))),Promise.all(s).then(i).catch(r)}),i)}addWindowToActivity(e,t,n){const i=this._bridge.joinActivity(e.id,t.id).then(()=>t);return zt(i,n),i}leaveWindowFromActivity(e,t,n){const i=this._bridge.leaveActivity(e.id,t.id).then(()=>t);return zt(i,n),i}setActivityContext(e,t,n){const i=new Promise((n,i)=>{Rt(e)&&i("activity can not be null"),this._bridge.updateActivityContext(e,t,!0).then(t=>{n(e)}).catch(e=>{i(e)})});return zt(i,n)}updateActivityContext(e,t,n){const i=new Promise((n,i)=>{Rt(e)&&i("activity can not be null");const r=[];for(const e in t)t.hasOwnProperty(e)&&null===t[e]&&r.push(e);for(const e of r)delete t[e];this._bridge.updateActivityContext(e,t,!1,r).then(t=>{n(e)}).catch(e=>{i(e)})});return zt(i,n)}subscribeActivityContextChanged(e){this._activities.subscribe((t,n)=>{if(n.type===Ht.ActivityContextChange){const i=n;e(t,i.context,i.updated,i.removed)}})}stopActivity(e,t){return zt(this._bridge.stopActivity(e),t)}getWindows(e){if(Mt(e))return this._windows.get();if(!Mt(e.id))return[this._windows.getByName(e.id)];return this._windows.get().filter(t=>{if(!Mt(e.type)&&t.type.id!==e.type)return!1;if(!Mt(e.name)&&t.name!==e.name)return!1;if(!Mt(e.activityId)){if(Rt(t.activity))return!1;if(t.activity.id!==e.activityId)return!1}return!0})}getWindowBounds(e){return this._bridge.getWindowBounds(e)}setWindowBounds(e,t,n){const i=new Promise((n,i)=>{this._bridge.setWindowBounds(e,t).then(()=>n()).catch(e=>i(e))});return zt(i,n)}closeWindow(e){return this._bridge.closeWindow(e)}activateWindow(e,t){return this._bridge.activateWindow(e,t)}setWindowVisibility(e,t){return this._bridge.setWindowVisibility(e,t)}clone(e,t,n){const i=new Promise((n,i)=>{e||i("activity can not be null"),this._bridge.cloneActivity(e.id,t).then(e=>{this._activities.getOrWait(e).then(e=>{n(e)}).catch(e=>i(e))}).catch(e=>i(e))});return zt(i,n)}attachActivities(e,t,n,i){n=n||{};const r=new Promise((i,r)=>{if(!this._activities.getByName(e))return void r("can not find activity with id "+e);if(this._activities.getByName(t))return this._bridge.attachActivities(e,t,n).then(e=>{const t=e.to,n=e.descriptor,r=e.descriptors;this._activities.getOrWait(t).then(e=>{e._updateDescriptors(r);const t=e.attached.filter(e=>e.ownerId===n.ownerId)[0];i(t)})}).catch(e=>{r(e)});r("can not find activity with id "+t)});return zt(r,i)}detachActivities(e,t,n){const i=new Promise((n,i)=>this._bridge.detachActivities(e,t).then(()=>{this._activities.getOrWait(undefined).then(e=>{e._updateDescriptors(undefined),this._activities.getOrWait(undefined).then(e=>{n(e)})}).catch(e=>i(e))}).catch(e=>{i(e)}));return zt(i,n)}subscribeActivitiesAttached(e){this._attachedCallbacks.push(e)}subscribeActivitiesDetached(e){this._detachedCallbacks.push(e)}subscribeActivityFrameColorChanged(e){this._frameColorChangesCallbacks.push(e)}_grabEntity(e){e._manager=this}_getInitialData(){this._logger.debug("Request initial data..."),this._bridge.getActivityTypes().then(e=>{this._activityTypes.add(e),this._dataReadyMarker.signal("Got act types")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity types -"+e)}),this._bridge.getWindowTypes().then(e=>{this._windowTypes.add(e),this._dataReadyMarker.signal("Got window types")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting window types "+e)}),this._bridge.getActivities().then(e=>{this._activities.add(e),this._dataReadyMarker.signal("Got activities")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity instances -"+e)}),this._bridge.getActivityWindows().then(e=>{this._windows.add(e),this._dataReadyMarker.signal("Got windows")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity windows -"+e)})}_subscribeForData(){this._logger.debug("Subscribe for data..."),this._bridge.onActivityTypeStatusChange(e=>{this._activityTypes.process(e)}),this._bridge.onWindowTypeStatusChange(e=>{this._windowTypes.process(e)}),this._bridge.onActivityWindowChange(e=>{this._windows.process(e)}),this._bridge.onActivityStatusChange(e=>{this._activities.process(e)})}_handleActivitiesAttached(e){const t=e.to,n=e.descriptor,i=e.descriptors;this._activities.getOrWait(t).then(e=>{e._updateDescriptors(i);const t=e.attached.filter(e=>e.ownerId===n.ownerId)[0];this._attachedCallbacks.forEach(n=>{try{n(e,t)}catch(e){return}})})}_handleActivitiesDetached(e){const t=e.oldActivityId,n=e.newActivityId,i=e.descriptors,r=e.descriptor;this._activities.getOrWait(t).then(e=>{e._updateDescriptors(i),this._activities.getOrWait(n).then(t=>{this._detachedCallbacks.forEach(n=>{try{n(t,e,r)}catch(e){return}})})})}_handleActivityDescriptorsRefreshed(e){const t=e.id,n=e.descriptors,i=this._activities.getByName(t);i&&i._updateDescriptors(n)}refreshDescriptors(){this._bridge.getAttachedDescriptors().then(e=>{e&&Object.keys(e).forEach(t=>{const n=t,i=e[t],r=this._activities.getByName(n);r&&r._updateDescriptors(i)}),this._descriptorsMarker.signal("Successfully got descriptors")}).catch(e=>{this._descriptorsMarker.error("failed to get descriptors - "+e)})}_handleWindowFrameColorChanged(e){if(!e.activityId)return;const t=this._activities.getByName(e.activityId);t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._frameColorChangesCallbacks.forEach(n=>{try{n(t,e.frameColor)}catch(e){return}})}}class vn{constructor(e,t){this._m=e,this._my=t,this.activityTypes={get:this._getActivityTypesWrapper.bind(this),register:this._m.registerActivityType.bind(this._m),unregister:this._m.unregisterActivityType.bind(this._m),subscribe:this._m.subscribeActivityTypeEvents.bind(this._m),unsubscribe:void 0,initiate:this._m.initiate.bind(this._m)},this.windowTypes={get:this._getWindowTypesWrapper.bind(this),registerFactory:this._m.registerWindowFactory.bind(this._m),unregisterFactory:this._m.unregisterWindowFactory.bind(this._m),subscribe:this._m.subscribeWindowTypeEvents.bind(this._m),unsubscribe:void 0},this.windows={get:this._m.getWindows.bind(this._m),subscribe:this._m.subscribeWindowEvents.bind(this._m),announce:this._m.announceWindow.bind(this._m),unsubscribe:void 0,create:this._m.createWindow.bind(this._m)},this.instances={get:this._m.getActivities.bind(this._m),subscribe:this._m.subscribeActivityEvents.bind(this._m),unsubscribe:void 0}}onAttached(e){this._m.subscribeActivitiesAttached(e)}onDetached(e){this._m.subscribeActivitiesDetached(e)}onActivityFrameColorChanged(e){this._m.subscribeActivityFrameColorChanged(e)}_getActivityTypesWrapper(e){return Mt(e)?this._m.getActivityTypes():this._m.getActivityType(e)}_getWindowTypesWrapper(e){return Mt(e)?this._m.getWindowTypes():this._m.getWindowType(e)}}class bn{constructor(e,t){this._mgr=e,this._my=t,this.all=new vn(e,t)}ready(e){const t=new Promise((e,t)=>{this._mgr.ready().then(()=>{e(this)}).catch(e=>{t(e)})});return zt(t,e)}get my(){return this._my}get aware(){return void 0!==this._my.window}get inActivity(){return this.aware&&void 0!==this._my.activity}get agm(){if(this.aware)return this.inActivity?this._my.activity.agm:new Jt(null)}getAvailableFrameColors(){return[]}}class _n{static checkIsUsingGW3Implementation(e){return 3===e.protocolVersion}get api(){return this._api}set api(e){this._api=e}constructor(e){if(!e)throw new Error("config can not be null");let t;if(Mt(e.logLevel)||(Zt.Level=e.logLevel),Rt(e.logger)||(Zt.GlueLogger=e.logger),this._isUsingHCImplementation=2===e.gdMajorVersion,this._isUsingGW3Implementation=_n.checkIsUsingGW3Implementation(e.connection),this._isUsingHCImplementation)throw new Error("GD2 not supported");if(!this._isUsingGW3Implementation)throw new Error("Unable to instantiate activity bridge implementation");if(t=new gn(e),!t)throw new Error("A bridge to native activity is needed to create activity lib.");Jt.AGM=e.agm;const n=new wn(t,!e.disableAutoAnnounce,e.windows),i=new fn(n,e.windows);this._api=new bn(n,i),this._readyPromise=n.ready().then(e=>this)}get isUsingHCImplementation(){return this._isUsingHCImplementation}get isUsingGW3Implementation(){return this._isUsingGW3Implementation}ready(e){return zt(this._readyPromise,e)}}const In="T42.ACS.GetFunctionalEntitlement",Cn="T42.ACS.CanI",An="T42.ACS.OnEvent",Tn="T42.ACS.GetApplications";var Sn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function kn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function xn(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var r=n instanceof Error?n:new Error(n);if(t)t(r);else{var o='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,r){var o=n[e];return o||(o=[],n[e]=o),o.push(t),r&&setTimeout(function(){r.forEach(function(r){var o;if(null===(o=n[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}catch(t){i(t,e)}})},0),function(){var i=n[e];i&&(0===(i=i.reduce(function(e,n,i){return n===t&&e.length===i||e.push(n),e},[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var o=n[e];if(!o||0===o.length)return[];var s=[];return o.forEach(function(n){try{var r=n.apply(void 0,t);s.push(r)}catch(t){s.push(void 0),i(t,e)}}),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}xn.default=xn;var En=kn(xn);function Pn(e){return e?Object.keys(e).map(t=>e[t]):[]}function Mn(e){let t;try{t=JSON.parse(JSON.stringify(e||{}))}catch(e){t={}}return t}function Rn(e,t){if(t.throwErrors&&"function"!=typeof e)throw new Error("Please provide the callback as a function!")}const Nn=9e4,On=9e4,jn=2147483647;class $n{static getGDMajorVersion(){if("undefined"==typeof window)return-1;if(!window.glueDesktop)return-1;if(!window.glueDesktop.version)return-1;const e=window.glueDesktop.version.split("."),t=Number(e[0]);return isNaN(t)?-1:t}static typedError(e){let t;return t=e instanceof Error?e:"string"==typeof e?new Error(e):"message"in e&&"string"==typeof e.message&&e.message.length>0?new Error(e.message):"returned"in e&&"object"==typeof e.returned&&"errorMsg"in e.returned&&"string"==typeof e.returned.errorMsg&&e.returned.errorMsg.length>0?new Error(e.returned.errorMsg):new Error("Unknown error"),t}static async callbackifyPromise(e,t,n){try{return(e=>("function"==typeof t&&t(e),Promise.resolve(e)))(await e())}catch(e){return(e=>{const t=$n.typedError(e);if("function"!=typeof n)return Promise.reject(t);n(t.message)})(e)}}static getMonitor(e,t){return t.map(t=>{const{left:n,top:i,workingAreaWidth:r,workingAreaHeight:o}=t;return{monitor:t,totalOverlap:this.calculateTotalOverlap({left:n,top:i,width:r,height:o},e)}}).sort((e,t)=>t.totalOverlap-e.totalOverlap)[0].monitor}static isRunningInIoCdContext(){return"undefined"!=typeof window&&(window.glue42gd||window.iodesktop)}static isNode(){if(void 0!==$n._isNode)return $n._isNode;if("undefined"!=typeof window)return $n._isNode=!1,!1;try{$n._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){$n._isNode=!1}return $n._isNode}static generateId(){return((e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})(10)}static isPromise(e){return Boolean(e&&"function"==typeof e.then)}static isAsyncFunction(e){return e&&"[object AsyncFunction]"==={}.toString.call(e)}static isNullOrUndefined(e){return null==e}static calculateTotalOverlap(e,t){const n=e.left,i=e.top,r=n+e.width,o=i+e.height,s=t.left,a=t.top,c=s+t.width,d=a+t.height;return Math.max(0,Math.min(r,c)-Math.max(n,s))*Math.max(0,Math.min(o,d)-Math.max(i,a))}}class Wn{constructor(e,t,n,i,r){this._appManager=e,this._name=t,this._agm=n,this._logger=i,this._configuration=r,this._registry=En(),e.onInstanceStarted(e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStarted",e)}),e.onInstanceStopped(e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStopped",e)}),e.onAppRemoved(e=>{e.name===this._name&&this._registry.execute("appRemoved",e)}),e.onAppChanged(e=>{e.name===this._name&&this._registry.execute("appChanged",e)}),e.onAppAvailable(e=>{e.name===this._name&&(this._props.IsReady=!0,this._registry.execute("appAvailable",e))}),e.onAppUnavailable(e=>{e.name===this._name&&(this._props.IsReady=!1,this._registry.execute("appUnavailable",e))})}get name(){return this._name}get title(){return this._props.Title}get version(){return this._props.Version}get autoStart(){return this._props.AutoStart}get isShell(){return this._props.IsShell}get caption(){return this._props.Caption}get hidden(){return this._props.IsHidden}get container(){return this._props.ApplicationName}get activityType(){return this._props.ActivityType}get activityWindowType(){return this._props.ActivityWindowType}get windowSettings(){return this._props.Arguments?Mn(this._props.Arguments):{}}get allowMultiple(){return this._props.AllowMultiple}get available(){return this._props.IsReady||!0}get icon(){return this._props.Icon}get iconURL(){return this._props.IconUrl}get sortOrder(){return this._props.SortOrder}get userProperties(){return this._props.UserProperties?Mn(this._props.UserProperties):{}}get keywords(){return this._props.Keywords?this._props.Keywords:[]}get isActivity(){return void 0!==this._props.ActivityType&&""!==this._props.ActivityType}get configuration(){return{autoStart:this._props.AutoStart,caption:this._props.Caption,hidden:this._props.IsHidden,container:this._props.ApplicationName,activityType:this._props.ActivityType,allowMultiple:this._props.AllowMultiple}}get instances(){return this._appManager.instances().filter(e=>e.application.name===this._name)}get type(){return this._props.Type}get mode(){if(!this._props)return"unknown";if(this._props.Mode&&"string"==typeof this._props.Mode)return this._props.Mode.toLowerCase();if(this.isActivity)return"unknown";if(this._props.Arguments&&this._props.Arguments.mode&&"string"==typeof this._props.Arguments.mode)return this._props.Arguments.mode.toLowerCase();let e=this._props.WindowStyleAttributes;if(e){e=e.split(" ").join("");const t='mode:"',n=e.indexOf(t);if(-1!==n){const i=n+t.length,r=e.indexOf('"',i),o=e.substr(i,r-i);if(o&&"string"==typeof o)return o.toLowerCase()}}return"flat"}async getConfiguration(){return(await this._agm.invoke(Tn,{v2:{apps:[this._name]}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.applications[0]}updateFromProps(e){this._props||(this._props={Name:e.Name}),Object.keys(e).forEach(t=>{this._props[t]=e[t]})}start(e,t){return new Promise(async(n,i)=>{var r,o,s,a;if(Rt(e))e={};else if((null===(r=this._configuration())||void 0===r?void 0:r.throwErrors)&&"object"!=typeof e||Array.isArray(e))return i(new Error('Invalid "context" parameter - must be an object.'));if(Rt(t))t={};else if((null===(o=this._configuration())||void 0===o?void 0:o.throwErrors)&&"object"!=typeof t)return i(new Error('Invalid "options" parameter - must be an object.'));const c=this._name;let d=null===(a=null!==(s=t.awaitInterop)&&void 0!==s?s:t.waitForAGMReady)||void 0===a||a,h=9e4;"number"==typeof t.timeout&&(h=1e3*t.timeout),void 0!==t.relativeTo&&"string"!=typeof t.relativeTo&&(t.relativeTo=t.relativeTo.id||"");const u=e=>{let t,r;const o=setTimeout(()=>{s();const t=`timed out while waiting for instance id ${e} for app ${this.name}`;this._logger.error(t),i(new Error(t))},h),s=()=>{clearTimeout(o),"function"==typeof t&&(t(),t=void 0),"function"==typeof r&&(r(),r=void 0)},a=t=>{t.id===e&&(s(),this._logger.trace(`instance ${e} appeared, resolving start promise`),n(t))};r=this._appManager.onInstanceStopped(t=>{t.id===e&&(s(),i(new Error(`instance ${e} was stopped while waiting for Interop to be ready`)))});const c=this._appManager.instances().find(t=>t.id===e);d?t=c?c.onAgmReady(a):this._appManager.onInstanceAgmServerReady(a):c?a(c):t=this._appManager.onInstanceStarted(a)};try{this._logger.trace(`starting application with "${c}" with options: ${JSON.stringify(t)}`);const i=(await this._agm.invoke("T42.ACS.StartApplication",{Name:c,Context:e,Options:t},"best",{methodResponseTimeoutMs:h,waitTimeoutMs:On})).returned;if(void 0!==i.timeout&&void 0===t.timeout&&(h=1e3*i.timeout),void 0!==i.waitForInterop&&void 0===t.waitForAGMReady&&void 0===t.awaitInterop&&(d=i.waitForInterop),i&&i.Id)if("startOnly"===this._appManager.mode){const e=this._appManager.handleInstanceStarted({ActivityId:void 0,IsActivityOwner:void 0,Context:void 0,Title:void 0,AgmServers:void 0,Id:i.Id,Name:i.Name});n(e)}else u(i.Id);else n(void 0)}catch(e){const t=$n.typedError(e);i(t)}})}onInstanceStarted(e){return Rn(e,this._configuration()),this._registry.add("instanceStarted",e)}onInstanceStopped(e){return Rn(e,this._configuration()),this._registry.add("instanceStopped",e)}onAvailable(e){return Rn(e,this._configuration()),this._props.IsReady&&setTimeout(()=>{this._registry.execute("appAvailable",this)},0),this._registry.add("appAvailable",e)}onUnavailable(e){return Rn(e,this._configuration()),!1===this._props.IsReady&&setTimeout(()=>{this._registry.execute("appUnavailable",this)},0),this._registry.add("appUnavailable",e)}onChanged(e){Rn(e,this._configuration()),this._registry.add("appChanged",e)}onRemoved(e){Rn(e,this._configuration()),this._registry.add("appRemoved",e)}}class Dn{constructor(e,t,n,i,r,o,s,a,c){this._id=e,this._appName=t,this._appManager=n,this._agm=i,this._activities=r,this._windows=o,this._logger=s,this._configuration=c,this._registry=En(),a||(this._unsubscribeInstanceStopped=this._appManager.onInstanceStopped(e=>{e.id===this._id&&this._registry.execute("stopped",e)}),this._unsubscribeInstanceAgmServerReady=this._appManager.onInstanceAgmServerReady(e=>{e.id===this._id&&this._registry.execute("agmReady",e)}))}get id(){return this._id}get application(){return this._appManager.application(this._appName)}get activity(){if(!this._activities)throw new Error("This method requires glue.activities library to be enabled.");return this._activities.all.instances.get().filter(e=>e.id===this._activityId)[0]}get isActivityOwner(){return this._isActivityOwner}get activityInstances(){return this._appManager.instances().filter(e=>"activity"!==e.application.type&&e.activityId&&e.activityId===this._activityId)}get activityOwnerInstance(){if(this._activityId)return this.activityInstances.filter(e=>null==e?void 0:e.isActivityOwner)[0]}get window(){if(!this._windows)throw new Error("This method requires glue.windows library to be enabled.");let e=this._windows.list().find(e=>e.id===this._id);return!e&&this._activities&&this.activity&&this.activityOwnerInstance&&(e=this.activityOwnerInstance.window),e}get context(){var e,t,n;return null!==(n=null!==(e=this._startUpContext)&&void 0!==e?e:null===(t=this.window)||void 0===t?void 0:t.context)&&void 0!==n?n:{}}get title(){return this._title}get isActivityInstance(){return this._isActivityInstance}get activityId(){return this._activityId}get inActivity(){return this._inActivity}get isSingleWindowApp(){return!this._inActivity}get agm(){return this._agmInstance}get interopInstance(){return this._agmInstance}onInteropReady(e){return Rn(e,this._configuration()),this._agmInstance&&setTimeout(()=>{this._registry.execute("agmReady",this)},0),this._registry.add("agmReady",e)}onAgmReady(e){return this.onInteropReady(e)}onStopped(e){return Rn(e,this._configuration()),this._registry.add("stopped",e)}getWindow(){return new Promise((e,t)=>{const n=this.window;if(n)return void e(n);const i=(n,i)=>{n&&t(n),i&&e(i),setTimeout(()=>{clearTimeout(r),o()},0)};this._logger.trace(`waiting for window with id ${this._id} to appear`);const r=setTimeout(()=>{this._logger.trace(`window with id ${this._id} did not appear in 90 sec`),i(new Error(`can not find a window with id ${this._id}`))},9e4),o=this._windows.onWindowAdded(e=>{e.id===this._id&&(this._logger.trace(`window with id ${this._id} appeared`),i(void 0,e))})})}updateFromProps(e){this._startUpContext=e.Context,this._title=e.Title,this._isActivityInstance=!1,e.ActivityId&&""!==e.ActivityId&&(this._activityId=e.ActivityId,this._isActivityInstance=!0),this._isActivityOwner=e.IsActivityOwner,!this._activityId&&this._startUpContext&&this._startUpContext.activityId&&(this._activityId=this._startUpContext.activityId),this._inActivity=Boolean(this._activityId),this.updateAgmInstanceFromProps(e)}updateAgmInstanceFromProps(e){if(!e.AgmServers)return;const t=e.AgmServers;t&&t.length>0&&!Rt(t[0])&&(this._agmInstance=t[0])}stop(){return new Promise((e,t)=>{let n=this._id;this.isActivityOwner&&(n=this.activityId);const i=this._appManager.onInstanceStopped(t=>{t.id===n&&(this._logger.trace(`instance with id ${n} stopped`),i(),e())});this._logger.trace(`stopping instance with id ${this._id}`),this._agm.invoke("T42.ACS.StopApplication",{Name:this._appName,Id:this._id},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(()=>{"startOnly"===this._appManager.mode&&(this._appManager.handleInstanceStopped({Name:this._appName,Id:this.id}),e())}).catch(e=>t(e))})}activate(){return this._agm.invoke("T42.ACS.ActivateApplication",{Name:this._appName,Id:this._id},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}done(){this._registry.clear(),this._unsubscribeInstanceAgmServerReady(),this._unsubscribeInstanceStopped()}getContext(){return Promise.resolve(this.context)}async startedBy(){return(await this._agm.invoke("T42.ACS.Execute",{command:"getStartedBy",Name:this._appName,Id:this._id},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}}class Fn{constructor(e,t,n,i,r,o,s){this.mode=e,this._agm=t,this._activities=n,this._windows=i,this._logger=r,this._gdMajorVersion=o,this._configuration=s,this._apps={},this._instances=[],this._registry=En(),this.getConfigurations=async e=>{const t={v2:{apps:void 0}};Array.isArray(e)&&(t.v2={apps:e});return(await this._agm.invoke(Tn,t,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.applications},this.application=e=>{var t;if((null===(t=this._configuration())||void 0===t?void 0:t.throwErrors)&&"string"!=typeof e||Nt(e))throw new Error('"name" must be string');return this._apps[e]},this.applications=()=>Object.keys(this._apps).map(e=>this._apps[e]),this.instances=()=>this._instances.map(e=>e),this.getMyInstance=()=>{const e="undefined"!=typeof window&&window.glue42gd;if(!e){const e=this._agm.instance.instance;return this._instances.find(t=>t.id===e)}if(this._gdMajorVersion>=3){const t=e.appInstanceId;return this._instances.find(e=>e.id===t)}},this.getMyApplication=()=>{var e;if(this._agm.instance)return null!==(e=this.application(this._agm.instance.applicationName))&&void 0!==e?e:this.application(this._agm.instance.application)},this.handleSnapshotAppsAdded=e=>{const t=this.applications();t.length>0&&t.forEach(t=>{const n=t.name;e.find(e=>e.Name===t.name)||this.handleAppRemoved({Name:n})}),e.forEach(e=>{t.find(t=>t.name===e.Name)||this.handleAppAdded(e)})},this.handleSnapshotInstanceStarted=e=>{const t=this.instances();t.length>0&&t.forEach(t=>{const n=t.id;e.find(e=>e.Id===n)||this.handleInstanceStopped({Name:t.application.name,Id:n})}),e.forEach(e=>{t.find(t=>t.id===e.Id)||this.handleInstanceStarted(e)})},this.handleAppAdded=e=>{const t=this._getAppId(e);this._logger.trace(`adding app ${t}`),this._apps[t]=new Wn(this,t,this._agm,this._logger,this._configuration);const n=this._updateAppFromProps(e);this._registry.execute("appAdded",n),this._registry.execute("appAvailable",n)},this.handleAppUpdated=e=>{const t=this._updateAppFromProps(e);this._registry.execute("appChanged",t)},this.handleAppRemoved=e=>{const t=this._getAppId(e);this._logger.trace(`removing app ${t}`);const n=this.application(t);this._instances=this._instances.filter(e=>e.application.name!==n.name),delete this._apps[t],this._registry.execute("appRemoved",n)},this.handleAppReady=e=>{const t=this._getAppId(e),n=this._getAppOrThrow(t);n.updateFromProps(e),n.available?this._registry.execute("appAvailable",n):this._registry.execute("appUnavailable",n)},this.handleInstanceStarted=e=>{this._logger.trace(`started app ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=new Dn(t,n,this,this._agm,this._activities,this._windows,this._logger,!1,this._configuration);return this._updateInstanceFromProps(i,e),this._instances.push(i),this._registry.execute("instanceStarted",i),i},this.handleInstanceStopped=e=>{this._logger.trace(`instance stopped ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=this._getInstanceOrThrow(t,n);this._instances=this._instances.filter(e=>!this._matchInstance(e,t,n)),this._registry.execute("instanceStopped",i),i.done()},this.handleInstanceAgmServerReady=e=>{this._logger.trace(`instance interop server ready ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=this._getInstanceOrThrow(t,n);i.updateAgmInstanceFromProps(e),this._registry.execute("instanceAgmServerReady",i)},this.handleInstanceStartFailed=e=>{const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=new Dn(t,n,this,this._agm,this._activities,this._windows,this._logger,!0,this._configuration);this._updateInstanceFromProps(i,e),this._registry.execute("instanceStartFailed",i)},this.handleInstanceUpdated=e=>{const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=this._getInstanceOrThrow(t,n);this._updateInstanceFromProps(i,e)},this.onInstanceStarted=e=>(Rn(e,this._configuration()),this._registry.add("instanceStarted",e,this._instances)),this.onInstanceStartFailed=e=>(Rn(e,this._configuration()),this._registry.add("instanceStartFailed",e)),this.onInstanceStopped=e=>(Rn(e,this._configuration()),this._registry.add("instanceStopped",e)),this.onInstanceUpdated=e=>(Rn(e,this._configuration()),this._registry.add("instanceChanged",e)),this.onInstanceAgmServerReady=e=>(Rn(e,this._configuration()),this._registry.add("instanceAgmServerReady",e)),this.onAppAdded=e=>(Rn(e,this._configuration()),this._registry.add("appAdded",e,Object.values(this._apps))),this.onAppRemoved=e=>(Rn(e,this._configuration()),this._registry.add("appRemoved",e)),this.onAppAvailable=e=>(Rn(e,this._configuration()),this._registry.add("appAvailable",e)),this.onAppUnavailable=e=>(Rn(e,this._configuration()),this._registry.add("appUnavailable",e)),this.onAppChanged=e=>(Rn(e,this._configuration()),this._registry.add("appChanged",e))}_getAppOrThrow(e){const t=this.application(e);if(!t)throw Error(`app with id ${e} not found`);return t}_getAppId(e){return e.Name}_matchInstance(e,t,n){return e.id===t&&e.application.name===n}_getInstanceByIdAndName(e,t){return this._instances.filter(n=>this._matchInstance(n,e,t))[0]}_getInstanceOrThrow(e,t){const n=this._getInstanceByIdAndName(e,t);if(!n)throw Error(`instance with id ${e} not found`);return n}_getInstanceId(e){return e.Id}_getInstanceAppName(e){return e.Name}_updateAppFromProps(e){const t=this._getAppId(e);this._logger.trace(`updating app with id: "${t}", ${JSON.stringify(e)}`);const n=this._getAppOrThrow(t);return n.updateFromProps(e),n}_updateInstanceFromProps(e,t){this._logger.trace("updating instance with "+this._getInstanceId(t)+" for app "+this._getInstanceAppName(t)),e.updateFromProps(t)}}function Ln(e,t,n){const i=e=>!!(e&&e.constructor&&e.call&&e.apply);return i(t)||i(n)?(i(t)?i(n)||(n=()=>{}):t=()=>{},e.then(t,n)):e}class Gn{constructor(e){this._agm=e,this._registry=En(),this._isMethodRegistered=!1,this.handleBranchModified=e=>{this._registry.execute("branchChanged",e)},this.handleBranchesModified=e=>{this._registry.execute("branchesChanged",e)},this.getRegion=(e,t)=>Ln(this._agmInvoke("T42.ACS.GetConfigurationRegion",e=>e.returned.Region),e,t),this.getBranches=(e,t)=>Ln(this._agmInvoke("T42.ACS.GetBranches",e=>{const t=e.returned.Branches;return Object.keys(t).map(e=>t[e])}),e,t),this.getCurrentBranch=(e,t)=>Ln(this._agmInvoke("T42.ACS.GetCurrentBranch",e=>e.returned.Branch,void 0),e,t),this.setRegion=(e,t,n)=>Ln(this._agmInvoke("T42.ACS.SetConfigurationRegion",e=>e.returned.ResultMessage,{Region:e}),t,n),this.setCurrentBranch=(e,t,n)=>Ln(this._agmInvoke("T42.ACS.SetCurrentBranch",e=>e.returned.ResultMessage,{Branch:e}),t,n),this.currentUser=(e,t)=>Ln(this._agmInvoke("T42.ACS.GetUser"),e,t),this.getFunctionalEntitlement=(e,t,n)=>Ln(this._agmInvoke(In,e=>e.returned.Entitlement,{Function:e}),t,n),this.getFunctionalEntitlementBranch=(e,t,n,i)=>Ln(this._agmInvoke(In,e=>e.returned.Entitlement,{Function:e,Branch:t}),n,i),this.canI=(e,t,n)=>Ln(this._agmInvoke(Cn,e=>e.returned.Result,{Function:e}),t,n),this.canIBranch=(e,t,n,i)=>Ln(this._agmInvoke(Cn,e=>e.returned.Result,{Function:e,Branch:t}),n,i),this.onBranchesChanged=e=>this._registry.add("branchesChanged",e),this.onBranchChanged=e=>this._registry.add("branchChanged",e),this.exit=e=>this._agmInvoke("T42.ACS.Shutdown",null,e),this.onShuttingDown=e=>(this.registerMethod(),this._registry.add("onShuttingDown",e)),this.restart=e=>this._agmInvoke("T42.ACS.Restart",null,e),this._agmInvoke=(e,t,n)=>(n=n||{},new Promise((i,r)=>{this._agm.invoke(e,n,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>{t||(t=e=>e.returned),i(t(e))}).catch(e=>r(e))}))}registerMethod(){this._isMethodRegistered||(this._agm.register("T42.ACS.OnGDShutdown",async e=>{try{const t=await Promise.all(this._registry.execute("onShuttingDown",e));return{prevent:t.some(e=>e.prevent)}}catch(e){}}),this._isMethodRegistered=!0)}}const Un="T42.ACS.InMemoryStoreCommand";class Hn{constructor(e){this.interop=e}import(e,t){if(!e||!Array.isArray(e))return Promise.reject(new Error("invalid apps argument - should be an array of application definitions"));if(t&&"replace"!==t&&"merge"!==t)return Promise.reject(new Error("invalid mode argument - should be 'replace' or 'merge'"));const n={command:"import",args:{apps:e,mode:t=null!=t?t:"replace"}};return this.interop.invoke(Un,n,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>e.returned)}export(){return this.interop.invoke(Un,{command:"export"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>e.returned.apps)}remove(e){if(!e||"string"!=typeof e)return Promise.reject(new Error("invalid app name, should be a string value"));const t={command:"remove",args:{apps:[e]}};return this.interop.invoke(Un,t,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>e.returned)}clear(){return this.interop.invoke(Un,{command:"clear"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>e.returned)}createAppDef(e,t){return t||(t="https://google.com"),{name:e,type:"window",title:e,details:{url:t}}}}var Bn=e=>{if(!e)throw Error("config not set");if(!e.agm)throw Error("config.agm is missing");const t="startOnly",n="skipIcons",i=e.mode||t;if(i!==t&&i!==n&&"full"!==i)throw new Error(`Invalid mode for appManager lib - ${i} is not supported`);const r=e.activities,o=e.agm,s=e.logger,a=e.windows;s.warn("AppManager API is deprecated. Please use the new Apps API (io.apps) instead. This API will be removed in a future version.");let c={};const d=new Fn(i,o,r,a,s.subLogger("applications"),e.gdMajorVersion,()=>c),h=new Gn(o);let u;if(i===t)u=function(e,t){return new Promise((n,i)=>{e.invoke(Tn,{skipIcon:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>{var i;const r=e.returned,o=null!==(i=e.returned.configuration)&&void 0!==i?i:{};r||n(o);const s=r.applications;s||n(o),Pn(s).map(e=>t.handleAppAdded(e)),n(o)}).catch(e=>i(new Error(`Error getting application snapshot: ${e.message}`)))})}(o,d);else{const e=function(e,t,n,i){let r,o=!1;return{start:()=>{let s,a;const c=new Promise((e,t)=>{s=e,a=t});return e.subscribe(An,{arguments:{skipIcon:i},waitTimeoutMs:On,methodResponseTimeout:On}).then(i=>{r=i,r.onData(i=>{var r;const a=i.data,c=null!==(r=a.configuration)&&void 0!==r?r:{},d=Pn(a.OnApplicationAdded);i.data.isSnapshot?t.handleSnapshotAppsAdded(d):d.forEach(e=>t.handleAppAdded(e)),Pn(a.OnApplicationChanged).forEach(e=>t.handleAppUpdated(e)),Pn(a.OnApplicationRemoved).forEach(e=>t.handleAppRemoved(e)),Pn(a.OnApplicationReady).forEach(e=>t.handleAppReady(e));const h=Pn(a.OnApplicationStarted);if(i.data.isSnapshot?t.handleSnapshotInstanceStarted(h):h.forEach(e=>t.handleInstanceStarted(e)),Pn(a.OnApplicationStartFailed).forEach(e=>t.handleInstanceStartFailed(e)),Pn(a.OnApplicationStopped).forEach(e=>t.handleInstanceStopped(e)),Pn(a.OnApplicationUpdated).forEach(e=>t.handleInstanceUpdated(e)),Pn(a.OnApplicationAgmServerReady).forEach(e=>t.handleInstanceAgmServerReady(e)),Pn(a.OnBranchChanged).forEach(e=>n.handleBranchModified(e)),Pn(a.OnBranchesModified).forEach(e=>n.handleBranchesModified(e)),!o){o=!0;const n=e.instance,i=d.some(e=>e.Name===n.application),r=h.some(e=>e.Id===n.instance);if(!i)return void s(c);if(!r&&($n.isNode()||$n.isRunningInIoCdContext())){const e=t.onInstanceStarted(t=>{t.id===n.instance&&(e(),s(c))});return}s(c)}}),r.onFailed(e=>a(e))}).catch(e=>{var t;return a(`Error subscribing for ${An} stream. Err: ${null!==(t=e.message)&&void 0!==t?t:JSON.stringify(e)}`)}),c},stop:()=>{r&&r.close()}}}(o,d,h,i===n);u=e.start()}return{ready:()=>u.then(e=>{c=e}),applications:d.applications,application:d.application,getConfigurations:d.getConfigurations,onAppAdded:d.onAppAdded,onAppRemoved:d.onAppRemoved,onAppChanged:d.onAppChanged,onAppAvailable:d.onAppAvailable,onAppUnavailable:d.onAppUnavailable,instances:d.instances,get myInstance(){return d.getMyInstance()},get myApplication(){return d.getMyApplication()},onInstanceStarted:d.onInstanceStarted,onInstanceStopped:d.onInstanceStopped,onInstanceUpdated:d.onInstanceUpdated,onInstanceStartFailed:d.onInstanceStartFailed,getRegion:h.getRegion,getBranches:h.getBranches,getCurrentBranch:h.getCurrentBranch,getFunctionalEntitlement:h.getFunctionalEntitlement,getFunctionalEntitlementBranch:h.getFunctionalEntitlementBranch,setCurrentBranch:h.setCurrentBranch,setRegion:h.setRegion,currentUser:h.currentUser,canI:h.canI,canIBranch:h.canIBranch,onBranchesChanged:h.onBranchesChanged,exit:h.exit,restart:h.restart,onShuttingDown:h.onShuttingDown,inMemory:new Hn(o)}};const Jn="T42.JumpList.Action";var qn=new class{constructor(){this._groupActionCallbacks=new Map,this._registered=!1}init(e,t,n){this._executor=e,this._agm=t,this._logger=n,this.registerCallbackMethod()}setEnabled(e,t){const n={enabled:t};return this._executor.updateJumpList(e,n)}createCategory(e,t,n){this.validateActions(t,n);const i={category:{title:t,operation:"create",actions:this.toUpdateActions(e,"create",t,n)}};return this._executor.updateJumpList(e,i)}removeCategory(e,t){const n={category:{title:t,operation:"remove",actions:[]}};return this.manageActionCallback(e,n.category.operation,t),this._executor.updateJumpList(e,n)}createActions(e,t,n){this.validateActions(t,n);const i={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"create",t,n)}};return this._executor.updateJumpList(e,i)}removeActions(e,t,n){const i={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"remove",t,n)}};return this._executor.updateJumpList(e,i)}async getActions(e,t){const n=[],i=(await this.getJumpListSettings(e)).categories.find(e=>e.title===t);return i&&i.actions.forEach(e=>{const t=this.getActionCallback(e.callbackId);t&&(e.callback=t.callback),n.push({icon:e.icon,callback:e.callback,singleInstanceTitle:e.singleInstanceTitle,multiInstanceTitle:e.multiInstanceTitle})}),Promise.resolve(n)}getJumpListSettings(e){return this._executor.getJumpList(e)}toUpdateActions(e,t,n,i){return i.map(i=>{const r={icon:i.icon,callback:i.callback,callbackId:$n.generateId(),singleInstanceTitle:i.singleInstanceTitle,multiInstanceTitle:i.multiInstanceTitle,operation:t};return this.manageActionCallback(e,t,n,r),r})}manageActionCallback(e,t,n,i){var r;const o=`${n}-${e}`;if("create"===t){this._groupActionCallbacks.has(o)||this._groupActionCallbacks.set(o,[]);this._groupActionCallbacks.get(o).push({callbackId:i.callbackId,callback:i.callback})}else if("remove"===t)if(i){let e=null!==(r=this._groupActionCallbacks.get(o))&&void 0!==r?r:[];e=e.filter(e=>e.callbackId!==i.callbackId),0===e.length?this._groupActionCallbacks.delete(o):this._groupActionCallbacks.set(o,e)}else this._groupActionCallbacks.delete(o)}registerCallbackMethod(){if(!this._registered){this._registered=!0;try{this._agm.register(Jn,(e,t)=>{const n=this.getActionCallback(e.callbackId);if(n)try{n.callback()}catch(e){this._logger.error("Unable to execute user callback for jump list action!",e)}})}catch(e){return this._logger.error(`Unable to register method ${Jn} for invoking jump list action callbacks!`,e),Promise.reject(e)}}}getActionCallback(e){let t;return[...this._groupActionCallbacks.values()].forEach(n=>{const i=n.find(t=>t.callbackId===e);i&&(t=i)}),t}validateActions(e,t){if(!(t&&t.length>0))throw new Error(`Category '${e}' doesn't contain any actions!`);t.forEach(t=>{if(!t.singleInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined singleInstanceTitle!`);if(!t.multiInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined multiInstanceTitle!`);if(!t.callback)throw new Error(`Category '${e}' contains an action with undefined callback function!`)})}};var Vn=new class{constructor(){this.waitForTimeoutInMilliseconds=6e4,this._windows={},this._pendingWindows={},this._pendingWindowsStates={},this._registry=En()}init(e){this._logger=e}get(e){return this._windows[e]||this._pendingWindows[e]}getIfReady(e){return this._windows[e]}get list(){return this._windows}add(e,t){void 0!==this._pendingWindows[e.API.id]?this._logger.error(`trying to add window with id ${e.API.id} from windowStore, which already exists`):(this._pendingWindows[e.API.id]=e,this._pendingWindowsStates[e.API.id]=t,this._registry.execute("on-added",e),this.shouldMarkReadyToShow(t)&&this.markReadyToShow(e.API.id))}remove(e){delete this._windows[e.API.id],delete this._pendingWindows[e.API.id],delete this._pendingWindowsStates[e.API.id],this._registry.execute("on-removed",e)}setUrlChangedState(e){const t=this._pendingWindowsStates[e];void 0!==t&&(t.urlChanged=!0,this.shouldMarkReadyToShow(t)&&this.markReadyToShow(e))}setCompositionChangedState(e){const t=e.API.id,n=this._pendingWindowsStates[t];void 0!==n&&(n.compositionChanged=!0,this.shouldMarkReadyToShow(n)&&this.markReadyToShow(t))}waitFor(e){return new Promise((t,n)=>{let i,r;const o=setTimeout(()=>{i(),r(),n(new Error(`Window with id "${e}" was not ready within ${this.waitForTimeoutInMilliseconds} milliseconds.`))},this.waitForTimeoutInMilliseconds),s=this._windows[e];if(s)clearTimeout(o),t(s);else{const s=()=>{clearTimeout(o),i(),r()};i=this.onReadyWindow(n=>{n.API.id===e&&(s(),t(n))}),r=this.onRemoved(t=>{t.API.id===e&&(s(),n(new Error(`Window with id "${e}" was closed before it became ready.`)))})}})}waitForName(e){return new Promise((t,n)=>{let i,r;const o=setTimeout(()=>{i(),r(),n(new Error(`Window with name "${e}" was not ready within ${this.waitForTimeoutInMilliseconds} milliseconds.`))},this.waitForTimeoutInMilliseconds),s=Object.keys(this._windows).find(t=>this._windows[t].API.name===e);if(s)clearTimeout(o),t(this._windows[s]);else{const s=()=>{clearTimeout(o),i(),r()};i=this.onReadyWindow(n=>{n.API.name===e&&(s(),t(n))}),r=this.onRemoved(t=>{t.API.name===e&&(s(),n(new Error(`Window with name "${e}" was closed before it became ready.`)))})}})}onReadyWindow(e){return this._registry.add("on-ready",e)}onAdded(e){return this._registry.add("on-added",e)}onRemoved(e){return this._registry.add("on-removed",e)}markReadyToShow(e){this._pendingWindows[e]&&(this._windows[e]=this._pendingWindows[e],delete this._pendingWindows[e],delete this._pendingWindowsStates[e]),this._registry.execute("on-ready",this._windows[e])}shouldMarkReadyToShow(e){return e&&e.urlChanged&&e.ready&&e.compositionChanged}};class zn{constructor(e,t){this.windowId=e,this._categoryTitle=t.title}list(){return qn.getActions(this.windowId,this._categoryTitle)}create(e){return qn.createActions(this.windowId,this._categoryTitle,e)}remove(e){return qn.removeActions(this.windowId,this._categoryTitle,e)}}class Kn{constructor(e){this.windowId=e}list(){return this.getCategories()}create(e,t){return qn.createCategory(this.windowId,e,t)}remove(e){return qn.removeCategory(this.windowId,e)}async find(e){return(await this.getCategories()).find(t=>t.title===e)}async getCategories(){const e=[];return(await qn.getJumpListSettings(this.windowId)).categories.forEach(t=>{e.push({title:t.title,actions:new zn(this.windowId,t)})}),e}}class Qn{constructor(e){this.windowId=e,this._categories=new Kn(e)}get categories(){return this._categories}async isEnabled(){return(await qn.getJumpListSettings(this.windowId)).enabled}setEnabled(e){return qn.setEnabled(this.windowId,e)}}class Zn{constructor(e){this.channel=e}get isJoinedToAnyChannel(){return!!this.channel}isOnChannel(e){return this.channel===e}leaveChannel(e){void 0!==e&&this.channel!==e||(this.channel=void 0)}joinChannel(e){this.channel=e}all(){return this.channel?[this.channel]:[]}toString(){return this.channel}equals(e){return e instanceof Zn&&this.channel===e.channel}}class Xn{constructor(e){this.ChannelDelimiter="+++",this.channels=e?"string"==typeof e?null==e?void 0:e.split(this.ChannelDelimiter).filter(Boolean):(null!=e?e:[]).filter(Boolean):[]}get isJoinedToAnyChannel(){return this.channels.length>0}isOnChannel(e){return this.channels.includes(e)}joinChannel(e){new Xn(e).all().forEach(e=>{this.channels.includes(e)||this.channels.push(e)})}leaveChannel(e){new Xn(null!=e?e:this.channels).all().forEach(e=>{this.channels=this.channels.filter(t=>t!==e)})}all(){return this.channels}toString(){if(0!==this.channels.length)return this.channels.join(this.ChannelDelimiter)}equals(e){return e instanceof Xn&&(this.channels.length===e.channels.length&&this.channels.every((t,n)=>t===e.channels[n]))}}var Yn=(e,t,n,i,r,o,s,a)=>{var c,d,h,u;const l=En(),p=()=>{const e=s();if(!e)throw new Error("To use this method you need to enable channels API - set the channels property to true when initializing the Glue42 library");return e},g=()=>{var e;return null===(e=r())||void 0===e?void 0:e.appManager},f=e,m=t.name,y=t.mode;let w=t.bounds,v=t.url,b=t.title,_=null!==(c=t.context)&&void 0!==c?c:{},I=t.frameColor,C=t.focus,A=null!==(d=t.neighbours)&&void 0!==d?d:{},T=t.groupId,S=t.isGroupHeaderVisible,k=t.isTabHeaderVisible,x=t.isGroupHibernated,E=t.isGroupVisible,P=null!==(h=t.isTabSelected)&&void 0!==h&&h,M=t.settings;const R=t.applicationName;let N,O=t.isVisible,j=t.isSticky,$=t.isCollapsed,W=t.state,D=t.tabGroupId,F=t.tabIndex,L=t.frameId,G=t.isLocked,U=t.allowWorkspaceDrop,H=t.isPinned,B=null!==(u=t.frameButtons)&&void 0!==u?u:[],J=t.zoomFactor,q=t.placementSettings;const V=new Qn(e);function z(e,t,i){return $n.callbackifyPromise(()=>{if(Rt(e))throw new Error("The properties of `bounds` cannot be null or undefined.");return n.moveResize(ne,e)},t,i)}function K(e,t,i){return $n.callbackifyPromise(()=>n.setVisible(ne,e),t,i)}function Q(e){return Z("group-changed",e)}function Z(e,t,n){if(!jt(t))throw new Error("callback must be a function");return l.add(e,t,n)}async function X(){var e;return null===(e=(await p().getWindowsWithChannels({windowIds:[f]}))[0])||void 0===e?void 0:e.channel}function Y(e){const t=A[e];if(void 0!==t)return t.reduce((e,t)=>{const n=Vn.get(t);return n&&e.push(n.API),e},[])}function ee(){var t;if(R)return R;if(_._APPLICATION_NAME)return _._APPLICATION_NAME;if(_&&_._t42&&_._t42.application)return _._t42.application;const n=te();if(n&&n.applicationName)return n.applicationName;const i=g();if(i){const n=i.instances().find(t=>e===t.id);if(n)return null===(t=n.application)||void 0===t?void 0:t.name}}function te(){if("undefined"!=typeof window&&window.glue42gd&&window.glue42gd.getWindowInfo){const t=window.glue42gd.getWindowInfo(e);return t||void 0}}const ne={get id(){return f},get name(){return m},get application(){const e=g();if(!e&&r().apps)throw new Error("The AppManager API is not available. Please use the 'getApplication' method instead.");const t=ee();if(t&&e)return e.application(t)},get appName(){return R||ee()},get hostInstance(){return n.hostInstance},get interopInstance(){const e=a.servers().find(e=>e.windowId===this.id);if(e)return e;{const e=ee();if(e)return{application:e}}},get agmInstance(){return ne.interopInstance},get url(){return v},get title(){return b},get windowStyleAttributes(){return M},get settings(){return M},get tabGroupId(){return"tab"===y.toLowerCase()?D:void 0},get tabIndex(){return"tab"===y.toLowerCase()?F:void 0},get frameId(){return L},get frameButtons(){return B.sort((e,t)=>e.order-t.order)},get mode(){return y},get state(){return W},get isCollapsed(){return $},get isVisible(){return O},get isLocked(){return G},get context(){return console.warn("The 'context' property is deprecated and will be removed in a future release. Please use 'getContext' method instead."),_},get bounds(){return w},get minHeight(){return M.minHeight},get maxHeight(){return M.maxHeight},get minWidth(){return M.minWidth},get maxWidth(){return M.maxWidth},get isFocused(){return C},get frameColor(){return I},get opened(){return void 0!==ne.id},get group(){return N},get groupId(){return T},get isSticky(){return j},get topNeighbours(){return Y("top")},get leftNeighbours(){return Y("left")},get rightNeighbours(){return Y("right")},get bottomNeighbours(){return Y("bottom")},get isGroupHeaderVisible(){return S},get activityId(){if(_._t42)return _._t42.activityId;const e=te();return e?e.activityId:void 0},get activityWindowId(){if(_._t42)return _._t42.activityWindowId;const e=te();return e?e.activityWindowId:void 0},get windowType(){return t.windowType||"electron"},get zoomFactor(){return J},get screen(){if("undefined"!=typeof window&&window.glue42gd)return $n.getMonitor(ne.bounds,window.glue42gd.monitors)},get placementSettings(){return Object.assign({},q)},get jumpList(){return V},get allowWorkspaceDrop(){return U},get isPinned(){return H},maximize:function(e,t){return $n.callbackifyPromise(()=>"maximized"===W?Promise.resolve(ne):n.maximize(ne),e,t)},restore:function(e,t){return $n.callbackifyPromise(()=>"normal"===W?Promise.resolve(ne):n.restore(ne),e,t)},minimize:function(e,t){return $n.callbackifyPromise(()=>"minimized"===W?Promise.resolve(ne):n.minimize(ne),e,t)},maximizeRestore:function(e,t){return $n.callbackifyPromise(()=>n.maximizeRestore(ne),e,t)},collapse:function(e,t){return $n.callbackifyPromise(()=>$?Promise.resolve(ne):n.collapse(ne),e,t)},expand:function(e,t){return $n.callbackifyPromise(()=>$?n.expand(ne):Promise.resolve(ne),e,t)},toggleCollapse:function(e,t){return $n.callbackifyPromise(()=>n.toggleCollapse(ne),e,t)},focus:function(e,t){return $n.callbackifyPromise(()=>C?Promise.resolve(ne):n.focus(ne),e,t)},activate:function(e,t){return $n.callbackifyPromise(()=>C?Promise.resolve(ne):n.activate(ne),e,t)},moveResize:z,setTitle:function(e,t,i){return $n.callbackifyPromise(()=>{if(Rt(e))throw new Error("`newTitle` must not be null or undefined.");return e===b?Promise.resolve(ne):n.setTitle(ne,e)},t,i)},setStyle:function(e,t,i){return $n.callbackifyPromise(()=>{if(!e||0===Object.keys(e).length||Object.keys(e).every(e=>!e))throw new Error("Invalid style arguments: "+JSON.stringify(e));if(e&&void 0!==e.focus){if("boolean"!=typeof e.focus)throw new Error("Focus must be a boolean value. Currently, only `focus: true` is supported.");!1===e.focus&&console.warn("`focus: false` is not supported!")}if(e&&void 0!==e.hidden&&"boolean"!=typeof e.hidden)throw new Error("The `hidden` property must hold a boolean value.");for(const t of["minHeight","maxHeight","minWidth","maxWidth"]){const n=e,i=n[t];if(t in e){if(Rt(i)){delete n[t];continue}if(!kt(n[t]))throw new Error(`"${t}" must be a number`)}}return n.setStyle(ne,e)},t,i)},setOnTop:function(e,t,i){return $n.callbackifyPromise(()=>{if("string"==typeof e){if("always"!==e)throw new Error("`onTop` must hold a `always` value.")}else if("boolean"!=typeof e)throw new Error("`onTop` must hold a boolean or `always` value.");return n.setOnTop(ne,e)},t,i)},resetButtons:function(e,t,i){return $n.callbackifyPromise(()=>n.resetButtons(ne,e),t,i)},getButtons:function(){return n.getButtons(ne)},setSizeConstraints:function(e,t,i){return $n.callbackifyPromise(()=>{if(!e||Object.keys(e).every(e=>void 0===e))throw new Error("The properties of `constraints` cannot be null or undefined.");return n.setSizeConstraints(ne,e)},t,i)},getSizeConstraints:function(){return n.getSizeConstraints(ne)},navigate:function(e,t,i){if("function"==typeof t)return $n.callbackifyPromise(()=>{if(Nt(e))throw new Error("The new URL must be a non-empty string.");return n.navigate(ne,e)},t,i);if(Nt(e))throw new Error("The new URL must be a non-empty string.");if((null==t?void 0:t.timeout)&&"number"!=typeof t.timeout)throw new Error("Timeout argument must be a valid number");return n.navigate(ne,e,t)},addFrameButton:function(e,t,i){return $n.callbackifyPromise(()=>{if(void 0===e||0===Object.keys(e).length)throw new Error("Button info is not available.");if(Nt(e.buttonId))throw new Error("`buttonId` must not be null or undefined.");if(Nt(e.imageBase64))throw new Error("`imageBase64` must not be null or undefined.");return n.addFrameButton(ne,e)},t,i)},removeFrameButton:function(e,t,i){return $n.callbackifyPromise(()=>{if(Nt(e))throw new Error("`buttonId` must not be null or undefined.");return n.removeFrameButton(ne,e)},t,i)},setVisible:K,show:()=>K(!0),hide:()=>K(!1),center:async function(e){return e&&function(e){if("object"!=typeof e)throw Error("display argument must be a valid display object");if(!e.workArea||!e.scaleFactor)throw Error("display argument is not a valid display object")}(e),n.center(ne,e)},close:function(t,i){return void 0===t||"function"==typeof t?$n.callbackifyPromise(()=>{if(!e)throw new Error("The window is already closed.");return n.close(ne)},t,i):n.close(ne,t)},snap:function(e,t,i,r){return $n.callbackifyPromise(()=>{if(Rt(e))throw new Error(`A target window is not specified - ${"string"==typeof e?e:JSON.stringify(e)}`);if("string"==typeof e){const t=Vn.get(e);if(!t)throw new Error(`Invalid "target" parameter or no such window. Invoked with: ${e}`);e=t.API}return"string"==typeof t&&(t={direction:t,autoAlign:!0}),n.snap(ne,e,t)},i,r)},dragMove:function(e){return n.dragMove(ne,e)},showLoader:function(e){return n.showLoader(ne,e)},hideLoader:function(){return n.hideLoader(ne)},updateContext:function(e,t,i){return $n.callbackifyPromise(()=>{if(!Et(e))throw new Error('"context" must not be null or undefined.');return n.updateContext(ne,e,!1)},t,i)},lock:function(e,t){return $n.callbackifyPromise(()=>n.lock(ne),e,t)},unlock:function(e,t){return $n.callbackifyPromise(()=>n.unlock(ne),e,t)},getIcon:function(e,t){return $n.callbackifyPromise(()=>n.getIcon(ne),e,t)},setIcon:function(e,t,i){return $n.callbackifyPromise(()=>{if(Nt(e))throw new Error('"base64Image" must be a non-empty string.');return n.setIcon(ne,e)},t,i)},setFrameColor:function(e,t,i){return $n.callbackifyPromise(()=>{if(Nt(e))throw new Error('"frameColor" must be a non-empty string');return n.setFrameColor(ne,e)},t,i)},setTabTooltip:async function(e){if(Nt(e))throw new Error(`"${e}" must not be null or undefined`);return n.setTabTooltip(ne,e)},getTabTooltip:async function(){return n.getTabTooltip(ne)},attachTab:function(e,t,i,r){return $n.callbackifyPromise(()=>{var i;const r='Invalid "tab" parameter - must be an object with an "id" property or a string. Invoked for source window with ID:';if(Rt(e)){const t=`${r} ${"string"==typeof e?e:JSON.stringify(e)}`;throw new Error(t)}let o;if("string"==typeof e){if(o=null===(i=Vn.get(e))||void 0===i?void 0:i.API,Rt(o)){const e=`${r} ${"string"==typeof o?o:JSON.stringify(o)}`;throw new Error(e)}}else{if(Rt(e.id))throw new Error(r);o=e}const s={};return Rt(t)||("number"==typeof t?s.index=t:(s.selected=t.selected,s.index=t.index)),n.attachTab(ne,o,s)},i,r)},detachTab:function(e={},t,i){return $n.callbackifyPromise(()=>{const t={};return void 0!==e.relativeTo?("string"==typeof e.relativeTo?t.relativeTo=e.relativeTo:Rt(e.relativeTo.id)||(t.relativeTo=e.relativeTo.id),Rt(e.relativeDirection)||(t.relativeDirection=e.relativeDirection),Rt(e.width)||(t.width=e.width),Rt(e.height)||(t.height=e.height)):Rt(e.bounds)||(t.bounds=e.bounds),Rt(e.hideTabHeader)||(t.hideTabHeader=e.hideTabHeader),n.detachTab(ne,t)},t,i)},setTabHeaderVisible:function(e,t,i){return $n.callbackifyPromise(()=>{if("boolean"!=typeof e)throw new Error('"toBeTabHeaderVisible" must hold a boolean value.');return n.setTabHeaderVisible(ne,e)},t,i)},showPopup:function(e){return n.showPopup(ne,e)},createFlydown:function(e){return n.createFlydown(ne.id,e)},setModalState:function(e){return n.setModalState(ne.id,e||!1)},setZoomFactor:function(e,t,i){return $n.callbackifyPromise(()=>{if(isNaN(e))throw new Error("zoomFactor is not a number");return n.setZoomFactor(ne,e)},t,i)},zoomIn:function(e,t){return $n.callbackifyPromise(()=>n.zoomIn(ne),e,t)},zoomOut:function(e,t){return $n.callbackifyPromise(()=>n.zoomOut(ne),e,t)},showDevTools:function(){return n.showDevTools(ne)},capture:function(e){return n.capture(ne,e)},flash:function(e,t){const i={shouldFlash:!0,mode:"auto"};return"boolean"==typeof e&&(i.shouldFlash=e),void 0!==t&&(i.mode=t),n.flash(ne,i)},flashTab:function(e){const t={shouldFlash:!0};return"boolean"==typeof e&&(t.shouldFlash=e),n.flashTab(ne,t)},setSticky:function(e,t,i){return $n.callbackifyPromise(()=>{if("boolean"!=typeof e)throw new Error("`isSticky` must hold a boolean value.");return n.setSticky(ne,e)},t,i)},setAllowWorkspaceDrop:function(e){if("boolean"!=typeof e)throw new Error("`allowWorkspaceDrop` must hold a boolean value.");return n.setAllowWorkspaceDrop(ne,e)},pin:function(){return n.pin(ne)},unpin:function(){return n.unpin(ne)},print:function(e){return n.print(ne,e)},printToPDF:function(e){return n.printToPDF(ne,e)},place:function(e){return n.place(ne,e)},clearPlacement:function(e){return n.clearPlacement(ne,e)},ungroup:function(t){return new Promise((i,r)=>{const o=Q((t,n,r)=>{e===t.id&&(o(),i(ne))});n.ungroup(ne,t).catch(e=>{o(),r(e)})})},refresh:function(e){return n.refresh(ne,e)},goBack:function(){return n.goBack(ne)},goForward:function(){return n.goForward(ne)},download:function(e,t){return n.download(ne,e,t)},configure:function(e){return n.configureWindow(ne,e)},getConfiguration:function(){return n.getWindowConfiguration(ne)},getDockingPlacement:function(){return n.getDockingPlacement(ne)},setDockingConfig:function(e){return n.setDockingConfig(ne,e)},getDockingConfig:function(){return n.getDockingConfig(ne)},dock:function(e){return n.dock(ne,e)},undock:function(e){return n.undock(ne,e)},clone:async function(e){return n.clone(ne,e)},executeCode:async function(e){if(!e)throw new Error("Code argument is missing");if("string"!=typeof e)throw new Error("Code argument must be a valid string");return(await n.executeCode(ne,e)).result},getChannel:X,getChannels:async function(){return new Xn(await X()).all()},startDrag:function(e){return n.startDrag(ne,e)},showDialog:function(e){if((null==e?void 0:e.timerDuration)&&isNaN(null==e?void 0:e.timerDuration))throw new Error("timerDuration must be a number");if((null==e?void 0:e.showTimer)&&"boolean"!=typeof(null==e?void 0:e.showTimer))throw new Error("showTimer must be a boolean");return n.showDialog(ne,e)},onClose:function(t){if(!jt(t))throw new Error("callback should be a function");return void 0===e&&t(ne),l.add("onClose",t)},onUrlChanged:function(e){return Z("onUrlChanged",e)},onTitleChanged:function(e){if(!jt(e))throw new Error("callback should be a function");return e(ne.title,ne),Z("onTitleChanged",e)},onFrameButtonAdded:function(e){return Z("onFrameButtonAdded",e)},onFrameButtonRemoved:function(e){return Z("onFrameButtonRemoved",e)},onFrameButtonClicked:function(e){return Z("onFrameButtonClicked",e)},onCollapsed:function(e){if(!jt(e))throw new Error("callback should be a function");return $&&e(ne),l.add("collapsed",e)},onExpanded:function(e){if(!jt(e))throw new Error("callback should be a function");return $||e(ne),l.add("expanded",e)},onMinimized:function(e){return"minimized"===W?Z("minimized",e,[ne]):Z("minimized",e)},onMaximized:function(e){return"maximized"===W?Z("maximized",e,[ne]):Z("maximized",e)},onNormal:function(e){return"normal"===W?Z("normal",e,[ne]):Z("normal",e)},onAttached:function(e){return Z("attached",e)},onDetached:function(e){return Z("detached",e)},onVisibilityChanged:function(e){return Z("visibility-changed",e)},onContextUpdated:function(e){return Z("context-updated",e)},onLockingChanged:function(e){return Z("lock-changed",e)},onBoundsChanged:function(e){return Z("bounds-changed",e)},onFrameColorChanged:function(e){return Z("frame-color-changed",e)},onFocusChanged:function(e){return Z("focus-changed",e)},onStickyChanged:function(e){return Z("sticky-changed",e)},onGroupChanged:Q,onWindowAttached:function(e){return Z("window-attached",e)},onWindowDetached:function(e){return Z("window-detached",e)},onTabSelectionChanged:function(e){return Z("tab-selection-changed",e)},onTabHeaderVisibilityChanged:function(e){return Z("tab-header-visibility-changed",e)},onClosing:function(e){if(!jt(e))throw new Error("callback must be a function");return n.onClosing((t,n,i)=>{const r=e(i);(null==r?void 0:r.then)?r.then(t).catch(n):t()},ne)},onRefreshing:function(e){if(!jt(e))throw new Error("callback must be a function");return n.onRefreshing((t,n,i)=>{const r=e(i);(null==r?void 0:r.then)?r.then(t).catch(n):t()},ne)},onZoomFactorChanged:function(e){return Z("zoom-factor-changed",e)},onPlacementSettingsChanged:function(e){return Z("placementSettingsChanged",e)},onNeighboursChanged:function(e){return Z("neighbours-changed",e)},onDockingChanged:function(e){return Z("docking-changed",e)},onNavigating:function(e){if(!jt(e))throw new Error("callback must be a function");return n.onNavigating((t,n,i,r)=>{const o=e(r);(null==o?void 0:o.then)?o.then(t).catch(n):t()},ne)},onChannelRestrictionsChanged:function(e){if(!jt(e))throw new Error("callback must be a function");return Z("channel-restrictions-changed",e)},get tabs(){return function(){const e=Vn.list;return"tab"!==y.toLowerCase()?[]:Object.keys(e).reduce((t,n)=>{const i=e[n];return i&&i.API.tabGroupId&&void 0!==i.API.tabGroupId&&void 0!==ne.tabGroupId&&i.API.tabGroupId===ne.tabGroupId&&t.push(i.API),t},[]).sort((e,t)=>{if(e.tabIndex!==t.tabIndex){if(-1===e.tabIndex)return Number.MAX_SAFE_INTEGER;if(-1===t.tabIndex)return Number.MIN_SAFE_INTEGER}return e.tabIndex-t.tabIndex})}()},get isTabHeaderVisible(){return k},get isTabSelected(){return P},getApplication(){var e;return null===(e=r())||void 0===e?void 0:e.getApp(R)},getURL:()=>Promise.resolve(v),getTitle:()=>Promise.resolve(b),getBounds:()=>Promise.resolve(w),async getContext(){try{return await n.getContext(ne)}catch(e){return _}},setContext(e){if(!Et(e))throw new Error('"context" must not be null or undefined, set to empty object if you want to clear it out.');return n.updateContext(ne,e,!0)},getDisplay:()=>o().getByWindowId(e),resizeTo:(e,t)=>z({width:e,height:t}),moveTo:(e,t)=>z({top:e,left:t}),async getParentWindow(){var e;const t=M.parentInstanceId;if(t)return null===(e=Vn.list[t])||void 0===e?void 0:e.API},getChildWindows:async()=>Object.keys(Vn.list).map(e=>Vn.list[e].API).filter(t=>t.settings.parentInstanceId===e),joinChannel:t=>p().join(t,e),leaveChannel:()=>p().leave(e)};return{API:ne,Events:{handleUpdate:function(e){v=e.url,b=e.title,_=e.context||{},w=e.bounds,I=e.frameColor,C=e.focus,A=e.neighbours||{},T=e.groupId,S=e.isGroupHeaderVisible,k=e.isTabHeaderVisible,x=e.isGroupHibernated,E=e.isGroupVisible,P=e.isTabSelected,M=e.settings,O=e.isVisible,j=e.isSticky,$=e.isCollapsed,W=e.state,D=e.tabGroupId,L=e.frameId,G=e.isLocked,U=e.allowWorkspaceDrop,H=e.isPinned,J=e.zoomFactor,q=e.placementSettings},handleWindowClose:function(){void 0!==e&&(l.execute("onClose",ne),e=void 0)},handleWindowChangeState:async function(e){"collapsed"===e?$=!0:"expanded"===e?$=!1:W=e,await n.finished,l.execute(e,ne)},handleTitleChanged:function(e){b=e,n.finished.finally(()=>{l.execute("onTitleChanged",e,ne)})},handleVisibilityChanged:function(e){e!==O&&(O=e,l.execute("visibility-changed",ne))},handleUrlChanged:function(e){v=e,l.execute("onUrlChanged",e,ne)},handleWindowSettingsChanged:function(e){M=e,l.execute("settings-changed",ne)},handleContextUpdated:function(e){_=e,l.execute("context-updated",_,ne)},handleFrameIsLockedChanged:function(e){G=e,l.execute("lock-changed",ne)},handleBoundsChanged:function(e){w.top===e.top&&w.left===e.left&&w.width===e.width&&w.height===e.height||(w=e,l.execute("bounds-changed",ne))},handleFocusChanged:function(e){C=e,l.execute("focus-changed",ne)},handleFrameButtonAdded:function(e){const t=["buttonId","imageBase64","order","tooltip"].reduce((t,n)=>(t[n]=e[n],t),{});-1===B.map(e=>e.buttonId).indexOf(e.buttonId)&&B.push(t),l.execute("onFrameButtonAdded",t,ne)},handleFrameButtonRemoved:function(e){let t;B=B.reduce((n,i)=>(i.buttonId===e?t=i:n.push(i),n),[]),void 0!==t&&l.execute("onFrameButtonRemoved",t,ne)},handleFrameButtonClicked:function(e){const t=B.filter(t=>t.buttonId===e.buttonId);t.length>0&&l.execute("onFrameButtonClicked",t[0],ne)},handleFrameColorChanged:function(e){I=e,l.execute("frame-color-changed",ne)},handleFrameAttached:function(e,t,n){D=e,L=t,k=n,l.execute("frame-attached",ne)},handleFrameSelectionChanged:async function(t,i){let r;t===e?(P=!0,r=ne):(P=!1,r=Vn.get(t)?Vn.get(t).API:void 0);const o=Vn.get(i)?Vn.get(i).API:void 0;await n.finished,l.execute("tab-selection-changed",r,o,ne)},handleCompositionChanged:function(e){A=e.neighbors||{},F=e.index,l.execute("neighbours-changed",A,ne)},handleAllowWorkspaceDropChanged:function(e){U=e,l.execute("allow-workspace-drop-changed",ne)},handleIsPinnedChanged:function(e){H=e,l.execute("is-pinned-changed",ne)},handleGroupHeaderVisibilityChanged:function(e){S=e},handleTabHeaderVisibilityChanged:function(e){k!==e&&(k=e,l.execute("tab-header-visibility-changed",ne))},handleGroupChanged:function(e,t){N=e,T=null==e?void 0:e.id,Rt(e)||Rt(t)||l.execute("group-changed",ne,e,t)},handleAttached:async function(e,t,i,r,o){D=e,k=i,L=t,void 0!==r&&(G=r),await n.finished,o.forEach(e=>{e.Events.handleWindowAttached(ne)}),l.execute("attached",ne)},handleDetached:async function(e,t){D=void 0,P=!1,void 0!==e&&(G=e),await n.finished,t.forEach(e=>{e.Events.handleWindowDetached(ne)}),l.execute("detached",ne)},handleWindowAttached:function(e){l.execute("window-attached",e)},handleWindowDetached:function(e){l.execute("window-detached",e)},handleZoomFactorChanged:function(e){J=e,l.execute("zoom-factor-changed",ne)},handleIsStickyChanged:function(e){j=e,l.execute("sticky-changed",e,ne)},handlePlacementSettingsChanged:function(e){let t;const n=e;if(n.display){const e=o();if(e){const i=n.display-1;t=new Promise((t,n)=>{e.all().then(e=>{const n=e.find(e=>e.index===i);t(n)}).catch(n)})}else t=Promise.resolve(void 0)}else t=Promise.resolve(void 0);t.then(e=>{n.display=e,q=n,l.execute("placementSettingsChanged",ne)})},handleDockingChanged:function(e){l.execute("docking-changed",ne,{docked:e.docked,position:e.position,claimScreenArea:e.claimScreenArea})},handleChannelRestrictionsChanged:function(e){l.execute("channel-restrictions-changed",e)}},GroupCreationArgs:{get isGroupHibernated(){return x},get isGroupVisible(){return E}}}};function ei(e,t){const n=Vn.list;return Object.keys(n).reduce((i,r)=>{const o=n[r];return o.API.tabGroupId===t&&o.API.id!==e&&i.push(o),i},[])}function ti(e){return!(e&&!Object.keys(e).every(t=>void 0===e[t]))}var ni=new class{constructor(){this.GroupMethodName="T42.Group.Execute",this.WndMethodName="T42.Wnd.Execute",this._registry=En(),this._finished=Promise.resolve(),this._configuration={windowAvailableOnURLChanged:!0},this.unsubCallbacks={}}get hostInstance(){return this.agmTarget}get finished(){return this._finished}get configuration(){return this._configuration}init(e,t,n){this.agm=e,this.logger=n,this.agmTarget=t,this._registry.add("event",e=>{if("Closed"===e.type){Object.keys(this.unsubCallbacks).forEach(t=>{t.startsWith(e.windowId)&&delete this.unsubCallbacks[t]})}})}setConfiguration(e){this._configuration={...this._configuration,...e}}handleEvent(e){this._registry.execute("event",e)}async open(e){let t;this._finished=new Promise(e=>{t=e});try{const t=await this.agm.invoke("T42.Wnd.Create",e,this.agmTarget,{waitTimeoutMs:On,methodResponseTimeoutMs:Nn});if(void 0===t.returned)throw new Error("failed to execute T42.Wnd.Create - unknown reason");const n=t.returned.id,i=await Vn.waitFor(n);return this.configuration&&!this.configuration.windowAvailableOnURLChanged||setTimeout(()=>{"electron"===i.API.windowType&&i.Events.handleUrlChanged(i.API.url)},0),i.API}finally{t()}}async close(e,t){const n=await this.execute("close",{windowId:e.id,options:t},"Closed");return t?n.closed:e}async navigate(e,t,n){let i=12e4;return"object"==typeof n&&"number"==typeof n.timeout&&(i=1e3*n.timeout,delete n.timeout),await this.execute("navigate",{windowId:e.id,options:{url:t,urlLoadOptions:n},invocationOptions:{methodResponseTimeoutMs:i}},"UrlChanged"),e}async setStyle(e,t){var n;const i=[],r=e=>i.push(e);if(Rt(t.focus)||e.isFocused||r(e.focus()),!Rt(t.hidden)){const n=!t.hidden;r(e.setVisible(n))}if(Rt(t.onTop)||r(e.setOnTop(t.onTop)),!Nt(t.tabTooltip)||!Nt(t.tabToolTip)){const i=null!==(n=t.tabTooltip)&&void 0!==n?n:t.tabToolTip;r(e.setTabTooltip(i))}Nt(t.tabTitle)||r(this.execute("setTabTitle",{windowId:e.id,options:{tabTitle:t.tabTitle}}));const o={minHeight:t.minHeight,minWidth:t.minWidth,maxHeight:t.maxHeight,maxWidth:t.maxWidth};!ti(o)&&r(e.setSizeConstraints(o));const s={allowClose:t.allowClose,allowCollapse:t.allowCollapse,allowLockUnlock:t.allowLockUnlock,allowMaximize:t.allowMaximize,allowMinimize:t.allowMinimize};return!ti(s)&&r(e.resetButtons(s)),await Promise.all(i),e}async setSizeConstraints(e,t){return await this.execute("setSizeConstraints",{windowId:e.id,options:t}),e}async getSizeConstraints(e){return await this.execute("getSizeConstraints",{windowId:e.id})}async setTabTooltip(e,t){return await this.execute("setTabTooltip",{windowId:e.id,options:{tabTooltip:t}}),e}async getTabTooltip(e){return(await this.execute("getTabTooltip",{windowId:e.id})).tabTooltip}async resetButtons(e,t){return await this.execute("resetButtons",{windowId:e.id,options:t}),e}async getButtons(e){return await this.execute("getButtons",{windowId:e.id})}async setOnTop(e,t){return await this.execute("setOnTop",{windowId:e.id,options:{onTop:t}}),e}async setTitle(e,t){const n={windowId:e.id,options:{title:t}};return await this.execute("setTitle",n,"TitleChanged"),e}async setSticky(e,t){const n={windowId:e.id,options:{isSticky:t}};return await this.execute("setSticky",n),e}async setAllowWorkspaceDrop(e,t){const n={windowId:e.id,options:{allowWorkspaceDrop:t}};return await this.execute("setAllowWorkspaceDrop",n),e}async pin(e){const t={windowId:e.id};return await this.execute("pinTab",t),e}async unpin(e){const t={windowId:e.id};return await this.execute("unpinTab",t),e}async moveResize(e,t){return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?new Promise(async(n,i)=>{const r=this.areBoundsEqual(t,e);let o=!1;const s=()=>{o||(o=!0,c&&(c(),c=void 0),n(e),a&&(clearTimeout(a),a=void 0))};let a,c;r||(c=e.onBoundsChanged(e=>{this.areBoundsEqual(t,e)&&s()}));try{await this.execute("moveResize",{windowId:e.id,options:{bounds:t}})}catch(e){return void i(e)}r?s():a=setTimeout(()=>{s()},1e3)}):(await this.execute("moveResize",{windowId:e.id,options:{bounds:t}}),e)}async addFrameButton(e,t){return await this.execute("addButton",{windowId:e.id,options:t},"ButtonAdded"),e}async removeFrameButton(e,t){return await this.execute("removeButton",{windowId:e.id,options:t},"ButtonRemoved"),e}async activate(e){return await this.execute("activate",{windowId:e.id}),e}async focus(e){return await this.execute("focus",{windowId:e.id}),e}async maximizeRestore(e){return await this.execute("maximizeRestore",{windowId:e.id},"StateChanged"),e}async maximize(e){return await this.execute("maximize",{windowId:e.id},"StateChanged"),e}async restore(e){return await this.execute("restore",{windowId:e.id},"StateChanged"),e}async minimize(e){return await this.execute("minimize",{windowId:e.id},"StateChanged"),e}async collapse(e){return await this.execute("collapse",{windowId:e.id},"StateChanged"),e}async expand(e){return await this.execute("expand",{windowId:e.id},"StateChanged"),e}async toggleCollapse(e){return await this.execute("toggleCollapse",{windowId:e.id},"StateChanged"),e}async snap(e,t,n){const i={targetWindowId:t.id};return i.snappingEdge=n.direction,i.autoAlign=n.autoAlign,await this.execute("snap",{windowId:e.id,options:i},"CompositionChanged",`CompositionChanged-${t.id}`),e}dragMove(e,t){return this.execute("dragMove",{windowId:e.id,options:t})}async attachTab(e,t,n){return await this.execute("attachTab",{windowId:e.id,options:{index:n,sourceWindowId:t.id,targetWindowId:e.id}},`WindowFrameAdded-${t.id}`,`WindowFrameRemoved-${t.id}`),e}async detachTab(e,t){const n=["WindowFrameRemoved","WindowFrameAdded"];return Rt(null==t?void 0:t.relativeTo)?n.push("BoundsChanged"):(n.push("CompositionChanged"),n.push(`CompositionChanged-${t.relativeTo}`)),await this.execute("detachTab",{windowId:e.id,options:t},...n),e}async setVisible(e,t=!0){let n;return n=t?"show":"hide",await this.execute(n,{windowId:e.id},"VisibilityChanged"),e}async center(e,t){return await this.execute("center",{windowId:e.id,options:t}),e}async showLoader(e,t){return await this.execute("showLoadingAnimation",{windowId:e.id,options:t}),e}async hideLoader(e){return await this.execute("hideLoadingAnimation",{windowId:e.id}),e}async updateContext(e,t,n){let i;try{const r=this.swapUndefinedToNull(t),o=new Promise((t,n)=>{i=e.onContextUpdated(()=>{t()})});return await Promise.all([this.execute("updateContext",{windowId:e.id,context:r,replace:n}),o]),e}finally{i&&i()}}async getContext(e){return(await this.execute("getContext",{windowId:e.id})).context}async lock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!0}},"FrameIsLockedChanged"),e}async unlock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!1}},"FrameIsLockedChanged"),e}async getIcon(e){return(await this.execute("getIcon",{windowId:e.id,options:{}})).icon}async setIcon(e,t){return await this.execute("setIcon",{windowId:e.id,options:{dataURL:t}}),e}async setFrameColor(e,t){return await this.execute("setFrameColor",{windowId:e.id,options:{frameColor:t}},"FrameColorChanged"),e}async setTabHeaderVisible(e,t){return await this.execute("setTabHeaderVisible",{windowId:e.id,options:{toShow:t}},"TabHeaderVisibilityChanged"),e}async showGroupPopup(e,t){const n=this.validatePopupOptions(e,t);await this.executeGroup("showGroupPopup",{groupId:e,options:n})}async showPopup(e,t){const n=this.validatePopupOptions(e.id,t);return await this.execute("showPopupWindow",{windowId:e.id,options:n}),e}async createFlydown(e,t){if(!t)throw new Error("The options object is not valid!");const n={...t};n.horizontalOffset||(n.horizontalOffset=0),n.verticalOffset||(n.verticalOffset=0);const i=this.reformatFlydownOptions(e,n);return this.execute("setFlydownArea",{windowId:e,options:i}).then(()=>{const e=i.zones.map(e=>e.id);return i.zones.forEach(e=>{let n="function"==typeof e.flydownSize?e.flydownSize:()=>e.flydownSize;t.size instanceof Function&&e.flydownSize&&(n=async(n,i)=>{let r;return t.size instanceof Function&&(r=await t.size(n,i)),e.flydownSize instanceof Function&&e.flydownSize!==t.size?await e.flydownSize(n,i)||r:r||e.flydownSize}),this._registry.clearKey(`${i.targetId}_${e.id}`),this._registry.add(`${i.targetId}_${e.id}`,n)}),{destroy:()=>this.clearFlydownArea(i.targetId,e),options:n}})}async setModalState(e,t){return this.execute("setModalState",{windowId:e,options:{isModal:t}})}async autoArrange(e){return this.execute("autoArrange",{options:{displayId:e}})}async handleFlydownBoundsRequested(e,t){const n={zoneId:t.flydownId,flydownWindowBounds:t.flydownWindowBounds,flydownWindowId:t.flydownWindowId},i=await Promise.all(this._registry.execute(`${e}_${t.flydownId}`,n,()=>t.cancel=!0));if(1===i.length){const e={height:0,width:0,top:0,left:0},n="object"!=typeof i[0]||Array.isArray(i[0])?e:i[0];return{...t,flydownWindowBounds:n}}}async handleOnEventRequested(e,t){var n;const i=null!==(n=this.unsubCallbacks[e])&&void 0!==n?n:[];let r=!1;const o=[];return await Promise.all(i.map(e=>new Promise((n,i)=>{e(()=>{n()},()=>{i()},e=>{r=!0,o.push(e)},t)}))),{prevented:r,preventArgs:o}}async zoomIn(e){return await this.execute("zoomIn",{windowId:e.id}),e}async zoomOut(e){return await this.execute("zoomOut",{windowId:e.id}),e}async setZoomFactor(e,t){return await this.execute("setZoomFactor",{windowId:e.id,options:{zoomFactor:t}}),e}async showDevTools(e){return await this.execute("showDevTools",{windowId:e.id}),e}async capture(e,t){return(await this.execute("captureScreenshot",{windowId:e.id,options:{...t}})).data}async captureGroup(e,t){return(await this.execute("captureGroupScreenshot",{windowId:e[0],options:{groupWindowIds:e,...t}})).data}async flash(e,t){return await this.execute("flash",{windowId:e.id,options:{...t}}),e}async flashTab(e,t){return await this.execute("flashTab",{windowId:e.id,options:{...t}}),e}async configure(e,t){return this.execute("configure",{windowId:e,options:{...t}})}async print(e,t){return await this.execute("print",{windowId:e.id,options:{...t}}),e}async printToPDF(e,t){return(await this.execute("printToPDF",{windowId:e.id,options:{...t}})).filePath}async place(e,t){const n={...t};return t.display&&"current"!==t.display||(n.display=await e.getDisplay()),n.display&&"string"!=typeof n.display&&"number"!=typeof n.display&&(n.display=n.display.index+1),this.execute("place",{windowId:e.id,options:{...n}})}async clearPlacement(e,t){return this.execute("clearPlacement",{windowId:e.id,options:t})}async refresh(e,t){return await this.execute("refresh",{windowId:e.id,options:{ignoreCache:t}}),e}async download(e,t,n={}){"boolean"==typeof(null==n?void 0:n.silent)&&(n.enableDownloadBar=!n.silent);const i=await this.execute("downloadURL",{windowId:e.id,options:{url:t,options:n}});return{url:t,path:i.fullPath,size:i.fileSize}}async configureWindow(e,t){return await this.execute("configureWindow",{windowId:e.id,options:t}),e}async getWindowConfiguration(e){return await this.execute("getWindowConfiguration",{windowId:e.id})}async startDrag(e,t){return await this.execute("startDrag",{windowId:e.id,options:t}),e}showDialog(e,t){return new Promise((n,i)=>{const r=$n.generateId(),o=this._registry.add("event",t=>{if("DialogResult"===t.type&&t.windowId===e.id&&t.data.token===r){o();const e=t.data;"status"in e&&("failed"===e.status?i(new Error(e.message)):"successful"===e.status&&n(e.result))}});this.execute("showDialog",{windowId:e.id,options:Object.assign({},{...t},{token:r})})})}async execute(e,t,...n){return this.executeCore(this.WndMethodName,e,t,...n)}async executeGroup(e,t,...n){return this.executeCore(this.GroupMethodName,e,t,...n)}async ungroup(e,t){const n={windowId:e.id,options:t};return await this.execute("ungroup",n),e}async updateJumpList(e,t){const n={windowId:e,options:t};await this.execute("updateJumplist",n)}async getJumpList(e){const t={windowId:e};return await this.execute("getJumplist",t)}onClosing(e,t){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===t.windowType?n.addCloseHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnClosing")}onGroupClosing(e,t){return this.nonWindowHandlersCore(t.id,"OnClosing",!0,e)}onRefreshing(e,t){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===t.windowType?n.addRefreshHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnRefreshing")}onNavigating(e,t){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===t.windowType?n.addWillNavigateHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnNavigating")}async clone(e,t){const n={windowId:e.id,options:t},i=await this.execute("clone",n);return(await Vn.waitFor(i.id)).API}async executeCode(e,t){const n={windowId:e.id,options:{code:t}};return this.execute("executeCode",n)}async goBack(e){await this.execute("goBack",{windowId:e.id})}async goForward(e){await this.execute("goForward",{windowId:e.id})}async getDockingPlacement(e){return this.execute("getDockingPlacement",{windowId:e.id})}setDockingConfig(e,t){return this.execute("setDockingConfig",{windowId:e.id,options:t})}getDockingConfig(e){return this.execute("getDockingConfig",{windowId:e.id})}dock(e,t){return this.execute("dock",{windowId:e.id,options:t})}undock(e,t){return this.execute("undock",{windowId:e.id,options:t})}clearCallbacks(e){Object.keys(this.unsubCallbacks).forEach(t=>{t.startsWith(e)&&delete this.unsubCallbacks[t]})}nonWindowHandlers(e,t,n){return this.nonWindowHandlersCore(t,n,!1,e)}nonWindowHandlersCore(e,t,n,i){const r=`${e}-${t}`,o=()=>{},s=()=>{var s;if(this.unsubCallbacks[r]){const e=this.unsubCallbacks[r];this.unsubCallbacks[r]=e.filter(e=>e!==i),0===this.unsubCallbacks[r].length&&delete this.unsubCallbacks[r]}if(0===(null!==(s=this.unsubCallbacks[r])&&void 0!==s?s:[]).length){const i={unsubscribe:!0};n?this.executeGroup(t,{groupId:e,options:i}).catch(o):this.execute(t,{windowId:e,options:i}).catch(o)}};return this.unsubCallbacks[r]?(this.unsubCallbacks[r].push(i),s):(this.unsubCallbacks[r]=[i],n?this.executeGroup(t,{groupId:e}).catch(o):this.execute(t,{windowId:e}).catch(o),s)}reformatFlydownOptions(e,t){const n=(e,n)=>{if(t[n]&&(void 0===e[n]||null===e[n])){const i=t[n];e[n]=i}},i=t.zones.map(e=>(n(e,"windowId"),n(e,"targetLocation"),!t.size||void 0!==e.flydownSize&&null!==e.flydownSize||(e.flydownSize=t.size),e.flydownBounds=e.flydownSize,e.flydownId=e.windowId,e.targetLocation||(e.targetLocation="bottom"),e));return{...t,zones:i,targetId:e,flydownBounds:t.size,flydownActiveArea:t.activeArea}}clearFlydownArea(e,t){return this.execute("clearFlydownWindowArea",{windowId:e,options:{}}).then(()=>{t.forEach(t=>{this._registry.clearKey(`${e}_${t}`)})})}executeWithoutToken(e,...t){const n=[],i=null==t?void 0:t.filter(e=>!Rt(e)).map(t=>new Promise(i=>{const[r,o=e.windowId]=t.split("-");n.push(this._registry.add("event",e=>{e.type===r&&e.windowId===o&&i()}))})),r=new Promise((t,n)=>{this.agm.invoke("T42.Wnd.Execute",e,this.agmTarget,{waitTimeoutMs:On,methodResponseTimeoutMs:Nn}).then(e=>{e.returned&&e.returned.errorMsg?n(e):t(e.returned)}).catch(e=>n(e))});return Promise.all([r,...i]).then(e=>e[0]).finally(()=>{n.forEach(e=>e())})}async executeCore(e,t,n,...i){const{invocationOptions:r,...o}=n,s={...o,command:t};let a;this._finished=new Promise(e=>{a=e});try{return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?await this.executeWithoutToken(s,...i):await this.executeWithToken(e,s,r)}finally{a()}}async executeWithToken(e,t,n){let i;try{const r=$n.generateId(),o=new Promise(t=>{i=this._registry.add("event",n=>{n.token===r&&(this.logger.debug(`"${e}" token: ${r} received`),t())})}),s=new Promise((i,o)=>{t.token=r,n?n.methodResponseTimeoutMs?n.waitTimeoutMs||(n.waitTimeoutMs=On):n.methodResponseTimeoutMs=Nn:n={waitTimeoutMs:On,methodResponseTimeoutMs:Nn},this.logger.debug(`executing "${e}" with options: ${JSON.stringify(t)} and token: ${r}`),this.agm.invoke(e,t,this.agmTarget,n).then(t=>{this.logger.debug(`"${e}" returned: ${JSON.stringify(t)}`),t.returned&&t.returned.errorMsg?o(new Error(t.returned.errorMsg)):i(t.returned)}).catch(t=>{const n=$n.typedError(t);this.logger.error(`"${e}" failed:`,n),o(n)})});return(await Promise.all([s,o]))[0]}finally{i&&i()}}areBoundsEqual(e,t){const n=t.bounds,i=t.settings;let r=e.height,o=e.width;e.height<i.minHeight&&(r=i.minHeight),e.height>i.maxHeight&&(r=i.maxHeight),e.width<i.minWidth&&(o=i.minWidth),e.width>i.maxWidth&&(o=i.maxWidth);const s=!r||n.height===r,a=!o||n.width===o,c=!e.left||n.left===e.left,d=!e.top||n.top===e.top;return s&&a&&c&&d}swapUndefinedToNull(e){try{const t={};for(const n of Object.keys(e)){let i=e[n];void 0===i&&(i=null),t[n]=i}return t}catch{return e}}validatePopupOptions(e,t){if(!t)throw new Error("The options object is not valid!");const n={...t};n.targetLocation||(n.targetLocation="bottom");return{...n,popupBounds:n.size,targetId:e,popupId:n.windowId}}};class ii{constructor(e,t,n,i,r,o,s){this._registry=En(),this._agm=e,this._logger=t.subLogger("gd-env"),this._windowId=o,this._groupId=s,this._appsController=n,this._displayAPIGetter=i,this._channelsAPIGetter=r}init(){return new Promise((e,t)=>{this._agm.register("T42.Wnd.OnEventWithResponse",(e,t)=>this.respondToEvent(e)),new Promise((n,i)=>{this._agm.subscribe("T42.Wnd.OnEvent",{target:"best",arguments:{withConfig:!0},waitTimeoutMs:On,methodResponseTimeout:On,onData:t=>{if("Configuration"===t.data.type)return this._configuration=t.data,void ni.setConfiguration(this._configuration);this.updateWindow(t.data,e),ni.handleEvent(t.data)},onConnected:e=>{this._agmInstance=e,ni.init(this._agm,this._agmInstance,this._logger.subLogger("executor"))}}).catch(e=>{var n;const i=`${null===(n=null==e?void 0:e.method)||void 0===n?void 0:n.name} - ${JSON.stringify(null==e?void 0:e.called_with)} - ${null==e?void 0:e.message}`;t(new Error(i))})})})}get executor(){return ni}open(e,t,n){n=n||{};const i={...n};return void 0!==i.relativeTo&&"string"!=typeof i.relativeTo&&(i.relativeTo=i.relativeTo.id||""),i.name=e,i.url=t,i.windowState=n.windowState||n.state,delete i.state,this.executor.open(i)}createFlydown(e,t){return this.executor.createFlydown(e,t)}async showPopup(e,t){const n=Vn.get(e);await this.executor.showPopup(n.API,t)}tabAttached(e){return this._registry.add("tab-attached",e)}tabDetached(e){return this._registry.add("tab-detached",e)}onWindowFrameColorChanged(e){return this._registry.add("frame-color-changed",e)}onEvent(e){return this._registry.add("window-event",e)}my(){return this._windowId}myGroup(){var e,t;return null!==(t=null===(e=Vn.get(this._windowId))||void 0===e?void 0:e.API.groupId)&&void 0!==t?t:this._groupId}onCompositionChanged(e){return this._registry.add("composition-changed",e)}onGroupHeaderVisibilityChanged(e){return this._registry.add("group-header-changed",e)}onGroupVisibilityChanged(e){return this._registry.add("group-visibility-changed",e)}onGroupStateChanged(e){return this._registry.add("group-state-changed",e)}onWindowGotFocus(e){return this._registry.add("got-focus",e)}onWindowLostFocus(e){return this._registry.add("lost-focus",e)}onWindowsAutoArrangeChanged(e){return this._registry.add("windows-auto-arranged-changed",e)}respondToEvent(e){return"ShowFlydownBoundsRequested"===e.type?this.executor.handleFlydownBoundsRequested(e.data.windowId,e.data):"OnClosing"===e.type||"OnRefreshing"===e.type||"OnNavigating"===e.type?this.executor.handleOnEventRequested(e.data.callbackId,e.data.args):Promise.reject(new Error(`There isn't a handler for ${e.type}`))}updateWindow(e,t){const n=this.getExtendedStreamEvent(e);if("Snapshot"===e.type){return e.windows.forEach(e=>{const t=Vn.get(e.id);t?(t.Events.handleUpdate(this.mapToWindowConstructorOptions(e)),t.GroupCreationArgs=this.mapToGroupCreationArgs(e)):this.createWindowFromSnapshot(e.id,e),this._registry.execute("window-event",n)}),void t(this)}if("CommandExecuted"===e.type)return void this._registry.execute("window-event",n);if("Created"===e.type){const t=e;return this.createWindowFromStream(t.windowId,t.data||{}),void this._registry.execute("window-event",n)}if("OnGroupVisibilityChanged"===e.type){const t=e;return this._registry.execute("group-visibility-changed",t.data),void this._registry.execute("window-event",e)}if("OnGroupStateChanged"===e.type){const t=e;return this._registry.execute("group-state-changed",t.data),void this._registry.execute("window-event",e)}if("OnWindowsAutoArrangeChanged"===e.type){const t=e;return this._registry.execute("windows-auto-arranged-changed",t.data),void this._registry.execute("window-event",e)}const i=Vn.get(e.windowId);if(!i)return void this._logger.error(`received update for unknown window. Stream:', ${JSON.stringify(e,null,4)}`);const r=i.API,o=i.Events;if("BoundsChanged"===e.type){const t=e;o.handleBoundsChanged(t.data)}if("UrlChanged"===e.type){const t=e;Vn.setUrlChangedState(t.windowId),o.handleUrlChanged(t.data)}if("TitleChanged"===e.type){const t=e;o.handleTitleChanged(t.data)}if("IsStickyChanged"===e.type){const t=e;o.handleIsStickyChanged(t.data)}if("VisibilityChanged"===e.type&&o.handleVisibilityChanged(e.data),"ContextChanged"===e.type&&o.handleContextUpdated(e.data),"StateChanged"===e.type&&o.handleWindowChangeState(e.data),"FrameColorChanged"===e.type&&(o.handleFrameColorChanged(e.data),this._registry.execute("frame-color-changed",r)),"CompositionChanged"===e.type){const t=e;o.handleCompositionChanged(t.data),Vn.setCompositionChangedState(i),this._registry.execute("composition-changed",t.data)}if("GroupHeaderVisibilityChanged"===e.type){const t=e;o.handleGroupHeaderVisibilityChanged(t.data.groupHeaderVisible),this._registry.execute("group-header-changed",t.data)}if("FocusChanged"===e.type){const t=e;this.focusChanged(o,r,t.data)}if("WindowFrameChanged"===e.type&&(o.handleFrameAttached(e.data.frameId,e.data.frameId,e.data.isTabHeaderVisible),this._registry.execute("frame-changed")),"WindowFrameAdded"===e.type){const t=ei(r.id,e.data.frameId),n=e.data;o.handleAttached(n.frameId,n.frameId,n.isTabHeaderVisible,n.isLocked,t).then(async()=>{t.length>0&&(await ni.finished,this._registry.execute("tab-attached",r,e.data.frameId,e.data.isTabHeaderVisible))})}if("WindowFrameRemoved"===e.type){const t=r.tabGroupId,n=ei(r.id,t);o.handleDetached(e.data.isLocked,n).then(async()=>{n.length>0&&(await ni.finished,this._registry.execute("tab-detached",r,e.data.frameId,r.tabGroupId))})}"TabHeaderVisibilityChanged"===e.type&&o.handleTabHeaderVisibilityChanged(e.data.isTabHeaderVisible),"FrameSelectionChanged"===e.type&&o.handleFrameSelectionChanged(e.data.newWindowId,e.data.prevWindowId),"ButtonClicked"===e.type&&o.handleFrameButtonClicked(e.data),"ButtonAdded"===e.type&&o.handleFrameButtonAdded(e.data),"ButtonRemoved"===e.type&&o.handleFrameButtonRemoved(e.data),"WindowZoomFactorChanged"===e.type&&o.handleZoomFactorChanged(e.data),"Closed"===e.type&&(Vn.remove(i),o.handleWindowClose()),"FrameIsLockedChanged"===e.type&&o.handleFrameIsLockedChanged(e.data),"PlacementSettingsChanged"===e.type&&o.handlePlacementSettingsChanged(e.data),"DockingChanged"===e.type&&o.handleDockingChanged(e.data),"AllowWorkspaceDropChanged"===e.type&&o.handleAllowWorkspaceDropChanged(e.data),"IsPinnedChanged"===e.type&&o.handleIsPinnedChanged(e.data),"WindowChannelRestrictionsChanged"===e.type&&o.handleChannelRestrictionsChanged(e.data),this._registry.execute("window-event",n)}createWindowFromSnapshot(e,t){const n=this.createWindowCore(e,t);Vn.add(n,{ready:!0,urlChanged:!0,compositionChanged:!0})}createWindowFromStream(e,t){var n;const i=this.createWindowCore(e,t),r="remote"===i.API.windowType,o="electron"===i.API.windowType&&"frameless"===i.API.mode,s=!1===i.API.isVisible;let a=!1,c=!1;r&&(a=!0),(o||s)&&(c=!0),r||(a=!(null===(n=this._configuration)||void 0===n?void 0:n.windowAvailableOnURLChanged)),Vn.add(i,{ready:!0,urlChanged:a,compositionChanged:c})}createWindowCore(e,t){const n=Yn(e,this.mapToWindowConstructorOptions(t),ni,this._logger,this._appsController,this._displayAPIGetter,this._channelsAPIGetter,this._agm);return n.GroupCreationArgs=this.mapToGroupCreationArgs(t),n}async focusChanged(e,t,n){e.handleFocusChanged(n);try{this._configuration.windowAvailableOnURLChanged||await Vn.waitFor(t.id)}catch(e){return}n?this._registry.execute("got-focus",t):this._registry.execute("lost-focus",t)}mapToWindowConstructorOptions(e){return{name:e.name,context:e.context,bounds:e.bounds,url:e.url,title:e.title,isVisible:e.isVisible,focus:e.isFocused,state:e.state,frameColor:e.frameColor,groupId:e.groupId,neighbours:e.neighbors,isFocused:e.isFocused,isGroupHeaderVisible:e.groupHeaderVisible,isCollapsed:e.isCollapsed,tabGroupId:e.frameId,frameId:e.frameId,mode:e.mode,isTabHeaderVisible:e.isTabHeaderVisible,isTabSelected:e.isActiveTab,settings:e.settings,windowType:e.windowType,zoomFactor:e.zoomFactor,isLocked:e.isLocked,placementSettings:e.placementSettings,isSticky:e.isSticky,tabIndex:e.tabIndex,frameButtons:e.frameButtons,jumpListOptions:e.jumpList,applicationName:e.applicationName,allowWorkspaceDrop:e.allowWorkspaceDrop,isPinned:e.isPinned}}mapToGroupCreationArgs(e){return{isGroupHibernated:e.isGroupHibernated,isGroupVisible:e.isGroupVisible}}getExtendedStreamEvent(e){try{if(!e.windowId)return e;const t=Vn.get(e.windowId);if(!t)return e;const n={state:e.type,windowName:t.API.name,...e};return"WindowFrameAdded"===n.state&&(n.state="TabAttached"),"StateChanged"===n.state&&(n.state=n.data.charAt(0).toUpperCase()+n.data.slice(1)),"ButtonAdded"===n.state&&(n.state="FrameButtonAdded"),"ButtonRemoved"===n.state&&(n.state="FrameButtonRemoved"),n}catch(t){return e}}}var ri=(e,t)=>{const n=En(),i=[];let r,o;async function s(e,n,...i){return await t.execute(e,n,...i),d}function a(){const e=[];return i.forEach(t=>{const n=c(t);void 0!==n&&e.push(n)}),e}function c(e){return Vn.get(e)?Vn.get(e).API:void 0}const d={id:e,get windows(){return a()},find:function(e,t,n){let i;"string"==typeof e?i=e:Rt(e)||(i=e.id);const r=c(i);if(r)return"function"==typeof t&&t(r),r;"function"==typeof n&&n(`No window with ID: ${i}`)},get isHeaderVisible(){return void 0===a().find(e=>!e.isGroupHeaderVisible)},get isHibernated(){return r},get isVisible(){return o},showHeader:(e,t)=>$n.callbackifyPromise(()=>s("setGroupHeaderVisibility",{windowId:i[0],options:{toShow:!0}},...i.map(e=>`GroupHeaderVisibilityChanged-${e}`)),e,t),hideHeader:(e,t)=>$n.callbackifyPromise(()=>s("setGroupHeaderVisibility",{windowId:i[0],options:{toShow:!1}},...i.map(e=>`GroupHeaderVisibilityChanged-${e}`)),e,t),getTitle:async()=>(await t.execute("getGroupTitle",{windowId:i[0]})).title,setTitle:async e=>{if(Nt(e))throw new Error("`title` must not be null or undefined.");return s("setGroupTitle",{windowId:i[0],options:{title:e}})},capture:e=>t.captureGroup(i,e),maximize:(e,t)=>$n.callbackifyPromise(()=>s("maximizeGroup",{windowId:i[0]},...i.map(e=>`StateChanged-${e}`)),e,t),restore:(e,t)=>$n.callbackifyPromise(()=>s("restoreGroup",{windowId:i[0]},...i.map(e=>`StateChanged-${e}`)),e,t),show:n=>{if(!Rt(n)&&!Ot(n))throw new Error("Activate flag must be a boolean!");return n=!!Rt(n)||n,t.executeGroup("showGroup",{groupId:e,options:{activate:n}})},hide:()=>t.executeGroup("hideGroup",{groupId:e}),reload:()=>t.executeGroup("reloadGroup",{groupId:e}),close:()=>t.executeGroup("closeGroup",{groupId:e}),showPopup:n=>t.showGroupPopup(e,n),onHeaderVisibilityChanged:function(e){return n.add("header-visibility-changed",e)},onWindowAdded:function(e){return n.add("window-added",e)},onWindowRemoved:function(e){return n.add("window-removed",e)},onVisibilityChanged:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return n.add("group-visibility-changed",e)},onClosing:function(e){if("function"!=typeof e)throw new Error("callback must be a function");return t.onGroupClosing((t,n,i)=>{const r=e(i);(null==r?void 0:r.then)?r.then(t).catch(n):t()},d)}},h={get windows(){return i},addWindow:async function(e){var s,a,c,h;if(-1===i.indexOf(e)){i.push(e);const u=Vn.get(e);u.Events.handleGroupChanged(d,void 0),r=null!==(a=null!==(s=u.GroupCreationArgs.isGroupHibernated)&&void 0!==s?s:r)&&void 0!==a&&a,o=null===(h=null!==(c=u.GroupCreationArgs.isGroupVisible)&&void 0!==c?c:o)||void 0===h||h,await t.finished,n.execute("window-added",d,u.API)}},removeWindow:async function(e){const r=i.indexOf(e.API.id);-1!==r&&(i.splice(r,1),e.Events.handleGroupChanged(void 0,d),await t.finished,n.execute("window-removed",d,e.API))},handleGroupHeaderVisibilityChanged:function(e){n.execute("header-visibility-changed",d)},handleGroupVisibilityChanged:function(e){o=e,n.execute("group-visibility-changed",d)},handleGroupHibernateChanged:function(e){r=e}};return{groupAPI:d,groupInternal:h}},oi=(e,t)=>{const n=En(),i={};let r=-1;const o=Vn.list;function s(e,t,n){let r;"string"==typeof e?r=e:Rt(e)||(r=e.id);const o=Object.values(i).find(e=>e.groupAPI.windows.filter(e=>e.id===r).length);if(o)return"function"==typeof t&&t(o.groupAPI),o.groupAPI;"function"==typeof n&&n("Cannot find the group of the window.")}function a(e){return e?new Promise((t,n)=>{const r=i[e];if(r)t(r.groupAPI);else{const n=c(i=>{i.id===e&&(n(),t(i))})}}):Promise.reject(new Error("groupId must be defined"))}function c(e){return n.add("group-added",e)}function d(t,r){const o=function(t){if(i.hasOwnProperty(t))return i[t];{const r=ri(t,e.executor);i[t]=r;const o=r.groupAPI;return n.execute("group-added",o),r}}(t);return o.groupInternal.addWindow(r),o}function h(e,t){e&&(e.groupInternal.removeWindow(t),function(e){const t=e.groupAPI;0===t.windows.length&&(delete i[t.id],ni.clearCallbacks(t.id),n.execute("group-removed",t))}(e))}function u(e){let t;return"string"==typeof e?t=e:Rt(e)||(t=e.id),Object.values(i).find(e=>e.groupInternal.windows.filter(e=>e===t).length)}function l(e){if(!e||"string"!=typeof e)throw new Error("Please provide a valid Group ID as a non-empty string!")}Object.keys(o).forEach(e=>{const t=o[e],n=t.API.groupId,i=t.API.id;Nt(n)||d(n,i)}),Vn.onRemoved(e=>{h(u(e.API),e)}),e.onCompositionChanged(e=>{!function(e){const t=e.groupId,r=e.windowId,o=Vn.get(r);if(!o)return;const s=u(o.API);if(Rt(t))return void h(s,o);if(Rt(s)&&!Rt(t))return void d(t,o.API.id);s.groupAPI.id!==t&&function(e,t,r){const o=e.API.id,s=i[t];h(s,e);const a=d(r,o);e.Events.handleGroupChanged(a.groupAPI,s.groupAPI),n.execute("window-moved",o,t,r)}(o,s.groupAPI.id,t)}(e)}),e.onGroupHeaderVisibilityChanged(e=>{const t=s(e.windowId);if(void 0!==t){const n=i[t.id];-1===r&&(r=t.windows.length),r--,0===r&&(r=-1,n.groupInternal.handleGroupHeaderVisibilityChanged(e))}}),e.onGroupVisibilityChanged(e=>{const t=i[e.groupId];t&&t.groupInternal.handleGroupVisibilityChanged(e.visible)}),e.onGroupStateChanged(e=>{const t=i[e.groupId];"hibernated"===e.state?((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!0),n.execute("group-hibernated",e.groupId)):"resumed"===e.state&&((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!1),n.execute("group-resumed",t.groupAPI))});const p={get my(){return function(){var t;return s(null!==(t=e.myGroup())&&void 0!==t?t:e.my())}()},create:async function(e){if(Rt(e))throw new Error("options must be defined");if(Rt(e.groups)||!Array.isArray(e.groups)||0===e.groups.length)throw new Error("options.groups must be defined");const{groupIds:t}=await ni.executeGroup("createGroups",{options:e}),n=t.map(e=>a(e));return Promise.all(n)},close:async function(e,t){if(Rt(e))throw new Error("group must be defined");let n="";if(n="string"==typeof e?e:e.id,Rt(t))throw new Error("options must be defined");await ni.executeGroup("closeGroup",{groupId:n,options:t})},list:function(e){const t=Object.keys(i).map(e=>{if(i[e])return i[e].groupAPI});return"function"==typeof e&&e(t),t},findGroupByWindow:s,waitForGroup:a,getMyGroup:function(){var t;return a(null!==(t=e.myGroup())&&void 0!==t?t:e.my())},onGroupAdded:c,onGroupRemoved:function(e){return n.add("group-removed",e)},hibernate:async function(e){return l(e),await ni.executeGroup("hibernateGroup",{groupId:e}),e},resume:async function(e,t){if(l(e),!Rt(t)&&!Ot(t))throw new Error("Activate flag must be a boolean!");t=!!Rt(t)||t,await ni.executeGroup("resumeGroup",{groupId:e,options:{activate:t}})},onHibernated:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return n.add("group-hibernated",e)},onResumed:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return n.add("group-resumed",e)}};return{groupsAPI:p,groupsEvents:{onWindowMoved:function(e){return n.add("window-moved",e)}}}},si=(e,t,n,i,r,o)=>{const s=En(),a=t;let c,d,h=1;Vn.init(a);const u=new Promise((t,s)=>{((e,t,n,i,r,o)=>{var s;const a=t;if(2===o)throw a.trace("running in HC"),new Error("GD2 not supported");return o>=3?(a.trace("running in GD 3"),new ii(e,a,n,i,r,window.glue42gd.windowId,null===(s=window.webGroupsManager)||void 0===s?void 0:s.id).init()):(a.trace("running in Browser or Node"),new ii(e,a,n,i,r).init())})(e,a,n,i,r,o).then(n=>{d=n,c=oi(n),qn.init(n.executor,e,a),t()}).catch(e=>{const t=`Timed out waiting for connection to Glue42 Enterprise: Error: ${e.message}`;a.error(t,e),s(new Error(t))})});function l(){const e=Vn.getIfReady(d.my());return e?e.API:void 0}function p(e){return s.add("window-added",e)}function g(e){return s.add("window-removed",e)}return Vn.onReadyWindow(function(e){s.execute("window-added",e.API)}),Vn.onRemoved(function(e){s.execute("window-removed",e.API)}),{my:l,open:function(e,t,n,i,r){return $n.callbackifyPromise(()=>{if(Nt(e))throw new Error("The window name is missing.");if(Nt(t))throw new Error("The window URL is missing.");if(!Rt(n)){const e=n;for(const t of["minHeight","maxHeight","minWidth","maxWidth","width","height","top","left"])if(t in e){const n=e[t];if(Rt(n)){delete e[t];continue}if(!kt(n)){throw new Error(`${t} must be a number`)}if(("width"===e[t]||"height"===e[t])&&n<=0){throw new Error(`${t} must be a positive number`)}}}return d.open(e,t,n)},i,r)},find:function(e,t,n){const i=Vn.list,r=Object.keys(i).reduce((t,n)=>{var r;const o=i[n];return(null===(r=null==o?void 0:o.API)||void 0===r?void 0:r.name)===e&&t.push(o.API),t},[]);if(r[0])return"function"==typeof t&&t(r[0]),r[0];"function"==typeof n&&n("There is no window with name:"+e)},findById:function(e,t,n){const i=Vn.list,r=Object.keys(i).reduce((t,n)=>{const r=i[n];return void 0!==r&&r.API.id===e&&t.push(r.API),t},[]);if(r[0])return"function"==typeof t&&t(r[0]),r[0];"function"==typeof n&&n("There is no window with such id:"+e)},list:function(e){const t=Vn.list,n=Object.keys(t).map(e=>t[e].API);if("function"!=typeof e)return n;e(n)},ready:function(){return u},onWindowAdded:p,windowAdded:p,onWindowRemoved:g,windowRemoved:g,onTabAttached:function(e){let t,n=!1;return u.then(()=>{n||(t=d.tabAttached(e))}),()=>{n=!0,t&&t()}},onTabDetached:function(e){let t,n=!1;return u.then(()=>{n||(t=d.tabDetached(e))}),()=>{n=!0,t&&t()}},onWindowFrameColorChanged:function(e){let t,n=!1;return u.then(()=>{n||(t=d.onWindowFrameColorChanged(e))}),()=>{n=!0,t&&t()}},onArrangementChanged:function(e){return d.onWindowsAutoArrangeChanged(e)},get groups(){return c.groupsAPI},onWindowGotFocus:function(e){let t,n=!1;return u.then(()=>{n||(t=d.onWindowGotFocus(e))}),()=>{n=!0,t&&t()}},onWindowLostFocus:function(e){let t,n=!1;return u.then(()=>{n||(t=d.onWindowLostFocus(e))}),()=>{n=!0,t&&t()}},onEvent:function(e){let t,n=!1;return u.then(()=>{n||(t=d.onEvent(e))}),()=>{n=!0,t&&t()}},createFlydown:function(e,t){return d.createFlydown(e,t)},createPopup:function(e){var t,n;if("undefined"==typeof window||!window.glue42gd||!window.glue42gd.createProcessWindow)throw new Error("Cannot create popup window. The glue42gd object is not available in the current environment.");if(!window.glue42gd.createProcessWindow)throw new Error("Cannot create popup window. The createProcessWindow method is not available in the glue42gd object.");let i="isInternalPopup=true, mode=frameless, hidden=true, outlivesOpener=false";if(e){const t=["left","top","width","height","roundedCorners","hasSizeAreas","hasMoveAreas"];for(const n of t)if(n in e){const t=e[n];Rt(t)||(i+=`, ${n}=${t}`)}}i+=`, transparent=${null!==(t=null==e?void 0:e.transparent)&&void 0!==t&&t}`;const r=`ioConnectPopup-${window.glue42gd.windowId}-${h++}`,o={name:r,features:i,copyStyles:null===(n=null==e?void 0:e.copyStyles)||void 0===n||n};return new Promise(async(e,t)=>{const n=await window.glue42gd.createProcessWindow(o).catch(e=>{t(e)});Vn.waitForName(r).then(t=>{e({browserWindow:n,ioConnectWindow:t.API})}).catch(e=>{n.close(),t(e)})})},showPopup:function(e,t){return d.showPopup(e,t)},configure:function(e){const t=l(),n=t?t.id:"";return ni.configure(n,e)},autoArrange:function(e){return ni.autoArrange(e)}}};var ai=new class{constructor(){this.layouts=[]}removeWhere(e){this.layouts=this.layouts.filter(e)}removeAll(){this.layouts=[]}add(e){this.layouts.push(e)}get all(){return this.layouts}where(e){return this.layouts.filter(e)}first(e){return this.where(e)[0]}};class ci{constructor(e,t,n,i){this.config=e,this.activitiesGetter=t,this.callbacks=n,this.logger=i,this.interop=e.agm,this.registerRequestMethods()}onSaveRequested(e){return this.callbacks.add("saveRequested",e)}isActivityOwner(){if("undefined"!=typeof htmlContainer){const e=htmlContainer.getContext();return e&&e._t42&&e._t42.activityIsOwner}const e=this.activitiesGetter();if(!e)return!1;if(!e.inActivity)return!1;const t=e.my.window,n=e.my.activity;return!(!n&&!t)&&n.owner.id===t.id}registerRequestMethods(){this.interop.register("T42.HC.GetSaveContext",e=>{const{ignoreContexts:t,...n}=e,i=this.callbacks.execute("saveRequested",n);(null==i?void 0:i.length)>1&&this.logger.warn('Multiple subscriptions for "glue.layouts.onSaveRequested" - only the first one will be used');const r=i[0],o=this.config.autoSaveWindowContext;if("boolean"==typeof o&&o)return{autoSaveWindowContext:o};if(Array.isArray(o)&&o.length>0)return{autoSaveWindowContext:o};const s={windowContext:null==r?void 0:r.windowContext,activityContext:void 0};return this.isActivityOwner()&&(s.activityContext=null==r?void 0:r.activityContext),t?{windowContext:void 0,activityContext:void 0}:s})}}function di(e){if(!e)return e;if(Array.isArray(e))return e.map(e=>di(e));if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;return Object.keys(e).reduce((t,n)=>{var i;const r=di(e[n]);let o=n;return(null===(i=n[0])||void 0===i?void 0:i.toLowerCase())!==n[0]&&(o=n[0].toLowerCase()+n.substr(1)),t[o]=r,t},{})}class hi{constructor(e){this.name=e.name,this.type=e.type,this.components=e.components,this.context=e.context,this.metadata=e.metadata,this.version=e.version,this.displays=e.displays}}var ui={},li={};Object.defineProperty(li,"__esModule",{value:!0});var pi={};Object.defineProperty(pi,"__esModule",{value:!0});var gi,fi,mi={};Object.defineProperty(mi,"__esModule",{value:!0}),mi.SwimlaneItemType=mi.LayoutType=void 0,function(e){e.Global="Global",e.Activity="Activity",e.ApplicationDefault="ApplicationDefault",e.Swimlane="Swimlane",e.Workspaces="Workspace"}(gi||(mi.LayoutType=gi={})),function(e){e.Tab="tab",e.Window="window",e.Canvas="canvas"}(fi||(mi.SwimlaneItemType=fi={}));var yi={};Object.defineProperty(yi,"__esModule",{value:!0});var wi={};Object.defineProperty(wi,"__esModule",{value:!0}),function(e){var t=Sn&&Sn.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),n=Sn&&Sn.__exportStar||function(e,n){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(n,i)||t(n,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(li,e),n(pi,e),n(mi,e),n(yi,e),n(wi,e)}(ui);const vi="T42.ACS.Command";class bi{constructor(e,t,n,i){this.config=e,this.stream=t,this.callbacks=n,this.logger=i,this.isRegisterMethodForLayoutModified=!1,this.provider=new ci(e,e.activityGetter,n,i),t.subscribe()}async setDefaultGlobal(e){await this.invokeMethodCore("SelectDefaultLayout",{name:e})}async clearDefaultGlobal(){await this.invokeMethodCore("DeselectDefaultLayout")}async getDefaultGlobal(){const e=(await this.invokeMethodCore("GetDefaultLayout")).returned;if(null!=e&&("object"!=typeof e||0!==Object.keys(e).length))return Mn(this.isSlimMode()?e:this.list().find(t=>t.name===e.name&&t.type===e.type))}ready(){return"fullWaitSnapshot"===this.config.mode?this.stream.gotSnapshot:this.stream.ready}save(e){return new Promise((t,n)=>{var i,r,o,s;if(this.verifyNotSlimMode(),Rt(e))return n(new Error("layout is required"));if(Nt(e.name))return n(new Error("layout.name argument is required"));Nt(e.type)&&(e.type="Global"),Nt(e.activityId)||(e.type="Activity");const a={name:e.name,type:e.type,context:null!==(i=e.context)&&void 0!==i?i:{},metadata:null!==(r=e.metadata)&&void 0!==r?r:{},options:{}};if("Activity"===e.type){let t=e.activityId;if(!t){if(!(null===(o=this.config.myInstance())||void 0===o?void 0:o.inActivity))return n(new Error("Current application is not in activity. Cannot save activity layout for it."));t=null===(s=this.config.myInstance())||void 0===s?void 0:s.activityId}a.activityId=t}else{if("Global"!==e.type)return n(new Error(`layout type ${e.type} is not supported`));Array.isArray(e.ignoreInstances)&&(a.options.ignoreInstances=e.ignoreInstances),Array.isArray(e.instances)&&(a.options.instances=e.instances),"boolean"==typeof e.setAsCurrent&&(a.options.setAsCurrent=e.setAsCurrent),"boolean"==typeof e.ignoreContexts&&(a.options.ignoreContexts=e.ignoreContexts)}this.invokeMethodAndTrack("SaveLayout",a,t,n)})}restore(e){return new Promise((t,n)=>{var i,r,o,s;if(this.verifyNotSlimMode(),Rt(e))return n(new Error("options argument is required"));if(Nt(e.name))return n(new Error("options.name argument is required"));if(Nt(e.type)&&(e.type="Global"),Nt(e.activityIdToJoin)||(e.type="Activity"),"Activity"===e.type){if(Rt(e.setActivityContext)&&(e.setActivityContext=!0),"boolean"!=typeof e.setActivityContext)return n(new Error("`setActivityContext` must hold a boolean value."));e.activityIdToJoin=null!==(i=e.activityIdToJoin)&&void 0!==i?i:null===(r=this.config.myInstance())||void 0===r?void 0:r.activityId}if(Rt(e.closeRunningInstance)||(e.closeRunningInstances=e.closeRunningInstance),Rt(e.closeRunningInstances)&&(e.closeRunningInstances=!0),!Ot(e.closeRunningInstances))return n(new Error("`closeRunningInstances` must hold a boolean value."));if(Rt(e.closeMe)&&(e.closeMe=e.closeRunningInstances),!Ot(e.closeMe))return n(new Error("`closeMe` must hold a boolean value."));if(!Rt(e.context)&&!Et(e.context))return n(new Error("`context` must hold an object value."));e.context=null!==(o=e.context)&&void 0!==o?o:{};const a={activityToJoin:e.activityIdToJoin,setActivityContext:e.setActivityContext,ignoreActivityWindowTypes:e.ignoreActivityWindowTypes,reuseExistingWindows:e.reuseWindows,restoreWorkspacesByReference:e.restoreWorkspacesByReference,closeRunningInstances:e.closeRunningInstances,excludeFromClosing:e.closeMe?[]:[null===(s=this.config.myInstance())||void 0===s?void 0:s.id]},c={type:e.type,name:e.name,context:e.context,options:a,timeout:jn};this.invokeMethodAndTrack("RestoreLayout",c,t,n,!0)})}reset(e){return new Promise((t,n)=>{if(this.verifyNotSlimMode(),"object"!=typeof e)return n(new Error("options argument is required"));if(Nt(e.layoutId))return n(new Error("options.layoutId argument is required"));const i={...e};this.invokeMethodAndTrack("ResetLayout",i,t,n,!0)})}remove(e,t){return new Promise((n,i)=>{if(this.verifyNotSlimMode(),!t)return i(new Error("name argument is required"));if(!e)return i(new Error("type argument is required"));const r={type:e,name:t};this.invokeMethodAndTrack("RemoveLayout",r,n,i)})}list(){return this.verifyNotSlimMode(),Mn(ai.all)}import(e,t){return new Promise((n,i)=>{if(this.verifyNotSlimMode(),!Rt(t)&&"merge"!==t&&"replace"!==t)return i(new Error(`${t} is not supported - only "merge" and "replace"`));if(!Array.isArray(e))return i(new Error("layouts arguments is not an array"));const r={mode:t||"replace",layouts:e};this.invokeMethodAndTrack("ImportLayouts",r,n,i,!0)})}export(e){return new Promise((t,n)=>{var i;if(!Rt(e)&&!(null===(i=Object.values(ui.LayoutType))||void 0===i?void 0:i.includes(e)))return n(new Error(`${e} is not a supported Layout Type`));this.invokeMethodAndTrack("ExportLayouts",{},n=>{let i=this.getObjectValues(n.Layouts).map(e=>new hi(di(e)));e&&(i=i.filter(t=>t.type===e)),t(i)},n,!0)})}rename(e,t){return new Promise((n,i)=>{if(this.verifyNotSlimMode(),!e)return i(new Error("layout argument is required"));if(!e.name)return i(new Error("name argument is required"));if(!e.type)return i(new Error("type argument is required"));const r={type:e.type,oldName:e.name,newName:t};this.invokeMethodAndTrack("RenameLayout",r,n,i)})}updateMetadata(e){return new Promise((t,n)=>{if(!e)return n(new Error("layout argument is required"));if(!e.name)return n(new Error("name argument is required"));if(!e.type)return n(new Error("type argument is required"));if(!e.metadata)return n(new Error("metadata argument is required"));const i={name:e.name,type:e.type,metadata:e.metadata};this.invokeMethodAndTrack("UpdateMetadata",i,t,n,!0)})}hibernate(e,t){return new Promise((n,i)=>{if(!e)return i(new Error("name cannot be empty"));const r={name:e,type:"Global",context:(t=t||{}).context||{},metadata:t.metadata||{}};this.invokeMethodAndTrack("HibernateLayout",r,n,i,!0)})}resume(e,t,n){return new Promise((i,r)=>{if(!e)return r(new Error("name cannot be empty"));const o={name:e,type:"Global",timeout:jn,context:t,...n};this.invokeMethodAndTrack("ResumeLayout",o,i,r,!0)})}async getCurrentLayout(){let e=(await this.invokeMethodCore("GetCurrentLayout")).returned.layout;if(e)return this.isSlimMode()||(e=this.list().find(t=>t.name===e.name&&t.type===e.type)),Mn(e)}getRestoredLayoutsInfo(){return new Promise((e,t)=>{this.invokeMethodCore("GetRestoredLayoutsInfo").then(t=>{const n=t.returned;e(n)}).catch(t)})}onAdded(e){const t=this.callbacks.add("added",e);return ai.all.length>0&&ai.all.forEach(t=>{try{e(t)}catch(e){}}),t}onRemoved(e){return this.callbacks.add("removed",e)}onChanged(e){return this.callbacks.add("changed",e)}onDefaultGlobalChanged(e){if("function"!=typeof e)throw new Error("callback must be a function");return this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.callbacks.add("default-changed",e)}onRestored(e){return this.callbacks.add("restored",e)}onRenamed(e){return this.callbacks.add("renamed",e)}onEvent(e){return this.stream.onEvent(e)}onSaveRequested(e){return this.provider.onSaveRequested(e)}onLayoutModified(e){return!1===this.isRegisterMethodForLayoutModified&&(this.isRegisterMethodForLayoutModified=!0,this.registerMethodForLayoutModified()),this.callbacks.add("layout-modified",e)}updateAppContextInCurrent(e){return new Promise((t,n)=>{if(e&&"object"!=typeof e)return n(new Error("Context must be an object"));const i={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateLayoutComponentContext",i,t,n,!0)})}updateDefaultContext(e){return new Promise((t,n)=>{if(e&&"object"!=typeof e)return n(new Error("Context must be an object"));const i={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateDefaultContext",i,t,n,!0)})}async get(e,t){const n=this.list().find(n=>n.name===e&&n.type===t);if(!n)throw new Error(`cannot find layout with name=${e} and type=${t}`);return Mn(n)}async getAll(e){var t;if(!Rt(e)&&!(null===(t=Object.values(ui.LayoutType))||void 0===t?void 0:t.includes(e)))throw new Error(`${e} is not a supported Layout Type`);return Mn(this.list().filter(t=>e===t.type))}async forceRefresh(){await this.invokeMethodCore("RefreshLayouts")}isSlimMode(){return"slim"===this.config.mode}verifyNotSlimMode(){if(this.isSlimMode())throw Error("Operation not allowed in slim mode. Run in full mode.")}async registerMethodForLayoutModified(){await this.config.agm.register("T42.ACS.LayoutModified",(e,t)=>{this.callbacks.execute("layout-modified",e)})}invokeMethodAndTrack(e,t,n,i,r){let o,s=r;const a=$n.generateId();t.token=a,this.logger.debug(`invoking method "${e}" with token ${a} will wait for stream event: ${!r}`);const c=()=>{s&&o&&(this.logger.debug(`method "${e}" resolved with token ${a} and result: ${JSON.stringify(o)}`),n(o))},d=e=>{const t=$n.typedError(e);i(t)},h="timeout"in t&&"number"==typeof t.timeout?t.timeout:12e4;r||this.stream.waitFor(a,h).then(()=>{s=!0,c()}).catch(d);this.invokeMethodCore(e,t,"best",{methodResponseTimeoutMs:h}).then(t=>{if(this.logger.debug(`method "${e}" returned with token "${a}" and result: ${JSON.stringify(t.returned)}`),!t.returned)return i(new Error("No result from method "+e));if(t.returned.status&&"Success"!==t.returned.status&&"PartialSuccess"!==t.returned.status){if("string"==typeof t.returned)return i(new Error(t.returned));if("object"==typeof t.returned)return t.returned.status&&t.returned.failed?i(new Error(`${t.returned.status}: ${JSON.stringify(t.returned.failed)}`)):i(new Error(t.returned))}o=t.returned,c()}).catch(d)}async invokeMethodCore(e,t,n,i){return void 0===(i=null!=i?i:{}).methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=On),void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=On),this.isCommandMethodPresent()?await this.config.agm.invoke(vi,{command:e,data:t},n,i):await this.config.agm.invoke(`T42.ACS.${e}`,t,n,i)}getObjectValues(e){return e?Object.keys(e).map(t=>e[t]):[]}isCommandMethodPresent(){return this.config.agm.methods().some(e=>e.name===vi)}}class _i{constructor(e,t,n){this.agm=e,this.logger=t,this.callbacks=n,this.StreamName="T42.ACS.OnLayoutEvent",this.ready=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this.gotSnapshot=new Promise((e,t)=>{this.resolveGotSnapshot=e,this.rejectGotSnapshot=t})}subscribe(e){const t=e=>this.getObjectValues(e).map(e=>di(e));this.checkForLayoutEventMethod()?(this.logger.trace(`subscribing to "${this.StreamName}" stream`),this.agm.subscribe(this.StreamName,{waitTimeoutMs:On,methodResponseTimeout:On}).then(e=>{this.logger.trace(`subscribed to "${this.StreamName}" stream`),e.onData(e=>{const n=e.data;this.logger.trace(`received data from "${this.StreamName}" stream: ${JSON.stringify(n)}`),n.IsSnapshot&&this.resolveGotSnapshot(),this.addLayouts(t(n.OnLayoutAdded),n.IsSnapshot),this.removeLayouts(t(n.OnLayoutRemoved)),this.changeLayouts(t(n.OnLayoutChanged)),this.renameLayouts(t(n.OnLayoutRenamed)),this.restoredLayout(t(n.OnLayoutRestored)),this.selectedDefaultLayout(t(n.OnLayoutSelectedDefault)),this.callbacks.execute("streamEvent",n)}),e.onFailed(e=>{const t=`Can not subscribe to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.logger.error(t,e),this.rejectReady(t),this.rejectGotSnapshot(t)}),this.resolveReady()}).catch(e=>{const t=`Error subscribing to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.logger.error(t,e),this.rejectReady(t),this.rejectGotSnapshot(t)})):(e&&this.resolveReady(),setTimeout(()=>{this.subscribe(!0)},500))}onEvent(e){return this.callbacks.add("streamEvent",e)}waitFor(e,t){return t||(t=3e4),this.logger.trace(`waiting for token ${e} with timeout ${t}ms`),new Promise((n,i)=>{let r=!1;const o=this.onEvent(t=>{t.Token===e&&(this.logger.trace(`token ${e} received`),r=!0,o(),n())});setTimeout(()=>{if(!r){o();const t=`Timeout waiting for token ${e}`;this.logger.error(t),i(new Error(t))}},t)})}checkForLayoutEventMethod(){try{return-1!==this.agm.methods().map(e=>e.name).indexOf(this.StreamName)}catch(e){return!1}}addLayouts(e,t){if(!e)return;const n=e=>{const t=new hi(e);ai.add(t),this.callbacks.execute("added",t)};e.forEach(e=>{if(t){ai.first(t=>this.compareLayouts(t,e))||n(e)}else n(e)})}removeLayouts(e){e&&e.forEach(e=>{ai.removeWhere(t=>!this.compareLayouts(t,e)),this.callbacks.execute("removed",e)})}changeLayouts(e){e&&e.forEach(e=>{ai.removeWhere(t=>!this.compareLayouts(t,e)),ai.add(new hi(e)),this.callbacks.execute("changed",e)})}renameLayouts(e){e&&e.forEach(e=>{const t=ai.first(t=>this.compareLayouts(t,{type:e.type,name:e.oldName}));if(!t)throw new Error(`received rename event for unknown layout with type ${e.type} and name ${e.oldName}`);t.name=e.newName,this.callbacks.execute("renamed",t,{name:e.oldName})})}compareLayouts(e,t){return e.name===t.name&&e.type===t.type}getObjectValues(e){return e?Object.keys(e).map(t=>e[t]):[]}restoredLayout(e){e&&e.forEach(e=>{const t=ai.first(t=>this.compareLayouts(t,{type:e.type,name:e.name}));this.callbacks.execute("restored",t)})}selectedDefaultLayout(e){this.callbacks.execute("default-changed",null==e?void 0:e[0])}}function Ii(e){if(!e.agm)throw Error("config.agm is required");if(!e.logger)throw Error("config.logger is required");e.mode=e.mode||"slim";const t=e.logger,n=En();let i;return i="full"===e.mode||"fullWaitSnapshot"===e.mode?new _i(e.agm,t.subLogger("stream"),n):{ready:Promise.resolve(void 0),subscribe:()=>{},onEvent:e=>()=>{},waitFor:(e,t)=>Promise.resolve(void 0),gotSnapshot:Promise.resolve(void 0)},new bi(e,i,n,t)}class Ci{constructor(e,t){this._agm=e,this._logger=t,this._registry=En(),this._registered=!1,this.all=async()=>(await this.callGD(Ai.GetAll,{})).map(this.decorateDisplay),this.get=async e=>{const t=await this.callGD(Ai.Get,{id:e});return this.decorateDisplay(t)},this.getPrimary=async()=>(await this.all()).find(e=>e.isPrimary),this.capture=async e=>await this.callGD(Ai.Capture,{...e}),this.captureAll=async e=>await this.callGD(Ai.CaptureAll,{...e}),this.getMousePosition=async()=>await this.callGD(Ai.GetMousePosition),this.callGD=async(e,t)=>(await this._agm.invoke("T42.Displays.Command",{options:{...t},command:e},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.data,this.decorateDisplay=e=>{const t={...e,capture:t=>this.capture({id:e.id,size:t})},n=t.workArea;return n.x=n.left,n.y=t.workArea.top,t}}getByWindowId(e){return this.callGD(Ai.GetByWindowId,{id:e})}onDisplayChanged(e){return this.register(),this._registry.add("on-display-changed",e)}register(){this._registered||(this._registered=!0,this._agm.register("T42.Displays.OnEvent",(e,t)=>{const n=e.event,i=e.data;if("display-changed"===n)this._registry.execute("on-display-changed",i.displays.map(this.decorateDisplay));else this._logger.warn(`unknown event - ${n}`)}))}}var Ai;let Ti,Si,ki;!function(e){e.Capture="capture",e.CaptureAll="captureAll",e.GetAll="getAll",e.Get="get",e.GetByWindowId="getByWindowId",e.GetMousePosition="getMousePosition"}(Ai||(Ai={}));const xi="T42.Channels.Announce";async function Ei(e,t,n){var i,r;ki=n,Ti=e,"undefined"!=typeof window&&window.glue42gd&&(Si=window.glue42gd.windowId),Si||(Si=e.instance.instance),await Ti.register("T42.Channels.Command",e=>{const n=e.command;if(!n)throw new Error("missing command argument");if(ki.trace(`received command "${n}" with ${JSON.stringify(e)}`),"join"===n){const n=e.channel;if(!n)throw new Error("missing argument id");return t.joinNoSelectorSwitch(n)}if("leave"===n)return t.leaveNoSelectorSwitch();if("get"===n){return{id:t.current()}}if("restrictions-changed"===n){const n=e.restrictions,i=e.swId;return void t.handleRestrictionsChanged(n,i)}if("isFdc3DataWrappingSupported"===n)return{isSupported:!0};if("join-multi"===n){const n=e.channelsToJoin;if(!n)throw new Error("missing argument channelsToJoin");return t.joinNoSelectorSwitch(new Xn(n).toString())}if("leave-multi"===n){const n=e.channelsToLeave;return t.leaveNoSelectorSwitch(new Xn(n).toString())}throw new Error(`unknown command ${n}`)});const o=await Ti.invoke(xi,{swId:Si,instance:Ti.instance.instance},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:Nn});return(null===(i=o.returned)||void 0===i?void 0:i.restrictions)&&t.handleRestrictionsChanged(null===(r=o.returned)||void 0===r?void 0:r.restrictions,Si),o.returned}async function Pi(e,t){var n;await ji("leaveChannel",{channel:e},null!==(n=t)&&void 0!==n?n:Si)}async function Mi(e,t){await ji("switchChannel",{newChannel:e},null!=t?t:Si)}async function Ri(e){try{return(await ji("getRestrictions",{},null!=e?e:Si)).returned}catch(e){}}async function Ni(e,t,n,i){await ji(e,{id:t,color:n,label:i})}async function Oi(e,t){if("boolean"!=typeof e.operationMode&&"string"==typeof e.operationMode)return function(e){if("single"!==e&&"multi"!==e)throw new Error(`Invalid mode: ${e}`)}(e.operationMode),{mode:e.operationMode,initialChannel:void 0};try{const e=await t.invoke(xi,{command:"getChannelsMode"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:Nn}),n=e.returned.initialChannel;return"single"===e.returned.mode?{mode:"single",initialChannel:n}:"multi"===e.returned.mode?{mode:"multi",initialChannel:n}:{mode:"single",initialChannel:n}}catch(e){return{mode:"single",initialChannel:void 0}}}function ji(e,t,n){const i={command:e,data:t};return n&&(i.swId=n),Ti.invoke(xi,i,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:Nn})}const $i="___channel___",Wi="latest_fdc3_type";class Di{constructor(e){this.contexts=e}subscribe(e){this.callback=e}subscribeFor(e,t){if(!this.isChannel(e))return Promise.reject(new Error(`Channel with name: ${e} doesn't exist!`));const n=this.createContextName(e);return this.contexts.subscribe(n,(e,n,i,r,o)=>{t(e.data,e,n,null==o?void 0:o.updaterId)})}all(){return this.contexts.all().filter(e=>e.startsWith($i)).map(e=>e.substr(13))}async getContextData(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e),n=await this.contexts.get(t);return n[Wi]?this.getContextWithFdc3Data(n):(delete n[Wi],n)}updateChannel(e,t){const n=this.createContextName(e);return this.contexts.update(n,t)}updateData(e,t){const n=this.createContextName(e),i=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map(e=>({path:"data."+e,value:t[e]}));return i&&e.push({path:Wi,value:i}),this.contexts.setPaths(n,e)}return i&&(t[Wi]=i),this.contexts.update(n,{data:t})}setPaths(e,t){const n=this.createContextName(e);if(this.contexts.setPathSupported){const e=t.map(e=>({path:"data."+e.path,value:e.value}));return e.map(t=>{const n=this.getFDC3Type(t.value);n&&e.push({path:Wi,value:n})}),this.contexts.setPaths(n,e)}throw new Error("setPaths is not supported!")}async clearContextData(e){const t=this.createContextName(e);return this.contexts.update(t,{data:{},[Wi]:void 0})}isChannel(e){return this.all().some(t=>t===e)}async remove(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e);await this.contexts.destroy(t)}createContextName(e){return $i+e}getFDC3Type(e){const t=Object.keys(e).filter(e=>0===e.indexOf("fdc3_"));if(0!==t.length){if(t.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return t[0].split("_").slice(1).join("_")}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...n}=e,i={type:t.split("&").join("."),...n.data[`fdc3_${t}`]};delete n.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...n.data,fdc3:i}}}}class Fi extends Di{constructor(){super(...arguments),this.currentlySubscribedChannels=[],this.unsubscribeMap={}}async switchChannel(e){const t=new Xn(e).all();for(const e of t)this.currentlySubscribedChannels.includes(e)||await this.subscribeToChannel(e)}async leave(e){const t=new Xn(e).all();for(const e of t)this.currentlySubscribedChannels.includes(e)&&this.unsubscribeFromChannel(e)}async updateData(e,t){const n=new Xn(e).all();for(const e of n)await super.updateData(e,t)}async setPaths(e,t){const n=new Xn(e).all();for(const e of n)await super.setPaths(e,t)}isChannel(e){return new Xn(e).all().every(e=>super.isChannel(e))}async subscribeToChannel(e){const t=this.createContextName(e),n=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.callback&&this.callback(e.data,e,t,null==r?void 0:r.updaterId)});this.currentlySubscribedChannels.push(e),this.unsubscribeMap[t]=n}async unsubscribeFromChannel(e){const t=this.createContextName(e),n=this.unsubscribeMap[t];n&&(n(),delete this.unsubscribeMap[t]),this.currentlySubscribedChannels=this.currentlySubscribedChannels.filter(t=>t!==e)}}class Li extends Di{async switchChannel(e){this.unsubscribe();const t=this.createContextName(e);this.unsubscribeFunc=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.callback&&this.callback(e.data,e,t,null==r?void 0:r.updaterId)})}async leave(){this.callback&&this.callback({},void 0,void 0,void 0),this.unsubscribe()}unsubscribe(){this.unsubscribeFunc&&(this.unsubscribeFunc(),this.unsubscribeFunc=void 0)}}const Gi=e=>{if("object"!=typeof e||Array.isArray(e))throw new Error("Provide options as an object");if(e.contextType&&("string"!=typeof e.contextType||!e.contextType.length))throw new Error("Provide options.contextType as a non-empty string")};class Ui{constructor(e,t,n){this.interop=e,this.getWindowsAPI=t,this.logger=n,this.subsKey="subs",this.changedKey="changed",this.channelsChangedKey="channelsChanged",this.isInitialJoin=!0,this.registry=En(),this.pendingRestrictionCallbacks=new Map}async getMyChannels(e){if(!this.currentChannelID)return Promise.resolve([]);if(0===this.currentChannelID.all().length)return Promise.resolve([]);const t=[];for(const n of this.currentChannelID.all())t.push(await this.get(n,e));return t}async init(e,t,n){this.mode=t,this.shared=e,this.shared.subscribe(this.handler.bind(this)),this.subscribeForChannelRestrictionsChange();let i=n;"undefined"!=typeof window&&void 0!==window.glue42gd&&(i=window.glue42gd.initialChannel),this.currentChannelID=this.getID(i),this.logger.trace(`initialized with mode: "${t}" and initial channel: "${i}"`),this.currentChannelID.isJoinedToAnyChannel&&(this.logger.trace(`joining initial channel: "${this.currentChannelID.toString()}"`),await this.joinNoSelectorSwitch(this.currentChannelID.toString()))}subscribe(e,t){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");(null==t?void 0:t.contextType)&&Gi(t);const n=$n.generateId();let i=!1;const r=()=>{i=!0},o=(null==t?void 0:t.contextType)?this.getWrappedSubscribeCallbackWithFdc3Type(e,n,t.contextType,r):this.getWrappedSubscribeCallback(e,n,r);let s;this.lastUpdate&&(s=setTimeout(()=>{i||o(this.lastUpdate.context.data,this.lastUpdate.context,{},this.lastUpdate.updaterId)},0));const a=this.registry.add(this.subsKey,o);return()=>{clearTimeout(s),this.pendingRestrictionCallbacks.delete(n),a()}}async subscribeFor(e,t,n){if("string"!=typeof e)throw new Error("Please provide the name as a string!");if("function"!=typeof t)throw new Error("Please provide the callback as a function!");(null==n?void 0:n.contextType)&&Gi(n);const i=$n.generateId(),r=()=>{},o=(null==n?void 0:n.contextType)?this.getWrappedSubscribeCallbackWithFdc3Type(t,i,n.contextType,r):this.getWrappedSubscribeCallback(t,i,r),s=await this.shared.subscribeFor(e,o);return()=>{this.pendingRestrictionCallbacks.delete(i),s()}}async publish(e,t){if("object"!=typeof e)throw new Error("Please provide the data as an object!");if(t&&this.validatePublishOptions(t),"object"==typeof t)return this.publishWithOptions(e,t);const n="string"==typeof t?t:this.currentChannelID.toString();if(!n)throw new Error("Not joined to any channel!");if(!this.shared.isChannel(n))return Promise.reject(new Error(`A channel with name: ${n} doesn't exist!`));if("multi"!==this.mode){if(!(await this.getRestrictionsByChannel(n)).write)throw new Error(`Window does not have permission to write to channel ${n}`);return this.shared.updateData(n,e)}{const t=new Xn(n).all(),i=[];for(const n of t){(await this.getRestrictionsByChannel(n)).write?await this.shared.updateData(n,e):i.push(n)}if(i.length>0){const e=`Unable to publish due to restrictions to the following channels: ${i.join(", ")}`;if(i.length===t.length)throw new Error(e);this.logger.warn(e)}}}async setPaths(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,e)}if(!this.currentChannelID)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentChannelID.toString())).write)throw new Error(`Window does not have permission to write to channel ${this.currentChannelID.toString()}`);if(!Array.isArray(e))throw new Error("Path Values argument is not a valid array");return e.forEach(e=>{this.validatePathArgs(e)}),this.shared.setPaths(this.currentChannelID.toString(),e)}async setPath(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,[e])}if(!this.currentChannelID)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentChannelID.toString())).write)throw new Error(`Window does not have permission to write to channel ${this.currentChannelID.toString()}`);return this.validatePathArgs(e),this.shared.setPaths(this.currentChannelID.toString(),[e])}all(){const e=this.shared.all();return Promise.resolve(e)}async list(){const e=await this.all();return await Promise.all(e.map(e=>this.get(e)))}async get(e,t){if("string"!=typeof e)return Promise.reject(new Error("Please provide the channel name as a string!"));if(!(null==t?void 0:t.contextType))return this.shared.getContextData(e);Gi(t);const n=await this.shared.getContextData(e);return this.getContextWithFdc3Type(n,t.contextType)}getMy(e){return this.currentChannelID?0===this.currentChannelID.all().length?Promise.resolve(void 0):this.get(this.currentChannelID.all()[0],e):Promise.resolve(void 0)}async join(e,t){return null!=t?(this.validateWindowIdArg(t),this.logger.trace(`joining channel ${e} for window: ${t}`),Mi(e,t)):this.joinCore(e)}async joinNoSelectorSwitch(e){return this.logger.trace(`joining channel "${e}" from command`),this.joinCore(e,!1)}leave(e){let t,n;return this.logger.trace(`leaving channel with options: ${JSON.stringify(e)}`),"string"==typeof e?t=e:"object"!=typeof e||Array.isArray(e)||null==e||(e.windowId&&(t=e.windowId),e.channel&&(n=e.channel)),"multi"===this.mode?this.leaveWhenMulti(n,t):this.leaveWhenSingle(n,t)}leaveNoSelectorSwitch(e){return this.logger.trace(`leaving channel "${e}" from command`),this.leaveCore(!1,e)}current(){return this.currentChannelID.toString()}my(){return this.current()}myChannels(){var e;return null!==(e=this.currentChannelID.all())&&void 0!==e?e:[]}onChannelsChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");let t;this.current()&&(t=setTimeout(()=>{e(this.myChannels())},0));const n=this.registry.add(this.channelsChangedKey,e);return()=>{n(),clearTimeout(t)}}changed(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");return this.current()&&setTimeout(()=>{e(this.current())},0),this.registry.add(this.changedKey,()=>{e(this.current())})}onChanged(e){return this.changed(e)}async add(e){var t;if("object"!=typeof e)throw new Error("Please provide the info as an object!");if(void 0===e.name)throw new Error("info.name is missing!");if("string"!=typeof e.name)throw new Error("Please provide the info.name as a string!");if(void 0===e.meta)throw new Error("info.meta is missing!");if("object"!=typeof e.meta)throw new Error("Please provide the info.meta as an object!");if(void 0===e.meta.color)throw new Error("info.meta.color is missing!");if("string"!=typeof e.meta.color)throw new Error("Please provide the info.meta.color as a string!");const n={name:e.name,meta:e.meta||{},data:e.data||{}};this.logger.trace(`adding channel: ${e.name}`);try{await Ni("addChannel",e.name,e.meta.color,null===(t=e.meta)||void 0===t?void 0:t.label)}catch(t){throw"message"in t&&t.message.includes(`Channel with name '${e.name}' already exists.`)&&(this.logger.trace(`channel: ${e.name} already exists - ignore channel add request`),await this.verifyChannelExists(e.name,1e4)),t}return await this.shared.updateChannel(e.name,n),n}async remove(e){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");this.logger.trace(`removing channel: ${e}`),await this.shared.remove(e),await Ni("removeChannel",e)}async getWindowsOnChannel(e){this.validateChannelArg(e);return(await this.getWindowsWithChannels({channels:[e]})).map(e=>e.window)}async getWindowsWithChannels(e){this.validateWindowsWithChannelsFilter(e);try{const t=await async function(e){return(await ji("getChannelsInfo",{filter:e})).returned}(e),n=this.getWindowsAPI();if(null==t?void 0:t.windows)return t.windows.reduce((e,t)=>{const i=n.findById(t.windowId);return e.push({window:i,channel:t.channel,application:t.application}),e},[])}catch(e){this.logger.error("Error getting all channel enabled windows. This method is available since Glue42 3.12",e)}return[]}async restrict(e){return this.validateRestrictionConfig(e),async function(e){var t;await ji("restrict",e,null!==(t=e.windowId)&&void 0!==t?t:Si)}(e)}async getRestrictions(e){return e&&this.validateWindowIdArg(e),Ri(e)}async restrictAll(e){return this.validateRestrictionConfig(e),async function(e){var t;await ji("restrictAll",e,null!==(t=e.windowId)&&void 0!==t?t:Si)}(e)}handleRestrictionsChanged(e,t){this.registry.execute("restrictions-changed",{restrictions:e,windowId:t})}async clearChannelData(e){const t="string"==typeof e?e:this.currentChannelID.toString();if(!t)return;if(!this.shared.isChannel(t))return;return(await this.getRestrictionsByChannel(t)).write?this.shared.clearContextData(t):void 0}handler(e,t,n,i){t||i?(this.lastUpdate={context:t,updaterId:i},this.registry.execute(this.subsKey,e,t,n,i)):this.lastUpdate=void 0}async joinCore(e,t=!0){if(this.logger.trace(`joining channel "${e}" ${t?"":"from command"}`),"string"!=typeof e)throw new Error("Please provide the channel name as a string!");const n=this.getID(e);this.isInitialJoin||!this.currentChannelID.isOnChannel(n.toString())?(this.isInitialJoin=!1,await Promise.all(n.all().map(e=>this.verifyChannelExists(e))),this.currentChannelID.joinChannel(e),this.lastUpdate=void 0,this.logger.trace(`switching channel context to: "${e}" ${t?"":"from command"}`),await this.shared.switchChannel(this.currentChannelID.toString()),t&&(this.logger.trace(`switching UI channel to: "${e}" ${t?"":"from command"}`),await Mi(e),this.logger.trace(`switched UI channel to: "${e}" ${t?"":"from command"}`)),this.raiseChannelsChangedEvents(),this.logger.trace(`joined channel: ${e} ${t?"":"from command"} - current channel/s: ${this.currentChannelID.toString()}`)):this.logger.trace(`already on channel: "${e}" ${t?"":"from command"}`)}async verifyChannelExists(e,t,n){const i=e=>this.shared.all().includes(e);if(!i(e)){const r=new Promise((r,o)=>{const s=setInterval(()=>{i(e)&&(clearTimeout(a),clearInterval(s),r())},null!=n?n:100),a=setTimeout(()=>(clearInterval(s),o(new Error(`A channel with name: ${e} doesn't exist!`))),null!=t?t:3e3)});await r}}async leaveCore(e=!0,t){if(this.currentChannelID.isJoinedToAnyChannel){if(!t||this.currentChannelID.isOnChannel(t))return this.currentChannelID.leaveChannel(t),this.lastUpdate=void 0,await this.shared.leave(t),this.raiseChannelsChangedEvents(),e&&(this.logger.trace(`switching UI channel to: "${t}" ${e?"":"from command"}`),await Mi(this.currentChannelID.toString()),this.logger.trace(`switched UI channel to: "${t}" ${e?"":"from command"}`)),this.logger.trace(`left single channel: "${t}" ${e?"":"from command"} - current channel/s: "${this.currentChannelID.toString()}"`),Promise.resolve();this.logger.trace(`leave called ${e?"":"from command"} when not joined to channel: "${t}"`)}else this.logger.trace(`leave called ${e?"":"from command"} when not joined to any channel change selector`)}async leaveCoreMulti(e=!0,t){this.logger.trace(`leaving multi channel: "${t.toString()}" ${e?"":"from command"}`);if(!this.currentChannelID.all().some(e=>t.isOnChannel(e))||!this.currentChannelID.isJoinedToAnyChannel)return void this.logger.trace(`leave called ${e?"":"from command"} when not joined to any channel`);const n=t.toString();return this.currentChannelID.leaveChannel(n),await this.shared.leave(n),this.lastUpdate=void 0,this.raiseChannelsChangedEvents(),e&&(this.logger.trace(`switching UI channel to: "${n}" ${e?"":"from command"}`),await Pi(n),this.logger.trace(`switched UI channel to: "${n}" ${e?"":"from command"}`)),this.logger.trace(`left multi channel: "${n}" ${e?"":"from command"} - current channel/s: ${this.currentChannelID.toString()}`),Promise.resolve()}raiseChannelsChangedEvents(){this.registry.execute(this.changedKey,this.currentChannelID.toString()),this.registry.execute(this.channelsChangedKey,this.currentChannelID.all())}async getRestrictionsByChannel(e){var t;const n=null!==(t=this.channelRestrictions)&&void 0!==t?t:await Ri();if(!n||!Array.isArray(n.channels)||!n.channels.find(t=>t.name===e))return{read:!0,write:!0};return n.channels.find(t=>t.name===e)}onRestrictionsChanged(e,t,n){this.pendingRestrictionCallbacks.set(t,{cb:e,channelName:n}),this.onRestrictionsChangedSub||(this.onRestrictionsChangedSub=this.registry.add("restrictions-changed",({restrictions:e})=>{this.logger.trace(`restrictions changed - ${JSON.stringify(e)}`),this.pendingRestrictionCallbacks.forEach(({cb:t,channelName:n},i)=>{const r=e.channels.find(e=>e.name===n);r?r.read&&(this.pendingRestrictionCallbacks.delete(i),0===this.pendingRestrictionCallbacks.values.length&&this.onRestrictionsChangedSub&&(this.onRestrictionsChangedSub(),this.onRestrictionsChangedSub=null),t()):this.logger.trace(`channel "${n}" not found in restrictions`)})}))}subscribeForChannelRestrictionsChange(){this.registry.add("restrictions-changed",e=>{this.logger.trace(`channel restrictions changed - ${JSON.stringify(e.restrictions)}`),this.channelRestrictions=e.restrictions})}validatePathArgs(e){if(!e)throw new Error("Please provide a valid path value argument");if("object"!=typeof e)throw new Error(`Path Value argument is not a valid object: ${JSON.stringify(e)}`);if(!e.path)throw new Error(`path property is missing from Path Value argument: ${JSON.stringify(e)}`);if(!e.value)throw new Error(`value property is missing from Path Value argument: ${JSON.stringify(e)}`);if("string"!=typeof e.path)throw new Error(`path property is not a valid string from the Path Value argument: ${JSON.stringify(e)}`)}validatePublishOptions(e){if("string"!=typeof e&&"object"!=typeof e||Array.isArray(e))throw new Error("Provide options as a string or an object");if("object"!=typeof e){if("string"===e&&!e.length)throw new Error("Provide options as a non-empty string")}else this.validatePublishOptionsObject(e)}validatePublishOptionsObject(e){if("object"!=typeof e||Array.isArray(e))throw new Error("Provide options as an object");if(e.name&&("string"!=typeof e.name||!e.name.length))throw new Error("Provide options.name as a non-empty string");if(Object.keys(e).includes("fdc3")&&"boolean"!=typeof e.fdc3)throw new Error("Provide options.fdc3 as a boolean")}async publishWithOptions(e,t){const n=t.name||this.currentChannelID.toString();if(!this.shared.isChannel(n))throw new Error(`A channel with name: ${t.name} doesn't exist!`);if(!n)throw new Error("Cannot publish to channel, because not joined to a channel!");if(!(await this.getRestrictionsByChannel(n)).write)throw new Error(`Window does not have permission to write to channel ${this.currentChannelID.toString()}`);return t.fdc3?this.publishFdc3Data(n,e):this.shared.updateData(n,e)}async publishFdc3Data(e,t){var n;if("string"!=typeof t.type||!(null===(n=t.type)||void 0===n?void 0:n.length))throw new Error("Expected a valid FDC3 Context with compulsory 'type' field");const{type:i,...r}=t,o=i.split(".").join("&"),s={[`fdc3_${o}`]:r};return this.shared.updateData(e,s)}getWrappedSubscribeCallback(e,t,n){return async(i,r,o,s)=>{n();const a=await this.getRestrictionsByChannel(r.name),c=this.getDataWithFdc3Encoding(r,o);a.read?e(c,r,s):this.onRestrictionsChanged(()=>e(c,r,s),t,r.name)}}getWrappedSubscribeCallbackWithFdc3Type(e,t,n,i){const r={replayed:!1};return async(o,s,a,c)=>{i();const d=()=>{const{data:t,latest_fdc3_type:i}=s,o=`fdc3_${n.split(".").join("&")}`;if(!t||!t[o]||a.data&&!a.data[o])return;if(r.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:i,searchedType:n,callback:e,context:s,updaterId:c});const d={type:n,...t[o]};e({fdc3:d},s,c),r.replayed=!0};(await this.getRestrictionsByChannel(s.name)).read?d():this.onRestrictionsChanged(d,t,s.name)}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:r,updaterId:o}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...r.data[`fdc3_${t}`]}},r,o)}getContextWithFdc3Type(e,t){var n,i;if((null===(i=null===(n=e.data)||void 0===n?void 0:n.fdc3)||void 0===i?void 0:i.type)===t)return{name:e.name,meta:e.meta,data:{fdc3:e.data.fdc3}};const r=`fdc3_${t.split(".").join("&")}`;if(!e.data[r])return{name:e.name,meta:e.meta,data:{}};const o={type:t,...e.data[r]};return{name:e.name,meta:e.meta,data:{fdc3:o}}}getDataWithFdc3Encoding(e,t){const{data:n,latest_fdc3_type:i}=e,r=`fdc3_${i}`;if(!i||t.data&&!t.data[r])return n;const o={type:i.split("&").join("."),...n[r]},{[r]:s,...a}=n;return{...a,fdc3:o}}getID(e){return"multi"===this.mode?new Xn(e):new Zn(e)}leaveWhenSingle(e,t){return t?(this.logger.trace(`leaving single channel "${e}" for window: "${t}"`),Mi(void 0,t)):(this.logger.trace(`leaving single channel "${e}" for our window`),this.leaveCore(!0,e))}async leaveWhenMulti(e,t){if(t)return this.logger.trace(`leaving multi channel "${e}" for window: "${t}"`),Pi(e,t);{const t=e?new Xn(e):this.currentChannelID;return this.logger.trace(`leaving multi channel "${t.toString()}" for our window`),this.leaveCoreMulti(!0,t)}}validateWindowIdArg(e){if("string"!=typeof e)throw new Error("The window ID must be a non-empty string!");if(!this.getWindowsAPI().findById(e))throw new Error(`Window with ID "${e}" doesn't exist!`)}validateChannelArg(e){if(!e)throw new Error("Please provide a valid Channel name as a non-empty string!");if("string"!=typeof e)throw new Error("The Channel name must be a non-empty string!");if(this.shared.all().every(t=>t!==e))throw new Error(`Channel "${e}" does not exist!"`)}validateWindowsWithChannelsFilter(e){if(void 0!==e&&(null===e||Array.isArray(e)||"object"!=typeof e))throw new Error("The `filter` argument must be a valid object!")}isRestrictions(e){return"name"in e}validateRestrictionConfig(e){if(null==e||Array.isArray(e)||"object"!=typeof e)throw new Error("The `restrictions` argument must be a valid object with Channel restrictions!");if(this.isRestrictions(e)&&"string"!=typeof e.name)throw new Error("The `name` restriction property must be a non-empty string!");if(null!==e.read&&void 0!==e.read&&"boolean"!=typeof e.read)throw new Error("The `read` restriction property must be a boolean value!");if(null!==e.write&&void 0!==e.write&&"boolean"!=typeof e.write)throw new Error("The `write` restriction property must be a boolean value!");if(!(null!==e.read&&void 0!==e.read||null!==e.write&&void 0!==e.write))throw new Error("It's required to set either the `read` or the `write` property of the Channel restriction object!");null!==e.windowId&&void 0!==e.windowId&&this.validateWindowIdArg(e.windowId)}}const Hi="T42.Hotkeys.Command";class Bi{constructor(e){this.agm=e,this.registry=En(),this.firstHotkey=!0,this.hotkeys=new Map}async register(e,t){if(void 0===e)throw new Error("Hotkey parameter missing");if("string"==typeof e)e={hotkey:e};else{if(!e.hotkey)throw new Error("Info's hotkey parameter missing");e={hotkey:e.hotkey,description:e.description}}const n=this.formatHotkey(e.hotkey);if(this.hotkeys.has(n))throw new Error(`Shortcut for ${n} already registered`);this.firstHotkey&&(this.firstHotkey=!1,await this.registerInvokeAGMMethod()),this.registry.add(n,t),await this.agm.invoke(Hi,{command:"register",hotkey:n,description:e.description},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}),this.hotkeys.set(n,e)}async unregister(e){if(void 0===e)throw new Error("hotkey parameter missing");if("string"!=typeof e)throw new Error("hotkey parameter must be string");const t=this.formatHotkey(e);await this.agm.invoke(Hi,{command:"unregister",hotkey:t},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}),this.hotkeys.delete(t),this.registry.clearKey(t)}async unregisterAll(){await this.agm.invoke(Hi,{command:"unregisterAll"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}),this.hotkeys.clear(),this.registry.clear()}isRegistered(e){const t=this.formatHotkey(e);return this.hotkeys.has(t)}registerInvokeAGMMethod(){return this.agm.register("T42.Hotkeys.Invoke",e=>{const t=e.key.toLowerCase(),n=this.hotkeys.get(t);this.registry.execute(t,n)})}formatHotkey(e){if(e)return e.replace(/\s/g,"").toLowerCase()}}class Ji{constructor(){this.RESTART_METHOD_NAME="T42.ACS.Restart",this.SHUTDOWN_METHOD_NAME="T42.ACS.Shutdown",this.ON_SHUTTING_DOWN_METHOD_NAME="T42.ACS.OnGDShutdown",this._isMethodRegistered=!1,this._registry=En(),this._agmInvoke=(e,t)=>(t=t||{},new Promise((n,i)=>{this._interop.invoke(e,t,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}).then(e=>{n(e.returned)}).catch(e=>i(new Error(e.message||"Platform API call failed")))}))}init(e,t){this._interop=e,this._logger=t}restart(e){return this._agmInvoke(this.RESTART_METHOD_NAME,e)}shutdown(e){return this._agmInvoke(this.SHUTDOWN_METHOD_NAME,e)}onShuttingDown(e){return this.registerShutdownMethod(),this._registry.add("on-shutting-down",e)}toAPI(){return{restart:this.restart.bind(this),shutdown:this.shutdown.bind(this),onShuttingDown:this.onShuttingDown.bind(this)}}registerShutdownMethod(){this._isMethodRegistered||this._interop.register(this.ON_SHUTTING_DOWN_METHOD_NAME,async e=>{try{const t=await Promise.all(this._registry.execute("on-shutting-down",e));return{prevent:t.some(e=>e.prevent)}}catch(e){return this._logger.error("Error in onShuttingDown callbacks:",e),{prevent:!1}}}).then(()=>{this._logger.info("Successfully registered onShuttingDown method"),this._isMethodRegistered=!0}).catch(e=>{this._logger.error("Failed to register onShuttingDown method:",e)})}}var qi="6.17.0",Vi=e=>{function t(e,t,i){if("boolean"==typeof e&&!e)return;const r=n(e,t,i);return void 0!==r?"object"==typeof e?(e.mode=r,e):{mode:r}:void 0}function n(e,t,i){return"object"==typeof e?n(e.mode,t,i).toString():void 0===e?"boolean"!=typeof t||t?"boolean"==typeof t&&t?void 0===i?t:i:void 0===t?void 0:t:void 0:"boolean"==typeof e?e?void 0===i?t:i:void 0:e}const i="undefined"!=typeof window&&"undefined"!=typeof document&&"htmlContainer"in window,r=!$n.isNode()&&(!!i&&"trackMyTypeAndInitiatedFromMe"),o="slim",s=o,a="boolean"==typeof e.exposeAPI||"boolean"==typeof e.exposeGlue;return{layouts:t(e.layouts,o,s),activities:t(e.activities,r,"trackMyTypeAndInitiatedFromMe"),appManager:t(e.appManager,!0,"startOnly"),apps:t(e.apps,!0,!0),windows:t(e.windows,!0,!0),channels:t("boolean"==typeof e.channels?e.channels:!("object"!=typeof e.channels||"boolean"!=typeof e.channels.enabled||!e.channels.enabled)&&{mode:!0,...e.channels},!1,!0),displays:t(e.displays,!0,!0),exposeAPI:a||!0}};class zi{constructor(e){this.options=e,this.callbacks=En(),this.actions=e.actions,this.body=e.body,this.badge=e.badge,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.title=e.title}close(){throw new Error("Method not implemented.")}addEventListener(e,t,n){this.callbacks.add(e,t)}removeEventListener(e,t,n){}dispatchEvent(e){return this.callbacks.execute(e.type,e),!0}}class Ki{constructor(e,t){this.interop=e,this.onStreamEvent=t}onVisibilityChanged(e){return this.onStreamEvent("on-panel-visibility-changed",e)}toggle(){return this.interop.invoke("T42.Notifications.Show",void 0,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}show(){return this.interop.invoke("T42.Notifications.Show",{show:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}hide(){return this.interop.invoke("T42.Notifications.Hide")}async isVisible(){return(await this.interop.invoke("T42.Notifications.Execute",{command:"isPanelVisible"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.panelVisible}toAPI(){return{onVisibilityChanged:this.onVisibilityChanged.bind(this),toggle:this.toggle.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),isVisible:this.isVisible.bind(this)}}}class Qi{constructor(e,t){this.interop=e,this.NotificationsSubscribeStream="T42.GNS.Subscribe.Notifications",this.NotificationsCounterStream="T42.Notifications.Counter",this.RaiseNotificationMethodName="T42.GNS.Publish.RaiseNotification",this.NotificationsExecuteMethod="T42.Notifications.Execute",this.NotificationFilterMethodName="T42.Notifications.Filter",this.methodsRegistered=!1,this.NOTIFICATIONS_CONFIGURE_METHOD_NAME="T42.Notifications.Configure",this.methodNameRoot="T42.Notifications.Handler-"+$n.generateId(),this.nextId=0,this.notifications={},this.registry=En(),this.subscribedForNotifications=!1,this.subscribedCounterStream=!1,this.subscriptionsCountForNotifications=0,this.subscriptionsCountForCounter=0,this.logger=t.subLogger("notifications"),this._panel=new Ki(e,this.onStreamEventCore.bind(this)),this._panelAPI=this._panel.toAPI(),this.subscribeInternalEvents()}get maxActions(){return 10}get panel(){return this._panelAPI}async raise(e){var t;this.logger.debug(`raising notification with options: ${JSON.stringify(e)}`);const n=await this.createNotification(e),i=new zi(e);this.notifications[n.id]=i;try{const e=await this.interop.invoke(this.RaiseNotificationMethodName,{notification:n},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On});i.id=null===(t=e.returned)||void 0===t?void 0:t.id,this.logger.debug(`notification raised with id: ${i.id}`)}catch(t){this.logger.error(`failed to raise notification with options: ${JSON.stringify(e)}`,t);const n=t.message;setTimeout(()=>{this.handleNotificationErrorEvent(i,n)},1)}return i}async setFilter(e){return(await this.interop.invoke(this.NotificationFilterMethodName,e,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}async getFilter(){return(await this.interop.invoke(this.NotificationFilterMethodName,void 0,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}async configure(e){var t,n,i,r,o,s,a,c;if(!e||Array.isArray(e))throw new Error("Invalid options - should be an object.");if(0===Object.values(e).length)throw new Error("The argument must be a non-empty object.");if(void 0!==e.enable&&"boolean"!=typeof e.enable)throw new Error("Expected type of enabled - boolean.");if(void 0!==e.enableToasts&&"boolean"!=typeof e.enableToasts)throw new Error("Expected type of enableToasts - boolean.");if(void 0!==e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("Expected type of toastExpiry - number.");if(e.sourceFilter&&"object"!=typeof e.sourceFilter)throw new Error("Expected type of sourceFilter - object.");if((null===(t=e.sourceFilter)||void 0===t?void 0:t.allowed)&&!Array.isArray(null===(n=e.sourceFilter)||void 0===n?void 0:n.allowed))throw new Error("Expected type of sourceFilter.allowed - array.");if((null===(i=e.sourceFilter)||void 0===i?void 0:i.blocked)&&!Array.isArray(null===(r=e.sourceFilter)||void 0===r?void 0:r.blocked))throw new Error("Expected type of sourceFilter.blocked - array.");if(e.toasts&&"object"!=typeof e.toasts)throw new Error("Expected type of (options.toasts - object.");if((null===(o=e.toasts)||void 0===o?void 0:o.mode)&&"string"!=typeof e.toasts.mode)throw new Error("Expected type of (options.toasts.mode - string.");if((null===(s=e.toasts)||void 0===s?void 0:s.stackBy)&&"string"!=typeof e.toasts.stackBy)throw new Error("Expected type of (options.toasts.stackBy - string.");if(e.placement&&"object"!=typeof e.placement)throw new Error("Expected type of (options.placement - object.");if((null===(a=e.placement)||void 0===a?void 0:a.toasts)&&"string"!=typeof e.placement.toasts)throw new Error("Expected type of (options.placement.toasts - string.");if((null===(c=e.placement)||void 0===c?void 0:c.panel)&&"string"!=typeof e.placement.panel)throw new Error("Expected type of (options.placement.panel - string.");if(void 0!==e.closeNotificationOnClick&&"boolean"!=typeof e.closeNotificationOnClick)throw new Error("Expected type of closeNotificationOnClick - boolean.");return(await this.interop.invoke(this.NOTIFICATIONS_CONFIGURE_METHOD_NAME,e,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}async getConfiguration(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"getConfiguration"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}async list(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"list",data:{statesVersion2:!0}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.notifications}async updateData(e,t){const n={key:"data",value:{stringValue:JSON.stringify(t,(e,t)=>void 0===t?null:t)}};return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"create-or-update-attribute",data:{id:e,attribute:n}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}onRaised(e){return this.onStreamEventCore("on-notification-raised",e)}onStateChanged(e){return this.onStreamEventCore("on-state-changed",e)}onClosed(e){return this.onStreamEventCore("on-notification-closed",e)}onConfigurationChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-configuration-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}onCounterChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribeForCounterStream();const t=this.registry.add("on-counter-changed",e);return()=>{t(),this.closeStreamCounterSubscriptionIfNoNeeded()}}onDataChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-notification-data-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}async clearAll(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAll"},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async clearOld(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAllOld",data:{statesVersion2:!0}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async clear(e){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clear",data:{id:e}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async clearMany(e){this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearMany",data:{notifications:e}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async click(e,t,n){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"click",data:{id:e,action:t,options:n}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async snooze(e,t){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snooze",data:{id:e,duration:t}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async snoozeMany(e,t){if(!t)throw new Error("The 'duration' argument cannot be null or undefined");if("number"!=typeof t)throw new Error("The 'duration' argument must be a valid number");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snoozeMany",data:{notifications:e,duration:t}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async setState(e,t){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");if(!t)throw new Error("The 'state' argument cannot be null or undefined");this.validateState(t),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateState",data:{id:e,state:t}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async setStates(e,t){if(!t)throw new Error("The 'state' argument cannot be null or undefined");if("string"!=typeof t)throw new Error("The 'state' argument must be a valid string");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateStates",data:{notifications:e,state:t}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}toAPI(){return{maxActions:this.maxActions,panel:this._panel.toAPI(),raise:this.raise.bind(this),setFilter:this.setFilter.bind(this),getFilter:this.getFilter.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onStateChanged:this.onStateChanged.bind(this),onClosed:this.onClosed.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onCounterChanged:this.onCounterChanged.bind(this),onDataChanged:this.onDataChanged.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),clear:this.clear.bind(this),click:this.click.bind(this),setState:this.setState.bind(this),updateData:this.updateData.bind(this),snooze:this.snooze.bind(this),snoozeMany:this.snoozeMany.bind(this),clearMany:this.clearMany.bind(this),setStates:this.setStates.bind(this),import:this.importNotifications.bind(this)}}async importNotifications(e){if(!e||!Array.isArray(e)||0===e.length)throw new Error("Notifications argument must be a valid array with notification options");const t=await Promise.all(e.map(e=>this.createNotification(e,!0)));return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"importNotifications",data:{notificationSettings:t}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.notifications}async createNotification(e,t){var n,i,r,o;if(this.validate(e,t),!this.methodsRegistered){const e=[];for(let t=0;t<this.maxActions;t++)e.push(this.interop.register(`${this.methodNameRoot}_${t}`,this.handleNotificationEvent.bind(this)));this.methodsRegistered=!0,await Promise.all(e)}const s=null!==(n=e.id)&&void 0!==n?n:$n.generateId(),a=null!==(i=e.type)&&void 0!==i?i:"Notification",c={id:s,state:null!==(r=e.state)&&void 0!==r?r:"Active",title:e.title,type:a,severity:null!==(o=e.severity)&&void 0!==o?o:"None",description:e.body,glueRoutingDetailMethodName:`${this.methodNameRoot}_0`,actions:[],sourceId:s,source:e.source,publishExtraEvents:!0,clickInterop:e.clickInterop};return e.actions&&this.handleActions(e,s,c),this.handleOptions(e,c),c}onStreamEventCore(e,t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");this.subscribe();const n=this.registry.add(e,t);return()=>{n(),this.closeStreamSubscriptionIfNoNeeded()}}handleOptions(e,t){if(e.icon&&(t.attributes=t.attributes||[],t.attributes.push({key:"icon",value:{stringValue:e.icon}})),e.data){t.attributes=t.attributes||[];const n=JSON.stringify(e.data);t.attributes.push({key:"data",value:{stringValue:n}})}"number"==typeof e.panelExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"panelExpiry",value:{stringValue:e.panelExpiry.toString()}})),"number"==typeof e.toastExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"toastExpiry",value:{stringValue:e.toastExpiry.toString()}}))}handleActions(e,t,n){var i,r,o;const s=e.actions.slice(0,this.maxActions);let a=0;for(const e of s){const s={g42notificationId:t,g42action:e.action,g42interopMethod:null===(i=e.interop)||void 0===i?void 0:i.method,g42interopTarget:null===(r=e.interop)||void 0===r?void 0:r.target,g42interopArguments:JSON.stringify(null===(o=e.interop)||void 0===o?void 0:o.arguments)},c=Object.keys(s).map(e=>({name:e,value:{stringValue:s[e]}})),d={name:`${this.methodNameRoot}_${a}`,description:e.title,displayName:e.title,displayPath:e.displayPath,displayId:e.displayId,parameters:c};n.actions.push(d),a++}}validate(e,t){if(!e)throw new Error("invalid options - should be an object");if("object"!=typeof e)throw new Error("invalid options - should be an object");if(!e.title)throw new Error("invalid options - should have a title");if("string"!=typeof e.title)throw new Error("invalid options - title should be a string");if(e.severity&&"string"!=typeof e.severity)throw new Error("invalid options - severity should be a string");if(e.panelExpiry&&"number"!=typeof e.panelExpiry)throw new Error("invalid options - panelExpiry should be a number");if(e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("invalid options - toastExpiry should be a number");e.state&&this.validateState(e.state,t)}validateState(e,t){if("string"!=typeof e)throw new Error("The 'state' argument must be a string");const n=["Active","Acknowledged","Stale"];if(t&&n.push("Seen","Snoozed","Processing","Closed"),!n.includes(e))throw new Error(`The state argument: ${e} is not valid!`)}subscribe(){this.subscriptionsCountForNotifications++,this.subscribedForNotifications||(this.subscribedForNotifications=!0,this.logger.debug(`attempting to subscribe to "${this.NotificationsSubscribeStream}".`),this.interop.subscribe(this.NotificationsSubscribeStream,{arguments:{sendDeltaOnly:!0,statesVersion2:!0},waitTimeoutMs:On,methodResponseTimeout:On}).then(e=>{this.subscriptionForNotifications=e,this.logger.debug(`successfully subscribed to "${this.NotificationsSubscribeStream}".`),e.onData(({data:e})=>{this.handleData(e)}),e.onClosed((...e)=>{this.subscribedForNotifications=!1,this.logger.debug(`stream subscription Closed - ${JSON.stringify(e)}`)}),e.onFailed((...e)=>{this.subscribedForNotifications=!1,this.logger.warn(`stream subscription Failed - ${JSON.stringify(e)}`)})}).catch(e=>{this.subscribedForNotifications=!1,this.logger.error(`unable to subscribe to "${this.NotificationsSubscribeStream}"`,e)}))}subscribeForCounterStream(){this.subscriptionsCountForCounter++,this.subscribedCounterStream||(this.subscribedCounterStream=!0,this.logger.debug(`attempting to subscribe to "${this.NotificationsCounterStream}".`),this.interop.subscribe(this.NotificationsCounterStream,{arguments:{sendDeltaOnly:!0},waitTimeoutMs:On,methodResponseTimeout:On}).then(e=>{this.subscriptionForCounter=e,this.logger.debug(`successfully subscribed to "${this.NotificationsCounterStream}".`),e.onData(({data:e})=>{this.registry.execute("on-counter-changed",{count:e.count})}),e.onClosed((...e)=>{this.subscribedCounterStream=!1,this.logger.debug(`stream subscription Closed - ${JSON.stringify(e)}`)}),e.onFailed((...e)=>{this.subscribedCounterStream=!1,this.logger.warn(`stream subscription Failed - ${JSON.stringify(e)}`)})}).catch(e=>{this.subscribedCounterStream=!1,this.logger.error(`unable to subscribe to "${this.NotificationsCounterStream}"`,e)}))}subscribeInternalEvents(){this.registry.add("on-notification-closed",e=>{this.handleOnClosed(e)}),this.registry.add("on-notification-raised",e=>{this.handleOnShow(e.id)})}handleData(e){var t;try{"items"in e&&Array.isArray(e.items)?this.handleItemsData(e):"deltas"in e&&Array.isArray(e.deltas)&&this.handleDeltas(e),"configuration"in e&&"object"==typeof e.configuration&&(this.logger.debug(`received configuration ${JSON.stringify(e.configuration)} from the stream`),this.registry.execute("on-configuration-changed",e.configuration,e.configuration.allApplications)),"command"in e&&"string"==typeof e.command&&(this.logger.debug(`received command "${null!==(t=e.command)&&void 0!==t?t:JSON.stringify(e)}" from the stream`),"showPanel"!==e.command&&"hidePanel"!==e.command||this.registry.execute("on-panel-visibility-changed","showPanel"===e.command))}catch(e){this.logger.error("failed to parse data from the stream",e)}}handleItemsData(e){const t=e.items;this.logger.debug(`received ${t.length} notifications from the stream`);const n=t;if(e.isSnapshot)n.forEach(e=>{this.registry.execute("on-notification-raised",e)});else{const e=n[0];"Closed"===e.state?this.registry.execute("on-notification-closed",{id:e.id}):this.registry.execute("on-notification-raised",e)}}handleDeltas(e){e.deltas.forEach(e=>{var t;const n=e.id,i=null!==(t=e.delta)&&void 0!==t?t:{};if("Closed"===i.state)this.registry.execute("on-notification-closed",{id:n,...i});else if(i.state)this.registry.execute("on-state-changed",{id:n},i.state);else if(i.attributes){const e=i.attributes.find(e=>"data"===e.key);e&&this.registry.execute("on-notification-data-changed",{id:n},JSON.parse(e.value.stringValue))}})}handleOnClosed(e){const{notification:t,key:n}=this.getNotification(e);t&&(this.handleEvent(t,"close"),delete this.notifications[n])}handleOnShow(e){this.logger.debug(`handling on show for notification with id: ${e}`);const{notification:t}=this.getNotification(e);t&&this.handleEvent(t,"show")}getNotification(e){let t,n;for(const i in this.notifications)if(this.notifications[i].id===e){t=this.notifications[i],n=i;break}return{notification:t,key:n}}handleNotificationEvent(e){const t=this.getGnsNotificationArgs(e);if("unknown"===t.event)return void this.logger.warn(`unknown event type: ${t.event} for notification with id: ${t.notificationId}`);const n=this.notifications[t.notificationId];n?this.handleNotificationEventCore(n,t):this.logger.warn(`missing notification for event type: ${t.event} with id: ${t.notificationId}`)}handleNotificationEventCore(e,t){switch(this.logger.debug(`handling notification event: ${t.event} for notification with id: ${e.id}`),t.event){case"action":return this.handleNotificationActionEvent(e,t.notificationActionPayload);case"click":return this.handleNotificationClickEvent(e);case"close":return this.handleEvent(e,"close");case"error":return this.handleNotificationErrorEvent(e,t.error);case"show":return this.handleEvent(e,"show");default:this.logger.warn(`unknown event type: ${t.event} for notification with id: ${e.id}`)}}handleNotificationActionEvent(e,t){const n={type:"onaction",action:t.g42action};e.onaction&&e.onaction(n),this.logger.debug(`dispatching event "onaction" for notification with id: ${e.id}, action: ${t.g42action}`),e.dispatchEvent(n)}handleNotificationClickEvent(e){const t={type:"onclick"};e.onclick&&e.onclick(t),this.logger.debug(`dispatching event "onclick" for notification with id: ${e.id}`),e.dispatchEvent(t)}handleEvent(e,t){var n;const i={type:t},r=`on${t}`;null===(n=e[r])||void 0===n||n.call(e,i),this.logger.debug(`dispatching event "${r}" for notification with id: ${e.id}`),e.dispatchEvent(i)}handleNotificationErrorEvent(e,t){const n={type:"onerror",error:t};e.onerror&&e.onerror(n),this.logger.error(`dispatching event "onerror" for notification with id: ${e.id}`,t),e.dispatchEvent(n)}getGnsNotificationArgs(e){var t;let n;const i=null===(t=e.notification)||void 0===t?void 0:t.event;return n=i?{event:i,notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:this.getBackwardGnsNotificationArgs(e),n}getBackwardGnsNotificationArgs(e){var t;let n;return n=e.g42notificationId?{event:"action",notificationId:e.g42notificationId,notificationActionPayload:e}:(null===(t=e.notification)||void 0===t?void 0:t.sourceNotificationId)?{event:"click",notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:{event:"unknown",notificationId:void 0,notificationActionPayload:e},n}closeStreamSubscriptionIfNoNeeded(){this.subscriptionsCountForNotifications--,this.subscriptionForNotifications&&0===this.subscriptionsCountForNotifications&&(this.subscriptionForNotifications.close(),this.subscriptionForNotifications=void 0)}closeStreamCounterSubscriptionIfNoNeeded(){this.subscriptionsCountForCounter--,this.subscriptionForCounter&&0===this.subscriptionsCountForCounter&&(this.subscriptionForCounter.close(),this.subscriptionForCounter=void 0)}validateNotificationsArr(e){if(!Array.isArray(e))throw new Error("The 'notifications' argument must be an array with valid notification IDs");if(e.some(e=>"string"!=typeof e))throw new Error("The 'notifications' argument must contain only valid string notification IDs")}}class Zi{constructor(e,t){this.contexts=e,this.interop=t,this.registry=En(),this.isSubscribed=!1,this.getConfiguration()}async list(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");return(await this.getAll()).returned.all}async getCurrent(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");const e=await this.getAll();return e.returned.all.find(t=>t.name===e.returned.selected)}async select(e){if(await this.getConfiguration(),!this.setMethodName)throw new Error("not supported");await this.interop.invoke(this.setMethodName,{theme:e})}onChanged(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return this.subscribe(),this.registry.add("changed",e)}async getConfiguration(){try{if(this.sharedContextName)return;const e=await this.interop.invoke("T42.Themes.Configuration");this.sharedContextName=e.returned.sharedContextName,this.getMethodName=e.returned.getThemesMethodName,this.setMethodName=e.returned.setThemesMethodName}catch(e){return}}async getAll(){return await this.getConfiguration(),await this.interop.invoke(this.getMethodName)}async subscribe(){await this.getConfiguration(),this.isSubscribed||(this.isSubscribed=!0,this.contexts.subscribe(this.sharedContextName,e=>{e&&e.all&&e.selected&&this.registry.execute("changed",e.all.find(t=>t.name===e.selected))}))}}const Xi=["name","title","version","customProperties","icon","caption","type"],Yi=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var er=function(e){return{ok:!0,result:e}},tr=function(e){return{ok:!1,error:e}},nr=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:er(e(t.result,n.result))},ir=function(e,t){return!0===t.ok?t:tr(e(t.error))},rr=function(){return rr=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},rr.apply(this,arguments)};function or(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!or(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!or(e[i[n]],t[i[n]]))return!1}return!0}}var sr=function(e){return Array.isArray(e)},ar=function(e){return"object"==typeof e&&null!==e&&!sr(e)},cr=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},dr=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},hr=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return rr({at:e+(n||"")},i)},ur=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return ir(function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}},n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e(function(e){return function(e,t){return!0===t.ok?er(e(t.result)):t}(t,n.decode(e))})},this.andThen=function(t){return new e(function(e){return function(e,t){return!0===t.ok?e(t.result):t}(function(n){return t(n).decode(e)},n.decode(e))})},this.where=function(t,i){return n.andThen(function(n){return t(n)?e.succeed(n):e.fail(i)})}}return e.string=function(){return new e(function(e){return"string"==typeof e?er(e):tr({message:cr("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?er(e):tr({message:cr("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?er(e):tr({message:cr("a boolean",e)})})},e.constant=function(t){return new e(function(e){return or(e,t)?er(t):tr({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ar(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?tr({message:"the key '"+i+"' is required but was not present"}):tr(hr("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return er(n)}return ar(e)?er(e):tr({message:cr("an object",e)})})},e.array=function(t){return new e(function(e){if(sr(e)&&t){return e.reduce(function(e,n,i){return nr(function(e,t){return e.concat([t])},e,function(e,n){return ir(function(e){return hr("["+n+"]",e)},t.decode(e))}(n,i))},er([]))}return sr(e)?er(e):tr({message:cr("an array",e)})})},e.tuple=function(t){return new e(function(e){if(sr(e)){if(e.length!==t.length)return tr({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return tr(hr("["+i+"]",r.error));n[i]=r.result}return er(n)}return tr({message:cr("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return nr(Object.assign,t,n.decode(e))},er({}))})},e.anyJson=function(){return new e(function(e){return er(e)})},e.unknownJson=function(){return new e(function(e){return er(e)})},e.dict=function(t){return new e(function(e){if(ar(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return tr(hr("."+i,r.error));n[i]=r.result}return er(n)}return tr({message:cr("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?er(void 0):t.decode(e)})},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e(function(e){for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var o=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return tr({message:'expected a value matching one of the decoders, got the errors ["'+o+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return er(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))})},e.valueAt=function(t,n){return new e(function(e){for(var i=e,r=0;r<t.length;r++){if(void 0===i)return tr({at:dr(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ar(i))return tr({at:dr(t.slice(0,r+1)),message:cr("an object",i)});if("number"==typeof t[r]&&!sr(i))return tr({at:dr(t.slice(0,r+1)),message:cr("an array",i)});i=i[t[r]]}return ir(function(e){return void 0===i?{at:dr(t),message:"path does not exist"}:hr(dr(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return er(t)})},e.fail=function(t){return new e(function(e){return tr({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),lr=ur.string,pr=ur.number,gr=ur.boolean,fr=ur.anyJson;ur.unknownJson;var mr=ur.constant,yr=ur.object,wr=ur.array;ur.tuple;var vr=ur.dict,br=ur.optional,_r=ur.oneOf;ur.union,ur.intersection,ur.withDefault,ur.valueAt,ur.succeed,ur.fail,ur.lazy;const Ir=lr().where(e=>e.length>0,"Expected a non-empty string"),Cr=pr().where(e=>e>=0,"Expected a non-negative number"),Ar=yr({name:Ir,displayName:br(lr()),contexts:br(wr(lr())),customConfig:br(yr())}),Tr=_r(mr("web"),mr("native"),mr("citrix"),mr("onlineNative"),mr("other")),Sr=yr({url:Ir}),kr=yr({src:Ir,size:br(Ir),type:br(Ir)}),xr=yr({src:Ir,size:br(Ir),type:br(Ir),label:br(Ir)}),Er=yr({contexts:wr(Ir),displayName:br(Ir),resultType:br(Ir),customConfig:br(fr())}),Pr=yr({listensFor:br(vr(Er)),raises:br(vr(wr(Ir)))}),Mr=yr({broadcasts:br(wr(Ir)),listensFor:br(wr(Ir))}),Rr=yr({name:Ir,description:br(Ir),broadcasts:br(wr(Ir)),listensFor:br(wr(Ir))}),Nr=yr({intents:br(Pr),userChannels:br(Mr),appChannels:br(wr(Rr))}),Or=yr({url:br(Ir),top:br(pr()),left:br(pr()),width:br(Cr),height:br(Cr)}),jr=yr({name:br(Ir),type:br(Ir.where(e=>"window"===e,"Expected a value of window")),title:br(Ir),version:br(Ir),customProperties:br(fr()),icon:br(lr()),caption:br(lr()),details:br(Or),intents:br(wr(Ar)),hidden:br(gr())}),$r=yr({name:Ir,appId:Ir,title:br(Ir),version:br(Ir),manifest:Ir,manifestType:Ir,tooltip:br(Ir),description:br(Ir),contactEmail:br(Ir),supportEmail:br(Ir),publisher:br(Ir),images:br(wr(yr({url:br(Ir)}))),icons:br(wr(yr({icon:br(Ir)}))),customConfig:fr(),intents:br(wr(Ar))}),Wr=yr({appId:br(Ir),name:br(Ir),details:br(Sr),version:br(Ir),title:br(Ir),tooltip:br(Ir),lang:br(Ir),description:br(Ir),categories:br(wr(Ir)),icons:br(wr(kr)),screenshots:br(wr(xr)),contactEmail:br(Ir),supportEmail:br(Ir),moreInfo:br(Ir),publisher:br(Ir),customConfig:br(wr(fr())),hostManifests:br(fr()),interop:br(Nr)}),Dr=yr({appId:Ir,name:Ir,type:Tr,details:Sr,version:br(Ir),title:br(Ir),tooltip:br(Ir),lang:br(Ir),description:br(Ir),categories:br(wr(Ir)),icons:br(wr(kr)),screenshots:br(wr(xr)),contactEmail:br(Ir),supportEmail:br(Ir),moreInfo:br(Ir),publisher:br(Ir),customConfig:br(wr(fr())),hostManifests:br(fr()),interop:br(Nr),localizedVersions:br(vr(Wr))}),Fr=_r($r,Dr),Lr=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Gr{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=Fr.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:Lr(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=Fr.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Lr(i.error)}`);const r=this.getUserPropertiesFromDefinition(e,n),o={url:this.getUrl(e,n)},s={name:e.appId,type:"window",createOptions:o,userProperties:{...r,intents:"1.2"===n?r.intents:this.getIntentsFromV2AppDefinition(e),details:o},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,n),caption:e.description,fdc3:"2.0"===n?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return s;const c=jr.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Lr(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(s,c.result):s}parseToDesktopAppConfig(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=Fr.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Lr(i.error)}`);if("1.2"===n){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,n)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const r=e,o={name:r.appId,type:this.fdc3ToDesktopDefinitionType[r.type],details:r.details,version:r.version,title:r.title,tooltip:r.tooltip,caption:r.description,icon:this.getIconFromDefinition(r,"2.0"),intents:this.getIntentsFromV2AppDefinition(r),fdc3:{...r,definitionVersion:"2.0"}},s=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!s)return o;if("object"!=typeof s||Array.isArray(s))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(o,s)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!Xi.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!Xi.includes(e)&&!Yi.includes(e)))}getUrl(e,t){let n;if("1.2"===t){const t=JSON.parse(e.manifest);n=t.details?.url||t.url}else n=e.details?.url;if(!n||"string"!=typeof n)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return n}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map(e=>{const[t,n]=e;return{name:t,...n}})}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find(e=>e.icon)?.icon||void 0:e.icons?.find(e=>e.src)?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let n=e;if(t.details){const i={...e.createOptions,...t.details};n.createOptions=i,n.userProperties.details=i}return Array.isArray(t.intents)&&(n.userProperties.intents=(n.userProperties.intents||[]).concat(t.intents)),n={...n,...t},delete n.details,delete n.intents,n}mergeDesktopConfigWithGlueManifest(e,t){const n=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(n.intents=(e.intents||[]).concat(t.intents)),n}}const Ur={common:{nonEmptyStringDecoder:Ir,nonNegativeNumberDecoder:Cr},fdc3:{allDefinitionsDecoder:Fr,v1DefinitionDecoder:$r,v2DefinitionDecoder:Dr}};var Hr;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(Hr||(Hr={}));const Br=new class{_fdc3;_decoders=Ur;_errors={intents:Hr};get fdc3(){return this._fdc3||(this._fdc3=(new Gr).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};Br.fdc3,Br.decoders;const Jr=Br.errors,qr="Tick42.FDC3.Intents.",Vr=["applicationName","type"],zr=9e4,Kr=Jr.intents,Qr=(e,t,n)=>new Promise((i,r)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;r(n||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),i(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),r(e))})}),Zr=e=>{if(!e)throw new Error("Provide 'handlerFilter' with at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'");const{title:t,openResolver:n,timeout:i,intent:r,contextTypes:o,resultType:s,applicationNames:a,excludeList:c}=e;if(void 0!==t&&("string"!=typeof t||!t.length))throw new Error("Provide 'title' as a non empty string");if(void 0!==n&&"boolean"!=typeof n)throw new Error("Provide 'openResolver' prop as a boolean");if(void 0!==i&&("number"!=typeof i||i<=0))throw new Error("Provide 'timeout' prop as a positive number");if(void 0!==r&&("string"!=typeof r||!r.length))throw new Error("Provide 'intent' as a non empty string");if(void 0!==o&&(!Array.isArray(o)||o.some(e=>"string"!=typeof e)))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==s&&("string"!=typeof s||!s.length))throw new Error("Provide 'resultType' as a non empty string");if(void 0!==a&&(!Array.isArray(a)||a.some(e=>"string"!=typeof e)))throw new Error("Provide 'applicationNames' as an array of non empty strings");const d=!c||(e=>!!Array.isArray(e)&&(!!e.every(e=>"object"==typeof e&&!Array.isArray(e)&&null!==e)&&(!!e.every(e=>"applicationName"in e||"instanceId"in e)&&e.every(e=>"applicationName"in e?"string"==typeof e.applicationName&&e.applicationName.length:"instanceId"in e&&"string"==typeof e.instanceId&&e.instanceId.length))))(c);if(!d)throw new Error("Provide 'excludeList' as an array of objects with either 'applicationName' or 'instanceId' key");const h="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)throw new Error(h);if(!(r||s||(null==o?void 0:o.length)||(null==a?void 0:a.length)))throw new Error(h)},Xr=e=>{var t,n;if("string"!=typeof e.intent)return{isValid:!1,error:"Response object has invalid 'intent' key. Expected a string, got "+typeof e.intent};if((null===(t=e.userSettings)||void 0===t?void 0:t.preserveChoice)&&"boolean"!=typeof(null===(n=e.userSettings)||void 0===n?void 0:n.preserveChoice))return{isValid:!1,error:"Response object has invalid 'userSettings.preserveChoice' key. Expected a boolean, got "+typeof e.userSettings.preserveChoice};const{isValid:i,error:r}=(e=>{if("object"!=typeof e)return{isValid:!1,error:"Response object has invalid 'handler' key. Expected an object, got "+typeof e};const t=Vr.filter(t=>!(t in e));return t.length?{isValid:!1,error:`Handler in Response object does not provide compulsory keys: ${t.join(", ")}`}:{isValid:!0,ok:e}})(e.handler);return i?{isValid:!0,ok:e}:{isValid:i,error:r}},Yr=e=>{if((e=>{if(e){if("object"!=typeof e)throw new Error("Please provide the intent context as an object");if(e.type&&"string"!=typeof e.type)throw new Error("Please provide the intent context as an object with 'type' property as string");if(e.data&&"object"!=typeof e.data)throw new Error("Please provide the intent context as an object with 'data' property as object")}})(e.context),(e=>{if(e&&"string"!=typeof e&&"object"!=typeof e)throw new Error('Please provide the intent target as one of the valid values: "reuse", "startNew", { app: string }, { instance: string } ')})(e.target),(e=>{if(e){if("number"!=typeof e)throw new Error("Please provide the timeout as a number");if(e<=0)throw new Error("Please provide the timeout as a positive number")}})(e.timeout),(e=>{if(e&&"boolean"!=typeof e)throw new Error("Please provide waitUserResponseIndefinitely as a boolean")})(e.waitUserResponseIndefinitely),void 0!==e.clearSavedHandler&&"boolean"!=typeof e.clearSavedHandler)throw new Error("Please provide 'clearSavedHandler' as a boolean");e.handlers&&e.handlers.forEach(e=>(e=>{if(!e.applicationName)throw new Error(`Please provide applicationName for handler ${JSON.stringify(e)}`);if(!e.type)throw new Error(`Please provide type for handler ${JSON.stringify(e)}`);if("instance"===e.type&&!e.instanceId)throw new Error(`Please provide instanceId for handler ${JSON.stringify(e)}`)})(e))};class eo{constructor(e,t,n,i,r,o){this.interop=e,this.windows=t,this.logger=n,this.prefsController=r,this.appsController=o,this.myIntents=new Set,this.intentsResolverResponsePromises={},this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[],this.addedHandlerInfoPerApp={},this.checkIfIntentsResolverIsEnabled(i,o)}async find(e){await Promise.all(this.unregisterIntentPromises);let t=await this.all();if(void 0===e)return t;if("string"==typeof e)return t.filter(t=>t.name===e);if("object"!=typeof e)throw new Error("Please provide the intentFilter as a string or an object!");if(e.contextType){const n=e.contextType.toLowerCase();t=t.filter(e=>e.handlers.some(e=>{var t;return null===(t=e.contextTypes)||void 0===t?void 0:t.some(e=>e.toLowerCase()===n)}))}if(e.resultType){const n=e.resultType.toLowerCase();t=t.filter(e=>e.handlers.some(e=>{var t;return(null===(t=e.resultType)||void 0===t?void 0:t.toLowerCase())===n}))}if(e.name){if("string"!=typeof e.name)throw new Error("Please provide the intentFilter as a string or an object!");t=t.filter(t=>t.name===e.name)}return t}async raise(e){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");"string"==typeof e&&(e={intent:e}),Yr(e),await Promise.all(this.unregisterIntentPromises),e.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${e.intent}`),await this.removeRememberedHandler(e.intent));const t={},n=e.timeout||zr,i=await this.checkHandleRaiseWithRememberedHandler(e,t,n);if(i)return i;const r=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:t,timeout:n});if(e.waitUserResponseIndefinitely)return r();const o=Qr(r,n,`${Kr.TIMEOUT_HIT} hit for intent request ${JSON.stringify(e)}`);return o.catch(()=>this.handleRaiseOnError(t.instanceId)),o}async all(){let e;await Promise.all(this.unregisterIntentPromises);try{const t=await this.interop.invoke("T42.ACS.GetApplications",{withIntentsInfo:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On});e=t.returned.applications}catch(e){return this.logger.error("Failed to get the applications!",e),[]}const t={},n=e.filter(e=>e.intents&&e.intents.length>0);for(const e of n)for(const n of e.intents){let i=t[n.name];i||(i={name:n.name,handlers:[]},t[n.name]=i);const r={applicationName:e.name,applicationTitle:e.title||"",applicationDescription:e.caption,displayName:n.displayName,contextTypes:n.contexts,applicationIcon:e.icon,type:"app",resultType:n.resultType,customConfig:null==n?void 0:n.customConfig};i.handlers.push(r)}const i=this.interop.servers(),r=i.map(e=>e.windowId).filter(e=>void 0!==e),o="T42.Wnd.GetInfo";let s;if(this.interop.methods().some(e=>e.name===o))try{const e=await this.interop.invoke(o,{ids:r},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On});s=e.returned.windows}catch(e){}for(const n of i)await Promise.all(n.getMethods().filter(e=>e.name.startsWith(qr)).map(async i=>{const r=i.name.replace(qr,"");let o=t[r];o||(o={name:r,handlers:[]},t[r]=o);const a=await this.windowsIdToTitle(n.windowId,s),c=this.constructIntentHandler({method:i,apps:e,server:n,intentName:r,title:a});o.handlers.push(c)}));return Object.values(t)}addIntentListener(e,t){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof t)throw new Error("Please provide the handler as a function!");const n="string"==typeof e?e:e.intent,i=`${qr}${n}`;let r,o={};if(this.myIntents.has(n))throw new Error(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);const s={unsubscribe:()=>{this.myIntents.delete(n),r.then(()=>this.interop.unregister(i)).catch(e=>this.logger.trace(`Unregistration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`))}};if("object"==typeof e){const{intent:t,...n}=e;o=n}return r=this.interop.register({name:i,flags:{intent:o}},e=>{if(this.myIntents.has(n))return t(e)}),r.catch(e=>{this.myIntents.delete(n),this.logger.warn(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}),s}async register(e,t){if((e=>{if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("string"!=typeof e){if(void 0!==e.contextTypes&&(!Array.isArray(e.contextTypes)||e.contextTypes.some(e=>"string"!=typeof e)))throw new Error("Please provide the 'contextTypes' as an array of strings!");if(void 0!==e.resultType&&"string"!=typeof e.resultType)throw new Error("Please provide the 'resultType' as a string!");if(void 0!==e.displayName&&"string"!=typeof e.displayName)throw new Error("Please provide the 'displayName' as a string!");if(void 0!==e.icon&&"string"!=typeof e.icon)throw new Error("Please provide the 'icon' as a string!");if(void 0!==e.description&&"string"!=typeof e.description)throw new Error("Please provide the 'description' as a string!");if(void 0!==e.customConfig&&("object"!=typeof e.customConfig||Array.isArray(e.customConfig)))throw new Error("Please provide the 'customConfig' as an object!")}})(e),"function"!=typeof t)throw new Error("Please provide the handler as a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);let r={};if(this.myIntents.has(n))throw new Error(`Intent listener for intent ${n} already registered!`);if(this.myIntents.add(n),"object"==typeof e){const{intent:t,...n}=e;r=n}try{await this.interop.register({name:i,flags:{intent:r}},(e,i)=>{if(this.myIntents.has(n))return t(e,i)})}catch(e){throw this.myIntents.delete(n),new Error(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async filterHandlers(e){var t,n;if(Zr(e),e.openResolver&&!this.useIntentsResolverUI)throw new Error("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");null===(t=this.logger)||void 0===t||t.trace(`Received 'filterHandlers' command with request: ${JSON.stringify(e)}`);const i=await this.all(),r=this.filterHandlersBy(i,e);if(!(null==r?void 0:r.length))return{handlers:[]};const{open:o,reason:s}=await this.checkIfResolverShouldBeOpenedForFilterHandlers(r,e);if(!o)return null===(n=this.logger)||void 0===n||n.trace(`Intent Resolver UI won't be used. Reason: ${s}`),{handlers:r};const a={instanceId:void 0},c=e.timeout||9e4;return{handlers:[await Qr(()=>this.startResolverApp({request:e,resolverInstance:a,method:"filterHandlers"}),c,`Timeout of ${c}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e)}`)]}}async getIntents(e){var t;this.logger.trace(`Received 'getIntents' command with handler ${JSON.stringify(e)}`),(e=>{if("object"!=typeof e)throw new Error("IntentHandler must be an object");if("string"!=typeof e.applicationName||!e.applicationName.length)throw new Error("Please provide 'applicationName' as a non-empty string");if("string"!=typeof e.type||!["app","instance"].includes(e.type))throw new Error(`Invalid 'type' property. Expected 'app' | 'instance' got ${e.type}`);if(void 0!==e.applicationTitle&&"string"!=typeof e.applicationTitle)throw new Error("Provide 'applicationTitle' as a string");if(void 0!==e.applicationDescription&&"string"!=typeof e.applicationDescription)throw new Error("Provide 'applicationDescription' as a string");if(void 0!==e.applicationIcon&&"string"!=typeof e.applicationIcon)throw new Error("Provide 'applicationIcon' as a string");if(void 0!==e.displayName&&"string"!=typeof e.displayName)throw new Error("Provide 'displayName' as a string");if(void 0!==e.contextTypes&&(!Array.isArray(e.contextTypes)||e.contextTypes.some(e=>"string"!=typeof e)))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==e.instanceId&&"string"!=typeof e.instanceId)throw new Error("Provide 'instanceId' as a string");if(void 0!==e.instanceTitle&&"string"!=typeof e.instanceTitle)throw new Error("Provide 'instanceTitle' as a string");if(void 0!==e.resultType&&"string"!=typeof e.resultType)throw new Error("Provide 'resultType' as a string")})(e);const n=await this.all();var i;i=e,Object.keys(i).forEach(e=>{null!==i[e]&&void 0!==i[e]||delete i[e]}),null===(t=this.logger)||void 0===t||t.trace("Extracting valid intents for the passed handler");const r=this.extractIntentsWithInfoByHandler(n,e);return this.logger.trace(`Returning intents for handler ${JSON.stringify(e)}`),{intents:r}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:null},{app:this.getMyAppName()})}onHandlerAdded(e){var t;if("function"!=typeof e)throw new Error("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const n=null===(t=this.appsController)||void 0===t?void 0:t.onAdded(async(t,n)=>{var i;const r=t.app.name,o=n;(null===(i=null==o?void 0:o.intents)||void 0===i?void 0:i.length)&&o.intents.forEach(t=>{const n=this.constructIntentHandlerFromApp(o,t);this.addedHandlerInfoPerApp[r]||(this.addedHandlerInfoPerApp[r]=[]);this.addedHandlerInfoPerApp[r].push({handler:n,name:t.name}),e(n,t.name)})},!0),i=this.interop.serverMethodAdded(({method:t,server:n})=>{if(!t.name.startsWith(qr))return;const i=t.name.replace(qr,""),r=this.constructIntentHandler({method:t,apps:[],server:n,intentName:i,title:""});e(r,i)});return()=>{"function"==typeof i&&i(),n.then(e=>{"function"==typeof e&&e()})}}onHandlerRemoved(e){var t;if("function"!=typeof e)throw new Error("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const n=null===(t=this.appsController)||void 0===t?void 0:t.onRemoved(async t=>{const n=t.appName,i=this.addedHandlerInfoPerApp[n];(null==i?void 0:i.length)&&(delete this.addedHandlerInfoPerApp[n],i.forEach(t=>{e(t.handler,t.name)}))}),i=this.interop.serverMethodRemoved(({method:t,server:n})=>{if(!t.name.startsWith(qr))return;const i=t.name.replace(qr,""),r=this.constructIntentHandler({method:t,apps:[],server:n,intentName:i,title:""});e(r,i)});return()=>{"function"==typeof i&&i(),null==n||n.then(e=>{"function"==typeof e&&e()})}}toAPI(){return{all:this.all.bind(this),find:this.find.bind(this),raise:this.raise.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntents.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}filterHandlersBy(e,t){const n=e.filter(e=>{if(!t.intent||t.intent===e.name){if(t.excludeList&&(e.handlers=this.excludeIntentHandlers(e,t.excludeList)),t.resultType){const n=e.handlers.filter(e=>e.resultType&&e.resultType===t.resultType);if(!n.length)return;e.handlers=n}if(t.contextTypes){const n=e.handlers.filter(e=>{var n;return null===(n=t.contextTypes)||void 0===n?void 0:n.every(t=>{var n;return null===(n=e.contextTypes)||void 0===n?void 0:n.includes(t)})});if(!n.length)return;e.handlers=n}if(t.applicationNames){const n=e.handlers.filter(e=>{var n;return null===(n=t.applicationNames)||void 0===n?void 0:n.includes(e.applicationName)});if(!n.length)return;e.handlers=n}return e}});return n.map(e=>e.handlers).flat(1)}excludeIntentHandlers(e,t){return e.handlers.filter(e=>!t.some(t=>"applicationName"in t?t.applicationName===e.applicationName:"instanceId"in t&&t.instanceId===e.instanceId))}async coreRaiseIntent({request:e,resolverInstance:t,timeout:n,resolverConfig:i}){var r,o;const s=await this.get(e.intent);if(void 0===s)throw new Error(`${Kr.INTENT_NOT_FOUND} with name ${e.intent}`);const{open:a,reason:c}=await this.checkIfResolverShouldBeOpenedForRaise(s,e,i);if(!a)return this.logger.trace(`Intent Resolver UI won't be used. Reason: ${c}`),e.waitUserResponseIndefinitely?Qr(()=>this.raiseIntent(e,n),n,`${Kr.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`):this.raiseIntent(e,n);const d=await this.startResolverApp({request:e,method:"raise",resolverInstance:t});if(null===(r=this.logger)||void 0===r||r.trace(`Raising intent to target handler: ${JSON.stringify(d)} with timeout of ${n}`),e.waitUserResponseIndefinitely)return Qr(()=>this.raiseIntentToTargetHandler(e,d,n),n,`${Kr.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`);const h=await this.raiseIntentToTargetHandler(e,d,n);return null===(o=this.logger)||void 0===o||o.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(h)}`),h}async get(e){return(await this.all()).find(t=>t.name===e)}async raiseIntent(e,t){const n=e.intent,i=await this.get(n);if(void 0===i)throw new Error(`${Kr.INTENT_NOT_FOUND} with name ${e.intent}`);const r=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(i.handlers,{type:"app"}),o=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(i.handlers,{type:"instance"});let s;if(e.target&&"reuse"!==e.target||(s=o||r),"startNew"===e.target&&(s=r),"object"==typeof e.target&&e.target.app&&(s=this.findHandlerByFilter(i.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(s=this.findHandlerByFilter(i.handlers,{instance:e.target.instance,app:e.target.app})),!s)throw new Error(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler(e,s,t)}async raiseIntentToTargetHandler(e,t,n){var i,r;if(null===(i=this.logger)||void 0===i||i.trace(`Raising intent to target handler:${JSON.stringify(t)}`),!t.instanceId){const n=this.invokeStartApp(t.applicationName,e.context,e.options).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e);throw new Error(`${Kr.TARGET_INSTANCE_UNAVAILABLE}. Reason: ${t}`)});t.instanceId=await n}const o=`${qr}${e.intent}`,s={methodResponseTimeoutMs:n?n+1e3:6e4,waitTimeoutMs:n?n+1e3:6e4},a=this.interop.invoke(o,e.context,{instance:t.instanceId},s).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e);throw new Error(`${Kr.INTENT_HANDLER_REJECTION}. Reason: ${t}`)}),c=await a;return null===(r=this.logger)||void 0===r||r.trace(`raiseIntent command completed. Returning result: ${JSON.stringify(c)}`),{request:e,handler:{...t,type:"instance"},result:c.returned}}async startResolverApp({request:e,method:t,resolverInstance:n}){var i,r,o,s;null===(i=this.logger)||void 0===i||i.trace(`Intents Resolver UI with app name ${this.intentsResolverAppName} will be used for request: ${JSON.stringify(e)}`);const a=await this.registerIntentResolverMethod();null===(r=this.logger)||void 0===r||r.trace(`Registered interop method ${a}`);const c=await this.buildStartContext(t,e,a),d=await this.buildStartOptions();null===(o=this.logger)||void 0===o||o.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(c)} and options: ${JSON.stringify(d)}`);const h=await this.appsController.start({name:this.intentsResolverAppName,context:c,definitionOverride:d});n.instanceId=h.id,null===(s=this.logger)||void 0===s||s.trace(`Intents Resolver instance with id ${h.id} opened`),await this.subscribeOnInstanceStopped(h,t);const u=e.timeout||"raise"===t?zr:9e4;this.createResponsePromise({intent:"raise"===t?e.intent:void 0,instanceId:h.id,responseMethodName:a,timeout:u,errorMsg:`Timeout of ${u}ms hit waiting for the user to choose a handler ${"raise"===t?`for intent ${e.intent}`:`for '${t}' method with filter ${JSON.stringify(e)}`}`});return await this.handleInstanceResponse({instanceId:h.id,caller:c.initialCaller,method:t,request:e})}async windowsIdToTitle(e,t){var n,i;if(void 0!==t)return null===(n=t.find(t=>t.id===e))||void 0===n?void 0:n.title;const r=null===(i=this.windows)||void 0===i?void 0:i.findById(e);return await(null==r?void 0:r.getTitle())}async handleInstanceResponse({instanceId:e,method:t,request:n,caller:i}){var r,o,s;try{const a=await this.intentsResolverResponsePromises[e].promise,c="raise"===t?`for intent ${a.intent} `:"";return null===(r=this.logger)||void 0===r||r.trace(`Intent handler chosen ${c}: ${JSON.stringify(a.handler)}. Stopping resolver instance with id ${e}`),this.stopResolverInstance(e),null===(o=this.logger)||void 0===o||o.trace(`Instance with id ${e} successfully stopped`),(null===(s=a.userSettings)||void 0===s?void 0:s.preserveChoice)&&await this.saveUserChoice({intent:a.intent,handler:a.handler,filter:"filterHandlers"===t?{applicationNames:n.applicationNames,contextTypes:n.contextTypes,resultType:n.resultType}:void 0,caller:i}),a.handler}catch(t){throw this.stopResolverInstance(e),new Error(t)}}async registerIntentResolverMethod(){const e="T42.Intents.Resolver.Control"+$n.generateId();return await this.interop.register(e,(e,t)=>this.resolverResponseHandler(e,t)),e}resolverResponseHandler(e,t){const{instance:n}=t,i=Xr(e);if(!i)return this.logger.trace(`Intent Resolver instance with id ${t.instance} sent invalid response. Error: ${i.error}`),this.intentsResolverResponsePromises[n].reject(i.error),void this.stopResolverInstance(n);const r=i.ok;this.intentsResolverResponsePromises[n].resolve(r),this.cleanUpIntentResolverPromise(n)}async buildStartContext(e,t,n){const i=this.getMyAppName(),r=(await this.appsController.getApp(i)).title||"",o={callerId:this.interop.instance.instance,methodName:n,initialCaller:{id:this.interop.instance.instance,applicationName:i,applicationTitle:r},resolverApi:"1.0"};return"raise"===e?{...o,intent:t}:{...o,handlerFilter:t}}async buildStartOptions(){const e=this.windows.my();if(!e)return;const t=await e.getBounds();return{top:await this.getResolverStartupTopBound(t),left:(t.width-400)/2+t.left,width:400,height:440}}async getResolverStartupTopBound(e){const t=(await this.windows.my().getDisplay()).workArea.height,n=(e.height-440)/2+e.top;return n<0?0:n+440>t?t/2:n}createResponsePromise({instanceId:e,intent:t,responseMethodName:n,timeout:i,errorMsg:r}){let o=()=>{},s=()=>{};const a=((e,t,n)=>new Promise((i,r)=>{const o=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),i(e)}).catch(e=>{clearTimeout(o),r(e)})}))((e,t)=>{o=e,s=t},i,r);this.intentsResolverResponsePromises[e]={intent:t,resolve:o,reject:s,promise:a,methodName:n}}async invokeStartApp(e,t,n){return(await this.interop.invoke("T42.ACS.StartApplication",{Name:e,options:{...n,startedByIntentAPI:!0}},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned.Id}async subscribeOnInstanceStopped(e,t){const n=await this.appsController.onInstanceStopped(i=>{if(i.id!==e.id)return;const r=this.intentsResolverResponsePromises[i.id];if(!r)return n();const o=`Cannot resolve ${"raise"===t?`raised intent ${r.intent}`:`'${t}' method`} - User closed ${e.appName} app without choosing a handler`;r.reject(o),this.cleanUpIntentResolverPromise(i.id),n()})}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch(e=>this.logger.warn(e)),delete this.intentsResolverResponsePromises[e]}handleRaiseOnError(e){e&&this.stopResolverInstance(e)}stopResolverInstance(e){const t=this.windows.findById(e);null==t||t.close().catch(e=>this.logger.error(e))}checkIfIntentsResolverIsEnabled(e,t){var n,i,r,o,s;t.isInitialized()?(this.useIntentsResolverUI="boolean"!=typeof(null===(n=e.intents)||void 0===n?void 0:n.enableIntentsResolverUI)||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(r=null===(i=e.intents)||void 0===i?void 0:i.intentsResolverAppName)&&void 0!==r?r:"intentsResolver",this.intentsResolverResponseTimeout=null!==(s=null===(o=e.intents)||void 0===o?void 0:o.methodResponseTimeoutMs)&&void 0!==s?s:6e4):this.useIntentsResolverUI=!1}async checkIfResolverShouldBeOpenedForRaise(e,t,n){if(n&&!n.enabled)return{open:!1,reason:"Intents Resolver is disabled"};const i=await this.checkIfIntentsResolverShouldBeOpened();if(!i.open)return i;return await this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:`Raised intent ${e.name} has only one handler`}}async checkIfResolverShouldBeOpenedForFilterHandlers(e,t){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:"boolean"!=typeof(null==t?void 0:t.openResolver)||t.openResolver?this.checkIfIntentsResolverShouldBeOpened():{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}}async checkIfIntentsResolverShouldBeOpened(){if(!this.useIntentsResolverUI)return{open:!1,reason:"Intent Resolver is disabled. Resolving to first found handler"};return await this.appsController.getApp(this.intentsResolverAppName)?{open:!0}:{open:!1,reason:`Intent Resolver Application with name ${this.intentsResolverAppName} not found.`}}async checkIfIntentHasMoreThanOneHandler(e,t){const n=await this.removeSingletons(t.handlers||e.handlers);if(!t.target)return n.length>1;if("reuse"===t.target)return n.filter(e=>"instance"===e.type&&e.instanceId).length>1||e.handlers.filter(e=>"app"===e.type).length>1;if("startNew"===t.target)return n.filter(e=>"app"===e.type).length>1;if(t.target.instance)return!1;if(t.target.app){const e=t.target.app;return n.filter(t=>t.applicationName===e&&t.instanceId).length>1}return!1}async removeSingletons(e){return(await Promise.all(e.map(async e=>{if("instance"===e.type)return e;const t=await this.appsController.getApp(e.applicationName),n=!1===(null==t?void 0:t.allowMultiple);return{...e,isSingleton:n}}))).filter((e,t,n)=>{if(e.instanceId||!e.isSingleton)return e;return n.find(t=>t.instanceId&&t.applicationName===e.applicationName)?void 0:e})}buildInteropMethodName(e){return`${qr}${e}`}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter(t=>t!==e)}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),n=this.interop.unregister(t);this.unregisterIntentPromises.push(n),n.then(()=>{this.clearUnregistrationPromise(n)}).catch(e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: `,e),this.clearUnregistrationPromise(n)})}findHandlerByFilter(e,t){return t.type?e.find(e=>e.type===t.type):t.instance?e.find(e=>t.app?e.applicationName===t.app&&e.instanceId===t.instance:e.instanceId===t.instance):t.app?e.find(e=>e.applicationName===t.app):void 0}extractIntentsWithInfoByHandler(e,t){const n=e.reduce((e,n)=>(n.handlers.forEach(i=>{const r=Object.keys(t).every(e=>{var n;return"contextTypes"===e?null===(n=t.contextTypes)||void 0===n?void 0:n.every(e=>{var t;return null===(t=i.contextTypes)||void 0===t?void 0:t.includes(e)}):i[e]===t[e]});if(!r)return;const o={intent:n.name,contextTypes:i.contextTypes,description:i.applicationDescription,displayName:i.displayName,icon:i.applicationIcon,resultType:i.resultType};e.push(o)}),e),[]);return n}getMyAppName(){return this.interop.instance.application||this.interop.instance.applicationName}async removeRememberedHandler(e){var t;let n;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{n=await this.prefsController.get(this.getMyAppName())}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${"string"==typeof e?e:JSON.stringify(e)}`)}const i=null===(t=n.data)||void 0===t?void 0:t.intents;if(!i)return void this.logger.trace("No app prefs found for current app");delete i[e];const r={...n.data,intents:i};try{await this.prefsController.update(r,{app:this.getMyAppName()})}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${"string"==typeof e?e:JSON.stringify(e)}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){var t,n;let i;try{i=await this.prefsController.get(this.getMyAppName())}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${"string"==typeof e?e:JSON.stringify(e)}`)}const r=null===(n=null===(t=i.data)||void 0===t?void 0:t.intents)||void 0===n?void 0:n[e.intent];return null==r?void 0:r.handler}async checkHandleRaiseWithRememberedHandler(e,t,n){if(e.target)return;const i=await this.checkForRememberedHandler(e);if(!i)return;const r={...e,target:{app:i.applicationName,instance:i.instanceId}},o={enabled:!1,appName:this.intentsResolverAppName,waitResponseTimeout:e.waitUserResponseIndefinitely?2147483647:e.timeout||zr};try{return await this.coreRaiseIntent({request:r,resolverInstance:t,timeout:n,resolverConfig:o})}catch(t){this.logger.trace("Could not raise intent to remembered handler. Removing it from Prefs store"),await this.removeRememberedHandler(e.intent)}}async saveUserChoice({intent:e,handler:t,filter:n}){var i,r;const o=await this.prefsController.get(this.getMyAppName()),s=(null===(i=null==o?void 0:o.data)||void 0===i?void 0:i.intents)||{},a={...o.data,intents:{...s,[e]:{handler:t,filter:n}}};await this.prefsController.update(a,{app:this.getMyAppName()}),null===(r=this.logger)||void 0===r||r.info(`Saved user's choice of handler for '${this.getMyAppName()}' app`)}constructIntentHandler({apps:e,intentName:t,method:n,server:i,title:r}){const o=n.flags.intent,s=e.find(e=>e.name===i.application);let a;(null==s?void 0:s.intents)&&(a=s.intents.find(e=>e.name===t));return{instanceId:i.instance,applicationName:i.application,applicationIcon:o.icon||(null==s?void 0:s.icon),applicationTitle:(null==s?void 0:s.title)||"",applicationDescription:o.description||(null==s?void 0:s.caption),displayName:o.displayName||(null==a?void 0:a.displayName),contextTypes:o.contextTypes||(null==a?void 0:a.contexts),instanceTitle:r,type:"instance",resultType:(null==a?void 0:a.resultType)||o.resultType,customConfig:null==o?void 0:o.customConfig}}constructIntentHandlerFromApp(e,t){return{applicationName:e.name,applicationTitle:e.title||"",applicationDescription:e.caption,displayName:t.displayName,contextTypes:t.contexts,applicationIcon:e.icon,type:"app",resultType:t.resultType,customConfig:null==t?void 0:t.customConfig}}}class to{constructor(e,t){this.appName=e,this.interop=t,this.registry=En(),this.interopMethodRegistered=!1}async get(e){Rt(e)||this.verifyApp(e);return(await this.interop.invoke(to.T42GetPrefsMethodName,{app:null!=e?e:this.appName},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}async set(e,t){var n;this.verifyDataObject(e),Rt(t)||this.verifyOptions(t),await this.interop.invoke(to.T42SetPrefsMethodName,{app:null!==(n=null==t?void 0:t.app)&&void 0!==n?n:this.appName,data:e,merge:!1},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async setFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.set(t,{app:e})}async update(e,t){this.verifyDataObject(e);let n=this.appName;!Rt(t)&&"app"in t&&(this.verifyApp(t.app),n=t.app),await this.interop.invoke(to.T42SetPrefsMethodName,{app:n,data:e,merge:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async updateFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.update(t,{app:e})}async clear(e){await this.interop.invoke(to.T42SetPrefsMethodName,{app:null!=e?e:this.appName,clear:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async clearFor(e){this.verifyApp(e),await this.interop.invoke(to.T42SetPrefsMethodName,{app:e,clear:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}async getAll(){return(await this.interop.invoke(to.T42GetPrefsMethodName,void 0,"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}async clearAll(){await this.interop.invoke(to.T42SetPrefsMethodName,{clear:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}subscribe(e){return this.verifyCallback(e),this.subscribeFor(this.appName,e)}subscribeFor(e,t){this.verifyApp(e),this.verifyCallback(t);const n=this.registry.add(e,t);return this.registerInteropIfNeeded().then(()=>{this.interop.invoke(to.T42GetPrefsMethodName,{app:e,subscribe:!0},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})}),()=>{n()}}async registerInteropIfNeeded(){this.interopMethodRegistered||(this.interopMethodRegistered=!0,await this.interop.register(to.T42UpdatePrefsMethodName,e=>{this.registry.execute(e.app,e)}))}verifyApp(e){if(!e)throw new Error("app argument should be a valid string");if(!xt(e))throw new Error("app should be a string")}verifyDataObject(e){if(!e)throw new Error("data should be defined");if(!Et(e))throw new Error("data should be an object")}verifyCallback(e){if(!jt(e))throw new Error("callback should be defined")}verifyOptions(e){if("object"!=typeof e)throw new Error("options argument should be an object");this.verifyApp(e.app)}}to.T42UpdatePrefsMethodName="T42.Prefs.Update",to.T42GetPrefsMethodName="T42.Prefs.Get",to.T42SetPrefsMethodName="T42.Prefs.Set";class no{constructor(e,t){this.methodName=e,this.interop=t}async get(e){return(await this.invoke("get-cookies",{filter:e})).returned.cookies}async set(e){this.verifyCookieObject(e),await this.invoke("set-cookie",e)}async remove(e,t){if(!xt(e))throw new Error("url should be a string");if(!xt(t))throw new Error("name should be a string");await this.invoke("remove-cookie",{url:e,name:t})}invoke(e,t){return this.interop.invoke(this.methodName,{command:e,args:t},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:Nn})}verifyCookieObject(e){if(!e)throw new Error("cookie should be defined");if(!Et(e))throw new Error("cookie should be an object");if($n.isNullOrUndefined(e.url)||!xt(e.url))throw new Error("cookie.url should be a string");if($n.isNullOrUndefined(e.name)||!xt(e.name))throw new Error("cookie.name should be a string");if(!$n.isNullOrUndefined(e.value)&&!xt(e.value))throw new Error("cookie.value should be a string");if(!$n.isNullOrUndefined(e.domain)&&!xt(e.domain))throw new Error("cookie.domain should be a string");if(!$n.isNullOrUndefined(e.path)&&!xt(e.path))throw new Error("cookie.path should be a string");if(!$n.isNullOrUndefined(e.secure)&&"boolean"!=typeof e.secure)throw new Error("cookie.secure should be a boolean");if(!$n.isNullOrUndefined(e.httpOnly)&&"boolean"!=typeof e.httpOnly)throw new Error("cookie.httpOnly should be a boolean");if(!$n.isNullOrUndefined(e.expirationDate)&&"number"!=typeof e.expirationDate)throw new Error("cookie.expirationDate should be a number")}}class io{constructor(e){this.config=e,this.glue42EventName="Glue42",this.events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)}}}start(e){this.glue=e,$n.isNode()?e.interop.invoke("T42.GD.Execute",{command:"announce-instance-ready",args:this.getAnnounceInfo()}).catch(()=>{}):(this.wireCustomEventListener(),this.announceStarted())}wireCustomEventListener(){window.addEventListener(this.glue42EventName,e=>{const t=e.detail;if(!t||!t.glue42)return;const n=t.glue42.event,i=this.events[n];i&&i.handle(t.glue42.message)})}announceStarted(){this.send("start",this.getAnnounceInfo())}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse",{glue:this.glue}):this.send("requestGlueResponse",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}send(e,t){const n={glue42:{event:e,message:t}},i=new CustomEvent(this.glue42EventName,{detail:n});window.dispatchEvent(i)}getAnnounceInfo(){const e=this.glue.performance,t=e.initTimes?e.initTimes:[];return{api:{version:this.glue.version,config:this.glue.userConfig,initTimes:t.map(e=>({name:e.name,duration:e.duration}))}}}}class ro{static delay(e){return new Promise(t=>setTimeout(t,e))}static async delayForever(){for(;;)await this.delay(2147483647)}get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}}const oo={register:"register",unregister:"unregister",raise:"raiseInterception",filterHandlers:"filterHandlersInterception"};class so{constructor(){this.InterceptorMethodName="T42.GD.Interception.Execute",this.InterceptorHandlerMethodName="T42.GD.Interception.Handler",this.interceptions=[]}init(e){this.interop=e}async register(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Please provide a valid object.");if("function"!=typeof e.handler)throw new Error("Please provide a valid handler function.");const t=e.interceptions;this.validateInterceptions(t),this.interceptions.push(e);const n=oo.register;try{await this.interop.invoke(this.InterceptorMethodName,{command:n,interceptions:t},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}),await this.registerMethodIfNotRegistered()}catch(t){this.interceptions=this.interceptions.filter(t=>t!==e);const n=t.message||"Unknown error";throw new Error(`Failed to register interception: ${n}`)}}async unregister(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Please provide a valid object.");const t=e.interceptions;this.validateInterceptions(t);const n=oo.unregister;try{await this.interop.invoke(this.InterceptorMethodName,{command:n,interceptions:t},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On}),this.interceptions=this.interceptions.filter(e=>!t.some(t=>e.interceptions.some(e=>e.domain===t.domain&&e.operation===t.operation)))}catch(e){const t=e.message||"Unknown error";throw new Error(`Failed to unregister interception: ${t}`)}}async handleInterception(e,t,n,i){if(0===this.interop.methods(this.InterceptorMethodName).length)return{};const r=oo[t];if(!r)throw new Error(`No command mapped for intercepting operation: ${t}`);return(await this.interop.invoke(this.InterceptorMethodName,{command:r,interceptions:[{operationArgs:n,domain:e,operation:t,phase:i}]},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On})).returned}static createProxyObject(e,t,n){const i=so.OperationsPerDomain[t]||[];return new Proxy(e,{get(e,r,o){const s=Reflect.get(e,r,o);try{if("function"!=typeof s)return s;const o=i.includes(r),a=$n.isPromise(s)||$n.isAsyncFunction(s);return o&&a?so.interceptMethod(s,r,e,t,n):s}catch(e){return s}}})}static interceptMethod(e,t,n,i,r){return async function(...o){const s=await r.handleInterception(i,t,o,"before");if(!$n.isNullOrUndefined(s.operationResult))return s.operationResult;$n.isNullOrUndefined(s.operationArgs)||(o=s.operationArgs);const a=await e.apply(n,o),c=await r.handleInterception(i,t,[a],"after");return $n.isNullOrUndefined(c.operationResult)?a:c.operationResult}}toAPI(){return{register:this.register.bind(this),unregister:this.unregister.bind(this)}}async registerMethodIfNotRegistered(){var e;(null===(e=this.whenRegisteredPromise)||void 0===e?void 0:e.ended)||(this.whenRegisteredPromise=new ro,this.registerMethod())}async registerMethod(){await this.interop.register(this.InterceptorHandlerMethodName,async e=>{const t=this.interceptions.find(t=>t.interceptions.some(t=>t.domain===e.interception.domain&&t.operation===e.interception.operation));if(!t)return;return await t.handler(e.interception)}),this.whenRegisteredPromise.resolve()}validateInterceptions(e){if(!Array.isArray(e))throw new Error("Please provide a valid array of interceptions.");if(0===e.length)throw new Error("Please provide at least one interception.");for(const t of e){if(null==t||"object"!=typeof t||Array.isArray(t))throw new Error("Please provide a valid interception object.");if("string"!=typeof t.domain||!t.domain)throw new Error("Please provide a valid domain string.");if("string"!=typeof t.operation||!t.operation)throw new Error("Please provide a valid operation string.");this.validateTypeString(t)}}validateTypeString(e){if(!Rt(e.phase)){const t=["all","before","after"].includes(e.phase);if("string"!=typeof e.phase||!t)throw new Error("Please provide a valid phase string.")}}}so.OperationsPerDomain={intents:["raise","filterHandlers"]};class ao{constructor(e){this.logger=e,this.myInstance=null,this.logger.debug("Initializing MyImpl")}initialize(e){this.myInstance=e}toApi(){const e={};return Object.defineProperty(e,"instance",{get:()=>this.myInstance,enumerable:!0,configurable:!1}),Object.defineProperty(e,"appName",{get:()=>{var e;return null===(e=this.myInstance)||void 0===e?void 0:e.appName},enumerable:!0,configurable:!1}),e}}const co="apps",ho=`${co}.command`,uo=`${co}.event`;function lo(e,t,n,i){return e.invoke(ho,{command:t,args:n},"best",{waitTimeoutMs:On,methodResponseTimeoutMs:On,...i||{}})}async function po(e,t,n,i,r){if("function"!=typeof i)throw new Error("Callback must be a function");if(!n)throw new Error("Event name must be provided");t.debug(`Subscribing to ${n} events`);const o=await function(e,t){return e.subscribe(uo,{arguments:{event:t},target:"best",waitTimeoutMs:On,methodResponseTimeout:On})}(e,n);return o.onData(e=>{const{data:o}=e;"object"==typeof o&&null!==o?Array.isArray(o.data)?o.data.forEach(e=>{i(r?r(e):e)}):i(r?r(o.data):o.data):t.warn(`Received empty data for event ${n}`)}),()=>{t.debug(`Unsubscribed from ${n} events`),o.close()}}class go{constructor(e,t){this.interop=e,this.logger=t,this.logger.debug("Initializing InMemoryStoreImpl")}async import(e,t="replace"){this.logger.debug(`Importing ${e.length} app definitions with mode: ${t}`);try{const n=await lo(this.interop,"in-memory-import",{apps:e,mode:t});if(!n.returned||0===Object.keys(n.returned).length)return{imported:[],errors:[]};const{imported:i,errors:r}=n.returned;return this.logger.debug(`Import completed: ${i.length} imported, ${r.length} errors`),{imported:i||[],errors:r||[]}}catch(e){const t=`Failed to import app definitions: ${e.message}`;throw this.logger.error(t,e),new Error(t)}}async has(e){if(!e)return!1;const t=await lo(this.interop,"in-memory-has",{name:e});return void 0!==t.returned.result&&t.returned.result}async remove(e){if(!(null==e?void 0:e.name))throw new Error("App name is required for removal");this.logger.debug(`Removing app definition: ${e.name}`);try{await lo(this.interop,"in-memory-remove",e),this.logger.debug(`Removed app definition: ${e.name}`)}catch(t){const n=`Failed to remove app definition: ${e.name}`;throw this.logger.error(n,t),new Error(n)}}async clear(e){this.logger.debug("Clearing all in-memory app definitions");try{await lo(this.interop,"in-memory-clear",e)}catch(e){const t=`Failed to clear in-memory app definitions: ${e.message}`;throw this.logger.error(t,e),new Error(t)}}}class fo{constructor(e,t){this.interop=e,this.logger=t,this.logger.debug("Initializing AppRegistryImpl"),this._inMemory=new go(this.interop,this.logger),this.subscribeToEvent=(e,t)=>po(this.interop,this.logger,e,t)}get inMemory(){return this._inMemory}async get(e){if(!(null==e?void 0:e.name))throw new Error("App name is required");this.logger.debug(`Getting app: ${e.name}`);try{const t=await lo(this.interop,"get-app",e);return t.returned&&0!==Object.keys(t.returned).length?t.returned:null}catch(t){return this.logger.error(`Failed to get app ${e.name}`,t),null}}async getMany(e){var t;this.logger.debug("Getting multiple apps");try{const n=await lo(this.interop,"get-apps",{filter:e});return n.returned&&0!==Object.keys(n.returned).length&&(null===(t=n.returned)||void 0===t?void 0:t.apps)||[]}catch(e){return this.logger.error("Failed to get multiple apps",e),[]}}async has(e){if(!e)return!1;this.logger.debug(`Checking if app exists: ${e}`);try{const t=await lo(this.interop,"has-app",{name:e});return void 0!==t.returned.result&&t.returned.result}catch(t){return this.logger.error(`Failed to check app existence: ${e}`,t),!1}}async onAdded(e){return this.subscribeToEvent("applications-added",e)}async onRemoved(e){return this.subscribeToEvent("applications-removed",e)}async onUpdated(e){return this.subscribeToEvent("applications-updated",e)}toApi(){return{inMemory:this.inMemory,get:this.get.bind(this),getMany:this.getMany.bind(this),has:this.has.bind(this),onAdded:this.onAdded.bind(this),onRemoved:this.onRemoved.bind(this),onUpdated:this.onUpdated.bind(this)}}}const mo={APP_NOT_FOUND:{description:"The specified application could not be found in the application registry",possibleCauses:["Application name was misspelled or incorrectly formatted","Application was not properly registered or imported","Application was removed from the registry","Case-sensitive name mismatch"],solutions:["Verify the application name spelling and case","Check if the application exists using apps.registry.list() or apps.registry.has()","Import the application using apps.registry.import() if it's missing","Ensure the application is properly defined in the configuration"]},INVALID_INSTANCE_ID:{description:"The provided instance ID is invalid or malformed",possibleCauses:["Instance ID is null or undefined","Instance ID is not a string (number, object, boolean, etc.)","Instance ID is an empty string or contains only whitespace","Instance ID format is incorrect or contains invalid characters"],solutions:["Ensure the instance ID is provided and not null/undefined","Make sure the instance ID is a string type","Verify the instance ID is not empty and contains actual content","Use a valid instance ID from apps.instances.list() or instance start result","Check that the instance ID hasn't been corrupted or modified"]},INSTANCE_NOT_FOUND:{description:"No running instance found with the specified ID",possibleCauses:["Instance was already stopped or crashed","Instance ID is from a different session","Instance was never successfully started","Instance belongs to a different application"],solutions:["Verify the instance is running using apps.instances.list()","Check if the instance was stopped using instance lifecycle events","Start a new instance if the previous one is no longer available","Use the correct instance ID for the target application"]},INVALID_APP_CONFIG:{description:"The application configuration is invalid or contains errors",possibleCauses:["Required configuration properties are missing","Configuration values have invalid types or formats","URL or path references are malformed","Security settings are conflicting or invalid"],solutions:["Validate all required configuration properties are present","Check configuration values match expected types and formats","Verify URLs and file paths are accessible and properly formatted","Review security settings for conflicts or invalid permissions"]}};class yo extends Error{constructor(e,t){const n=mo[e],i=n?n.description:`Apps error: ${e}`;super(t||i),this.code=e,this.name="AppsError"}toString(){return`[${this.name}:${this.code}] ${this.message}`}getHint(){const e=mo[this.code];return e||{description:`Unknown Apps API error: ${this.code}`,possibleCauses:["Unrecognized error code"],solutions:["Check that the error code is spelled correctly","Verify the error code is supported by the Apps API","Contact support if this error persists"]}}static create(e,t){return new yo(e,t)}static appNotFound(e){return new yo("APP_NOT_FOUND",`Application '${e}' not found`)}static instanceNotFound(e,t){return new yo("INSTANCE_NOT_FOUND",`Instance '${e}' not found${t?` for app '${t}'`:""}`)}static invalidInstanceId(e){let t;return t=null==e?"Instance ID cannot be "+(null===e?"null":"undefined"):"string"!=typeof e?`Instance ID must be a string, received ${typeof e}: ${String(e)}`:""===e.trim()?"Instance ID cannot be empty or whitespace-only":`Invalid instance ID: ${String(e)}`,new yo("INVALID_INSTANCE_ID",t)}static invalidAppConfig(e,t){return new yo("INVALID_APP_CONFIG",`Invalid configuration for app '${e}': ${t}`)}}class wo{constructor(e,t){this.interop=e,this.logger=t,this.logger.debug("Initializing InstanceManagerImpl"),this.subscribeToEvent=(e,t,n)=>po(this.interop,this.logger,e,t,n)}async start(e){if(!(null==e?void 0:e.name))throw new Error("App name is required to start an instance");this.logger.debug(`Starting app instance: ${e.name}`);try{const t=await lo(this.interop,"start-app",e);return this.logger.debug(`Start app instance result: ${JSON.stringify(t)}`),this.buildInstanceObject(t.returned)}catch(t){const n=$n.typedError(t),i="message"in n?n.message:String(n);if(i.includes("can not find application")||i.includes("application not found"))throw yo.appNotFound(e.name);const r=`Failed to start app instance: ${e.name}`;throw this.logger.error(r,n),new Error(`${r}: ${i}`)}}async stop(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw yo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Stopping app instance: ${e.id}`);try{await lo(this.interop,"stop-app",e),this.logger.debug(`Successfully stopped instance: ${e.id}`)}catch(t){const n=`Failed to stop app instance: ${e.id}`,i=$n.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async waitForReady(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw yo.invalidInstanceId(null==e?void 0:e.id);const t=e.id;this.logger.debug(`Waiting for instance ${t} to be ready`);try{await lo(this.interop,"wait-for-ready",{...e},{waitTimeoutMs:jn,methodResponseTimeoutMs:jn}),this.logger.debug(`Instance ${t} is now ready`)}catch(e){const n=`Failed to wait for instance ${t} ready state`,i=$n.typedError(e);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async get(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw yo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Getting instance: ${e.id}`);try{const t=await lo(this.interop,"get-instance",{...e});return t.returned&&0!==Object.keys(t.returned).length?this.buildInstanceObject(t.returned):null}catch(t){const n=`Failed to get instance ${e.id}`,i=$n.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async getMany(e){this.logger.debug("Getting multiple instances");try{const t=await lo(this.interop,"get-instances",{filter:e});return t.returned&&0!==Object.keys(t.returned).length&&t.returned.instances?t.returned.instances.map(e=>this.buildInstanceObject(e)):[]}catch(e){const t="Failed to get instances",n=$n.typedError(e);throw this.logger.error(t,n),new Error(`${t}: ${"message"in n?n.message:String(n)}`)}}async getState(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw yo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Getting state for instance: ${e.id}`);try{return(await lo(this.interop,"get-instance-state",{...e})).returned.state}catch(t){const n=`Failed to get state for instance ${e.id}`,i=$n.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async getContext(e){var t;if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw yo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Getting context for instance: ${e.id}`);try{return(null===(t=(await lo(this.interop,"get-instance-context",{...e})).returned)||void 0===t?void 0:t.context)||{}}catch(t){const n=`Failed to get context for instance ${e.id}`,i=$n.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async restart(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw yo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Restarting instance: ${e.id}`);try{const t=await lo(this.interop,"restart-instance",{...e});return this.logger.debug(`Restart app instance result: ${JSON.stringify(t)}`),this.buildInstanceObject(t.returned)}catch(t){const n=`Failed to restart app instance: ${e.id}`,i=$n.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async onStarted(e){return this.subscribeToEvent("instance-started",e,e=>({...e,instance:this.buildInstanceObject(e.instance)}))}async onStopped(e){return this.subscribeToEvent("instance-stopped",e)}async onStateChanged(e){return this.subscribeToEvent("instance-state-changed",e,e=>({...e,instance:this.buildInstanceObject(e.instance)}))}toApi(){return{start:this.start.bind(this),stop:this.stop.bind(this),waitForReady:this.waitForReady.bind(this),get:this.get.bind(this),getMany:this.getMany.bind(this),getState:this.getState.bind(this),getContext:this.getContext.bind(this),restart:this.restart.bind(this),onStarted:this.onStarted.bind(this),onStopped:this.onStopped.bind(this),onStateChanged:this.onStateChanged.bind(this)}}buildInstanceObject(e){const t={...e};return Object.defineProperty(t,"interopInstance",{get:()=>this.interop.servers().find(t=>t.instance===e.id),enumerable:!0,configurable:!1}),t}}class vo{constructor(){this._appManager=null,this._apps=null}setAppManager(e){this._appManager=e}get appManager(){return this._appManager}setApps(e){this._apps=e}get apps(){return this._apps}get myInstance(){var e,t,n,i,r,o,s,a,c,d;return{id:null!==(n=null===(t=null===(e=this._appManager)||void 0===e?void 0:e.myInstance)||void 0===t?void 0:t.id)&&void 0!==n?n:null===(o=null===(r=null===(i=this._apps)||void 0===i?void 0:i.my)||void 0===r?void 0:r.instance)||void 0===o?void 0:o.id,activityId:null===(a=null===(s=this._appManager)||void 0===s?void 0:s.myInstance)||void 0===a?void 0:a.activityId,inActivity:null===(d=null===(c=this._appManager)||void 0===c?void 0:c.myInstance)||void 0===d?void 0:d.inActivity}}isInitialized(){return!(!this._apps&&!this._appManager)}async getApp(e){var t,n,i;return this.ensureInitialized(),this._appManager?await(null===(n=null===(t=this._appManager)||void 0===t?void 0:t.application(e))||void 0===n?void 0:n.getConfiguration()):this._apps?null===(i=await this._apps.registry.get({name:e,includeDefinition:!0}))||void 0===i?void 0:i.definition:void 0}async start(e){var t;if(this.ensureInitialized(),this._appManager){const n=await(null===(t=this._appManager)||void 0===t?void 0:t.application(null==e?void 0:e.name).start(e.context,e.definitionOverride));return{id:n.id,appName:n.application.name,startedAt:new Date,startedBy:await n.startedBy()}}return this._apps.instances.start(e)}onAdded(e,t){if(this.ensureInitialized(),this._appManager){if(!0===t){const t=this._appManager.onAppAdded(async t=>{var n;const i=await(null===(n=this._appManager)||void 0===n?void 0:n.application(t.name).getConfiguration()),r=i||void 0;return this.callWithErrorGuard(e,{app:{name:t.name,type:t.type}},r)});return Promise.resolve(t)}{const t=this._appManager.onAppAdded(async t=>this.callWithErrorGuard(e,{app:{name:t.name,type:t.type}}));return Promise.resolve(t)}}if(this._apps)return!0===t?this._apps.registry.onAdded(async t=>{var n;const i=await(null===(n=this._apps)||void 0===n?void 0:n.registry.get({name:t.app.name,includeDefinition:!0})),r=i?i.definition:void 0;return this.callWithErrorGuard(e,t,r)}):this._apps.registry.onAdded(e)}onRemoved(e){if(this.ensureInitialized(),this._appManager){const t=this._appManager.onAppRemoved(t=>this.callWithErrorGuard(e,{appName:t.name}));return Promise.resolve(t)}if(this._apps)return this._apps.registry.onRemoved(e)}onInstanceStopped(e){if(this.ensureInitialized(),this._appManager){const t=this._appManager.onInstanceStopped(t=>{this.callWithErrorGuard(e,{id:t.id,appName:t.application.name,startedAt:new Date,startedBy:void 0})});return Promise.resolve(t)}if(this._apps)return this._apps.instances.onStopped(t=>{this.callWithErrorGuard(e,{id:t.instance.id,appName:t.instance.appName,startedAt:t.instance.startedAt,startedBy:t.instance.startedBy})})}async getInstance(e){var t;if(this.ensureInitialized(),this._apps)return this._apps.instances.get({id:e});{const n=null===(t=this._appManager)||void 0===t?void 0:t.instances().find(t=>t.id===e);if(n)return{id:n.id,appName:n.application.name,startedAt:new Date,startedBy:await n.startedBy()}}}ensureInitialized(){if(!this._apps&&!this._appManager)throw new Error("Both AppManager API and Apps API are not initialized")}callWithErrorGuard(e,...t){try{e(...t)}catch{}}}const bo=new class{constructor(){this.initialized=!1,this.details=[],this.reject=()=>{},this.resolve=()=>{}}init(e){this.initialized=!0,this.addCall(e),this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}addCall(e){this.details.push({date:new Date,config:e})}done(e){this.resolve(e)}error(e){this.reject(e)}},_o=async e=>{let t=!1;bo.initialized||(t=!0,bo.init(e));const n="undefined"!=typeof window&&window.glue42gd;if(n&&!t)return bo.addCall(e),bo.promise;const i=await Io(e,n);return bo.resolve(i),i},Io=async(e,t)=>{const n=$n.getGDMajorVersion(),i=Vi(e=e||{});let r,o,s,a,c,d,h;e.gateway=e.gateway||{};const u=new so,l=new Ji,p=new vo,g=new io(i);function f(e,t,n){const i=t.subLogger(e);if(n&&n.logger){const e=n.logger;e.console&&i.consoleLevel(e.console),e.publish&&i.publishLevel(e.publish)}return i}const m={libs:[{name:"windows",create:function(e){if(i.windows){const t=f("windows",e.logger,i.windows);return s=si(e.agm,t,()=>p,()=>a,()=>c,n),w(s),s}}},{name:"activities",create:function(e){var a;if(i.activities&&_n.checkIsUsingGW3Implementation&&_n.checkIsUsingGW3Implementation(e.connection)){const c=f("activity",e.logger,i.activities);return o=new _n({connection:e.connection,contexts:e.contexts,agm:e.agm,logger:c,logLevel:"info",disableAutoAnnounce:!1,disposeRequestHandling:"exit",announcementInfo:null,windows:s,appManagerGetter:()=>r,mode:i.activities.mode,typesToTrack:i.activities.typesToTrack,activityId:null===(a=null==t?void 0:t.activityInfo)||void 0===a?void 0:a.activityId,gdMajorVersion:n}).api,w(o),o}}},{name:"appManager",create:function(e){if(!i.appManager)return;const t=f("appManager",e.logger,i.appManager);return r=Bn({agm:e.agm,windows:s,logger:t,activities:o,mode:i.appManager.mode,gdMajorVersion:n}),w(r),p.setAppManager(r),r}},{name:"apps",create:function(e){if(!i.apps)return;const t=f("apps",e.logger,i.apps);return h=function(e,t){if(!e)throw new Error("Interop API is required for Apps API initialization");if(!t)throw new Error("Logger is required for Apps API initialization");if(0===e.methods(ho).length)return void t.debug("Apps API method not registered in interop; skipping Apps API initialization");t.debug("Initializing new Apps API factory");let n=()=>{t.debug("Apps API factory ready")},i=e=>{t.error("Apps API factory initialization failed",e)};const r=new Promise((e,t)=>{n=e,i=t}),o=new ao(t),s=new fo(e,t),a=new wo(e,t);return lo(e,"announce",{}).then(e=>{o.initialize(e.returned),n()}).catch(e=>{t.error("Failed to announce current application instance",e),i(e)}),t.debug("New Apps API factory initialized successfully"),{ready:()=>r,my:o.toApi(),registry:s.toApi(),instances:a.toApi()}}(e.agm,t),h?(w(h),p.setApps(h),h):void 0}},{name:"platform",create:function(e){return l.init(e.interop,e.logger),w(l),l.toAPI()}},{name:"layouts",create:function(e){var t;if(!i.layouts)return;const r=f("layouts",e.logger,i.layouts),s=i.layouts,a=Ii({agm:e.agm,myInstance:()=>p.myInstance,activityGetter:()=>o,logger:r,mode:s.mode,autoSaveWindowContext:null!==(t=s.autoSaveWindowContext)&&void 0!==t&&t,gdMajorVersion:n});return w(a),a}},{name:"channels",create:function(e){if(!i.channels)return;const t=f("channels",e.logger,i.channels);if(e.contexts)return c=function(e,t,n,i,r){const o=Oi(e,n).then(async({mode:e,initialChannel:i})=>{const o="single"===e?new Li(t):new Fi(t);return"multi"===e&&r.info("multi-channel mode enabled"),await s.init(o,e,i),await Ei(n,s,r),!0}),s=new Ui(n,i,r);return{subscribe:s.subscribe.bind(s),subscribeFor:s.subscribeFor.bind(s),publish:s.publish.bind(s),setPath:s.setPath.bind(s),setPaths:s.setPaths.bind(s),all:s.all.bind(s),list:s.list.bind(s),get:s.get.bind(s),join:s.join.bind(s),leave:s.leave.bind(s),restrict:s.restrict.bind(s),getRestrictions:s.getRestrictions.bind(s),restrictAll:s.restrictAll.bind(s),current:s.current.bind(s),clearChannelData:s.clearChannelData.bind(s),my:s.my.bind(s),changed:s.changed.bind(s),onChanged:s.onChanged.bind(s),add:s.add.bind(s),remove:s.remove.bind(s),getWindowsOnChannel:s.getWindowsOnChannel.bind(s),getWindowsWithChannels:s.getWindowsWithChannels.bind(s),getMy:s.getMy.bind(s),ready:async()=>{await Promise.all([t.ready(),o])},get mode(){return s.mode},getMyChannels:s.getMyChannels.bind(s),myChannels:s.myChannels.bind(s),onChannelsChanged:s.onChannelsChanged.bind(s)}}({operationMode:i.channels.operationMode},e.contexts,e.agm,()=>s,t),w(c),c;t.error("Channels library requires Contexts library to be initialized.")}},{name:"hotkeys",create:function(e){const t=function(e){const t=new Bi(e);return{register:t.register.bind(t),unregister:t.unregister.bind(t),unregisterAll:t.unregisterAll.bind(t),isRegistered:t.isRegistered.bind(t),ready:()=>Promise.resolve()}}(e.agm);return w(t),t}},{name:"displays",create:function(e){if(i.displays){const t=f("displays",e.logger,i.displays);return a=new Ci(e.agm,t),w(a),a}}},{name:"prefs",create:function(n){var i,r;const o=null!==(r=null!==(i=e.application)&&void 0!==i?i:null==t?void 0:t.applicationName)&&void 0!==r?r:n.interop.instance.application;return d=new to(o,n.interop),w(d),d}},{name:"intents",create:function(t){const n="intents",i=new eo(t.agm,s,t.logger.subLogger(n),e,d,p).toAPI(),r=so.createProxyObject(i,n,u);return w(r),r}},{name:"notifications",create:function(e){const t=new Qi(e.interop,e.logger).toAPI();return w(t),t}},{name:"themes",create:function(e){if(!e.contexts)return;const t=function(e,t){const n=new Zi(e,t);return{list:n.list.bind(n),getCurrent:n.getCurrent.bind(n),select:n.select.bind(n),onChanged:n.onChanged.bind(n),ready:()=>Promise.resolve()}}(e.contexts,e.interop);return w(t),t}},{name:"cookies",create:function(e){const t=function(e,t){const n=new no(t,e);return{get:n.get.bind(n),remove:n.remove.bind(n),set:n.set.bind(n),ready:()=>Promise.resolve()}}(e.interop,"T42.GD.Execute");return w(t),t}},{name:"interception",create:function(e){return u.init(e.interop),w(u),u.toAPI()}}],version:qi,enrichGlue:e=>{e.config.activities=i.activities,e.config.windows=i.windows,e.config.appManager=i.appManager,e.config.apps=i.apps,e.config.layouts=i.layouts,e.config.channels=i.channels,e.config.displays=i.displays}},y=[];function w(e){y.push(e)}"undefined"!=typeof window&&(window.glueFactoryLog||(window.glueFactoryLog=[]),window.glueFactoryLog.push(y));const v=await Tt(e,m);return Array.isArray(null==e?void 0:e.libraries)&&e.libraries.length&&await Promise.all(e.libraries.map(t=>t(v,e))),g.start(v),v};var Co,Ao;_o.coreVersion=Tt.version,_o.version=qi,_o.calls=bo;let To=_o,So=!0;if("undefined"!=typeof window){const e=window,t=null!==(Co=e.iodesktop)&&void 0!==Co?Co:e.glue42gd;t&&t.autoInjected&&(To=null!==(Ao=e.IODesktop)&&void 0!==Ao?Ao:e.Glue,So=!1),So&&(e.Glue=To,e.IODesktop=To),delete e.IOBrowser,delete e.GlueCore}return To.default=To,To});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).desktop=e.desktop||{},e.desktop.browser=e.desktop.browser||{},e.desktop.browser.min=t())}(this,function(){"use strict";var e=1,t=2,n=3,i=4;function r(r){return r.type===n?"timestamp":r.type===t?"number":r.type===e?"string":r.type===i?"object":"unknown"}function o(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function s(e){const t={},n=r(e);if("object"===n){const n=Object.keys(e.value).reduce((t,n)=>{const i=o(e.value[n]);if("object"===i){const i=a(e.value[n]);t[n]={type:"object",description:"",context:{},composite:i}}else t[n]={type:i,description:"",context:{}};return t},{});t.composite=n}return t.name=c(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function a(e){return Object.keys(e).reduce((t,n)=>{const i=o(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:a(e[n])}:{type:i,description:"",context:{}},t},{})}function c(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function d(e){return"timestamp"===r(e)?Date.now():h(e.value)}function h(e){return"object"!=typeof e?e:Object.keys(e).reduce((t,n)=>{const i=e[n];return"object"==typeof i&&i.constructor!==Date?t[n]=h(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t},{})}function l(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?l(t):t),[])}function u(e){const t=l(e.root.getAggregateState()),n=t.sort((e,t)=>e.state?t.state?t.state-e.state:-1:1)[0];const i=function(e){let t="";return e.forEach((e,n,i)=>{const r=e.path.join(".");n===i.length-1?t+=r+"."+e.name+": "+e.description:t+=r+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var p=(e,t,n)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===n||"object"!=typeof n)throw new Error("Missing transport")};class g{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,n,i,r){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=r,p(e,t,n),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,n.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class f extends g{constructor(e,n,i,r){super(e,n,i,r,t)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class m extends g{constructor(e,t,n,r){super(e,t,n,r,i)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach(t=>{void 0!==e[t]&&(this.value[t]=e[t])})}}class y extends g{constructor(t,n,i,r){super(t,n,i,r,e)}}class w extends g{constructor(e,t,i,r){super(e,t,i,r,n)}now(){this.update(new Date)}}function v(r,o,s,a,c){if(!o)throw new Error("Repository is required");if(!s)throw new Error("Transport is required");const d=s,h=r,l=c||"",u=o,p=a,g=function e(t){if(!t||!t.parent)return[];const n=e(t.parent);return n.push(t.name),n}(a);let b={};const _=(C="/",((I=g)&&I.length>0?I.join(C):"")+r);var I,C;const A=o.root,T=[],S=[];function k(e,t,n,i){let r={name:""};r="string"==typeof e?{name:e}:e;const o=S.filter(e=>e.name===r.name);if(o.length>0){const e=o[0];if(e.type!==t)throw new Error(`A metric named ${r.name} is already defined with different type.`);return void 0!==n&&e.update(n).catch(()=>{}),e}const s=i(r);return S.push(s),s}const x={get name(){return h},get description(){return l},get repo(){return u},get parent(){return p},path:g,id:_,root:A,get subSystems(){return T},get metrics(){return S},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=T.filter(t=>t.name===e);if(n.length>0)return n[0];const i=v(e,u,d,x,t);return T.push(i),i},getState:()=>b,setState:function(e,t){b={state:e,description:t},d.updateSystem(x,b)},stringMetric:function(t,n){return k(t,e,n,e=>new y(e,x,d,n))},timestampMetric:function(e,t){return k(e,n,t,e=>new w(e,x,d,t))},objectMetric:function(e,t){return k(e,i,t,e=>new m(e,x,d,t))},numberMetric:function(e,n){return k(e,t,n,e=>new f(e,x,d,n))},getAggregateState:function(){const e=[];return Object.keys(b).length>0&&e.push({name:h,path:g,state:b.state,description:b.description}),T.forEach(t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)}),e}};return d.createSystem(x),x}class b{root;constructor(e,t){t.init(this),this.root=v("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),n=e=>{if(!e.target)return;const n=e.target,i=n?n.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:i,id:n.id,type:"<"+n.tagName.toLowerCase()+">",href:n.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",n):document.attachEvent("onclick",n)}e.stringMetric("StartTime",(new Date).toString());const n=e.stringMetric("StartURL",""),i=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;n.update(e)}void 0!==window.glue42gd&&i.update(window.glue42gd.appName)}}}class _{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class I{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,n){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=n??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout(()=>{this.collect(),setInterval(()=>{this.collect()},this.publishInterval)},this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map(e=>e.toJSON());this.system.stringMetric("entries",JSON.stringify(t))}}var C=e=>{let t;t=e.connection&&"object"==typeof e.connection?function(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let n,i;const r=e=>{o(e.root)},o=e=>{a(e),e.metrics.forEach(e=>{h(e)}),e.subSystems.forEach(e=>{o(e)})},a=async e=>{if(void 0===e.parent)return;await n;const r={type:"define",metrics:[{name:c(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(n)}`)})},h=async e=>{const r=p(e);await n;const o={type:"define",metrics:[s(r)]};i.sendFireAndForget(o).catch(n=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(n)}`)}),void 0!==r.value&&l(r)},l=e=>{if(g()){const n=d(e),r={type:"publish",values:[{name:c(e.path.join("/")+"/"+e.name),value:n,timestamp:Date.now()}]};return i.sendFireAndForget(r).catch(n=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(n)}`)})}return Promise.resolve()},p=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},g=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:o=>{let s;n=new Promise(e=>{s=e}),i=e.domain("metrics"),i.onJoined(e=>{!e&&s&&(s(),s=void 0);const n={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.sendFireAndForget(n).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&r(o)}),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:a,updateSystem:async(r,o)=>{await n;const s={type:"publish",values:[{name:c(r.path.join("/")+"/"+r.name+"/State"),value:{Description:o.description,Value:o.state},timestamp:Date.now()}]};i.sendFireAndForget(s).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${r.name}: ${JSON.stringify(e)}`)});const a=u(r),d={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};i.sendFireAndForget(d).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${r.name}: ${JSON.stringify(e)}`)})},createMetric:h,updateMetric:async e=>{const t=p(e);await n,l(t)}}}(e.connection,e):new _;let n=new b(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));const i=function(e){const t=e.subSystem("reporting"),n={name:"features"};let i;const r=(e,r,o)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===r||""===r)throw new Error("action is mandatory");if(void 0===o||""===o)throw new Error("payload is mandatory");i?i.update({name:e,action:r,payload:o}):i=t.objectMetric(n,{name:e,action:r,payload:o})};return e.featureMetric=r,e}(n);return function(e,t){if("undefined"==typeof window)return;const n=window?.glue42gd?.metrics?.pagePerformanceMetrics;n&&(t=n);t?.enabled&&new I(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var A="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function T(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function S(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var r=n instanceof Error?n:new Error(n);if(t)t(r);else{var o='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,r){var o=n[e];return o||(o=[],n[e]=o),o.push(t),r&&setTimeout(function(){r.forEach(function(r){var o;if(null===(o=n[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}catch(t){i(t,e)}})},0),function(){var i=n[e];i&&(0===(i=i.reduce(function(e,n,i){return n===t&&e.length===i||e.push(n),e},[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var o=n[e];if(!o||0===o.length)return[];var s=[];return o.forEach(function(n){try{var r=n.apply(void 0,t);s.push(r)}catch(t){s.push(void 0),i(t,e)}}),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}S.default=S;var k=T(S);class x{gw;registry=k();client;constructor(e,t){this.gw=e.facade,this.gw.connect((e,t)=>{this.messageHandler(t)}).then(e=>{this.client=e})}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class E{logger;worker;registry=k();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}let P=class e{static isNode(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode}static _isNode},M=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};const R={};function N(e){const t=R[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const r=i();let o,s;function a(e,t){const r=t??i();let o=0;n.length>0&&(o=r-n[n.length-1].time),n.push({name:e,time:r,diff:o})}a("start",r);const c={get startTime(){return r},get endTime(){return o},get period(){return s},stop:function(){return o=i(),a("end",o),s=o-r,s},mark:a,marks:n};return R[e]=c,c}const O=P.isNode()?null:window.WebSocket;class j{ws;logger;settings;startupTimer=N("connection");_running=!0;_registry=k();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise((t,n)=>{this.waitForSocketConnection(()=>{try{this.ws?.send(e),t()}catch(e){n(e)}},n)})}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise((e,t)=>{this.waitForSocketConnection(e,t)})}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new M;return this.waitForSocketConnection(()=>{e.resolve()}),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout(()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)},e)}}initiateSocket(){const e=new M;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new O(this.settings.ws??"");let t=!1;return this.ws.onerror=n=>{let i;try{i=JSON.stringify(n)}catch(e){const t=new WeakSet,r=(e,n)=>{if("object"==typeof n&&null!==n){if(t.has(n))return;t.add(n)}return n instanceof Error?{message:n.message,name:n.name,stack:n.stack}:n};i=JSON.stringify(n,r)}this.logger.info(`ws error - reason: ${i}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error")),this.notifyStatusChanged(!1,i)},this.ws.onclose=n=>{this.logger.info(`ws closed - code: ${n?.code} reason: ${n?.reason}`),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach(t=>{e?t.failed&&t.failed(e):t.callback()}),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class ${specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const n of this.specs[t].types){let t=this.subsRefCount[n];if(t||(t=0),t+=1,this.subsRefCount[n]=t,t>1)continue;const i=e.on(n,e=>this.processMessage(n,e));this.subs[n]=i}}processMessage(e,t){if(!this.isDone&&t)for(const n of this.specsNames)if(-1!==this.specs[n].types.indexOf(e)){const e=this.messages[n]||[];this.messages[n]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let W=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const D=(e,t,n)=>new Promise((i,r)=>{const o=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),i(e)}).catch(e=>{clearTimeout(o),r(e)})});class F{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=k();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:()=>{}},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,n){this.settings=e,this.logger=t,this.identity=n,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=n=>{if(this.iAmConnected&&!n.data?.glue42core)return void this.registry.execute("onMessage",n.data);const i=n.data?.glue42core;i&&(i.type===this.messages.gatewayInternalConnect.name&&i.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),i.type===this.messages.gatewayInternalConnect.name&&i.error&&t(i.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))})}initiateRemoteConnection(e){return D((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??W(10);const i=this.getMyWindowId()||W(10),r={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:i,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return r.glue42core.clientType="child",r.glue42core.bridgeInstanceId=this.myClientId,r.glue42core.parentWindowId=this.parentWindowId,window.postMessage(r,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(r,this.defaultTargetString)},this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):(this.logger.debug("setting up window message listener"),window.addEventListener("message",e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const n=this.settings.allowedOrigins||[];if(n.length&&!n.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const i=t.type;this.logger.debug(`received valid glue42core message of type: ${i}`),this.messages[i].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent?.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId!==t.clientId?this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||W(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",e=>{const t=e.data?.glue42ExtInc;if(!t)return;const n=this.settings.allowedOrigins||[];!n.length||n.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)}),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleConnectionRejected(e){if(this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),!this.connectionReject)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const n=e.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>D((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},window.origin)},this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out"))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():D(e=>{window.addEventListener("Glue42EXTReady",()=>{e()})},this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),n=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),i=new Set([...t,...n]);if(!i.size&&!this.extContentAvailable)throw new Error(e);if(!i.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(i)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=D(t=>{this.parentPingResolve=t;const n={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval(()=>{e.forEach(e=>{e.postMessage(n,this.defaultTargetString)})},1e3)},this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch(()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)}),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${W(10)}`,this.selfAssignedWindowId):void 0}}class L{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,n)=>{this.queue.push({action:e,resolve:t,reject:n}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}}function G(e,t,n,i,r){null==e&&(e="global"),i=i??["success"],r=r??["error"];let o,s="global"===e,a=!1,c=!1;const d=k();t.disconnected(function(){n.debug("connection is down"),c=!1,s=!1,a=!0,Object.keys(h).forEach(e=>{const t=h[e];t&&(n.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),d.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){n.debug("connection is now up - trying to reconnect...");try{await l(o)}catch{n.trace("failed to reconnect")}}}),t.on("success",e=>g(e)),t.on("error",e=>p(e)),t.on("result",e=>g(e)),i&&i.forEach(e=>{t.on(e,e=>g(e))}),r&&r.forEach(e=>{t.on(e,e=>p(e))});const h={};function l(t){return o=t,new Promise((i,r)=>{if(s)return void i({});let o;if("global"===e)o=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);o=y({type:"join",destination:e,domain:"global",options:t})}o.then(()=>{!function(){n.debug("did join "+e),s=!0;const t=a;a=!1,d.execute("onJoined",t)}(),i({})}).catch(t=>{n.debug("error joining "+e+" domain: "+JSON.stringify(t)),r(t)})})}function u(e){return s&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const n=t.request_id;if(!n)return;const i=h[n];i&&i.error(t)}function g(t){if(t.domain!==e)return;const n=t.request_id;if(!n)return;const i=h[n];i&&i.success(t)}function f(){return W(10)}let m=[];function y(i,r,o){if(i.type&&-1===["hello","join"].indexOf(i.type)&&!s){console.warn(`trying to send a message (${i.domain} ${i.type}) but not connected, will queue`);const e=new M;if(m.push({msg:i,tag:r,options:o,pw:e}),1===m.length){const e=u(()=>{n.info(`joined - will now send queued messages (${m.length} -> [${m.map(e=>e.msg.type)}])`),m.forEach(e=>{y(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),m=[],e()})}return e.promise}o=o??{},i.request_id=i.request_id??f(),i.domain=i.domain??e,o.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise((e,n)=>{h[a]={success:t=>{delete h[a],t._tag=r,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete h[a],e._tag=r,n(e)}},t.send(i,o).catch(e=>{h[a]?.error({err:e})})})}return{join:l,leave:function(){return"global"===e?Promise.resolve():(n.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then(()=>{s=!1,d.execute("onLeft")}).catch(()=>{s=!1,d.execute("onLeft")}))},onJoined:u,onLeft:function(e){return s||e(),d.add("onLeft",e)},send:y,sendFireAndForget:function(n){return n.request_id=n.request_id?n.request_id:f(),n.domain=n.domain??e,n.peer_id=t.peerId,t.send(n)},on:(i,r)=>{t.on(i,t=>{if(t.domain===e)try{r(t)}catch(e){n.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}})},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class U{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=k();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new L;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;loginRetryInProgress=!1;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new x(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new E(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new F(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new j(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const n=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),i=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(n),this._transportSubscriptions.push(i),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue(async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const n=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await n;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}})}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const n=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(n)}`),this.transport.sendObject(n,t)}{const n=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${n}`),this.transport.send(n,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const n=this.ids++;return this.messageHandlers[e][n]=t,{type:e,id:n}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn(()=>{const t=this.transport.name();e(t)})}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),N("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(n)}`),N("connection").mark("protocol-logged-in"),n}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,n){let i=this.sessions.find(t=>t.domain===e);return i||(i=G(e,this,this.logger.subLogger(`domain=${e}`),t,n),this.sessions.push(i)),i}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then(e=>e.token):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,this.registry.execute("onLoggedIn"))}distributeMessage(e,t){const n=this.messageHandlers[t.toLowerCase()];void 0!==n&&Object.keys(n).forEach(t=>{const i=n[t];if(void 0!==i)try{i(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new $(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&this.attemptLoginWithRetry(),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3)}finally{this.loginRetryInProgress=!1}}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return D(e=>{let t;const n=((e,t)=>{let n=e;return()=>{n--,0===n&&t()}})(2,()=>{t&&t(),e()});t=this.onLibReAnnounced(e=>"interop"===e.name||"contexts"===e.name?n():void 0)},1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new j(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport.close().catch(e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`)),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,(e,t)=>{if("string"!=typeof t)return t;if(t.length<this.dateMinLen)return t;if(!t.startsWith(this.datePrefixFirstChar))return t;if(t.substring(0,this.datePrefixLen)!==this.datePrefix)return t;try{const e=parseInt(t.substring(this.datePrefixLen,t.length),10);return isNaN(e)?t:new Date(e)}catch(e){return t}});return{msg:t,msgType:t.type}}createStringMessage(e){const t=Date.prototype.toJSON;try{const t=this.datePrefix;Date.prototype.toJSON=function(){return t+this.getTime()};return JSON.stringify(e)}finally{Date.prototype.toJSON=t}}processObjectMessage(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}}createObjectMessage(e){return e}async loginCore(e,t){this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0;const n=await this.setupAuthConfig(e,t),i={type:"hello",identity:this.settings.identity,authentication:n};e.sessionId&&(i.request_id=e.sessionId),this.globalDomain||(this.globalDomain=G("global",this,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]));const r={skipPeerId:!0};this.initialLogin&&(r.retryInterval=this.settings.reconnectInterval,r.maxRetries=this.settings.reconnectAttempts);try{const t=await this.tryAuthenticate(this.globalDomain,i,r,e);return this.logger.info("login successful with peerId "+t.peer_id),this.peerId=t.peer_id,this.resolvedIdentity=t.resolved_identity,this.availableDomains=t.available_domains,t.options&&(this.token=t.options.access_token,this.info=t.options.info),this.setLoggedIn(!0),t.resolved_identity}catch(e){throw this.logger.error("error sending hello message - "+(e.message||e.msg||e.reason||e),e),e}finally{e?.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null)}}async tryAuthenticate(e,t,n,i){let r;for(;;){const o=await e.send(t,void 0,n);if("authentication-request"!==o.type){if("welcome"===o.type){r=o;break}throw"error"===o.type?new Error("Authentication failed: "+o.reason):new Error("Unexpected message type during authentication: "+o.type)}{const e=Buffer.from(o.authentication.token,"base64");i.flowCallback&&i.sessionId&&(t.authentication.token=(await i.flowCallback(i.sessionId,e)).data.toString("base64")),t.request_id=i.sessionId}}return r}async setupAuthConfig(e,t){const n={};if(this.gatewayToken=e.gatewayToken,e.gatewayToken){if(t)try{e.gatewayToken=await this.getNewGWToken()}catch(e){this.logger.warn(`failed to get GW token when reconnecting ${e?.message||e}`)}n.method="gateway-token",n.token=e.gatewayToken,this.gatewayToken=e.gatewayToken}else if("sspi"===e.flowName){if(n.provider="win",n.method="access-token",!e.flowCallback||!e.sessionId)throw new Error("Invalid SSPI config");n.token=(await e.flowCallback(e.sessionId,null)).data.toString("base64")}else if(e.token)n.method="access-token",n.token=e.token;else if(e.username)n.method="secret",n.login=e.username,n.secret=e.password;else{if(!e.provider)throw new Error("invalid auth message"+JSON.stringify(e));n.provider=e.provider,n.providerContext=e.providerContext}return n}async logoutCore(){this.logger.debug("core logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer);const e=this.sessions.map(e=>e.leave());await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout(()=>{this.ping()},3e4))}}const H=["trace","debug","info","warn","error","off"];let B=class e{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,n){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}subLogger(t){const n=this.subLoggers.filter(e=>e.name===t)[0];if(void 0!==n)return n;Object.keys(this).forEach(e=>{if(e===t)throw new Error("This sub logger name is not allowed.")});const i=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(i),i}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,n){this.publishMessage(t||"info",e,n)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return H.indexOf(e)>=H.indexOf(t||this.consoleLevel()||"trace")}publishMessage(t,n,i){const r=this.loggerFullName;if("error"===t&&!i){const e=new Error;e.stack&&(n=n+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(t,this.publishLevel())){const o=e.Interop;if(o)try{if(o.methods({name:e.InteropMethodName}).length>0){const s={msg:n,logger:r,level:t};i&&i instanceof Error&&(s.error={message:i.message,stack:i.stack??""}),o.invoke(e.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(t)){let e="";if(this.includeTimeAndLevel){const n=new Date;e=`[${`${n.getHours()}:${n.getMinutes()}:${n.getSeconds()}:${n.getMilliseconds()}`}] [${t}] `}const o=`${e}${r}: ${n}`;switch(t){case"trace":this.logFn.debug(o);break;case"debug":this.logFn.debug?this.logFn.debug(o):this.logFn.log(o);break;case"info":this.logFn.info(o);break;case"warn":this.logFn.warn(o);break;case"error":i?this.logFn.error(o,i):this.logFn.error(o)}}}};const J="create-context",q="created",V="destroyed",z="context-created",K="context-added",Q="subscribe-context",Z="subscribed-context",X="unsubscribe-context",Y="destroy-context",ee="context-destroyed",te="update-context",ne="context-updated",ie="joined",re={get name(){return"context"},get types(){return[J,q,V,z,K,Q,Z,X,Y,ee,te,ne,ie]}};var oe="6.8.1";class se{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new M}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,n,i){this.contextId=e,this.name=t,this.isAnnounced=n,this.activityId=i,this.context={},this.snapshotPromiseWrapper=new M}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var ae={exports:{}};!function(e,t){var n="__lodash_hash_undefined__",i=9007199254740991,r="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",h="[object Number]",l="[object Object]",u="[object Promise]",p="[object RegExp]",g="[object Set]",f="[object String]",m="[object Symbol]",y="[object WeakMap]",w="[object ArrayBuffer]",v="[object DataView]",b="[object Float32Array]",_="[object Float64Array]",I="[object Int8Array]",C="[object Int16Array]",T="[object Int32Array]",S="[object Uint8Array]",k="[object Uint8ClampedArray]",x="[object Uint16Array]",E="[object Uint32Array]",P=/\w*$/,M=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,N={};N[r]=N["[object Array]"]=N[w]=N[v]=N[o]=N[s]=N[b]=N[_]=N[I]=N[C]=N[T]=N[d]=N[h]=N[l]=N[p]=N[g]=N[f]=N[m]=N[S]=N[k]=N[x]=N[E]=!0,N["[object Error]"]=N[a]=N[y]=!1;var O="object"==typeof A&&A&&A.Object===Object&&A,j="object"==typeof self&&self&&self.Object===Object&&self,$=O||j||Function("return this")(),W=t&&!t.nodeType&&t,D=W&&e&&!e.nodeType&&e,F=D&&D.exports===W;function L(e,t){return e.set(t[0],t[1]),e}function G(e,t){return e.add(t),e}function U(e,t,n,i){for(var r=-1,o=e?e.length:0;++r<o;)n=t(n,e[r],r,e);return n}function H(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function B(e){var t=-1,n=Array(e.size);return e.forEach(function(e,i){n[++t]=[i,e]}),n}function J(e,t){return function(n){return e(t(n))}}function q(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}var V,z=Array.prototype,K=Function.prototype,Q=Object.prototype,Z=$["__core-js_shared__"],X=(V=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+V:"",Y=K.toString,ee=Q.hasOwnProperty,te=Q.toString,ne=RegExp("^"+Y.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ie=F?$.Buffer:void 0,re=$.Symbol,oe=$.Uint8Array,se=J(Object.getPrototypeOf,Object),ae=Object.create,ce=Q.propertyIsEnumerable,de=z.splice,he=Object.getOwnPropertySymbols,le=ie?ie.isBuffer:void 0,ue=J(Object.keys,Object),pe=De($,"DataView"),ge=De($,"Map"),fe=De($,"Promise"),me=De($,"Set"),ye=De($,"WeakMap"),we=De(Object,"create"),ve=He(pe),be=He(ge),_e=He(fe),Ie=He(me),Ce=He(ye),Ae=re?re.prototype:void 0,Te=Ae?Ae.valueOf:void 0;function Se(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function ke(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function xe(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Ee(e){this.__data__=new ke(e)}function Pe(e,t){var n=Je(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&qe(e)}(e)&&ee.call(e,"callee")&&(!ce.call(e,"callee")||te.call(e)==r)}(e)?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],i=n.length,o=!!i;for(var s in e)!ee.call(e,s)||o&&("length"==s||Ge(s,i))||n.push(s);return n}function Me(e,t,n){var i=e[t];ee.call(e,t)&&Be(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Re(e,t){for(var n=e.length;n--;)if(Be(e[n][0],t))return n;return-1}function Ne(e,t,n,i,u,y,A){var M;if(i&&(M=y?i(e,u,y,A):i(e)),void 0!==M)return M;if(!Ke(e))return e;var R=Je(e);if(R){if(M=function(e){var t=e.length,n=e.constructor(t);t&&"string"==typeof e[0]&&ee.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!t)return function(e,t){var n=-1,i=e.length;t||(t=Array(i));for(;++n<i;)t[n]=e[n];return t}(e,M)}else{var O=Le(e),j=O==a||O==c;if(Ve(e))return function(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}(e,t);if(O==l||O==r||j&&!y){if(H(e))return y?e:{};if(M=function(e){return"function"!=typeof e.constructor||Ue(e)?{}:(t=se(e),Ke(t)?ae(t):{});var t}(j?{}:e),!t)return function(e,t){return $e(e,Fe(e),t)}(e,function(e,t){return e&&$e(t,Qe(t),e)}(M,e))}else{if(!N[O])return y?e:{};M=function(e,t,n,i){var r=e.constructor;switch(t){case w:return je(e);case o:case s:return new r(+e);case v:return function(e,t){var n=t?je(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case b:case _:case I:case C:case T:case S:case k:case x:case E:return function(e,t){var n=t?je(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}(e,i);case d:return function(e,t,n){var i=t?n(B(e),!0):B(e);return U(i,L,new e.constructor)}(e,i,n);case h:case f:return new r(e);case p:return function(e){var t=new e.constructor(e.source,P.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(q(e),!0):q(e);return U(i,G,new e.constructor)}(e,i,n);case m:return a=e,Te?Object(Te.call(a)):{}}var a}(e,O,Ne,t)}}A||(A=new Ee);var $=A.get(e);if($)return $;if(A.set(e,M),!R)var W=n?function(e){return function(e,t,n){var i=t(e);return Je(e)?i:function(e,t){for(var n=-1,i=t.length,r=e.length;++n<i;)e[r+n]=t[n];return e}(i,n(e))}(e,Qe,Fe)}(e):Qe(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(W||e,function(r,o){W&&(r=e[o=r]),Me(M,o,Ne(r,t,n,i,o,e,A))}),M}function Oe(e){return!(!Ke(e)||(t=e,X&&X in t))&&(ze(e)||H(e)?ne:M).test(He(e));var t}function je(e){var t=new e.constructor(e.byteLength);return new oe(t).set(new oe(e)),t}function $e(e,t,n,i){n||(n={});for(var r=-1,o=t.length;++r<o;){var s=t[r];Me(n,s,e[s])}return n}function We(e,t){var n,i,r=e.__data__;return("string"==(i=typeof(n=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?r["string"==typeof t?"string":"hash"]:r.map}function De(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Oe(n)?n:void 0}Se.prototype.clear=function(){this.__data__=we?we(null):{}},Se.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},Se.prototype.get=function(e){var t=this.__data__;if(we){var i=t[e];return i===n?void 0:i}return ee.call(t,e)?t[e]:void 0},Se.prototype.has=function(e){var t=this.__data__;return we?void 0!==t[e]:ee.call(t,e)},Se.prototype.set=function(e,t){return this.__data__[e]=we&&void 0===t?n:t,this},ke.prototype.clear=function(){this.__data__=[]},ke.prototype.delete=function(e){var t=this.__data__,n=Re(t,e);return!(n<0)&&(n==t.length-1?t.pop():de.call(t,n,1),!0)},ke.prototype.get=function(e){var t=this.__data__,n=Re(t,e);return n<0?void 0:t[n][1]},ke.prototype.has=function(e){return Re(this.__data__,e)>-1},ke.prototype.set=function(e,t){var n=this.__data__,i=Re(n,e);return i<0?n.push([e,t]):n[i][1]=t,this},xe.prototype.clear=function(){this.__data__={hash:new Se,map:new(ge||ke),string:new Se}},xe.prototype.delete=function(e){return We(this,e).delete(e)},xe.prototype.get=function(e){return We(this,e).get(e)},xe.prototype.has=function(e){return We(this,e).has(e)},xe.prototype.set=function(e,t){return We(this,e).set(e,t),this},Ee.prototype.clear=function(){this.__data__=new ke},Ee.prototype.delete=function(e){return this.__data__.delete(e)},Ee.prototype.get=function(e){return this.__data__.get(e)},Ee.prototype.has=function(e){return this.__data__.has(e)},Ee.prototype.set=function(e,t){var n=this.__data__;if(n instanceof ke){var i=n.__data__;if(!ge||i.length<199)return i.push([e,t]),this;n=this.__data__=new xe(i)}return n.set(e,t),this};var Fe=he?J(he,Object):function(){return[]},Le=function(e){return te.call(e)};function Ge(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e<t}function Ue(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Q)}function He(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Be(e,t){return e===t||e!=e&&t!=t}(pe&&Le(new pe(new ArrayBuffer(1)))!=v||ge&&Le(new ge)!=d||fe&&Le(fe.resolve())!=u||me&&Le(new me)!=g||ye&&Le(new ye)!=y)&&(Le=function(e){var t=te.call(e),n=t==l?e.constructor:void 0,i=n?He(n):void 0;if(i)switch(i){case ve:return v;case be:return d;case _e:return u;case Ie:return g;case Ce:return y}return t});var Je=Array.isArray;function qe(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}(e.length)&&!ze(e)}var Ve=le||function(){return!1};function ze(e){var t=Ke(e)?te.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Qe(e){return qe(e)?Pe(e):function(e){if(!Ue(e))return ue(e);var t=[];for(var n in Object(e))ee.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Ne(e,!0,!0)}}(ae,ae.exports);var ce=T(ae.exports);function de(e,t,n){try{if(n?.canPublish("trace")&&n?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=he(e,void 0),t.commands){for(const n of t.commands)"remove"===n.type?fe(e,n.path):"set"===n.type&&pe(e,n.value,n.path);return e}const i=t.added,r=t.updated,o=t.removed;return i&&Object.keys(i).forEach(t=>{e[t]=i[t]}),r&&Object.keys(r).forEach(t=>{le(t,e,r)}),o&&o.forEach(t=>{delete e[t]}),e}catch(i){return n?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,i),e}}function he(e,t){return ce(e)}const le=(e,t,n)=>{const i=n[e];if(void 0===i)return t;const r=t[e];return r&&i?"string"==typeof r||"number"==typeof r||"boolean"==typeof r||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(r)||Array.isArray(i)?(t[e]=i,t):(t[e]=Object.assign({},r,i),t):(t[e]=i,t)};function ue(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(e[n]!==t[n]){if("object"!=typeof e[n])return!1;if(!ue(e[n],t[n]))return!1}}for(const n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function pe(e,t,n){const i=n.split("."),r=["__proto__","constructor","prototype"];let o;for(o=0;o<i.length-1;o++){const t=i[o];if(r.includes(t))throw new Error(`The provided path ${n} is invalid. It cannot contain segment/key that is equal to one of the following values: ${r}.`);e[t]||(e[t]={}),"object"!=typeof e[t]&&(e[t]={}),e=e[t]}e[i[o]]=t}function ge(e,t){return Object.keys(t).every(n=>"object"==typeof t[n]?ge(e?.[n]||{},t[n]||{}):t[n]===e?.[n])}function fe(e,t){const n=t.split(".");let i;for(i=0;i<n.length-1;i++){if(!e[n[i]])return;e=e[n[i]]}delete e[n[i]]}let me=class{ERROR_URI_FAILURE="global.errors.failure";ERROR_URI_INVALID_CONTEXT="global.errors.invalid_context";_logger;_connection;_trackAllContexts;_reAnnounceKnownContexts;_subscribeOnUpdate;_subscribeOnGet;_onlyReAnnounceSubscribedContexts;_gw3Session;_contextNameToData={};_gw3Subscriptions=[];_nextCallbackSubscriptionNumber=0;_creationPromises={};_contextNameToId={};_contextIdToName={};_protocolVersion=void 0;_contextsTempCache={};_contextsSubscriptionsCache=[];_systemContextsSubKey;get protocolVersion(){if(!this._protocolVersion){const e=this._connection.availableDomains.find(e=>"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[z,Z,ee,ne]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(re.name,e=>{const t=e.type;t&&(t===z||t===K||t===q?this.handleContextCreatedMessage(e):t===Z||t===ne||t===ie?this.handleContextUpdatedMessage(e):t!==ee&&t!==V||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:J,domain:"global",name:e,data:t,lifetime:"retained"}).then(n=>{this._contextNameToId[e]=n.context_id,this._contextIdToName[n.context_id]=e;const i=this._contextNameToData[e]||new se(n.context_id,e,!0,void 0);return i.isAnnounced=!0,i.name=e,i.contextId=n.context_id,i.context=n.data||he(t),i.hasReceivedSnapshot=!0,this._contextNameToData[e]=i,delete this._creationPromises[e],i.sentExplicitSubscription=!0,i.createdByUs=!0,this.subscribe(e,()=>{}),n.context_id})),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=he(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return void await this.createContext(e,t);const i=await this.get(n.name),r=this.setPathSupported?this.calculateContextDeltaV2(i,t):this.calculateContextDeltaV1(i,t);if(!(Object.keys(r.added).length||Object.keys(r.updated).length||r.removed.length||r.commands?.length))return Promise.resolve();const o=await this._gw3Session.send({type:te,domain:"global",context_id:n.contextId,delta:r},{},{skipPeerId:!1});!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,this.handleUpdated(n,r,{updaterId:o.peer_id}))}async set(e,t){t&&(t=he(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return this.createContext(e,t);const i=await this._gw3Session.send({type:te,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1});!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&this.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:i.peer_id})}setPath(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=he(t)),e in this._creationPromises&&await this._creationPromises[e];const n=this._contextNameToData[e];if(!n||!n.isAnnounced){const n={};for(const e of t)pe(n,e.value,e.path);return this.createContext(e,n)}const i=[];for(const e of t)null===e.value?i.push({type:"remove",path:e.path}):i.push({type:"set",path:e.path,value:e.value});const r=await this._gw3Session.send({type:te,domain:"global",context_id:n.contextId,delta:{commands:i}},{},{skipPeerId:!1});!this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||n.sentExplicitSubscription||n.activityId)&&(await n.snapshotPromise,this.handleUpdated(n,{added:{},removed:[],updated:{},commands:i},{updaterId:r.peer_id}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return!t&&this._subscribeOnGet&&this.subscribe(e,()=>{}),Promise.resolve({});if(t&&!t.sentExplicitSubscription)return new Promise((t,n)=>{this.subscribe(e,(e,n,i,r)=>{this._subscribeOnGet||this.unsubscribe(r),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):n(e)})});await t.snapshotPromise;const n=t?.context??{};return Promise.resolve(he(n))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribe(e,t,n){e in this._creationPromises&&await this._creationPromises[e];const i=void 0===n?this._nextCallbackSubscriptionNumber:n;void 0===n&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t}));let r=this._contextNameToData[e];if(!r||!r.isAnnounced)return r=r||new se(void 0,e,!1,void 0),this._contextNameToData[e]=r,r.updateCallbacks[i]=t,Promise.resolve(i);const o=r.hasCallbacks();if(r.updateCallbacks[i]=t,o){if(r.hasReceivedSnapshot&&!n){const e=he(r.context);t(e,e,[],i)}return Promise.resolve(i)}if(r.joinedActivity||r.createdByUs){if(r.hasReceivedSnapshot&&!n){const e=he(r.context);t(e,e,[],i)}return Promise.resolve(i)}if(r.context&&r.sentExplicitSubscription){if(r.hasReceivedSnapshot&&!n){const e=he(r.context);t(e,e,[],i)}return Promise.resolve(i)}return this.sendSubscribe(r).then(()=>i,()=>(this.unsubscribe(i,!0),i))}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const n=this._contextNameToData[t];if(!n)continue;const i=n.hasCallbacks();delete n.updateCallbacks[e],n.isAnnounced&&i&&!n.hasCallbacks()&&n.sentExplicitSubscription&&(n.hasReceivedSnapshot=!1,n.context={},this.sendUnsubscribe(n).catch(()=>{})),n.isAnnounced||n.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],n.contextId&&delete this._contextIdToName[n.contextId])}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e],n=t?.contextId;return t&&n?this._gw3Session.send({type:Y,domain:"global",context_id:t.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,n){const i=e.context;e.context=de(e.context,t,this._logger),this._contextNameToData[e.name]!==e||ue(i,e.context)||this.invokeUpdateCallbacks(e,t,n)}subscribeToContextCreatedMessages(){const e=[K,z,q];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===q?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===K&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const n=this._contextIdToName[e.context_id];if(!n)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[n])throw new Error("Received created event for context with unknown id: "+e.context_id);let i=this._contextNameToData[n];if(i){if(i.isAnnounced)return;if(!i.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");i.isAnnounced=!0,i.contextId=e.context_id,i.activityId=e.activity_id,i.sentExplicitSubscription||this.sendSubscribe(i).catch(()=>{})}else this._contextNameToData[n]=i=new se(e.context_id,n,!0,e.activity_id),this._trackAllContexts&&this.subscribe(n,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[ne,Z,ie];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,n=e.context_id;let i=this._contextNameToData[this._contextIdToName[n]];const r=!i||!i.isAnnounced;if(t===ie)i||(i=this._contextNameToData[e.activity_id]||new se(n,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=i,this._contextIdToName[n]=e.activity_id,this._contextNameToId[e.activity_id]=n,i.contextId=n,i.isAnnounced=!0,i.activityId=e.activity_id,i.joinedActivity=!0;else if(!i||!i.isAnnounced)return void(t===Z?(i=i||new se(n,e.name,!0,void 0),i.sentExplicitSubscription=!0,this._contextNameToData[e.name]=i,this._contextIdToName[n]=e.name,this._contextNameToId[e.name]=n):this._logger.error(`Received 'update' for unknown context: ${n}`));const o=i.context;if(i.hasReceivedSnapshot=!0,t===Z)i.context=e.data??{};else if(t===ie)i.context=e.context_snapshot??{};else{if(t!==ne)throw new Error("Unrecognized context update message "+t);i.context=de(i.context,e.delta,this._logger)}!r&&ue(i.context,o)&&t!==Z||this.invokeUpdateCallbacks(i,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,n){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),pe(t.updated,null,e.path)):"set"===e.type&&pe(t.updated,e.value,e.path)}for(const i in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(i))try{(0,e.updateCallbacks[i])(he(e.context),he(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(i,10),n)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[ee,V];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,n;if(e.type===V){if(n=e.activity_id,t=this._contextNameToId[n],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,n=this._contextIdToName[t],!n)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[n];const i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:Q,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:X,domain:"global",context_id:e.contextId})}catch(n){throw e.sentExplicitSubscription=t,n}}calculateContextDeltaV1(e,t){const n={added:{},updated:{},removed:[],reset:void 0};if(e)for(const i of Object.keys(e))-1===Object.keys(t).indexOf(i)||null===t[i]||ue(e[i],t[i])||(n.updated[i]=t[i]);for(const i of Object.keys(t))e&&-1!==Object.keys(e).indexOf(i)?null===t[i]&&n.removed.push(i):null!==t[i]&&(n.added[i]=t[i]);return n}calculateContextDeltaV2(e,t){const n={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const i of Object.keys(t))if(null!==t[i]){ue(e?e[i]:null,t[i])||n.commands?.push({type:"set",path:i,value:t[i]})}else n.commands?.push({type:"remove",path:i});return n}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const n=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||n.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(re.name,e=>{const t=e.type;t&&(t===z||t===K||t===q?this.handleContextCreatedMessage(e):t===Z||t===ne||t===ie?this.handleContextUpdatedMessage(e):t!==ee&&t!==V||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}};class ye{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new me(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,n){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(n),this.set(e,n)):this._bridge.setPath(e,t,n)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:n}of t){this.checkPath(e);""===e&&this.checkData(n)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,n,i,r,o)=>t(e,n,i,()=>this._bridge.unsubscribe(r),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function we(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n))}function ve(e=0,t,n){let i;const r=()=>{i&&clearTimeout(i)};return t.then(()=>{r()}).catch(()=>{r()}),new Promise((t,r)=>{i=setTimeout(()=>r(n),e)})}var be=function(e){return{ok:!0,result:e}},_e=function(e){return{ok:!1,error:e}},Ie=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:be(e(t.result,n.result))},Ce=function(e,t){return!0===t.ok?t:_e(e(t.error))},Ae=function(){return Ae=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},Ae.apply(this,arguments)};function Te(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!Te(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!Te(e[i[n]],t[i[n]]))return!1}return!0}}var Se=function(e){return Array.isArray(e)},ke=function(e){return"object"==typeof e&&null!==e&&!Se(e)},xe=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},Ee=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},Pe=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return Ae({at:e+(n||"")},i)},Me=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return Ce(function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}},n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e(function(e){return function(e,t){return!0===t.ok?be(e(t.result)):t}(t,n.decode(e))})},this.andThen=function(t){return new e(function(e){return function(e,t){return!0===t.ok?e(t.result):t}(function(n){return t(n).decode(e)},n.decode(e))})},this.where=function(t,i){return n.andThen(function(n){return t(n)?e.succeed(n):e.fail(i)})}}return e.string=function(){return new e(function(e){return"string"==typeof e?be(e):_e({message:xe("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?be(e):_e({message:xe("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?be(e):_e({message:xe("a boolean",e)})})},e.constant=function(t){return new e(function(e){return Te(e,t)?be(t):_e({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ke(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?_e({message:"the key '"+i+"' is required but was not present"}):_e(Pe("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return be(n)}return ke(e)?be(e):_e({message:xe("an object",e)})})},e.array=function(t){return new e(function(e){if(Se(e)&&t){return e.reduce(function(e,n,i){return Ie(function(e,t){return e.concat([t])},e,function(e,n){return Ce(function(e){return Pe("["+n+"]",e)},t.decode(e))}(n,i))},be([]))}return Se(e)?be(e):_e({message:xe("an array",e)})})},e.tuple=function(t){return new e(function(e){if(Se(e)){if(e.length!==t.length)return _e({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return _e(Pe("["+i+"]",r.error));n[i]=r.result}return be(n)}return _e({message:xe("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return Ie(Object.assign,t,n.decode(e))},be({}))})},e.anyJson=function(){return new e(function(e){return be(e)})},e.unknownJson=function(){return new e(function(e){return be(e)})},e.dict=function(t){return new e(function(e){if(ke(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return _e(Pe("."+i,r.error));n[i]=r.result}return be(n)}return _e({message:xe("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?be(void 0):t.decode(e)})},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e(function(e){for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var o=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return _e({message:'expected a value matching one of the decoders, got the errors ["'+o+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return be(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))})},e.valueAt=function(t,n){return new e(function(e){for(var i=e,r=0;r<t.length;r++){if(void 0===i)return _e({at:Ee(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ke(i))return _e({at:Ee(t.slice(0,r+1)),message:xe("an object",i)});if("number"==typeof t[r]&&!Se(i))return _e({at:Ee(t.slice(0,r+1)),message:xe("an array",i)});i=i[t[r]]}return Ce(function(e){return void 0===i?{at:Ee(t),message:"path does not exist"}:Pe(Ee(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return be(t)})},e.fail=function(t){return new e(function(e){return _e({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),Re=Me.string,Ne=Me.number,Oe=Me.boolean,je=Me.anyJson;Me.unknownJson;var $e=Me.constant,We=Me.object,De=Me.array;Me.tuple,Me.dict;var Fe=Me.optional;Me.oneOf;var Le=Me.union;Me.intersection,Me.withDefault,Me.valueAt,Me.succeed;var Ge=Me.fail;Me.lazy;const Ue=(e,t)=>{const n=typeof e;return"function"===n?je():Ge(`The provided argument as ${t} should be of type function, provided: ${typeof n}`)},He=Re().where(e=>e.length>0,"Expected a non-empty string"),Be=Ne().where(e=>e>=0,"Expected a non-negative number or 0"),Je=Le(He,We({name:He,objectTypes:Fe(De(He)),displayName:Fe(He),accepts:Fe(He),returns:Fe(He),description:Fe(He),version:Fe(Be),supportsStreaming:Fe(Oe()),flags:Fe(We()),getServers:Fe(je().andThen(e=>Ue(e,"method definition getServers")))})),qe=We({application:Fe(He),applicationName:Fe(He),pid:Fe(Be),machine:Fe(He),user:Fe(He),environment:Fe(He),region:Fe(He),service:Fe(He),instance:Fe(He),windowId:Fe(He),peerId:Fe(He),isLocal:Fe(Oe()),api:Fe(He),getMethods:Fe(je().andThen(e=>Ue(e,"instance getMethods"))),getStreams:Fe(je().andThen(e=>Ue(e,"instance getStreams")))}),Ve=Le($e("best"),$e("all"),$e("skipMine"),qe,De(qe)),ze=We({waitTimeoutMs:Fe(Be),methodResponseTimeoutMs:Fe(Be)});var Ke;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Ke||(Ke={}));class Qe{protocol;repo;instance;configuration;constructor(e,t,n,i){this.protocol=e,this.repo=t,this.instance=n,this.configuration=i}subscribe(e,t,n,i,r){const o=(e,n,i,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(n,t,e,i,o,r)},s=new Promise((n,i)=>{const r=e=>{n(e)},s=e=>{i(e)};if(!e)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void i(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let d=0,h=this.getServerMethodsByFilterAndTarget(a,c);if(h.length>0)o(h,h[0].methods[0],r,s);else{const n=()=>{if(c&&t.waitTimeoutMs)if(d+=500,h=this.getServerMethodsByFilterAndTarget(a,c),h.length>0){const e=h[0].methods[0];o(h,e,r,s)}else if(d>=t.waitTimeoutMs){o(h,"string"==typeof e?{name:e}:e,r,s)}else setTimeout(n,500)};setTimeout(n,500)}});return we(s,n,i)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,n)=>{e(t,n)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,n)=>{e({server:t,method:n})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,n)=>{e({server:t,method:n})})}async invoke(e,t,n,i,r,o){return we((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),n||(n="best"),i||(i={});const a=Je.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=Ve.run(n);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const d=ze.run(i);if(!d.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(d.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(r&&"function"!=typeof r){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=i.method_response_timeout,void 0===i.methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=i.wait_for_method_timeout,void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=this.configuration.waitTimeoutMs));let h=this.getServerMethodsByFilterAndTarget(s,n);if(0===h.length)try{h=await this.tryToAwaitForMethods(s,n,i)}catch(i){const r=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(n)}`;return Promise.reject(this.generateInvalidInputInvocationResult(r,s,t))}const l=i.methodResponseTimeoutMs,u=i,p=h.map(e=>{const n=W(10),i=e.methods[0],r=e.server,o=this.protocol.client.invoke(n,i,t,r,u);return Promise.race([o,ve(l,o,{invocationId:n,message:`Invocation timeout (${l} ms) reached for method name: ${i?.name}, target instance: ${JSON.stringify(r.instance)}, options: ${JSON.stringify(u)}`,status:Ke.Error})])}),g=await Promise.all(p),f=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===Ke.Error)?Promise.reject(f):f})(),r,o)}generateInvalidInputInvocationResult(e,t,n){const i={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},r={invocationId:W(10),status:Ke.Error,message:e};return this.getInvocationResultObj([r],i,n)}getInvocationResultObj(e,t,n){const i=e.filter(e=>e.status===Ke.Success).reduce((e,i)=>e=[...e,{executed_by:i.instance,returned:i.result,called_with:n,method:t,message:i.message,status:i.status}],[]),r=e.filter(e=>e.status===Ke.Error).reduce((e,i)=>e=[...e,{executed_by:i.instance,called_with:n,name:t.name,message:i.message}],[]),o=e[0];return{method:t,called_with:n,returned:o.result,executed_by:o.instance,all_return_values:i,all_errors:r,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,n){return new Promise((i,r)=>{if(0===n.waitTimeoutMs)return void r();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),i(a);else if(o>=(n.waitTimeoutMs||1e4))return clearInterval(s),void r()},500)})}filterByTarget(e,t){if("string"!=typeof e){let n;n=Array.isArray(e)?e:[e];return n.reduce((e,n)=>{const i=t.filter(e=>this.instanceMatch(n,e.server.instance));return e.concat(i)},[])}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(n=>{let i;const r=e[n],o=t[n];switch(n){case"objectTypes":i=(r||[]).every(e=>(o||[]).includes(e));break;case"flags":i=ge(o||{},r||{});break;default:i=String(r).toLowerCase()===String(o).toLowerCase()}return i})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let n={};return 1===t.length?n=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const i=e.methods[t];n[i.identifier]=i})}),Object.keys(n).map(e=>n[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,n)=>{const i=Object.values(n.methods).filter(t=>this.methodMatch(e,t));return i.length>0&&t.push({server:n,methods:i}),t},[])}getServerMethodsByFilterAndTarget(e,t){const n=this.getServers(e);return this.filterByTarget(t,n)}}class Ze{protocol;repoMethod;subscription;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.subscription=n}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}class Xe{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,n){this.protocol=e,this.repoMethod=t,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}}let Ye=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const n=new Xe(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const n=new Ze(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const n=new Ze(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}};class et{key;protocol;repoMethod;constructor(e,t,n){this.key=e,this.protocol=t,this.repoMethod=n}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new Ze(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class tt{_protocol;_repoMethod;_server;name;constructor(e,t,n){this._protocol=e,this._repoMethod=t,this._server=n,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new et(e,this._protocol,this._repoMethod):void 0:t.map(e=>new et(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new Ze(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class nt{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new Ye(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,n,i,r){const o=new Promise((n,i)=>{if(!e)return void i("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return i(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return i(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;r?(e=r,r.updateRepoMethod(s)):e=new tt(this.protocol,s,this),s.stream=e,n(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),i(e)})});return we(o,n,i)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{const i=t(e.args,e.instance);if(i&&"function"==typeof i.then){n(void 0,await i)}else n(void 0,i)}catch(e){n(e??"",e??"")}};return n.userCallback=t,this.registerCore(e,n)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const n=async(e,n)=>{try{let i=!1;const r=e=>{i||n(void 0,e),i=!0},o=e=>{i||(e||(e=""),n(e,e)),i=!0},s=t(e.args,e.instance,r,o);s&&"function"==typeof s.then&&s.then(r).catch(o)}catch(e){n(e,void 0)}};return n.userCallbackAsync=t,this.registerCore(e,n)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let n;if(n="string"==typeof e?{name:e}:e,void 0===n.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const i=this.serverRepository.getList().find(e=>e.definition.name===n.name&&(e.definition.supportsStreaming||!1)===t);if(!i)return Promise.reject(`Method with a name "${n.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([i])}async unregisterWithPredicate(e,t){const n=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!n||0===n.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(n)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const n=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(n),this.addAsCurrentlyUnregistering(e.definition.name,n)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const n=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,n]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let n;if(n="string"==typeof e?{name:""+e}:{...e},!n.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const i=this.currentlyUnregistering[n.name];void 0!==i&&await i;if(this.serverRepository.getList().some(e=>e.definition.name===n.name))return Promise.reject(`A method with the name "${n.name}" already exists! Please, provide a unique name for the method.`);if(n.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${n.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const r=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}});return this.protocol.server.register(r).catch(e=>{throw r?.repoId&&this.serverRepository.remove(r.repoId),e})}onMethodInvoked(e,t,n){e&&e.theFunction&&e.theFunction(n,(n,i)=>{if(null!=n)if(n.message&&"string"==typeof n.message)n=n.message;else if("string"!=typeof n)try{n=JSON.stringify(n)}catch(e){n=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(n)}`}i?("object"!=typeof i||Array.isArray(i))&&(i={_value:i}):i={},this.protocol.server.methodInvocationResult(e,t,n,i)})}}class it{wrapped={};constructor(e,t,n){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),n&&(n.loggedIn(()=>{this.refresh(n)}),this.refresh(n))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,n=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(n)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??W(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const rt=e=>({...e,flags:e.flags.metadata||{}});class ot{logger;API;servers={};myServer;methodsCount={};callbacks=k();constructor(e,t){this.logger=e,this.API=t;const n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const n=this.servers[t];if(n)return n.id;const i=new it(this.API,e),r={id:t,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[t]=r,this.callbacks.execute("onServerAdded",r.instance),t}removeServerById(e,t){const n=this.servers[e];n?(this.logger.debug(`removing server ${e}`),Object.keys(n.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",n.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");if(n.methods[t.id])return;const i=this.createMethodIdentifier(t),r=this,o={identifier:i,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>r.getServersByMethod(i)};o.object_types=o.objectTypes,o.display_name=o.displayName,o.version=o.version,n.methods[t.id]=o;const s=rt(o);return this.methodsCount[i]||(this.methodsCount[i]=0,this.callbacks.execute("onMethodAdded",s)),this.methodsCount[i]=this.methodsCount[i]+1,this.callbacks.execute("onServerMethodAdded",n.instance,s),o}removeServerMethod(e,t){const n=this.servers[e];if(!n)throw new Error("server does not exists");const i=n.methods[t];delete n.methods[t];const r=rt(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",r),this.callbacks.execute("onServerMethodRemoved",n.instance,r)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(rt)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),n=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,n,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),n=this.getMethods();return this.returnUnsubWithDelayedReplay(t,n,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let n=!1;const i=this.getServers();return setTimeout(()=>{i.forEach(t=>{const i=t.methods;Object.keys(i).forEach(r=>{n||e(t.instance,i[r])})})},0),()=>{n=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",n=e.result_signature??"";return(e.name+t+n).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(n=>{Object.values(n.methods).forEach(i=>{i.identifier===e&&t.push(n.instance)})}),t}returnUnsubWithDelayedReplay(e,t,n){let i=!1;return setTimeout(()=>{t.forEach(e=>{i||n(e)})},0),()=>{i=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,n])=>{t[e]=rt(n)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class st{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}}const at="onSubscriptionRequest",ct="onSubscriptionAdded",dt="onSubscriptionRemoved";class ht{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=k();nextStreamId=0;constructor(e,t,n,i){this.session=e,this.repository=t,this.serverRepository=n,this.logger=i,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,n){if("string"!=typeof n&&(n=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const i=this.getStreamId(t,n),r=e.msg.subscription_id,o={id:r,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[r]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:r,stream_id:i}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${r}: ${JSON.stringify(e)}`)}),this.callbacks.execute(ct,o,t)}rejectRequest(e,t,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,e.msg.subscription_id)}pushData(e,t,n){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof n?n=[n]:(!Array.isArray(n)||n.length<=0)&&(n=[]);e.protocolState.branchKeyToStreamIdMap.filter(e=>!n||0===n.length||n.indexOf(e.key)>=0).map(e=>e.streamId).forEach(e=>{const n={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(n).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");const i={type:"post",subscription_id:t.id,data:n};this.session.sendFireAndForget(i).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const n={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),t.instance,this.callbacks.execute(dt,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const n=e.protocolState.subscriptionsMap;let i=Object.keys(n).map(e=>n[e]);"string"==typeof t&&(i=i.filter(e=>e.branchKey===t)),i.forEach(e=>{delete n[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let n=[];if(!e.protocolState.subscriptionsMap)return[];const i=e.protocolState.subscriptionsMap,r=Object.keys(i).map(e=>i[e]);return n="string"!=typeof t?r:r.filter(e=>e.branchKey===t),n}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,n=Object.keys(t).map(e=>t[e]),i=[];return n.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===i.indexOf(t)&&i.push(t)}),i}onSubAdded(e){this.onSubscriptionLifetimeEvent(ct,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(at,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(dt,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const n=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(dt,n,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),n=t?.instance??{},i={msg:e,arguments:e.arguments_kv||{},instance:n},r=this.serverRepository.getById(e.method_id);if(void 0===r){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}r.protocolState.subscriptionsMap&&r.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(at,i,r)}sendSubscriptionFailed(e,t){const n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:i})),i}}class lt{session;clientRepository;serverRepository;logger;callbacks=k();streaming;constructor(e,t,n,i){this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.streaming=new ht(e,t,n,i.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const n=e.definition,i=Object.assign({},{metadata:n.flags??{}},{streaming:t||!1}),r={type:"register",methods:[{id:e.repoId,name:n.name,display_name:n.displayName,description:n.description,version:n.version,flags:i,object_types:n.objectTypes||n.object_types,input_signature:n.accepts,result_signature:n.returns,restrictions:void 0}]};return this.session.send(r,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,n,i){let r;r=n||""===n?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:n,context:i,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:i,request_id:void 0},this.session.sendFireAndForget(r).catch(n=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(n)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,n){this.streaming.pushData(e,t,n)}pushDataToSingle(e,t,n){this.streaming.pushDataToSingle(e,t,n)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,n){this.streaming.acceptRequestOnBranch(e,t,n)}rejectRequest(e,t,n){this.streaming.rejectRequest(e,t,n)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,n=e.caller_id,i=e.method_id,r=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===i)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(n)?.instance,a={args:r,instance:s};this.callbacks.execute("onInvoked",o,t,a)}}class ut{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const n=this.repository.getServerById(t.serverId)?.instance;n&&e.push(n)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class pt{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=W(10);this.cache.push({id:t,element:e});const n=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(n)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}}const gt="awaitingAccept",ft="subscribed",mt="Subscription failed.",yt="ClientInitiated";class wt{session;repository;logger;subscriptionsList={};timedCache=new pt({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,n,i,r,o){if(0===n.length)return void r({method:e,called_with:t.arguments,message:mt+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,i,r,t.methodResponseTimeout||1e4,o);"object"==typeof a?n.forEach(n=>{const i=n.server.id,r=n.methods.find(t=>t.name===e.name);if(!r)return void this.logger.error(`can not find method ${e.name} for target ${n.server.id}`);a.trackedServers.push({serverId:i,subscriptionId:void 0});const o={type:"subscribe",server_id:i,method_id:r.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:i,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):r({method:e,called_with:t.arguments,message:mt+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,n,i,r,o,s){const a={localKey:e,status:gt,method:t,params:n,success:i,error:r,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(n.onData&&a.handlers.onData.push(n.onData),n.onClosed&&a.handlers.onClosed.push(n.onClosed),n.onConnected&&a.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const i=this.subscriptionsList[e];i.status===gt?(r({method:t,called_with:n.arguments,message:mt+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):i.status===ft&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter(e=>void 0!==e.subscriptionId),delete i.timeoutId,i.trackedServers.length<=0&&(this.callOnClosedHandlers(i),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,n=t.subLocalKey,i=this.subscriptionsList[n];if("object"==typeof i&&(i.trackedServers=i.trackedServers.filter(e=>e.serverId!==t.serverId),i.trackedServers.length<=0)){if(clearTimeout(i.timeoutId),i.status===gt){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",n="object"==typeof i.params.arguments?JSON.stringify(i.params.arguments):"{}";i.error({message:"Subscription rejected."+t+" Called with:"+n,called_with:i.params.arguments,method:i.method})}else i.status===ft&&this.callOnClosedHandlers(i);delete this.subscriptionsList[n]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=e._tag.serverId,r=n.trackedServers.filter(e=>e.serverId===i)[0];if("object"!=typeof r)return;r.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=n.status===gt;if(n.status=ft,o){let e=!1,t=n.subscription;t?(t.setNewSubscription(n),n.success(t),e=!0):(t=new ut(this.repository,n),n.subscription=t,n.success(t));for(const i of n.handlers.onConnected)try{i(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==i.length)return;const r=e.oob,o=i[0].serverId,s=this.repository.getServerById(o),a=()=>({data:e.data,server:s?.instance??{},requestArguments:n.params.arguments,message:void 0,private:r}),c=n.handlers.onData,d=n.queued.data;c.length>0?c.forEach(e=>{"function"==typeof e&&e(a())}):d.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const n=this.subscriptionsList[t];if("object"!=typeof n)return;const i=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(n.queued.closers.push(t.serverId),!1)),n.trackedServers.length===i&&(n.trackedServers.length<=0&&(this.timedCache.add(n),clearTimeout(n.timeoutId),this.callOnClosedHandlers(n),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const n=e.queued.closers.length,i=n>0?e.queued.closers[n-1]:null;let r;void 0!==i&&"string"==typeof i&&(r=this.repository.getServerById(i)?.instance??{}),e.handlers.onClosed.forEach(n=>{"function"==typeof n&&n({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:r,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:yt}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,yt),delete this.subscriptionsList[e])}}class vt{session;repository;logger;streaming;constructor(e,t,n){this.session=e,this.repository=t,this.logger=n,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new wt(e,t,n)}subscribe(e,t,n,i,r,o){this.streaming.subscribe(e,t,n,i,r,o)}invoke(e,t,n,i){const r=i.id,o={type:"call",server_id:r,method_id:t.gatewayId,arguments_kv:n};return this.session.send(o,{invocationId:e,serverId:r}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,n=e.identity,i=!e.meta||e.meta.local,r=Number(n.process),o={machine:n.machine,pid:isNaN(r)?n.process:r,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:t,api:n.api,isLocal:i};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,n=e.reason;this.repository.removeServerById(t,n)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,n=e.methods,i=this.repository.getServerById(t);if(i){Object.keys(i.methods).forEach(e=>{const r=i.methods[e];n.indexOf(r.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,n=e.result,i=e._tag.serverId,r=this.repository.getServerById(i);return{invocationId:t,result:n,instance:r?.instance,status:Ke.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,n=e._tag.serverId,i=this.repository.getServerById(n),r=e.reason;return{invocationId:t,result:e.context,instance:i?.instance,status:Ke.Error,message:r}}return{invocationId:"",message:e.message,status:Ke.Error,error:e}}}function bt(e,t,n,i,r,o){const s=r.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),d=t.domain("agm",["subscribed"]),h=new lt(d,n,i,s.subLogger("server")),l=new vt(d,n,s.subLogger("client"));return d.onJoined(r=>{n.addServer(e,t.peerId),r?async function(){s.info("reconnected - will replay registered methods and subscriptions"),l.drainSubscriptionsCache().forEach(e=>{const t=e.method,n=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),o.client.subscribe(t,n,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=l.drainSubscriptions();for(const n of t){const t=n.method,i=Object.assign({},n.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),e.push(o.client.subscribe(t,i,void 0,void 0,n).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const n=i.getList();i.reset();for(const t of n){const n=t.definition;t.stream?e.push(o.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${n.name} DONE`)).catch(()=>s.warn(`subscribing to method ${n.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(n,t.theFunction.userCallback).then(()=>s.info(`registering method ${n.name} DONE`)).catch(()=>s.warn(`registering method ${n.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(n,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${n.name} DONE`)).catch(()=>s.warn(`registering method ${n.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:l,server:h}),a=void 0)}),d.onLeft(()=>{n.reset()}),d.join(),c}class _t{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let n;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new it(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ot(e.logger.subLogger("cRep"),this),this.serverRepository=new st,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);n=bt(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then(t=>(this.protocol=t,this.client=new Qe(this.protocol,this.clientRepository,this.instance,e),this.server=new nt(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,n,i){return this.client.subscribe(e,t,n,i)}createStream(e,t,n,i){return this.server.createStream(e,t,n,i)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,n,i,r,o){return this.client.invoke(e,t,n,i,r,o)}waitForMethod(e){const t=new M,n=this.client.methodAdded(i=>{i.name===e&&(n(),t.resolve(i))});return t.promise}}const It=["subscribed","success"];class Ct{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",It),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()})}ready(){return this.readyPromise}publish=(e,t,n)=>{const{routingKey:i,target:r}=n||{},o=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:i,target_identity:r});this.session.send(o).catch(t=>{this.logger.error(`Failed to publish message to topic ${e} with routing key ${i} for ${JSON.stringify(r)}: ${JSON.stringify(t)}`)})};subscribe=(e,t,n)=>new Promise((i,r)=>{const{routingKey:o,target:s}=n||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:o,source:s});this.session.send(a).then(n=>{const{subscription_id:r}=n;this.subscriptions.push({subscription_id:r,topic:e,callback:t,source:s}),i({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:r,peer_id:this.peerId}).then(()=>{this.subscriptions=this.subscriptions.filter(e=>e.subscription_id!==r)}).catch(e=>{this.logger.warn(`Failed to send unsubscribe request for ${r}: ${JSON.stringify(e)}`)}),Promise.resolve())})}).catch(e=>r(e))});watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:n}=e,i=e["publisher-identity"],r=this.subscriptions.find(e=>e.subscription_id===n);r&&(r.source?this.keysMatch(r.source,i)&&r.callback(t,r.topic,i):r.callback(t,r.topic,i))})};removeEmptyValues(e){const t={};return Object.keys(e).forEach(n=>{void 0!==e[n]&&null!==e[n]&&(t[n]=e[n])}),t}keysMatch(e,t){const n=Object.keys(e);let i=!0;return n.forEach(n=>{e[n]!==t[n]&&(i=!1)}),i}}const At=(e,t)=>{const n="object"==typeof window?window.iodesktop??window.glue42gd:void 0,i="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),r=N("glue"),o=function(e,t,n){let i;if(P.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{i=JSON.parse(e)}catch{}}function r(){if(e.application)return e.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=W(10);return P.isNode()?i?i.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let d=o?.ws;const h=o?.sharedWorker,l=o?.inproc,u=o?.webPlatform??void 0;let p,g,f,m,y;n&&(d=n.gwURL),P.isNode()&&i&&i.gwURL&&(d=i.gwURL),d||h||l||(d="ws://localhost:8385");const w=r();let v=w;void 0!==n?(g=n.windowId,f=n.pid,n.env&&(m=n.env.env,y=n.env.region),v=n.application??"glue-app",p=n.appInstanceId):P.isNode()?(f=process.pid,i&&(m=i.env,y=i.region,p=i.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,f=window?.glue42electron.pid,m=window?.glue42electron.env,y=window?.glue42electron.region,v=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const b=e.gateway?.replaySpecs??[];b.push(re);let _={application:v,applicationName:w,windowId:g,instance:p,process:f,region:y,environment:m,api:t.version||oe};return e.identity&&(_=Object.assign(_,e.identity)),{identity:_,reconnectInterval:a,ws:d,sharedWorker:h,webPlatform:u,inproc:l,protocolVersion:s,reconnectAttempts:c,replaySpecs:b}}();let s=r();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:P.isNode()&&i&&i.gwToken?{gatewayToken:i.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const i="warn";let r;return t||(t=i),n&&(r=n.consoleLogLevel),"string"==typeof t?{console:r??t,publish:i}:{console:r??t.console??i,publish:t.publish??i}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||oe,libs:t.libs??[],customLogger:e.customLogger}}(e=e||{},t=t||{},n);let s,a,c,d,h,l,u;const p={};function g(e,t,n){u=c.canPublish("trace"),u&&c.trace(`registering ${e} module`);const i=i=>{if(t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,!u)return;const r=i?`${e} failed - ${i.message}`:`${e} is ready - ${n.endTime-n.startTime}`;c.trace(r)};t.initStartTime=n.startTime,t.ready?t.ready().then(()=>{i()}).catch(e=>{const t="string"==typeof e?new Error(e):e;i(t)}):i(),Array.isArray(e)||(e=[e]),e.forEach(e=>{p[e]=t,At[e]=t})}function f(){const e=N("metrics"),t=o.metrics,i=n?.getMetricsPublishingEnabled,r=o.connection.identity,a=i||(()=>!0),h=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return d=C({connection:t?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:r?.service??n?.applicationName??o.application,instance:r?.instance??r?.windowId??W(10),disableAutoAppSystem:h,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",d,e),Promise.resolve()}function m(){const e=N("interop"),t={connection:s,logger:c.subLogger("interop")};return a=new _t(t),B.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=o.activities&&3===s.protocolVersion;if(o.contexts||e){const e=N("contexts");h=new ye({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof o.contexts&&o.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof o.contexts&&o.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof o.contexts||o.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof o.contexts||o.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof o.contexts||o.contexts.onlyReAnnounceSubscribedContexts}),g("contexts",h,e)}else{const e=s.replayer;e&&e.drain(re.name)}return Promise.resolve()}async function w(){if(!o.bus)return Promise.resolve();const e=N("bus");return l=new Ct(s,c.subLogger("bus")),g("bus",l,e),Promise.resolve()}function v(e){try{return e.forEach(e=>{!function(e,t){const n=N(e),i=t(p);i&&g(e,i,n)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return i.then(function(){const e=N("logger");return c=new B(`${o.connection.identity?.application}`,void 0,o.customLogger),c.consoleLevel(o.logger.console),c.publishLevel(o.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)}).then(function(){const e=N("connection");s=new U(o.connection,c.subLogger("connection"));let t=Promise.resolve(o.auth);return o.connection&&!o.auth&&(n?t=n.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let n;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return n=t,s.login(n)}).then(()=>(g("connection",s,e),o)).catch(e=>{throw s&&s.logout(),e})}).then(()=>Promise.all([f(),m(),y(),w()])).then(()=>a.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(P.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>v(o.libs||[])).then(function(){const e=Object.keys(p).map(e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const i={coreVersion:oe,version:o.version};r.stop();const u={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:i,logger:c,interop:a,agm:a,connection:s,metrics:d,contexts:h,bus:l,version:o.version,userConfig:e,done:()=>(c?.info("done called by user..."),s.logout())};if(u.performance={get glueVer(){return o.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=R;return Object.keys(e).map(t=>{const n=e[t];return{name:t,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}})}},Object.keys(p).forEach(e=>{const t=p[e];u[e]=t}),u.config={},Object.keys(o).forEach(e=>{u.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{u.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(u),n&&n.updatePerfData&&n.updatePerfData(u.performance),u.agm){const e=(e,t,n)=>function(){return u.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${n}' instead.`),e.apply(u.agm,arguments)},t=u.agm;t.method_added=e(u.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(u.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(u.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(u.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(u.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return u}).catch(e=>Promise.reject({err:e,libs:p}))};"undefined"!=typeof window&&(window.IOConnectCore=At),At.version=oe,At.default=At;class Tt{constructor(e){this._id=e}get id(){return this._id}_update(e){if(e._id!==this._id)throw Error("Can not update from entity with different id.");this._updateCore(e)}_updateCore(e){}_beforeDelete(e){}}function St(e){return"number"==typeof e}function kt(e){return"string"==typeof e}function xt(e){return"object"==typeof e&&!Array.isArray(e)&&null!==e}function Et(e){return Array.isArray?Array.isArray(e):"[object Array]"===toString.call(e)}function Pt(e){return void 0===e}function Mt(e){return null==e}function Rt(e){return"string"!=typeof e||!e||0===e.length||/^\s*$/.test(e)}function Nt(e){return!0===e||!1===e||"[object Boolean]"===toString.call(e)}function Ot(e){return!!(e&&e.constructor&&e.call&&e.apply)}function jt(e,t){void 0!==e&&t(e)}class $t extends Tt{constructor(e,t,n,i){super(e),this._name=e,this._description=i,this._ownerWindow=t,this._helperWindows=n||[]}get name(){return this._name}get description(){return this._description}get helperWindows(){return this._helperWindows.map(e=>this.covertToWindowDef(e))}get ownerWindow(){return this.covertToWindowDef(this._ownerWindow)}initiate(e,t,n){return this._manager.initiate(this._name,e,t,n)}_updateCore(e){super._updateCore(e),jt(e._description,e=>this._description=e),jt(e._ownerWindow,e=>this._ownerWindow=e),jt(e._helperWindows,e=>this._helperWindows=e)}covertToWindowDef(e){var t,n;return{type:null===(t=null==e?void 0:e.id)||void 0===t?void 0:t.type,name:null===(n=null==e?void 0:e.id)||void 0===n?void 0:n.name}}}class Wt extends Tt{constructor(e,t){super(e),this._name=e,this._appByWindowTypeGetter=t}get name(){return this._name}get config(){return this._appByWindowTypeGetter(this._name)}get windows(){return this._manager.getWindows({type:this._name})}create(e,t){const n=Object.assign({type:this.name,name:this.name,isIndependent:!1},t);return this._manager.createWindow(e,n)}}class Dt{constructor(e,t){this.entity=e,this.context=t}}class Ft{constructor(e){this.type=e}}class Lt extends Ft{constructor(e,t){super(Ut.StatusChange),this.newStatus=e,this.oldStatus=t}}class Gt extends Ft{constructor(e,t,n){super(Ut.ActivityContextChange),this.context="string"==typeof e?JSON.parse(e):e,this.updated=t,this.removed=n}}class Ut{}Ut.Added="added",Ut.Removed="removed",Ut.Updated="updated",Ut.Closed="closed",Ut.StatusChange="statusChange",Ut.ActivityContextChange="activityContextUpdate",Ut.ActivityWindowEvent="activityWindowEvent",Ut.ActivityWindowJoinedActivity="joined",Ut.ActivityWindowLeftActivity="left";class Ht{}Ht.Created="created",Ht.Started="started",Ht.Destroyed="destroyed";class Bt{constructor(e){this._activity=e}register(e,t){this._ensureHasAgm(),Bt.AGM.register(e,t)}servers(){return this._ensureHasAgm(),Mt(this._activity)?[]:this._activity.windows.map(e=>e.instance)}methods(){if(this._ensureHasAgm(),Mt(this._activity))return[];const e=this._activity.windows,t=[],n=[];return e.forEach(e=>{this.methodsForWindow(e).forEach(e=>{-1===t.indexOf(e.name)&&(t.push(e.name),n.push(e))})}),n}methodsForWindow(e){return this._ensureHasAgm(),e.instance?Bt.AGM.methodsForInstance(e.instance):[]}invoke(e,t,n,i,r,o){this._ensureHasAgm();const s=this.servers();if(Mt(n)&&(n="activity.all"),kt(n))if("activity.all"===n);else{if("activity.best"!==n){if("all"===n||"best"===n)return function(e,t,n){if("function"!=typeof t&&"function"!=typeof n)return e;"function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n)}(Bt.AGM.invoke(e,t,n,i),r,o);throw new Error("Invalid invoke target "+n)}{const t=s.filter(t=>Bt.AGM.methodsForInstance(t).filter(t=>t.name===e).length>0);t.length>0&&t[0]}}else if(Et(n)){if(n.length>=0){const e=n[0];if(this._isInstance(e))n.map(e=>e);else{if(!this._isActivityWindow(e))throw new Error("Unknown target object");n.map(e=>e.instance)}}}else if(this._isInstance(n));else{if(!this._isActivityWindow(n))throw new Error("Unknown target object");n.instance}throw new Error("Not implemented")}unregister(e){return this._ensureHasAgm(),Bt.AGM.unregister(e)}createStream(e,t,n){this._ensureHasAgm(),Bt.AGM.createStream(e,{subscriptionAddedHandler:t,subscriptionRemovedHandler:n,subscriptionRequestHandler:void 0})}subscribe(e,t,n){return this._ensureHasAgm(),Bt.AGM.subscribe(e,t)}_ensureHasAgm(){if(Mt(Bt.AGM))throw new Error("Agm should be configured to be used in activity")}_isInstance(e){return void 0!==e.application}_isActivityWindow(e){return void 0!==e.instance}}class Jt{constructor(e,t,n){this._manager=e,this._ownerActivityId=t,this._state=n}get ownerId(){return this._state.ownerId}get windowIds(){return this._state.windowIds}get frameColor(){return this._state.frameColor}get context(){return this._state.context}get tag(){return this._state.tag}detach(e){e=e||{};const t={};return Object.keys(this._state).forEach(e=>{t[e]=this._state[e]}),t.context=e.context||t.context,t.frameColor=e.frameColor||t.frameColor,this._manager.detachActivities(this._ownerActivityId,t)}}const qt=e=>{setTimeout(e,0)};function Vt(e,t){if(!Ot(t))return e;e.then(e=>{qt(()=>{t(null,e)})},e=>{qt(()=>{t(e,null)})})}class zt extends Tt{constructor(e,t,n,i,r){super(e),this._id=e,this._actType=t,this._status=n,this._context=i,this._ownerId=r,this._agm=new Bt(this)}get type(){if(this._manager)return this._manager.getActivityType(this._actType)}get context(){return this._context}get status(){return this._status}get owner(){return this._ownerId?this._manager.getWindows({id:this._ownerId})[0]:null}get windows(){return this._manager.getWindows({activityId:this._id})}get agm(){return this._agm}addWindow(e,t){return this._manager.addWindowToActivity(this,e,t)}createWindow(e,t){return this._manager.createWindow(this,e,t)}createStackedWindows(e,t,n){return this._manager.createStackedWindows(this,e,t,n)}leave(e,t){return this._manager.leaveWindowFromActivity(this,e,t)}getWindowsByType(e){const t={activityId:this._id,type:e};return this._manager.getWindows(t)}setContext(e,t){return this._manager.setActivityContext(this,e,t)}updateContext(e,t){return this._manager.updateActivityContext(this,e,t)}onStatusChange(e){return this._manager.subscribeActivityEvents((t,n,i)=>{t.id===this.id&&e(t,n,i)})}onWindowEvent(e){return this._manager.subscribeWindowEvents((t,n,i)=>{t.id===this.id&&e(t,n,i)})}onContextChanged(e){this._manager.subscribeActivityContextChanged((t,n,i,r)=>{t.id===this.id&&e(n,i,r,t)});try{e(this.context,this.context,[],this)}catch(e){return}}stop(){this._manager.stopActivity(this)}clone(e){return this._manager.clone(this,e)}attach(e,t){let n;return n="string"==typeof e?e:e.id,this._manager.attachActivities(n,this.id,t)}onActivityAttached(e){this._manager.subscribeActivitiesAttached((t,n,i)=>{t===this._id&&e(i)})}onDetached(e){this._manager.subscribeActivitiesDetached((t,n,i)=>{n.id===this._id&&e(t,i)})}_updateCore(e){super._updateCore(e),jt(e._actType,e=>this._actType=e),jt(e._context,e=>this._context=e),jt(e._ownerId,e=>this._ownerId=e),!e._status||this._status&&this._status.state===e._status.state||(this._status=e._status)}_updateDescriptors(e){this._attached=e.map(e=>new Jt(this._manager,this._id,e))}get attached(){return this._attached}setFrameColor(e,t){return Vt(new Promise((t,n)=>{let i=this.windows.length;0===i&&t(this),this.windows.forEach(n=>{n.underlyingWindow.setFrameColor(e,()=>{i--,i<=0&&t(this)})}),setTimeout(()=>{i>0&&n(this.id+" - timed out waiting for setFrameColor with"+e)},5e3)}),t)}getFrameColor(){return this.windows&&0!==this.windows.length?this.windows[0].underlyingWindow.frameColor:""}}class Kt{}Kt.Trace="trace",Kt.Debug="debug",Kt.Info="info",Kt.Warn="warn",Kt.Error="error";class Qt{static GetNamed(e){return new Qt(e)}static Get(e){return new Qt(Qt.GetTypeName(e))}constructor(e){this._name=e,Mt(Qt.GlueLogger)||(this._glueLogger=Qt.GlueLogger.subLogger(e))}trace(e){Mt(this._glueLogger)?Qt.Level===Kt.Trace&&console.info(this._getMessage(e,Kt.Trace)):this._glueLogger.trace(e)}debug(e){Mt(this._glueLogger)?Qt.Level!==Kt.Debug&&Qt.Level!==Kt.Trace||console.info(this._getMessage(e,Kt.Debug)):this._glueLogger.debug(e)}info(e){Mt(this._glueLogger)?Qt.Level!==Kt.Debug&&Qt.Level!==Kt.Trace&&Qt.Level!==Kt.Info||console.info(this._getMessage(e,Kt.Info)):this._glueLogger.info(e)}warn(e){Mt(this._glueLogger)?Qt.Level!==Kt.Debug&&Qt.Level!==Kt.Trace&&Qt.Level!==Kt.Info&&Qt.Level!==Kt.Warn||console.info(this._getMessage(e,Kt.Info)):this._glueLogger.warn(e)}error(e){Mt(this._glueLogger)?(console.error(this._getMessage(e,Kt.Error)),console.trace()):this._glueLogger.error(e)}_getMessage(e,t){return"["+t+"] "+this._name+" - "+e}static GetTypeName(e){const t=/function (.{1,})\(/.exec(e.constructor.toString());return t&&t.length>1?t[1]:""}}Qt.Level=Kt.Info;class Zt extends Tt{constructor(e,t,n,i,r,o,s,a){super(e),this._logger=Qt.Get("window"),this._type=n,this._activityId=i,this._name=t,this._instance=r,this._isIndependent=o,this._windowGetter=s,this._hcWindowId=a}getBounds(){return this._manager.getWindowBounds(this.id)}get name(){return this._name}get isIndependent(){return this._isIndependent}get type(){if(this._manager)return this._manager.getWindowType(this._type)}get activity(){if(!Pt(this._activityId))return this._manager.getActivityById(this._activityId)}get isOwner(){const e=this.activity;return!Pt(e)&&e.owner.id===this.id}setVisible(e,t){return this._manager.setWindowVisibility(this.id,e)}activate(e){return this._manager.activateWindow(this.id,e)}setBounds(e,t){return this._manager.setWindowBounds(this.id,e,t)}close(){return this._manager.closeWindow(this.id)}get instance(){return this._instance}get underlyingWindow(){const e=this._windowGetter();return e||{id:this._hcWindowId}}onActivityJoined(e){this._subscribeForActivityWindowEvent(Ut.ActivityWindowJoinedActivity,e)}onActivityRemoved(e){this._subscribeForActivityWindowEvent(Ut.ActivityWindowLeftActivity,e)}_updateCore(e){jt(e._activityId,e=>this._activityId=e),jt(e._isIndependent,e=>this._isIndependent=e),jt(e._hcWindowId,e=>this._hcWindowId=e),jt(e._type,e=>this._type=e),jt(e._name,e=>this._name=e),Mt(e._instance)||(this._instance=e._instance)}_subscribeForActivityWindowEvent(e,t){this._manager.subscribeWindowEvents((n,i,r)=>{i.id===this.id&&r===e&&t(n)})}_beforeDelete(e){this._hcWindowId=e._hcWindowId}}class Xt{constructor(e,t,n){this.state=e,this.message=t,this.time=n}getState(){return this.state}getMessage(){return this.message}getTime(){return this.time}}const Yt="error",en="add-types",tn="created",nn="destroyed",rn="initiated",on="joined",sn="activity-joined",an="left",cn="owner-changed",dn="add-peer-factories",hn="peer-factories-added",ln="peer-factories-removed",un="peer-created";class pn{static activityTypeGwMessageEntityToActivityType(e,t){const n=e=>new Wt(e,void 0);return new $t(e.name,e.owner_type&&n(e.owner_type),e.helper_types&&e.helper_types.map(n),t)}static peerFactoryGwMessageEntityToWindowType(e){return new Wt(e.peer_type,e=>{})}static activityGwMessageToActivity(e,t){const n=void 0!==e.owner?e.owner.peer_id:e.owner_id;return new zt(e.activity_id,e.activity_type,t,e.context_snapshot,n)}static activityToActivityStatusChangeEvent(e){return new Dt(e,new Lt(e.status,void 0))}constructor(e){if(this._activityChangeCallbacks=[],this._activityTypeStatusChangeCallbacks=[],this._activityWindowChangeCallbacks=[],this._windowTypeStatusChangeCallbacks=[],this._peerIdAndFactoryIdToPeerType={},this._peerFactoriesRegisteredByUs={},this._gw3Subscriptions=[],this._contextSubscriptions={},this._activityTypesInitiatedFromMe={},this._config=e,this._connection=e.connection,this._logger=e.logger,this._contexts=e.contexts,this._windows=e.windows,this._sessionJoinedPromise=new Promise(e=>{this._sessionJoinedPromiseResolve=e}),this._activityJoinedPromise=new Promise(e=>{this._activityJoinedPromiseResolve=e}),this._config.activityId||this._activityJoinedPromiseResolve({}),this._gw3Session=this._connection.domain("activity",["joined","initiated","peer-created","token"]),"undefined"!=typeof window){const e=window.glue42gd;e&&e.activityInfo&&("function"==typeof e.addRefreshHandler&&e.addRefreshHandler((t,n)=>{this._gw3Session.send({type:"reload"}).then(i=>{if(i.token){try{e.setGWToken(i.token)}catch(e){return void n(e.message||e)}t()}else n("Expected gateway token for refreshing.")},n)}),e&&"function"==typeof e.addWillNavigateHandler&&e.addWillNavigateHandler((t,n)=>{this._gw3Session.send({type:"reload"}).then(i=>{if(i.token){try{e.setGWToken(i.token)}catch(e){return void n(e.message||e)}t()}else n("Expected gateway token for refreshing.")},n)}))}}get bridgeType(){return"GW3"}init(){this.forwardActivityTypeMessagesToStatusEventHandlers(),this.subscribe(tn,this.handleActivityCreatedMessage),this.subscribe(nn,this.handleActivityDestroyedMessage),this.forwardActivityMessagesToStatusEventHandlers(),this.forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(),this.forwardPeerFactoryMessagesToStatusEventHandlers(),this.forwardPeerFactoryMessagesToPeerFactoryRequests(),this.subscribe(hn,this.handlePeerFactoriesAdded),this.subscribe(ln,this.handlePeerFactoriesRemoved),this.forwardActivityWindowMessagesToEventHandlers(),this.subscribe("dispose-peer",()=>{if("dispose"!==this._config.disposeRequestHandling){if("exit"===this._config.disposeRequestHandling){if(this._windows&&void 0!==this._windows.my())return void this._windows.my().close();if("undefined"!=typeof window&&"function"==typeof window.close)return void window.close();if("undefined"!=typeof process&&"function"==typeof process.exit)return void process.exit()}}else this.dispose()}),this._gw3Session.onJoined(()=>{"trackMyOnly"===this._config.mode||"trackMyTypeAndInitiatedFromMe"===this._config.mode?this._sessionJoinedPromiseResolve(this):this._gw3Session.send({type:"subscribe",activity_types:"trackAll"===this._config.mode?[]:"trackTypes"===this._config.mode?this._config.typesToTrack:[]}).then(()=>{this._sessionJoinedPromiseResolve(this)})}),this._gw3Session.join()}dispose(){this._gw3Subscriptions.forEach(e=>e&&this._connection.off(e)),this._gw3Subscriptions.length=0}ready(){return Promise.all([this._sessionJoinedPromise,this._activityJoinedPromise])}initReady(){return this._sessionJoinedPromise}onActivityTypeStatusChange(e){this._activityTypeStatusChangeCallbacks.push(e)}registerActivityType(e,t,n,i,r){const o={};o.name=e;const s=e=>({type:e.type,name:e.name,configuration:e});return o.owner_type=s(t),o.helper_types=n.map(s),this._gw3Session.send({type:en,types:[o]}).then(()=>{const e=pn.activityTypeGwMessageEntityToActivityType(o,r);return this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new Dt(e,new Ft(Ut.Added)),en),e})}unregisterActivityType(e){return this._gw3Session.send({type:"remove-types",types:[e]}).then(()=>{const t=new $t(e,void 0,void 0,void 0);this.invokeCallbacks(this._activityTypeStatusChangeCallbacks,new Dt(t,new Ft(Ut.Removed)),en)})}onWindowTypeStatusChange(e){this._windowTypeStatusChangeCallbacks.push(e)}registerWindowFactory(e,t,n){if(this._peerFactoriesRegisteredByUs[e])return Promise.reject(new Error(`Factory for windowType ${e} already registered.`));this._peerFactoriesRegisteredByUs[e]=t;const i={id:e,peer_type:e,configuration:n};return this._gw3Session.send({type:dn,factories:[i]}).then(()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new Dt(pn.peerFactoryGwMessageEntityToWindowType(i),new Ft(Ut.Added)),dn)}).catch(()=>{delete this._peerFactoriesRegisteredByUs[e]})}unregisterWindowFactory(e){return this._peerFactoriesRegisteredByUs[e]?(delete this._peerFactoriesRegisteredByUs[e],this._gw3Session.send({type:"remove-peer-factories",factory_ids:[e]}).then(()=>{this.invokeCallbacks(this._windowTypeStatusChangeCallbacks,new Dt(new Wt(e,void 0),new Ft(Ut.Removed)),dn)})):Promise.reject(new Error(`Factory for windowType ${e} not registered.`))}onActivityStatusChange(e){this._activityChangeCallbacks.push(e)}initiateActivity(e,t,n){const i={type:"create",activity_type:e,initial_context:t};return this.isOverrideTypeDefinition(n)?i.types_override={owner_type:{type:n.owner.type,name:n.owner.name,configuration:n.owner},helper_types:n.helpers&&n.helpers.map(e=>({type:e.type,name:e.name,configuration:e}))}:i.configuration=n&&n.map(e=>({type:e.type,name:e.name,configuration:e})),this.sendCreateAndMapResultingMessagesToPromise(i,rn,(e,t)=>e.request_id===t,tn,(e,t,n)=>e.activity_id===n.activity_id,nn,(e,t,n)=>e.activity_id===n.activity_id,e=>e.activity_id,null).then(t=>"trackMyTypeAndInitiatedFromMe"!==this._config.mode||this._activityTypesInitiatedFromMe[e]?t:(this._activityTypesInitiatedFromMe[e]=!0,this._gw3Session.send({type:"subscribe",activity_types:[e]}).then(()=>t)))}stopActivity(e){return this._gw3Session.send({type:"destroy",activity_id:e.id,reason_uri:"com.tick42.glue.activity.constants.destroyReason.general",reason:"Destroying activity"}).then(e=>!0)}updateActivityContext(e,t,n,i){if(n)return this._contexts.set(e.id,t);i=i||[];for(const e of i)t[e]=null;return this._contexts.update(e.id,t)}announceWindow(e,t){throw new Error("Invalid operation 'announceWindow' for GW3 protocol")}registerWindow(e,t,n){let i=void 0!==this._connection.gatewayToken;const r=this._connection.peerId;if("undefined"!=typeof window){const e=window.glue42gd;e&&(i=void 0!==e.activityInfo)}return i&&this._gw3Session.send({type:"ready"}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new Dt(new Zt(r,t,e,void 0,this.getAgmInstance(r),n,this.generateWindowGetter(r),void 0),new Ft(Ut.Added)),"register window"),Promise.resolve(r)}onActivityWindowChange(e){this._activityWindowChangeCallbacks.push(e)}createWindow(e,t){t.layout||(t.left||t.width||t.height||t.top)&&(t.layout={mode:"pixels",cellSize:1});const n=n=>{if(e)return this.joinActivity(e,n,t.name).then(()=>n)};return this.sendCreateAndMapResultingMessagesToPromise({type:"create-peer",peer_type:t.type,peer_name:t.name||t.type,configuration:t,activity_id:e},void 0,void 0,un,(e,t)=>e.request_id===t,void 0,void 0,e=>e.created_id,n).then(n)}async closeWindow(e){await this._gw3Session.send({type:"destroy-peer",destroy_peer_id:e})}getAnnouncementInfo(){let e=this._config.activityId||this._config.announcementInfo&&this._config.announcementInfo.activityId,t=this._config.announcementInfo&&this._config.announcementInfo.activityWindowType,n=this._config.announcementInfo&&this._config.announcementInfo.activityWindowIndependent,i=this._config.announcementInfo&&this._config.announcementInfo.activityWindowName;if("undefined"!=typeof window&&void 0!==window.location&&window.location.search&&"function"==typeof URLSearchParams){const r=new URLSearchParams(location.search.slice(1));t=t||r.get("t42PeerType"),t=t||r.get("t42ActivityWindowType"),void 0===n&&(n=r.get("t42ActivityWindowIndependent")),i=i||r.get("t42ActivityWindowName"),e=e||r.get("t42ActivityId")}return t=t||"unknown",n=n||!1,i=i||this._connection.peerId,{activityWindowId:void 0,activityId:e,activityWindowType:t,activityWindowIndependent:n,activityWindowName:i}}joinActivity(e,t,n){const i=n&&{name:n}||{};return this._gw3Session.send({type:"join-activity",target_id:t,activity_id:e,...i}).then(()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new Dt(new Zt(t,void 0,void 0,e,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new Ft(Ut.ActivityWindowJoinedActivity)),"activity joined - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new Dt(new zt(e,void 0,new Xt("created",void 0,void 0),void 0,void 0),new Ft(Ut.Updated)),"activity joined - Activity")})}leaveActivity(e,t){return this._gw3Session.send({type:"leave-activity",target_id:t,activity_id:e}).then(()=>{this.invokeCallbacks(this._activityWindowChangeCallbacks,new Dt(new Zt(t,void 0,void 0,null,this.getAgmInstance(t),void 0,this.generateWindowGetter(t),void 0),new Ft(Ut.ActivityWindowLeftActivity)),"activity left - ActivityWindow"),this.invokeCallbacks(this._activityChangeCallbacks,new Dt(new zt(e,void 0,new Xt("created",void 0,void 0),void 0,void 0),new Ft(Ut.Updated)),"activity left - Activity")})}getActivityTypes(){return Promise.resolve([])}getWindowTypes(){return Promise.resolve([])}getActivities(){return Promise.resolve([])}getActivityWindows(){return Promise.resolve([])}createStackedWindows(e,t,n){}getWindowBounds(e){}setWindowBounds(e,t){}activateWindow(e,t){}setWindowVisibility(e,t){}cloneActivity(e,t){}attachActivities(e,t,n){return this._gw3Session.send({type:"merge",into:t,merge:e})}detachActivities(e,t){return this._gw3Session.send({type:"split",from:e}).then(()=>"")}onActivitiesAttached(e){}onActivitiesDetached(e){}onActivityAttachedDescriptorsRefreshed(e){}getAttachedDescriptors(){return Promise.resolve([])}getRandomRequestId(){return this._connection.peerId+":"+Math.floor(1e9*Math.random())}forwardAddedAndRemovedMessagesToEventHandler(e,t,n,i){const r=e=>t=>new Dt(t,new Ft(e?Ut.Added:Ut.Removed));return[e&&this.forwardMessageToEventHandler(e,e=>n(e,!0),r(!0),i),t&&this.forwardMessageToEventHandler(t,e=>n(e,!1),r(!1),i)].filter(e=>e)}forwardMessageToEventHandler(e,t,n,i){return this.subscribe(e,e=>{t(e).forEach(t=>i.forEach(i=>i(n(t,e))))})}sendCreateAndMapResultingMessagesToPromise(e,t,n,i,r,o,s,a,c){const d=this.getRandomRequestId();let h,l;const u=new Promise((e,t)=>{h=e,l=t});let p,g,f,m,y=null;const w=()=>{this.dropSubscription(p),c||this.dropSubscription(g),this.dropSubscription(f),this.dropSubscription(m)};p=t&&this.subscribe(t,e=>{n(e,d)&&(y=e,this.dropSubscription(p))});let v=!1;g=this.subscribe(i,e=>{r(e,d,y)&&(v?c&&c(a(e)):(v=!0,h(a(e))))}),f=o&&this.subscribe(o,e=>{s(e,d,y)&&l(e)}),m=o&&this.subscribe(Yt,e=>{e.request_id===d&&l(e)}),e.request_id=d;const b=this._gw3Session.send(e).then(()=>u);return b.then(w,w),b}peerFactoryIdAndOwnerIdToWindowType(e,t){const n=this._peerIdAndFactoryIdToPeerType[t+":"+e];return n?new Wt(n,void 0):null}subscribe(e,t){const n=this._connection.on(e,e=>t.bind(this)(e));return this._gw3Subscriptions.push(n),n}dropSubscription(e){e&&(this._connection.off(e),delete this._gw3Subscriptions[this._gw3Subscriptions.indexOf(e)])}invokeCallbacks(e,t,n){e.forEach(e=>{try{e(t)}catch(e){this._logger.error(`Error in ${n||t.context.type} callback: `+JSON.stringify(e))}})}handleActivityCreatedMessage(e){e.context_id?this._contextSubscriptions[e.activity_id]||this.subscribeToContext(e):this._logger.error("Activity created with unknown context_id: "+e.activity_id)}async subscribeToContext(e){const t=e.activity_id;this._contextSubscriptions[t]=await this._contexts.subscribe(t,(e,n,i)=>{const r=new Dt(new zt(t,void 0,void 0,e,void 0),new Gt(e,n,i));this.invokeCallbacks(this._activityChangeCallbacks,r,"context updated")})}handleActivityDestroyedMessage(e){const t=this._contextSubscriptions[e.activity_id];"function"==typeof t&&t(),delete this._contextSubscriptions[e.activity_id]}handlePeerFactoriesAdded(e){e.factories.forEach(t=>{this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t.id]=t.peer_type})}handlePeerFactoriesRemoved(e){e.factory_ids.forEach(t=>{delete this._peerIdAndFactoryIdToPeerType[e.owner_id+":"+t]})}forwardActivityTypeMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler("types-added","types-removed",(e,t)=>t?e.types.map(e=>pn.activityTypeGwMessageEntityToActivityType(e,void 0)):e.types.map(e=>new $t(e.name,void 0,void 0,void 0)),this._activityTypeStatusChangeCallbacks)}forwardActivityCreatedAndJoinedActivityToActivityWindowEventHandlers(){for(const e of[tn,on,cn])this.forwardMessageToEventHandler(e,e=>[e.owner||{...e,type:e.peer_type,name:e.peer_name,peer_id:e.owner_id}].concat(e.participants||[]).map(t=>new Zt(t.peer_id,t.name,t.type,e.activity_id,this.getAgmInstance(t.peer_id),void 0,this.generateWindowGetter(t.peer_id),void 0)),(e,t)=>new Dt(e,new Ft(Ut.ActivityWindowJoinedActivity)),this._activityWindowChangeCallbacks)}forwardActivityMessagesToStatusEventHandlers(){for(const e of[tn,on])this.forwardMessageToEventHandler(e,e=>[pn.activityGwMessageToActivity(e,new Xt("started","",new Date))],(e,t)=>pn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks);this.forwardMessageToEventHandler(nn,e=>[pn.activityGwMessageToActivity(e,new Xt("destroyed",e.reason,new Date))],(e,t)=>pn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks),this.forwardMessageToEventHandler(rn,e=>[pn.activityGwMessageToActivity(e,new Xt("created","",new Date))],(e,t)=>pn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks),this.forwardMessageToEventHandler(cn,e=>[pn.activityGwMessageToActivity(e,new Xt("created","",new Date))],(e,t)=>pn.activityToActivityStatusChangeEvent(e),this._activityChangeCallbacks)}forwardPeerFactoryMessagesToStatusEventHandlers(){this.forwardAddedAndRemovedMessagesToEventHandler(hn,ln,(e,t)=>t?e.factories.map(pn.peerFactoryGwMessageEntityToWindowType):e.factory_ids.map(t=>this.peerFactoryIdAndOwnerIdToWindowType(t,e.owner_id)).filter(e=>null!=e),this._windowTypeStatusChangeCallbacks)}forwardPeerFactoryMessagesToPeerFactoryRequests(){this.subscribe("peer-requested",e=>{const t=this._peerFactoriesRegisteredByUs[e.peer_factory];if(t)try{const n=e.configuration||{};n.gateway_token=n.gateway_token||e.gateway_token,n.peer_factory=n.peer_factory||e.peer_factory;const i=t({activityId:e.activity&&e.activity.id,activityType:e.activity&&e.activity.type,type:e.configuration&&e.configuration.type,gwToken:n.gateway_token,configuration:n});i&&i.then&&i.catch&&i.catch(t=>this._gw3Session.send({type:Yt,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))}))}catch(t){this._gw3Session.send({type:Yt,request_id:e.request_id,reason:t&&(t.message||JSON.stringify(t))})}else this._gw3Session.send({type:Yt,request_id:e.request_id,reason:`Unknown peer factory ${e.peer_factory}`})})}forwardActivityWindowMessagesToEventHandlers(){for(const e of[sn,on])this.subscribe(e,t=>{const n=e===sn?t.joined_id:t.peer_id,i=e===sn?t.joined_type:t.peer_type,r=e===sn?t.joined_name:t.peer_name,o=new Zt(n,r,i,t.activity_id,this.getAgmInstance(n),void 0,this.generateWindowGetter(n),void 0);this._contextSubscriptions[t.activity_id]?e===on&&this._activityJoinedPromiseResolve({}):this.subscribeToContext(t).then(()=>{e===on&&this._activityJoinedPromiseResolve({})}),this.invokeCallbacks(this._activityWindowChangeCallbacks,new Dt(o,new Ft(Ut.ActivityWindowJoinedActivity)),e)});this.subscribe(an,e=>{const t=new Zt(e.left_id,void 0,void 0,null,this.getAgmInstance(e.left_id),void 0,this.generateWindowGetter(e.left_id),void 0);this.invokeCallbacks(this._activityWindowChangeCallbacks,new Dt(t,new Ft(Ut.ActivityWindowLeftActivity)),an)}),this.forwardAddedAndRemovedMessagesToEventHandler(un,void 0,e=>[new Zt(e.created_id,void 0,void 0,void 0,void 0,void 0,this.generateWindowGetter(e.created_id),void 0)],this._activityWindowChangeCallbacks)}getAgmInstance(e){return this._config.agm.servers().find(t=>t.peerId===e||t.windowId===e)}generateWindowGetter(e){return()=>{const t=this.getAgmInstance(e);if(!t)return;const n=t.windowId;return this._config.windows.list().filter(e=>e.id===n)[0]}}isOverrideTypeDefinition(e){return void 0!==e&&!!e.owner}}class gn{constructor(e,t){this._myAttached=[],this._myDetached=[],this._myAttachedTo=[],this._myDetachedFrom=[],this._myActivityFrameColorChanged=[],this._myActivityJoinedCallbacks=[],this._myActivityRemovedCallbacks=[],this._myContextUpdateCallbacks=[],this._logger=Qt.Get(this),this._m=e,e.ready().then(e=>{e.subscribeActivityContextChanged(this._subscribeMyContextChanged.bind(this)),e.subscribeWindowEvents(this._subscribeMyWindowEvent.bind(this)),e.subscribeActivitiesAttached(this._subscribeActivitiesAttached.bind(this)),e.subscribeActivitiesDetached(this._subscribeActivitiesDetached.bind(this)),t&&t.onWindowFrameColorChanged(this._subscribeWindowFrameColorChanged.bind(this))})}get window(){if(Mt(this._w)){const e=this._m.announcedWindows;e.length>0&&(this._w=e[0])}return this._w}get activity(){const e=this.window;if(!Mt(e))return e.activity}createWindow(e){return this._m.createWindow(this.activity,e)}createStackedWindows(e,t){return this._m.createStackedWindows(this.activity,e,t)}get context(){const e=this.activity;return Pt(e)?{}:e.context}updateContext(e,t){const n=this.activity;return Pt(n)?new Promise((e,t)=>{t("Not in activity")}):n.updateContext(e,t)}setContext(e,t){const n=this.activity;return Pt(n)?new Promise((e,t)=>{t("Not in activity")}):n.setContext(e,t)}onActivityJoined(e){this._myActivityJoinedCallbacks.push(e);const t=this.window;Mt(t)||Mt(t.activity)||e(t.activity)}onActivityLeft(e){this._myActivityRemovedCallbacks.push(e)}onContextChanged(e){this._myContextUpdateCallbacks.push(e);const t=this.window;if(Mt(t))return;const n=t.activity;Mt(n)||e(n.context,n.context,[],n)}clone(e,t){const n=this.activity;return this._m.clone(n,e,t)}attach(e,t){let n;return n="string"==typeof e?e:e.id,this._m.attachActivities(n,this.activity.id,t)}onActivityAttached(e){this._myAttached.push(e)}onActivityDetached(e){this._myDetached.push(e)}onAttachedToActivity(e){this._myAttachedTo.push(e)}onDetachedFromActivity(e){this._myDetachedFrom.push(e)}get attached(){return this.activity?this.activity.attached:[]}setFrameColor(e,t){return this.activity?this.activity.setFrameColor(e,t):Promise.resolve(null)}getFrameColor(){return this.activity?this.activity.getFrameColor():""}onFrameColorChanged(e){this._myActivityFrameColorChanged.push(e)}_subscribeMyContextChanged(e,t,n,i){const r=this.window;if(Mt(r))return;const o=r.activity;Mt(o)||e.id===o.id&&this._notifyMyContextChanged(e,t,n,i)}_subscribeMyWindowEvent(e,t,n){Mt(this.window)||this.window.id===t.id&&(n===Ut.ActivityWindowJoinedActivity?(this._notifyMyWindowEvent(e,this._myActivityJoinedCallbacks),this._notifyMyContextChanged(e,e.context,null,null)):n===Ut.ActivityWindowLeftActivity&&this._notifyMyWindowEvent(e,this._myActivityRemovedCallbacks))}_notifyMyWindowEvent(e,t){t.forEach(t=>{try{t(e,event)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyMyContextChanged(e,t,n,i){n=n||{},i=i||[],this._myContextUpdateCallbacks.forEach(r=>{try{r(t,n,i,e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyAttached(e){this._myAttached.forEach(t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyDetached(e){this._myDetached.forEach(t=>{try{t(e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyAttachedTo(e){this._myAttachedTo.forEach(t=>{try{t(this.activity,e)}catch(e){this._logger.warn("error in user callback "+e)}})}_notifyDetachedFrom(e,t,n){this._myDetachedFrom.forEach(i=>{try{i(e,t,n)}catch(e){this._logger.warn("error in user callback "+e)}})}_subscribeActivitiesAttached(e,t){const n=this.window;if(Mt(n))return;const i=n.activity;Mt(i)||e.id===i.id&&(t.windowIds.indexOf(n.id)>=0?this._notifyAttachedTo(t):this._notifyAttached(t))}_subscribeActivitiesDetached(e,t,n){const i=this.window;if(Mt(i))return;const r=i.activity;Mt(r)||(t.id===r.id&&this._notifyDetached(n),e.id===r.id&&this._notifyDetachedFrom(e,t,n))}_subscribeWindowFrameColorChanged(e){const t=this.activity;t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._myActivityFrameColorChanged.forEach(t=>{t(e.frameColor)})}}class fn{constructor(e,t){if(this._logger=Qt.Get("ReadyMarker ["+e+"]"),this._logger.debug("Initializing ready marker for '"+e+"' with "+t+" signals to wait"),t<=0)throw new Error("Invalid signal number. Should be > 0");this._signals=t,this._callbacks=[],this._name=e}setCallback(e){this.isSet()?e(void 0):this.isError()?e(this._error):this._callbacks.push(e)}signal(e){if(this._logger.debug("Signaled - "+e+" - signals left "+(this._signals-1)),this._signals--,this._signals<0)throw new Error("Error in ready marker '"+this._name+" - signals are "+this._signals);this.isSet()&&this._callbacks.forEach(e=>{e(void 0)})}error(e){this._error=e,this._callbacks.forEach(t=>{t(e)})}isSet(){return!this.isError()&&0===this._signals}isError(){return!Pt(this._error)}getError(){return this._error}}class mn{constructor(e){this._items={},this._listeners=[],this._processNew=e}addOne(e){this.add([e])}add(e){e.forEach(e=>{this.process(new Dt(e,new Ft(Ut.Added)))})}process(e){const t=e.context,n=t.type,i=e.entity;if(n===Ut.StatusChange&&!t.oldStatus){const e=this._items[i.id];e&&(t.oldStatus=e.status)}n===Ut.StatusChange&&t.oldStatus&&t.newStatus&&t.oldStatus.state===t.newStatus.state&&(t.type=Ut.Updated),"undefined"==typeof htmlContainer&&(n===Ut.ActivityWindowJoinedActivity&&this._items[i.id]&&this._items[i.id].activity&&(t.type=Ut.Updated),n===Ut.ActivityWindowLeftActivity&&this._items[i.id]&&!this._items[i.id].activity&&(t.type=Ut.Updated));const r=this._updateInternalCollections(i,n,t);return this._notifyListeners(r,t),r}get(){const e=[];for(const t in this._items)if(this._items.hasOwnProperty(t)){const n=this._items[t];e.push(n)}return e}getByName(e){for(const t in this._items)if(t===e)return this._items[t]}getOrWait(e){return new Promise(t=>{const n=i=>{i.id===e&&(t(i),this.unsubscribe(n))};this.subscribe(n);const i=this.getByName(e);if(i)return this.unsubscribe(n),void t(i)})}subscribe(e){return this._listeners.push(e),Object.keys(this._items).forEach(t=>{const n=this._items[t];e(n,new Ft(Ut.Added.toString()))}),()=>{this.unsubscribe(e)}}unsubscribe(e){const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}_notifyListeners(e,t){this._listeners.forEach(n=>{try{n(e,t)}catch(e){return}})}_updateInternalCollections(e,t,n){const i=e,r=t===Ut.StatusChange&&i.status&&i.status.state===Ht.Destroyed||t===Ut.StatusChange&&n&&n.newStatus&&n.newStatus.state===Ht.Destroyed,o=t===Ut.Closed;if(t===Ut.Removed&&void 0===i.isIndependent||o||r){const t=this._items[e.id];return delete this._items[e.id],this._processNew(e),t&&e._beforeDelete(t),e}{const t=e.id;this._items.hasOwnProperty(t)?this._items[e.id]._update(e):(this._processNew(e),this._items[e.id]=e)}return this._items[e.id]}}class yn{get usingHc(){return"HC"===this._bridge.bridgeType}get announcedWindows(){return this._announcedWindows}set announcedWindows(e){throw new Error("not allowed")}constructor(e,t,n){this._logger=Qt.Get("activityManager"),this._announcedWindows=[],this._attachedCallbacks=[],this._detachedCallbacks=[],this._frameColorChangesCallbacks=[],this._windowHandlers=[],this._bridge=e,this._activityTypes=new mn(e=>this._grabEntity(e)),this._windowTypes=new mn(e=>this._grabEntity(e)),this._activities=new mn(e=>this._grabEntity(e)),this._windows=new mn(e=>this._grabEntity(e)),this._dataReadyMarker=new fn("Activity Manager Data",4),this._descriptorsMarker=new fn("Attached Activities Descriptors",1),t?(this._readyMarker=new fn("Activity Manager Announce",1),this._dataReadyMarker.setCallback(e=>{e&&this._readyMarker.error(e),this._descriptorsMarker.setCallback(e=>{e&&this._readyMarker.error(e),this._logger.debug("Auto announcing window"),this.announceWindow().then(e=>{this._announcedWindows.push(e),this._readyMarker.signal("Successfully announced window with id '"+e.id+"'")}).catch(e=>{this._logger.debug("Will not announce window - "+e),this._readyMarker.signal()})}),this.refreshDescriptors()})):this._readyMarker=this._dataReadyMarker,this._bridge.onActivitiesAttached(e=>{this._handleActivitiesAttached(e)}),this._bridge.onActivitiesDetached(e=>{this._handleActivitiesDetached(e)}),this._bridge.onActivityAttachedDescriptorsRefreshed(e=>{this._handleActivityDescriptorsRefreshed(e)}),n&&n.onWindowFrameColorChanged(this._handleWindowFrameColorChanged.bind(this)),this._bridge.init(),this._subscribeForData(),this._bridge.initReady().then(e=>{this._getInitialData()}).catch(e=>{console.log(e)})}ready(e){const t=new Promise((e,t)=>{this._readyMarker.setCallback(n=>{n?t(this._readyMarker.getError()):e(this)})});return Vt(Promise.all([this._bridge.ready(),t]).then(()=>this),e)}getActivityTypes(){return this._activityTypes.get()}getActivityType(e){return this._activityTypes.getByName(e)}registerActivityType(e,t,n,i,r,o){return Vt(new Promise((o,s)=>{if(Mt(e))return void s("activityTypeName argument can not be undefined");if(!kt(e))return void s("activityTypeName should be string");if(!Mt(this.getActivityType(e)))return void s("Activity type '"+e+"' already exists");let a;if(Pt(t))return void s("Owner window type can not be undefined");a=kt(t)?{type:t,name:"",isIndependent:!1,arguments:{}}:t;const c=[];if(!Pt(n)&&Et(n))for(const e in n){const t=n[e];if(kt(t)){const e={type:t,name:"",isIndependent:!1,arguments:{},relativeTo:"",relativeDirection:"",windowStyleAttributes:{}};c.push(e)}else c.push(t)}this._bridge.registerActivityType(e,a,c,i,r).then(e=>{this._grabEntity(e),o(e)}).catch(e=>{s(e)})}),o)}unregisterActivityType(e,t){return Vt(new Promise((t,n)=>{const i=this.getActivityType(e);Pt(i)?n("Activity type '"+e+"' does not exists"):this._bridge.unregisterActivityType(e).then(()=>t(i),n)}),t)}initiate(e,t,n,i){const r=new Promise((n,r)=>{Pt(this.getActivityType(e))?r("Activity type '"+e+"' does not exists"):this._bridge.initiateActivity(e,t,i).then(e=>{this._activities.getOrWait(e).then(e=>{n(e)}).catch(e=>r(e))}).catch(e=>{r(e)})});return Vt(r,n)}subscribeActivityTypeEvents(e){this._activityTypes.subscribe((t,n)=>{e(t,n.type)})}getWindowTypes(){return this._windowTypes.get()}getWindowType(e){return this._windowTypes.getByName(e)}registerWindowFactory(e,t,n){const i=new Promise((n,i)=>{if(Mt(e))i("no windowType specified");else{if(xt(e))e=e.getName();else if(!kt(e))return void i("windowType should be string or object that has getName method");this._bridge.registerWindowFactory(e,t).then(e=>{n(e)}).catch(e=>{i(e)})}});return Vt(i,n)}unregisterWindowFactory(e,t){const n=new Promise((t,n)=>{Mt(e)?n("no windowType specified"):kt(e)?this._bridge.unregisterWindowFactory(e).then(e=>{t(e)}).catch(e=>{n(e)}):n("windowType should be a string")});return Vt(n,t)}getActivities(e){let t=this._activities.get();if(t=t.filter(e=>e._ownerId),!e)return t;let n=e;if(kt(e))n=[e];else if(e instanceof $t)n=[e.name];else if(!(e instanceof Array))throw new Error("Invalid input argument 'activityType' = "+e);return t.filter(e=>{const t=e.type;return function(e,t){for(let n=0;n<e.length;n++)if(t(e[n],n))return!0;return!1}(n,e=>t.id===e.id)})}getActivityById(e){return this._activities.getByName(e)}announceWindow(e,t){const n=new Promise((n,i)=>{const r=this._bridge.getAnnouncementInfo();if(Pt(e)&&(e=r.activityWindowId),Pt(t)&&(t=r.activityWindowType),Mt(t))throw new Error("Can not announce - unknown windowType");const o=r&&r.activityId;if(Mt(e))this._logger.debug("Registering window with type:'"+t+"', name:'"+r.activityWindowName+"', ind.:'"+r.activityWindowIndependent+"'"),this._bridge.registerWindow(t,r.activityWindowName,r.activityWindowIndependent).then(this._windows.getOrWait.bind(this._windows)).then(e=>o?this._activities.getOrWait(o).then(t=>e):e).then(e=>{n(e)}).catch(e=>{this._logger.error(e)});else{this._logger.debug("Announcing window with id '"+e+"' and type '"+t+"'");const r=this._windows.getByName(e);if(!Mt(r))return this._logger.debug("Window with id '"+e+"' already announced - reusing the window"),void n(r);const o=(t,r,s)=>{if(e===r.id&&s===Ut.ActivityWindowJoinedActivity){Pt(r.activity)&&i("UNDEFINED ACTIVITY"),this._logger.trace("Got joined event for id '"+e+"'"),n(r),this.unsubscribeWindowEvents(o)}};this.subscribeWindowEvents(o),this._logger.trace("Waiting for joined event for id '"+e+"'"),this._bridge.announceWindow(t,e)}});return n}subscribeWindowTypeEvents(e){this._windowTypes.subscribe((t,n)=>{e(t,n.type)})}subscribeActivityEvents(e){return this._activities.subscribe((t,n)=>{if(n.type===Ut.StatusChange){const i=n;e(t,i.newStatus,i.oldStatus)}if(n.type===Ut.Removed||n.type===Ut.StatusChange&&n.newStatus.getState()===Ht.Destroyed)for(const e of this._windows.get())e.activity&&e.activity.id===t.id&&this._windows.process(new Dt(e,new Ft(Ut.ActivityWindowLeftActivity)))})}subscribeWindowEvents(e){const t=(t,n)=>{let i=n.type;i===Ut.Added&&(i="opened"),e(t.activity,t,i)};return this._windowHandlers.push([e,t]),this._windows.subscribe(t)}unsubscribeWindowEvents(e){const t=this._windowHandlers.find(t=>t[0]===e);t&&(this._windowHandlers.splice(this._windowHandlers.indexOf(t),1),this._windows.unsubscribe(t[1]))}createWindow(e,t,n){const i=new Promise((n,i)=>{let r,o;if(Mt(t)&&i("windowType is undefined"),kt(t))r={type:t,name:"",isIndependent:!1,arguments:{}};else if(t instanceof Wt)r={type:t.type||t.id,name:t.name||t.type||t.id,isIndependent:!1};else{const e=["url"],n={};Object.keys(t).forEach(i=>{-1===e.indexOf(i)&&(n[i]=t[i])}),r=n}if(!Mt(r.relativeTo))if(o=r.relativeTo,"string"==typeof o){const e=this.getWindows({type:o});!Mt(e)&&e.length>0&&(r.relativeTo=e[0].id)}else if(Mt(o.type))Mt(o.windowId)||(r.relativeTo=o.windowId);else{const e=this.getWindows({type:o.type});!Mt(e)&&e.length>0&&(r.relativeTo=e[0].id)}this._bridge.createWindow(e&&e.id,r).then(t=>{this._logger.debug("Window created, waiting for window entity with id "+t);const i=(r,o)=>{r.id!==t||e&&!r.activity||(this._logger.debug("Got entity window with id "+t),n(r),this._windows.unsubscribe(i))};this._windows.subscribe(i)}).catch(e=>{i(e)})});return Vt(i,n)}createStackedWindows(e,t,n,i){return Vt(new Promise((i,r)=>{Mt(e)&&r("activity is undefined"),Mt(t)&&r("relativeWindowTypes is undefined"),Array.isArray(t)||r("relativeWindowTypes has to be an array"),Mt(n)&&(n=2e4);const o=[];t.forEach(e=>{let t,i;if(t=kt(e)?{type:e,name:"",isIndependent:!1,arguments:{}}:e,t.stackedWindow=!0,t.timeout=n,!Mt(t.relativeTo))if(i=t.relativeTo,Mt(i.type)){if(!Mt(i.windowId)){const e=this.getWindows({id:i.windowId});!Mt(e)&&e.length>0&&(t.relativeTo=e[0].type.name)}}else t.relativeTo=i.type;o.push(t)});const s=[];o.forEach(t=>s.push(this.createWindow(e,t))),Promise.all(s).then(i).catch(r)}),i)}addWindowToActivity(e,t,n){const i=this._bridge.joinActivity(e.id,t.id).then(()=>t);return Vt(i,n),i}leaveWindowFromActivity(e,t,n){const i=this._bridge.leaveActivity(e.id,t.id).then(()=>t);return Vt(i,n),i}setActivityContext(e,t,n){const i=new Promise((n,i)=>{Mt(e)&&i("activity can not be null"),this._bridge.updateActivityContext(e,t,!0).then(t=>{n(e)}).catch(e=>{i(e)})});return Vt(i,n)}updateActivityContext(e,t,n){const i=new Promise((n,i)=>{Mt(e)&&i("activity can not be null");const r=[];for(const e in t)t.hasOwnProperty(e)&&null===t[e]&&r.push(e);for(const e of r)delete t[e];this._bridge.updateActivityContext(e,t,!1,r).then(t=>{n(e)}).catch(e=>{i(e)})});return Vt(i,n)}subscribeActivityContextChanged(e){this._activities.subscribe((t,n)=>{if(n.type===Ut.ActivityContextChange){const i=n;e(t,i.context,i.updated,i.removed)}})}stopActivity(e,t){return Vt(this._bridge.stopActivity(e),t)}getWindows(e){if(Pt(e))return this._windows.get();if(!Pt(e.id))return[this._windows.getByName(e.id)];return this._windows.get().filter(t=>{if(!Pt(e.type)&&t.type.id!==e.type)return!1;if(!Pt(e.name)&&t.name!==e.name)return!1;if(!Pt(e.activityId)){if(Mt(t.activity))return!1;if(t.activity.id!==e.activityId)return!1}return!0})}getWindowBounds(e){return this._bridge.getWindowBounds(e)}setWindowBounds(e,t,n){const i=new Promise((n,i)=>{this._bridge.setWindowBounds(e,t).then(()=>n()).catch(e=>i(e))});return Vt(i,n)}closeWindow(e){return this._bridge.closeWindow(e)}activateWindow(e,t){return this._bridge.activateWindow(e,t)}setWindowVisibility(e,t){return this._bridge.setWindowVisibility(e,t)}clone(e,t,n){const i=new Promise((n,i)=>{e||i("activity can not be null"),this._bridge.cloneActivity(e.id,t).then(e=>{this._activities.getOrWait(e).then(e=>{n(e)}).catch(e=>i(e))}).catch(e=>i(e))});return Vt(i,n)}attachActivities(e,t,n,i){n=n||{};const r=new Promise((i,r)=>{if(!this._activities.getByName(e))return void r("can not find activity with id "+e);if(this._activities.getByName(t))return this._bridge.attachActivities(e,t,n).then(e=>{const t=e.to,n=e.descriptor,r=e.descriptors;this._activities.getOrWait(t).then(e=>{e._updateDescriptors(r);const t=e.attached.filter(e=>e.ownerId===n.ownerId)[0];i(t)})}).catch(e=>{r(e)});r("can not find activity with id "+t)});return Vt(r,i)}detachActivities(e,t,n){const i=new Promise((n,i)=>this._bridge.detachActivities(e,t).then(()=>{this._activities.getOrWait(undefined).then(e=>{e._updateDescriptors(undefined),this._activities.getOrWait(undefined).then(e=>{n(e)})}).catch(e=>i(e))}).catch(e=>{i(e)}));return Vt(i,n)}subscribeActivitiesAttached(e){this._attachedCallbacks.push(e)}subscribeActivitiesDetached(e){this._detachedCallbacks.push(e)}subscribeActivityFrameColorChanged(e){this._frameColorChangesCallbacks.push(e)}_grabEntity(e){e._manager=this}_getInitialData(){this._logger.debug("Request initial data..."),this._bridge.getActivityTypes().then(e=>{this._activityTypes.add(e),this._dataReadyMarker.signal("Got act types")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity types -"+e)}),this._bridge.getWindowTypes().then(e=>{this._windowTypes.add(e),this._dataReadyMarker.signal("Got window types")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting window types "+e)}),this._bridge.getActivities().then(e=>{this._activities.add(e),this._dataReadyMarker.signal("Got activities")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity instances -"+e)}),this._bridge.getActivityWindows().then(e=>{this._windows.add(e),this._dataReadyMarker.signal("Got windows")}).catch(e=>{this._logger.error(e),this._dataReadyMarker.error("Can not initialize ActivityManager - error getting activity windows -"+e)})}_subscribeForData(){this._logger.debug("Subscribe for data..."),this._bridge.onActivityTypeStatusChange(e=>{this._activityTypes.process(e)}),this._bridge.onWindowTypeStatusChange(e=>{this._windowTypes.process(e)}),this._bridge.onActivityWindowChange(e=>{this._windows.process(e)}),this._bridge.onActivityStatusChange(e=>{this._activities.process(e)})}_handleActivitiesAttached(e){const t=e.to,n=e.descriptor,i=e.descriptors;this._activities.getOrWait(t).then(e=>{e._updateDescriptors(i);const t=e.attached.filter(e=>e.ownerId===n.ownerId)[0];this._attachedCallbacks.forEach(n=>{try{n(e,t)}catch(e){return}})})}_handleActivitiesDetached(e){const t=e.oldActivityId,n=e.newActivityId,i=e.descriptors,r=e.descriptor;this._activities.getOrWait(t).then(e=>{e._updateDescriptors(i),this._activities.getOrWait(n).then(t=>{this._detachedCallbacks.forEach(n=>{try{n(t,e,r)}catch(e){return}})})})}_handleActivityDescriptorsRefreshed(e){const t=e.id,n=e.descriptors,i=this._activities.getByName(t);i&&i._updateDescriptors(n)}refreshDescriptors(){this._bridge.getAttachedDescriptors().then(e=>{e&&Object.keys(e).forEach(t=>{const n=t,i=e[t],r=this._activities.getByName(n);r&&r._updateDescriptors(i)}),this._descriptorsMarker.signal("Successfully got descriptors")}).catch(e=>{this._descriptorsMarker.error("failed to get descriptors - "+e)})}_handleWindowFrameColorChanged(e){if(!e.activityId)return;const t=this._activities.getByName(e.activityId);t&&t.owner&&t.owner.underlyingWindow.id===e.id&&this._frameColorChangesCallbacks.forEach(n=>{try{n(t,e.frameColor)}catch(e){return}})}}class wn{constructor(e,t){this._m=e,this._my=t,this.activityTypes={get:this._getActivityTypesWrapper.bind(this),register:this._m.registerActivityType.bind(this._m),unregister:this._m.unregisterActivityType.bind(this._m),subscribe:this._m.subscribeActivityTypeEvents.bind(this._m),unsubscribe:void 0,initiate:this._m.initiate.bind(this._m)},this.windowTypes={get:this._getWindowTypesWrapper.bind(this),registerFactory:this._m.registerWindowFactory.bind(this._m),unregisterFactory:this._m.unregisterWindowFactory.bind(this._m),subscribe:this._m.subscribeWindowTypeEvents.bind(this._m),unsubscribe:void 0},this.windows={get:this._m.getWindows.bind(this._m),subscribe:this._m.subscribeWindowEvents.bind(this._m),announce:this._m.announceWindow.bind(this._m),unsubscribe:void 0,create:this._m.createWindow.bind(this._m)},this.instances={get:this._m.getActivities.bind(this._m),subscribe:this._m.subscribeActivityEvents.bind(this._m),unsubscribe:void 0}}onAttached(e){this._m.subscribeActivitiesAttached(e)}onDetached(e){this._m.subscribeActivitiesDetached(e)}onActivityFrameColorChanged(e){this._m.subscribeActivityFrameColorChanged(e)}_getActivityTypesWrapper(e){return Pt(e)?this._m.getActivityTypes():this._m.getActivityType(e)}_getWindowTypesWrapper(e){return Pt(e)?this._m.getWindowTypes():this._m.getWindowType(e)}}class vn{constructor(e,t){this._mgr=e,this._my=t,this.all=new wn(e,t)}ready(e){const t=new Promise((e,t)=>{this._mgr.ready().then(()=>{e(this)}).catch(e=>{t(e)})});return Vt(t,e)}get my(){return this._my}get aware(){return void 0!==this._my.window}get inActivity(){return this.aware&&void 0!==this._my.activity}get agm(){if(this.aware)return this.inActivity?this._my.activity.agm:new Bt(null)}getAvailableFrameColors(){return[]}}class bn{static checkIsUsingGW3Implementation(e){return 3===e.protocolVersion}get api(){return this._api}set api(e){this._api=e}constructor(e){if(!e)throw new Error("config can not be null");let t;if(Pt(e.logLevel)||(Qt.Level=e.logLevel),Mt(e.logger)||(Qt.GlueLogger=e.logger),this._isUsingHCImplementation=2===e.gdMajorVersion,this._isUsingGW3Implementation=bn.checkIsUsingGW3Implementation(e.connection),this._isUsingHCImplementation)throw new Error("GD2 not supported");if(!this._isUsingGW3Implementation)throw new Error("Unable to instantiate activity bridge implementation");if(t=new pn(e),!t)throw new Error("A bridge to native activity is needed to create activity lib.");Bt.AGM=e.agm;const n=new yn(t,!e.disableAutoAnnounce,e.windows),i=new gn(n,e.windows);this._api=new vn(n,i),this._readyPromise=n.ready().then(e=>this)}get isUsingHCImplementation(){return this._isUsingHCImplementation}get isUsingGW3Implementation(){return this._isUsingGW3Implementation}ready(e){return Vt(this._readyPromise,e)}}const _n="T42.ACS.GetFunctionalEntitlement",In="T42.ACS.CanI",Cn="T42.ACS.OnEvent",An="T42.ACS.GetApplications";var Tn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Sn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function kn(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function i(n,i){var r=n instanceof Error?n:new Error(n);if(t)t(r);else{var o='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,r){var o=n[e];return o||(o=[],n[e]=o),o.push(t),r&&setTimeout(function(){r.forEach(function(r){var o;if(null===(o=n[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(r)?t.apply(void 0,r):t.apply(void 0,[r])}catch(t){i(t,e)}})},0),function(){var i=n[e];i&&(0===(i=i.reduce(function(e,n,i){return n===t&&e.length===i||e.push(n),e},[])).length?delete n[e]:n[e]=i)}},execute:function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var o=n[e];if(!o||0===o.length)return[];var s=[];return o.forEach(function(n){try{var r=n.apply(void 0,t);s.push(r)}catch(t){s.push(void 0),i(t,e)}}),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}kn.default=kn;var xn=Sn(kn);function En(e){return e?Object.keys(e).map(t=>e[t]):[]}function Pn(e){let t;try{t=JSON.parse(JSON.stringify(e||{}))}catch(e){t={}}return t}function Mn(e,t){if(t.throwErrors&&"function"!=typeof e)throw new Error("Please provide the callback as a function!")}const Rn=9e4,Nn=9e4,On=2147483647;class jn{static getGDMajorVersion(){if("undefined"==typeof window)return-1;if(!window.glueDesktop)return-1;if(!window.glueDesktop.version)return-1;const e=window.glueDesktop.version.split("."),t=Number(e[0]);return isNaN(t)?-1:t}static typedError(e){let t;return t=e instanceof Error?e:"string"==typeof e?new Error(e):"message"in e&&"string"==typeof e.message&&e.message.length>0?new Error(e.message):"returned"in e&&"object"==typeof e.returned&&"errorMsg"in e.returned&&"string"==typeof e.returned.errorMsg&&e.returned.errorMsg.length>0?new Error(e.returned.errorMsg):new Error("Unknown error"),t}static async callbackifyPromise(e,t,n){try{return(e=>("function"==typeof t&&t(e),Promise.resolve(e)))(await e())}catch(e){return(e=>{const t=jn.typedError(e);if("function"!=typeof n)return Promise.reject(t);n(t.message)})(e)}}static getMonitor(e,t){return t.map(t=>{const{left:n,top:i,workingAreaWidth:r,workingAreaHeight:o}=t;return{monitor:t,totalOverlap:this.calculateTotalOverlap({left:n,top:i,width:r,height:o},e)}}).sort((e,t)=>t.totalOverlap-e.totalOverlap)[0].monitor}static isRunningInIoCdContext(){return"undefined"!=typeof window&&(window.glue42gd||window.iodesktop)}static isNode(){if(void 0!==jn._isNode)return jn._isNode;if("undefined"!=typeof window)return jn._isNode=!1,!1;try{jn._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){jn._isNode=!1}return jn._isNode}static generateId(){return((e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})(10)}static isPromise(e){return Boolean(e&&"function"==typeof e.then)}static isAsyncFunction(e){return e&&"[object AsyncFunction]"==={}.toString.call(e)}static isNullOrUndefined(e){return null==e}static calculateTotalOverlap(e,t){const n=e.left,i=e.top,r=n+e.width,o=i+e.height,s=t.left,a=t.top,c=s+t.width,d=a+t.height;return Math.max(0,Math.min(r,c)-Math.max(n,s))*Math.max(0,Math.min(o,d)-Math.max(i,a))}}class $n{constructor(e,t,n,i,r){this._appManager=e,this._name=t,this._agm=n,this._logger=i,this._configuration=r,this._registry=xn(),e.onInstanceStarted(e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStarted",e)}),e.onInstanceStopped(e=>{e.application&&e.application.name!==this._name||this._registry.execute("instanceStopped",e)}),e.onAppRemoved(e=>{e.name===this._name&&this._registry.execute("appRemoved",e)}),e.onAppChanged(e=>{e.name===this._name&&this._registry.execute("appChanged",e)}),e.onAppAvailable(e=>{e.name===this._name&&(this._props.IsReady=!0,this._registry.execute("appAvailable",e))}),e.onAppUnavailable(e=>{e.name===this._name&&(this._props.IsReady=!1,this._registry.execute("appUnavailable",e))})}get name(){return this._name}get title(){return this._props.Title}get version(){return this._props.Version}get autoStart(){return this._props.AutoStart}get isShell(){return this._props.IsShell}get caption(){return this._props.Caption}get hidden(){return this._props.IsHidden}get container(){return this._props.ApplicationName}get activityType(){return this._props.ActivityType}get activityWindowType(){return this._props.ActivityWindowType}get windowSettings(){return this._props.Arguments?Pn(this._props.Arguments):{}}get allowMultiple(){return this._props.AllowMultiple}get available(){return this._props.IsReady||!0}get icon(){return this._props.Icon}get iconURL(){return this._props.IconUrl}get sortOrder(){return this._props.SortOrder}get userProperties(){return this._props.UserProperties?Pn(this._props.UserProperties):{}}get keywords(){return this._props.Keywords?this._props.Keywords:[]}get isActivity(){return void 0!==this._props.ActivityType&&""!==this._props.ActivityType}get configuration(){return{autoStart:this._props.AutoStart,caption:this._props.Caption,hidden:this._props.IsHidden,container:this._props.ApplicationName,activityType:this._props.ActivityType,allowMultiple:this._props.AllowMultiple}}get instances(){return this._appManager.instances().filter(e=>e.application.name===this._name)}get type(){return this._props.Type}get mode(){if(!this._props)return"unknown";if(this._props.Mode&&"string"==typeof this._props.Mode)return this._props.Mode.toLowerCase();if(this.isActivity)return"unknown";if(this._props.Arguments&&this._props.Arguments.mode&&"string"==typeof this._props.Arguments.mode)return this._props.Arguments.mode.toLowerCase();let e=this._props.WindowStyleAttributes;if(e){e=e.split(" ").join("");const t='mode:"',n=e.indexOf(t);if(-1!==n){const i=n+t.length,r=e.indexOf('"',i),o=e.substr(i,r-i);if(o&&"string"==typeof o)return o.toLowerCase()}}return"flat"}async getConfiguration(){return(await this._agm.invoke(An,{v2:{apps:[this._name]}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.applications[0]}updateFromProps(e){this._props||(this._props={Name:e.Name}),Object.keys(e).forEach(t=>{this._props[t]=e[t]})}start(e,t){return new Promise(async(n,i)=>{var r,o,s,a;if(Mt(e))e={};else if((null===(r=this._configuration())||void 0===r?void 0:r.throwErrors)&&"object"!=typeof e||Array.isArray(e))return i(new Error('Invalid "context" parameter - must be an object.'));if(Mt(t))t={};else if((null===(o=this._configuration())||void 0===o?void 0:o.throwErrors)&&"object"!=typeof t)return i(new Error('Invalid "options" parameter - must be an object.'));const c=this._name;let d=null===(a=null!==(s=t.awaitInterop)&&void 0!==s?s:t.waitForAGMReady)||void 0===a||a,h=9e4;"number"==typeof t.timeout&&(h=1e3*t.timeout),void 0!==t.relativeTo&&"string"!=typeof t.relativeTo&&(t.relativeTo=t.relativeTo.id||"");const l=e=>{let t,r;const o=setTimeout(()=>{s();const t=`timed out while waiting for instance id ${e} for app ${this.name}`;this._logger.error(t),i(new Error(t))},h),s=()=>{clearTimeout(o),"function"==typeof t&&(t(),t=void 0),"function"==typeof r&&(r(),r=void 0)},a=t=>{t.id===e&&(s(),this._logger.trace(`instance ${e} appeared, resolving start promise`),n(t))};r=this._appManager.onInstanceStopped(t=>{t.id===e&&(s(),i(new Error(`instance ${e} was stopped while waiting for Interop to be ready`)))});const c=this._appManager.instances().find(t=>t.id===e);d?t=c?c.onAgmReady(a):this._appManager.onInstanceAgmServerReady(a):c?a(c):t=this._appManager.onInstanceStarted(a)};try{this._logger.trace(`starting application with "${c}" with options: ${JSON.stringify(t)}`);const i=(await this._agm.invoke("T42.ACS.StartApplication",{Name:c,Context:e,Options:t},"best",{methodResponseTimeoutMs:h,waitTimeoutMs:Nn})).returned;if(void 0!==i.timeout&&void 0===t.timeout&&(h=1e3*i.timeout),void 0!==i.waitForInterop&&void 0===t.waitForAGMReady&&void 0===t.awaitInterop&&(d=i.waitForInterop),i&&i.Id)if("startOnly"===this._appManager.mode){const e=this._appManager.handleInstanceStarted({ActivityId:void 0,IsActivityOwner:void 0,Context:void 0,Title:void 0,AgmServers:void 0,Id:i.Id,Name:i.Name});n(e)}else l(i.Id);else n(void 0)}catch(e){const t=jn.typedError(e);i(t)}})}onInstanceStarted(e){return Mn(e,this._configuration()),this._registry.add("instanceStarted",e)}onInstanceStopped(e){return Mn(e,this._configuration()),this._registry.add("instanceStopped",e)}onAvailable(e){return Mn(e,this._configuration()),this._props.IsReady&&setTimeout(()=>{this._registry.execute("appAvailable",this)},0),this._registry.add("appAvailable",e)}onUnavailable(e){return Mn(e,this._configuration()),!1===this._props.IsReady&&setTimeout(()=>{this._registry.execute("appUnavailable",this)},0),this._registry.add("appUnavailable",e)}onChanged(e){Mn(e,this._configuration()),this._registry.add("appChanged",e)}onRemoved(e){Mn(e,this._configuration()),this._registry.add("appRemoved",e)}}class Wn{constructor(e,t,n,i,r,o,s,a,c){this._id=e,this._appName=t,this._appManager=n,this._agm=i,this._activities=r,this._windows=o,this._logger=s,this._configuration=c,this._registry=xn(),a||(this._unsubscribeInstanceStopped=this._appManager.onInstanceStopped(e=>{e.id===this._id&&this._registry.execute("stopped",e)}),this._unsubscribeInstanceAgmServerReady=this._appManager.onInstanceAgmServerReady(e=>{e.id===this._id&&this._registry.execute("agmReady",e)}))}get id(){return this._id}get application(){return this._appManager.application(this._appName)}get activity(){if(!this._activities)throw new Error("This method requires glue.activities library to be enabled.");return this._activities.all.instances.get().filter(e=>e.id===this._activityId)[0]}get isActivityOwner(){return this._isActivityOwner}get activityInstances(){return this._appManager.instances().filter(e=>"activity"!==e.application.type&&e.activityId&&e.activityId===this._activityId)}get activityOwnerInstance(){if(this._activityId)return this.activityInstances.filter(e=>null==e?void 0:e.isActivityOwner)[0]}get window(){if(!this._windows)throw new Error("This method requires glue.windows library to be enabled.");let e=this._windows.list().find(e=>e.id===this._id);return!e&&this._activities&&this.activity&&this.activityOwnerInstance&&(e=this.activityOwnerInstance.window),e}get context(){var e,t,n;return null!==(n=null!==(e=this._startUpContext)&&void 0!==e?e:null===(t=this.window)||void 0===t?void 0:t.context)&&void 0!==n?n:{}}get title(){return this._title}get isActivityInstance(){return this._isActivityInstance}get activityId(){return this._activityId}get inActivity(){return this._inActivity}get isSingleWindowApp(){return!this._inActivity}get agm(){return this._agmInstance}get interopInstance(){return this._agmInstance}onInteropReady(e){return Mn(e,this._configuration()),this._agmInstance&&setTimeout(()=>{this._registry.execute("agmReady",this)},0),this._registry.add("agmReady",e)}onAgmReady(e){return this.onInteropReady(e)}onStopped(e){return Mn(e,this._configuration()),this._registry.add("stopped",e)}getWindow(){return new Promise((e,t)=>{const n=this.window;if(n)return void e(n);const i=(n,i)=>{n&&t(n),i&&e(i),setTimeout(()=>{clearTimeout(r),o()},0)};this._logger.trace(`waiting for window with id ${this._id} to appear`);const r=setTimeout(()=>{this._logger.trace(`window with id ${this._id} did not appear in 90 sec`),i(new Error(`can not find a window with id ${this._id}`))},9e4),o=this._windows.onWindowAdded(e=>{e.id===this._id&&(this._logger.trace(`window with id ${this._id} appeared`),i(void 0,e))})})}updateFromProps(e){this._startUpContext=e.Context,this._title=e.Title,this._isActivityInstance=!1,e.ActivityId&&""!==e.ActivityId&&(this._activityId=e.ActivityId,this._isActivityInstance=!0),this._isActivityOwner=e.IsActivityOwner,!this._activityId&&this._startUpContext&&this._startUpContext.activityId&&(this._activityId=this._startUpContext.activityId),this._inActivity=Boolean(this._activityId),this.updateAgmInstanceFromProps(e)}updateAgmInstanceFromProps(e){if(!e.AgmServers)return;const t=e.AgmServers;t&&t.length>0&&!Mt(t[0])&&(this._agmInstance=t[0])}stop(){return new Promise((e,t)=>{let n=this._id;this.isActivityOwner&&(n=this.activityId);const i=this._appManager.onInstanceStopped(t=>{t.id===n&&(this._logger.trace(`instance with id ${n} stopped`),i(),e())});this._logger.trace(`stopping instance with id ${this._id}`),this._agm.invoke("T42.ACS.StopApplication",{Name:this._appName,Id:this._id},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(()=>{"startOnly"===this._appManager.mode&&(this._appManager.handleInstanceStopped({Name:this._appName,Id:this.id}),e())}).catch(e=>t(e))})}activate(){return this._agm.invoke("T42.ACS.ActivateApplication",{Name:this._appName,Id:this._id},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}done(){this._registry.clear(),this._unsubscribeInstanceAgmServerReady(),this._unsubscribeInstanceStopped()}getContext(){return Promise.resolve(this.context)}async startedBy(){return(await this._agm.invoke("T42.ACS.Execute",{command:"getStartedBy",Name:this._appName,Id:this._id},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}}class Dn{constructor(e,t,n,i,r,o,s){this.mode=e,this._agm=t,this._activities=n,this._windows=i,this._logger=r,this._gdMajorVersion=o,this._configuration=s,this._apps={},this._instances=[],this._registry=xn(),this.getConfigurations=async e=>{const t={v2:{apps:void 0}};Array.isArray(e)&&(t.v2={apps:e});return(await this._agm.invoke(An,t,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.applications},this.application=e=>{var t;if((null===(t=this._configuration())||void 0===t?void 0:t.throwErrors)&&"string"!=typeof e||Rt(e))throw new Error('"name" must be string');return this._apps[e]},this.applications=()=>Object.keys(this._apps).map(e=>this._apps[e]),this.instances=()=>this._instances.map(e=>e),this.getMyInstance=()=>{const e="undefined"!=typeof window&&window.glue42gd;if(!e){const e=this._agm.instance.instance;return this._instances.find(t=>t.id===e)}if(this._gdMajorVersion>=3){const t=e.appInstanceId;return this._instances.find(e=>e.id===t)}},this.getMyApplication=()=>{var e;if(this._agm.instance)return null!==(e=this.application(this._agm.instance.applicationName))&&void 0!==e?e:this.application(this._agm.instance.application)},this.handleSnapshotAppsAdded=e=>{const t=this.applications();t.length>0&&t.forEach(t=>{const n=t.name;e.find(e=>e.Name===t.name)||this.handleAppRemoved({Name:n})}),e.forEach(e=>{t.find(t=>t.name===e.Name)||this.handleAppAdded(e)})},this.handleSnapshotInstanceStarted=e=>{const t=this.instances();t.length>0&&t.forEach(t=>{const n=t.id;e.find(e=>e.Id===n)||this.handleInstanceStopped({Name:t.application.name,Id:n})}),e.forEach(e=>{t.find(t=>t.id===e.Id)||this.handleInstanceStarted(e)})},this.handleAppAdded=e=>{const t=this._getAppId(e);this._logger.trace(`adding app ${t}`),this._apps[t]=new $n(this,t,this._agm,this._logger,this._configuration);const n=this._updateAppFromProps(e);this._registry.execute("appAdded",n),this._registry.execute("appAvailable",n)},this.handleAppUpdated=e=>{const t=this._updateAppFromProps(e);this._registry.execute("appChanged",t)},this.handleAppRemoved=e=>{const t=this._getAppId(e);this._logger.trace(`removing app ${t}`);const n=this.application(t);this._instances=this._instances.filter(e=>e.application.name!==n.name),delete this._apps[t],this._registry.execute("appRemoved",n)},this.handleAppReady=e=>{const t=this._getAppId(e),n=this._getAppOrThrow(t);n.updateFromProps(e),n.available?this._registry.execute("appAvailable",n):this._registry.execute("appUnavailable",n)},this.handleInstanceStarted=e=>{this._logger.trace(`started app ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=new Wn(t,n,this,this._agm,this._activities,this._windows,this._logger,!1,this._configuration);return this._updateInstanceFromProps(i,e),this._instances.push(i),this._registry.execute("instanceStarted",i),i},this.handleInstanceStopped=e=>{this._logger.trace(`instance stopped ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=this._getInstanceOrThrow(t,n);this._instances=this._instances.filter(e=>!this._matchInstance(e,t,n)),this._registry.execute("instanceStopped",i),i.done()},this.handleInstanceAgmServerReady=e=>{this._logger.trace(`instance interop server ready ${e.Name} ${e.Id}`);const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=this._getInstanceOrThrow(t,n);i.updateAgmInstanceFromProps(e),this._registry.execute("instanceAgmServerReady",i)},this.handleInstanceStartFailed=e=>{const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=new Wn(t,n,this,this._agm,this._activities,this._windows,this._logger,!0,this._configuration);this._updateInstanceFromProps(i,e),this._registry.execute("instanceStartFailed",i)},this.handleInstanceUpdated=e=>{const t=this._getInstanceId(e),n=this._getInstanceAppName(e),i=this._getInstanceOrThrow(t,n);this._updateInstanceFromProps(i,e)},this.onInstanceStarted=e=>(Mn(e,this._configuration()),this._registry.add("instanceStarted",e,this._instances)),this.onInstanceStartFailed=e=>(Mn(e,this._configuration()),this._registry.add("instanceStartFailed",e)),this.onInstanceStopped=e=>(Mn(e,this._configuration()),this._registry.add("instanceStopped",e)),this.onInstanceUpdated=e=>(Mn(e,this._configuration()),this._registry.add("instanceChanged",e)),this.onInstanceAgmServerReady=e=>(Mn(e,this._configuration()),this._registry.add("instanceAgmServerReady",e)),this.onAppAdded=e=>(Mn(e,this._configuration()),this._registry.add("appAdded",e,Object.values(this._apps))),this.onAppRemoved=e=>(Mn(e,this._configuration()),this._registry.add("appRemoved",e)),this.onAppAvailable=e=>(Mn(e,this._configuration()),this._registry.add("appAvailable",e)),this.onAppUnavailable=e=>(Mn(e,this._configuration()),this._registry.add("appUnavailable",e)),this.onAppChanged=e=>(Mn(e,this._configuration()),this._registry.add("appChanged",e))}_getAppOrThrow(e){const t=this.application(e);if(!t)throw Error(`app with id ${e} not found`);return t}_getAppId(e){return e.Name}_matchInstance(e,t,n){return e.id===t&&e.application.name===n}_getInstanceByIdAndName(e,t){return this._instances.filter(n=>this._matchInstance(n,e,t))[0]}_getInstanceOrThrow(e,t){const n=this._getInstanceByIdAndName(e,t);if(!n)throw Error(`instance with id ${e} not found`);return n}_getInstanceId(e){return e.Id}_getInstanceAppName(e){return e.Name}_updateAppFromProps(e){const t=this._getAppId(e);this._logger.trace(`updating app with id: "${t}", ${JSON.stringify(e)}`);const n=this._getAppOrThrow(t);return n.updateFromProps(e),n}_updateInstanceFromProps(e,t){this._logger.trace("updating instance with "+this._getInstanceId(t)+" for app "+this._getInstanceAppName(t)),e.updateFromProps(t)}}function Fn(e,t,n){const i=e=>!!(e&&e.constructor&&e.call&&e.apply);return i(t)||i(n)?(i(t)?i(n)||(n=()=>{}):t=()=>{},e.then(t,n)):e}class Ln{constructor(e){this._agm=e,this._registry=xn(),this._isMethodRegistered=!1,this.handleBranchModified=e=>{this._registry.execute("branchChanged",e)},this.handleBranchesModified=e=>{this._registry.execute("branchesChanged",e)},this.getRegion=(e,t)=>Fn(this._agmInvoke("T42.ACS.GetConfigurationRegion",e=>e.returned.Region),e,t),this.getBranches=(e,t)=>Fn(this._agmInvoke("T42.ACS.GetBranches",e=>{const t=e.returned.Branches;return Object.keys(t).map(e=>t[e])}),e,t),this.getCurrentBranch=(e,t)=>Fn(this._agmInvoke("T42.ACS.GetCurrentBranch",e=>e.returned.Branch,void 0),e,t),this.setRegion=(e,t,n)=>Fn(this._agmInvoke("T42.ACS.SetConfigurationRegion",e=>e.returned.ResultMessage,{Region:e}),t,n),this.setCurrentBranch=(e,t,n)=>Fn(this._agmInvoke("T42.ACS.SetCurrentBranch",e=>e.returned.ResultMessage,{Branch:e}),t,n),this.currentUser=(e,t)=>Fn(this._agmInvoke("T42.ACS.GetUser"),e,t),this.getFunctionalEntitlement=(e,t,n)=>Fn(this._agmInvoke(_n,e=>e.returned.Entitlement,{Function:e}),t,n),this.getFunctionalEntitlementBranch=(e,t,n,i)=>Fn(this._agmInvoke(_n,e=>e.returned.Entitlement,{Function:e,Branch:t}),n,i),this.canI=(e,t,n)=>Fn(this._agmInvoke(In,e=>e.returned.Result,{Function:e}),t,n),this.canIBranch=(e,t,n,i)=>Fn(this._agmInvoke(In,e=>e.returned.Result,{Function:e,Branch:t}),n,i),this.onBranchesChanged=e=>this._registry.add("branchesChanged",e),this.onBranchChanged=e=>this._registry.add("branchChanged",e),this.exit=e=>this._agmInvoke("T42.ACS.Shutdown",null,e),this.onShuttingDown=e=>(this.registerMethod(),this._registry.add("onShuttingDown",e)),this.restart=e=>this._agmInvoke("T42.ACS.Restart",null,e),this._agmInvoke=(e,t,n)=>(n=n||{},new Promise((i,r)=>{this._agm.invoke(e,n,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>{t||(t=e=>e.returned),i(t(e))}).catch(e=>r(e))}))}registerMethod(){this._isMethodRegistered||(this._agm.register("T42.ACS.OnGDShutdown",async e=>{try{const t=await Promise.all(this._registry.execute("onShuttingDown",e));return{prevent:t.some(e=>e.prevent)}}catch(e){}}),this._isMethodRegistered=!0)}}const Gn="T42.ACS.InMemoryStoreCommand";class Un{constructor(e){this.interop=e}import(e,t){if(!e||!Array.isArray(e))return Promise.reject(new Error("invalid apps argument - should be an array of application definitions"));if(t&&"replace"!==t&&"merge"!==t)return Promise.reject(new Error("invalid mode argument - should be 'replace' or 'merge'"));const n={command:"import",args:{apps:e,mode:t=null!=t?t:"replace"}};return this.interop.invoke(Gn,n,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>e.returned)}export(){return this.interop.invoke(Gn,{command:"export"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>e.returned.apps)}remove(e){if(!e||"string"!=typeof e)return Promise.reject(new Error("invalid app name, should be a string value"));const t={command:"remove",args:{apps:[e]}};return this.interop.invoke(Gn,t,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>e.returned)}clear(){return this.interop.invoke(Gn,{command:"clear"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>e.returned)}createAppDef(e,t){return t||(t="https://google.com"),{name:e,type:"window",title:e,details:{url:t}}}}var Hn=e=>{if(!e)throw Error("config not set");if(!e.agm)throw Error("config.agm is missing");const t="startOnly",n="skipIcons",i=e.mode||t;if(i!==t&&i!==n&&"full"!==i)throw new Error(`Invalid mode for appManager lib - ${i} is not supported`);const r=e.activities,o=e.agm,s=e.logger,a=e.windows;s.warn("AppManager API is deprecated. Please use the new Apps API (io.apps) instead. This API will be removed in a future version.");let c={};const d=new Dn(i,o,r,a,s.subLogger("applications"),e.gdMajorVersion,()=>c),h=new Ln(o);let l;if(i===t)l=function(e,t){return new Promise((n,i)=>{e.invoke(An,{skipIcon:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>{var i;const r=e.returned,o=null!==(i=e.returned.configuration)&&void 0!==i?i:{};r||n(o);const s=r.applications;s||n(o),En(s).map(e=>t.handleAppAdded(e)),n(o)}).catch(e=>i(new Error(`Error getting application snapshot: ${e.message}`)))})}(o,d);else{const e=function(e,t,n,i){let r,o=!1;return{start:()=>{let s,a;const c=new Promise((e,t)=>{s=e,a=t});return e.subscribe(Cn,{arguments:{skipIcon:i},waitTimeoutMs:Nn,methodResponseTimeout:Nn}).then(i=>{r=i,r.onData(i=>{var r;const a=i.data,c=null!==(r=a.configuration)&&void 0!==r?r:{},d=En(a.OnApplicationAdded);i.data.isSnapshot?t.handleSnapshotAppsAdded(d):d.forEach(e=>t.handleAppAdded(e)),En(a.OnApplicationChanged).forEach(e=>t.handleAppUpdated(e)),En(a.OnApplicationRemoved).forEach(e=>t.handleAppRemoved(e)),En(a.OnApplicationReady).forEach(e=>t.handleAppReady(e));const h=En(a.OnApplicationStarted);if(i.data.isSnapshot?t.handleSnapshotInstanceStarted(h):h.forEach(e=>t.handleInstanceStarted(e)),En(a.OnApplicationStartFailed).forEach(e=>t.handleInstanceStartFailed(e)),En(a.OnApplicationStopped).forEach(e=>t.handleInstanceStopped(e)),En(a.OnApplicationUpdated).forEach(e=>t.handleInstanceUpdated(e)),En(a.OnApplicationAgmServerReady).forEach(e=>t.handleInstanceAgmServerReady(e)),En(a.OnBranchChanged).forEach(e=>n.handleBranchModified(e)),En(a.OnBranchesModified).forEach(e=>n.handleBranchesModified(e)),!o){o=!0;const n=e.instance,i=d.some(e=>e.Name===n.application),r=h.some(e=>e.Id===n.instance);if(!i)return void s(c);if(!r&&(jn.isNode()||jn.isRunningInIoCdContext())){const e=t.onInstanceStarted(t=>{t.id===n.instance&&(e(),s(c))});return}s(c)}}),r.onFailed(e=>a(e))}).catch(e=>{var t;return a(`Error subscribing for ${Cn} stream. Err: ${null!==(t=e.message)&&void 0!==t?t:JSON.stringify(e)}`)}),c},stop:()=>{r&&r.close()}}}(o,d,h,i===n);l=e.start()}return{ready:()=>l.then(e=>{c=e}),applications:d.applications,application:d.application,getConfigurations:d.getConfigurations,onAppAdded:d.onAppAdded,onAppRemoved:d.onAppRemoved,onAppChanged:d.onAppChanged,onAppAvailable:d.onAppAvailable,onAppUnavailable:d.onAppUnavailable,instances:d.instances,get myInstance(){return d.getMyInstance()},get myApplication(){return d.getMyApplication()},onInstanceStarted:d.onInstanceStarted,onInstanceStopped:d.onInstanceStopped,onInstanceUpdated:d.onInstanceUpdated,onInstanceStartFailed:d.onInstanceStartFailed,getRegion:h.getRegion,getBranches:h.getBranches,getCurrentBranch:h.getCurrentBranch,getFunctionalEntitlement:h.getFunctionalEntitlement,getFunctionalEntitlementBranch:h.getFunctionalEntitlementBranch,setCurrentBranch:h.setCurrentBranch,setRegion:h.setRegion,currentUser:h.currentUser,canI:h.canI,canIBranch:h.canIBranch,onBranchesChanged:h.onBranchesChanged,exit:h.exit,restart:h.restart,onShuttingDown:h.onShuttingDown,inMemory:new Un(o)}};const Bn="T42.JumpList.Action";var Jn=new class{constructor(){this._groupActionCallbacks=new Map,this._registered=!1}init(e,t,n){this._executor=e,this._agm=t,this._logger=n,this.registerCallbackMethod()}setEnabled(e,t){const n={enabled:t};return this._executor.updateJumpList(e,n)}createCategory(e,t,n){this.validateActions(t,n);const i={category:{title:t,operation:"create",actions:this.toUpdateActions(e,"create",t,n)}};return this._executor.updateJumpList(e,i)}removeCategory(e,t){const n={category:{title:t,operation:"remove",actions:[]}};return this.manageActionCallback(e,n.category.operation,t),this._executor.updateJumpList(e,n)}createActions(e,t,n){this.validateActions(t,n);const i={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"create",t,n)}};return this._executor.updateJumpList(e,i)}removeActions(e,t,n){const i={category:{title:t,operation:"update",actions:this.toUpdateActions(e,"remove",t,n)}};return this._executor.updateJumpList(e,i)}async getActions(e,t){const n=[],i=(await this.getJumpListSettings(e)).categories.find(e=>e.title===t);return i&&i.actions.forEach(e=>{const t=this.getActionCallback(e.callbackId);t&&(e.callback=t.callback),n.push({icon:e.icon,callback:e.callback,singleInstanceTitle:e.singleInstanceTitle,multiInstanceTitle:e.multiInstanceTitle})}),Promise.resolve(n)}getJumpListSettings(e){return this._executor.getJumpList(e)}toUpdateActions(e,t,n,i){return i.map(i=>{const r={icon:i.icon,callback:i.callback,callbackId:jn.generateId(),singleInstanceTitle:i.singleInstanceTitle,multiInstanceTitle:i.multiInstanceTitle,operation:t};return this.manageActionCallback(e,t,n,r),r})}manageActionCallback(e,t,n,i){var r;const o=`${n}-${e}`;if("create"===t){this._groupActionCallbacks.has(o)||this._groupActionCallbacks.set(o,[]);this._groupActionCallbacks.get(o).push({callbackId:i.callbackId,callback:i.callback})}else if("remove"===t)if(i){let e=null!==(r=this._groupActionCallbacks.get(o))&&void 0!==r?r:[];e=e.filter(e=>e.callbackId!==i.callbackId),0===e.length?this._groupActionCallbacks.delete(o):this._groupActionCallbacks.set(o,e)}else this._groupActionCallbacks.delete(o)}registerCallbackMethod(){if(!this._registered){this._registered=!0;try{this._agm.register(Bn,(e,t)=>{const n=this.getActionCallback(e.callbackId);if(n)try{n.callback()}catch(e){this._logger.error("Unable to execute user callback for jump list action!",e)}})}catch(e){return this._logger.error(`Unable to register method ${Bn} for invoking jump list action callbacks!`,e),Promise.reject(e)}}}getActionCallback(e){let t;return[...this._groupActionCallbacks.values()].forEach(n=>{const i=n.find(t=>t.callbackId===e);i&&(t=i)}),t}validateActions(e,t){if(!(t&&t.length>0))throw new Error(`Category '${e}' doesn't contain any actions!`);t.forEach(t=>{if(!t.singleInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined singleInstanceTitle!`);if(!t.multiInstanceTitle)throw new Error(`Category '${e}' contains an action with undefined multiInstanceTitle!`);if(!t.callback)throw new Error(`Category '${e}' contains an action with undefined callback function!`)})}};var qn=new class{constructor(){this.waitForTimeoutInMilliseconds=6e4,this._windows={},this._pendingWindows={},this._pendingWindowsStates={},this._registry=xn()}init(e){this._logger=e}get(e){return this._windows[e]||this._pendingWindows[e]}getIfReady(e){return this._windows[e]}get list(){return this._windows}add(e,t){void 0!==this._pendingWindows[e.API.id]?this._logger.error(`trying to add window with id ${e.API.id} from windowStore, which already exists`):(this._pendingWindows[e.API.id]=e,this._pendingWindowsStates[e.API.id]=t,this._registry.execute("on-added",e),this.shouldMarkReadyToShow(t)&&this.markReadyToShow(e.API.id))}remove(e){delete this._windows[e.API.id],delete this._pendingWindows[e.API.id],delete this._pendingWindowsStates[e.API.id],this._registry.execute("on-removed",e)}setUrlChangedState(e){const t=this._pendingWindowsStates[e];void 0!==t&&(t.urlChanged=!0,this.shouldMarkReadyToShow(t)&&this.markReadyToShow(e))}setCompositionChangedState(e){const t=e.API.id,n=this._pendingWindowsStates[t];void 0!==n&&(n.compositionChanged=!0,this.shouldMarkReadyToShow(n)&&this.markReadyToShow(t))}waitFor(e){return new Promise((t,n)=>{let i,r;const o=setTimeout(()=>{i(),r(),n(new Error(`Window with id "${e}" was not ready within ${this.waitForTimeoutInMilliseconds} milliseconds.`))},this.waitForTimeoutInMilliseconds),s=this._windows[e];if(s)clearTimeout(o),t(s);else{const s=()=>{clearTimeout(o),i(),r()};i=this.onReadyWindow(n=>{n.API.id===e&&(s(),t(n))}),r=this.onRemoved(t=>{t.API.id===e&&(s(),n(new Error(`Window with id "${e}" was closed before it became ready.`)))})}})}waitForName(e){return new Promise((t,n)=>{let i,r;const o=setTimeout(()=>{i(),r(),n(new Error(`Window with name "${e}" was not ready within ${this.waitForTimeoutInMilliseconds} milliseconds.`))},this.waitForTimeoutInMilliseconds),s=Object.keys(this._windows).find(t=>this._windows[t].API.name===e);if(s)clearTimeout(o),t(this._windows[s]);else{const s=()=>{clearTimeout(o),i(),r()};i=this.onReadyWindow(n=>{n.API.name===e&&(s(),t(n))}),r=this.onRemoved(t=>{t.API.name===e&&(s(),n(new Error(`Window with name "${e}" was closed before it became ready.`)))})}})}onReadyWindow(e){return this._registry.add("on-ready",e)}onAdded(e){return this._registry.add("on-added",e)}onRemoved(e){return this._registry.add("on-removed",e)}markReadyToShow(e){this._pendingWindows[e]&&(this._windows[e]=this._pendingWindows[e],delete this._pendingWindows[e],delete this._pendingWindowsStates[e]),this._registry.execute("on-ready",this._windows[e])}shouldMarkReadyToShow(e){return e&&e.urlChanged&&e.ready&&e.compositionChanged}};class Vn{constructor(e,t){this.windowId=e,this._categoryTitle=t.title}list(){return Jn.getActions(this.windowId,this._categoryTitle)}create(e){return Jn.createActions(this.windowId,this._categoryTitle,e)}remove(e){return Jn.removeActions(this.windowId,this._categoryTitle,e)}}class zn{constructor(e){this.windowId=e}list(){return this.getCategories()}create(e,t){return Jn.createCategory(this.windowId,e,t)}remove(e){return Jn.removeCategory(this.windowId,e)}async find(e){return(await this.getCategories()).find(t=>t.title===e)}async getCategories(){const e=[];return(await Jn.getJumpListSettings(this.windowId)).categories.forEach(t=>{e.push({title:t.title,actions:new Vn(this.windowId,t)})}),e}}class Kn{constructor(e){this.windowId=e,this._categories=new zn(e)}get categories(){return this._categories}async isEnabled(){return(await Jn.getJumpListSettings(this.windowId)).enabled}setEnabled(e){return Jn.setEnabled(this.windowId,e)}}class Qn{constructor(e){this.channel=e}get isJoinedToAnyChannel(){return!!this.channel}isOnChannel(e){return this.channel===e}leaveChannel(e){void 0!==e&&this.channel!==e||(this.channel=void 0)}joinChannel(e){this.channel=e}all(){return this.channel?[this.channel]:[]}toString(){return this.channel}equals(e){return e instanceof Qn&&this.channel===e.channel}}class Zn{constructor(e){this.ChannelDelimiter="+++",this.channels=e?"string"==typeof e?null==e?void 0:e.split(this.ChannelDelimiter).filter(Boolean):(null!=e?e:[]).filter(Boolean):[]}get isJoinedToAnyChannel(){return this.channels.length>0}isOnChannel(e){return this.channels.includes(e)}joinChannel(e){new Zn(e).all().forEach(e=>{this.channels.includes(e)||this.channels.push(e)})}leaveChannel(e){new Zn(null!=e?e:this.channels).all().forEach(e=>{this.channels=this.channels.filter(t=>t!==e)})}all(){return this.channels}toString(){if(0!==this.channels.length)return this.channels.join(this.ChannelDelimiter)}equals(e){return e instanceof Zn&&(this.channels.length===e.channels.length&&this.channels.every((t,n)=>t===e.channels[n]))}}var Xn=(e,t,n,i,r,o,s,a)=>{var c,d,h,l;const u=xn(),p=()=>{const e=s();if(!e)throw new Error("To use this method you need to enable channels API - set the channels property to true when initializing the Glue42 library");return e},g=()=>{var e;return null===(e=r())||void 0===e?void 0:e.appManager},f=e,m=t.name,y=t.mode;let w=t.bounds,v=t.url,b=t.title,_=null!==(c=t.context)&&void 0!==c?c:{},I=t.frameColor,C=t.focus,A=null!==(d=t.neighbours)&&void 0!==d?d:{},T=t.groupId,S=t.isGroupHeaderVisible,k=t.isTabHeaderVisible,x=t.isGroupHibernated,E=t.isGroupVisible,P=null!==(h=t.isTabSelected)&&void 0!==h&&h,M=t.settings;const R=t.applicationName;let N,O=t.isVisible,j=t.isSticky,$=t.isCollapsed,W=t.state,D=t.tabGroupId,F=t.tabIndex,L=t.frameId,G=t.isLocked,U=t.allowWorkspaceDrop,H=t.isPinned,B=null!==(l=t.frameButtons)&&void 0!==l?l:[],J=t.zoomFactor,q=t.placementSettings;const V=new Kn(e);function z(e,t,i){return jn.callbackifyPromise(()=>{if(Mt(e))throw new Error("The properties of `bounds` cannot be null or undefined.");return n.moveResize(ne,e)},t,i)}function K(e,t,i){return jn.callbackifyPromise(()=>n.setVisible(ne,e),t,i)}function Q(e){return Z("group-changed",e)}function Z(e,t,n){if(!Ot(t))throw new Error("callback must be a function");return u.add(e,t,n)}async function X(){var e;return null===(e=(await p().getWindowsWithChannels({windowIds:[f]}))[0])||void 0===e?void 0:e.channel}function Y(e){const t=A[e];if(void 0!==t)return t.reduce((e,t)=>{const n=qn.get(t);return n&&e.push(n.API),e},[])}function ee(){var t;if(R)return R;if(_._APPLICATION_NAME)return _._APPLICATION_NAME;if(_&&_._t42&&_._t42.application)return _._t42.application;const n=te();if(n&&n.applicationName)return n.applicationName;const i=g();if(i){const n=i.instances().find(t=>e===t.id);if(n)return null===(t=n.application)||void 0===t?void 0:t.name}}function te(){if("undefined"!=typeof window&&window.glue42gd&&window.glue42gd.getWindowInfo){const t=window.glue42gd.getWindowInfo(e);return t||void 0}}const ne={get id(){return f},get name(){return m},get application(){const e=g();if(!e&&r().apps)throw new Error("The AppManager API is not available. Please use the 'getApplication' method instead.");const t=ee();if(t&&e)return e.application(t)},get appName(){return R||ee()},get hostInstance(){return n.hostInstance},get interopInstance(){const e=a.servers().find(e=>e.windowId===this.id);if(e)return e;{const e=ee();if(e)return{application:e}}},get agmInstance(){return ne.interopInstance},get url(){return v},get title(){return b},get windowStyleAttributes(){return M},get settings(){return M},get tabGroupId(){return"tab"===y.toLowerCase()?D:void 0},get tabIndex(){return"tab"===y.toLowerCase()?F:void 0},get frameId(){return L},get frameButtons(){return B.sort((e,t)=>e.order-t.order)},get mode(){return y},get state(){return W},get isCollapsed(){return $},get isVisible(){return O},get isLocked(){return G},get context(){return console.warn("The 'context' property is deprecated and will be removed in a future release. Please use 'getContext' method instead."),_},get bounds(){return w},get minHeight(){return M.minHeight},get maxHeight(){return M.maxHeight},get minWidth(){return M.minWidth},get maxWidth(){return M.maxWidth},get isFocused(){return C},get frameColor(){return I},get opened(){return void 0!==ne.id},get group(){return N},get groupId(){return T},get isSticky(){return j},get topNeighbours(){return Y("top")},get leftNeighbours(){return Y("left")},get rightNeighbours(){return Y("right")},get bottomNeighbours(){return Y("bottom")},get isGroupHeaderVisible(){return S},get activityId(){if(_._t42)return _._t42.activityId;const e=te();return e?e.activityId:void 0},get activityWindowId(){if(_._t42)return _._t42.activityWindowId;const e=te();return e?e.activityWindowId:void 0},get windowType(){return t.windowType||"electron"},get zoomFactor(){return J},get screen(){if("undefined"!=typeof window&&window.glue42gd)return jn.getMonitor(ne.bounds,window.glue42gd.monitors)},get placementSettings(){return Object.assign({},q)},get jumpList(){return V},get allowWorkspaceDrop(){return U},get isPinned(){return H},maximize:function(e,t){return jn.callbackifyPromise(()=>"maximized"===W?Promise.resolve(ne):n.maximize(ne),e,t)},restore:function(e,t){return jn.callbackifyPromise(()=>"normal"===W?Promise.resolve(ne):n.restore(ne),e,t)},minimize:function(e,t){return jn.callbackifyPromise(()=>"minimized"===W?Promise.resolve(ne):n.minimize(ne),e,t)},maximizeRestore:function(e,t){return jn.callbackifyPromise(()=>n.maximizeRestore(ne),e,t)},collapse:function(e,t){return jn.callbackifyPromise(()=>$?Promise.resolve(ne):n.collapse(ne),e,t)},expand:function(e,t){return jn.callbackifyPromise(()=>$?n.expand(ne):Promise.resolve(ne),e,t)},toggleCollapse:function(e,t){return jn.callbackifyPromise(()=>n.toggleCollapse(ne),e,t)},focus:function(e,t){return jn.callbackifyPromise(()=>C?Promise.resolve(ne):n.focus(ne),e,t)},activate:function(e,t){return jn.callbackifyPromise(()=>C?Promise.resolve(ne):n.activate(ne),e,t)},moveResize:z,setTitle:function(e,t,i){return jn.callbackifyPromise(()=>{if(Mt(e))throw new Error("`newTitle` must not be null or undefined.");return e===b?Promise.resolve(ne):n.setTitle(ne,e)},t,i)},setStyle:function(e,t,i){return jn.callbackifyPromise(()=>{if(!e||0===Object.keys(e).length||Object.keys(e).every(e=>!e))throw new Error("Invalid style arguments: "+JSON.stringify(e));if(e&&void 0!==e.focus){if("boolean"!=typeof e.focus)throw new Error("Focus must be a boolean value. Currently, only `focus: true` is supported.");!1===e.focus&&console.warn("`focus: false` is not supported!")}if(e&&void 0!==e.hidden&&"boolean"!=typeof e.hidden)throw new Error("The `hidden` property must hold a boolean value.");for(const t of["minHeight","maxHeight","minWidth","maxWidth"]){const n=e,i=n[t];if(t in e){if(Mt(i)){delete n[t];continue}if(!St(n[t]))throw new Error(`"${t}" must be a number`)}}return n.setStyle(ne,e)},t,i)},setOnTop:function(e,t,i){return jn.callbackifyPromise(()=>{if("string"==typeof e){if("always"!==e)throw new Error("`onTop` must hold a `always` value.")}else if("boolean"!=typeof e)throw new Error("`onTop` must hold a boolean or `always` value.");return n.setOnTop(ne,e)},t,i)},resetButtons:function(e,t,i){return jn.callbackifyPromise(()=>n.resetButtons(ne,e),t,i)},getButtons:function(){return n.getButtons(ne)},setSizeConstraints:function(e,t,i){return jn.callbackifyPromise(()=>{if(!e||Object.keys(e).every(e=>void 0===e))throw new Error("The properties of `constraints` cannot be null or undefined.");return n.setSizeConstraints(ne,e)},t,i)},getSizeConstraints:function(){return n.getSizeConstraints(ne)},navigate:function(e,t,i){if("function"==typeof t)return jn.callbackifyPromise(()=>{if(Rt(e))throw new Error("The new URL must be a non-empty string.");return n.navigate(ne,e)},t,i);if(Rt(e))throw new Error("The new URL must be a non-empty string.");if((null==t?void 0:t.timeout)&&"number"!=typeof t.timeout)throw new Error("Timeout argument must be a valid number");return n.navigate(ne,e,t)},addFrameButton:function(e,t,i){return jn.callbackifyPromise(()=>{if(void 0===e||0===Object.keys(e).length)throw new Error("Button info is not available.");if(Rt(e.buttonId))throw new Error("`buttonId` must not be null or undefined.");if(Rt(e.imageBase64))throw new Error("`imageBase64` must not be null or undefined.");return n.addFrameButton(ne,e)},t,i)},removeFrameButton:function(e,t,i){return jn.callbackifyPromise(()=>{if(Rt(e))throw new Error("`buttonId` must not be null or undefined.");return n.removeFrameButton(ne,e)},t,i)},setVisible:K,show:()=>K(!0),hide:()=>K(!1),center:async function(e){return e&&function(e){if("object"!=typeof e)throw Error("display argument must be a valid display object");if(!e.workArea||!e.scaleFactor)throw Error("display argument is not a valid display object")}(e),n.center(ne,e)},close:function(t,i){return void 0===t||"function"==typeof t?jn.callbackifyPromise(()=>{if(!e)throw new Error("The window is already closed.");return n.close(ne)},t,i):n.close(ne,t)},snap:function(e,t,i,r){return jn.callbackifyPromise(()=>{if(Mt(e))throw new Error(`A target window is not specified - ${"string"==typeof e?e:JSON.stringify(e)}`);if("string"==typeof e){const t=qn.get(e);if(!t)throw new Error(`Invalid "target" parameter or no such window. Invoked with: ${e}`);e=t.API}return"string"==typeof t&&(t={direction:t,autoAlign:!0}),n.snap(ne,e,t)},i,r)},dragMove:function(e){return n.dragMove(ne,e)},showLoader:function(e){return n.showLoader(ne,e)},hideLoader:function(){return n.hideLoader(ne)},updateContext:function(e,t,i){return jn.callbackifyPromise(()=>{if(!xt(e))throw new Error('"context" must not be null or undefined.');return n.updateContext(ne,e,!1)},t,i)},lock:function(e,t){return jn.callbackifyPromise(()=>n.lock(ne),e,t)},unlock:function(e,t){return jn.callbackifyPromise(()=>n.unlock(ne),e,t)},getIcon:function(e,t){return jn.callbackifyPromise(()=>n.getIcon(ne),e,t)},setIcon:function(e,t,i){return jn.callbackifyPromise(()=>{if(Rt(e))throw new Error('"base64Image" must be a non-empty string.');return n.setIcon(ne,e)},t,i)},setFrameColor:function(e,t,i){return jn.callbackifyPromise(()=>{if(Rt(e))throw new Error('"frameColor" must be a non-empty string');return n.setFrameColor(ne,e)},t,i)},setTabTooltip:async function(e){if(Rt(e))throw new Error(`"${e}" must not be null or undefined`);return n.setTabTooltip(ne,e)},getTabTooltip:async function(){return n.getTabTooltip(ne)},attachTab:function(e,t,i,r){return jn.callbackifyPromise(()=>{var i;const r='Invalid "tab" parameter - must be an object with an "id" property or a string. Invoked for source window with ID:';if(Mt(e)){const t=`${r} ${"string"==typeof e?e:JSON.stringify(e)}`;throw new Error(t)}let o;if("string"==typeof e){if(o=null===(i=qn.get(e))||void 0===i?void 0:i.API,Mt(o)){const e=`${r} ${"string"==typeof o?o:JSON.stringify(o)}`;throw new Error(e)}}else{if(Mt(e.id))throw new Error(r);o=e}const s={};return Mt(t)||("number"==typeof t?s.index=t:(s.selected=t.selected,s.index=t.index)),n.attachTab(ne,o,s)},i,r)},detachTab:function(e={},t,i){return jn.callbackifyPromise(()=>{const t={};return void 0!==e.relativeTo?("string"==typeof e.relativeTo?t.relativeTo=e.relativeTo:Mt(e.relativeTo.id)||(t.relativeTo=e.relativeTo.id),Mt(e.relativeDirection)||(t.relativeDirection=e.relativeDirection),Mt(e.width)||(t.width=e.width),Mt(e.height)||(t.height=e.height)):Mt(e.bounds)||(t.bounds=e.bounds),Mt(e.hideTabHeader)||(t.hideTabHeader=e.hideTabHeader),n.detachTab(ne,t)},t,i)},setTabHeaderVisible:function(e,t,i){return jn.callbackifyPromise(()=>{if("boolean"!=typeof e)throw new Error('"toBeTabHeaderVisible" must hold a boolean value.');return n.setTabHeaderVisible(ne,e)},t,i)},showPopup:function(e){return n.showPopup(ne,e)},createFlydown:function(e){return n.createFlydown(ne.id,e)},setModalState:function(e){return n.setModalState(ne.id,e||!1)},setZoomFactor:function(e,t,i){return jn.callbackifyPromise(()=>{if(isNaN(e))throw new Error("zoomFactor is not a number");return n.setZoomFactor(ne,e)},t,i)},zoomIn:function(e,t){return jn.callbackifyPromise(()=>n.zoomIn(ne),e,t)},zoomOut:function(e,t){return jn.callbackifyPromise(()=>n.zoomOut(ne),e,t)},showDevTools:function(){return n.showDevTools(ne)},capture:function(e){return n.capture(ne,e)},flash:function(e,t){const i={shouldFlash:!0,mode:"auto"};return"boolean"==typeof e&&(i.shouldFlash=e),void 0!==t&&(i.mode=t),n.flash(ne,i)},flashTab:function(e){const t={shouldFlash:!0};return"boolean"==typeof e&&(t.shouldFlash=e),n.flashTab(ne,t)},setSticky:function(e,t,i){return jn.callbackifyPromise(()=>{if("boolean"!=typeof e)throw new Error("`isSticky` must hold a boolean value.");return n.setSticky(ne,e)},t,i)},setAllowWorkspaceDrop:function(e){if("boolean"!=typeof e)throw new Error("`allowWorkspaceDrop` must hold a boolean value.");return n.setAllowWorkspaceDrop(ne,e)},pin:function(){return n.pin(ne)},unpin:function(){return n.unpin(ne)},print:function(e){return n.print(ne,e)},printToPDF:function(e){return n.printToPDF(ne,e)},place:function(e){return n.place(ne,e)},clearPlacement:function(e){return n.clearPlacement(ne,e)},ungroup:function(t){return new Promise((i,r)=>{const o=Q((t,n,r)=>{e===t.id&&(o(),i(ne))});n.ungroup(ne,t).catch(e=>{o(),r(e)})})},refresh:function(e){return n.refresh(ne,e)},goBack:function(){return n.goBack(ne)},goForward:function(){return n.goForward(ne)},download:function(e,t){return n.download(ne,e,t)},configure:function(e){return n.configureWindow(ne,e)},getConfiguration:function(){return n.getWindowConfiguration(ne)},getDockingPlacement:function(){return n.getDockingPlacement(ne)},setDockingConfig:function(e){return n.setDockingConfig(ne,e)},getDockingConfig:function(){return n.getDockingConfig(ne)},dock:function(e){return n.dock(ne,e)},undock:function(e){return n.undock(ne,e)},clone:async function(e){return n.clone(ne,e)},executeCode:async function(e){if(!e)throw new Error("Code argument is missing");if("string"!=typeof e)throw new Error("Code argument must be a valid string");return(await n.executeCode(ne,e)).result},getChannel:X,getChannels:async function(){return new Zn(await X()).all()},startDrag:function(e){return n.startDrag(ne,e)},showDialog:function(e){if((null==e?void 0:e.timerDuration)&&isNaN(null==e?void 0:e.timerDuration))throw new Error("timerDuration must be a number");if((null==e?void 0:e.showTimer)&&"boolean"!=typeof(null==e?void 0:e.showTimer))throw new Error("showTimer must be a boolean");return n.showDialog(ne,e)},onClose:function(t){if(!Ot(t))throw new Error("callback should be a function");return void 0===e&&t(ne),u.add("onClose",t)},onUrlChanged:function(e){return Z("onUrlChanged",e)},onTitleChanged:function(e){if(!Ot(e))throw new Error("callback should be a function");return e(ne.title,ne),Z("onTitleChanged",e)},onFrameButtonAdded:function(e){return Z("onFrameButtonAdded",e)},onFrameButtonRemoved:function(e){return Z("onFrameButtonRemoved",e)},onFrameButtonClicked:function(e){return Z("onFrameButtonClicked",e)},onCollapsed:function(e){if(!Ot(e))throw new Error("callback should be a function");return $&&e(ne),u.add("collapsed",e)},onExpanded:function(e){if(!Ot(e))throw new Error("callback should be a function");return $||e(ne),u.add("expanded",e)},onMinimized:function(e){return"minimized"===W?Z("minimized",e,[ne]):Z("minimized",e)},onMaximized:function(e){return"maximized"===W?Z("maximized",e,[ne]):Z("maximized",e)},onNormal:function(e){return"normal"===W?Z("normal",e,[ne]):Z("normal",e)},onAttached:function(e){return Z("attached",e)},onDetached:function(e){return Z("detached",e)},onVisibilityChanged:function(e){return Z("visibility-changed",e)},onContextUpdated:function(e){return Z("context-updated",e)},onLockingChanged:function(e){return Z("lock-changed",e)},onBoundsChanged:function(e){return Z("bounds-changed",e)},onFrameColorChanged:function(e){return Z("frame-color-changed",e)},onFocusChanged:function(e){return Z("focus-changed",e)},onStickyChanged:function(e){return Z("sticky-changed",e)},onGroupChanged:Q,onWindowAttached:function(e){return Z("window-attached",e)},onWindowDetached:function(e){return Z("window-detached",e)},onTabSelectionChanged:function(e){return Z("tab-selection-changed",e)},onTabHeaderVisibilityChanged:function(e){return Z("tab-header-visibility-changed",e)},onClosing:function(e){if(!Ot(e))throw new Error("callback must be a function");return n.onClosing((t,n,i)=>{const r=e(i);(null==r?void 0:r.then)?r.then(t).catch(n):t()},ne)},onRefreshing:function(e){if(!Ot(e))throw new Error("callback must be a function");return n.onRefreshing((t,n,i)=>{const r=e(i);(null==r?void 0:r.then)?r.then(t).catch(n):t()},ne)},onZoomFactorChanged:function(e){return Z("zoom-factor-changed",e)},onPlacementSettingsChanged:function(e){return Z("placementSettingsChanged",e)},onNeighboursChanged:function(e){return Z("neighbours-changed",e)},onDockingChanged:function(e){return Z("docking-changed",e)},onNavigating:function(e){if(!Ot(e))throw new Error("callback must be a function");return n.onNavigating((t,n,i,r)=>{const o=e(r);(null==o?void 0:o.then)?o.then(t).catch(n):t()},ne)},onChannelRestrictionsChanged:function(e){if(!Ot(e))throw new Error("callback must be a function");return Z("channel-restrictions-changed",e)},get tabs(){return function(){const e=qn.list;return"tab"!==y.toLowerCase()?[]:Object.keys(e).reduce((t,n)=>{const i=e[n];return i&&i.API.tabGroupId&&void 0!==i.API.tabGroupId&&void 0!==ne.tabGroupId&&i.API.tabGroupId===ne.tabGroupId&&t.push(i.API),t},[]).sort((e,t)=>{if(e.tabIndex!==t.tabIndex){if(-1===e.tabIndex)return Number.MAX_SAFE_INTEGER;if(-1===t.tabIndex)return Number.MIN_SAFE_INTEGER}return e.tabIndex-t.tabIndex})}()},get isTabHeaderVisible(){return k},get isTabSelected(){return P},getApplication(){var e;return null===(e=r())||void 0===e?void 0:e.getApp(R)},getURL:()=>Promise.resolve(v),getTitle:()=>Promise.resolve(b),getBounds:()=>Promise.resolve(w),async getContext(){try{return await n.getContext(ne)}catch(e){return _}},setContext(e){if(!xt(e))throw new Error('"context" must not be null or undefined, set to empty object if you want to clear it out.');return n.updateContext(ne,e,!0)},getDisplay:()=>o().getByWindowId(e),resizeTo:(e,t)=>z({width:e,height:t}),moveTo:(e,t)=>z({top:e,left:t}),async getParentWindow(){var e;const t=M.parentInstanceId;if(t)return null===(e=qn.list[t])||void 0===e?void 0:e.API},getChildWindows:async()=>Object.keys(qn.list).map(e=>qn.list[e].API).filter(t=>t.settings.parentInstanceId===e),joinChannel:t=>p().join(t,e),leaveChannel:()=>p().leave(e)};return{API:ne,Events:{handleUpdate:function(e){v=e.url,b=e.title,_=e.context||{},w=e.bounds,I=e.frameColor,C=e.focus,A=e.neighbours||{},T=e.groupId,S=e.isGroupHeaderVisible,k=e.isTabHeaderVisible,x=e.isGroupHibernated,E=e.isGroupVisible,P=e.isTabSelected,M=e.settings,O=e.isVisible,j=e.isSticky,$=e.isCollapsed,W=e.state,D=e.tabGroupId,L=e.frameId,G=e.isLocked,U=e.allowWorkspaceDrop,H=e.isPinned,J=e.zoomFactor,q=e.placementSettings},handleWindowClose:function(){void 0!==e&&(u.execute("onClose",ne),e=void 0)},handleWindowChangeState:async function(e){"collapsed"===e?$=!0:"expanded"===e?$=!1:W=e,await n.finished,u.execute(e,ne)},handleTitleChanged:function(e){b=e,n.finished.finally(()=>{u.execute("onTitleChanged",e,ne)})},handleVisibilityChanged:function(e){e!==O&&(O=e,u.execute("visibility-changed",ne))},handleUrlChanged:function(e){v=e,u.execute("onUrlChanged",e,ne)},handleWindowSettingsChanged:function(e){M=e,u.execute("settings-changed",ne)},handleContextUpdated:function(e){_=e,u.execute("context-updated",_,ne)},handleFrameIsLockedChanged:function(e){G=e,u.execute("lock-changed",ne)},handleBoundsChanged:function(e){w.top===e.top&&w.left===e.left&&w.width===e.width&&w.height===e.height||(w=e,u.execute("bounds-changed",ne))},handleFocusChanged:function(e){C=e,u.execute("focus-changed",ne)},handleFrameButtonAdded:function(e){const t=["buttonId","imageBase64","order","tooltip"].reduce((t,n)=>(t[n]=e[n],t),{});-1===B.map(e=>e.buttonId).indexOf(e.buttonId)&&B.push(t),u.execute("onFrameButtonAdded",t,ne)},handleFrameButtonRemoved:function(e){let t;B=B.reduce((n,i)=>(i.buttonId===e?t=i:n.push(i),n),[]),void 0!==t&&u.execute("onFrameButtonRemoved",t,ne)},handleFrameButtonClicked:function(e){const t=B.filter(t=>t.buttonId===e.buttonId);t.length>0&&u.execute("onFrameButtonClicked",t[0],ne)},handleFrameColorChanged:function(e){I=e,u.execute("frame-color-changed",ne)},handleFrameAttached:function(e,t,n){D=e,L=t,k=n,u.execute("frame-attached",ne)},handleFrameSelectionChanged:async function(t,i){let r;t===e?(P=!0,r=ne):(P=!1,r=qn.get(t)?qn.get(t).API:void 0);const o=qn.get(i)?qn.get(i).API:void 0;await n.finished,u.execute("tab-selection-changed",r,o,ne)},handleCompositionChanged:function(e){A=e.neighbors||{},F=e.index,u.execute("neighbours-changed",A,ne)},handleAllowWorkspaceDropChanged:function(e){U=e,u.execute("allow-workspace-drop-changed",ne)},handleIsPinnedChanged:function(e){H=e,u.execute("is-pinned-changed",ne)},handleGroupHeaderVisibilityChanged:function(e){S=e},handleTabHeaderVisibilityChanged:function(e){k!==e&&(k=e,u.execute("tab-header-visibility-changed",ne))},handleGroupChanged:function(e,t){N=e,T=null==e?void 0:e.id,Mt(e)||Mt(t)||u.execute("group-changed",ne,e,t)},handleAttached:async function(e,t,i,r,o){D=e,k=i,L=t,void 0!==r&&(G=r),await n.finished,o.forEach(e=>{e.Events.handleWindowAttached(ne)}),u.execute("attached",ne)},handleDetached:async function(e,t){D=void 0,P=!1,void 0!==e&&(G=e),await n.finished,t.forEach(e=>{e.Events.handleWindowDetached(ne)}),u.execute("detached",ne)},handleWindowAttached:function(e){u.execute("window-attached",e)},handleWindowDetached:function(e){u.execute("window-detached",e)},handleZoomFactorChanged:function(e){J=e,u.execute("zoom-factor-changed",ne)},handleIsStickyChanged:function(e){j=e,u.execute("sticky-changed",e,ne)},handlePlacementSettingsChanged:function(e){let t;const n=e;if(n.display){const e=o();if(e){const i=n.display-1;t=new Promise((t,n)=>{e.all().then(e=>{const n=e.find(e=>e.index===i);t(n)}).catch(n)})}else t=Promise.resolve(void 0)}else t=Promise.resolve(void 0);t.then(e=>{n.display=e,q=n,u.execute("placementSettingsChanged",ne)})},handleDockingChanged:function(e){u.execute("docking-changed",ne,{docked:e.docked,position:e.position,claimScreenArea:e.claimScreenArea})},handleChannelRestrictionsChanged:function(e){u.execute("channel-restrictions-changed",e)}},GroupCreationArgs:{get isGroupHibernated(){return x},get isGroupVisible(){return E}}}};function Yn(e,t){const n=qn.list;return Object.keys(n).reduce((i,r)=>{const o=n[r];return o.API.tabGroupId===t&&o.API.id!==e&&i.push(o),i},[])}function ei(e){return!(e&&!Object.keys(e).every(t=>void 0===e[t]))}var ti=new class{constructor(){this.GroupMethodName="T42.Group.Execute",this.WndMethodName="T42.Wnd.Execute",this._registry=xn(),this._finished=Promise.resolve(),this._configuration={windowAvailableOnURLChanged:!0},this.unsubCallbacks={}}get hostInstance(){return this.agmTarget}get finished(){return this._finished}get configuration(){return this._configuration}init(e,t,n){this.agm=e,this.logger=n,this.agmTarget=t,this._registry.add("event",e=>{if("Closed"===e.type){Object.keys(this.unsubCallbacks).forEach(t=>{t.startsWith(e.windowId)&&delete this.unsubCallbacks[t]})}})}setConfiguration(e){this._configuration={...this._configuration,...e}}handleEvent(e){this._registry.execute("event",e)}async open(e){let t;this._finished=new Promise(e=>{t=e});try{const t=await this.agm.invoke("T42.Wnd.Create",e,this.agmTarget,{waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn});if(void 0===t.returned)throw new Error("failed to execute T42.Wnd.Create - unknown reason");const n=t.returned.id,i=await qn.waitFor(n);return this.configuration&&!this.configuration.windowAvailableOnURLChanged||setTimeout(()=>{"electron"===i.API.windowType&&i.Events.handleUrlChanged(i.API.url)},0),i.API}finally{t()}}async close(e,t){const n=await this.execute("close",{windowId:e.id,options:t},"Closed");return t?n.closed:e}async navigate(e,t,n){let i=12e4;return"object"==typeof n&&"number"==typeof n.timeout&&(i=1e3*n.timeout,delete n.timeout),await this.execute("navigate",{windowId:e.id,options:{url:t,urlLoadOptions:n},invocationOptions:{methodResponseTimeoutMs:i}},"UrlChanged"),e}async setStyle(e,t){var n;const i=[],r=e=>i.push(e);if(Mt(t.focus)||e.isFocused||r(e.focus()),!Mt(t.hidden)){const n=!t.hidden;r(e.setVisible(n))}if(Mt(t.onTop)||r(e.setOnTop(t.onTop)),!Rt(t.tabTooltip)||!Rt(t.tabToolTip)){const i=null!==(n=t.tabTooltip)&&void 0!==n?n:t.tabToolTip;r(e.setTabTooltip(i))}Rt(t.tabTitle)||r(this.execute("setTabTitle",{windowId:e.id,options:{tabTitle:t.tabTitle}}));const o={minHeight:t.minHeight,minWidth:t.minWidth,maxHeight:t.maxHeight,maxWidth:t.maxWidth};!ei(o)&&r(e.setSizeConstraints(o));const s={allowClose:t.allowClose,allowCollapse:t.allowCollapse,allowLockUnlock:t.allowLockUnlock,allowMaximize:t.allowMaximize,allowMinimize:t.allowMinimize};return!ei(s)&&r(e.resetButtons(s)),await Promise.all(i),e}async setSizeConstraints(e,t){return await this.execute("setSizeConstraints",{windowId:e.id,options:t}),e}async getSizeConstraints(e){return await this.execute("getSizeConstraints",{windowId:e.id})}async setTabTooltip(e,t){return await this.execute("setTabTooltip",{windowId:e.id,options:{tabTooltip:t}}),e}async getTabTooltip(e){return(await this.execute("getTabTooltip",{windowId:e.id})).tabTooltip}async resetButtons(e,t){return await this.execute("resetButtons",{windowId:e.id,options:t}),e}async getButtons(e){return await this.execute("getButtons",{windowId:e.id})}async setOnTop(e,t){return await this.execute("setOnTop",{windowId:e.id,options:{onTop:t}}),e}async setTitle(e,t){const n={windowId:e.id,options:{title:t}};return await this.execute("setTitle",n,"TitleChanged"),e}async setSticky(e,t){const n={windowId:e.id,options:{isSticky:t}};return await this.execute("setSticky",n),e}async setAllowWorkspaceDrop(e,t){const n={windowId:e.id,options:{allowWorkspaceDrop:t}};return await this.execute("setAllowWorkspaceDrop",n),e}async pin(e){const t={windowId:e.id};return await this.execute("pinTab",t),e}async unpin(e){const t={windowId:e.id};return await this.execute("unpinTab",t),e}async moveResize(e,t){return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?new Promise(async(n,i)=>{const r=this.areBoundsEqual(t,e);let o=!1;const s=()=>{o||(o=!0,c&&(c(),c=void 0),n(e),a&&(clearTimeout(a),a=void 0))};let a,c;r||(c=e.onBoundsChanged(e=>{this.areBoundsEqual(t,e)&&s()}));try{await this.execute("moveResize",{windowId:e.id,options:{bounds:t}})}catch(e){return void i(e)}r?s():a=setTimeout(()=>{s()},1e3)}):(await this.execute("moveResize",{windowId:e.id,options:{bounds:t}}),e)}async addFrameButton(e,t){return await this.execute("addButton",{windowId:e.id,options:t},"ButtonAdded"),e}async removeFrameButton(e,t){return await this.execute("removeButton",{windowId:e.id,options:t},"ButtonRemoved"),e}async activate(e){return await this.execute("activate",{windowId:e.id}),e}async focus(e){return await this.execute("focus",{windowId:e.id}),e}async maximizeRestore(e){return await this.execute("maximizeRestore",{windowId:e.id},"StateChanged"),e}async maximize(e){return await this.execute("maximize",{windowId:e.id},"StateChanged"),e}async restore(e){return await this.execute("restore",{windowId:e.id},"StateChanged"),e}async minimize(e){return await this.execute("minimize",{windowId:e.id},"StateChanged"),e}async collapse(e){return await this.execute("collapse",{windowId:e.id},"StateChanged"),e}async expand(e){return await this.execute("expand",{windowId:e.id},"StateChanged"),e}async toggleCollapse(e){return await this.execute("toggleCollapse",{windowId:e.id},"StateChanged"),e}async snap(e,t,n){const i={targetWindowId:t.id};return i.snappingEdge=n.direction,i.autoAlign=n.autoAlign,await this.execute("snap",{windowId:e.id,options:i},"CompositionChanged",`CompositionChanged-${t.id}`),e}dragMove(e,t){return this.execute("dragMove",{windowId:e.id,options:t})}async attachTab(e,t,n){return await this.execute("attachTab",{windowId:e.id,options:{index:n,sourceWindowId:t.id,targetWindowId:e.id}},`WindowFrameAdded-${t.id}`,`WindowFrameRemoved-${t.id}`),e}async detachTab(e,t){const n=["WindowFrameRemoved","WindowFrameAdded"];return Mt(null==t?void 0:t.relativeTo)?n.push("BoundsChanged"):(n.push("CompositionChanged"),n.push(`CompositionChanged-${t.relativeTo}`)),await this.execute("detachTab",{windowId:e.id,options:t},...n),e}async setVisible(e,t=!0){let n;return n=t?"show":"hide",await this.execute(n,{windowId:e.id},"VisibilityChanged"),e}async center(e,t){return await this.execute("center",{windowId:e.id,options:t}),e}async showLoader(e,t){return await this.execute("showLoadingAnimation",{windowId:e.id,options:t}),e}async hideLoader(e){return await this.execute("hideLoadingAnimation",{windowId:e.id}),e}async updateContext(e,t,n){let i;try{const r=this.swapUndefinedToNull(t),o=new Promise((t,n)=>{i=e.onContextUpdated(()=>{t()})});return await Promise.all([this.execute("updateContext",{windowId:e.id,context:r,replace:n}),o]),e}finally{i&&i()}}async getContext(e){return(await this.execute("getContext",{windowId:e.id})).context}async lock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!0}},"FrameIsLockedChanged"),e}async unlock(e){return await this.execute("lockUnlock",{windowId:e.id,options:{lock:!1}},"FrameIsLockedChanged"),e}async getIcon(e){return(await this.execute("getIcon",{windowId:e.id,options:{}})).icon}async setIcon(e,t){return await this.execute("setIcon",{windowId:e.id,options:{dataURL:t}}),e}async setFrameColor(e,t){return await this.execute("setFrameColor",{windowId:e.id,options:{frameColor:t}},"FrameColorChanged"),e}async setTabHeaderVisible(e,t){return await this.execute("setTabHeaderVisible",{windowId:e.id,options:{toShow:t}},"TabHeaderVisibilityChanged"),e}async showGroupPopup(e,t){const n=this.validatePopupOptions(e,t);await this.executeGroup("showGroupPopup",{groupId:e,options:n})}async showPopup(e,t){const n=this.validatePopupOptions(e.id,t);return await this.execute("showPopupWindow",{windowId:e.id,options:n}),e}async createFlydown(e,t){if(!t)throw new Error("The options object is not valid!");const n={...t};n.horizontalOffset||(n.horizontalOffset=0),n.verticalOffset||(n.verticalOffset=0);const i=this.reformatFlydownOptions(e,n);return this.execute("setFlydownArea",{windowId:e,options:i}).then(()=>{const e=i.zones.map(e=>e.id);return i.zones.forEach(e=>{let n="function"==typeof e.flydownSize?e.flydownSize:()=>e.flydownSize;t.size instanceof Function&&e.flydownSize&&(n=async(n,i)=>{let r;return t.size instanceof Function&&(r=await t.size(n,i)),e.flydownSize instanceof Function&&e.flydownSize!==t.size?await e.flydownSize(n,i)||r:r||e.flydownSize}),this._registry.clearKey(`${i.targetId}_${e.id}`),this._registry.add(`${i.targetId}_${e.id}`,n)}),{destroy:()=>this.clearFlydownArea(i.targetId,e),options:n}})}async setModalState(e,t){return this.execute("setModalState",{windowId:e,options:{isModal:t}})}async autoArrange(e){return this.execute("autoArrange",{options:{displayId:e}})}async handleFlydownBoundsRequested(e,t){const n={zoneId:t.flydownId,flydownWindowBounds:t.flydownWindowBounds,flydownWindowId:t.flydownWindowId},i=await Promise.all(this._registry.execute(`${e}_${t.flydownId}`,n,()=>t.cancel=!0));if(1===i.length){const e={height:0,width:0,top:0,left:0},n="object"!=typeof i[0]||Array.isArray(i[0])?e:i[0];return{...t,flydownWindowBounds:n}}}async handleOnEventRequested(e,t){var n;const i=null!==(n=this.unsubCallbacks[e])&&void 0!==n?n:[];let r=!1;const o=[];return await Promise.all(i.map(e=>new Promise((n,i)=>{e(()=>{n()},()=>{i()},e=>{r=!0,o.push(e)},t)}))),{prevented:r,preventArgs:o}}async zoomIn(e){return await this.execute("zoomIn",{windowId:e.id}),e}async zoomOut(e){return await this.execute("zoomOut",{windowId:e.id}),e}async setZoomFactor(e,t){return await this.execute("setZoomFactor",{windowId:e.id,options:{zoomFactor:t}}),e}async showDevTools(e){return await this.execute("showDevTools",{windowId:e.id}),e}async capture(e,t){return(await this.execute("captureScreenshot",{windowId:e.id,options:{...t}})).data}async captureGroup(e,t){return(await this.execute("captureGroupScreenshot",{windowId:e[0],options:{groupWindowIds:e,...t}})).data}async flash(e,t){return await this.execute("flash",{windowId:e.id,options:{...t}}),e}async flashTab(e,t){return await this.execute("flashTab",{windowId:e.id,options:{...t}}),e}async configure(e,t){return this.execute("configure",{windowId:e,options:{...t}})}async print(e,t){return await this.execute("print",{windowId:e.id,options:{...t}}),e}async printToPDF(e,t){return(await this.execute("printToPDF",{windowId:e.id,options:{...t}})).filePath}async place(e,t){const n={...t};return t.display&&"current"!==t.display||(n.display=await e.getDisplay()),n.display&&"string"!=typeof n.display&&"number"!=typeof n.display&&(n.display=n.display.index+1),this.execute("place",{windowId:e.id,options:{...n}})}async clearPlacement(e,t){return this.execute("clearPlacement",{windowId:e.id,options:t})}async refresh(e,t){return await this.execute("refresh",{windowId:e.id,options:{ignoreCache:t}}),e}async download(e,t,n={}){"boolean"==typeof(null==n?void 0:n.silent)&&(n.enableDownloadBar=!n.silent);const i=await this.execute("downloadURL",{windowId:e.id,options:{url:t,options:n}});return{url:t,path:i.fullPath,size:i.fileSize}}async configureWindow(e,t){return await this.execute("configureWindow",{windowId:e.id,options:t}),e}async getWindowConfiguration(e){return await this.execute("getWindowConfiguration",{windowId:e.id})}async startDrag(e,t){return await this.execute("startDrag",{windowId:e.id,options:t}),e}showDialog(e,t){return new Promise((n,i)=>{const r=jn.generateId(),o=this._registry.add("event",t=>{if("DialogResult"===t.type&&t.windowId===e.id&&t.data.token===r){o();const e=t.data;"status"in e&&("failed"===e.status?i(new Error(e.message)):"successful"===e.status&&n(e.result))}});this.execute("showDialog",{windowId:e.id,options:Object.assign({},{...t},{token:r})})})}async execute(e,t,...n){return this.executeCore(this.WndMethodName,e,t,...n)}async executeGroup(e,t,...n){return this.executeCore(this.GroupMethodName,e,t,...n)}async ungroup(e,t){const n={windowId:e.id,options:t};return await this.execute("ungroup",n),e}async updateJumpList(e,t){const n={windowId:e,options:t};await this.execute("updateJumplist",n)}async getJumpList(e){const t={windowId:e};return await this.execute("getJumplist",t)}onClosing(e,t){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===t.windowType?n.addCloseHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnClosing")}onGroupClosing(e,t){return this.nonWindowHandlersCore(t.id,"OnClosing",!0,e)}onRefreshing(e,t){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===t.windowType?n.addRefreshHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnRefreshing")}onNavigating(e,t){const n="undefined"!=typeof window&&window.glue42gd;return n&&"electron"===t.windowType?n.addWillNavigateHandler(e,t.id):this.nonWindowHandlers(e,t.id,"OnNavigating")}async clone(e,t){const n={windowId:e.id,options:t},i=await this.execute("clone",n);return(await qn.waitFor(i.id)).API}async executeCode(e,t){const n={windowId:e.id,options:{code:t}};return this.execute("executeCode",n)}async goBack(e){await this.execute("goBack",{windowId:e.id})}async goForward(e){await this.execute("goForward",{windowId:e.id})}async getDockingPlacement(e){return this.execute("getDockingPlacement",{windowId:e.id})}setDockingConfig(e,t){return this.execute("setDockingConfig",{windowId:e.id,options:t})}getDockingConfig(e){return this.execute("getDockingConfig",{windowId:e.id})}dock(e,t){return this.execute("dock",{windowId:e.id,options:t})}undock(e,t){return this.execute("undock",{windowId:e.id,options:t})}clearCallbacks(e){Object.keys(this.unsubCallbacks).forEach(t=>{t.startsWith(e)&&delete this.unsubCallbacks[t]})}nonWindowHandlers(e,t,n){return this.nonWindowHandlersCore(t,n,!1,e)}nonWindowHandlersCore(e,t,n,i){const r=`${e}-${t}`,o=()=>{},s=()=>{var s;if(this.unsubCallbacks[r]){const e=this.unsubCallbacks[r];this.unsubCallbacks[r]=e.filter(e=>e!==i),0===this.unsubCallbacks[r].length&&delete this.unsubCallbacks[r]}if(0===(null!==(s=this.unsubCallbacks[r])&&void 0!==s?s:[]).length){const i={unsubscribe:!0};n?this.executeGroup(t,{groupId:e,options:i}).catch(o):this.execute(t,{windowId:e,options:i}).catch(o)}};return this.unsubCallbacks[r]?(this.unsubCallbacks[r].push(i),s):(this.unsubCallbacks[r]=[i],n?this.executeGroup(t,{groupId:e}).catch(o):this.execute(t,{windowId:e}).catch(o),s)}reformatFlydownOptions(e,t){const n=(e,n)=>{if(t[n]&&(void 0===e[n]||null===e[n])){const i=t[n];e[n]=i}},i=t.zones.map(e=>(n(e,"windowId"),n(e,"targetLocation"),!t.size||void 0!==e.flydownSize&&null!==e.flydownSize||(e.flydownSize=t.size),e.flydownBounds=e.flydownSize,e.flydownId=e.windowId,e.targetLocation||(e.targetLocation="bottom"),e));return{...t,zones:i,targetId:e,flydownBounds:t.size,flydownActiveArea:t.activeArea}}clearFlydownArea(e,t){return this.execute("clearFlydownWindowArea",{windowId:e,options:{}}).then(()=>{t.forEach(t=>{this._registry.clearKey(`${e}_${t}`)})})}executeWithoutToken(e,...t){const n=[],i=null==t?void 0:t.filter(e=>!Mt(e)).map(t=>new Promise(i=>{const[r,o=e.windowId]=t.split("-");n.push(this._registry.add("event",e=>{e.type===r&&e.windowId===o&&i()}))})),r=new Promise((t,n)=>{this.agm.invoke("T42.Wnd.Execute",e,this.agmTarget,{waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn}).then(e=>{e.returned&&e.returned.errorMsg?n(e):t(e.returned)}).catch(e=>n(e))});return Promise.all([r,...i]).then(e=>e[0]).finally(()=>{n.forEach(e=>e())})}async executeCore(e,t,n,...i){const{invocationOptions:r,...o}=n,s={...o,command:t};let a;this._finished=new Promise(e=>{a=e});try{return"undefined"!=typeof window&&window.glueDesktop.versionNum<31200?await this.executeWithoutToken(s,...i):await this.executeWithToken(e,s,r)}finally{a()}}async executeWithToken(e,t,n){let i;try{const r=jn.generateId(),o=new Promise(t=>{i=this._registry.add("event",n=>{n.token===r&&(this.logger.debug(`"${e}" token: ${r} received`),t())})}),s=new Promise((i,o)=>{t.token=r,n?n.methodResponseTimeoutMs?n.waitTimeoutMs||(n.waitTimeoutMs=Nn):n.methodResponseTimeoutMs=Rn:n={waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn},this.logger.debug(`executing "${e}" with options: ${JSON.stringify(t)} and token: ${r}`),this.agm.invoke(e,t,this.agmTarget,n).then(t=>{this.logger.debug(`"${e}" returned: ${JSON.stringify(t)}`),t.returned&&t.returned.errorMsg?o(new Error(t.returned.errorMsg)):i(t.returned)}).catch(t=>{const n=jn.typedError(t);this.logger.error(`"${e}" failed:`,n),o(n)})});return(await Promise.all([s,o]))[0]}finally{i&&i()}}areBoundsEqual(e,t){const n=t.bounds,i=t.settings;let r=e.height,o=e.width;e.height<i.minHeight&&(r=i.minHeight),e.height>i.maxHeight&&(r=i.maxHeight),e.width<i.minWidth&&(o=i.minWidth),e.width>i.maxWidth&&(o=i.maxWidth);const s=!r||n.height===r,a=!o||n.width===o,c=!e.left||n.left===e.left,d=!e.top||n.top===e.top;return s&&a&&c&&d}swapUndefinedToNull(e){try{const t={};for(const n of Object.keys(e)){let i=e[n];void 0===i&&(i=null),t[n]=i}return t}catch{return e}}validatePopupOptions(e,t){if(!t)throw new Error("The options object is not valid!");const n={...t};n.targetLocation||(n.targetLocation="bottom");return{...n,popupBounds:n.size,targetId:e,popupId:n.windowId}}};class ni{constructor(e,t,n,i,r,o,s){this._registry=xn(),this._agm=e,this._logger=t.subLogger("gd-env"),this._windowId=o,this._groupId=s,this._appsController=n,this._displayAPIGetter=i,this._channelsAPIGetter=r}init(){return new Promise((e,t)=>{this._agm.register("T42.Wnd.OnEventWithResponse",(e,t)=>this.respondToEvent(e)),new Promise((n,i)=>{this._agm.subscribe("T42.Wnd.OnEvent",{target:"best",arguments:{withConfig:!0},waitTimeoutMs:Nn,methodResponseTimeout:Nn,onData:t=>{if("Configuration"===t.data.type)return this._configuration=t.data,void ti.setConfiguration(this._configuration);this.updateWindow(t.data,e),ti.handleEvent(t.data)},onConnected:e=>{this._agmInstance=e,ti.init(this._agm,this._agmInstance,this._logger.subLogger("executor"))}}).catch(e=>{var n;const i=`${null===(n=null==e?void 0:e.method)||void 0===n?void 0:n.name} - ${JSON.stringify(null==e?void 0:e.called_with)} - ${null==e?void 0:e.message}`;t(new Error(i))})})})}get executor(){return ti}open(e,t,n){n=n||{};const i={...n};return void 0!==i.relativeTo&&"string"!=typeof i.relativeTo&&(i.relativeTo=i.relativeTo.id||""),i.name=e,i.url=t,i.windowState=n.windowState||n.state,delete i.state,this.executor.open(i)}createFlydown(e,t){return this.executor.createFlydown(e,t)}async showPopup(e,t){const n=qn.get(e);await this.executor.showPopup(n.API,t)}tabAttached(e){return this._registry.add("tab-attached",e)}tabDetached(e){return this._registry.add("tab-detached",e)}onWindowFrameColorChanged(e){return this._registry.add("frame-color-changed",e)}onEvent(e){return this._registry.add("window-event",e)}my(){return this._windowId}myGroup(){var e,t;return null!==(t=null===(e=qn.get(this._windowId))||void 0===e?void 0:e.API.groupId)&&void 0!==t?t:this._groupId}onCompositionChanged(e){return this._registry.add("composition-changed",e)}onGroupHeaderVisibilityChanged(e){return this._registry.add("group-header-changed",e)}onGroupVisibilityChanged(e){return this._registry.add("group-visibility-changed",e)}onGroupStateChanged(e){return this._registry.add("group-state-changed",e)}onWindowGotFocus(e){return this._registry.add("got-focus",e)}onWindowLostFocus(e){return this._registry.add("lost-focus",e)}onWindowsAutoArrangeChanged(e){return this._registry.add("windows-auto-arranged-changed",e)}respondToEvent(e){return"ShowFlydownBoundsRequested"===e.type?this.executor.handleFlydownBoundsRequested(e.data.windowId,e.data):"OnClosing"===e.type||"OnRefreshing"===e.type||"OnNavigating"===e.type?this.executor.handleOnEventRequested(e.data.callbackId,e.data.args):Promise.reject(new Error(`There isn't a handler for ${e.type}`))}updateWindow(e,t){const n=this.getExtendedStreamEvent(e);if("Snapshot"===e.type){return e.windows.forEach(e=>{const t=qn.get(e.id);t?(t.Events.handleUpdate(this.mapToWindowConstructorOptions(e)),t.GroupCreationArgs=this.mapToGroupCreationArgs(e)):this.createWindowFromSnapshot(e.id,e),this._registry.execute("window-event",n)}),void t(this)}if("CommandExecuted"===e.type)return void this._registry.execute("window-event",n);if("Created"===e.type){const t=e;return this.createWindowFromStream(t.windowId,t.data||{}),void this._registry.execute("window-event",n)}if("OnGroupVisibilityChanged"===e.type){const t=e;return this._registry.execute("group-visibility-changed",t.data),void this._registry.execute("window-event",e)}if("OnGroupStateChanged"===e.type){const t=e;return this._registry.execute("group-state-changed",t.data),void this._registry.execute("window-event",e)}if("OnWindowsAutoArrangeChanged"===e.type){const t=e;return this._registry.execute("windows-auto-arranged-changed",t.data),void this._registry.execute("window-event",e)}const i=qn.get(e.windowId);if(!i)return void this._logger.error(`received update for unknown window. Stream:', ${JSON.stringify(e,null,4)}`);const r=i.API,o=i.Events;if("BoundsChanged"===e.type){const t=e;o.handleBoundsChanged(t.data)}if("UrlChanged"===e.type){const t=e;qn.setUrlChangedState(t.windowId),o.handleUrlChanged(t.data)}if("TitleChanged"===e.type){const t=e;o.handleTitleChanged(t.data)}if("IsStickyChanged"===e.type){const t=e;o.handleIsStickyChanged(t.data)}if("VisibilityChanged"===e.type&&o.handleVisibilityChanged(e.data),"ContextChanged"===e.type&&o.handleContextUpdated(e.data),"StateChanged"===e.type&&o.handleWindowChangeState(e.data),"FrameColorChanged"===e.type&&(o.handleFrameColorChanged(e.data),this._registry.execute("frame-color-changed",r)),"CompositionChanged"===e.type){const t=e;o.handleCompositionChanged(t.data),qn.setCompositionChangedState(i),this._registry.execute("composition-changed",t.data)}if("GroupHeaderVisibilityChanged"===e.type){const t=e;o.handleGroupHeaderVisibilityChanged(t.data.groupHeaderVisible),this._registry.execute("group-header-changed",t.data)}if("FocusChanged"===e.type){const t=e;this.focusChanged(o,r,t.data)}if("WindowFrameChanged"===e.type&&(o.handleFrameAttached(e.data.frameId,e.data.frameId,e.data.isTabHeaderVisible),this._registry.execute("frame-changed")),"WindowFrameAdded"===e.type){const t=Yn(r.id,e.data.frameId),n=e.data;o.handleAttached(n.frameId,n.frameId,n.isTabHeaderVisible,n.isLocked,t).then(async()=>{t.length>0&&(await ti.finished,this._registry.execute("tab-attached",r,e.data.frameId,e.data.isTabHeaderVisible))})}if("WindowFrameRemoved"===e.type){const t=r.tabGroupId,n=Yn(r.id,t);o.handleDetached(e.data.isLocked,n).then(async()=>{n.length>0&&(await ti.finished,this._registry.execute("tab-detached",r,e.data.frameId,r.tabGroupId))})}"TabHeaderVisibilityChanged"===e.type&&o.handleTabHeaderVisibilityChanged(e.data.isTabHeaderVisible),"FrameSelectionChanged"===e.type&&o.handleFrameSelectionChanged(e.data.newWindowId,e.data.prevWindowId),"ButtonClicked"===e.type&&o.handleFrameButtonClicked(e.data),"ButtonAdded"===e.type&&o.handleFrameButtonAdded(e.data),"ButtonRemoved"===e.type&&o.handleFrameButtonRemoved(e.data),"WindowZoomFactorChanged"===e.type&&o.handleZoomFactorChanged(e.data),"Closed"===e.type&&(qn.remove(i),o.handleWindowClose()),"FrameIsLockedChanged"===e.type&&o.handleFrameIsLockedChanged(e.data),"PlacementSettingsChanged"===e.type&&o.handlePlacementSettingsChanged(e.data),"DockingChanged"===e.type&&o.handleDockingChanged(e.data),"AllowWorkspaceDropChanged"===e.type&&o.handleAllowWorkspaceDropChanged(e.data),"IsPinnedChanged"===e.type&&o.handleIsPinnedChanged(e.data),"WindowChannelRestrictionsChanged"===e.type&&o.handleChannelRestrictionsChanged(e.data),this._registry.execute("window-event",n)}createWindowFromSnapshot(e,t){const n=this.createWindowCore(e,t);qn.add(n,{ready:!0,urlChanged:!0,compositionChanged:!0})}createWindowFromStream(e,t){var n;const i=this.createWindowCore(e,t),r="remote"===i.API.windowType,o="electron"===i.API.windowType&&"frameless"===i.API.mode,s=!1===i.API.isVisible;let a=!1,c=!1;r&&(a=!0),(o||s)&&(c=!0),r||(a=!(null===(n=this._configuration)||void 0===n?void 0:n.windowAvailableOnURLChanged)),qn.add(i,{ready:!0,urlChanged:a,compositionChanged:c})}createWindowCore(e,t){const n=Xn(e,this.mapToWindowConstructorOptions(t),ti,this._logger,this._appsController,this._displayAPIGetter,this._channelsAPIGetter,this._agm);return n.GroupCreationArgs=this.mapToGroupCreationArgs(t),n}async focusChanged(e,t,n){e.handleFocusChanged(n);try{this._configuration.windowAvailableOnURLChanged||await qn.waitFor(t.id)}catch(e){return}n?this._registry.execute("got-focus",t):this._registry.execute("lost-focus",t)}mapToWindowConstructorOptions(e){return{name:e.name,context:e.context,bounds:e.bounds,url:e.url,title:e.title,isVisible:e.isVisible,focus:e.isFocused,state:e.state,frameColor:e.frameColor,groupId:e.groupId,neighbours:e.neighbors,isFocused:e.isFocused,isGroupHeaderVisible:e.groupHeaderVisible,isCollapsed:e.isCollapsed,tabGroupId:e.frameId,frameId:e.frameId,mode:e.mode,isTabHeaderVisible:e.isTabHeaderVisible,isTabSelected:e.isActiveTab,settings:e.settings,windowType:e.windowType,zoomFactor:e.zoomFactor,isLocked:e.isLocked,placementSettings:e.placementSettings,isSticky:e.isSticky,tabIndex:e.tabIndex,frameButtons:e.frameButtons,jumpListOptions:e.jumpList,applicationName:e.applicationName,allowWorkspaceDrop:e.allowWorkspaceDrop,isPinned:e.isPinned}}mapToGroupCreationArgs(e){return{isGroupHibernated:e.isGroupHibernated,isGroupVisible:e.isGroupVisible}}getExtendedStreamEvent(e){try{if(!e.windowId)return e;const t=qn.get(e.windowId);if(!t)return e;const n={state:e.type,windowName:t.API.name,...e};return"WindowFrameAdded"===n.state&&(n.state="TabAttached"),"StateChanged"===n.state&&(n.state=n.data.charAt(0).toUpperCase()+n.data.slice(1)),"ButtonAdded"===n.state&&(n.state="FrameButtonAdded"),"ButtonRemoved"===n.state&&(n.state="FrameButtonRemoved"),n}catch(t){return e}}}var ii=(e,t)=>{const n=xn(),i=[];let r,o;async function s(e,n,...i){return await t.execute(e,n,...i),d}function a(){const e=[];return i.forEach(t=>{const n=c(t);void 0!==n&&e.push(n)}),e}function c(e){return qn.get(e)?qn.get(e).API:void 0}const d={id:e,get windows(){return a()},find:function(e,t,n){let i;"string"==typeof e?i=e:Mt(e)||(i=e.id);const r=c(i);if(r)return"function"==typeof t&&t(r),r;"function"==typeof n&&n(`No window with ID: ${i}`)},get isHeaderVisible(){return void 0===a().find(e=>!e.isGroupHeaderVisible)},get isHibernated(){return r},get isVisible(){return o},showHeader:(e,t)=>jn.callbackifyPromise(()=>s("setGroupHeaderVisibility",{windowId:i[0],options:{toShow:!0}},...i.map(e=>`GroupHeaderVisibilityChanged-${e}`)),e,t),hideHeader:(e,t)=>jn.callbackifyPromise(()=>s("setGroupHeaderVisibility",{windowId:i[0],options:{toShow:!1}},...i.map(e=>`GroupHeaderVisibilityChanged-${e}`)),e,t),getTitle:async()=>(await t.execute("getGroupTitle",{windowId:i[0]})).title,setTitle:async e=>{if(Rt(e))throw new Error("`title` must not be null or undefined.");return s("setGroupTitle",{windowId:i[0],options:{title:e}})},capture:e=>t.captureGroup(i,e),maximize:(e,t)=>jn.callbackifyPromise(()=>s("maximizeGroup",{windowId:i[0]},...i.map(e=>`StateChanged-${e}`)),e,t),restore:(e,t)=>jn.callbackifyPromise(()=>s("restoreGroup",{windowId:i[0]},...i.map(e=>`StateChanged-${e}`)),e,t),show:n=>{if(!Mt(n)&&!Nt(n))throw new Error("Activate flag must be a boolean!");return n=!!Mt(n)||n,t.executeGroup("showGroup",{groupId:e,options:{activate:n}})},hide:()=>t.executeGroup("hideGroup",{groupId:e}),reload:()=>t.executeGroup("reloadGroup",{groupId:e}),close:()=>t.executeGroup("closeGroup",{groupId:e}),showPopup:n=>t.showGroupPopup(e,n),onHeaderVisibilityChanged:function(e){return n.add("header-visibility-changed",e)},onWindowAdded:function(e){return n.add("window-added",e)},onWindowRemoved:function(e){return n.add("window-removed",e)},onVisibilityChanged:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return n.add("group-visibility-changed",e)},onClosing:function(e){if("function"!=typeof e)throw new Error("callback must be a function");return t.onGroupClosing((t,n,i)=>{const r=e(i);(null==r?void 0:r.then)?r.then(t).catch(n):t()},d)}},h={get windows(){return i},addWindow:async function(e){var s,a,c,h;if(-1===i.indexOf(e)){i.push(e);const l=qn.get(e);l.Events.handleGroupChanged(d,void 0),r=null!==(a=null!==(s=l.GroupCreationArgs.isGroupHibernated)&&void 0!==s?s:r)&&void 0!==a&&a,o=null===(h=null!==(c=l.GroupCreationArgs.isGroupVisible)&&void 0!==c?c:o)||void 0===h||h,await t.finished,n.execute("window-added",d,l.API)}},removeWindow:async function(e){const r=i.indexOf(e.API.id);-1!==r&&(i.splice(r,1),e.Events.handleGroupChanged(void 0,d),await t.finished,n.execute("window-removed",d,e.API))},handleGroupHeaderVisibilityChanged:function(e){n.execute("header-visibility-changed",d)},handleGroupVisibilityChanged:function(e){o=e,n.execute("group-visibility-changed",d)},handleGroupHibernateChanged:function(e){r=e}};return{groupAPI:d,groupInternal:h}},ri=(e,t)=>{const n=xn(),i={};let r=-1;const o=qn.list;function s(e,t,n){let r;"string"==typeof e?r=e:Mt(e)||(r=e.id);const o=Object.values(i).find(e=>e.groupAPI.windows.filter(e=>e.id===r).length);if(o)return"function"==typeof t&&t(o.groupAPI),o.groupAPI;"function"==typeof n&&n("Cannot find the group of the window.")}function a(e){return e?new Promise((t,n)=>{const r=i[e];if(r)t(r.groupAPI);else{const n=c(i=>{i.id===e&&(n(),t(i))})}}):Promise.reject(new Error("groupId must be defined"))}function c(e){return n.add("group-added",e)}function d(t,r){const o=function(t){if(i.hasOwnProperty(t))return i[t];{const r=ii(t,e.executor);i[t]=r;const o=r.groupAPI;return n.execute("group-added",o),r}}(t);return o.groupInternal.addWindow(r),o}function h(e,t){e&&(e.groupInternal.removeWindow(t),function(e){const t=e.groupAPI;0===t.windows.length&&(delete i[t.id],ti.clearCallbacks(t.id),n.execute("group-removed",t))}(e))}function l(e){let t;return"string"==typeof e?t=e:Mt(e)||(t=e.id),Object.values(i).find(e=>e.groupInternal.windows.filter(e=>e===t).length)}function u(e){if(!e||"string"!=typeof e)throw new Error("Please provide a valid Group ID as a non-empty string!")}Object.keys(o).forEach(e=>{const t=o[e],n=t.API.groupId,i=t.API.id;Rt(n)||d(n,i)}),qn.onRemoved(e=>{h(l(e.API),e)}),e.onCompositionChanged(e=>{!function(e){const t=e.groupId,r=e.windowId,o=qn.get(r);if(!o)return;const s=l(o.API);if(Mt(t))return void h(s,o);if(Mt(s)&&!Mt(t))return void d(t,o.API.id);s.groupAPI.id!==t&&function(e,t,r){const o=e.API.id,s=i[t];h(s,e);const a=d(r,o);e.Events.handleGroupChanged(a.groupAPI,s.groupAPI),n.execute("window-moved",o,t,r)}(o,s.groupAPI.id,t)}(e)}),e.onGroupHeaderVisibilityChanged(e=>{const t=s(e.windowId);if(void 0!==t){const n=i[t.id];-1===r&&(r=t.windows.length),r--,0===r&&(r=-1,n.groupInternal.handleGroupHeaderVisibilityChanged(e))}}),e.onGroupVisibilityChanged(e=>{const t=i[e.groupId];t&&t.groupInternal.handleGroupVisibilityChanged(e.visible)}),e.onGroupStateChanged(e=>{const t=i[e.groupId];"hibernated"===e.state?((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!0),n.execute("group-hibernated",e.groupId)):"resumed"===e.state&&((null==t?void 0:t.groupAPI)&&t.groupInternal.handleGroupHibernateChanged(!1),n.execute("group-resumed",t.groupAPI))});const p={get my(){return function(){var t;return s(null!==(t=e.myGroup())&&void 0!==t?t:e.my())}()},create:async function(e){if(Mt(e))throw new Error("options must be defined");if(Mt(e.groups)||!Array.isArray(e.groups)||0===e.groups.length)throw new Error("options.groups must be defined");const{groupIds:t}=await ti.executeGroup("createGroups",{options:e}),n=t.map(e=>a(e));return Promise.all(n)},close:async function(e,t){if(Mt(e))throw new Error("group must be defined");let n="";if(n="string"==typeof e?e:e.id,Mt(t))throw new Error("options must be defined");await ti.executeGroup("closeGroup",{groupId:n,options:t})},list:function(e){const t=Object.keys(i).map(e=>{if(i[e])return i[e].groupAPI});return"function"==typeof e&&e(t),t},findGroupByWindow:s,waitForGroup:a,getMyGroup:function(){var t;return a(null!==(t=e.myGroup())&&void 0!==t?t:e.my())},onGroupAdded:c,onGroupRemoved:function(e){return n.add("group-removed",e)},hibernate:async function(e){return u(e),await ti.executeGroup("hibernateGroup",{groupId:e}),e},resume:async function(e,t){if(u(e),!Mt(t)&&!Nt(t))throw new Error("Activate flag must be a boolean!");t=!!Mt(t)||t,await ti.executeGroup("resumeGroup",{groupId:e,options:{activate:t}})},onHibernated:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return n.add("group-hibernated",e)},onResumed:function(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return n.add("group-resumed",e)}};return{groupsAPI:p,groupsEvents:{onWindowMoved:function(e){return n.add("window-moved",e)}}}},oi=(e,t,n,i,r,o)=>{const s=xn(),a=t;let c,d,h=1;qn.init(a);const l=new Promise((t,s)=>{((e,t,n,i,r,o)=>{var s;const a=t;if(2===o)throw a.trace("running in HC"),new Error("GD2 not supported");return o>=3?(a.trace("running in GD 3"),new ni(e,a,n,i,r,window.glue42gd.windowId,null===(s=window.webGroupsManager)||void 0===s?void 0:s.id).init()):(a.trace("running in Browser or Node"),new ni(e,a,n,i,r).init())})(e,a,n,i,r,o).then(n=>{d=n,c=ri(n),Jn.init(n.executor,e,a),t()}).catch(e=>{const t=`Timed out waiting for connection to Glue42 Enterprise: Error: ${e.message}`;a.error(t,e),s(new Error(t))})});function u(){const e=qn.getIfReady(d.my());return e?e.API:void 0}function p(e){return s.add("window-added",e)}function g(e){return s.add("window-removed",e)}return qn.onReadyWindow(function(e){s.execute("window-added",e.API)}),qn.onRemoved(function(e){s.execute("window-removed",e.API)}),{my:u,open:function(e,t,n,i,r){return jn.callbackifyPromise(()=>{if(Rt(e))throw new Error("The window name is missing.");if(Rt(t))throw new Error("The window URL is missing.");if(!Mt(n)){const e=n;for(const t of["minHeight","maxHeight","minWidth","maxWidth","width","height","top","left"])if(t in e){const n=e[t];if(Mt(n)){delete e[t];continue}if(!St(n)){throw new Error(`${t} must be a number`)}if(("width"===e[t]||"height"===e[t])&&n<=0){throw new Error(`${t} must be a positive number`)}}}return d.open(e,t,n)},i,r)},find:function(e,t,n){const i=qn.list,r=Object.keys(i).reduce((t,n)=>{var r;const o=i[n];return(null===(r=null==o?void 0:o.API)||void 0===r?void 0:r.name)===e&&t.push(o.API),t},[]);if(r[0])return"function"==typeof t&&t(r[0]),r[0];"function"==typeof n&&n("There is no window with name:"+e)},findById:function(e,t,n){const i=qn.list,r=Object.keys(i).reduce((t,n)=>{const r=i[n];return void 0!==r&&r.API.id===e&&t.push(r.API),t},[]);if(r[0])return"function"==typeof t&&t(r[0]),r[0];"function"==typeof n&&n("There is no window with such id:"+e)},list:function(e){const t=qn.list,n=Object.keys(t).map(e=>t[e].API);if("function"!=typeof e)return n;e(n)},ready:function(){return l},onWindowAdded:p,windowAdded:p,onWindowRemoved:g,windowRemoved:g,onTabAttached:function(e){let t,n=!1;return l.then(()=>{n||(t=d.tabAttached(e))}),()=>{n=!0,t&&t()}},onTabDetached:function(e){let t,n=!1;return l.then(()=>{n||(t=d.tabDetached(e))}),()=>{n=!0,t&&t()}},onWindowFrameColorChanged:function(e){let t,n=!1;return l.then(()=>{n||(t=d.onWindowFrameColorChanged(e))}),()=>{n=!0,t&&t()}},onArrangementChanged:function(e){return d.onWindowsAutoArrangeChanged(e)},get groups(){return c.groupsAPI},onWindowGotFocus:function(e){let t,n=!1;return l.then(()=>{n||(t=d.onWindowGotFocus(e))}),()=>{n=!0,t&&t()}},onWindowLostFocus:function(e){let t,n=!1;return l.then(()=>{n||(t=d.onWindowLostFocus(e))}),()=>{n=!0,t&&t()}},onEvent:function(e){let t,n=!1;return l.then(()=>{n||(t=d.onEvent(e))}),()=>{n=!0,t&&t()}},createFlydown:function(e,t){return d.createFlydown(e,t)},createPopup:function(e){var t,n;if("undefined"==typeof window||!window.glue42gd||!window.glue42gd.createProcessWindow)throw new Error("Cannot create popup window. The glue42gd object is not available in the current environment.");if(!window.glue42gd.createProcessWindow)throw new Error("Cannot create popup window. The createProcessWindow method is not available in the glue42gd object.");let i="isInternalPopup=true, mode=frameless, hidden=true, outlivesOpener=false";if(e){const t=["left","top","width","height","roundedCorners","hasSizeAreas","hasMoveAreas"];for(const n of t)if(n in e){const t=e[n];Mt(t)||(i+=`, ${n}=${t}`)}}i+=`, transparent=${null!==(t=null==e?void 0:e.transparent)&&void 0!==t&&t}`;const r=`ioConnectPopup-${window.glue42gd.windowId}-${h++}`,o={name:r,features:i,copyStyles:null===(n=null==e?void 0:e.copyStyles)||void 0===n||n};return new Promise(async(e,t)=>{const n=await window.glue42gd.createProcessWindow(o).catch(e=>{t(e)});qn.waitForName(r).then(t=>{e({browserWindow:n,ioConnectWindow:t.API})}).catch(e=>{n.close(),t(e)})})},showPopup:function(e,t){return d.showPopup(e,t)},configure:function(e){const t=u(),n=t?t.id:"";return ti.configure(n,e)},autoArrange:function(e){return ti.autoArrange(e)}}};var si=new class{constructor(){this.layouts=[]}removeWhere(e){this.layouts=this.layouts.filter(e)}removeAll(){this.layouts=[]}add(e){this.layouts.push(e)}get all(){return this.layouts}where(e){return this.layouts.filter(e)}first(e){return this.where(e)[0]}};class ai{constructor(e,t,n,i){this.config=e,this.activitiesGetter=t,this.callbacks=n,this.logger=i,this.interop=e.agm,this.registerRequestMethods()}onSaveRequested(e){return this.callbacks.add("saveRequested",e)}isActivityOwner(){if("undefined"!=typeof htmlContainer){const e=htmlContainer.getContext();return e&&e._t42&&e._t42.activityIsOwner}const e=this.activitiesGetter();if(!e)return!1;if(!e.inActivity)return!1;const t=e.my.window,n=e.my.activity;return!(!n&&!t)&&n.owner.id===t.id}registerRequestMethods(){this.interop.register("T42.HC.GetSaveContext",e=>{const{ignoreContexts:t,...n}=e,i=this.callbacks.execute("saveRequested",n);(null==i?void 0:i.length)>1&&this.logger.warn('Multiple subscriptions for "glue.layouts.onSaveRequested" - only the first one will be used');const r=i[0],o=this.config.autoSaveWindowContext;if("boolean"==typeof o&&o)return{autoSaveWindowContext:o};if(Array.isArray(o)&&o.length>0)return{autoSaveWindowContext:o};const s={windowContext:null==r?void 0:r.windowContext,activityContext:void 0};return this.isActivityOwner()&&(s.activityContext=null==r?void 0:r.activityContext),t?{windowContext:void 0,activityContext:void 0}:s})}}function ci(e){if(!e)return e;if(Array.isArray(e))return e.map(e=>ci(e));if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;return Object.keys(e).reduce((t,n)=>{var i;const r=ci(e[n]);let o=n;return(null===(i=n[0])||void 0===i?void 0:i.toLowerCase())!==n[0]&&(o=n[0].toLowerCase()+n.substr(1)),t[o]=r,t},{})}class di{constructor(e){this.name=e.name,this.type=e.type,this.components=e.components,this.context=e.context,this.metadata=e.metadata,this.version=e.version,this.displays=e.displays}}var hi={},li={};Object.defineProperty(li,"__esModule",{value:!0});var ui={};Object.defineProperty(ui,"__esModule",{value:!0});var pi,gi,fi={};Object.defineProperty(fi,"__esModule",{value:!0}),fi.SwimlaneItemType=fi.LayoutType=void 0,function(e){e.Global="Global",e.Activity="Activity",e.ApplicationDefault="ApplicationDefault",e.Swimlane="Swimlane",e.Workspaces="Workspace"}(pi||(fi.LayoutType=pi={})),function(e){e.Tab="tab",e.Window="window",e.Canvas="canvas"}(gi||(fi.SwimlaneItemType=gi={}));var mi={};Object.defineProperty(mi,"__esModule",{value:!0});var yi={};Object.defineProperty(yi,"__esModule",{value:!0}),function(e){var t=Tn&&Tn.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),n=Tn&&Tn.__exportStar||function(e,n){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(n,i)||t(n,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(li,e),n(ui,e),n(fi,e),n(mi,e),n(yi,e)}(hi);const wi="T42.ACS.Command";class vi{constructor(e,t,n,i){this.config=e,this.stream=t,this.callbacks=n,this.logger=i,this.isRegisterMethodForLayoutModified=!1,this.provider=new ai(e,e.activityGetter,n,i),t.subscribe()}async setDefaultGlobal(e){await this.invokeMethodCore("SelectDefaultLayout",{name:e})}async clearDefaultGlobal(){await this.invokeMethodCore("DeselectDefaultLayout")}async getDefaultGlobal(){const e=(await this.invokeMethodCore("GetDefaultLayout")).returned;if(null!=e&&("object"!=typeof e||0!==Object.keys(e).length))return Pn(this.isSlimMode()?e:this.list().find(t=>t.name===e.name&&t.type===e.type))}ready(){return"fullWaitSnapshot"===this.config.mode?this.stream.gotSnapshot:this.stream.ready}save(e){return new Promise((t,n)=>{var i,r,o,s;if(this.verifyNotSlimMode(),Mt(e))return n(new Error("layout is required"));if(Rt(e.name))return n(new Error("layout.name argument is required"));Rt(e.type)&&(e.type="Global"),Rt(e.activityId)||(e.type="Activity");const a={name:e.name,type:e.type,context:null!==(i=e.context)&&void 0!==i?i:{},metadata:null!==(r=e.metadata)&&void 0!==r?r:{},options:{}};if("Activity"===e.type){let t=e.activityId;if(!t){if(!(null===(o=this.config.myInstance())||void 0===o?void 0:o.inActivity))return n(new Error("Current application is not in activity. Cannot save activity layout for it."));t=null===(s=this.config.myInstance())||void 0===s?void 0:s.activityId}a.activityId=t}else{if("Global"!==e.type)return n(new Error(`layout type ${e.type} is not supported`));Array.isArray(e.ignoreInstances)&&(a.options.ignoreInstances=e.ignoreInstances),Array.isArray(e.instances)&&(a.options.instances=e.instances),"boolean"==typeof e.setAsCurrent&&(a.options.setAsCurrent=e.setAsCurrent),"boolean"==typeof e.ignoreContexts&&(a.options.ignoreContexts=e.ignoreContexts)}this.invokeMethodAndTrack("SaveLayout",a,t,n)})}restore(e){return new Promise((t,n)=>{var i,r,o,s;if(this.verifyNotSlimMode(),Mt(e))return n(new Error("options argument is required"));if(Rt(e.name))return n(new Error("options.name argument is required"));if(Rt(e.type)&&(e.type="Global"),Rt(e.activityIdToJoin)||(e.type="Activity"),"Activity"===e.type){if(Mt(e.setActivityContext)&&(e.setActivityContext=!0),"boolean"!=typeof e.setActivityContext)return n(new Error("`setActivityContext` must hold a boolean value."));e.activityIdToJoin=null!==(i=e.activityIdToJoin)&&void 0!==i?i:null===(r=this.config.myInstance())||void 0===r?void 0:r.activityId}if(Mt(e.closeRunningInstance)||(e.closeRunningInstances=e.closeRunningInstance),Mt(e.closeRunningInstances)&&(e.closeRunningInstances=!0),!Nt(e.closeRunningInstances))return n(new Error("`closeRunningInstances` must hold a boolean value."));if(Mt(e.closeMe)&&(e.closeMe=e.closeRunningInstances),!Nt(e.closeMe))return n(new Error("`closeMe` must hold a boolean value."));if(!Mt(e.context)&&!xt(e.context))return n(new Error("`context` must hold an object value."));e.context=null!==(o=e.context)&&void 0!==o?o:{};const a={activityToJoin:e.activityIdToJoin,setActivityContext:e.setActivityContext,ignoreActivityWindowTypes:e.ignoreActivityWindowTypes,reuseExistingWindows:e.reuseWindows,restoreWorkspacesByReference:e.restoreWorkspacesByReference,closeRunningInstances:e.closeRunningInstances,excludeFromClosing:e.closeMe?[]:[null===(s=this.config.myInstance())||void 0===s?void 0:s.id]},c={type:e.type,name:e.name,context:e.context,options:a,timeout:On};this.invokeMethodAndTrack("RestoreLayout",c,t,n,!0)})}reset(e){return new Promise((t,n)=>{if(this.verifyNotSlimMode(),"object"!=typeof e)return n(new Error("options argument is required"));if(Rt(e.layoutId))return n(new Error("options.layoutId argument is required"));const i={...e};this.invokeMethodAndTrack("ResetLayout",i,t,n,!0)})}remove(e,t){return new Promise((n,i)=>{if(this.verifyNotSlimMode(),!t)return i(new Error("name argument is required"));if(!e)return i(new Error("type argument is required"));const r={type:e,name:t};this.invokeMethodAndTrack("RemoveLayout",r,n,i)})}list(){return this.verifyNotSlimMode(),Pn(si.all)}import(e,t){return new Promise((n,i)=>{if(this.verifyNotSlimMode(),!Mt(t)&&"merge"!==t&&"replace"!==t)return i(new Error(`${t} is not supported - only "merge" and "replace"`));if(!Array.isArray(e))return i(new Error("layouts arguments is not an array"));const r={mode:t||"replace",layouts:e};this.invokeMethodAndTrack("ImportLayouts",r,n,i,!0)})}export(e){return new Promise((t,n)=>{var i;if(!Mt(e)&&!(null===(i=Object.values(hi.LayoutType))||void 0===i?void 0:i.includes(e)))return n(new Error(`${e} is not a supported Layout Type`));this.invokeMethodAndTrack("ExportLayouts",{},n=>{let i=this.getObjectValues(n.Layouts).map(e=>new di(ci(e)));e&&(i=i.filter(t=>t.type===e)),t(i)},n,!0)})}rename(e,t){return new Promise((n,i)=>{if(this.verifyNotSlimMode(),!e)return i(new Error("layout argument is required"));if(!e.name)return i(new Error("name argument is required"));if(!e.type)return i(new Error("type argument is required"));const r={type:e.type,oldName:e.name,newName:t};this.invokeMethodAndTrack("RenameLayout",r,n,i)})}updateMetadata(e){return new Promise((t,n)=>{if(!e)return n(new Error("layout argument is required"));if(!e.name)return n(new Error("name argument is required"));if(!e.type)return n(new Error("type argument is required"));if(!e.metadata)return n(new Error("metadata argument is required"));const i={name:e.name,type:e.type,metadata:e.metadata};this.invokeMethodAndTrack("UpdateMetadata",i,t,n,!0)})}hibernate(e,t){return new Promise((n,i)=>{if(!e)return i(new Error("name cannot be empty"));const r={name:e,type:"Global",context:(t=t||{}).context||{},metadata:t.metadata||{}};this.invokeMethodAndTrack("HibernateLayout",r,n,i,!0)})}resume(e,t,n){return new Promise((i,r)=>{if(!e)return r(new Error("name cannot be empty"));const o={name:e,type:"Global",timeout:On,context:t,...n};this.invokeMethodAndTrack("ResumeLayout",o,i,r,!0)})}async getCurrentLayout(){let e=(await this.invokeMethodCore("GetCurrentLayout")).returned.layout;if(e)return this.isSlimMode()||(e=this.list().find(t=>t.name===e.name&&t.type===e.type)),Pn(e)}getRestoredLayoutsInfo(){return new Promise((e,t)=>{this.invokeMethodCore("GetRestoredLayoutsInfo").then(t=>{const n=t.returned;e(n)}).catch(t)})}onAdded(e){const t=this.callbacks.add("added",e);return si.all.length>0&&si.all.forEach(t=>{try{e(t)}catch(e){}}),t}onRemoved(e){return this.callbacks.add("removed",e)}onChanged(e){return this.callbacks.add("changed",e)}onDefaultGlobalChanged(e){if("function"!=typeof e)throw new Error("callback must be a function");return this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.callbacks.add("default-changed",e)}onRestored(e){return this.callbacks.add("restored",e)}onRenamed(e){return this.callbacks.add("renamed",e)}onEvent(e){return this.stream.onEvent(e)}onSaveRequested(e){return this.provider.onSaveRequested(e)}onLayoutModified(e){return!1===this.isRegisterMethodForLayoutModified&&(this.isRegisterMethodForLayoutModified=!0,this.registerMethodForLayoutModified()),this.callbacks.add("layout-modified",e)}updateAppContextInCurrent(e){return new Promise((t,n)=>{if(e&&"object"!=typeof e)return n(new Error("Context must be an object"));const i={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateLayoutComponentContext",i,t,n,!0)})}updateDefaultContext(e){return new Promise((t,n)=>{if(e&&"object"!=typeof e)return n(new Error("Context must be an object"));const i={context:e=null!=e?e:{}};this.invokeMethodAndTrack("UpdateDefaultContext",i,t,n,!0)})}async get(e,t){const n=this.list().find(n=>n.name===e&&n.type===t);if(!n)throw new Error(`cannot find layout with name=${e} and type=${t}`);return Pn(n)}async getAll(e){var t;if(!Mt(e)&&!(null===(t=Object.values(hi.LayoutType))||void 0===t?void 0:t.includes(e)))throw new Error(`${e} is not a supported Layout Type`);return Pn(this.list().filter(t=>e===t.type))}async forceRefresh(){await this.invokeMethodCore("RefreshLayouts")}isSlimMode(){return"slim"===this.config.mode}verifyNotSlimMode(){if(this.isSlimMode())throw Error("Operation not allowed in slim mode. Run in full mode.")}async registerMethodForLayoutModified(){await this.config.agm.register("T42.ACS.LayoutModified",(e,t)=>{this.callbacks.execute("layout-modified",e)})}invokeMethodAndTrack(e,t,n,i,r){let o,s=r;const a=jn.generateId();t.token=a,this.logger.debug(`invoking method "${e}" with token ${a} will wait for stream event: ${!r}`);const c=()=>{s&&o&&(this.logger.debug(`method "${e}" resolved with token ${a} and result: ${JSON.stringify(o)}`),n(o))},d=e=>{const t=jn.typedError(e);i(t)},h="timeout"in t&&"number"==typeof t.timeout?t.timeout:12e4;r||this.stream.waitFor(a,h).then(()=>{s=!0,c()}).catch(d);this.invokeMethodCore(e,t,"best",{methodResponseTimeoutMs:h}).then(t=>{if(this.logger.debug(`method "${e}" returned with token "${a}" and result: ${JSON.stringify(t.returned)}`),!t.returned)return i(new Error("No result from method "+e));if(t.returned.status&&"Success"!==t.returned.status&&"PartialSuccess"!==t.returned.status){if("string"==typeof t.returned)return i(new Error(t.returned));if("object"==typeof t.returned)return t.returned.status&&t.returned.failed?i(new Error(`${t.returned.status}: ${JSON.stringify(t.returned.failed)}`)):i(new Error(t.returned))}o=t.returned,c()}).catch(d)}async invokeMethodCore(e,t,n,i){return void 0===(i=null!=i?i:{}).methodResponseTimeoutMs&&(i.methodResponseTimeoutMs=Nn),void 0===i.waitTimeoutMs&&(i.waitTimeoutMs=Nn),this.isCommandMethodPresent()?await this.config.agm.invoke(wi,{command:e,data:t},n,i):await this.config.agm.invoke(`T42.ACS.${e}`,t,n,i)}getObjectValues(e){return e?Object.keys(e).map(t=>e[t]):[]}isCommandMethodPresent(){return this.config.agm.methods().some(e=>e.name===wi)}}class bi{constructor(e,t,n){this.agm=e,this.logger=t,this.callbacks=n,this.StreamName="T42.ACS.OnLayoutEvent",this.ready=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this.gotSnapshot=new Promise((e,t)=>{this.resolveGotSnapshot=e,this.rejectGotSnapshot=t})}subscribe(e){const t=e=>this.getObjectValues(e).map(e=>ci(e));this.checkForLayoutEventMethod()?(this.logger.trace(`subscribing to "${this.StreamName}" stream`),this.agm.subscribe(this.StreamName,{waitTimeoutMs:Nn,methodResponseTimeout:Nn}).then(e=>{this.logger.trace(`subscribed to "${this.StreamName}" stream`),e.onData(e=>{const n=e.data;this.logger.trace(`received data from "${this.StreamName}" stream: ${JSON.stringify(n)}`),n.IsSnapshot&&this.resolveGotSnapshot(),this.addLayouts(t(n.OnLayoutAdded),n.IsSnapshot),this.removeLayouts(t(n.OnLayoutRemoved)),this.changeLayouts(t(n.OnLayoutChanged)),this.renameLayouts(t(n.OnLayoutRenamed)),this.restoredLayout(t(n.OnLayoutRestored)),this.selectedDefaultLayout(t(n.OnLayoutSelectedDefault)),this.callbacks.execute("streamEvent",n)}),e.onFailed(e=>{const t=`Can not subscribe to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.logger.error(t,e),this.rejectReady(t),this.rejectGotSnapshot(t)}),this.resolveReady()}).catch(e=>{const t=`Error subscribing to "${this.StreamName}" stream - ${JSON.stringify(e)}`;this.logger.error(t,e),this.rejectReady(t),this.rejectGotSnapshot(t)})):(e&&this.resolveReady(),setTimeout(()=>{this.subscribe(!0)},500))}onEvent(e){return this.callbacks.add("streamEvent",e)}waitFor(e,t){return t||(t=3e4),this.logger.trace(`waiting for token ${e} with timeout ${t}ms`),new Promise((n,i)=>{let r=!1;const o=this.onEvent(t=>{t.Token===e&&(this.logger.trace(`token ${e} received`),r=!0,o(),n())});setTimeout(()=>{if(!r){o();const t=`Timeout waiting for token ${e}`;this.logger.error(t),i(new Error(t))}},t)})}checkForLayoutEventMethod(){try{return-1!==this.agm.methods().map(e=>e.name).indexOf(this.StreamName)}catch(e){return!1}}addLayouts(e,t){if(!e)return;const n=e=>{const t=new di(e);si.add(t),this.callbacks.execute("added",t)};e.forEach(e=>{if(t){si.first(t=>this.compareLayouts(t,e))||n(e)}else n(e)})}removeLayouts(e){e&&e.forEach(e=>{si.removeWhere(t=>!this.compareLayouts(t,e)),this.callbacks.execute("removed",e)})}changeLayouts(e){e&&e.forEach(e=>{si.removeWhere(t=>!this.compareLayouts(t,e)),si.add(new di(e)),this.callbacks.execute("changed",e)})}renameLayouts(e){e&&e.forEach(e=>{const t=si.first(t=>this.compareLayouts(t,{type:e.type,name:e.oldName}));if(!t)throw new Error(`received rename event for unknown layout with type ${e.type} and name ${e.oldName}`);t.name=e.newName,this.callbacks.execute("renamed",t,{name:e.oldName})})}compareLayouts(e,t){return e.name===t.name&&e.type===t.type}getObjectValues(e){return e?Object.keys(e).map(t=>e[t]):[]}restoredLayout(e){e&&e.forEach(e=>{const t=si.first(t=>this.compareLayouts(t,{type:e.type,name:e.name}));this.callbacks.execute("restored",t)})}selectedDefaultLayout(e){this.callbacks.execute("default-changed",null==e?void 0:e[0])}}function _i(e){if(!e.agm)throw Error("config.agm is required");if(!e.logger)throw Error("config.logger is required");e.mode=e.mode||"slim";const t=e.logger,n=xn();let i;return i="full"===e.mode||"fullWaitSnapshot"===e.mode?new bi(e.agm,t.subLogger("stream"),n):{ready:Promise.resolve(void 0),subscribe:()=>{},onEvent:e=>()=>{},waitFor:(e,t)=>Promise.resolve(void 0),gotSnapshot:Promise.resolve(void 0)},new vi(e,i,n,t)}class Ii{constructor(e,t){this._agm=e,this._logger=t,this._registry=xn(),this._registered=!1,this.all=async()=>(await this.callGD(Ci.GetAll,{})).map(this.decorateDisplay),this.get=async e=>{const t=await this.callGD(Ci.Get,{id:e});return this.decorateDisplay(t)},this.getPrimary=async()=>(await this.all()).find(e=>e.isPrimary),this.capture=async e=>await this.callGD(Ci.Capture,{...e}),this.captureAll=async e=>await this.callGD(Ci.CaptureAll,{...e}),this.getMousePosition=async()=>await this.callGD(Ci.GetMousePosition),this.callGD=async(e,t)=>(await this._agm.invoke("T42.Displays.Command",{options:{...t},command:e},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.data,this.decorateDisplay=e=>{const t={...e,capture:t=>this.capture({id:e.id,size:t})},n=t.workArea;return n.x=n.left,n.y=t.workArea.top,t}}getByWindowId(e){return this.callGD(Ci.GetByWindowId,{id:e})}onDisplayChanged(e){return this.register(),this._registry.add("on-display-changed",e)}register(){this._registered||(this._registered=!0,this._agm.register("T42.Displays.OnEvent",(e,t)=>{const n=e.event,i=e.data;if("display-changed"===n)this._registry.execute("on-display-changed",i.displays.map(this.decorateDisplay));else this._logger.warn(`unknown event - ${n}`)}))}}var Ci;let Ai,Ti,Si;!function(e){e.Capture="capture",e.CaptureAll="captureAll",e.GetAll="getAll",e.Get="get",e.GetByWindowId="getByWindowId",e.GetMousePosition="getMousePosition"}(Ci||(Ci={}));const ki="T42.Channels.Announce";async function xi(e,t,n){var i,r;Si=n,Ai=e,"undefined"!=typeof window&&window.glue42gd&&(Ti=window.glue42gd.windowId),Ti||(Ti=e.instance.instance),await Ai.register("T42.Channels.Command",e=>{const n=e.command;if(!n)throw new Error("missing command argument");if(Si.trace(`received command "${n}" with ${JSON.stringify(e)}`),"join"===n){const n=e.channel;if(!n)throw new Error("missing argument id");return t.joinNoSelectorSwitch(n)}if("leave"===n)return t.leaveNoSelectorSwitch();if("get"===n){return{id:t.current()}}if("restrictions-changed"===n){const n=e.restrictions,i=e.swId;return void t.handleRestrictionsChanged(n,i)}if("isFdc3DataWrappingSupported"===n)return{isSupported:!0};if("join-multi"===n){const n=e.channelsToJoin;if(!n)throw new Error("missing argument channelsToJoin");return t.joinNoSelectorSwitch(new Zn(n).toString())}if("leave-multi"===n){const n=e.channelsToLeave;return t.leaveNoSelectorSwitch(new Zn(n).toString())}throw new Error(`unknown command ${n}`)});const o=await Ai.invoke(ki,{swId:Ti,instance:Ai.instance.instance},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn});return(null===(i=o.returned)||void 0===i?void 0:i.restrictions)&&t.handleRestrictionsChanged(null===(r=o.returned)||void 0===r?void 0:r.restrictions,Ti),o.returned}async function Ei(e,t){var n;await Oi("leaveChannel",{channel:e},null!==(n=t)&&void 0!==n?n:Ti)}async function Pi(e,t){await Oi("switchChannel",{newChannel:e},null!=t?t:Ti)}async function Mi(e){try{return(await Oi("getRestrictions",{},null!=e?e:Ti)).returned}catch(e){}}async function Ri(e,t,n,i){await Oi(e,{id:t,color:n,label:i})}async function Ni(e,t){if("boolean"!=typeof e.operationMode&&"string"==typeof e.operationMode)return function(e){if("single"!==e&&"multi"!==e)throw new Error(`Invalid mode: ${e}`)}(e.operationMode),{mode:e.operationMode,initialChannel:void 0};try{const e=await t.invoke(ki,{command:"getChannelsMode"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn}),n=e.returned.initialChannel;return"single"===e.returned.mode?{mode:"single",initialChannel:n}:"multi"===e.returned.mode?{mode:"multi",initialChannel:n}:{mode:"single",initialChannel:n}}catch(e){return{mode:"single",initialChannel:void 0}}}function Oi(e,t,n){const i={command:e,data:t};return n&&(i.swId=n),Ai.invoke(ki,i,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn})}const ji="___channel___",$i="latest_fdc3_type";class Wi{constructor(e){this.contexts=e}subscribe(e){this.callback=e}subscribeFor(e,t){if(!this.isChannel(e))return Promise.reject(new Error(`Channel with name: ${e} doesn't exist!`));const n=this.createContextName(e);return this.contexts.subscribe(n,(e,n,i,r,o)=>{t(e.data,e,n,null==o?void 0:o.updaterId)})}all(){return this.contexts.all().filter(e=>e.startsWith(ji)).map(e=>e.substr(13))}async getContextData(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e),n=await this.contexts.get(t);return n[$i]?this.getContextWithFdc3Data(n):(delete n[$i],n)}updateChannel(e,t){const n=this.createContextName(e);return this.contexts.update(n,t)}updateData(e,t){const n=this.createContextName(e),i=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map(e=>({path:"data."+e,value:t[e]}));return i&&e.push({path:$i,value:i}),this.contexts.setPaths(n,e)}return i&&(t[$i]=i),this.contexts.update(n,{data:t})}setPaths(e,t){const n=this.createContextName(e);if(this.contexts.setPathSupported){const e=t.map(e=>({path:"data."+e.path,value:e.value}));return e.map(t=>{const n=this.getFDC3Type(t.value);n&&e.push({path:$i,value:n})}),this.contexts.setPaths(n,e)}throw new Error("setPaths is not supported!")}async clearContextData(e){const t=this.createContextName(e);return this.contexts.update(t,{data:{},[$i]:void 0})}isChannel(e){return this.all().some(t=>t===e)}async remove(e){if(!this.isChannel(e))throw new Error(`A channel with name: ${e} doesn't exist!`);const t=this.createContextName(e);await this.contexts.destroy(t)}createContextName(e){return ji+e}getFDC3Type(e){const t=Object.keys(e).filter(e=>0===e.indexOf("fdc3_"));if(0!==t.length){if(t.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return t[0].split("_").slice(1).join("_")}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...n}=e,i={type:t.split("&").join("."),...n.data[`fdc3_${t}`]};delete n.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...n.data,fdc3:i}}}}class Di extends Wi{constructor(){super(...arguments),this.currentlySubscribedChannels=[],this.unsubscribeMap={}}async switchChannel(e){const t=new Zn(e).all();for(const e of t)this.currentlySubscribedChannels.includes(e)||await this.subscribeToChannel(e)}async leave(e){const t=new Zn(e).all();for(const e of t)this.currentlySubscribedChannels.includes(e)&&this.unsubscribeFromChannel(e)}async updateData(e,t){const n=new Zn(e).all();for(const e of n)await super.updateData(e,t)}async setPaths(e,t){const n=new Zn(e).all();for(const e of n)await super.setPaths(e,t)}isChannel(e){return new Zn(e).all().every(e=>super.isChannel(e))}async subscribeToChannel(e){const t=this.createContextName(e),n=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.callback&&this.callback(e.data,e,t,null==r?void 0:r.updaterId)});this.currentlySubscribedChannels.push(e),this.unsubscribeMap[t]=n}async unsubscribeFromChannel(e){const t=this.createContextName(e),n=this.unsubscribeMap[t];n&&(n(),delete this.unsubscribeMap[t]),this.currentlySubscribedChannels=this.currentlySubscribedChannels.filter(t=>t!==e)}}class Fi extends Wi{async switchChannel(e){this.unsubscribe();const t=this.createContextName(e);this.unsubscribeFunc=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.callback&&this.callback(e.data,e,t,null==r?void 0:r.updaterId)})}async leave(){this.callback&&this.callback({},void 0,void 0,void 0),this.unsubscribe()}unsubscribe(){this.unsubscribeFunc&&(this.unsubscribeFunc(),this.unsubscribeFunc=void 0)}}const Li=e=>{if("object"!=typeof e||Array.isArray(e))throw new Error("Provide options as an object");if(e.contextType&&("string"!=typeof e.contextType||!e.contextType.length))throw new Error("Provide options.contextType as a non-empty string")};class Gi{constructor(e,t,n){this.interop=e,this.getWindowsAPI=t,this.logger=n,this.subsKey="subs",this.changedKey="changed",this.channelsChangedKey="channelsChanged",this.isInitialJoin=!0,this.registry=xn(),this.pendingRestrictionCallbacks=new Map}async getMyChannels(e){if(!this.currentChannelID)return Promise.resolve([]);if(0===this.currentChannelID.all().length)return Promise.resolve([]);const t=[];for(const n of this.currentChannelID.all())t.push(await this.get(n,e));return t}async init(e,t,n){this.mode=t,this.shared=e,this.shared.subscribe(this.handler.bind(this)),this.subscribeForChannelRestrictionsChange();let i=n;"undefined"!=typeof window&&void 0!==window.glue42gd&&(i=window.glue42gd.initialChannel),this.currentChannelID=this.getID(i),this.logger.trace(`initialized with mode: "${t}" and initial channel: "${i}"`),this.currentChannelID.isJoinedToAnyChannel&&(this.logger.trace(`joining initial channel: "${this.currentChannelID.toString()}"`),await this.joinNoSelectorSwitch(this.currentChannelID.toString()))}subscribe(e,t){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");(null==t?void 0:t.contextType)&&Li(t);const n=jn.generateId();let i=!1;const r=()=>{i=!0},o=(null==t?void 0:t.contextType)?this.getWrappedSubscribeCallbackWithFdc3Type(e,n,t.contextType,r):this.getWrappedSubscribeCallback(e,n,r);let s;this.lastUpdate&&(s=setTimeout(()=>{i||o(this.lastUpdate.context.data,this.lastUpdate.context,{},this.lastUpdate.updaterId)},0));const a=this.registry.add(this.subsKey,o);return()=>{clearTimeout(s),this.pendingRestrictionCallbacks.delete(n),a()}}async subscribeFor(e,t,n){if("string"!=typeof e)throw new Error("Please provide the name as a string!");if("function"!=typeof t)throw new Error("Please provide the callback as a function!");(null==n?void 0:n.contextType)&&Li(n);const i=jn.generateId(),r=()=>{},o=(null==n?void 0:n.contextType)?this.getWrappedSubscribeCallbackWithFdc3Type(t,i,n.contextType,r):this.getWrappedSubscribeCallback(t,i,r),s=await this.shared.subscribeFor(e,o);return()=>{this.pendingRestrictionCallbacks.delete(i),s()}}async publish(e,t){if("object"!=typeof e)throw new Error("Please provide the data as an object!");if(t&&this.validatePublishOptions(t),"object"==typeof t)return this.publishWithOptions(e,t);const n="string"==typeof t?t:this.currentChannelID.toString();if(!n)throw new Error("Not joined to any channel!");if(!this.shared.isChannel(n))return Promise.reject(new Error(`A channel with name: ${n} doesn't exist!`));if("multi"!==this.mode){if(!(await this.getRestrictionsByChannel(n)).write)throw new Error(`Window does not have permission to write to channel ${n}`);return this.shared.updateData(n,e)}{const t=new Zn(n).all(),i=[];for(const n of t){(await this.getRestrictionsByChannel(n)).write?await this.shared.updateData(n,e):i.push(n)}if(i.length>0){const e=`Unable to publish due to restrictions to the following channels: ${i.join(", ")}`;if(i.length===t.length)throw new Error(e);this.logger.warn(e)}}}async setPaths(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,e)}if(!this.currentChannelID)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentChannelID.toString())).write)throw new Error(`Window does not have permission to write to channel ${this.currentChannelID.toString()}`);if(!Array.isArray(e))throw new Error("Path Values argument is not a valid array");return e.forEach(e=>{this.validatePathArgs(e)}),this.shared.setPaths(this.currentChannelID.toString(),e)}async setPath(e,t){if(t){if("string"!=typeof t)throw new Error("Please provide the name as a string!");if(!this.shared.isChannel(t))return Promise.reject(new Error(`A channel with name: ${t} doesn't exist!`));if(!(await this.getRestrictionsByChannel(t)).write)throw new Error(`Window does not have permission to write to channel ${t}`);return this.shared.setPaths(t,[e])}if(!this.currentChannelID)throw new Error("Not joined to any channel!");if(!(await this.getRestrictionsByChannel(this.currentChannelID.toString())).write)throw new Error(`Window does not have permission to write to channel ${this.currentChannelID.toString()}`);return this.validatePathArgs(e),this.shared.setPaths(this.currentChannelID.toString(),[e])}all(){const e=this.shared.all();return Promise.resolve(e)}async list(){const e=await this.all();return await Promise.all(e.map(e=>this.get(e)))}async get(e,t){if("string"!=typeof e)return Promise.reject(new Error("Please provide the channel name as a string!"));if(!(null==t?void 0:t.contextType))return this.shared.getContextData(e);Li(t);const n=await this.shared.getContextData(e);return this.getContextWithFdc3Type(n,t.contextType)}getMy(e){return this.currentChannelID?0===this.currentChannelID.all().length?Promise.resolve(void 0):this.get(this.currentChannelID.all()[0],e):Promise.resolve(void 0)}async join(e,t){return null!=t?(this.validateWindowIdArg(t),this.logger.trace(`joining channel ${e} for window: ${t}`),Pi(e,t)):this.joinCore(e)}async joinNoSelectorSwitch(e){return this.logger.trace(`joining channel "${e}" from command`),this.joinCore(e,!1)}leave(e){let t,n;return this.logger.trace(`leaving channel with options: ${JSON.stringify(e)}`),"string"==typeof e?t=e:"object"!=typeof e||Array.isArray(e)||null==e||(e.windowId&&(t=e.windowId),e.channel&&(n=e.channel)),"multi"===this.mode?this.leaveWhenMulti(n,t):this.leaveWhenSingle(n,t)}leaveNoSelectorSwitch(e){return this.logger.trace(`leaving channel "${e}" from command`),this.leaveCore(!1,e)}current(){return this.currentChannelID.toString()}my(){return this.current()}myChannels(){var e;return null!==(e=this.currentChannelID.all())&&void 0!==e?e:[]}onChannelsChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");let t;this.current()&&(t=setTimeout(()=>{e(this.myChannels())},0));const n=this.registry.add(this.channelsChangedKey,e);return()=>{n(),clearTimeout(t)}}changed(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");return this.current()&&setTimeout(()=>{e(this.current())},0),this.registry.add(this.changedKey,()=>{e(this.current())})}onChanged(e){return this.changed(e)}async add(e){var t;if("object"!=typeof e)throw new Error("Please provide the info as an object!");if(void 0===e.name)throw new Error("info.name is missing!");if("string"!=typeof e.name)throw new Error("Please provide the info.name as a string!");if(void 0===e.meta)throw new Error("info.meta is missing!");if("object"!=typeof e.meta)throw new Error("Please provide the info.meta as an object!");if(void 0===e.meta.color)throw new Error("info.meta.color is missing!");if("string"!=typeof e.meta.color)throw new Error("Please provide the info.meta.color as a string!");const n={name:e.name,meta:e.meta||{},data:e.data||{}};this.logger.trace(`adding channel: ${e.name}`);try{await Ri("addChannel",e.name,e.meta.color,null===(t=e.meta)||void 0===t?void 0:t.label)}catch(t){throw"message"in t&&t.message.includes(`Channel with name '${e.name}' already exists.`)&&(this.logger.trace(`channel: ${e.name} already exists - ignore channel add request`),await this.verifyChannelExists(e.name,1e4)),t}return await this.shared.updateChannel(e.name,n),n}async remove(e){if("string"!=typeof e)throw new Error("Please provide the channel name as a string!");this.logger.trace(`removing channel: ${e}`),await this.shared.remove(e),await Ri("removeChannel",e)}async getWindowsOnChannel(e){this.validateChannelArg(e);return(await this.getWindowsWithChannels({channels:[e]})).map(e=>e.window)}async getWindowsWithChannels(e){this.validateWindowsWithChannelsFilter(e);try{const t=await async function(e){return(await Oi("getChannelsInfo",{filter:e})).returned}(e),n=this.getWindowsAPI();if(null==t?void 0:t.windows)return t.windows.reduce((e,t)=>{const i=n.findById(t.windowId);return e.push({window:i,channel:t.channel,application:t.application}),e},[])}catch(e){this.logger.error("Error getting all channel enabled windows. This method is available since Glue42 3.12",e)}return[]}async restrict(e){return this.validateRestrictionConfig(e),async function(e){var t;await Oi("restrict",e,null!==(t=e.windowId)&&void 0!==t?t:Ti)}(e)}async getRestrictions(e){return e&&this.validateWindowIdArg(e),Mi(e)}async restrictAll(e){return this.validateRestrictionConfig(e),async function(e){var t;await Oi("restrictAll",e,null!==(t=e.windowId)&&void 0!==t?t:Ti)}(e)}handleRestrictionsChanged(e,t){this.registry.execute("restrictions-changed",{restrictions:e,windowId:t})}async clearChannelData(e){const t="string"==typeof e?e:this.currentChannelID.toString();if(!t)return;if(!this.shared.isChannel(t))return;return(await this.getRestrictionsByChannel(t)).write?this.shared.clearContextData(t):void 0}handler(e,t,n,i){t||i?(this.lastUpdate={context:t,updaterId:i},this.registry.execute(this.subsKey,e,t,n,i)):this.lastUpdate=void 0}async joinCore(e,t=!0){if(this.logger.trace(`joining channel "${e}" ${t?"":"from command"}`),"string"!=typeof e)throw new Error("Please provide the channel name as a string!");const n=this.getID(e);this.isInitialJoin||!this.currentChannelID.isOnChannel(n.toString())?(this.isInitialJoin=!1,await Promise.all(n.all().map(e=>this.verifyChannelExists(e))),this.currentChannelID.joinChannel(e),this.lastUpdate=void 0,this.logger.trace(`switching channel context to: "${e}" ${t?"":"from command"}`),await this.shared.switchChannel(this.currentChannelID.toString()),t&&(this.logger.trace(`switching UI channel to: "${e}" ${t?"":"from command"}`),await Pi(e),this.logger.trace(`switched UI channel to: "${e}" ${t?"":"from command"}`)),this.raiseChannelsChangedEvents(),this.logger.trace(`joined channel: ${e} ${t?"":"from command"} - current channel/s: ${this.currentChannelID.toString()}`)):this.logger.trace(`already on channel: "${e}" ${t?"":"from command"}`)}async verifyChannelExists(e,t,n){const i=e=>this.shared.all().includes(e);if(!i(e)){const r=new Promise((r,o)=>{const s=setInterval(()=>{i(e)&&(clearTimeout(a),clearInterval(s),r())},null!=n?n:100),a=setTimeout(()=>(clearInterval(s),o(new Error(`A channel with name: ${e} doesn't exist!`))),null!=t?t:3e3)});await r}}async leaveCore(e=!0,t){if(this.currentChannelID.isJoinedToAnyChannel){if(!t||this.currentChannelID.isOnChannel(t))return this.currentChannelID.leaveChannel(t),this.lastUpdate=void 0,await this.shared.leave(t),this.raiseChannelsChangedEvents(),e&&(this.logger.trace(`switching UI channel to: "${t}" ${e?"":"from command"}`),await Pi(this.currentChannelID.toString()),this.logger.trace(`switched UI channel to: "${t}" ${e?"":"from command"}`)),this.logger.trace(`left single channel: "${t}" ${e?"":"from command"} - current channel/s: "${this.currentChannelID.toString()}"`),Promise.resolve();this.logger.trace(`leave called ${e?"":"from command"} when not joined to channel: "${t}"`)}else this.logger.trace(`leave called ${e?"":"from command"} when not joined to any channel change selector`)}async leaveCoreMulti(e=!0,t){this.logger.trace(`leaving multi channel: "${t.toString()}" ${e?"":"from command"}`);if(!this.currentChannelID.all().some(e=>t.isOnChannel(e))||!this.currentChannelID.isJoinedToAnyChannel)return void this.logger.trace(`leave called ${e?"":"from command"} when not joined to any channel`);const n=t.toString();return this.currentChannelID.leaveChannel(n),await this.shared.leave(n),this.lastUpdate=void 0,this.raiseChannelsChangedEvents(),e&&(this.logger.trace(`switching UI channel to: "${n}" ${e?"":"from command"}`),await Ei(n),this.logger.trace(`switched UI channel to: "${n}" ${e?"":"from command"}`)),this.logger.trace(`left multi channel: "${n}" ${e?"":"from command"} - current channel/s: ${this.currentChannelID.toString()}`),Promise.resolve()}raiseChannelsChangedEvents(){this.registry.execute(this.changedKey,this.currentChannelID.toString()),this.registry.execute(this.channelsChangedKey,this.currentChannelID.all())}async getRestrictionsByChannel(e){var t;const n=null!==(t=this.channelRestrictions)&&void 0!==t?t:await Mi();if(!n||!Array.isArray(n.channels)||!n.channels.find(t=>t.name===e))return{read:!0,write:!0};return n.channels.find(t=>t.name===e)}onRestrictionsChanged(e,t,n){this.pendingRestrictionCallbacks.set(t,{cb:e,channelName:n}),this.onRestrictionsChangedSub||(this.onRestrictionsChangedSub=this.registry.add("restrictions-changed",({restrictions:e})=>{this.logger.trace(`restrictions changed - ${JSON.stringify(e)}`),this.pendingRestrictionCallbacks.forEach(({cb:t,channelName:n},i)=>{const r=e.channels.find(e=>e.name===n);r?r.read&&(this.pendingRestrictionCallbacks.delete(i),0===this.pendingRestrictionCallbacks.values.length&&this.onRestrictionsChangedSub&&(this.onRestrictionsChangedSub(),this.onRestrictionsChangedSub=null),t()):this.logger.trace(`channel "${n}" not found in restrictions`)})}))}subscribeForChannelRestrictionsChange(){this.registry.add("restrictions-changed",e=>{this.logger.trace(`channel restrictions changed - ${JSON.stringify(e.restrictions)}`),this.channelRestrictions=e.restrictions})}validatePathArgs(e){if(!e)throw new Error("Please provide a valid path value argument");if("object"!=typeof e)throw new Error(`Path Value argument is not a valid object: ${JSON.stringify(e)}`);if(!e.path)throw new Error(`path property is missing from Path Value argument: ${JSON.stringify(e)}`);if(!e.value)throw new Error(`value property is missing from Path Value argument: ${JSON.stringify(e)}`);if("string"!=typeof e.path)throw new Error(`path property is not a valid string from the Path Value argument: ${JSON.stringify(e)}`)}validatePublishOptions(e){if("string"!=typeof e&&"object"!=typeof e||Array.isArray(e))throw new Error("Provide options as a string or an object");if("object"!=typeof e){if("string"===e&&!e.length)throw new Error("Provide options as a non-empty string")}else this.validatePublishOptionsObject(e)}validatePublishOptionsObject(e){if("object"!=typeof e||Array.isArray(e))throw new Error("Provide options as an object");if(e.name&&("string"!=typeof e.name||!e.name.length))throw new Error("Provide options.name as a non-empty string");if(Object.keys(e).includes("fdc3")&&"boolean"!=typeof e.fdc3)throw new Error("Provide options.fdc3 as a boolean")}async publishWithOptions(e,t){const n=t.name||this.currentChannelID.toString();if(!this.shared.isChannel(n))throw new Error(`A channel with name: ${t.name} doesn't exist!`);if(!n)throw new Error("Cannot publish to channel, because not joined to a channel!");if(!(await this.getRestrictionsByChannel(n)).write)throw new Error(`Window does not have permission to write to channel ${this.currentChannelID.toString()}`);return t.fdc3?this.publishFdc3Data(n,e):this.shared.updateData(n,e)}async publishFdc3Data(e,t){var n;if("string"!=typeof t.type||!(null===(n=t.type)||void 0===n?void 0:n.length))throw new Error("Expected a valid FDC3 Context with compulsory 'type' field");const{type:i,...r}=t,o=i.split(".").join("&"),s={[`fdc3_${o}`]:r};return this.shared.updateData(e,s)}getWrappedSubscribeCallback(e,t,n){return async(i,r,o,s)=>{n();const a=await this.getRestrictionsByChannel(r.name),c=this.getDataWithFdc3Encoding(r,o);a.read?e(c,r,s):this.onRestrictionsChanged(()=>e(c,r,s),t,r.name)}}getWrappedSubscribeCallbackWithFdc3Type(e,t,n,i){const r={replayed:!1};return async(o,s,a,c)=>{i();const d=()=>{const{data:t,latest_fdc3_type:i}=s,o=`fdc3_${n.split(".").join("&")}`;if(!t||!t[o]||a.data&&!a.data[o])return;if(r.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:i,searchedType:n,callback:e,context:s,updaterId:c});const d={type:n,...t[o]};e({fdc3:d},s,c),r.replayed=!0};(await this.getRestrictionsByChannel(s.name)).read?d():this.onRestrictionsChanged(d,t,s.name)}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:r,updaterId:o}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...r.data[`fdc3_${t}`]}},r,o)}getContextWithFdc3Type(e,t){var n,i;if((null===(i=null===(n=e.data)||void 0===n?void 0:n.fdc3)||void 0===i?void 0:i.type)===t)return{name:e.name,meta:e.meta,data:{fdc3:e.data.fdc3}};const r=`fdc3_${t.split(".").join("&")}`;if(!e.data[r])return{name:e.name,meta:e.meta,data:{}};const o={type:t,...e.data[r]};return{name:e.name,meta:e.meta,data:{fdc3:o}}}getDataWithFdc3Encoding(e,t){const{data:n,latest_fdc3_type:i}=e,r=`fdc3_${i}`;if(!i||t.data&&!t.data[r])return n;const o={type:i.split("&").join("."),...n[r]},{[r]:s,...a}=n;return{...a,fdc3:o}}getID(e){return"multi"===this.mode?new Zn(e):new Qn(e)}leaveWhenSingle(e,t){return t?(this.logger.trace(`leaving single channel "${e}" for window: "${t}"`),Pi(void 0,t)):(this.logger.trace(`leaving single channel "${e}" for our window`),this.leaveCore(!0,e))}async leaveWhenMulti(e,t){if(t)return this.logger.trace(`leaving multi channel "${e}" for window: "${t}"`),Ei(e,t);{const t=e?new Zn(e):this.currentChannelID;return this.logger.trace(`leaving multi channel "${t.toString()}" for our window`),this.leaveCoreMulti(!0,t)}}validateWindowIdArg(e){if("string"!=typeof e)throw new Error("The window ID must be a non-empty string!");if(!this.getWindowsAPI().findById(e))throw new Error(`Window with ID "${e}" doesn't exist!`)}validateChannelArg(e){if(!e)throw new Error("Please provide a valid Channel name as a non-empty string!");if("string"!=typeof e)throw new Error("The Channel name must be a non-empty string!");if(this.shared.all().every(t=>t!==e))throw new Error(`Channel "${e}" does not exist!"`)}validateWindowsWithChannelsFilter(e){if(void 0!==e&&(null===e||Array.isArray(e)||"object"!=typeof e))throw new Error("The `filter` argument must be a valid object!")}isRestrictions(e){return"name"in e}validateRestrictionConfig(e){if(null==e||Array.isArray(e)||"object"!=typeof e)throw new Error("The `restrictions` argument must be a valid object with Channel restrictions!");if(this.isRestrictions(e)&&"string"!=typeof e.name)throw new Error("The `name` restriction property must be a non-empty string!");if(null!==e.read&&void 0!==e.read&&"boolean"!=typeof e.read)throw new Error("The `read` restriction property must be a boolean value!");if(null!==e.write&&void 0!==e.write&&"boolean"!=typeof e.write)throw new Error("The `write` restriction property must be a boolean value!");if(!(null!==e.read&&void 0!==e.read||null!==e.write&&void 0!==e.write))throw new Error("It's required to set either the `read` or the `write` property of the Channel restriction object!");null!==e.windowId&&void 0!==e.windowId&&this.validateWindowIdArg(e.windowId)}}const Ui="T42.Hotkeys.Command";class Hi{constructor(e){this.agm=e,this.registry=xn(),this.firstHotkey=!0,this.hotkeys=new Map}async register(e,t){if(void 0===e)throw new Error("Hotkey parameter missing");if("string"==typeof e)e={hotkey:e};else{if(!e.hotkey)throw new Error("Info's hotkey parameter missing");e={hotkey:e.hotkey,description:e.description}}const n=this.formatHotkey(e.hotkey);if(this.hotkeys.has(n))throw new Error(`Shortcut for ${n} already registered`);this.firstHotkey&&(this.firstHotkey=!1,await this.registerInvokeAGMMethod()),this.registry.add(n,t),await this.agm.invoke(Ui,{command:"register",hotkey:n,description:e.description},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}),this.hotkeys.set(n,e)}async unregister(e){if(void 0===e)throw new Error("hotkey parameter missing");if("string"!=typeof e)throw new Error("hotkey parameter must be string");const t=this.formatHotkey(e);await this.agm.invoke(Ui,{command:"unregister",hotkey:t},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}),this.hotkeys.delete(t),this.registry.clearKey(t)}async unregisterAll(){await this.agm.invoke(Ui,{command:"unregisterAll"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}),this.hotkeys.clear(),this.registry.clear()}isRegistered(e){const t=this.formatHotkey(e);return this.hotkeys.has(t)}registerInvokeAGMMethod(){return this.agm.register("T42.Hotkeys.Invoke",e=>{const t=e.key.toLowerCase(),n=this.hotkeys.get(t);this.registry.execute(t,n)})}formatHotkey(e){if(e)return e.replace(/\s/g,"").toLowerCase()}}class Bi{constructor(){this.RESTART_METHOD_NAME="T42.ACS.Restart",this.SHUTDOWN_METHOD_NAME="T42.ACS.Shutdown",this.ON_SHUTTING_DOWN_METHOD_NAME="T42.ACS.OnGDShutdown",this._isMethodRegistered=!1,this._registry=xn(),this._agmInvoke=(e,t)=>(t=t||{},new Promise((n,i)=>{this._interop.invoke(e,t,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}).then(e=>{n(e.returned)}).catch(e=>i(new Error(e.message||"Platform API call failed")))}))}init(e,t){this._interop=e,this._logger=t}restart(e){return this._agmInvoke(this.RESTART_METHOD_NAME,e)}shutdown(e){return this._agmInvoke(this.SHUTDOWN_METHOD_NAME,e)}onShuttingDown(e){return this.registerShutdownMethod(),this._registry.add("on-shutting-down",e)}toAPI(){return{restart:this.restart.bind(this),shutdown:this.shutdown.bind(this),onShuttingDown:this.onShuttingDown.bind(this)}}registerShutdownMethod(){this._isMethodRegistered||this._interop.register(this.ON_SHUTTING_DOWN_METHOD_NAME,async e=>{try{const t=await Promise.all(this._registry.execute("on-shutting-down",e));return{prevent:t.some(e=>e.prevent)}}catch(e){return this._logger.error("Error in onShuttingDown callbacks:",e),{prevent:!1}}}).then(()=>{this._logger.info("Successfully registered onShuttingDown method"),this._isMethodRegistered=!0}).catch(e=>{this._logger.error("Failed to register onShuttingDown method:",e)})}}var Ji="6.18.0",qi=e=>{function t(e,t,i){if("boolean"==typeof e&&!e)return;const r=n(e,t,i);return void 0!==r?"object"==typeof e?(e.mode=r,e):{mode:r}:void 0}function n(e,t,i){return"object"==typeof e?n(e.mode,t,i).toString():void 0===e?"boolean"!=typeof t||t?"boolean"==typeof t&&t?void 0===i?t:i:void 0===t?void 0:t:void 0:"boolean"==typeof e?e?void 0===i?t:i:void 0:e}const i="undefined"!=typeof window&&"undefined"!=typeof document&&"htmlContainer"in window,r=!jn.isNode()&&(!!i&&"trackMyTypeAndInitiatedFromMe"),o="slim",s=o,a="boolean"==typeof e.exposeAPI||"boolean"==typeof e.exposeGlue;return{layouts:t(e.layouts,o,s),activities:t(e.activities,r,"trackMyTypeAndInitiatedFromMe"),appManager:t(e.appManager,!0,"startOnly"),apps:t(e.apps,!0,!0),windows:t(e.windows,!0,!0),channels:t("boolean"==typeof e.channels?e.channels:!("object"!=typeof e.channels||"boolean"!=typeof e.channels.enabled||!e.channels.enabled)&&{mode:!0,...e.channels},!1,!0),displays:t(e.displays,!0,!0),exposeAPI:a||!0}};class Vi{constructor(e){this.options=e,this.callbacks=xn(),this.actions=e.actions,this.body=e.body,this.badge=e.badge,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.title=e.title}close(){throw new Error("Method not implemented.")}addEventListener(e,t,n){this.callbacks.add(e,t)}removeEventListener(e,t,n){}dispatchEvent(e){return this.callbacks.execute(e.type,e),!0}}class zi{constructor(e,t){this.interop=e,this.onStreamEvent=t}onVisibilityChanged(e){return this.onStreamEvent("on-panel-visibility-changed",e)}toggle(){return this.interop.invoke("T42.Notifications.Show",void 0,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}show(){return this.interop.invoke("T42.Notifications.Show",{show:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}hide(){return this.interop.invoke("T42.Notifications.Hide")}async isVisible(){return(await this.interop.invoke("T42.Notifications.Execute",{command:"isPanelVisible"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.panelVisible}toAPI(){return{onVisibilityChanged:this.onVisibilityChanged.bind(this),toggle:this.toggle.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),isVisible:this.isVisible.bind(this)}}}class Ki{constructor(e,t){this.interop=e,this.NotificationsSubscribeStream="T42.GNS.Subscribe.Notifications",this.NotificationsCounterStream="T42.Notifications.Counter",this.RaiseNotificationMethodName="T42.GNS.Publish.RaiseNotification",this.NotificationsExecuteMethod="T42.Notifications.Execute",this.NotificationFilterMethodName="T42.Notifications.Filter",this.methodsRegistered=!1,this.NOTIFICATIONS_CONFIGURE_METHOD_NAME="T42.Notifications.Configure",this.methodNameRoot="T42.Notifications.Handler-"+jn.generateId(),this.nextId=0,this.notifications={},this.registry=xn(),this.subscribedForNotifications=!1,this.subscribedCounterStream=!1,this.subscriptionsCountForNotifications=0,this.subscriptionsCountForCounter=0,this.logger=t.subLogger("notifications"),this._panel=new zi(e,this.onStreamEventCore.bind(this)),this._panelAPI=this._panel.toAPI(),this.subscribeInternalEvents()}get maxActions(){return 10}get panel(){return this._panelAPI}async raise(e){var t;this.logger.debug(`raising notification with options: ${JSON.stringify(e)}`);const n=await this.createNotification(e),i=new Vi(e);this.notifications[n.id]=i;try{const e=await this.interop.invoke(this.RaiseNotificationMethodName,{notification:n},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn});i.id=null===(t=e.returned)||void 0===t?void 0:t.id,this.logger.debug(`notification raised with id: ${i.id}`)}catch(t){this.logger.error(`failed to raise notification with options: ${JSON.stringify(e)}`,t);const n=t.message;setTimeout(()=>{this.handleNotificationErrorEvent(i,n)},1)}return i}async setFilter(e){return(await this.interop.invoke(this.NotificationFilterMethodName,e,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}async getFilter(){return(await this.interop.invoke(this.NotificationFilterMethodName,void 0,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}async configure(e){var t,n,i,r,o,s,a,c;if(!e||Array.isArray(e))throw new Error("Invalid options - should be an object.");if(0===Object.values(e).length)throw new Error("The argument must be a non-empty object.");if(void 0!==e.enable&&"boolean"!=typeof e.enable)throw new Error("Expected type of enabled - boolean.");if(void 0!==e.enableToasts&&"boolean"!=typeof e.enableToasts)throw new Error("Expected type of enableToasts - boolean.");if(void 0!==e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("Expected type of toastExpiry - number.");if(e.sourceFilter&&"object"!=typeof e.sourceFilter)throw new Error("Expected type of sourceFilter - object.");if((null===(t=e.sourceFilter)||void 0===t?void 0:t.allowed)&&!Array.isArray(null===(n=e.sourceFilter)||void 0===n?void 0:n.allowed))throw new Error("Expected type of sourceFilter.allowed - array.");if((null===(i=e.sourceFilter)||void 0===i?void 0:i.blocked)&&!Array.isArray(null===(r=e.sourceFilter)||void 0===r?void 0:r.blocked))throw new Error("Expected type of sourceFilter.blocked - array.");if(e.toasts&&"object"!=typeof e.toasts)throw new Error("Expected type of (options.toasts - object.");if((null===(o=e.toasts)||void 0===o?void 0:o.mode)&&"string"!=typeof e.toasts.mode)throw new Error("Expected type of (options.toasts.mode - string.");if((null===(s=e.toasts)||void 0===s?void 0:s.stackBy)&&"string"!=typeof e.toasts.stackBy)throw new Error("Expected type of (options.toasts.stackBy - string.");if(e.placement&&"object"!=typeof e.placement)throw new Error("Expected type of (options.placement - object.");if((null===(a=e.placement)||void 0===a?void 0:a.toasts)&&"string"!=typeof e.placement.toasts)throw new Error("Expected type of (options.placement.toasts - string.");if((null===(c=e.placement)||void 0===c?void 0:c.panel)&&"string"!=typeof e.placement.panel)throw new Error("Expected type of (options.placement.panel - string.");if(void 0!==e.closeNotificationOnClick&&"boolean"!=typeof e.closeNotificationOnClick)throw new Error("Expected type of closeNotificationOnClick - boolean.");return(await this.interop.invoke(this.NOTIFICATIONS_CONFIGURE_METHOD_NAME,e,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}async getConfiguration(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"getConfiguration"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}async list(){return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"list",data:{statesVersion2:!0}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.notifications}async updateData(e,t){const n={key:"data",value:{stringValue:JSON.stringify(t,(e,t)=>void 0===t?null:t)}};return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"create-or-update-attribute",data:{id:e,attribute:n}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}onRaised(e){return this.onStreamEventCore("on-notification-raised",e)}onStateChanged(e){return this.onStreamEventCore("on-state-changed",e)}onClosed(e){return this.onStreamEventCore("on-notification-closed",e)}onConfigurationChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-configuration-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}onCounterChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribeForCounterStream();const t=this.registry.add("on-counter-changed",e);return()=>{t(),this.closeStreamCounterSubscriptionIfNoNeeded()}}onDataChanged(e){if("function"!=typeof e)throw new Error("Please provide the callback as a function!");this.subscribe();const t=this.registry.add("on-notification-data-changed",e);return()=>{t(),this.closeStreamSubscriptionIfNoNeeded()}}async clearAll(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAll"},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async clearOld(){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearAllOld",data:{statesVersion2:!0}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async clear(e){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clear",data:{id:e}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async clearMany(e){this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"clearMany",data:{notifications:e}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async click(e,t,n){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"click",data:{id:e,action:t,options:n}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async snooze(e,t){await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snooze",data:{id:e,duration:t}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async snoozeMany(e,t){if(!t)throw new Error("The 'duration' argument cannot be null or undefined");if("number"!=typeof t)throw new Error("The 'duration' argument must be a valid number");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"snoozeMany",data:{notifications:e,duration:t}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async setState(e,t){if(!e)throw new Error("The 'id' argument cannot be null or undefined");if("string"!=typeof e)throw new Error("The 'id' argument must be a string");if(!t)throw new Error("The 'state' argument cannot be null or undefined");this.validateState(t),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateState",data:{id:e,state:t}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async setStates(e,t){if(!t)throw new Error("The 'state' argument cannot be null or undefined");if("string"!=typeof t)throw new Error("The 'state' argument must be a valid string");this.validateNotificationsArr(e),await this.interop.invoke(this.NotificationsExecuteMethod,{command:"updateStates",data:{notifications:e,state:t}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}toAPI(){return{maxActions:this.maxActions,panel:this._panel.toAPI(),raise:this.raise.bind(this),setFilter:this.setFilter.bind(this),getFilter:this.getFilter.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onStateChanged:this.onStateChanged.bind(this),onClosed:this.onClosed.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onCounterChanged:this.onCounterChanged.bind(this),onDataChanged:this.onDataChanged.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),clear:this.clear.bind(this),click:this.click.bind(this),setState:this.setState.bind(this),updateData:this.updateData.bind(this),snooze:this.snooze.bind(this),snoozeMany:this.snoozeMany.bind(this),clearMany:this.clearMany.bind(this),setStates:this.setStates.bind(this),import:this.importNotifications.bind(this)}}async importNotifications(e){if(!e||!Array.isArray(e)||0===e.length)throw new Error("Notifications argument must be a valid array with notification options");const t=await Promise.all(e.map(e=>this.createNotification(e,!0)));return(await this.interop.invoke(this.NotificationsExecuteMethod,{command:"importNotifications",data:{notificationSettings:t}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.notifications}async createNotification(e,t){var n,i,r,o;if(this.validate(e,t),!this.methodsRegistered){const e=[];for(let t=0;t<this.maxActions;t++)e.push(this.interop.register(`${this.methodNameRoot}_${t}`,this.handleNotificationEvent.bind(this)));this.methodsRegistered=!0,await Promise.all(e)}const s=null!==(n=e.id)&&void 0!==n?n:jn.generateId(),a=null!==(i=e.type)&&void 0!==i?i:"Notification",c={id:s,state:null!==(r=e.state)&&void 0!==r?r:"Active",title:e.title,type:a,severity:null!==(o=e.severity)&&void 0!==o?o:"None",description:e.body,glueRoutingDetailMethodName:`${this.methodNameRoot}_0`,actions:[],sourceId:s,source:e.source,publishExtraEvents:!0,clickInterop:e.clickInterop};return e.actions&&this.handleActions(e,s,c),this.handleOptions(e,c),c}onStreamEventCore(e,t){if("function"!=typeof t)throw new Error("Please provide the callback as a function!");this.subscribe();const n=this.registry.add(e,t);return()=>{n(),this.closeStreamSubscriptionIfNoNeeded()}}handleOptions(e,t){if(e.icon&&(t.attributes=t.attributes||[],t.attributes.push({key:"icon",value:{stringValue:e.icon}})),e.data){t.attributes=t.attributes||[];const n=JSON.stringify(e.data);t.attributes.push({key:"data",value:{stringValue:n}})}"number"==typeof e.panelExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"panelExpiry",value:{stringValue:e.panelExpiry.toString()}})),"number"==typeof e.toastExpiry&&(t.attributes=t.attributes||[],t.attributes.push({key:"toastExpiry",value:{stringValue:e.toastExpiry.toString()}}))}handleActions(e,t,n){var i,r,o;const s=e.actions.slice(0,this.maxActions);let a=0;for(const e of s){const s={g42notificationId:t,g42action:e.action,g42interopMethod:null===(i=e.interop)||void 0===i?void 0:i.method,g42interopTarget:null===(r=e.interop)||void 0===r?void 0:r.target,g42interopArguments:JSON.stringify(null===(o=e.interop)||void 0===o?void 0:o.arguments)},c=Object.keys(s).map(e=>({name:e,value:{stringValue:s[e]}})),d={name:`${this.methodNameRoot}_${a}`,description:e.title,displayName:e.title,displayPath:e.displayPath,displayId:e.displayId,parameters:c};n.actions.push(d),a++}}validate(e,t){if(!e)throw new Error("invalid options - should be an object");if("object"!=typeof e)throw new Error("invalid options - should be an object");if(!e.title)throw new Error("invalid options - should have a title");if("string"!=typeof e.title)throw new Error("invalid options - title should be a string");if(e.severity&&"string"!=typeof e.severity)throw new Error("invalid options - severity should be a string");if(e.panelExpiry&&"number"!=typeof e.panelExpiry)throw new Error("invalid options - panelExpiry should be a number");if(e.toastExpiry&&"number"!=typeof e.toastExpiry)throw new Error("invalid options - toastExpiry should be a number");e.state&&this.validateState(e.state,t)}validateState(e,t){if("string"!=typeof e)throw new Error("The 'state' argument must be a string");const n=["Active","Acknowledged","Stale"];if(t&&n.push("Seen","Snoozed","Processing","Closed"),!n.includes(e))throw new Error(`The state argument: ${e} is not valid!`)}subscribe(){this.subscriptionsCountForNotifications++,this.subscribedForNotifications||(this.subscribedForNotifications=!0,this.logger.debug(`attempting to subscribe to "${this.NotificationsSubscribeStream}".`),this.interop.subscribe(this.NotificationsSubscribeStream,{arguments:{sendDeltaOnly:!0,statesVersion2:!0},waitTimeoutMs:Nn,methodResponseTimeout:Nn}).then(e=>{this.subscriptionForNotifications=e,this.logger.debug(`successfully subscribed to "${this.NotificationsSubscribeStream}".`),e.onData(({data:e})=>{this.handleData(e)}),e.onClosed((...e)=>{this.subscribedForNotifications=!1,this.logger.debug(`stream subscription Closed - ${JSON.stringify(e)}`)}),e.onFailed((...e)=>{this.subscribedForNotifications=!1,this.logger.warn(`stream subscription Failed - ${JSON.stringify(e)}`)})}).catch(e=>{this.subscribedForNotifications=!1,this.logger.error(`unable to subscribe to "${this.NotificationsSubscribeStream}"`,e)}))}subscribeForCounterStream(){this.subscriptionsCountForCounter++,this.subscribedCounterStream||(this.subscribedCounterStream=!0,this.logger.debug(`attempting to subscribe to "${this.NotificationsCounterStream}".`),this.interop.subscribe(this.NotificationsCounterStream,{arguments:{sendDeltaOnly:!0},waitTimeoutMs:Nn,methodResponseTimeout:Nn}).then(e=>{this.subscriptionForCounter=e,this.logger.debug(`successfully subscribed to "${this.NotificationsCounterStream}".`),e.onData(({data:e})=>{this.registry.execute("on-counter-changed",{count:e.count})}),e.onClosed((...e)=>{this.subscribedCounterStream=!1,this.logger.debug(`stream subscription Closed - ${JSON.stringify(e)}`)}),e.onFailed((...e)=>{this.subscribedCounterStream=!1,this.logger.warn(`stream subscription Failed - ${JSON.stringify(e)}`)})}).catch(e=>{this.subscribedCounterStream=!1,this.logger.error(`unable to subscribe to "${this.NotificationsCounterStream}"`,e)}))}subscribeInternalEvents(){this.registry.add("on-notification-closed",e=>{this.handleOnClosed(e)}),this.registry.add("on-notification-raised",e=>{this.handleOnShow(e.id)})}handleData(e){var t;try{"items"in e&&Array.isArray(e.items)?this.handleItemsData(e):"deltas"in e&&Array.isArray(e.deltas)&&this.handleDeltas(e),"configuration"in e&&"object"==typeof e.configuration&&(this.logger.debug(`received configuration ${JSON.stringify(e.configuration)} from the stream`),this.registry.execute("on-configuration-changed",e.configuration,e.configuration.allApplications)),"command"in e&&"string"==typeof e.command&&(this.logger.debug(`received command "${null!==(t=e.command)&&void 0!==t?t:JSON.stringify(e)}" from the stream`),"showPanel"!==e.command&&"hidePanel"!==e.command||this.registry.execute("on-panel-visibility-changed","showPanel"===e.command))}catch(e){this.logger.error("failed to parse data from the stream",e)}}handleItemsData(e){const t=e.items;this.logger.debug(`received ${t.length} notifications from the stream`);const n=t;if(e.isSnapshot)n.forEach(e=>{this.registry.execute("on-notification-raised",e)});else{const e=n[0];"Closed"===e.state?this.registry.execute("on-notification-closed",{id:e.id}):this.registry.execute("on-notification-raised",e)}}handleDeltas(e){e.deltas.forEach(e=>{var t;const n=e.id,i=null!==(t=e.delta)&&void 0!==t?t:{};if("Closed"===i.state)this.registry.execute("on-notification-closed",{id:n,...i});else if(i.state)this.registry.execute("on-state-changed",{id:n},i.state);else if(i.attributes){const e=i.attributes.find(e=>"data"===e.key);e&&this.registry.execute("on-notification-data-changed",{id:n},JSON.parse(e.value.stringValue))}})}handleOnClosed(e){const{notification:t,key:n}=this.getNotification(e);t&&(this.handleEvent(t,"close"),delete this.notifications[n])}handleOnShow(e){this.logger.debug(`handling on show for notification with id: ${e}`);const{notification:t}=this.getNotification(e);t&&this.handleEvent(t,"show")}getNotification(e){let t,n;for(const i in this.notifications)if(this.notifications[i].id===e){t=this.notifications[i],n=i;break}return{notification:t,key:n}}handleNotificationEvent(e){const t=this.getGnsNotificationArgs(e);if("unknown"===t.event)return void this.logger.warn(`unknown event type: ${t.event} for notification with id: ${t.notificationId}`);const n=this.notifications[t.notificationId];n?this.handleNotificationEventCore(n,t):this.logger.warn(`missing notification for event type: ${t.event} with id: ${t.notificationId}`)}handleNotificationEventCore(e,t){switch(this.logger.debug(`handling notification event: ${t.event} for notification with id: ${e.id}`),t.event){case"action":return this.handleNotificationActionEvent(e,t.notificationActionPayload);case"click":return this.handleNotificationClickEvent(e);case"close":return this.handleEvent(e,"close");case"error":return this.handleNotificationErrorEvent(e,t.error);case"show":return this.handleEvent(e,"show");default:this.logger.warn(`unknown event type: ${t.event} for notification with id: ${e.id}`)}}handleNotificationActionEvent(e,t){const n={type:"onaction",action:t.g42action};e.onaction&&e.onaction(n),this.logger.debug(`dispatching event "onaction" for notification with id: ${e.id}, action: ${t.g42action}`),e.dispatchEvent(n)}handleNotificationClickEvent(e){const t={type:"onclick"};e.onclick&&e.onclick(t),this.logger.debug(`dispatching event "onclick" for notification with id: ${e.id}`),e.dispatchEvent(t)}handleEvent(e,t){var n;const i={type:t},r=`on${t}`;null===(n=e[r])||void 0===n||n.call(e,i),this.logger.debug(`dispatching event "${r}" for notification with id: ${e.id}`),e.dispatchEvent(i)}handleNotificationErrorEvent(e,t){const n={type:"onerror",error:t};e.onerror&&e.onerror(n),this.logger.error(`dispatching event "onerror" for notification with id: ${e.id}`,t),e.dispatchEvent(n)}getGnsNotificationArgs(e){var t;let n;const i=null===(t=e.notification)||void 0===t?void 0:t.event;return n=i?{event:i,notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:this.getBackwardGnsNotificationArgs(e),n}getBackwardGnsNotificationArgs(e){var t;let n;return n=e.g42notificationId?{event:"action",notificationId:e.g42notificationId,notificationActionPayload:e}:(null===(t=e.notification)||void 0===t?void 0:t.sourceNotificationId)?{event:"click",notificationId:e.notification.sourceNotificationId,notificationActionPayload:e}:{event:"unknown",notificationId:void 0,notificationActionPayload:e},n}closeStreamSubscriptionIfNoNeeded(){this.subscriptionsCountForNotifications--,this.subscriptionForNotifications&&0===this.subscriptionsCountForNotifications&&(this.subscriptionForNotifications.close(),this.subscriptionForNotifications=void 0)}closeStreamCounterSubscriptionIfNoNeeded(){this.subscriptionsCountForCounter--,this.subscriptionForCounter&&0===this.subscriptionsCountForCounter&&(this.subscriptionForCounter.close(),this.subscriptionForCounter=void 0)}validateNotificationsArr(e){if(!Array.isArray(e))throw new Error("The 'notifications' argument must be an array with valid notification IDs");if(e.some(e=>"string"!=typeof e))throw new Error("The 'notifications' argument must contain only valid string notification IDs")}}class Qi{constructor(e,t){this.contexts=e,this.interop=t,this.registry=xn(),this.isSubscribed=!1,this.getConfiguration()}async list(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");return(await this.getAll()).returned.all}async getCurrent(){if(await this.getConfiguration(),!this.getMethodName)throw new Error("not supported");const e=await this.getAll();return e.returned.all.find(t=>t.name===e.returned.selected)}async select(e){if(await this.getConfiguration(),!this.setMethodName)throw new Error("not supported");await this.interop.invoke(this.setMethodName,{theme:e})}onChanged(e){if(!e)throw new Error("Callback argument is required");if(e&&"function"!=typeof e)throw new Error("Callback argument must be a function");return this.subscribe(),this.registry.add("changed",e)}async getConfiguration(){try{if(this.sharedContextName)return;const e=await this.interop.invoke("T42.Themes.Configuration");this.sharedContextName=e.returned.sharedContextName,this.getMethodName=e.returned.getThemesMethodName,this.setMethodName=e.returned.setThemesMethodName}catch(e){return}}async getAll(){return await this.getConfiguration(),await this.interop.invoke(this.getMethodName)}async subscribe(){await this.getConfiguration(),this.isSubscribed||(this.isSubscribed=!0,this.contexts.subscribe(this.sharedContextName,e=>{e&&e.all&&e.selected&&this.registry.execute("changed",e.all.find(t=>t.name===e.selected))}))}}const Zi=["name","title","version","customProperties","icon","caption","type"],Xi=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var Yi=function(e){return{ok:!0,result:e}},er=function(e){return{ok:!1,error:e}},tr=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:Yi(e(t.result,n.result))},nr=function(e,t){return!0===t.ok?t:er(e(t.error))},ir=function(){return ir=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},ir.apply(this,arguments)};function rr(e,t){if(e===t)return!0;if(null===e&&null===t)return!0;if(typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!rr(e[n],t[n]))return!1;return!0}var i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(n=0;n<i.length;n++){if(!t.hasOwnProperty(i[n]))return!1;if(!rr(e[i[n]],t[i[n]]))return!1}return!0}}var or=function(e){return Array.isArray(e)},sr=function(e){return"object"==typeof e&&null!==e&&!or(e)},ar=function(e,t){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(t)},cr=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},dr=function(e,t){var n=t.at,i=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}(t,["at"]);return ir({at:e+(n||"")},i)},hr=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return nr(function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}},n.decode(e))},this.runPromise=function(e){return!0===(t=n.run(e)).ok?Promise.resolve(t.result):Promise.reject(t.error);var t},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(t){return new e(function(e){return function(e,t){return!0===t.ok?Yi(e(t.result)):t}(t,n.decode(e))})},this.andThen=function(t){return new e(function(e){return function(e,t){return!0===t.ok?e(t.result):t}(function(n){return t(n).decode(e)},n.decode(e))})},this.where=function(t,i){return n.andThen(function(n){return t(n)?e.succeed(n):e.fail(i)})}}return e.string=function(){return new e(function(e){return"string"==typeof e?Yi(e):er({message:ar("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?Yi(e):er({message:ar("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?Yi(e):er({message:ar("a boolean",e)})})},e.constant=function(t){return new e(function(e){return rr(e,t)?Yi(t):er({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(sr(e)&&t){var n={};for(var i in t)if(t.hasOwnProperty(i)){var r=t[i].decode(e[i]);if(!0!==r.ok)return void 0===e[i]?er({message:"the key '"+i+"' is required but was not present"}):er(dr("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return Yi(n)}return sr(e)?Yi(e):er({message:ar("an object",e)})})},e.array=function(t){return new e(function(e){if(or(e)&&t){return e.reduce(function(e,n,i){return tr(function(e,t){return e.concat([t])},e,function(e,n){return nr(function(e){return dr("["+n+"]",e)},t.decode(e))}(n,i))},Yi([]))}return or(e)?Yi(e):er({message:ar("an array",e)})})},e.tuple=function(t){return new e(function(e){if(or(e)){if(e.length!==t.length)return er({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e[i]);if(!r.ok)return er(dr("["+i+"]",r.error));n[i]=r.result}return Yi(n)}return er({message:ar("a tuple of length "+t.length,e)})})},e.union=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];return new e(function(e){return[t,n].concat(i).reduce(function(t,n){return tr(Object.assign,t,n.decode(e))},Yi({}))})},e.anyJson=function(){return new e(function(e){return Yi(e)})},e.unknownJson=function(){return new e(function(e){return Yi(e)})},e.dict=function(t){return new e(function(e){if(sr(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return er(dr("."+i,r.error));n[i]=r.result}return Yi(n)}return er({message:ar("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?Yi(void 0):t.decode(e)})},e.oneOf=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return new e(function(e){for(var n=[],i=0;i<t.length;i++){var r=t[i].decode(e);if(!0===r.ok)return r;n[i]=r.error}var o=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return er({message:'expected a value matching one of the decoders, got the errors ["'+o+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return Yi(function(e,t){return!0===t.ok?t.result:e}(t,n.decode(e)))})},e.valueAt=function(t,n){return new e(function(e){for(var i=e,r=0;r<t.length;r++){if(void 0===i)return er({at:cr(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!sr(i))return er({at:cr(t.slice(0,r+1)),message:ar("an object",i)});if("number"==typeof t[r]&&!or(i))return er({at:cr(t.slice(0,r+1)),message:ar("an array",i)});i=i[t[r]]}return nr(function(e){return void 0===i?{at:cr(t),message:"path does not exist"}:dr(cr(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return Yi(t)})},e.fail=function(t){return new e(function(e){return er({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),lr=hr.string,ur=hr.number,pr=hr.boolean,gr=hr.anyJson;hr.unknownJson;var fr=hr.constant,mr=hr.object,yr=hr.array;hr.tuple;var wr=hr.dict,vr=hr.optional,br=hr.oneOf;hr.union,hr.intersection,hr.withDefault,hr.valueAt,hr.succeed,hr.fail,hr.lazy;const _r=lr().where(e=>e.length>0,"Expected a non-empty string"),Ir=ur().where(e=>e>=0,"Expected a non-negative number"),Cr=mr({name:_r,displayName:vr(lr()),contexts:vr(yr(lr())),customConfig:vr(mr())}),Ar=br(fr("web"),fr("native"),fr("citrix"),fr("onlineNative"),fr("other")),Tr=mr({url:_r}),Sr=mr({src:_r,size:vr(_r),type:vr(_r)}),kr=mr({src:_r,size:vr(_r),type:vr(_r),label:vr(_r)}),xr=mr({contexts:yr(_r),displayName:vr(_r),resultType:vr(_r),customConfig:vr(gr())}),Er=mr({listensFor:vr(wr(xr)),raises:vr(wr(yr(_r)))}),Pr=mr({broadcasts:vr(yr(_r)),listensFor:vr(yr(_r))}),Mr=mr({name:_r,description:vr(_r),broadcasts:vr(yr(_r)),listensFor:vr(yr(_r))}),Rr=mr({intents:vr(Er),userChannels:vr(Pr),appChannels:vr(yr(Mr))}),Nr=mr({url:vr(_r),top:vr(ur()),left:vr(ur()),width:vr(Ir),height:vr(Ir)}),Or=mr({name:vr(_r),type:vr(_r.where(e=>"window"===e,"Expected a value of window")),title:vr(_r),version:vr(_r),customProperties:vr(gr()),icon:vr(lr()),caption:vr(lr()),details:vr(Nr),intents:vr(yr(Cr)),hidden:vr(pr())}),jr=mr({name:_r,appId:_r,title:vr(_r),version:vr(_r),manifest:_r,manifestType:_r,tooltip:vr(_r),description:vr(_r),contactEmail:vr(_r),supportEmail:vr(_r),publisher:vr(_r),images:vr(yr(mr({url:vr(_r)}))),icons:vr(yr(mr({icon:vr(_r)}))),customConfig:gr(),intents:vr(yr(Cr))}),$r=mr({appId:vr(_r),name:vr(_r),details:vr(Tr),version:vr(_r),title:vr(_r),tooltip:vr(_r),lang:vr(_r),description:vr(_r),categories:vr(yr(_r)),icons:vr(yr(Sr)),screenshots:vr(yr(kr)),contactEmail:vr(_r),supportEmail:vr(_r),moreInfo:vr(_r),publisher:vr(_r),customConfig:vr(yr(gr())),hostManifests:vr(gr()),interop:vr(Rr)}),Wr=mr({appId:_r,name:_r,type:Ar,details:Tr,version:vr(_r),title:vr(_r),tooltip:vr(_r),lang:vr(_r),description:vr(_r),categories:vr(yr(_r)),icons:vr(yr(Sr)),screenshots:vr(yr(kr)),contactEmail:vr(_r),supportEmail:vr(_r),moreInfo:vr(_r),publisher:vr(_r),customConfig:vr(yr(gr())),hostManifests:vr(gr()),interop:vr(Rr),localizedVersions:vr(wr($r))}),Dr=br(jr,Wr),Fr=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Lr{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=Dr.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:Fr(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=Dr.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Fr(i.error)}`);const r=this.getUserPropertiesFromDefinition(e,n),o={url:this.getUrl(e,n)},s={name:e.appId,type:"window",createOptions:o,userProperties:{...r,intents:"1.2"===n?r.intents:this.getIntentsFromV2AppDefinition(e),details:o},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,n),caption:e.description,fdc3:"2.0"===n?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return s;const c=Or.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Fr(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(s,c.result):s}parseToDesktopAppConfig(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=Dr.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Fr(i.error)}`);if("1.2"===n){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,n)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const r=e,o={name:r.appId,type:this.fdc3ToDesktopDefinitionType[r.type],details:r.details,version:r.version,title:r.title,tooltip:r.tooltip,caption:r.description,icon:this.getIconFromDefinition(r,"2.0"),intents:this.getIntentsFromV2AppDefinition(r),fdc3:{...r,definitionVersion:"2.0"}},s=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!s)return o;if("object"!=typeof s||Array.isArray(s))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(o,s)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!Zi.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!Zi.includes(e)&&!Xi.includes(e)))}getUrl(e,t){let n;if("1.2"===t){const t=JSON.parse(e.manifest);n=t.details?.url||t.url}else n=e.details?.url;if(!n||"string"!=typeof n)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return n}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map(e=>{const[t,n]=e;return{name:t,...n}})}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find(e=>e.icon)?.icon||void 0:e.icons?.find(e=>e.src)?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let n=e;if(t.details){const i={...e.createOptions,...t.details};n.createOptions=i,n.userProperties.details=i}return Array.isArray(t.intents)&&(n.userProperties.intents=(n.userProperties.intents||[]).concat(t.intents)),n={...n,...t},delete n.details,delete n.intents,n}mergeDesktopConfigWithGlueManifest(e,t){const n=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(n.intents=(e.intents||[]).concat(t.intents)),n}}const Gr={common:{nonEmptyStringDecoder:_r,nonNegativeNumberDecoder:Ir},fdc3:{allDefinitionsDecoder:Dr,v1DefinitionDecoder:jr,v2DefinitionDecoder:Wr}};var Ur;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(Ur||(Ur={}));const Hr=new class{_fdc3;_decoders=Gr;_errors={intents:Ur};get fdc3(){return this._fdc3||(this._fdc3=(new Lr).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};Hr.fdc3,Hr.decoders;const Br=Hr.errors,Jr="Tick42.FDC3.Intents.",qr=["applicationName","type"],Vr=9e4,zr=Br.intents,Kr=(e,t,n)=>new Promise((i,r)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;r(n||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),i(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),r(e))})}),Qr=e=>{if(!e)throw new Error("Provide 'handlerFilter' with at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'");const{title:t,openResolver:n,timeout:i,intent:r,contextTypes:o,resultType:s,applicationNames:a,excludeList:c}=e;if(void 0!==t&&("string"!=typeof t||!t.length))throw new Error("Provide 'title' as a non empty string");if(void 0!==n&&"boolean"!=typeof n)throw new Error("Provide 'openResolver' prop as a boolean");if(void 0!==i&&("number"!=typeof i||i<=0))throw new Error("Provide 'timeout' prop as a positive number");if(void 0!==r&&("string"!=typeof r||!r.length))throw new Error("Provide 'intent' as a non empty string");if(void 0!==o&&(!Array.isArray(o)||o.some(e=>"string"!=typeof e)))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==s&&("string"!=typeof s||!s.length))throw new Error("Provide 'resultType' as a non empty string");if(void 0!==a&&(!Array.isArray(a)||a.some(e=>"string"!=typeof e)))throw new Error("Provide 'applicationNames' as an array of non empty strings");const d=!c||(e=>!!Array.isArray(e)&&(!!e.every(e=>"object"==typeof e&&!Array.isArray(e)&&null!==e)&&(!!e.every(e=>"applicationName"in e||"instanceId"in e)&&e.every(e=>"applicationName"in e?"string"==typeof e.applicationName&&e.applicationName.length:"instanceId"in e&&"string"==typeof e.instanceId&&e.instanceId.length))))(c);if(!d)throw new Error("Provide 'excludeList' as an array of objects with either 'applicationName' or 'instanceId' key");const h="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)throw new Error(h);if(!(r||s||(null==o?void 0:o.length)||(null==a?void 0:a.length)))throw new Error(h)},Zr=e=>{var t,n;if("string"!=typeof e.intent)return{isValid:!1,error:"Response object has invalid 'intent' key. Expected a string, got "+typeof e.intent};if((null===(t=e.userSettings)||void 0===t?void 0:t.preserveChoice)&&"boolean"!=typeof(null===(n=e.userSettings)||void 0===n?void 0:n.preserveChoice))return{isValid:!1,error:"Response object has invalid 'userSettings.preserveChoice' key. Expected a boolean, got "+typeof e.userSettings.preserveChoice};const{isValid:i,error:r}=(e=>{if("object"!=typeof e)return{isValid:!1,error:"Response object has invalid 'handler' key. Expected an object, got "+typeof e};const t=qr.filter(t=>!(t in e));return t.length?{isValid:!1,error:`Handler in Response object does not provide compulsory keys: ${t.join(", ")}`}:{isValid:!0,ok:e}})(e.handler);return i?{isValid:!0,ok:e}:{isValid:i,error:r}},Xr=e=>{if((e=>{if(e){if("object"!=typeof e)throw new Error("Please provide the intent context as an object");if(e.type&&"string"!=typeof e.type)throw new Error("Please provide the intent context as an object with 'type' property as string");if(e.data&&"object"!=typeof e.data)throw new Error("Please provide the intent context as an object with 'data' property as object")}})(e.context),(e=>{if(e&&"string"!=typeof e&&"object"!=typeof e)throw new Error('Please provide the intent target as one of the valid values: "reuse", "startNew", { app: string }, { instance: string } ')})(e.target),(e=>{if(e){if("number"!=typeof e)throw new Error("Please provide the timeout as a number");if(e<=0)throw new Error("Please provide the timeout as a positive number")}})(e.timeout),(e=>{if(e&&"boolean"!=typeof e)throw new Error("Please provide waitUserResponseIndefinitely as a boolean")})(e.waitUserResponseIndefinitely),void 0!==e.clearSavedHandler&&"boolean"!=typeof e.clearSavedHandler)throw new Error("Please provide 'clearSavedHandler' as a boolean");e.handlers&&e.handlers.forEach(e=>(e=>{if(!e.applicationName)throw new Error(`Please provide applicationName for handler ${JSON.stringify(e)}`);if(!e.type)throw new Error(`Please provide type for handler ${JSON.stringify(e)}`);if("instance"===e.type&&!e.instanceId)throw new Error(`Please provide instanceId for handler ${JSON.stringify(e)}`)})(e))};class Yr{constructor(e,t,n,i,r,o){this.interop=e,this.windows=t,this.logger=n,this.prefsController=r,this.appsController=o,this.myIntents=new Set,this.intentsResolverResponsePromises={},this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[],this.addedHandlerInfoPerApp={},this.checkIfIntentsResolverIsEnabled(i,o)}async find(e){await Promise.all(this.unregisterIntentPromises);let t=await this.all();if(void 0===e)return t;if("string"==typeof e)return t.filter(t=>t.name===e);if("object"!=typeof e)throw new Error("Please provide the intentFilter as a string or an object!");if(e.contextType){const n=e.contextType.toLowerCase();t=t.filter(e=>e.handlers.some(e=>{var t;return null===(t=e.contextTypes)||void 0===t?void 0:t.some(e=>e.toLowerCase()===n)}))}if(e.resultType){const n=e.resultType.toLowerCase();t=t.filter(e=>e.handlers.some(e=>{var t;return(null===(t=e.resultType)||void 0===t?void 0:t.toLowerCase())===n}))}if(e.name){if("string"!=typeof e.name)throw new Error("Please provide the intentFilter as a string or an object!");t=t.filter(t=>t.name===e.name)}return t}async raise(e){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");"string"==typeof e&&(e={intent:e}),Xr(e),await Promise.all(this.unregisterIntentPromises),e.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${e.intent}`),await this.removeRememberedHandler(e.intent));const t={},n=e.timeout||Vr,i=await this.checkHandleRaiseWithRememberedHandler(e,t,n);if(i)return i;const r=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:t,timeout:n});if(e.waitUserResponseIndefinitely)return r();const o=Kr(r,n,`${zr.TIMEOUT_HIT} hit for intent request ${JSON.stringify(e)}`);return o.catch(()=>this.handleRaiseOnError(t.instanceId)),o}async all(){let e;await Promise.all(this.unregisterIntentPromises);try{const t=await this.interop.invoke("T42.ACS.GetApplications",{withIntentsInfo:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn});e=t.returned.applications}catch(e){return this.logger.error("Failed to get the applications!",e),[]}const t={},n=e.filter(e=>e.intents&&e.intents.length>0);for(const e of n)for(const n of e.intents){let i=t[n.name];i||(i={name:n.name,handlers:[]},t[n.name]=i);const r={applicationName:e.name,applicationTitle:e.title||"",applicationDescription:e.caption,displayName:n.displayName,contextTypes:n.contexts,applicationIcon:e.icon,type:"app",resultType:n.resultType,customConfig:null==n?void 0:n.customConfig};i.handlers.push(r)}const i=this.interop.servers(),r=i.map(e=>e.windowId).filter(e=>void 0!==e),o="T42.Wnd.GetInfo";let s;if(this.interop.methods().some(e=>e.name===o))try{const e=await this.interop.invoke(o,{ids:r},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn});s=e.returned.windows}catch(e){}for(const n of i)await Promise.all(n.getMethods().filter(e=>e.name.startsWith(Jr)).map(async i=>{const r=i.name.replace(Jr,"");let o=t[r];o||(o={name:r,handlers:[]},t[r]=o);const a=await this.windowsIdToTitle(n.windowId,s),c=this.constructIntentHandler({method:i,apps:e,server:n,intentName:r,title:a});o.handlers.push(c)}));return Object.values(t)}addIntentListener(e,t){if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("function"!=typeof t)throw new Error("Please provide the handler as a function!");const n="string"==typeof e?e:e.intent,i=`${Jr}${n}`;let r,o={};if(this.myIntents.has(n))throw new Error(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);const s={unsubscribe:()=>{this.myIntents.delete(n),r.then(()=>this.interop.unregister(i)).catch(e=>this.logger.trace(`Unregistration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`))}};if("object"==typeof e){const{intent:t,...n}=e;o=n}return r=this.interop.register({name:i,flags:{intent:o}},e=>{if(this.myIntents.has(n))return t(e)}),r.catch(e=>{this.myIntents.delete(n),this.logger.warn(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}),s}async register(e,t){if((e=>{if("string"!=typeof e&&"object"!=typeof e||"object"==typeof e&&"string"!=typeof e.intent)throw new Error("Please provide the intent as a string or an object with an intent property!");if("string"!=typeof e){if(void 0!==e.contextTypes&&(!Array.isArray(e.contextTypes)||e.contextTypes.some(e=>"string"!=typeof e)))throw new Error("Please provide the 'contextTypes' as an array of strings!");if(void 0!==e.resultType&&"string"!=typeof e.resultType)throw new Error("Please provide the 'resultType' as a string!");if(void 0!==e.displayName&&"string"!=typeof e.displayName)throw new Error("Please provide the 'displayName' as a string!");if(void 0!==e.icon&&"string"!=typeof e.icon)throw new Error("Please provide the 'icon' as a string!");if(void 0!==e.description&&"string"!=typeof e.description)throw new Error("Please provide the 'description' as a string!");if(void 0!==e.customConfig&&("object"!=typeof e.customConfig||Array.isArray(e.customConfig)))throw new Error("Please provide the 'customConfig' as an object!")}})(e),"function"!=typeof t)throw new Error("Please provide the handler as a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);let r={};if(this.myIntents.has(n))throw new Error(`Intent listener for intent ${n} already registered!`);if(this.myIntents.add(n),"object"==typeof e){const{intent:t,...n}=e;r=n}try{await this.interop.register({name:i,flags:{intent:r}},(e,i)=>{if(this.myIntents.has(n))return t(e,i)})}catch(e){throw this.myIntents.delete(n),new Error(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async filterHandlers(e){var t,n;if(Qr(e),e.openResolver&&!this.useIntentsResolverUI)throw new Error("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");null===(t=this.logger)||void 0===t||t.trace(`Received 'filterHandlers' command with request: ${JSON.stringify(e)}`);const i=await this.all(),r=this.filterHandlersBy(i,e);if(!(null==r?void 0:r.length))return{handlers:[]};const{open:o,reason:s}=await this.checkIfResolverShouldBeOpenedForFilterHandlers(r,e);if(!o)return null===(n=this.logger)||void 0===n||n.trace(`Intent Resolver UI won't be used. Reason: ${s}`),{handlers:r};const a={instanceId:void 0},c=e.timeout||9e4;return{handlers:[await Kr(()=>this.startResolverApp({request:e,resolverInstance:a,method:"filterHandlers"}),c,`Timeout of ${c}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e)}`)]}}async getIntents(e){var t;this.logger.trace(`Received 'getIntents' command with handler ${JSON.stringify(e)}`),(e=>{if("object"!=typeof e)throw new Error("IntentHandler must be an object");if("string"!=typeof e.applicationName||!e.applicationName.length)throw new Error("Please provide 'applicationName' as a non-empty string");if("string"!=typeof e.type||!["app","instance"].includes(e.type))throw new Error(`Invalid 'type' property. Expected 'app' | 'instance' got ${e.type}`);if(void 0!==e.applicationTitle&&"string"!=typeof e.applicationTitle)throw new Error("Provide 'applicationTitle' as a string");if(void 0!==e.applicationDescription&&"string"!=typeof e.applicationDescription)throw new Error("Provide 'applicationDescription' as a string");if(void 0!==e.applicationIcon&&"string"!=typeof e.applicationIcon)throw new Error("Provide 'applicationIcon' as a string");if(void 0!==e.displayName&&"string"!=typeof e.displayName)throw new Error("Provide 'displayName' as a string");if(void 0!==e.contextTypes&&(!Array.isArray(e.contextTypes)||e.contextTypes.some(e=>"string"!=typeof e)))throw new Error("Provide 'contextTypes' as an array of non empty strings");if(void 0!==e.instanceId&&"string"!=typeof e.instanceId)throw new Error("Provide 'instanceId' as a string");if(void 0!==e.instanceTitle&&"string"!=typeof e.instanceTitle)throw new Error("Provide 'instanceTitle' as a string");if(void 0!==e.resultType&&"string"!=typeof e.resultType)throw new Error("Provide 'resultType' as a string")})(e);const n=await this.all();var i;i=e,Object.keys(i).forEach(e=>{null!==i[e]&&void 0!==i[e]||delete i[e]}),null===(t=this.logger)||void 0===t||t.trace("Extracting valid intents for the passed handler");const r=this.extractIntentsWithInfoByHandler(n,e);return this.logger.trace(`Returning intents for handler ${JSON.stringify(e)}`),{intents:r}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:null},{app:this.getMyAppName()})}onHandlerAdded(e){var t;if("function"!=typeof e)throw new Error("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const n=null===(t=this.appsController)||void 0===t?void 0:t.onAdded(async(t,n)=>{var i;const r=t.app.name,o=n;(null===(i=null==o?void 0:o.intents)||void 0===i?void 0:i.length)&&o.intents.forEach(t=>{const n=this.constructIntentHandlerFromApp(o,t);this.addedHandlerInfoPerApp[r]||(this.addedHandlerInfoPerApp[r]=[]);this.addedHandlerInfoPerApp[r].push({handler:n,name:t.name}),e(n,t.name)})},!0),i=this.interop.serverMethodAdded(({method:t,server:n})=>{if(!t.name.startsWith(Jr))return;const i=t.name.replace(Jr,""),r=this.constructIntentHandler({method:t,apps:[],server:n,intentName:i,title:""});e(r,i)});return()=>{"function"==typeof i&&i(),n.then(e=>{"function"==typeof e&&e()})}}onHandlerRemoved(e){var t;if("function"!=typeof e)throw new Error("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const n=null===(t=this.appsController)||void 0===t?void 0:t.onRemoved(async t=>{const n=t.appName,i=this.addedHandlerInfoPerApp[n];(null==i?void 0:i.length)&&(delete this.addedHandlerInfoPerApp[n],i.forEach(t=>{e(t.handler,t.name)}))}),i=this.interop.serverMethodRemoved(({method:t,server:n})=>{if(!t.name.startsWith(Jr))return;const i=t.name.replace(Jr,""),r=this.constructIntentHandler({method:t,apps:[],server:n,intentName:i,title:""});e(r,i)});return()=>{"function"==typeof i&&i(),null==n||n.then(e=>{"function"==typeof e&&e()})}}toAPI(){return{all:this.all.bind(this),find:this.find.bind(this),raise:this.raise.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntents.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}filterHandlersBy(e,t){const n=e.filter(e=>{if(!t.intent||t.intent===e.name){if(t.excludeList&&(e.handlers=this.excludeIntentHandlers(e,t.excludeList)),t.resultType){const n=e.handlers.filter(e=>e.resultType&&e.resultType===t.resultType);if(!n.length)return;e.handlers=n}if(t.contextTypes){const n=e.handlers.filter(e=>{var n;return null===(n=t.contextTypes)||void 0===n?void 0:n.every(t=>{var n;return null===(n=e.contextTypes)||void 0===n?void 0:n.includes(t)})});if(!n.length)return;e.handlers=n}if(t.applicationNames){const n=e.handlers.filter(e=>{var n;return null===(n=t.applicationNames)||void 0===n?void 0:n.includes(e.applicationName)});if(!n.length)return;e.handlers=n}return e}});return n.map(e=>e.handlers).flat(1)}excludeIntentHandlers(e,t){return e.handlers.filter(e=>!t.some(t=>"applicationName"in t?t.applicationName===e.applicationName:"instanceId"in t&&t.instanceId===e.instanceId))}async coreRaiseIntent({request:e,resolverInstance:t,timeout:n,resolverConfig:i}){var r,o;const s=await this.get(e.intent);if(void 0===s)throw new Error(`${zr.INTENT_NOT_FOUND} with name ${e.intent}`);const{open:a,reason:c}=await this.checkIfResolverShouldBeOpenedForRaise(s,e,i);if(!a)return this.logger.trace(`Intent Resolver UI won't be used. Reason: ${c}`),e.waitUserResponseIndefinitely?Kr(()=>this.raiseIntent(e,n),n,`${zr.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`):this.raiseIntent(e,n);const d=await this.startResolverApp({request:e,method:"raise",resolverInstance:t});if(null===(r=this.logger)||void 0===r||r.trace(`Raising intent to target handler: ${JSON.stringify(d)} with timeout of ${n}`),e.waitUserResponseIndefinitely)return Kr(()=>this.raiseIntentToTargetHandler(e,d,n),n,`${zr.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`);const h=await this.raiseIntentToTargetHandler(e,d,n);return null===(o=this.logger)||void 0===o||o.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(h)}`),h}async get(e){return(await this.all()).find(t=>t.name===e)}async raiseIntent(e,t){const n=e.intent,i=await this.get(n);if(void 0===i)throw new Error(`${zr.INTENT_NOT_FOUND} with name ${e.intent}`);const r=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(i.handlers,{type:"app"}),o=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(i.handlers,{type:"instance"});let s;if(e.target&&"reuse"!==e.target||(s=o||r),"startNew"===e.target&&(s=r),"object"==typeof e.target&&e.target.app&&(s=this.findHandlerByFilter(i.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(s=this.findHandlerByFilter(i.handlers,{instance:e.target.instance,app:e.target.app})),!s)throw new Error(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler(e,s,t)}async raiseIntentToTargetHandler(e,t,n){var i,r;if(null===(i=this.logger)||void 0===i||i.trace(`Raising intent to target handler:${JSON.stringify(t)}`),!t.instanceId){const n=this.invokeStartApp(t.applicationName,e.context,e.options).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e);throw new Error(`${zr.TARGET_INSTANCE_UNAVAILABLE}. Reason: ${t}`)});t.instanceId=await n}const o=`${Jr}${e.intent}`,s={methodResponseTimeoutMs:n?n+1e3:6e4,waitTimeoutMs:n?n+1e3:6e4},a=this.interop.invoke(o,e.context,{instance:t.instanceId},s).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e);throw new Error(`${zr.INTENT_HANDLER_REJECTION}. Reason: ${t}`)}),c=await a;return null===(r=this.logger)||void 0===r||r.trace(`raiseIntent command completed. Returning result: ${JSON.stringify(c)}`),{request:e,handler:{...t,type:"instance"},result:c.returned}}async startResolverApp({request:e,method:t,resolverInstance:n}){var i,r,o,s;null===(i=this.logger)||void 0===i||i.trace(`Intents Resolver UI with app name ${this.intentsResolverAppName} will be used for request: ${JSON.stringify(e)}`);const a=await this.registerIntentResolverMethod();null===(r=this.logger)||void 0===r||r.trace(`Registered interop method ${a}`);const c=await this.buildStartContext(t,e,a),d=await this.buildStartOptions();null===(o=this.logger)||void 0===o||o.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(c)} and options: ${JSON.stringify(d)}`);const h=await this.appsController.start({name:this.intentsResolverAppName,context:c,definitionOverride:d});n.instanceId=h.id,null===(s=this.logger)||void 0===s||s.trace(`Intents Resolver instance with id ${h.id} opened`),await this.subscribeOnInstanceStopped(h,t);const l=e.timeout||"raise"===t?Vr:9e4;this.createResponsePromise({intent:"raise"===t?e.intent:void 0,instanceId:h.id,responseMethodName:a,timeout:l,errorMsg:`Timeout of ${l}ms hit waiting for the user to choose a handler ${"raise"===t?`for intent ${e.intent}`:`for '${t}' method with filter ${JSON.stringify(e)}`}`});return await this.handleInstanceResponse({instanceId:h.id,caller:c.initialCaller,method:t,request:e})}async windowsIdToTitle(e,t){var n,i;if(void 0!==t)return null===(n=t.find(t=>t.id===e))||void 0===n?void 0:n.title;const r=null===(i=this.windows)||void 0===i?void 0:i.findById(e);return await(null==r?void 0:r.getTitle())}async handleInstanceResponse({instanceId:e,method:t,request:n,caller:i}){var r,o,s;try{const a=await this.intentsResolverResponsePromises[e].promise,c="raise"===t?`for intent ${a.intent} `:"";return null===(r=this.logger)||void 0===r||r.trace(`Intent handler chosen ${c}: ${JSON.stringify(a.handler)}. Stopping resolver instance with id ${e}`),this.stopResolverInstance(e),null===(o=this.logger)||void 0===o||o.trace(`Instance with id ${e} successfully stopped`),(null===(s=a.userSettings)||void 0===s?void 0:s.preserveChoice)&&await this.saveUserChoice({intent:a.intent,handler:a.handler,filter:"filterHandlers"===t?{applicationNames:n.applicationNames,contextTypes:n.contextTypes,resultType:n.resultType}:void 0,caller:i}),a.handler}catch(t){throw this.stopResolverInstance(e),new Error(t)}}async registerIntentResolverMethod(){const e="T42.Intents.Resolver.Control"+jn.generateId();return await this.interop.register(e,(e,t)=>this.resolverResponseHandler(e,t)),e}resolverResponseHandler(e,t){const{instance:n}=t,i=Zr(e);if(!i)return this.logger.trace(`Intent Resolver instance with id ${t.instance} sent invalid response. Error: ${i.error}`),this.intentsResolverResponsePromises[n].reject(i.error),void this.stopResolverInstance(n);const r=i.ok;this.intentsResolverResponsePromises[n].resolve(r),this.cleanUpIntentResolverPromise(n)}async buildStartContext(e,t,n){const i=this.getMyAppName(),r=(await this.appsController.getApp(i)).title||"",o={callerId:this.interop.instance.instance,methodName:n,initialCaller:{id:this.interop.instance.instance,applicationName:i,applicationTitle:r},resolverApi:"1.0"};return"raise"===e?{...o,intent:t}:{...o,handlerFilter:t}}async buildStartOptions(){const e=this.windows.my();if(!e)return;const t=await e.getBounds();return{top:await this.getResolverStartupTopBound(t),left:(t.width-400)/2+t.left,width:400,height:440}}async getResolverStartupTopBound(e){const t=(await this.windows.my().getDisplay()).workArea.height,n=(e.height-440)/2+e.top;return n<0?0:n+440>t?t/2:n}createResponsePromise({instanceId:e,intent:t,responseMethodName:n,timeout:i,errorMsg:r}){let o=()=>{},s=()=>{};const a=((e,t,n)=>new Promise((i,r)=>{const o=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),i(e)}).catch(e=>{clearTimeout(o),r(e)})}))((e,t)=>{o=e,s=t},i,r);this.intentsResolverResponsePromises[e]={intent:t,resolve:o,reject:s,promise:a,methodName:n}}async invokeStartApp(e,t,n){return(await this.interop.invoke("T42.ACS.StartApplication",{Name:e,options:{...n,startedByIntentAPI:!0}},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned.Id}async subscribeOnInstanceStopped(e,t){const n=await this.appsController.onInstanceStopped(i=>{if(i.id!==e.id)return;const r=this.intentsResolverResponsePromises[i.id];if(!r)return n();const o=`Cannot resolve ${"raise"===t?`raised intent ${r.intent}`:`'${t}' method`} - User closed ${e.appName} app without choosing a handler`;r.reject(o),this.cleanUpIntentResolverPromise(i.id),n()})}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch(e=>this.logger.warn(e)),delete this.intentsResolverResponsePromises[e]}handleRaiseOnError(e){e&&this.stopResolverInstance(e)}stopResolverInstance(e){const t=this.windows.findById(e);null==t||t.close().catch(e=>this.logger.error(e))}checkIfIntentsResolverIsEnabled(e,t){var n,i,r,o,s;t.isInitialized()?(this.useIntentsResolverUI="boolean"!=typeof(null===(n=e.intents)||void 0===n?void 0:n.enableIntentsResolverUI)||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(r=null===(i=e.intents)||void 0===i?void 0:i.intentsResolverAppName)&&void 0!==r?r:"intentsResolver",this.intentsResolverResponseTimeout=null!==(s=null===(o=e.intents)||void 0===o?void 0:o.methodResponseTimeoutMs)&&void 0!==s?s:6e4):this.useIntentsResolverUI=!1}async checkIfResolverShouldBeOpenedForRaise(e,t,n){if(n&&!n.enabled)return{open:!1,reason:"Intents Resolver is disabled"};const i=await this.checkIfIntentsResolverShouldBeOpened();if(!i.open)return i;return await this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:`Raised intent ${e.name} has only one handler`}}async checkIfResolverShouldBeOpenedForFilterHandlers(e,t){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:"boolean"!=typeof(null==t?void 0:t.openResolver)||t.openResolver?this.checkIfIntentsResolverShouldBeOpened():{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}}async checkIfIntentsResolverShouldBeOpened(){if(!this.useIntentsResolverUI)return{open:!1,reason:"Intent Resolver is disabled. Resolving to first found handler"};return await this.appsController.getApp(this.intentsResolverAppName)?{open:!0}:{open:!1,reason:`Intent Resolver Application with name ${this.intentsResolverAppName} not found.`}}async checkIfIntentHasMoreThanOneHandler(e,t){const n=await this.removeSingletons(t.handlers||e.handlers);if(!t.target)return n.length>1;if("reuse"===t.target)return n.filter(e=>"instance"===e.type&&e.instanceId).length>1||e.handlers.filter(e=>"app"===e.type).length>1;if("startNew"===t.target)return n.filter(e=>"app"===e.type).length>1;if(t.target.instance)return!1;if(t.target.app){const e=t.target.app;return n.filter(t=>t.applicationName===e&&t.instanceId).length>1}return!1}async removeSingletons(e){return(await Promise.all(e.map(async e=>{if("instance"===e.type)return e;const t=await this.appsController.getApp(e.applicationName),n=!1===(null==t?void 0:t.allowMultiple);return{...e,isSingleton:n}}))).filter((e,t,n)=>{if(e.instanceId||!e.isSingleton)return e;return n.find(t=>t.instanceId&&t.applicationName===e.applicationName)?void 0:e})}buildInteropMethodName(e){return`${Jr}${e}`}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter(t=>t!==e)}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),n=this.interop.unregister(t);this.unregisterIntentPromises.push(n),n.then(()=>{this.clearUnregistrationPromise(n)}).catch(e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: `,e),this.clearUnregistrationPromise(n)})}findHandlerByFilter(e,t){return t.type?e.find(e=>e.type===t.type):t.instance?e.find(e=>t.app?e.applicationName===t.app&&e.instanceId===t.instance:e.instanceId===t.instance):t.app?e.find(e=>e.applicationName===t.app):void 0}extractIntentsWithInfoByHandler(e,t){const n=e.reduce((e,n)=>(n.handlers.forEach(i=>{const r=Object.keys(t).every(e=>{var n;return"contextTypes"===e?null===(n=t.contextTypes)||void 0===n?void 0:n.every(e=>{var t;return null===(t=i.contextTypes)||void 0===t?void 0:t.includes(e)}):i[e]===t[e]});if(!r)return;const o={intent:n.name,contextTypes:i.contextTypes,description:i.applicationDescription,displayName:i.displayName,icon:i.applicationIcon,resultType:i.resultType};e.push(o)}),e),[]);return n}getMyAppName(){return this.interop.instance.application||this.interop.instance.applicationName}async removeRememberedHandler(e){var t;let n;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{n=await this.prefsController.get(this.getMyAppName())}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${"string"==typeof e?e:JSON.stringify(e)}`)}const i=null===(t=n.data)||void 0===t?void 0:t.intents;if(!i)return void this.logger.trace("No app prefs found for current app");delete i[e];const r={...n.data,intents:i};try{await this.prefsController.update(r,{app:this.getMyAppName()})}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${"string"==typeof e?e:JSON.stringify(e)}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){var t,n;let i;try{i=await this.prefsController.get(this.getMyAppName())}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${"string"==typeof e?e:JSON.stringify(e)}`)}const r=null===(n=null===(t=i.data)||void 0===t?void 0:t.intents)||void 0===n?void 0:n[e.intent];return null==r?void 0:r.handler}async checkHandleRaiseWithRememberedHandler(e,t,n){if(e.target)return;const i=await this.checkForRememberedHandler(e);if(!i)return;const r={...e,target:{app:i.applicationName,instance:i.instanceId}},o={enabled:!1,appName:this.intentsResolverAppName,waitResponseTimeout:e.waitUserResponseIndefinitely?2147483647:e.timeout||Vr};try{return await this.coreRaiseIntent({request:r,resolverInstance:t,timeout:n,resolverConfig:o})}catch(t){this.logger.trace("Could not raise intent to remembered handler. Removing it from Prefs store"),await this.removeRememberedHandler(e.intent)}}async saveUserChoice({intent:e,handler:t,filter:n}){var i,r;const o=await this.prefsController.get(this.getMyAppName()),s=(null===(i=null==o?void 0:o.data)||void 0===i?void 0:i.intents)||{},a={...o.data,intents:{...s,[e]:{handler:t,filter:n}}};await this.prefsController.update(a,{app:this.getMyAppName()}),null===(r=this.logger)||void 0===r||r.info(`Saved user's choice of handler for '${this.getMyAppName()}' app`)}constructIntentHandler({apps:e,intentName:t,method:n,server:i,title:r}){const o=n.flags.intent,s=e.find(e=>e.name===i.application);let a;(null==s?void 0:s.intents)&&(a=s.intents.find(e=>e.name===t));return{instanceId:i.instance,applicationName:i.application,applicationIcon:o.icon||(null==s?void 0:s.icon),applicationTitle:(null==s?void 0:s.title)||"",applicationDescription:o.description||(null==s?void 0:s.caption),displayName:o.displayName||(null==a?void 0:a.displayName),contextTypes:o.contextTypes||(null==a?void 0:a.contexts),instanceTitle:r,type:"instance",resultType:(null==a?void 0:a.resultType)||o.resultType,customConfig:null==o?void 0:o.customConfig}}constructIntentHandlerFromApp(e,t){return{applicationName:e.name,applicationTitle:e.title||"",applicationDescription:e.caption,displayName:t.displayName,contextTypes:t.contexts,applicationIcon:e.icon,type:"app",resultType:t.resultType,customConfig:null==t?void 0:t.customConfig}}}class eo{constructor(e,t){this.appName=e,this.interop=t,this.registry=xn(),this.interopMethodRegistered=!1}async get(e){Mt(e)||this.verifyApp(e);return(await this.interop.invoke(eo.T42GetPrefsMethodName,{app:null!=e?e:this.appName},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}async set(e,t){var n;this.verifyDataObject(e),Mt(t)||this.verifyOptions(t),await this.interop.invoke(eo.T42SetPrefsMethodName,{app:null!==(n=null==t?void 0:t.app)&&void 0!==n?n:this.appName,data:e,merge:!1},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async setFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.set(t,{app:e})}async update(e,t){this.verifyDataObject(e);let n=this.appName;!Mt(t)&&"app"in t&&(this.verifyApp(t.app),n=t.app),await this.interop.invoke(eo.T42SetPrefsMethodName,{app:n,data:e,merge:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async updateFor(e,t){return this.verifyApp(e),this.verifyDataObject(t),this.update(t,{app:e})}async clear(e){await this.interop.invoke(eo.T42SetPrefsMethodName,{app:null!=e?e:this.appName,clear:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async clearFor(e){this.verifyApp(e),await this.interop.invoke(eo.T42SetPrefsMethodName,{app:e,clear:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}async getAll(){return(await this.interop.invoke(eo.T42GetPrefsMethodName,void 0,"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}async clearAll(){await this.interop.invoke(eo.T42SetPrefsMethodName,{clear:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}subscribe(e){return this.verifyCallback(e),this.subscribeFor(this.appName,e)}subscribeFor(e,t){this.verifyApp(e),this.verifyCallback(t);const n=this.registry.add(e,t);return this.registerInteropIfNeeded().then(()=>{this.interop.invoke(eo.T42GetPrefsMethodName,{app:e,subscribe:!0},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})}),()=>{n()}}async registerInteropIfNeeded(){this.interopMethodRegistered||(this.interopMethodRegistered=!0,await this.interop.register(eo.T42UpdatePrefsMethodName,e=>{this.registry.execute(e.app,e)}))}verifyApp(e){if(!e)throw new Error("app argument should be a valid string");if(!kt(e))throw new Error("app should be a string")}verifyDataObject(e){if(!e)throw new Error("data should be defined");if(!xt(e))throw new Error("data should be an object")}verifyCallback(e){if(!Ot(e))throw new Error("callback should be defined")}verifyOptions(e){if("object"!=typeof e)throw new Error("options argument should be an object");this.verifyApp(e.app)}}eo.T42UpdatePrefsMethodName="T42.Prefs.Update",eo.T42GetPrefsMethodName="T42.Prefs.Get",eo.T42SetPrefsMethodName="T42.Prefs.Set";class to{constructor(e,t){this.methodName=e,this.interop=t}async get(e){return(await this.invoke("get-cookies",{filter:e})).returned.cookies}async set(e){this.verifyCookieObject(e),await this.invoke("set-cookie",e)}async remove(e,t){if(!kt(e))throw new Error("url should be a string");if(!kt(t))throw new Error("name should be a string");await this.invoke("remove-cookie",{url:e,name:t})}invoke(e,t){return this.interop.invoke(this.methodName,{command:e,args:t},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Rn})}verifyCookieObject(e){if(!e)throw new Error("cookie should be defined");if(!xt(e))throw new Error("cookie should be an object");if(jn.isNullOrUndefined(e.url)||!kt(e.url))throw new Error("cookie.url should be a string");if(jn.isNullOrUndefined(e.name)||!kt(e.name))throw new Error("cookie.name should be a string");if(!jn.isNullOrUndefined(e.value)&&!kt(e.value))throw new Error("cookie.value should be a string");if(!jn.isNullOrUndefined(e.domain)&&!kt(e.domain))throw new Error("cookie.domain should be a string");if(!jn.isNullOrUndefined(e.path)&&!kt(e.path))throw new Error("cookie.path should be a string");if(!jn.isNullOrUndefined(e.secure)&&"boolean"!=typeof e.secure)throw new Error("cookie.secure should be a boolean");if(!jn.isNullOrUndefined(e.httpOnly)&&"boolean"!=typeof e.httpOnly)throw new Error("cookie.httpOnly should be a boolean");if(!jn.isNullOrUndefined(e.expirationDate)&&"number"!=typeof e.expirationDate)throw new Error("cookie.expirationDate should be a number")}}class no{constructor(e){this.config=e,this.glue42EventName="Glue42",this.events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)}}}start(e){this.glue=e,jn.isNode()?e.interop.invoke("T42.GD.Execute",{command:"announce-instance-ready",args:this.getAnnounceInfo()}).catch(()=>{}):(this.wireCustomEventListener(),this.announceStarted())}wireCustomEventListener(){window.addEventListener(this.glue42EventName,e=>{const t=e.detail;if(!t||!t.glue42)return;const n=t.glue42.event,i=this.events[n];i&&i.handle(t.glue42.message)})}announceStarted(){this.send("start",this.getAnnounceInfo())}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse",{glue:this.glue}):this.send("requestGlueResponse",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}send(e,t){const n={glue42:{event:e,message:t}},i=new CustomEvent(this.glue42EventName,{detail:n});window.dispatchEvent(i)}getAnnounceInfo(){const e=this.glue.performance,t=e.initTimes?e.initTimes:[];return{api:{version:this.glue.version,config:this.glue.userConfig,initTimes:t.map(e=>({name:e.name,duration:e.duration}))}}}}class io{static delay(e){return new Promise(t=>setTimeout(t,e))}static async delayForever(){for(;;)await this.delay(2147483647)}get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}}const ro={register:"register",unregister:"unregister",raise:"raiseInterception",filterHandlers:"filterHandlersInterception"};class oo{constructor(){this.InterceptorMethodName="T42.GD.Interception.Execute",this.InterceptorHandlerMethodName="T42.GD.Interception.Handler",this.interceptions=[]}init(e){this.interop=e}async register(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Please provide a valid object.");if("function"!=typeof e.handler)throw new Error("Please provide a valid handler function.");const t=e.interceptions;this.validateInterceptions(t),this.interceptions.push(e);const n=ro.register;try{await this.interop.invoke(this.InterceptorMethodName,{command:n,interceptions:t},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}),await this.registerMethodIfNotRegistered()}catch(t){this.interceptions=this.interceptions.filter(t=>t!==e);const n=t.message||"Unknown error";throw new Error(`Failed to register interception: ${n}`)}}async unregister(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Please provide a valid object.");const t=e.interceptions;this.validateInterceptions(t);const n=ro.unregister;try{await this.interop.invoke(this.InterceptorMethodName,{command:n,interceptions:t},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn}),this.interceptions=this.interceptions.filter(e=>!t.some(t=>e.interceptions.some(e=>e.domain===t.domain&&e.operation===t.operation)))}catch(e){const t=e.message||"Unknown error";throw new Error(`Failed to unregister interception: ${t}`)}}async handleInterception(e,t,n,i){if(0===this.interop.methods(this.InterceptorMethodName).length)return{};const r=ro[t];if(!r)throw new Error(`No command mapped for intercepting operation: ${t}`);return(await this.interop.invoke(this.InterceptorMethodName,{command:r,interceptions:[{operationArgs:n,domain:e,operation:t,phase:i}]},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn})).returned}static createProxyObject(e,t,n){const i=oo.OperationsPerDomain[t]||[];return new Proxy(e,{get(e,r,o){const s=Reflect.get(e,r,o);try{if("function"!=typeof s)return s;const o=i.includes(r),a=jn.isPromise(s)||jn.isAsyncFunction(s);return o&&a?oo.interceptMethod(s,r,e,t,n):s}catch(e){return s}}})}static interceptMethod(e,t,n,i,r){return async function(...o){const s=await r.handleInterception(i,t,o,"before");if(!jn.isNullOrUndefined(s.operationResult))return s.operationResult;jn.isNullOrUndefined(s.operationArgs)||(o=s.operationArgs);const a=await e.apply(n,o),c=await r.handleInterception(i,t,[a],"after");return jn.isNullOrUndefined(c.operationResult)?a:c.operationResult}}toAPI(){return{register:this.register.bind(this),unregister:this.unregister.bind(this)}}async registerMethodIfNotRegistered(){var e;(null===(e=this.whenRegisteredPromise)||void 0===e?void 0:e.ended)||(this.whenRegisteredPromise=new io,this.registerMethod())}async registerMethod(){await this.interop.register(this.InterceptorHandlerMethodName,async e=>{const t=this.interceptions.find(t=>t.interceptions.some(t=>t.domain===e.interception.domain&&t.operation===e.interception.operation));if(!t)return;return await t.handler(e.interception)}),this.whenRegisteredPromise.resolve()}validateInterceptions(e){if(!Array.isArray(e))throw new Error("Please provide a valid array of interceptions.");if(0===e.length)throw new Error("Please provide at least one interception.");for(const t of e){if(null==t||"object"!=typeof t||Array.isArray(t))throw new Error("Please provide a valid interception object.");if("string"!=typeof t.domain||!t.domain)throw new Error("Please provide a valid domain string.");if("string"!=typeof t.operation||!t.operation)throw new Error("Please provide a valid operation string.");this.validateTypeString(t)}}validateTypeString(e){if(!Mt(e.phase)){const t=["all","before","after"].includes(e.phase);if("string"!=typeof e.phase||!t)throw new Error("Please provide a valid phase string.")}}}oo.OperationsPerDomain={intents:["raise","filterHandlers"]};class so{constructor(e){this.logger=e,this.myInstance=null,this.logger.debug("Initializing MyImpl")}initialize(e){this.myInstance=e}toApi(){const e={};return Object.defineProperty(e,"instance",{get:()=>this.myInstance,enumerable:!0,configurable:!1}),Object.defineProperty(e,"appName",{get:()=>{var e;return null===(e=this.myInstance)||void 0===e?void 0:e.appName},enumerable:!0,configurable:!1}),e}}const ao="apps",co=`${ao}.command`,ho=`${ao}.event`;function lo(e,t,n,i){return e.invoke(co,{command:t,args:n},"best",{waitTimeoutMs:Nn,methodResponseTimeoutMs:Nn,...i||{}})}async function uo(e,t,n,i,r){if("function"!=typeof i)throw new Error("Callback must be a function");if(!n)throw new Error("Event name must be provided");t.debug(`Subscribing to ${n} events`);const o=await function(e,t){return e.subscribe(ho,{arguments:{event:t},target:"best",waitTimeoutMs:Nn,methodResponseTimeout:Nn})}(e,n);return o.onData(e=>{const{data:o}=e;"object"==typeof o&&null!==o?Array.isArray(o.data)?o.data.forEach(e=>{i(r?r(e):e)}):i(r?r(o.data):o.data):t.warn(`Received empty data for event ${n}`)}),()=>{t.debug(`Unsubscribed from ${n} events`),o.close()}}class po{constructor(e,t){this.interop=e,this.logger=t,this.logger.debug("Initializing InMemoryStoreImpl")}async import(e,t="replace"){this.logger.debug(`Importing ${e.length} app definitions with mode: ${t}`);try{const n=await lo(this.interop,"in-memory-import",{apps:e,mode:t});if(!n.returned||0===Object.keys(n.returned).length)return{imported:[],errors:[]};const{imported:i,errors:r}=n.returned;return this.logger.debug(`Import completed: ${i.length} imported, ${r.length} errors`),{imported:i||[],errors:r||[]}}catch(e){const t=`Failed to import app definitions: ${e instanceof Error?e.message:String(e)}`;throw this.logger.error(t,e),new Error(t,{cause:e})}}async has(e){if(!e)return!1;const t=await lo(this.interop,"in-memory-has",{name:e});return void 0!==t.returned.result&&t.returned.result}async remove(e){if(void 0===(null==e?void 0:e.name))throw new Error("App name is required for removal");const t=Array.isArray(e.name)?e.name:[e.name];if(0===t.length)throw new Error("At least one app name is required for removal");const n=[];if(t.forEach((e,t)=>{"string"!=typeof e?n.push(`index ${t}: expected string, got ${typeof e}`):""===e.trim()&&n.push(`index ${t}: empty or whitespace-only string`)}),n.length>0)throw new Error(`Invalid app name(s) for removal: ${n.join("; ")}`);const i=t.slice(0,10),r=Array.isArray(e.name)?`[${i.join(", ")}${t.length>10?", ...":""}] (total ${t.length})`:e.name;this.logger.debug(`Removing app definition(s): ${r}`);try{await lo(this.interop,"in-memory-remove",e),this.logger.debug(`Removed app definition(s): ${r}`)}catch(e){const t=`Failed to remove app definition(s): ${r}. ${e instanceof Error?e.message:String(e)}`;throw this.logger.error(t,e),new Error(t,{cause:e})}}async clear(e){this.logger.debug("Clearing all in-memory app definitions");try{await lo(this.interop,"in-memory-clear",e)}catch(e){const t=`Failed to clear in-memory app definitions: ${e instanceof Error?e.message:String(e)}`;throw this.logger.error(t,e),new Error(t,{cause:e})}}}class go{constructor(e,t){this.interop=e,this.logger=t,this.logger.debug("Initializing AppRegistryImpl"),this._inMemory=new po(this.interop,this.logger),this.subscribeToEvent=(e,t)=>uo(this.interop,this.logger,e,t)}get inMemory(){return this._inMemory}async get(e){if(!(null==e?void 0:e.name))throw new Error("App name is required");this.logger.debug(`Getting app: ${e.name}`);try{const t=await lo(this.interop,"get-app",e);return t.returned&&0!==Object.keys(t.returned).length?t.returned:null}catch(t){return this.logger.error(`Failed to get app ${e.name}`,t),null}}async getMany(e){var t;this.logger.debug("Getting multiple apps");try{const n=await lo(this.interop,"get-apps",{filter:e});return n.returned&&0!==Object.keys(n.returned).length&&(null===(t=n.returned)||void 0===t?void 0:t.apps)||[]}catch(e){return this.logger.error("Failed to get multiple apps",e),[]}}async has(e){if(!e)return!1;this.logger.debug(`Checking if app exists: ${e}`);try{const t=await lo(this.interop,"has-app",{name:e});return void 0!==t.returned.result&&t.returned.result}catch(t){return this.logger.error(`Failed to check app existence: ${e}`,t),!1}}async onAdded(e){return this.subscribeToEvent("applications-added",e)}async onRemoved(e){return this.subscribeToEvent("applications-removed",e)}async onUpdated(e){return this.subscribeToEvent("applications-updated",e)}toApi(){return{inMemory:this.inMemory,get:this.get.bind(this),getMany:this.getMany.bind(this),has:this.has.bind(this),onAdded:this.onAdded.bind(this),onRemoved:this.onRemoved.bind(this),onUpdated:this.onUpdated.bind(this)}}}const fo={APP_NOT_FOUND:{description:"The specified application could not be found in the application registry",possibleCauses:["Application name was misspelled or incorrectly formatted","Application was not properly registered or imported","Application was removed from the registry","Case-sensitive name mismatch"],solutions:["Verify the application name spelling and case","Check if the application exists using apps.registry.list() or apps.registry.has()","Import the application using apps.registry.import() if it's missing","Ensure the application is properly defined in the configuration"]},INVALID_INSTANCE_ID:{description:"The provided instance ID is invalid or malformed",possibleCauses:["Instance ID is null or undefined","Instance ID is not a string (number, object, boolean, etc.)","Instance ID is an empty string or contains only whitespace","Instance ID format is incorrect or contains invalid characters"],solutions:["Ensure the instance ID is provided and not null/undefined","Make sure the instance ID is a string type","Verify the instance ID is not empty and contains actual content","Use a valid instance ID from apps.instances.list() or instance start result","Check that the instance ID hasn't been corrupted or modified"]},INSTANCE_NOT_FOUND:{description:"No running instance found with the specified ID",possibleCauses:["Instance was already stopped or crashed","Instance ID is from a different session","Instance was never successfully started","Instance belongs to a different application"],solutions:["Verify the instance is running using apps.instances.list()","Check if the instance was stopped using instance lifecycle events","Start a new instance if the previous one is no longer available","Use the correct instance ID for the target application"]},INVALID_APP_CONFIG:{description:"The application configuration is invalid or contains errors",possibleCauses:["Required configuration properties are missing","Configuration values have invalid types or formats","URL or path references are malformed","Security settings are conflicting or invalid"],solutions:["Validate all required configuration properties are present","Check configuration values match expected types and formats","Verify URLs and file paths are accessible and properly formatted","Review security settings for conflicts or invalid permissions"]}};class mo extends Error{constructor(e,t){const n=fo[e],i=n?n.description:`Apps error: ${e}`;super(t||i),this.code=e,this.name="AppsError"}toString(){return`[${this.name}:${this.code}] ${this.message}`}getHint(){const e=fo[this.code];return e||{description:`Unknown Apps API error: ${this.code}`,possibleCauses:["Unrecognized error code"],solutions:["Check that the error code is spelled correctly","Verify the error code is supported by the Apps API","Contact support if this error persists"]}}static create(e,t){return new mo(e,t)}static appNotFound(e){return new mo("APP_NOT_FOUND",`Application '${e}' not found`)}static instanceNotFound(e,t){return new mo("INSTANCE_NOT_FOUND",`Instance '${e}' not found${t?` for app '${t}'`:""}`)}static invalidInstanceId(e){let t;return t=null==e?"Instance ID cannot be "+(null===e?"null":"undefined"):"string"!=typeof e?`Instance ID must be a string, received ${typeof e}: ${String(e)}`:""===e.trim()?"Instance ID cannot be empty or whitespace-only":`Invalid instance ID: ${String(e)}`,new mo("INVALID_INSTANCE_ID",t)}static invalidAppConfig(e,t){return new mo("INVALID_APP_CONFIG",`Invalid configuration for app '${e}': ${t}`)}}class yo{constructor(e,t){this.interop=e,this.logger=t,this.logger.debug("Initializing InstanceManagerImpl"),this.subscribeToEvent=(e,t,n)=>uo(this.interop,this.logger,e,t,n)}async start(e){if(!(null==e?void 0:e.name))throw new Error("App name is required to start an instance");this.logger.debug(`Starting app instance: ${e.name}`);try{const t=await lo(this.interop,"start-app",e);return this.logger.debug(`Start app instance result: ${JSON.stringify(t)}`),this.buildInstanceObject(t.returned)}catch(t){const n=jn.typedError(t),i="message"in n?n.message:String(n);if(i.includes("can not find application")||i.includes("application not found"))throw mo.appNotFound(e.name);const r=`Failed to start app instance: ${e.name}`;throw this.logger.error(r,n),new Error(`${r}: ${i}`)}}async stop(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw mo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Stopping app instance: ${e.id}`);try{await lo(this.interop,"stop-app",e),this.logger.debug(`Successfully stopped instance: ${e.id}`)}catch(t){const n=`Failed to stop app instance: ${e.id}`,i=jn.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async waitForReady(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw mo.invalidInstanceId(null==e?void 0:e.id);const t=e.id;this.logger.debug(`Waiting for instance ${t} to be ready`);try{await lo(this.interop,"wait-for-ready",{...e},{waitTimeoutMs:On,methodResponseTimeoutMs:On}),this.logger.debug(`Instance ${t} is now ready`)}catch(e){const n=`Failed to wait for instance ${t} ready state`,i=jn.typedError(e);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async get(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw mo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Getting instance: ${e.id}`);try{const t=await lo(this.interop,"get-instance",{...e});return t.returned&&0!==Object.keys(t.returned).length?this.buildInstanceObject(t.returned):null}catch(t){const n=`Failed to get instance ${e.id}`,i=jn.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async getMany(e){this.logger.debug("Getting multiple instances");try{const t=await lo(this.interop,"get-instances",{filter:e});return t.returned&&0!==Object.keys(t.returned).length&&t.returned.instances?t.returned.instances.map(e=>this.buildInstanceObject(e)):[]}catch(e){const t="Failed to get instances",n=jn.typedError(e);throw this.logger.error(t,n),new Error(`${t}: ${"message"in n?n.message:String(n)}`)}}async getState(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw mo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Getting state for instance: ${e.id}`);try{return(await lo(this.interop,"get-instance-state",{...e})).returned.state}catch(t){const n=`Failed to get state for instance ${e.id}`,i=jn.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async getContext(e){var t;if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw mo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Getting context for instance: ${e.id}`);try{return(null===(t=(await lo(this.interop,"get-instance-context",{...e})).returned)||void 0===t?void 0:t.context)||{}}catch(t){const n=`Failed to get context for instance ${e.id}`,i=jn.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async restart(e){if(!(null==e?void 0:e.id)||"string"!=typeof e.id||""===e.id.trim())throw mo.invalidInstanceId(null==e?void 0:e.id);this.logger.debug(`Restarting instance: ${e.id}`);try{const t=await lo(this.interop,"restart-instance",{...e});return this.logger.debug(`Restart app instance result: ${JSON.stringify(t)}`),this.buildInstanceObject(t.returned)}catch(t){const n=`Failed to restart app instance: ${e.id}`,i=jn.typedError(t);throw this.logger.error(n,i),new Error(`${n}: ${"message"in i?i.message:String(i)}`)}}async onStarted(e){return this.subscribeToEvent("instance-started",e,e=>({...e,instance:this.buildInstanceObject(e.instance)}))}async onStopped(e){return this.subscribeToEvent("instance-stopped",e)}async onStateChanged(e){return this.subscribeToEvent("instance-state-changed",e,e=>({...e,instance:this.buildInstanceObject(e.instance)}))}toApi(){return{start:this.start.bind(this),stop:this.stop.bind(this),waitForReady:this.waitForReady.bind(this),get:this.get.bind(this),getMany:this.getMany.bind(this),getState:this.getState.bind(this),getContext:this.getContext.bind(this),restart:this.restart.bind(this),onStarted:this.onStarted.bind(this),onStopped:this.onStopped.bind(this),onStateChanged:this.onStateChanged.bind(this)}}buildInstanceObject(e){const t={...e};return Object.defineProperty(t,"interopInstance",{get:()=>this.interop.servers().find(t=>t.instance===e.id),enumerable:!0,configurable:!1}),t}}class wo{constructor(){this._appManager=null,this._apps=null}setAppManager(e){this._appManager=e}get appManager(){return this._appManager}setApps(e){this._apps=e}get apps(){return this._apps}get myInstance(){var e,t,n,i,r,o,s,a,c,d;return{id:null!==(n=null===(t=null===(e=this._appManager)||void 0===e?void 0:e.myInstance)||void 0===t?void 0:t.id)&&void 0!==n?n:null===(o=null===(r=null===(i=this._apps)||void 0===i?void 0:i.my)||void 0===r?void 0:r.instance)||void 0===o?void 0:o.id,activityId:null===(a=null===(s=this._appManager)||void 0===s?void 0:s.myInstance)||void 0===a?void 0:a.activityId,inActivity:null===(d=null===(c=this._appManager)||void 0===c?void 0:c.myInstance)||void 0===d?void 0:d.inActivity}}isInitialized(){return!(!this._apps&&!this._appManager)}async getApp(e){var t,n,i;return this.ensureInitialized(),this._appManager?await(null===(n=null===(t=this._appManager)||void 0===t?void 0:t.application(e))||void 0===n?void 0:n.getConfiguration()):this._apps?null===(i=await this._apps.registry.get({name:e,includeDefinition:!0}))||void 0===i?void 0:i.definition:void 0}async start(e){var t;if(this.ensureInitialized(),this._appManager){const n=await(null===(t=this._appManager)||void 0===t?void 0:t.application(null==e?void 0:e.name).start(e.context,e.definitionOverride));return{id:n.id,appName:n.application.name,startedAt:new Date,startedBy:await n.startedBy()}}return this._apps.instances.start(e)}onAdded(e,t){if(this.ensureInitialized(),this._appManager){if(!0===t){const t=this._appManager.onAppAdded(async t=>{var n;const i=await(null===(n=this._appManager)||void 0===n?void 0:n.application(t.name).getConfiguration()),r=i||void 0;return this.callWithErrorGuard(e,{app:{name:t.name,type:t.type}},r)});return Promise.resolve(t)}{const t=this._appManager.onAppAdded(async t=>this.callWithErrorGuard(e,{app:{name:t.name,type:t.type}}));return Promise.resolve(t)}}if(this._apps)return!0===t?this._apps.registry.onAdded(async t=>{var n;const i=await(null===(n=this._apps)||void 0===n?void 0:n.registry.get({name:t.app.name,includeDefinition:!0})),r=i?i.definition:void 0;return this.callWithErrorGuard(e,t,r)}):this._apps.registry.onAdded(e)}onRemoved(e){if(this.ensureInitialized(),this._appManager){const t=this._appManager.onAppRemoved(t=>this.callWithErrorGuard(e,{appName:t.name}));return Promise.resolve(t)}if(this._apps)return this._apps.registry.onRemoved(e)}onInstanceStopped(e){if(this.ensureInitialized(),this._appManager){const t=this._appManager.onInstanceStopped(t=>{this.callWithErrorGuard(e,{id:t.id,appName:t.application.name,startedAt:new Date,startedBy:void 0})});return Promise.resolve(t)}if(this._apps)return this._apps.instances.onStopped(t=>{this.callWithErrorGuard(e,{id:t.instance.id,appName:t.instance.appName,startedAt:t.instance.startedAt,startedBy:t.instance.startedBy})})}async getInstance(e){var t;if(this.ensureInitialized(),this._apps)return this._apps.instances.get({id:e});{const n=null===(t=this._appManager)||void 0===t?void 0:t.instances().find(t=>t.id===e);if(n)return{id:n.id,appName:n.application.name,startedAt:new Date,startedBy:await n.startedBy()}}}ensureInitialized(){if(!this._apps&&!this._appManager)throw new Error("Both AppManager API and Apps API are not initialized")}callWithErrorGuard(e,...t){try{e(...t)}catch{}}}const vo=new class{constructor(){this.initialized=!1,this.details=[],this.reject=()=>{},this.resolve=()=>{}}init(e){this.initialized=!0,this.addCall(e),this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}addCall(e){this.details.push({date:new Date,config:e})}done(e){this.resolve(e)}error(e){this.reject(e)}},bo=async e=>{let t=!1;vo.initialized||(t=!0,vo.init(e));const n="undefined"!=typeof window&&window.glue42gd;if(n&&!t)return vo.addCall(e),vo.promise;const i=await _o(e,n);return vo.resolve(i),i},_o=async(e,t)=>{const n=jn.getGDMajorVersion(),i=qi(e=e||{});let r,o,s,a,c,d,h;e.gateway=e.gateway||{};const l=new oo,u=new Bi,p=new wo,g=new no(i);function f(e,t,n){const i=t.subLogger(e);if(n&&n.logger){const e=n.logger;e.console&&i.consoleLevel(e.console),e.publish&&i.publishLevel(e.publish)}return i}const m={libs:[{name:"windows",create:function(e){if(i.windows){const t=f("windows",e.logger,i.windows);return s=oi(e.agm,t,()=>p,()=>a,()=>c,n),w(s),s}}},{name:"activities",create:function(e){var a;if(i.activities&&bn.checkIsUsingGW3Implementation&&bn.checkIsUsingGW3Implementation(e.connection)){const c=f("activity",e.logger,i.activities);return o=new bn({connection:e.connection,contexts:e.contexts,agm:e.agm,logger:c,logLevel:"info",disableAutoAnnounce:!1,disposeRequestHandling:"exit",announcementInfo:null,windows:s,appManagerGetter:()=>r,mode:i.activities.mode,typesToTrack:i.activities.typesToTrack,activityId:null===(a=null==t?void 0:t.activityInfo)||void 0===a?void 0:a.activityId,gdMajorVersion:n}).api,w(o),o}}},{name:"appManager",create:function(e){if(!i.appManager)return;const t=f("appManager",e.logger,i.appManager);return r=Hn({agm:e.agm,windows:s,logger:t,activities:o,mode:i.appManager.mode,gdMajorVersion:n}),w(r),p.setAppManager(r),r}},{name:"apps",create:function(e){if(!i.apps)return;const t=f("apps",e.logger,i.apps);return h=function(e,t){if(!e)throw new Error("Interop API is required for Apps API initialization");if(!t)throw new Error("Logger is required for Apps API initialization");if(0===e.methods(co).length)return void t.debug("Apps API method not registered in interop; skipping Apps API initialization");t.debug("Initializing new Apps API factory");let n=()=>{t.debug("Apps API factory ready")},i=e=>{t.error("Apps API factory initialization failed",e)};const r=new Promise((e,t)=>{n=e,i=t}),o=new so(t),s=new go(e,t),a=new yo(e,t);return lo(e,"announce",{}).then(e=>{o.initialize(e.returned),n()}).catch(e=>{t.error("Failed to announce current application instance",e),i(e)}),t.debug("New Apps API factory initialized successfully"),{ready:()=>r,my:o.toApi(),registry:s.toApi(),instances:a.toApi()}}(e.agm,t),h?(w(h),p.setApps(h),h):void 0}},{name:"platform",create:function(e){return u.init(e.interop,e.logger),w(u),u.toAPI()}},{name:"layouts",create:function(e){var t;if(!i.layouts)return;const r=f("layouts",e.logger,i.layouts),s=i.layouts,a=_i({agm:e.agm,myInstance:()=>p.myInstance,activityGetter:()=>o,logger:r,mode:s.mode,autoSaveWindowContext:null!==(t=s.autoSaveWindowContext)&&void 0!==t&&t,gdMajorVersion:n});return w(a),a}},{name:"channels",create:function(e){if(!i.channels)return;const t=f("channels",e.logger,i.channels);if(e.contexts)return c=function(e,t,n,i,r){const o=Ni(e,n).then(async({mode:e,initialChannel:i})=>{const o="single"===e?new Fi(t):new Di(t);return"multi"===e&&r.info("multi-channel mode enabled"),await s.init(o,e,i),await xi(n,s,r),!0}),s=new Gi(n,i,r);return{subscribe:s.subscribe.bind(s),subscribeFor:s.subscribeFor.bind(s),publish:s.publish.bind(s),setPath:s.setPath.bind(s),setPaths:s.setPaths.bind(s),all:s.all.bind(s),list:s.list.bind(s),get:s.get.bind(s),join:s.join.bind(s),leave:s.leave.bind(s),restrict:s.restrict.bind(s),getRestrictions:s.getRestrictions.bind(s),restrictAll:s.restrictAll.bind(s),current:s.current.bind(s),clearChannelData:s.clearChannelData.bind(s),my:s.my.bind(s),changed:s.changed.bind(s),onChanged:s.onChanged.bind(s),add:s.add.bind(s),remove:s.remove.bind(s),getWindowsOnChannel:s.getWindowsOnChannel.bind(s),getWindowsWithChannels:s.getWindowsWithChannels.bind(s),getMy:s.getMy.bind(s),ready:async()=>{await Promise.all([t.ready(),o])},get mode(){return s.mode},getMyChannels:s.getMyChannels.bind(s),myChannels:s.myChannels.bind(s),onChannelsChanged:s.onChannelsChanged.bind(s)}}({operationMode:i.channels.operationMode},e.contexts,e.agm,()=>s,t),w(c),c;t.error("Channels library requires Contexts library to be initialized.")}},{name:"hotkeys",create:function(e){const t=function(e){const t=new Hi(e);return{register:t.register.bind(t),unregister:t.unregister.bind(t),unregisterAll:t.unregisterAll.bind(t),isRegistered:t.isRegistered.bind(t),ready:()=>Promise.resolve()}}(e.agm);return w(t),t}},{name:"displays",create:function(e){if(i.displays){const t=f("displays",e.logger,i.displays);return a=new Ii(e.agm,t),w(a),a}}},{name:"prefs",create:function(n){var i,r;const o=null!==(r=null!==(i=e.application)&&void 0!==i?i:null==t?void 0:t.applicationName)&&void 0!==r?r:n.interop.instance.application;return d=new eo(o,n.interop),w(d),d}},{name:"intents",create:function(t){const n="intents",i=new Yr(t.agm,s,t.logger.subLogger(n),e,d,p).toAPI(),r=oo.createProxyObject(i,n,l);return w(r),r}},{name:"notifications",create:function(e){const t=new Ki(e.interop,e.logger).toAPI();return w(t),t}},{name:"themes",create:function(e){if(!e.contexts)return;const t=function(e,t){const n=new Qi(e,t);return{list:n.list.bind(n),getCurrent:n.getCurrent.bind(n),select:n.select.bind(n),onChanged:n.onChanged.bind(n),ready:()=>Promise.resolve()}}(e.contexts,e.interop);return w(t),t}},{name:"cookies",create:function(e){const t=function(e,t){const n=new to(t,e);return{get:n.get.bind(n),remove:n.remove.bind(n),set:n.set.bind(n),ready:()=>Promise.resolve()}}(e.interop,"T42.GD.Execute");return w(t),t}},{name:"interception",create:function(e){return l.init(e.interop),w(l),l.toAPI()}}],version:Ji,enrichGlue:e=>{e.config.activities=i.activities,e.config.windows=i.windows,e.config.appManager=i.appManager,e.config.apps=i.apps,e.config.layouts=i.layouts,e.config.channels=i.channels,e.config.displays=i.displays}},y=[];function w(e){y.push(e)}"undefined"!=typeof window&&(window.glueFactoryLog||(window.glueFactoryLog=[]),window.glueFactoryLog.push(y));const v=await At(e,m);return Array.isArray(null==e?void 0:e.libraries)&&e.libraries.length&&await Promise.all(e.libraries.map(t=>t(v,e))),g.start(v),v};var Io,Co;bo.coreVersion=At.version,bo.version=Ji,bo.calls=vo;let Ao=bo,To=!0;if("undefined"!=typeof window){const e=window,t=null!==(Io=e.iodesktop)&&void 0!==Io?Io:e.glue42gd;t&&t.autoInjected&&(Ao=null!==(Co=e.IODesktop)&&void 0!==Co?Co:e.Glue,To=!1),To&&(e.Glue=Ao,e.IODesktop=Ao),delete e.IOBrowser,delete e.GlueCore}return Ao.default=Ao,Ao});
2
2
  //# sourceMappingURL=desktop.browser.min.js.map