@interopio/browser 4.4.0 → 4.5.0-beta.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,14 +1,14 @@
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).browser=e.browser||{},e.browser.min=t())}(this,function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===n}(e)}(e)};var n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function i(e,t){return!1!==t.clone&&t.isMergeableObject(e)?c((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function r(e,t,n){return e.concat(t).map(function(e){return i(e,n)})}function s(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function o(e,t){try{return t in e}catch(e){return!1}}function a(e,t,n){var r={};return n.isMergeableObject(e)&&s(e).forEach(function(t){r[t]=i(e[t],n)}),s(t).forEach(function(s){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(o(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return c;var n=t.customMerge(e);return"function"==typeof n?n:c}(s,n)(e[s],t[s],n):r[s]=i(t[s],n))}),r}function c(e,n,s){(s=s||{}).arrayMerge=s.arrayMerge||r,s.isMergeableObject=s.isMergeableObject||t,s.cloneUnlessOtherwiseSpecified=i;var o=Array.isArray(n);return o===Array.isArray(e)?o?s.arrayMerge(e,n,s):a(e,n,s):i(n,s)}c.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return c(e,n,t)},{})};var d=e(c),l=function(e){return{ok:!0,result:e}},h=function(e){return{ok:!1,error:e}},u=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:l(e(t.result,n.result))},p=function(e,t){return!0===t.ok?t:h(e(t.error))},g=function(){return g=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},g.apply(this,arguments)};function f(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(!f(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(!f(e[i[n]],t[i[n]]))return!1}return!0}}var m=function(e){return Array.isArray(e)},b=function(e){return"object"==typeof e&&null!==e&&!m(e)},y=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)},w=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},v=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 g({at:e+(n||"")},i)},C=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return p(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?l(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?l(e):h({message:y("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?l(e):h({message:y("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?l(e):h({message:y("a boolean",e)})})},e.constant=function(t){return new e(function(e){return f(e,t)?l(t):h({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(b(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]?h({message:"the key '"+i+"' is required but was not present"}):h(v("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return l(n)}return b(e)?l(e):h({message:y("an object",e)})})},e.array=function(t){return new e(function(e){if(m(e)&&t){return e.reduce(function(e,n,i){return u(function(e,t){return e.concat([t])},e,function(e,n){return p(function(e){return v("["+n+"]",e)},t.decode(e))}(n,i))},l([]))}return m(e)?l(e):h({message:y("an array",e)})})},e.tuple=function(t){return new e(function(e){if(m(e)){if(e.length!==t.length)return h({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 h(v("["+i+"]",r.error));n[i]=r.result}return l(n)}return h({message:y("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 u(Object.assign,t,n.decode(e))},l({}))})},e.anyJson=function(){return new e(function(e){return l(e)})},e.unknownJson=function(){return new e(function(e){return l(e)})},e.dict=function(t){return new e(function(e){if(b(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return h(v("."+i,r.error));n[i]=r.result}return l(n)}return h({message:y("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?l(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 s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return h({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return l(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 h({at:w(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!b(i))return h({at:w(t.slice(0,r+1)),message:y("an object",i)});if("number"==typeof t[r]&&!m(i))return h({at:w(t.slice(0,r+1)),message:y("an array",i)});i=i[t[r]]}return p(function(e){return void 0===i?{at:w(t),message:"path does not exist"}:v(w(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return l(t)})},e.fail=function(t){return new e(function(e){return h({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),I=C.string,S=C.number,_=C.boolean,x=C.anyJson;C.unknownJson;var T=C.constant,k=C.object,P=C.array;C.tuple,C.dict;var O=C.optional,R=C.oneOf,A=C.union,M=C.intersection;C.withDefault,C.valueAt,C.succeed,C.fail;var E=C.lazy;const D={gateway:{webPlatform:{}},libraries:[],exposeAPI:!0},j={awaitFactory:!0,enable:!1,timeout:5e3,restoreLastKnownPosition:!0},N={alerts:{enabled:!1},dialogs:{enabled:!1},awaitFactory:!0,timeout:5e3},F={enable:!1,timeout:5e3,awaitFactory:!0},L={name:"platformUnload"},$={name:"transportSwitchRequest"},W={name:"transportSwitchResponse"},H={name:"getCurrentTransport"},U={name:"getCurrentTransportResponse"},q={name:"checkPreferredLogic"},B={name:"checkPreferredConnection"},G={name:"checkPreferredLogicResponse"},J={name:"checkPreferredConnectionResponse"},z="web-platform",V="latest_fdc3_type",K=new MessageChannel,Z=2147483647,Q={configurable:!1,enumerable:!0,writable:!1},Y=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),X=(e,t)=>{try{return e.runWithException(t)}catch(e){return re.raiseError(e,!0)}},ee=e=>Object.keys(e).filter(t=>e[t].execute),te=(e,t)=>({isSupported:e.some(e=>e.toLowerCase()===t.toLowerCase())}),ne=e=>Math.min(e,Z),ie=()=>{let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}};const re=new class{raiseError(e,t){const n=Y(e);if(K.port1.postMessage(n),t)throw e;throw new Error(n)}},se=["name","title","version","customProperties","icon","caption","type"],oe=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ae=function(e){return{ok:!0,result:e}},ce=function(e){return{ok:!1,error:e}},de=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:ae(e(t.result,n.result))},le=function(e,t){return!0===t.ok?t:ce(e(t.error))},he=function(){return he=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},he.apply(this,arguments)};function ue(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(!ue(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(!ue(e[i[n]],t[i[n]]))return!1}return!0}}var pe=function(e){return Array.isArray(e)},ge=function(e){return"object"==typeof e&&null!==e&&!pe(e)},fe=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)},me=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},be=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 he({at:e+(n||"")},i)},ye=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return le(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?ae(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?ae(e):ce({message:fe("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ae(e):ce({message:fe("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ae(e):ce({message:fe("a boolean",e)})})},e.constant=function(t){return new e(function(e){return ue(e,t)?ae(t):ce({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ge(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]?ce({message:"the key '"+i+"' is required but was not present"}):ce(be("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return ae(n)}return ge(e)?ae(e):ce({message:fe("an object",e)})})},e.array=function(t){return new e(function(e){if(pe(e)&&t){return e.reduce(function(e,n,i){return de(function(e,t){return e.concat([t])},e,function(e,n){return le(function(e){return be("["+n+"]",e)},t.decode(e))}(n,i))},ae([]))}return pe(e)?ae(e):ce({message:fe("an array",e)})})},e.tuple=function(t){return new e(function(e){if(pe(e)){if(e.length!==t.length)return ce({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 ce(be("["+i+"]",r.error));n[i]=r.result}return ae(n)}return ce({message:fe("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 de(Object.assign,t,n.decode(e))},ae({}))})},e.anyJson=function(){return new e(function(e){return ae(e)})},e.unknownJson=function(){return new e(function(e){return ae(e)})},e.dict=function(t){return new e(function(e){if(ge(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return ce(be("."+i,r.error));n[i]=r.result}return ae(n)}return ce({message:fe("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ae(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 s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return ce({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return ae(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 ce({at:me(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ge(i))return ce({at:me(t.slice(0,r+1)),message:fe("an object",i)});if("number"==typeof t[r]&&!pe(i))return ce({at:me(t.slice(0,r+1)),message:fe("an array",i)});i=i[t[r]]}return le(function(e){return void 0===i?{at:me(t),message:"path does not exist"}:be(me(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return ae(t)})},e.fail=function(t){return new e(function(e){return ce({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),we=ye.string,ve=ye.number,Ce=ye.boolean,Ie=ye.anyJson;ye.unknownJson;var Se=ye.constant,_e=ye.object,xe=ye.array;ye.tuple;var Te=ye.dict,ke=ye.optional,Pe=ye.oneOf;ye.union,ye.intersection,ye.withDefault,ye.valueAt,ye.succeed,ye.fail,ye.lazy;const Oe=we().where(e=>e.length>0,"Expected a non-empty string"),Re=ve().where(e=>e>=0,"Expected a non-negative number"),Ae=Ie().andThen(e=>e instanceof RegExp?Ie():fail("expected a regex, got a "+typeof e)),Me=Oe.andThen(e=>{try{return new URL(e),Oe}catch{return fail("Should be a valid URL")}}),Ee=_e({name:Oe,displayName:ke(we()),contexts:ke(xe(we())),customConfig:ke(_e())}),De=Pe(Se("web"),Se("native"),Se("citrix"),Se("onlineNative"),Se("other")),je=_e({url:Oe}),Ne=_e({src:Oe,size:ke(Oe),type:ke(Oe)}),Fe=_e({src:Oe,size:ke(Oe),type:ke(Oe),label:ke(Oe)}),Le=_e({contexts:xe(Oe),displayName:ke(Oe),resultType:ke(Oe),customConfig:ke(Ie())}),$e=_e({listensFor:ke(Te(Le)),raises:ke(Te(xe(Oe)))}),We=_e({broadcasts:ke(xe(Oe)),listensFor:ke(xe(Oe))}),He=_e({name:Oe,description:ke(Oe),broadcasts:ke(xe(Oe)),listensFor:ke(xe(Oe))}),Ue=_e({intents:ke($e),userChannels:ke(We),appChannels:ke(xe(He))}),qe=_e({url:ke(Oe),top:ke(ve()),left:ke(ve()),width:ke(Re),height:ke(Re)}),Be=_e({name:ke(Oe),type:ke(Oe.where(e=>"window"===e,"Expected a value of window")),title:ke(Oe),version:ke(Oe),customProperties:ke(Ie()),icon:ke(we()),caption:ke(we()),details:ke(qe),intents:ke(xe(Ee)),hidden:ke(Ce())}),Ge=_e({name:Oe,appId:Oe,title:ke(Oe),version:ke(Oe),manifest:Oe,manifestType:Oe,tooltip:ke(Oe),description:ke(Oe),contactEmail:ke(Oe),supportEmail:ke(Oe),publisher:ke(Oe),images:ke(xe(_e({url:ke(Oe)}))),icons:ke(xe(_e({icon:ke(Oe)}))),customConfig:Ie(),intents:ke(xe(Ee))}),Je=_e({appId:ke(Oe),name:ke(Oe),details:ke(je),version:ke(Oe),title:ke(Oe),tooltip:ke(Oe),lang:ke(Oe),description:ke(Oe),categories:ke(xe(Oe)),icons:ke(xe(Ne)),screenshots:ke(xe(Fe)),contactEmail:ke(Oe),supportEmail:ke(Oe),moreInfo:ke(Oe),publisher:ke(Oe),customConfig:ke(xe(Ie())),hostManifests:ke(Ie()),interop:ke(Ue)}),ze=_e({appId:Oe,name:ke(Oe),type:De,details:je,version:ke(Oe),title:ke(Oe),tooltip:ke(Oe),lang:ke(Oe),description:ke(Oe),categories:ke(xe(Oe)),icons:ke(xe(Ne)),screenshots:ke(xe(Fe)),contactEmail:ke(Oe),supportEmail:ke(Oe),moreInfo:ke(Oe),publisher:ke(Oe),customConfig:ke(xe(Ie())),hostManifests:ke(Ie()),interop:ke(Ue),localizedVersions:ke(Te(Je))}),Ve=Pe(Ge,ze),Ke=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Ze{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=Ve.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:Ke(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=Ve.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ke(i.error)}`);const r=this.getUserPropertiesFromDefinition(e,n),s={url:this.getUrl(e,n)},o={name:e.appId,type:"window",createOptions:s,userProperties:{...r,intents:"1.2"===n?r.intents:this.getIntentsFromV2AppDefinition(e),details:s},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 o;const c=Be.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ke(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(o,c.result):o}parseToDesktopAppConfig(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=Ve.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ke(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,s={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"}},o=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!o)return s;if("object"!=typeof o||Array.isArray(o))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(s,o)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e)&&!oe.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.customProperties&&(n.userProperties={...e.userProperties,...t.customProperties}),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 Qe={common:{nonEmptyStringDecoder:Oe,nonNegativeNumberDecoder:Re,regexDecoder:Ae,urlDecoder:Me},fdc3:{allDefinitionsDecoder:Ve,v1DefinitionDecoder:Ge,v2DefinitionDecoder:ze}};var Ye;!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"}(Ye||(Ye={}));const Xe=new class{_fdc3;_decoders=Qe;_errors={intents:Ye};get fdc3(){return this._fdc3||(this._fdc3=(new Ze).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};Xe.fdc3;const et=Xe.decoders;Xe.errors;const tt=I().where(e=>e.length>0,"Expected a non-empty string"),nt=S().where(e=>e>=0,"Expected a non-negative number"),it=O(tt),rt=R(T("system"),T("windows"),T("appManager"),T("layouts"),T("intents"),T("notifications"),T("channels"),T("extension"),T("themes"),T("prefs"),T("ui")),st=R(T("openWindow"),T("windowHello"),T("windowAdded"),T("windowRemoved"),T("getBounds"),T("getFrameBounds"),T("getUrl"),T("moveResize"),T("focus"),T("close"),T("getTitle"),T("setTitle"),T("focusChange"),T("getChannel"),T("notifyChannelsChanged"),T("setZoomFactor"),T("zoomFactorChange"),T("refresh"),T("operationCheck")),ot=R(T("appHello"),T("appDirectoryStateChange"),T("instanceStarted"),T("instanceStopped"),T("applicationStart"),T("instanceStop"),T("clear"),T("operationCheck")),at=R(T("layoutAdded"),T("layoutChanged"),T("layoutRemoved"),T("layoutRenamed"),T("get"),T("getAll"),T("export"),T("import"),T("remove"),T("rename"),T("clientSaveRequest"),T("getGlobalPermissionState"),T("checkGlobalActivated"),T("requestGlobalPermission"),T("getDefaultGlobal"),T("setDefaultGlobal"),T("clearDefaultGlobal"),T("updateMetadata"),T("operationCheck"),T("getCurrent"),T("defaultLayoutChanged"),T("layoutRestored")),ct=R(T("raiseNotification"),T("requestPermission"),T("notificationShow"),T("notificationClick"),T("getPermission"),T("list"),T("notificationRaised"),T("notificationClosed"),T("click"),T("clear"),T("clearAll"),T("configure"),T("getConfiguration"),T("configurationChanged"),T("setState"),T("clearOld"),T("activeCountChange"),T("stateChange"),T("operationCheck"),T("getActiveCount")),dt=R(T("getEnvironment"),T("getBase"),T("platformShutdown"),T("isFdc3DataWrappingSupported"),T("clientError"),T("systemHello"),T("operationCheck")),lt=R(T("top"),T("left"),T("right"),T("bottom")),ht=k({top:S(),left:S(),width:nt,height:nt}),ut=O(k({top:O(S()),left:O(S()),width:O(nt),height:O(nt),context:O(x()),relativeTo:O(tt),relativeDirection:O(lt),windowId:O(tt),layoutComponentId:O(tt)})),pt=k({name:tt,url:tt,options:ut}),gt=k({windowId:O(tt)}),ft=k({windowId:tt,name:tt}),mt=k({windowId:tt}),bt=k({windows:P(ft),isWorkspaceFrame:_()}),yt=k({windowId:tt,title:I()}),wt=k({windowId:tt,hasFocus:_()}),vt=k({windowId:tt,top:O(S()),left:O(S()),width:O(nt),height:O(nt),relative:O(_())}),Ct=k({windowId:tt,bounds:k({top:S(),left:S(),width:nt,height:nt})}),It=k({bounds:k({top:S(),left:S(),width:nt,height:nt})}),St=k({windowId:tt,url:tt}),_t=k({windowId:tt,factorIndex:nt}),xt=x(),Tt=k({top:O(S()),left:O(S()),width:O(nt),height:O(nt)}),kt=k({id:tt,applicationName:tt}),Pt=k({flags:I()}),Ot=k({flags:I()}),Rt=k({windowId:tt,channelsNames:P(tt)}),At=k({enabled:_()}),Mt=k({url:tt,top:O(S()),left:O(S()),width:O(nt),height:O(nt),workspacesSandbox:O(Ot),channelSelector:O(At),iframePermissionsPolicy:O(Pt)}),Et=k({name:tt,displayName:O(I()),contexts:O(P(I())),customConfig:O(k()),resultType:O(I())}),Dt=k({name:tt,type:tt.where(e=>"window"===e,"Expected a value of window"),title:O(tt),version:O(tt),customProperties:O(x()),icon:O(I()),caption:O(I()),details:Mt,intents:O(P(Et)),hidden:O(_()),fdc3:O(et.fdc3.v2DefinitionDecoder)}),jt=k({name:tt}),Nt=k({definitions:P(Dt)}),Ft=k({name:tt,type:tt.where(e=>"window"===e,"Expected a value of window"),instances:P(kt),userProperties:O(x()),title:O(tt),version:O(tt),icon:O(I()),caption:O(tt),fdc3:O(x())}),Lt=k({name:tt,type:tt.where(e=>"window"===e,"Expected a value of window"),userProperties:x(),title:O(tt),version:O(tt),icon:O(I()),caption:O(tt),fdc3:O(x())}),$t=k({appsAdded:P(Lt),appsChanged:P(Lt),appsRemoved:P(Lt)}),Wt=k({apps:P(Ft),initialChannelId:O(tt)}),Ht=k({id:tt}),Ut=R(T("Global"),T("Activity"),T("ApplicationDefault"),T("Swimlane"),T("Workspace")),qt=R(T("application"),T("activity")),Bt=k({context:O(x()),bounds:ht,createArgs:k({name:O(tt),url:O(tt),context:O(x())}),windowState:O(tt),restoreState:O(tt),instanceId:tt,isCollapsed:O(_()),isSticky:O(_()),restoreSettings:k({groupId:O(tt),groupZOrder:O(S())}),channelId:O(tt)}),Gt=k({type:T("window"),componentType:O(qt),application:tt,state:Bt}),Jt=k({type:T("window"),config:k({appName:tt,url:O(tt),title:O(I()),allowExtract:O(_()),allowReorder:O(_()),showCloseButton:O(_()),isMaximized:O(_()),instanceId:O(tt)})}),zt=k({type:T("group"),config:x(),children:P(R(Jt))}),Vt=k({type:T("column"),config:x(),children:P(R(zt,Jt,E(()=>Vt),E(()=>Kt)))}),Kt=k({type:T("row"),config:x(),children:P(R(Vt,zt,Jt,E(()=>Kt)))}),Zt=k({config:x(),context:x(),children:P(R(Kt,Vt,zt,Jt))}),Qt=k({type:T("Workspace"),application:O(tt),state:Zt}),Yt=k({bounds:ht,instanceId:tt,selectedWorkspace:nt,workspaces:P(Zt),windowState:O(tt),restoreState:O(tt),context:O(x())}),Xt=k({type:T("workspaceFrame"),application:tt,componentType:O(qt),state:Yt}),en=k({name:tt,type:Ut,token:O(tt),components:P(R(Gt,Qt,Xt)),context:O(x()),metadata:O(x()),version:O(S())}),tn=k({name:tt,type:Ut,token:O(tt),components:P(R(Gt,Qt,Xt)),context:O(x()),metadata:O(x()),version:O(S()),prevName:tt}),nn=k({name:tt,context:O(x()),metadata:O(x()),instances:O(P(tt)),ignoreInstances:O(P(tt)),setAsCurrent:O(_()),ignoreContexts:O(_()),saveWindowContexts:O(_())}),rn=k({name:tt,context:O(x()),closeRunningInstance:O(_()),closeMe:O(_()),timeout:O(nt)}),sn=k({name:tt,type:Ut,context:O(x()),metadata:O(x())}),on=k({name:tt,type:Ut}),an=k({layout:nn}),cn=k({layout:en,newName:tt}),dn=k({status:tt}),ln=k({layout:en}),hn=k({layout:rn}),un=k({type:Ut}),pn=k({layouts:P(en)}),gn=O(k({name:tt})),fn=R(T("replace"),T("merge")),mn=k({layouts:P(en),mode:fn,skipManagerRequest:O(_())}),bn=k({summaries:P(sn)}),yn=k({layout:en}),wn=k({layout:O(en)}),vn=k({name:tt}),Cn=R(T("findIntent"),T("getIntents"),T("getIntentsByHandler"),T("raise"),T("filterHandlers")),In=k({applicationName:tt,applicationTitle:O(I()),applicationDescription:O(I()),applicationIcon:O(I()),type:R(T("app"),T("instance")),displayName:O(I()),contextTypes:O(P(tt)),instanceId:O(I()),instanceTitle:O(I()),resultType:O(I()),customConfig:O(k())});k({applicationName:I(),applicationIcon:O(I()),instanceId:O(I())}),k({intent:tt,handler:In});const Sn=k({name:tt,handlers:P(In)}),_n=R(T("startNew"),T("reuse"),k({app:O(tt),instance:O(tt)})),xn=k({type:O(tt),data:O(x())}),Tn=P(Sn),kn=k({intents:Tn}),Pn=k({name:O(tt),contextType:O(tt),resultType:O(tt)}),On=R(tt,Pn),Rn=k({filter:O(Pn)}),An=k({top:O(S()),left:O(S()),width:O(nt),height:O(nt),relativeTo:O(tt),relativeDirection:O(lt),waitForAGMReady:O(_()),channelId:O(tt)}),Mn=k({intent:tt,target:O(_n),context:O(xn),options:O(An),handlers:O(P(In)),timeout:O(nt),waitUserResponseIndefinitely:O(_()),clearSavedHandler:O(_())}),En=k({interopInstance:tt,name:O(tt)}),Dn=k({originApp:En,intentRequest:O(Mn)}),jn=k({name:tt,waitForAGMReady:_(),id:O(tt),context:O(x()),top:O(S()),left:O(S()),width:O(nt),height:O(nt),relativeTo:O(tt),relativeDirection:O(lt),forceChromeTab:O(_()),layoutComponentId:O(tt),channelId:O(tt),startReason:Dn}),Nn=R(tt,Mn),Fn=k({enabled:_(),appName:tt,waitResponseTimeout:S()}),Ln=R(k({applicationName:tt}),k({instanceId:tt})),$n=k({title:O(tt),openResolver:O(_()),timeout:O(nt),intent:O(tt),contextTypes:O(P(tt)),resultType:O(tt),applicationNames:O(P(tt)),excludeList:O(P(Ln))}),Wn=k({enabled:_(),initialCaller:k({instanceId:tt})}),Hn=k({intentRequest:Mn,resolverConfig:Fn,embeddedResolverConfig:O(Wn)}),Un=k({request:Mn,handler:In,result:x()}),qn=k({handlers:P(In)}),Bn=k({filterHandlersRequest:$n,resolverConfig:Fn,embeddedResolverConfig:O(Wn)}),Gn=k({intent:tt,contextTypes:O(P(tt)),displayName:O(I()),icon:O(I()),description:O(I()),resultType:O(I()),customConfig:O(k())}),Jn=R(tt,Gn),zn=k({intent:tt,contextTypes:O(P(tt)),description:O(tt),displayName:O(tt),icon:O(tt),resultType:O(tt)}),Vn=k({intents:P(zn)}),Kn=e=>tt.where(t=>e.includes(t),"Expected a valid channel name"),Zn=k({contextType:O(tt)}),Qn=O(R(tt,k({name:O(tt),fdc3:O(_())}))),Yn=k({windowId:it,channel:it}),Xn=x().where(e=>"string"==typeof e.type,"Expected a valid FDC3 Context with compulsory 'type' field"),ei=k({method:tt,arguments:O(x()),target:O(R(T("all"),T("best")))}),ti=k({action:I(),title:tt,icon:O(I()),interop:O(ei)}),ni=R(T("Active"),T("Acknowledged"),T("Seen"),T("Closed"),T("Stale"),T("Snoozed"),T("Processing")),ii=k({count:S()}),ri=k({badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(nt),vibrate:O(P(S()))}),si=k({title:tt,clickInterop:O(ei),actions:O(P(ti)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(nt),vibrate:O(P(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ni)}),oi=k({id:tt,state:ni});k().where(e=>!e.fdc3||"string"==typeof e.fdc3.type,"Expected a valid FDC3 Context with compulsory 'type' field");const ai=k({color:O(tt),icon:O(tt),name:O(tt),glyph:O(tt)}),ci=k({id:tt,displayMetadata:O(ai)}),di=k({color:tt,fdc3:O(ci)}),li=k({name:tt,meta:di,data:O(k())}),hi=k({path:tt,value:x()}),ui=P(hi),pi=k({name:tt}),gi=k({name:tt,read:_(),write:_(),windowId:O(tt)}),fi=k({name:tt,read:_(),write:_(),windowId:tt}),mi=k({config:fi}),bi=k({channels:P(gi)}),yi=k({windowId:tt}),wi=k({read:_(),write:_(),windowId:O(tt)}),vi=k({restrictions:wi}),Ci=k({settings:si,id:tt}),Ii=k({settings:si}),Si=k({permissionGranted:_()}),_i=k({permission:R(T("default"),T("granted"),T("denied"))}),xi=k({definition:ri,action:O(I()),id:O(tt)}),Ti=k({allowed:O(P(tt)),blocked:O(P(tt))}),ki=k({enable:O(_()),enableToasts:O(_()),sourceFilter:O(Ti),showNotificationBadge:O(_())}),Pi=k({configuration:ki}),Oi=k({configuration:k({enable:_(),enableToasts:_(),sourceFilter:k({allowed:P(tt),blocked:P(tt)})})}),Ri=k({layoutType:R(T("Global"),T("Workspace")),layoutName:tt,context:O(x())}),Ai=k({windowContext:O(x())}),Mi=k({state:R(T("prompt"),T("denied"),T("granted"))}),Ei=k({isAvailable:_()}),Di=k({itemId:tt}),ji=k({isSupported:_()}),Ni=k({operation:tt}),Fi=k({bounds:ht}),Li=k({displayName:tt,name:tt}),$i=k({theme:Li}),Wi=k({themes:P(Li)}),Hi=k({name:tt}),Ui=k({id:tt,title:tt,clickInterop:O(ei),actions:O(P(ti)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(nt),vibrate:O(P(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ni)}),qi=k({notification:Ui}),Bi=k({notifications:P(Ui)}),Gi=k({id:tt}),Ji=k({channel:tt}),zi=k({windowIds:P(tt)}),Vi=R(T("appHello"),T("addChannel"),T("getMyChannel"),T("getWindowIdsOnChannel"),T("getWindowIdsWithChannels"),T("joinChannel"),T("restrict"),T("getRestrictions"),T("restrictAll"),T("notifyChannelsChanged"),T("leaveChannel"),T("getMode"),T("operationCheck")),Ki=R(T("single"),T("multi")),Zi=k({mode:Ki}),Qi=k({windowId:tt}),Yi=k({mode:Ki,channels:P(tt),restrictions:P(gi)}),Xi=k({channel:O(tt)}),er=k({application:O(tt),channels:O(P(tt)),windowIds:O(P(tt))}),tr=k({filter:O(er)}),nr=k({windowIdsWithChannels:P(k({application:tt,channel:O(tt),windowId:tt}))}),ir=O(x()),rr=O(k({top:O(S()),left:O(S()),width:O(nt),height:O(nt),relativeTo:O(tt),relativeDirection:O(lt),waitForAGMReady:O(_()),channelId:O(tt),reuseId:O(tt),originIntentRequest:O(Mn)})),sr=k({channel:tt,windowId:tt}),or=k({windowId:tt,channelName:O(tt)}),ar=k({windowId:tt,channelNames:P(tt)}),cr=k({channel:O(tt)}),dr=R(T("clear"),T("clearAll"),T("get"),T("getAll"),T("set"),T("update"),T("prefsChanged"),T("prefsHello"),T("operationCheck"),T("registerSubscriber")),lr=k({app:tt,data:k(),lastUpdate:O(tt)}),hr=k({app:tt}),ur=k({prefs:lr}),pr=k({all:P(lr)}),gr=k({interopId:tt,appName:O(tt)}),fr=k({app:tt,data:k()}),mr=k({platform:k({app:tt}),validNonExistentApps:O(P(tt)),isAppValidationEnabled:O(_())}),br=k({message:tt}),yr=k({isClientErrorOperationSupported:_()}),wr=et.common.nonEmptyStringDecoder,vr=et.common.nonNegativeNumberDecoder,Cr=k({bundle:wr,styles:P(wr),fonts:O(P(wr))}),Ir=k({bundle:wr,styles:P(wr),fonts:O(P(wr))}),Sr=k({bundle:wr,styles:P(wr),fonts:O(P(wr))}),_r=R(T("directional"),T("default")),xr=k({type:O(_r),enable:O(_())}),Tr=R(T("top-left"),T("top-center"),T("top-right"),T("center-left"),T("center-right"),T("bottom-left"),T("bottom-center"),T("bottom-right")),kr=R(T("all"),T("fdc3")),Pr=k({selector:O(xr),displayMode:O(kr)}),Or=k({channels:O(Pr),position:O(Tr),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),Rr=k({enable:_(),awaitFactory:O(_()),timeout:O(vr),channels:O(Pr),position:O(Tr),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),Ar=k({alerts:O(k({enabled:_()})),dialogs:O(k({enabled:_()})),awaitFactory:O(_()),timeout:O(vr)}),Mr=R(T("getResources"),T("operationCheck"),T("showAlert"),T("showDialog"),T("alertInteropAction"),T("showResolver")),Er=k({origin:wr}),Dr=k({blockedOrigin:T(!0)}),jr=A(Dr,k({blockedOrigin:T(!1),config:Or,sources:Cr})),Nr=A(Dr,k({blockedOrigin:T(!1),sources:Ir})),Fr=A(Dr,k({blockedOrigin:T(!1),sources:Sr})),Lr=k({widget:O(jr),modals:O(Nr),intentResolver:O(Fr)}),$r=k({resources:Lr}),Wr=k({method:wr,arguments:O(x()),target:O(R(T("best"),T("all"),wr))}),Hr=R(T("Global"),T("WindowContainer"),wr),Ur=k({instance:wr,container:O(R(T("Global"),T("WindowContainer")))}),qr=k({variant:R(T("default"),T("success"),T("critical"),T("info"),T("warning")),text:wr,showCloseButton:O(_()),clickInterop:O(Wr),onCloseInterop:O(Wr),actions:O(P(k({id:wr,title:wr,clickInterop:Wr}))),data:O(x()),ttl:O(vr),target:O(Hr)}),Br=k({config:qr,target:Ur}),Gr=k({templateName:wr,variables:x(),target:O(Hr),timer:O(k({duration:vr})),size:O(k({width:vr,height:vr})),movable:O(_()),transparent:O(_())}),Jr=k({isExpired:O(_()),isClosed:O(_()),isEnterPressed:O(_()),responseButtonClicked:O(k({id:wr,text:wr})),inputs:O(P(k({type:R(T("checkbox"),T("email"),T("number"),T("password"),T("text")),id:wr,checked:O(_()),value:O(I())})))});k({result:Jr});const zr=k({config:Gr,target:Ur}),Vr=k({id:wr}),Kr=k({id:wr,responsePromise:x()}),Zr=k({response:Jr}),Qr=k({name:wr,settings:Wr}),Yr=k({interopAction:Qr}),Xr=k({interopAction:Qr}),es=k({enable:_(),awaitFactory:O(_()),timeout:O(vr)}),ts=k({id:wr}),ns=k({preserveChoice:_()}),is=k({intent:wr,handler:In,userSettings:ns}),rs=k({isExpired:O(_()),isClosed:O(_()),userChoice:O(is)}),ss=k({response:rs}),os=M(A(k({intentRequest:Mn}),k({handlerFilter:$n})),k({timeout:vr})),as=k({config:os}),cs=k({result:rs}),ds={openWindow:{name:"openWindow",dataDecoder:pt,resultDecoder:ft},windowHello:{name:"windowHello",dataDecoder:gt,resultDecoder:bt},windowAdded:{name:"windowAdded",dataDecoder:ft},windowRemoved:{name:"windowRemoved",dataDecoder:mt},getBounds:{name:"getBounds",dataDecoder:mt,resultDecoder:Ct},getFrameBounds:{name:"getFrameBounds",dataDecoder:mt,resultDecoder:It},getUrl:{name:"getUrl",dataDecoder:mt,resultDecoder:St},moveResize:{name:"moveResize",dataDecoder:vt},focus:{name:"focus",dataDecoder:mt},close:{name:"close",dataDecoder:mt},getTitle:{name:"getTitle",dataDecoder:mt,resultDecoder:yt},setTitle:{name:"setTitle",dataDecoder:yt},focusChange:{name:"focusChange",dataDecoder:wt},getChannel:{name:"getChannel",dataDecoder:mt,resultDecoder:cr},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:ar},setZoomFactor:{name:"setZoomFactor",dataDecoder:_t},zoomFactorChange:{name:"zoomFactorChange",dataDecoder:_t},refresh:{name:"refresh",dataDecoder:mt},operationCheck:{name:"operationCheck"}};function ls(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 s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.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 s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}ls.default=ls;var hs=e(ls);const us=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class ps{_id;_name;_bridge;_logger;registry=hs();myCtxKey;ctxUnsubscribe;zoomFactorIndex=7;me;constructor(e,t,n,i){this._id=e,this._name=t,this._bridge=n,this._logger=i,this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}get zoomFactor(){return us[this.zoomFactorIndex]}clean(){this.ctxUnsubscribe&&this.ctxUnsubscribe()}processSelfFocusEvent(e){this.me.isFocused=e,this.registry.execute("focus-change",this.me)}processChannelsChangedEvent(e){this.registry.execute("channels-changed",e)}processSelfZoomFactorChangedEvent(e){this.zoomFactorIndex=e,this.registry.execute("zoom-factor-changed",this.me)}async toApi(){return this.ctxUnsubscribe=await this._bridge.contextLib.subscribe(this.myCtxKey,e=>this.registry.execute("context-updated",e)),this.me={id:this.id,name:this.name,isFocused:!1,zoomFactor:this.zoomFactor,getURL:this.getURL.bind(this),moveResize:this.moveResize.bind(this),resizeTo:this.resizeTo.bind(this),moveTo:this.moveTo.bind(this),focus:this.focus.bind(this),close:this.close.bind(this),getTitle:this.getTitle.bind(this),setTitle:this.setTitle.bind(this),getBounds:this.getBounds.bind(this),getContext:this.getContext.bind(this),updateContext:this.updateContext.bind(this),setContext:this.setContext.bind(this),refresh:this.refresh.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),zoomIn:this.zoomIn.bind(this),zoomOut:this.zoomOut.bind(this),setZoomFactor:this.setZoomFactor.bind(this),onZoomFactorChanged:this.onZoomFactorChanged.bind(this)},Object.defineProperties(this.me,{id:Q,name:Q,zoomFactor:{get:()=>this.zoomFactor,enumerable:!0}}),this.me}async getURL(){return(await this._bridge.send("windows",ds.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"):this.registry.add("focus-change",e)}async moveResize(e){const t=X(Tt,e),n=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",ds.moveResize,n),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(nt,e),void 0!==t&&X(nt,t);const n=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",ds.moveResize,n),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(S(),e),void 0!==t&&X(S(),t);const n=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",ds.moveResize,n),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",ds.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",ds.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",ds.getTitle,{windowId:this.id})).title}async setTitle(e){const t=X(tt,e);return await this._bridge.send("windows",ds.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",ds.getBounds,{windowId:this.id})).bounds}async getContext(){const e=await this._bridge.contextLib.get(this.myCtxKey),{___io___:t,...n}=e;return n}async updateContext(e){const t=X(xt,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=X(xt,e),n=await this._bridge.contextLib.get(this.myCtxKey),i=n.___io___?{...t,___io___:n.___io___}:t;return await this._bridge.contextLib.set(this.myCtxKey,i),this.me}onContextUpdated(e){if("function"!=typeof e)return re.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",t=>{const{___io___:n,...i}=t;e(i,this.me)})}async getChannel(){return(await this._bridge.send("windows",ds.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}getClosestZoomFactorIndex(e){const t=Object.entries(us).reduce((t,[n,i])=>Math.abs(i-e)<=Math.abs(us[t]-e)?parseInt(n):t,0),n=us[t];return n!==e&&this._logger.warn(`Zoom factor ${e} is not available, using closest value ${n} instead.`),t}async zoom(e){e!==this.zoomFactorIndex&&e in us&&(await this._bridge.send("windows",ds.setZoomFactor,{windowId:this.id,factorIndex:e},void 0,{includeOperationCheck:!0}),this.zoomFactorIndex=e)}async zoomIn(){return await this.zoom(this.zoomFactorIndex+1),this.me}async zoomOut(){return await this.zoom(this.zoomFactorIndex-1),this.me}async setZoomFactor(e){const t=X(S(),e),n=this.getClosestZoomFactorIndex(t);return await this.zoom(n),this.me}onZoomFactorChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"):this.registry.add("zoom-factor-changed",e)}async refresh(){return await this._bridge.send("windows",ds.refresh,{windowId:this.id},void 0,{includeOperationCheck:!0}),this.me}}const gs={operationCheck:{name:"operationCheck",dataDecoder:Ni,resultDecoder:ji},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:Fi,dataDecoder:Di}},fs=(e,t,n)=>new Promise((i,r)=>{let s=!0;const o=setTimeout(()=>{if(!s)return;s=!1;r(n||`Promise timeout hit: ${t}`)},t);e().then(e=>{s&&(s=!1,clearTimeout(o),i(e))}).catch(e=>{s&&(s=!1,clearTimeout(o),r(e))})}),ms=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class bs{supportedOperationsNames=[];focusEventHandler;registry=hs();platformRegistration;ioc;bridge;publicWindowId;allWindowProjections=[];me;logger;isWorkspaceFrame;instanceId;channelsController;async start(e,t){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=t.publicWindowId,this.addWindowOperationExecutors(),this.ioc=t,this.bridge=t.bridge,this.instanceId=e.interop.instance.instance,this.channelsController=t.channelsController,this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`),this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,await this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const n=this.toApi();e.windows=n}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}async handleBridgeMessage(e){await this.platformRegistration;const t=X(st,e.operation),n=ds[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async open(e,t,n){X(tt,e),X(tt,t);const i=X(ut,n),r=await this.bridge.send("windows",ds.openWindow,{name:e,url:t,options:i});return this.waitForWindowAdded(r.windowId)}list(){return this.allWindowProjections.map(e=>e.api)}findById(e){return X(tt,e),this.allWindowProjections.find(t=>t.id===e)?.api}toApi(){return{open:this.open.bind(this),my:this.my.bind(this),list:this.list.bind(this),findById:this.findById.bind(this),onWindowAdded:this.onWindowAdded.bind(this),onWindowRemoved:this.onWindowRemoved.bind(this),onWindowGotFocus:this.onWindowGotFocus.bind(this),onWindowLostFocus:this.onWindowLostFocus.bind(this)}}addWindowOperationExecutors(){ds.focusChange.execute=this.handleFocusChangeEvent.bind(this),ds.windowAdded.execute=this.handleWindowAdded.bind(this),ds.windowRemoved.execute=this.handleWindowRemoved.bind(this),ds.getBounds.execute=this.handleGetBounds.bind(this),ds.getFrameBounds.execute=this.handleGetBounds.bind(this),ds.getTitle.execute=this.handleGetTitle.bind(this),ds.getUrl.execute=this.handleGetUrl.bind(this),ds.moveResize.execute=this.handleMoveResize.bind(this),ds.setTitle.execute=this.handleSetTitle.bind(this),ds.getChannel.execute=this.handleGetChannel.bind(this),ds.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this),ds.setZoomFactor.execute=this.handleSetZoomFactor.bind(this),ds.zoomFactorChange.execute=this.handleZoomFactorChanged.bind(this),ds.refresh.execute=this.handleRefresh.bind(this),ds.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(ds)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"):this.registry.add("window-added",e)}onWindowRemoved(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"):this.registry.add("window-removed",e)}onWindowGotFocus(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"):this.registry.add("window-got-focus",e)}onWindowLostFocus(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"):this.registry.add("window-lost-focus",e)}async sayHello(){return await this.bridge.send("windows",ds.windowHello,{windowId:this.publicWindowId})}async registerWithPlatform(){const{windows:e,isWorkspaceFrame:t}=await this.sayHello();if(this.isWorkspaceFrame=t,this.logger.trace("the platform responded to the hello message"),!this.isWorkspaceFrame&&this.publicWindowId){this.logger.trace("i am not treated as a workspace frame, setting my window");const t=e.find(e=>e.windowId===this.publicWindowId);if(!t){const t=e.map(e=>`${e.windowId}:${e.name}`).join(", ");return re.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${t}`)}const n=await this.ioc.buildWebWindow(this.publicWindowId,t.name,this.logger);this.me=n.api,this.allWindowProjections.push(n)}const n=await Promise.all(e.filter(e=>e.windowId!==this.publicWindowId).map(e=>this.ioc.buildWebWindow(e.windowId,e.name,this.logger)));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...n)}async handleFocusChangeEvent(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);if(!t)return;t.model.processSelfFocusEvent(e.hasFocus);const n=e.hasFocus?"window-got-focus":"window-lost-focus";this.registry.execute(n,t.api)}async handleWindowAdded(e){if(this.allWindowProjections.some(t=>t.id===e.windowId))return;const t=await this.ioc.buildWebWindow(e.windowId,e.name,this.logger);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}async handleWindowRemoved(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&(this.allWindowProjections=this.allWindowProjections.filter(t=>t.id!==e.windowId),t.model.clean(),this.registry.execute("window-removed",t.api))}async handleGetBounds(){return this.me||this.isWorkspaceFrame?{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}:re.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe")}async handleGetTitle(){return this.me?{windowId:this.me.id,title:document.title}:re.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe")}async handleGetUrl(){return this.me?{windowId:this.me.id,url:window.location.href}:re.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe")}async handleMoveResize(e){const t="number"==typeof e.top?e.top:e.relative?0:window.screenTop,n="number"==typeof e.left?e.left:e.relative?0:window.screenLeft,i="number"==typeof e.height?e.height:e.relative?0:window.innerHeight,r="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,s=e.relative?window.moveBy:window.moveTo,o=e.relative?window.resizeBy:window.resizeTo;s(n,t),o(r,i)}async handleSetTitle(e){document.title=e.title}async initializeFocusTracking(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{await this.bridge.send("windows",gs.operationCheck,{operation:"focusChange"})}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client.")}const e=document.hasFocus();await this.transmitFocusChange(!0),e||await this.transmitFocusChange(!1),this.defineEventListeners()}processFocusEvent(){const e=document.hasFocus();this.transmitFocusChange(e)}waitForWindowAdded(e){const t=this.allWindowProjections.find(t=>t.id===e);return t?Promise.resolve(t.api):ms(t=>{const n=this.onWindowAdded(i=>{i.id===e&&(n(),t(i))})},3e4,`Timed out waiting for ${e} to be announced`)}async transmitFocusChange(e){const t={windowId:this.me?.id||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),await this.bridge.send("windows",ds.focusChange,t)}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}async handleGetChannel(){if(!this.me)return re.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleRefresh(){if(!this.me)return re.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe");setTimeout(()=>{window.location.reload()},0)}async handleChannelsChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t?.model.processChannelsChangedEvent(e.channelNames)}async handleSetZoomFactor(e){if(!this.me)return re.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe");document.body.style.zoom=`${us[e.factorIndex]}%`}async handleZoomFactorChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&t.model.processSelfZoomFactorChangedEvent(e.factorIndex)}}const ys="T42.Web.Platform.Control",ws="T42.Web.Platform.Stream",vs="T42.Web.Client.Control",Cs="T42.Core.Plus.Themes.Stream";class Is{coreGlue;communicationId;platformMethodTimeoutMs=1e4;controllers;sub;running;constructor(e,t){this.coreGlue=e,this.communicationId=t}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}async stop(){this.running=!1,this.sub.close(),await this.coreGlue.interop.unregister(vs)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(ys),this.checkWaitMethod(ws)]);const t=this.communicationId,[n]=await Promise.all([this.coreGlue.interop.subscribe(ws,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(vs,(e,t,n,i)=>this.passMessageController(e,n,i))]);this.sub=n,this.sub.onData(e=>this.passMessageController(e.data))}getInteropInstance(e){const t=this.coreGlue.interop.servers().find(t=>t.windowId&&t.windowId===e);return{application:t?.application,applicationName:t?.applicationName,peerId:t?.peerId,instance:t?.instance,windowId:t?.windowId}}async send(e,t,n,i,r){if(t.dataDecoder)try{t.dataDecoder.runWithException(n)}catch(e){return re.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!r?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return re.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const r=await this.transmitMessage(e,t,n,i);return t.resultDecoder&&t.resultDecoder.runWithException(r),r}catch(e){return e?.kind?re.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):re.raiseError(e)}}async createThemesSubscription(){return this.coreGlue.interop.methods().some(e=>e.name===Cs)?this.coreGlue.interop.subscribe(Cs,this.communicationId?{target:{instance:this.communicationId}}:void 0):re.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.")}async checkOperationSupported(e,t){try{return await this.send(e,gs.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return ms(t=>{if(this.coreGlue.interop.methods().some(t=>{const n=t.name===e,i=!this.communicationId||t.getServers().some(e=>e.instance===this.communicationId);return n&&i}))return t();const n=this.coreGlue.interop.serverMethodAdded(i=>{const r=i.method,s=i.server,o=!this.communicationId||s.instance===this.communicationId;r.name===e&&o&&(n(),t())})},this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,n){const i=rt.run(e.domain);if(!i.ok)return void(n&&n(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(i.error)}`));const r=i.result;this.controllers[r].handleBridgeMessage(e).then(e=>{t&&t(e)}).catch(e=>{n&&n(e),console.warn(e)})}async transmitMessage(e,t,n,i){const r={domain:e,data:n,operation:t.name};let s;const o=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(t.name)} with data: ${JSON.stringify(n)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(s=await this.coreGlue.interop.invoke(ys,r,a?{instance:this.communicationId}:void 0,i),!s)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(s.all_return_values)||0===s.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;throw new Error(`${o} -> Inner message: ${t}`)}throw new Error(`${o} -> Inner message: ${e.message}`)}return s.all_return_values[0].returned}}const Ss={appHello:{name:"appHello",dataDecoder:gt,resultDecoder:Wt},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:$t},instanceStarted:{name:"instanceStarted",dataDecoder:kt},instanceStopped:{name:"instanceStopped",dataDecoder:kt},applicationStart:{name:"applicationStart",dataDecoder:jn,resultDecoder:kt},instanceStop:{name:"instanceStop",dataDecoder:Ht},import:{name:"import"},remove:{name:"remove",dataDecoder:jt},export:{name:"export",resultDecoder:Nt},clear:{name:"clear"},operationCheck:{name:"operationCheck"}};class _s{me;supportedOperationsNames=[];baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=hs();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;interop;initialChannelId;handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}async start(e,t){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=t.publicWindowId,this.addOperationsExecutors(),this.ioc=t,this.bridge=t.bridge,this.channelsController=t.channelsController,this.interop=e.interop,this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const n=this.toApi();e.appManager=n}async postStart(){this.initialChannelId&&await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId)}async handleBridgeMessage(e){await this.platformRegistration;const t=X(ot,e.operation),n=Ss[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}onInstanceStarted(e){return"function"!=typeof e?re.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?re.raiseError("onInstanceStopped requires a single argument of type function"):this.registry.add("instance-stopped",e)}async startApplication(e,t,n){const i=await this.channelsController.all();if(n?.channelId&&!i.includes(n.channelId))return re.raiseError(`The channel with name "${n.channelId}" doesn't exist!`);const r={name:e,waitForAGMReady:n?.waitForAGMReady??!0,context:t,top:n?.top,left:n?.left,width:n?.width,height:n?.height,relativeTo:n?.relativeTo,relativeDirection:n?.relativeDirection,id:n?.reuseId,forceChromeTab:n?.forceTab,layoutComponentId:n?.layoutComponentId,channelId:n?.channelId,startReason:{originApp:{name:this.me?.application.name,interopInstance:this.interop.instance.instance}}};n?.originIntentRequest&&(r.startReason.intentRequest=n.originIntentRequest);const s=await this.bridge.send("appManager",Ss.applicationStart,r),o=this.applications.find(e=>e.name===s.applicationName);return this.ioc.buildInstance(s,o)}getApplication(e){const t=X(tt,e);return this.applications.find(e=>e.name===t)}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?re.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?re.raiseError("onAppRemoved requires a single argument of type function"):this.registry.add("application-removed",e)}toApi(){return{myInstance:this.me,inMemory:{import:this.importApps.bind(this),remove:this.remove.bind(this),export:this.exportApps.bind(this),clear:this.clear.bind(this)},application:this.getApplication.bind(this),applications:this.getApplications.bind(this),instances:this.getInstances.bind(this),onAppAdded:this.onAppAdded.bind(this),onAppChanged:this.onAppChanged.bind(this),onAppRemoved:this.onAppRemoved.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)}}addOperationsExecutors(){Ss.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),Ss.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),Ss.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this),Ss.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Ss)}async handleAppDirectoryStateChange(e){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}onAppChanged(e){return"function"!=typeof e?re.raiseError("onAppChanged requires a single argument of type function"):this.registry.add("application-changed",e)}async handleApplicationAddedMessage(e){if(this.applications.some(t=>t.name===e.name))return;const t=await this.ioc.buildApplication(e,[]),n=this.instances.filter(e=>e.application.name===t.name);t.instances.push(...n),this.applications.push(t),this.registry.execute("application-added",t)}async handleApplicationRemovedMessage(e){const t=this.applications.findIndex(t=>t.name===e.name);if(t<0)return;const n=this.applications[t];this.applications.splice(t,1),this.registry.execute("application-removed",n)}async handleApplicationChangedMessage(e){const t=this.applications.find(t=>t.name===e.name);if(!t)return this.handleApplicationAddedMessage(e);t.title=e.title,t.version=e.version,t.icon=e.icon,t.caption=e.caption,t.userProperties=e.userProperties,this.registry.execute("application-changed",t)}async handleInstanceStartedMessage(e){if(this.instances.some(t=>t.id===e.id))return;const t=this.applications.find(t=>t.name===e.applicationName);if(!t)return re.raiseError(`Cannot add instance: ${e.id}, because there is no application definition associated with it`);const n=this.ioc.buildInstance(e,t);this.instances.push(n),t.instances.push(n),this.registry.execute("instance-started",n)}async handleInstanceStoppedMessage(e){const t=this.instances.find(t=>t.id===e.id);if(t){const t=this.instances.findIndex(t=>t.id===e.id);this.instances.splice(t,1)}const n=this.applications.find(t=>t.instances.some(t=>t.id===e.id));if(n){const t=n.instances.findIndex(t=>t.id===e.id);n.instances.splice(t,1)}t&&this.registry.execute("instance-stopped",t)}async importApps(e,t="replace"){if(X(fn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return re.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const n=e.reduce((e,t)=>{const{isValid:n,error:i}=this.isValidDefinition(t);return n?e.valid.push(t):e.invalid.push({app:t?.name,error:i??`Provided definition is invalid ${JSON.stringify(t)}`}),e},{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*n.valid.length;return await this.bridge.send("appManager",Ss.import,{definitions:n.valid,mode:t},{methodResponseTimeoutMs:i}),{imported:n.valid.map(e=>e.name),errors:n.invalid}}isValidDefinition(e){if(e?.appId&&e?.details){const t=et.fdc3.v2DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v2 definition. Error: ${JSON.stringify(t.error)}`}}if(e?.appId&&e?.manifest){const t=et.fdc3.v1DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v1 definition. Error: ${JSON.stringify(t.error)}`}}const t=Dt.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid definition. Error: ${JSON.stringify(t.error)}`}}async remove(e){X(tt,e),await this.bridge.send("appManager",Ss.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",Ss.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",Ss.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async registerWithPlatform(){const e=await this.bridge.send("appManager",Ss.appHello,{windowId:this.publicWindowId},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS});this.logger.trace("the platform responded to the hello message with a full list of apps"),this.applications=await Promise.all(e.apps.map(e=>this.ioc.buildApplication(e,e.instances))),this.instances=this.applications.reduce((e,t)=>(e.push(...t.instances),e),[]),this.me=this.findMyInstance(),this.logger.trace(`all applications were parsed and saved. I am ${this.me?"NOT a":"a"} valid instance`),this.initialChannelId=e.initialChannelId}findMyInstance(){for(const e of this.applications){const t=e.instances.find(e=>e.id===this.publicWindowId);if(t)return t}}}class xs{data;bridge;application;me;myCtxKey;constructor(e,t,n){this.data=e,this.bridge=t,this.application=n,this.myCtxKey=`___instance___${this.data.id}`}toApi(){const e=this.bridge.getInteropInstance(this.data.id),t={id:this.data.id,agm:e,application:this.application,stop:this.stop.bind(this),getContext:this.getContext.bind(this)};return this.me=Object.freeze(t),this.me}async getContext(){return this.bridge.contextLib.get(this.myCtxKey)}async stop(){await this.bridge.send("appManager",Ss.instanceStop,{id:this.data.id})}}class Ts{data;instances;controller;me;constructor(e,t,n){this.data=e,this.instances=t,this.controller=n}toApi(){const e={name:this.data.name,title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,userProperties:this.data.userProperties,instances:this.instances,start:this.start.bind(this),getConfiguration:this.getConfiguration.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?re.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStarted(t=>{t.application.name===this.data.name&&e(t)})}onInstanceStopped(e){return"function"!=typeof e?re.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStopped(t=>{t.application.name===this.data.name&&e(t)})}async start(e,t){const n=X(ir,e),i=X(rr,t);return this.controller.startApplication(this.data.name,n,i)}async getConfiguration(){const{details:e,intents:t,hidden:n,...i}=this.data.userProperties,r={name:this.data.name,type:this.data.type,details:e,customProperties:i},s={title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,intents:t,hidden:n,fdc3:this.data.fdc3};for(const[e,t]of Object.entries(s))void 0!==t&&(r[e]=t);return r}}const ks={layoutAdded:{name:"layoutAdded",dataDecoder:en},layoutChanged:{name:"layoutChanged",dataDecoder:en},layoutRemoved:{name:"layoutRemoved",dataDecoder:en},layoutRestored:{name:"layoutRestored",dataDecoder:en},defaultLayoutChanged:{name:"defaultLayoutChanged",dataDecoder:gn},layoutRenamed:{name:"layoutRenamed",dataDecoder:tn},get:{name:"get",dataDecoder:on,resultDecoder:wn},getAll:{name:"getAll",dataDecoder:un,resultDecoder:bn},export:{name:"export",dataDecoder:un,resultDecoder:pn},import:{name:"import",dataDecoder:mn},remove:{name:"remove",dataDecoder:on},rename:{name:"rename",dataDecoder:cn,resultDecoder:dn},save:{name:"save",dataDecoder:an,resultDecoder:yn},restore:{name:"restore",dataDecoder:hn},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:Ri,resultDecoder:Ai},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:Mi},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:Ei},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:Ei},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:wn},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:vn},clearDefaultGlobal:{name:"clearDefaultGlobal"},getCurrent:{name:"getCurrent",resultDecoder:wn},updateMetadata:{name:"updateMetadata",dataDecoder:ln},operationCheck:{name:"operationCheck"}};class Ps{supportedOperationsNames=[];defaultLayoutRestoreTimeoutMS=12e4;registry=hs();bridge;logger;windowsController;saveRequestSubscription;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=t.bridge,this.windowsController=t.windowsController,this.addOperationsExecutors();const n=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=n}async handleBridgeMessage(e){const t=X(at,e.operation),n=ks[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),getCurrentLayout:this.getCurrentLayout.bind(this),export:this.exportLayouts.bind(this),import:this.importLayouts.bind(this),save:this.save.bind(this),restore:this.restore.bind(this),remove:this.remove.bind(this),onAdded:this.onAdded.bind(this),onChanged:this.onChanged.bind(this),onRemoved:this.onRemoved.bind(this),onDefaultGlobalChanged:this.onDefaultGlobalChanged.bind(this),onSaveRequested:this.subscribeOnSaveRequested.bind(this),getMultiScreenPermissionState:this.getGlobalPermissionState.bind(this),requestMultiScreenPermission:this.requestGlobalPermission.bind(this),getGlobalTypeState:this.checkGlobalActivated.bind(this),getDefaultGlobal:this.getDefaultGlobal.bind(this),setDefaultGlobal:this.setDefaultGlobal.bind(this),clearDefaultGlobal:this.clearDefaultGlobal.bind(this),rename:this.rename.bind(this),onRenamed:this.onRenamed.bind(this),onRestored:this.onRestored.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){ks.layoutAdded.execute=this.handleOnAdded.bind(this),ks.layoutChanged.execute=this.handleOnChanged.bind(this),ks.layoutRemoved.execute=this.handleOnRemoved.bind(this),ks.layoutRenamed.execute=this.handleOnRenamed.bind(this),ks.layoutRestored.execute=this.handleOnRestored.bind(this),ks.defaultLayoutChanged.execute=this.handleOnDefaultChanged.bind(this),ks.clientSaveRequest.execute=this.handleSaveRequest.bind(this),ks.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(ks)}async get(e,t){X(tt,e),X(Ut,t);return(await this.bridge.send("layouts",ks.get,{name:e,type:t})).layout}async getCurrentLayout(){return(await this.bridge.send("layouts",ks.getCurrent,void 0)).layout}async getAll(e){X(Ut,e);return(await this.bridge.send("layouts",ks.getAll,{type:e})).summaries}async exportLayouts(e){X(Ut,e);return(await this.bridge.send("layouts",ks.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(X(fn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return re.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const n=e.reduce((e,t)=>{const n=en.run(t);return n.ok?e.valid.push(t):this.logger.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(n.error)}`),e},{valid:[]}),i=e.filter(e=>n.valid.some(t=>t.name===e.name));await this.bridge.send("layouts",ks.import,{layouts:i,mode:t})}async save(e){X(nn,e);return(await this.bridge.send("layouts",ks.save,{layout:e})).layout}async restore(e){X(rn,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",ks.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){X(Ut,e),X(tt,t),await this.bridge.send("layouts",ks.remove,{type:e,name:t})}async handleSaveRequest(e){const t={};if(this.saveRequestSubscription)try{const n=this.saveRequestSubscription(e);t.windowContext=n?.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}async getGlobalPermissionState(){return await this.bridge.send("layouts",ks.getGlobalPermissionState,void 0)}async requestGlobalPermission(){const e=(await this.getGlobalPermissionState()).state;if("denied"===e)return{permissionGranted:!1};if("granted"===e)return{permissionGranted:!0};const t=this.windowsController.my(),n=(window.glue42core||window.iobrowser).isPlatformFrame;if("Platform"!==t.name&&!n)return re.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",ks.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",ks.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",ks.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){X(tt,e),await this.bridge.send("layouts",ks.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",ks.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){X(en,e),X(tt,t);return await this.bridge.send("layouts",ks.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){X(en,e),await this.bridge.send("layouts",ks.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"):(this.exportLayouts("Global").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.exportLayouts("Workspace").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.registry.add(ks.layoutAdded.name,e))}onChanged(e){return this.registry.add(ks.layoutChanged.name,e)}onDefaultGlobalChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"):(this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.registry.add(ks.defaultLayoutChanged.name,e))}onRemoved(e){return this.registry.add(ks.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(ks.layoutRenamed.name,e)}onRestored(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"):this.registry.add(ks.layoutRestored.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?re.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."):(this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription})}async handleOnAdded(e){this.registry.execute(ks.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(ks.layoutChanged.name,e)}async handleOnDefaultChanged(e){this.registry.execute(ks.defaultLayoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(ks.layoutRemoved.name,e)}async handleOnRestored(e){this.registry.execute(ks.layoutRestored.name,e)}async handleOnRenamed(e){const{prevName:t,...n}=e;this.registry.execute(ks.layoutRenamed.name,n,{name:t})}}const Os={raiseNotification:{name:"raiseNotification",dataDecoder:Ci,resultDecoder:Ii},requestPermission:{name:"requestPermission",resultDecoder:Si},notificationShow:{name:"notificationShow",dataDecoder:xi},notificationClick:{name:"notificationClick",dataDecoder:xi},getPermission:{name:"getPermission",resultDecoder:_i},list:{name:"list",resultDecoder:Bi},notificationRaised:{name:"notificationRaised",dataDecoder:qi},notificationClosed:{name:"notificationClosed",dataDecoder:Gi},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:Pi},getConfiguration:{name:"getConfiguration",resultDecoder:Oi},getActiveCount:{name:"getActiveCount",resultDecoder:ii},configurationChanged:{name:"configurationChanged",resultDecoder:Oi},setState:{name:"setState",dataDecoder:oi},activeCountChange:{name:"activeCountChange",resultDecoder:ii},stateChange:{name:"stateChange",resultDecoder:oi},operationCheck:{name:"operationCheck"}};let Rs=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};class As{supportedOperationsNames=[];registry=hs();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;notificationsConfiguration;notificationsActiveCount=0;handlePlatformShutdown(){this.notifications={},this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=t.bridge,this.coreGlue=e,this.notificationsSettings=t.config.notifications,this.buildNotificationFunc=t.buildNotification,this.notificationsConfiguration=await this.getConfiguration(),this.notificationsActiveCount=await this.getActiveCount();const n=this.toApi();this.addOperationExecutors(),e.notifications=n,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=X(ct,e.operation),n=Os[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={raise:this.raise.bind(this),requestPermission:this.requestPermission.bind(this),getPermission:this.getPermission.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onClosed:this.onClosed.bind(this),click:this.click.bind(this),clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),getFilter:this.getFilter.bind(this),setFilter:this.setFilter.bind(this),setState:this.setState.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onActiveCountChanged:this.onActiveCountChanged.bind(this),onCounterChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",Os.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",Os.requestPermission,void 0)).permissionGranted}async raise(e){const t=X(si,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return re.raiseError("Cannot raise the notification, because the user has declined the permission request");const n=Rs(10),i=await this.bridge.send("notifications",Os.raiseNotification,{settings:t,id:n}),r=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=r,r}async list(){return(await this.bridge.send("notifications",Os.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?re.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?re.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){X(tt,e),t&&X(tt,t),await this.bridge.send("notifications",Os.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){X(tt,e),await this.bridge.send("notifications",Os.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",Os.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",Os.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=X(ki,e);await this.bridge.send("notifications",Os.configure,{configuration:t},void 0,{includeOperationCheck:!0})}async getConfiguration(){return(await this.bridge.send("notifications",Os.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getActiveCount(){try{return(await this.bridge.send("notifications",Os.getActiveCount,void 0,void 0,{includeOperationCheck:!0})).count}catch(e){return console.warn("Failed to get accurate active notifications count",e),0}}async getFilter(){return(await this.bridge.send("notifications",Os.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=X(Ti,e);return await this.bridge.send("notifications",Os.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){X(tt,e),X(ni,t),await this.bridge.send("notifications",Os.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):(setTimeout(()=>e(this.notificationsConfiguration),0),this.registry.add("notifications-config-changed",e))}onActiveCountChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):(setTimeout(()=>e({count:this.notificationsActiveCount}),0),this.registry.add("notifications-active-count-changed",e))}onStateChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){Os.notificationShow.execute=this.handleNotificationShow.bind(this),Os.notificationClick.execute=this.handleNotificationClick.bind(this),Os.notificationRaised.execute=this.handleNotificationRaised.bind(this),Os.notificationClosed.execute=this.handleNotificationClosed.bind(this),Os.configurationChanged.execute=this.handleConfigurationChanged.bind(this),Os.activeCountChange.execute=this.handleActiveCountChanged.bind(this),Os.stateChange.execute=this.handleNotificationStateChanged.bind(this),Os.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Os)}async handleConfigurationChanged(e){this.notificationsConfiguration=e.configuration,this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.notificationsActiveCount=e.count,this.registry.execute("notifications-active-count-changed",e)}async handleNotificationStateChanged(e){this.registry.execute("notification-state-changed",{id:e.id},e.state)}async handleNotificationShow(e){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}async handleNotificationClick(e){if(!e.action&&this.notificationsSettings?.defaultClick&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&this.notificationsSettings?.actionClicks?.some(t=>t.action===e.action)){const t=this.notificationsSettings?.actionClicks?.find(t=>t.action===e.action);t.handler(this.coreGlue,e.definition)}if(!e.id)return;const t=this.notifications[e.id];t&&t.onclick&&(t.onclick(),delete this.notifications[e.id])}async handleNotificationRaised(e){this.registry.execute("notification-raised",e.notification)}async handleNotificationClosed(e){this.registry.execute("notification-closed",e)}}const Ms={getIntents:{name:"getIntents",resultDecoder:kn},findIntent:{name:"findIntent",dataDecoder:Rn,resultDecoder:kn},raise:{name:"raise",dataDecoder:Hn,resultDecoder:Un},filterHandlers:{name:"filterHandlers",dataDecoder:Bn,resultDecoder:qn},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:In,resultDecoder:Vn}},Es="Tick42.FDC3.Intents.";class Ds{bridge;logger;interop;appManagerController;windowsController;myIntents=new Set;prefsController;uiController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout=6e4;unregisterIntentPromises=[];async start(e,t){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=t.bridge,this.interop=e.interop,this.appManagerController=t.appManagerController,this.windowsController=t.windowsController,this.prefsController=t.prefsController,this.uiController=t.uiController,this.checkIfIntentsResolverIsEnabled(t.config);const n=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=n}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}async handleBridgeMessage(e){const t=X(Cn,e.operation),n=Ms[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){return{raise:this.raise.bind(this),all:this.all.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),find:this.find.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntentsByHandler.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}async raise(e){const t=X(Nn,e),n="string"==typeof t?{intent:t}:t;await Promise.all(this.unregisterIntentPromises),n.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${n.intent}`),await this.removeRememberedHandler(n.intent));const i=await this.checkHandleRaiseWithRememberedHandler(n);if(i)return i;const r={intentRequest:n,resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:n}),embeddedResolverConfig:this.getEmbeddedResolverConfig()},s=n.waitUserResponseIndefinitely?Z:(n.timeout||this.intentResolverResponseTimeout)+3e4;this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${s}ms`);const o=await this.bridge.send("intents",Ms.raise,r,{methodResponseTimeoutMs:s,waitTimeoutMs:s});return this.logger.trace(`Raise operation completed with response: ${JSON.stringify(o)}`),o}getLegacyResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||9e4};const t=e.intentRequest?.waitUserResponseIndefinitely?Z:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}getEmbeddedResolverConfig(){return{enabled:this.uiController.isIntentResolverEnabled(),initialCaller:{instanceId:this.interop.instance.instance}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",Ms.getIntents,void 0)).intents}addIntentListener(e,t){if(X(Jn,e),"function"!=typeof t)return re.raiseError("Cannot add intent listener, because the provided handler is not a function!");let n;const i="string"==typeof e?e:e.intent,r=this.buildInteropMethodName(i);if(this.myIntents.has(i))return re.raiseError(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const s={unsubscribe:()=>{this.myIntents.delete(i),n.then(()=>this.interop.unregister(r)).catch(e=>this.logger.trace(`Unregistration of a method with name ${r} failed with reason: ${e}`))}};let o={};if("object"==typeof e){const{intent:t,...n}=e;o=n}return n=this.interop.register({name:r,flags:{intent:o}},e=>{if(this.myIntents.has(i)){const{_initialCallerId:n,...i}=e;return t(i)}}),n.catch(e=>{this.myIntents.delete(i),this.logger.warn(`Registration of a method with name ${r} failed with reason: ${e}`)}),s}async register(e,t){if(X(Jn,e),"function"!=typeof t)return re.raiseError("Cannot add intent listener, because the provided handler is not a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);if(this.myIntents.has(n))return re.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);let r={};if("object"==typeof e){const{intent:t,...n}=e;r=n}try{await this.interop.register({name:i,flags:{intent:r}},e=>{if(this.myIntents.has(n)){const{_initialCallerId:n,...i}=e,r=this.interop.servers().find(e=>e.instance===n);return t(i,r)}})}catch(e){return this.myIntents.delete(n),re.raiseError(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async find(e){let t;if(void 0!==e){const n=X(On,e);"string"==typeof n?t={filter:{name:n}}:"object"==typeof n&&(t={filter:n})}await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",Ms.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return re.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppAdded",e),n=this.subscribeForServerMethodEvent("serverMethodAdded",e);return()=>{t(),n()}}onHandlerRemoved(e){if("function"!=typeof e)return re.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppRemoved",e),n=this.subscribeForServerMethodEvent("serverMethodRemoved",e);return()=>{t(),n()}}subscribeForAppEvent(e,t){return this.appManagerController[e](e=>{const n=e.userProperties.intents;n?.length&&n.forEach(n=>{const i=this.buildIntentHandlerFromApp(e,n);t(i,n.name)})})}subscribeForServerMethodEvent(e,t){return this.interop[e](async({server:n,method:i})=>{if(!i.name.startsWith(Es))return;const r=i.name.replace(Es,""),s=await this.buildIntentHandlerFromServerMethod(e,n,i,r);t(s,r)})}buildIntentHandlerFromApp(e,t){return{applicationName:e.name,type:"app",applicationDescription:e.caption,applicationIcon:e.icon,applicationTitle:e.title,contextTypes:t.contexts,displayName:t.displayName,resultType:t.resultType,customConfig:t.customConfig}}async buildIntentHandlerFromServerMethod(e,t,n,i){const r=n.flags.intent,s=this.appManagerController.getApplication(t.application||t.applicationName);let o;"serverMethodAdded"===e&&t.windowId&&(o=await(this.windowsController.findById(t.windowId)?.getTitle()));const a=s?.userProperties?.intents?.find(e=>e.name===i);return{applicationName:t.application||t.applicationName||"",instanceId:t.windowId||t.instance,type:"instance",applicationIcon:r?.icon||s?.icon,applicationTitle:s?.title,applicationDescription:r?.description||s?.caption,contextTypes:r?.contextTypes||a?.contexts,instanceTitle:o,displayName:r?.displayName||a?.displayName,resultType:r?.resultType||a?.resultType,customConfig:r?.customConfig}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}checkIfIntentsResolverIsEnabled(e){this.useIntentsResolverUI="boolean"!=typeof e.intents?.enableIntentsResolverUI||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=e.intents?.intentsResolverAppName??"intentsResolver",this.intentResolverResponseTimeout=e.intents?.methodResponseTimeoutMs??6e4}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter(t=>t!==e)}buildInteropMethodName(e){return`${Es}${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)})}async filterHandlers(e){X($n,e),this.checkIfAtLeastOneFilterIsPresent(e);const t=this.getEmbeddedResolverConfig();if(e.openResolver&&!this.useIntentsResolverUI&&!t.enabled)return re.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const n=(e.timeout||9e4)+3e4,i={filterHandlersRequest:e,resolverConfig:this.getLegacyResolverConfigByRequest({handlerFilter:e}),embeddedResolverConfig:t};return await this.bridge.send("intents",Ms.filterHandlers,i,{methodResponseTimeoutMs:n,waitTimeoutMs:n},{includeOperationCheck:!0})}checkIfAtLeastOneFilterIsPresent(e){const t="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)return re.raiseError(t);const{intent:n,resultType:i,contextTypes:r,applicationNames:s}=e,o=r?.length,a=s?.length;return n||i||o||a?void 0:re.raiseError(t)}async getIntentsByHandler(e){X(In,e);return await this.bridge.send("intents",Ms.getIntentsByHandler,e,void 0,{includeOperationCheck:!0})}async removeRememberedHandler(e){let t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const n=t.data?.intents;if(!n)return void this.logger.trace("No app prefs found for current app");delete n[e];const i={...t.data,intents:n};try{await this.prefsController.update(i)}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${e}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){let t;try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const n=t.data?.intents?.[e.intent];return n?.handler}async checkHandleRaiseWithRememberedHandler(e){if(e.target)return;const t=await this.checkForRememberedHandler(e);if(!t)return;const n={intentRequest:{...e,target:{app:t.applicationName,instance:t.instanceId}},resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:e}),embeddedResolverConfig:this.getEmbeddedResolverConfig()};try{return await this.bridge.send("intents",Ms.raise,n)}catch(t){this.logger.trace(`Could not raise intent to remembered handler. Reason: ${t}. Removing it from Prefs store`),await this.removeRememberedHandler(e.intent)}}}const js={appHello:{name:"appHello",dataDecoder:Qi,resultDecoder:Yi},addChannel:{name:"addChannel",dataDecoder:li},removeChannel:{name:"removeChannel",dataDecoder:pi},getMyChannel:{name:"getMyChannel",resultDecoder:Xi},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:Ji,resultDecoder:zi},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:tr,resultDecoder:nr},joinChannel:{name:"joinChannel",dataDecoder:sr},restrict:{name:"restrict",dataDecoder:mi},getRestrictions:{name:"getRestrictions",dataDecoder:yi,resultDecoder:bi},restrictAll:{name:"restrictAll",dataDecoder:vi},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:ar},leaveChannel:{name:"leaveChannel",dataDecoder:or},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:Rt},getMode:{name:"getMode",resultDecoder:Zi},operationCheck:{name:"operationCheck"}},Ns="___channel___",Fs="subs",Ls="changed",$s="channels_changed",Ws="io_connect_channels",Hs="inMemory";class Us{supportedOperationsNames=[];registry=hs();logger;contexts;interop;bridge;windowsController;_mode;myWindowId;storage;handlePlatformShutdown(){this.registry.clear(),this.storage.clear()}addOperationsExecutors(){js.getMyChannel.execute=this.handleGetMyChannel.bind(this),js.joinChannel.execute=this.handleJoinChannel.bind(this),js.leaveChannel.execute=this.handleLeaveChannel.bind(this),js.restrict.execute=this.handleRestrict.bind(this),js.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),js.restrictAll.execute=this.handleRestrictAll.bind(this),js.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(js)}async start(e,t){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.interop=e.interop,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.storage=t.channelsStorage,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this.myWindowId=this.windowsController.my().id??this.interop.instance.instance,await this.initialize();const n=this.toApi();e.channels=n}async postStart(e,t){try{await this.requestChannelSelector(e.appManager.myInstance)}catch(e){this.logger.warn(`Failed to display channel selector: ${Y(e)}`)}}async handleBridgeMessage(e){const t=X(Vi,e.operation),n=js[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async list(){const e=this.getAllChannelNames();return await Promise.all(e.map(e=>this.get(e)))}my(){return this.current()}async handleGetMyChannel(){const e=this.my();return e?{channel:e}:{}}async join(e,t){const n=this.getAllChannelNames();X(Kn(n),e),X(it,t);const i={channel:e,windowId:t??this.myWindowId};await this.bridge.send("channels",js.joinChannel,i,void 0,{includeOperationCheck:!0})}handleJoinChannel({channel:e}){return"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}onChanged(e){return this.changed(e)}async leave(e={}){if(X(Yn,e),e.channel){const t=this.getAllChannelNames();X(Kn(t),e.channel)}const t={channelName:e.channel,windowId:e.windowId??this.myWindowId};await this.bridge.send("channels",js.leaveChannel,t,void 0,{includeOperationCheck:!0})}async handleAppManagerInitialChannelId(e){if("inMemory"!==this.storage.mode&&!this.storage.getSessionStorageData())return this.handleJoinChannel({channel:e,windowId:this.myWindowId})}async handleLeaveChannel({channelName:e}){const t=e?[e]:this.storage.channels;t.forEach(e=>this.storage.invokeUnsubscribes(e)),this.storage.channels=this.storage.channels.filter(e=>!t.includes(e)),this.executeChangedEvents(),await this.notifyChannelsChanged()}toApi(){const e={mode:this._mode,subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),publish:this.publish.bind(this),all:this.all.bind(this),list:this.list.bind(this),get:this.get.bind(this),getMyChannels:this.getMyChannels.bind(this),myChannels:this.myChannels.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),join:this.join.bind(this),leave:this.leave.bind(this),current:this.current.bind(this),my:this.my.bind(this),changed:this.changed.bind(this),onChanged:this.onChanged.bind(this),add:this.add.bind(this),remove:this.remove.bind(this),getMy:this.getMy.bind(this),getWindowsOnChannel:this.getWindowsOnChannel.bind(this),getWindowsWithChannels:this.getWindowsWithChannels.bind(this),restrict:this.restrict.bind(this),getRestrictions:this.getRestrictions.bind(this),restrictAll:this.restrictAll.bind(this),clearChannelData:this.clearChannelData.bind(this),setPath:this.setPath.bind(this),setPaths:this.setPaths.bind(this)};return Object.freeze(e)}createContextName(e){return`${Ns}${e}`}getAllChannelNames(){return this.contexts.all().filter(e=>e.startsWith(Ns)).map(e=>e.replace(Ns,""))}async joinAdditionalChannel(e){if(this.storage.channels.includes(e))return;this.storage.channels=[...this.storage.channels,e];const t=this.createContextName(e),n=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute(Fs,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,n),this.executeChangedEvents(e),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.storage.channels[0];if(e===t)return;this.storage.invokeUnsubscribes(t),this.storage.channels=[e];const n=this.createContextName(e),i=await this.contexts.subscribe(n,(e,t,n,i,r)=>{this.registry.execute(Fs,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,i),this.executeChangedEvents(e),await this.notifyChannelsChanged()}executeChangedEvents(e){this.registry.execute(Ls,e),this.registry.execute($s,this.storage.channels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",js.notifyChannelsChanged,{channelNames:this.storage.channels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${Y(e)}`)}}async 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]}));i&&e.push({path:V,value:i}),await this.contexts.setPaths(n,e)}else i&&(t[V]=i),await this.contexts.update(n,{data:t})}getFDC3Type(e){const t=Object.keys(e).filter(e=>0===e.indexOf("fdc3_"));if(0!==t.length)return t.length>1?re.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return re.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&X(Zn,t);const n=this.current(),i=t?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(e,t.contextType):this.getWrappedSubscribeCallback(e);return n&&this.replaySubscribe(i,n),this.registry.add(Fs,i)}async subscribeFor(e,t,n){const i=this.getAllChannelNames();if(X(Kn(i),e),"function"!=typeof t)return re.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);n&&X(Zn,n);const r=this.createContextName(e),s=n?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,n.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(r,(e,t,n,i,r)=>{s(e.data,e,t,r?.updaterId)})}async publish(e,t){if("object"!=typeof e)return re.raiseError("Cannot publish to channel, because the provided data is not an object!");if(X(Qn,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();X(Kn(e),t)}if(!t&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e);const n="string"==typeof t?t:this.storage.channels[0];if(!n)return re.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?this.updateData(n,e):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const n=this.getAllChannelNames();X(Kn(n),e),t&&X(Zn,t);const i=this.createContextName(e),r=await this.contexts.get(i);return t?.contextType?this.getContextForFdc3Type(r,t.contextType):r.latest_fdc3_type?this.getContextWithFdc3Data(r):r}async getMyChannels(){return Promise.all(this.storage.channels.map(e=>{const t=this.createContextName(e);return this.contexts.get(t)}))}myChannels(){return this.storage.channels}getContextForFdc3Type(e,t){const n=`fdc3_${t.split(".").join("&")}`;if(!e.data[n])return{name:e.name,meta:e.meta,data:{}};const i={type:t,...e.data[n]};return{name:e.name,meta:e.meta,data:{fdc3:i}}}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}}}current(){return this.storage.channels[0]}changed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(Ls,e)}async add(e){const t=X(li,e);return this.getAllChannelNames().includes(t.name)?re.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",js.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){X(tt,e);if(!this.getAllChannelNames().includes(e))return re.raiseError("There's no channel with such name");await this.bridge.send("channels",js.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then(t=>{if(!t)return;const n=this.createContextName(t.name);return this.contexts.subscribe(n,(t,n,i,r,s)=>{e(t.data,t,n,s?.updaterId)})}).then(e=>e?.()).catch(e=>this.logger.trace(e))};async getMy(e){if(this.storage.channels.length)return e&&X(Zn,e),this.get(this.storage.channels[this.storage.channels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();X(Kn(t),e);const{windowIds:n}=await this.bridge.send("channels",js.getWindowIdsOnChannel,{channel:e},void 0,{includeOperationCheck:!0});return n.reduce((e,t)=>{const n=this.windowsController.findById(t);return n?[...e,n]:e},[])}async getWindowsWithChannels(e){const t=void 0!==e?{filter:X(er,e)}:{},{windowIdsWithChannels:n}=await this.bridge.send("channels",js.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0});return n.reduce((e,{application:t,channel:n,windowId:i})=>{const r=this.windowsController.findById(i);return r?[...e,{application:t,channel:n,window:r}]:e},[])}async clearChannelData(e){await this.handleSetPaths("clearChannelData",[{path:"data",value:{}},{path:"latest_fdc3_type",value:null}],e)}async restrict(e){X(gi,e);const t=this.getAllChannelNames();X(Kn(t),e.name);const n={config:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",js.restrict,n,void 0,{includeOperationCheck:!0})}async handleRestrict({config:e}){const t=await this.getMy();if(!t)return this.updateRestriction(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateRestriction(e);e.name===t.name&&!n&&e.read&&this.replaySubscribeCallback(e.name)}updateRestriction(e){const t=this.storage.restrictions.some(t=>t.name===e.name);this.storage.restrictions=t?this.storage.restrictions.map(t=>t.name===e.name?e:t):this.storage.restrictions.concat(e)}updateAllRestrictions(e){const t=this.getAllChannelNames();this.storage.restrictions=t.map(t=>({name:t,...e}))}async getRestrictions(e){X(it,e);const t=e&&e!==this.interop.instance.instance;return e&&t?this.bridge.send("channels",js.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):{channels:this.storage.restrictions}}async restrictAll(e){X(wi,e);const t={restrictions:{...e,windowId:e.windowId??this.myWindowId}};return this.bridge.send("channels",js.restrictAll,t,void 0,{includeOperationCheck:!0})}async handleRestrictAll({restrictions:e}){const t=await this.getMy();if(!t)return this.updateAllRestrictions(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateAllRestrictions(e),!n&&e.read&&this.replaySubscribeCallback(t.name)}async setPath(e,t){const n=X(hi,e),i=[{path:`data.${n.path}`,value:n.value}];await this.handleSetPaths("setPath",i,t)}async setPaths(e,t){const n=X(ui,e).map(({path:e,value:t})=>({path:`data.${e}`,value:t}));await this.handleSetPaths("setPaths",n,t)}async handleSetPaths(e,t,n){const i=n?[n]:this.storage.channels;if(!i.length)return re.raiseError(`Cannot complete ${e} operation, because channel is not specified. Either join one or pass a channel name as second argument!`);this.validateChannelNames(i);const{allowed:r,forbidden:s}=this.groupChannelsByPermission("write",i);if(i.length===s.length)return re.raiseError(`Cannot complete ${e} operation due to write restrictions to the following channels: ${i.join(", ")}`);s.length&&this.logger.warn(`Cannot set paths on channel${s.length>1?"s":""}: ${s.join(", ")} due to write restrictions`),await Promise.all(r.map(e=>{const n=this.createContextName(e);return this.contexts.setPaths(n,t)}))}validateChannelNames(e){const t=this.getAllChannelNames();e.forEach(e=>X(Kn(t),e))}groupChannelsByPermission(e,t){return t.reduce((t,n)=>(this.isAllowedByRestrictions(n,e)?t.allowed.push(n):t.forbidden.push(n),t),{allowed:[],forbidden:[]})}isAllowedByRestrictions(e,t){const n=this.storage.restrictions.find(t=>t.name===e);return!n||n[t]}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute(Fs,e.data,e,t,r?.updaterId)}).then(e=>{e&&"function"==typeof e&&e()}).catch(e=>this.logger.error(e))}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();X(Kn(e),t.name)}if(!t.name&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const n=t.name||this.storage.channels[0];if(!n)return re.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?t.fdc3?this.publishFdc3Data(n,e):this.updateData(n,e):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async publishOnMultipleChannels(e,t){const{allowed:n,forbidden:i}=this.groupChannelsByPermission("write",this.storage.channels);if(this.storage.channels.length===i.length)return re.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`);i.length&&this.logger.warn(`Data on channel${i.length>1?"s":""}: ${i.join(", ")} won't be published due to write restrictions`);const r=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(n.map(t=>r(t,e)))}async publishFdc3Data(e,t){X(Xn,t);const{type:n,...i}=t,r=n.split(".").join("&"),s={[`fdc3_${r}`]:i};return this.updateData(e,s)}getWrappedSubscribeCallback(e){return(t,n,i,r)=>{if(!this.isAllowedByRestrictions(n.name,"read"))return;const{data:s,latest_fdc3_type:o}=n,a=`fdc3_${o}`;if(!o||i.data&&!i.data[a])return void e(t,n,r);const c={type:o.split("&").join("."),...s[a]},{[a]:d,...l}=t;e({...l,fdc3:c},n,r)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const n={replayed:!1};return(i,r,s,o)=>{if(!this.isAllowedByRestrictions(r.name,"read"))return;const{data:a,latest_fdc3_type:c}=r,d=`fdc3_${t.split(".").join("&")}`;if(!a[d]||s.data&&!s.data[d])return;if(n.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:c,searchedType:t,callback:e,context:r,updaterId:o});const l={type:t,...a[d]};e({fdc3:l},r,o),n.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:r,updaterId:s}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...r.data[`fdc3_${t}`]}},r,s)}async requestChannelSelector(e){if(!e)return;const t=e.application,n=t.userProperties?.details;if(!n)return;if(!n?.channelSelector?.enabled)return;const i={windowId:e.id,channelsNames:this.storage.channels};await this.bridge.send("channels",js.requestChannelSelector,i,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",js.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),"single"}}onChannelsChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add($s,e)}async initialize(){if(!await this.checkIfAppHelloSupported())return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions");const{success:e,error:t}=await this.sendAppHello();if(t)return this.handleAppHelloFailure(t);this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(e)}`);const{mode:n,channels:i,restrictions:r}=e;this.storage.mode="inMemory",this._mode=n,this.storage.channels=i,this.storage.restrictions=r}async handleAppHelloFailure(e){this.logger.trace(e),this.storage.mode="sessionStorage",this._mode=await this.getPlatformChannelsMode()}async sendAppHello(){try{return{success:await this.bridge.send("channels",js.appHello,{windowId:this.myWindowId},void 0,{includeOperationCheck:!0}),error:void 0}}catch(e){return{error:`Failed to get initial state from platform. Error: ${Y(e)}`,success:void 0}}}async checkIfAppHelloSupported(){try{const{isSupported:e}=await this.bridge.send("channels",js.operationCheck,{operation:js.appHello.name},void 0,{includeOperationCheck:!0});return e}catch(e){return this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${Y(e)}`),!1}}}const qs={getEnvironment:{name:"getEnvironment",resultDecoder:xt},getBase:{name:"getBase",resultDecoder:xt},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:br},systemHello:{name:"systemHello",resultDecoder:yr},operationCheck:{name:"operationCheck"}};class Bs{supportedOperationsNames=[];bridge;ioc;logger;errorPort=K.port2;async start(e,t){this.logger=e.logger.subLogger("system.controller.web"),this.logger.trace("starting the web system controller"),this.bridge=t.bridge,this.ioc=t,this.addOperationsExecutors();let n=!1;try{const e=await this.bridge.send("system",qs.systemHello,void 0,void 0,{includeOperationCheck:!0});n=e.isClientErrorOperationSupported}catch(e){this.logger.warn("The platform of this client is outdated and does not support some system operations.")}this.errorPort.onmessage=async e=>{n&&await this.bridge.send("system",qs.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=X(dt,e.operation),n=qs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async processPlatformShutdown(){Object.values(this.ioc.controllers).forEach(e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),await this.bridge.stop()}async setEnvironment(){const e=await this.bridge.send("system",qs.getEnvironment,void 0),t=await this.bridge.send("system",qs.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",r=Object.assign({},n,t,{environment:e});window[i]=r}addOperationsExecutors(){qs.platformShutdown.execute=this.processPlatformShutdown.bind(this),qs.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this),qs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(qs)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}}class Gs{onclick=()=>{};onshow=()=>{};id;title;badge;body;data;dir;icon;image;lang;renotify;requireInteraction;silent;tag;timestamp;vibrate;clickInterop;actions;focusPlatformOnDefaultClick;severity;showToast;showInPanel;state;constructor(e,t){this.id=t,this.badge=e.badge,this.body=e.body,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.vibrate=e.vibrate,this.title=e.title,this.clickInterop=e.clickInterop,this.actions=e.actions,this.focusPlatformOnDefaultClick=e.focusPlatformOnDefaultClick,this.severity=e.severity,this.showToast=e.showToast,this.showInPanel=e.showInPanel,this.state=e.state}}R(T("clientHello"));const Js={clientHello:{name:"clientHello",resultDecoder:k({widget:k({inject:_()})})}};class zs{windowId;logger;bridge;eventsDispatcher;channelsController;config;channels=[];unsubFuncs=[];contentCommands={widgetVisualizationPermission:{name:"widgetVisualizationPermission",handle:this.handleWidgetVisualizationPermission.bind(this)},changeChannel:{name:"changeChannel",handle:this.handleChangeChannel.bind(this)}};handlePlatformShutdown(){this.unsubFuncs.forEach(e=>e()),this.channels=[],this.unsubFuncs=[]}async start(e,t){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=t.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=t.bridge,this.channelsController=t.channelsController,this.eventsDispatcher=t.eventsDispatcher;try{await this.registerWithPlatform()}catch(e){return}this.channels=await this.channelsController.list();const n=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),i=this.channelsController.onChanged(e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})});this.unsubFuncs.push(n),this.unsubFuncs.push(i)}async handleBridgeMessage(e){}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}async registerWithPlatform(){this.logger.trace("registering with the platform"),this.config=await this.bridge.send("extension",Js.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}async handleWidgetVisualizationPermission(){if(!this.config?.widget.inject)return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const e=this.channels.find(e=>e.name===this.channelsController.my());this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:e})}async handleChangeChannel(e){"no-channel"!==e.name?await this.channelsController.join(e.name):await this.channelsController.leave()}}class Vs{config;glue;registry=hs();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;_resolveModalsUIFactoryReadyPromise;_resolveIntentResolverUIFactoryReadyPromise;constructor(e){this.config=e}events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},contentInc:{name:"contentInc",handle:this.handleContentInc.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)},widgetFactoryReady:{name:"widgetFactoryReady",handle:this.handleWidgetReady.bind(this)},modalsUIFactoryReady:{name:"modalsUIFactoryReady",handle:this.handleModalsUIFactoryReady.bind(this)},intentResolverUIFactoryReady:{name:"intentResolverUIFactoryReady",handle:this.handleIntentResolverUIFactoryReady.bind(this)}};stop(){window.removeEventListener(this.glue42EventName,this._handleMessage)}start(e){this.glue=e,this.wireCustomEventListener(),this.announceStarted()}sendContentMessage(e){this.send("contentOut","glue42core",e)}onContentMessage(e){return this.registry.add("content-inc",e)}async widgetReady(){const e=new Promise(e=>{this._resolveWidgetReadyPromise=e});return this.requestWidgetReady(),e}async modalsUIFactoryReady(){const e=new Promise(e=>{this._resolveModalsUIFactoryReadyPromise=e});return this.requestModalsUIFactoryReady(),e}async intentResolverUIFactoryReady(){const e=new Promise(e=>{this._resolveIntentResolverUIFactoryReadyPromise=e});return this.requestIntentResolverUIFactoryReady(),e}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){const t=e.detail,n=t?.glue42??t?.glue42core;if(!n)return;const i=n.event,r=this.events[i];r&&r.handle(n.message)}announceStarted(){this.send("start","glue42")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse","glue42",{glue:this.glue}):this.send("requestGlueResponse","glue42",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}handleContentInc(e){this.registry.execute("content-inc",e)}requestWidgetReady(){this.send("requestWidgetFactoryReady","glue42")}handleWidgetReady(){this._resolveWidgetReadyPromise?.()}requestModalsUIFactoryReady(){this.send("requestModalsUIFactoryReady","glue42")}handleModalsUIFactoryReady(){this._resolveModalsUIFactoryReadyPromise?.()}requestIntentResolverUIFactoryReady(){this.send("requestIntentResolverUIFactoryReady","glue42")}handleIntentResolverUIFactoryReady(){this._resolveIntentResolverUIFactoryReadyPromise?.()}send(e,t,n){const i={};i[t]={event:e,message:n};const r=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(r)}}class Ks{coreGlue;transactionTimeout=15e3;transactionLocks={};webPlatformTransport;webPlatformMessagesUnsubscribe;reconnectCounter=0;logger;constructor(e){this.coreGlue=e,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}async start(e){if(e.isPlatformInternal)return void this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic.");if(!(this.coreGlue.connection.transport.name()===z))return re.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport.");if(!this.coreGlue.connection.transport.isPreferredActivated)return void this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization.");this.webPlatformTransport=this.coreGlue.connection.transport,this.webPlatformMessagesUnsubscribe=this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this));const t=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(t)}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===z,n=e.type,i=e.args,r=e.transactionId;return n===$.name?this.handleTransportSwitchRequest(i,r):n!==L.name||t?n===U.name?this.handleGetCurrentTransportResponse(i,r):n===q.name?this.handleCheckPreferredLogic(r):n===B.name?this.handleCheckPreferredConnection(i,r):void 0:this.handlePlatformUnload()}async reEstablishPlatformPort(){try{await this.webPlatformTransport.connect()}catch(e){if(this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(e)}`),--this.reconnectCounter,this.reconnectCounter>0)return this.reEstablishPlatformPort();this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform.")}this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."),this.reconnectCounter=0,this.webPlatformTransport.close();const e=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(e)}async checkSwitchTransport(e){const t=this.coreGlue.connection.transport.name();if(t===e.transportName)return void this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary");this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${t}, but it should reconnect to ${JSON.stringify(e)}`);const n=await this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(n)}`)}async getCurrentPlatformTransportState(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(H.name);this.sendPlatformMessage(H.name,e.id);const t=await e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}setTransaction(e){const t={},n=Rs(10),i=new Promise((i,r)=>{let s=!0;t.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{s=!1,delete this.transactionLocks[n],r(e)},setTimeout(()=>{s&&(s=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],r(`Transaction for operation: ${e} timed out.`))},this.transactionTimeout)});return t.lock=i,t.id=n,this.transactionLocks[n]=t,t}sendPlatformMessage(e,t,n){this.logger.trace(`Sending a platform message of type: ${e}, id: ${t} and args: ${JSON.stringify(n)}`),this.webPlatformTransport.sendObject({glue42core:{type:e,args:n,transactionId:t}})}handleTransportSwitchRequest(e,t){this.logger.trace(`Received a transport switch request with id: ${t} and data: ${JSON.stringify(e)}`),this.coreGlue.connection.switchTransport(e.switchSettings).then(e=>{this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(e)}`),this.setConnected(),this.sendPlatformMessage(W.name,t,{success:e.success})}).catch(e=>{this.logger.error(e),this.sendPlatformMessage(W.name,t,{success:!1})})}handlePlatformUnload(){this.reconnectCounter=5,this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."),this.reEstablishPlatformPort()}handleGetCurrentTransportResponse(e,t){this.logger.trace(`Got a current transport response from the platform with id: ${t} and data: ${JSON.stringify(e)}`);const n=e.transportState,i=this.transactionLocks[t];i?.lift(n)}handleCheckPreferredLogic(e){setTimeout(()=>this.sendPlatformMessage(G.name,e),0)}handleCheckPreferredConnection(e,t){const n=e.url;this.logger.trace(`Testing the possible connection to: ${n}`),this.checkPreferredConnection(n).then(e=>{this.logger.trace(`The connection to ${n} is possible`),this.sendPlatformMessage(J.name,t,e)}).catch(e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(J.name,t,{error:e})})}checkPreferredConnection(e){return new Promise(t=>{const n=new WebSocket(e);n.onerror=()=>t({live:!1}),n.onopen=()=>{n.close(),t({live:!0})}})}setConnected(){this.webPlatformTransport.manualSetReadyState()}}const Zs={getCurrent:{name:"getCurrent",resultDecoder:$i},list:{name:"list",resultDecoder:Wi},select:{name:"select",dataDecoder:Hi}};class Qs{logger;bridge;registry=hs();themesSubscription;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge,await this.setupSubscription(),this.logger.trace("themes subscription is ready");const n=this.toApi();e.themes=n,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),this.themesSubscription?.close(),delete this.themesSubscription}async handleBridgeMessage(){}toApi(){const e={getCurrent:this.getCurrent.bind(this),list:this.list.bind(this),select:this.select.bind(this),onChanged:this.onChanged.bind(this)};return Object.freeze(e)}async getCurrent(){return(await this.bridge.send("themes",Zs.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",Zs.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){X(tt,e),await this.bridge.send("themes",Zs.select,{name:e},void 0,{includeOperationCheck:!0})}onChanged(e){return"function"!=typeof e?re.raiseError("onChanged requires a callback of type function"):this.registry.add("on-theme-change",e)}async setupSubscription(){this.themesSubscription=await this.bridge.createThemesSubscription(),this.themesSubscription.onData(this.handleStreamData.bind(this)),this.themesSubscription.onClosed(this.handleStreamClosure.bind(this))}handleStreamData(e){const t=e.data,n=$i.run(t);if(!n.ok)return void this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(n.error)}`);const i=n.result;this.registry.execute("on-theme-change",i.theme)}handleStreamClosure(){this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),delete this.themesSubscription}}class Ys{sessionStorage=window.sessionStorage;_mode=Hs;inMemoryChannels=[];inMemoryRestrictions=[];_unsubscribeDict={};clear(){this._mode=Hs,this.inMemoryChannels=[],this.inMemoryRestrictions=[],this._unsubscribeDict={},this.sessionStorage.setItem(Ws,JSON.stringify([]))}get mode(){return this._mode}set mode(e){this._mode=e}get channels(){return"inMemory"===this.mode?this.inMemoryChannels.slice():this.getSessionStorageData()?.channels??[]}set channels(e){"inMemory"===this.mode&&(this.inMemoryChannels=e),this.setSessionStorageChannels(e)}get restrictions(){return"inMemory"===this.mode?this.inMemoryRestrictions.slice():this.getSessionStorageData()?.restrictions??[]}set restrictions(e){"inMemory"===this.mode&&(this.inMemoryRestrictions=e),this.setSessionStorageRestrictions(e)}getSessionStorageData(){return JSON.parse(this.sessionStorage.getItem(Ws)||"null")}addUnsubscribe(e,t){this._unsubscribeDict[e]=t}invokeUnsubscribes(e){if(e)return this._unsubscribeDict[e]?.(),void delete this._unsubscribeDict[e];Object.values(this._unsubscribeDict).forEach(e=>e()),this._unsubscribeDict={}}setSessionStorageChannels(e){const t=this.getSessionStorageData();if(t?.channels)return t.channels=e,this.setSessionStorageData(t);const n={channels:e,restrictions:t?.restrictions??[]};return this.setSessionStorageData(n)}setSessionStorageRestrictions(e){const t=this.getSessionStorageData();if(t?.restrictions)return t.restrictions=e,this.setSessionStorageData(t);const n={channels:t?.channels??[],restrictions:e};return this.setSessionStorageData(n)}setSessionStorageData(e){this.sessionStorage.setItem(Ws,JSON.stringify(e))}}const Xs={clear:{name:"clear",dataDecoder:hr},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:hr,resultDecoder:ur},getAll:{name:"getAll",resultDecoder:pr},set:{name:"set",dataDecoder:fr},update:{name:"update",dataDecoder:fr},prefsChanged:{name:"prefsChanged",dataDecoder:ur},prefsHello:{name:"prefsHello",resultDecoder:mr},operationCheck:{name:"operationCheck"},registerSubscriber:{name:"registerSubscriber",dataDecoder:gr}};class eo{supportedOperationsNames=[];bridge;config;logger;appManagerController;platformAppName;registry=hs();validNonExistentApps;signaledSubscription=!1;interopId;isAppValidationEnabled;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("prefs.controller.web"),this.logger.trace("starting the web prefs controller"),this.addOperationsExecutors(),this.interopId=e.interop.instance.instance,this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",Xs.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[],this.isAppValidationEnabled=e.isAppValidationEnabled??!0}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support Prefs API.")}this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning");const n=this.toApi();e.prefs=n}async handleBridgeMessage(e){const t=X(dr,e.operation),n=Xs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async get(e){const t=null==e?this.getMyAppName():X(tt,e),{prefs:n}=await this.bridge.send("prefs",Xs.get,{app:t},void 0,{includeOperationCheck:!0});return n}async update(e,t){const n=X(O(hr),t),i=n?.app??this.getMyAppName();await this.updateFor(i,e)}addOperationsExecutors(){Xs.prefsChanged.execute=this.handleOnChanged.bind(this),Xs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Xs)}toApi(){return{clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearFor:this.clearFor.bind(this),get:this.get.bind(this),getAll:this.getAll.bind(this),set:this.set.bind(this),setFor:this.setFor.bind(this),subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),update:this.update.bind(this),updateFor:this.updateFor.bind(this)}}async clear(){const e=this.getMyAppName();await this.clearFor(e)}async clearAll(){await this.bridge.send("prefs",Xs.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=X(tt,e);await this.bridge.send("prefs",Xs.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",Xs.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const n=X(O(hr),t),i=n?.app??this.getMyAppName();await this.setFor(i,e)}async setFor(e,t){const n=X(tt,e),i=X(k(),t);await this.bridge.send("prefs",Xs.set,{app:n,data:i},void 0,{includeOperationCheck:!0})}subscribe(e){const t=this.getMyAppName();return this.subscribeFor(t,e)}subscribeFor(e,t){const n=X(tt,e),i=this.appManagerController.getApplications();if(!(!this.isAppValidationEnabled||(n===this.platformAppName||i.some(e=>e.name===n)||this.validNonExistentApps.includes(n))))return re.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return re.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");this.signaledSubscription||(this.bridge.send("prefs",Xs.registerSubscriber,{interopId:this.interopId,appName:n},void 0,{includeOperationCheck:!0}).catch(e=>{this.logger.warn("Failed to register subscriber for prefs"),this.logger.error(e)}),this.signaledSubscription=!0);const r=this.getSubscriptionKey(n);return this.get(n).then(t),this.registry.add(r,t)}async updateFor(e,t){const n=X(tt,e),i=X(k(),t);await this.bridge.send("prefs",Xs.update,{app:n,data:i},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||re.raiseError("App Preferences operations can not be executed for windows that do not have app!")}getSubscriptionKey(e){return`prefs-changed-${e}`}async handleOnChanged({prefs:e}){const t=this.getSubscriptionKey(e.app);this.registry.execute(t,e)}}const to={getResources:{name:"getResources",dataDecoder:Er,resultDecoder:$r},operationCheck:{name:"operationCheck",dataDecoder:Ni,resultDecoder:ji},showAlert:{name:"showAlert",dataDecoder:Br},showDialog:{name:"showDialog",dataDecoder:zr},alertInteropAction:{name:"alertInteropAction",dataDecoder:Xr},showResolver:{name:"showResolver",dataDecoder:as,resultDecoder:cs}},no="io-modals-shadow-host",io="io-widget-shadow-host",ro="io-intent-resolver-shadow-host";class so{ioc;supportedOperationsNames=[];logger;bridge;config;zIndexDictionary={[io]:"100",[no]:"101",[ro]:"100"};widgetResources;modalsResources;intentResolverResources;rootElements=[];modalsUiApi;isDialogOpen=!1;intentResolverUiApi;isIntentResolverOpen=!1;constructor(e){this.ioc=e}async start(e,t){this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.addOperationsExecutors();const n=await this.getResources();n?(this.logger.trace(`Received UI resources from platform: ${JSON.stringify(n)}`),this.setResources(n)):this.logger.trace("No UI elements to display - platform is not initialized with any UI resources")}async handleBridgeMessage(e){const t=X(Mr,e.operation),n=to[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async showComponents(e){const t=this.widgetResources?this.initializeWidget(e,this.widgetResources):Promise.resolve(),n=this.modalsResources?this.initializeModalsUi(e,this.modalsResources):Promise.resolve(),i=this.intentResolverResources?this.initializeIntentResolverUI(e,this.intentResolverResources):Promise.resolve();this.subscribeForThemeChanges(e),await Promise.all([this.config.widget.awaitFactory?t:Promise.resolve(),this.config.modals.awaitFactory?n:Promise.resolve(),this.config.intentResolver.awaitFactory?i:Promise.resolve()])}isIntentResolverEnabled(){return!!this.intentResolverResources&&this.config.intentResolver.enable}addOperationsExecutors(){to.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),to.showAlert.execute=this.handleShowAlert.bind(this),to.showDialog.execute=this.handleShowDialog.bind(this),to.showResolver.execute=this.handleShowResolver.bind(this),this.supportedOperationsNames=ee(to)}async handleShowAlert({config:e}){if(!this.config.modals.alerts.enabled)return re.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showAlert operation because modalsUiApi is missing.");const{promise:n,resolve:i}=ie(),r=e=>{const t=Yr.run(e);if(!t.ok)return void this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(t.error)}.`);const{interopAction:n}=t.result;this.bridge.send("ui",to.alertInteropAction,{interopAction:n},void 0,{includeOperationCheck:!0}).catch(e=>this.logger.warn(Y(e)))};let s;try{this.logger.trace(`Open alert with config: ${JSON.stringify(e)}`),s=t.alerts.open({...e,onClick:r,onClose:i})}catch(e){return re.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${Y(e)}.`)}const o=Vr.run(s);if(!o.ok)return re.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);const a=setTimeout(()=>{i()},ne(e.ttl??5e3));n.then(()=>{clearTimeout(a);try{t.alerts.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close alert with id ${o.result.id}. Reason: ${Y(e)}`)}})}async handleShowDialog({config:e}){if(!this.config.modals.dialogs.enabled)return re.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showDialog operation because modalsUiApi is missing.");if(this.isDialogOpen)return re.raiseError("Cannot open a dialog because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open dialog with config: ${JSON.stringify(e)}`),r=t.dialogs.open({...e,onCompletion:i})}catch(e){return re.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${Y(e)}.`)}const s=Kr.run(r);if(!s.ok)return re.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);let o;this.isDialogOpen=!0,e.timer&&(o=setTimeout(()=>{i({response:{isExpired:!0}})},ne(e.timer.duration)));const a=await n;clearTimeout(o),this.isDialogOpen=!1;try{t.dialogs.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close dialog with id ${s.result.id}. Reason: ${Y(e)}`)}const c=Zr.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async handleShowResolver({config:e}){if(this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(e)}`),!this.config.intentResolver.enable)return re.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config.");const t=this.intentResolverUiApi;if(!t)return re.raiseError("Unable to perform showResolver operation because intentResolverApi is missing.");if(this.isIntentResolverOpen)return re.raiseError("Cannot open the intent resolver because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open intent resolver with config: ${JSON.stringify(e)}`),r=t.open({...e,onUserResponse:i})}catch(e){return re.raiseError(`intentResolverUI.open() failed. Reason: ${Y(e)}.`)}const s=ts.run(r);if(!s.ok)return re.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);const o=setTimeout(()=>i({response:{isExpired:!0}}),ne(e.timeout)),a=await n;clearTimeout(o),this.isIntentResolverOpen=!1;try{t.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close intent resolver with id ${s.result.id}. Reason: ${Y(e)}`)}const c=ss.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",to.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}appendModalsResources(e){return this.logger.trace("Appending modals resources"),this.appendResources(no,"io-modals-root",e.sources)}appendWidgetResources(e){return this.logger.trace("Appending widget resources"),this.appendResources(io,"io-widget-root",e.sources)}appendIntentResolverResources(e){return this.logger.trace("Appending intent resolver resources"),this.appendResources(ro,"io-intent-resolver-root",e.sources)}appendResources(e,t,n){const{bundle:i,fonts:r=[],styles:s}=n,o=document.createElement("div");o.id=e,o.style.position="fixed",o.style.zIndex=this.zIndexDictionary[e];const a=o.attachShadow({mode:"open"}),c=document.createElement("script");c.src=i,c.type="module",a.appendChild(c);const d=document.createElement("div");return d.id=t,d.className="io-body io-variables",a.appendChild(d),s.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,a.appendChild(t)}),r.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.insertBefore(t,document.head.firstChild)}),document.body.appendChild(o),{rootElement:d}}async initializeWidget(e,t){this.logger.trace("Initializing IOBrowserWidget.");const{rootElement:n}=this.appendWidgetResources(t);this.rootElements.push(n);const i={...d(t.config,this.config.widget),rootElement:n};return fs(async()=>{await this.ioc.eventsDispatcher.widgetReady(),this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(i)}`),await window.IOBrowserWidget(e,i),this.logger.trace("IOBrowserWidget was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserWidget to initialize.`)}async initializeModalsUi(e,t){this.logger.trace("Initializing IOBrowserModalsUI.");const{rootElement:n}=this.appendModalsResources(t);this.rootElements.push(n);const i={...this.config.modals,rootElement:n};return fs(async()=>{await this.ioc.eventsDispatcher.modalsUIFactoryReady(),this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.modalsUiApi=await window.IOBrowserModalsUI(e,i),this.logger.trace("IOBrowserModalsUI was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`)}async initializeIntentResolverUI(e,t){this.logger.trace("Initializing IOBrowserIntentResolverUI.");const{rootElement:n}=this.appendIntentResolverResources(t);this.rootElements.push(n);const i={...this.config.intentResolver,rootElement:n},r=i.timeout;return fs(async()=>{await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(),this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.intentResolverUiApi=await window.IOBrowserIntentResolverUI(e,i),this.logger.trace("IOBrowserIntentResolverUI initialized successfully.")},r,`Timeout of ${r}ms hit waiting for IOBrowserIntentResolverUI to initialize.`)}setResources(e){this.setWidgetResources(e.widget),this.setModalsUiResources(e.modals),this.setIntentResolverResources(e.intentResolver)}setWidgetResources(e){const t="Widget won't be displayed. Reason: ",n=Rr.run(this.config.widget);n.ok?this.config.widget.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`):this.widgetResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'widget: { enable: false }' config`):this.logger.warn(`${t} invalid widget config. Error: ${n.error}`)}setModalsUiResources(e){const t="Modals won't be displayed. Reason: ",n=Ar.run(this.config.modals);n.ok?this.config.modals.alerts.enabled||this.config.modals.dialogs.enabled?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`):this.modalsResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`):this.logger.warn(`${t} invalid modals config. Error: ${n.error}`)}setIntentResolverResources(e){const t="Intent Resolver UI won't be displayed. Reason: ",n=es.run(this.config.intentResolver);n.ok?this.config.intentResolver.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`):this.intentResolverResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'intentResolver: { enable: false }' config`):this.logger.warn(`${t} invalid intent resolver config. Error: ${JSON.stringify(n.error)}`)}subscribeForThemeChanges(e){const t=e.themes;if(!t)return;const n=async e=>{await Promise.all(this.rootElements.map(n=>this.applyThemeToElement(n,t,e)))};t.onChanged(n),t.getCurrent().then(n)}async applyThemeToElement(e,t,n){if(e.classList.contains(n.name))return;const i=await t.list();e.classList.remove(...i.map(({name:e})=>e)),e.classList.add(n.name)}}class oo{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_channelsStorage;_prefsControllerInstance;_uiController;controllers={windows:this.windowsController,appManager:this.appManagerController,layouts:this.layoutsController,notifications:this.notificationsController,intents:this.intentsController,channels:this.channelsController,system:this.systemController,extension:this.extensionController,themes:this.themesController,prefs:this.prefsController,ui:this.uiController};get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new bs),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new so(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new _s),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Ps),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new Qs),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new As),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new Ds),this._intentsControllerInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new Bs),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new Us),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new eo),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new zs),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new Vs(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Is(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new Ks(this._coreGlue)),this._preferredConnectionController}get channelsStorage(){return this._channelsStorage||(this._channelsStorage=new Ys),this._channelsStorage}get config(){return this._webConfig}defineGlue(e){this._coreGlue=e,this._publicWindowId=e.connection.transport.publicWindowId;const t=window.glue42core||window.iobrowser;this._communicationId=e.connection.transport.communicationId||t.communicationId}defineConfig(e){this._webConfig=e}async buildWebWindow(e,t,n){const i=new ps(e,t,this.bridge,n),r=await i.toApi();return{id:e,model:i,api:r}}buildNotification(e,t){return new Gs(e,t)}async buildApplication(e,t){const n=new Ts(e,[],this.appManagerController).toApi(),i=t.map(e=>this.buildInstance(e,n));return n.instances.push(...i),n}buildInstance(e,t){return new xs(e,this.bridge,t).toApi()}}var ao="4.4.0";const co=(e,t)=>({getContainerInfo:async()=>{if(window!==window.parent)return window.name.includes("#wsp")?{workspaceFrame:{id:"N/A"}}:window.parent===window.top?{top:{}}:{parent:{}}},getProfileData:async()=>{if(!t)throw new Error("Bridge is not available and cannot fetch the profile data");return await t.send("system",{name:"getProfileData"},void 0)}});var lo=1,ho=2,uo=3,po=4;function go(e){return e.type===uo?"timestamp":e.type===ho?"number":e.type===lo?"string":e.type===po?"object":"unknown"}function fo(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function mo(e){const t={},n=go(e);if("object"===n){const n=Object.keys(e.value).reduce((t,n)=>{const i=fo(e.value[n]);if("object"===i){const i=bo(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=yo(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function bo(e){return Object.keys(e).reduce((t,n)=>{const i=fo(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:bo(e[n])}:{type:i,description:"",context:{}},t},{})}function yo(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function wo(e){return"timestamp"===go(e)?Date.now():vo(e.value)}function vo(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]=vo(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t},{})}function Co(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?Co(t):t),[])}function Io(e){const t=Co(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 So=(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 _o{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,So(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 xo extends _o{constructor(e,t,n,i){super(e,t,n,i,ho)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class To extends _o{constructor(e,t,n,i){super(e,t,n,i,po)}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 ko extends _o{constructor(e,t,n,i){super(e,t,n,i,lo)}}class Po extends _o{constructor(e,t,n,i){super(e,t,n,i,uo)}now(){this.update(new Date)}}function Oo(e,t,n,i,r){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const s=n,o=e,a=r||"",c=t,d=i,l=function e(t){if(!t||!t.parent)return[];const n=e(t.parent);return n.push(t.name),n}(i);let h={};const u=(g="/",((p=l)&&p.length>0?p.join(g):"")+e);var p,g;const f=t.root,m=[],b=[];function y(e,t,n,i){let r={name:""};r="string"==typeof e?{name:e}:e;const s=b.filter(e=>e.name===r.name);if(s.length>0){const e=s[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 o=i(r);return b.push(o),o}const w={get name(){return o},get description(){return a},get repo(){return c},get parent(){return d},path:l,id:u,root:f,get subSystems(){return m},get metrics(){return b},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=m.filter(t=>t.name===e);if(n.length>0)return n[0];const i=Oo(e,c,s,w,t);return m.push(i),i},getState:()=>h,setState:function(e,t){h={state:e,description:t},s.updateSystem(w,h)},stringMetric:function(e,t){return y(e,lo,t,e=>new ko(e,w,s,t))},timestampMetric:function(e,t){return y(e,uo,t,e=>new Po(e,w,s,t))},objectMetric:function(e,t){return y(e,po,t,e=>new To(e,w,s,t))},numberMetric:function(e,t){return y(e,ho,t,e=>new xo(e,w,s,t))},getAggregateState:function(){const e=[];return Object.keys(h).length>0&&e.push({name:o,path:l,state:h.state,description:h.description}),m.forEach(t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)}),e}};return s.createSystem(w),w}class Ro{root;constructor(e,t){t.init(this),this.root=Oo("",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 Ao{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class Mo{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;if(!e||!e.memory)return;const t=e.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.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 Eo=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=>{s(e.root)},s=e=>{o(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{s(e)})},o=async e=>{if(void 0===e.parent)return;await n;const r={type:"define",metrics:[{name:yo(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)}`)})},a=async e=>{const r=d(e);await n;const s={type:"define",metrics:[mo(r)]};i.sendFireAndForget(s).catch(n=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(n)}`)}),void 0!==r.value&&c(r)},c=e=>{if(l()){const n=wo(e),r={type:"publish",values:[{name:yo(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()},d=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},l=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:s=>{let o;n=new Promise(e=>{o=e}),i=e.domain("metrics"),i.onJoined(e=>{!e&&o&&(o(),o=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(s)}),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:o,updateSystem:async(r,s)=>{await n;const o={type:"publish",values:[{name:yo(r.path.join("/")+"/"+r.name+"/State"),value:{Description:s.description,Value:s.state},timestamp:Date.now()}]};i.sendFireAndForget(o).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${r.name}: ${JSON.stringify(e)}`)});const a=Io(r),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};i.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${r.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=d(e);await n,c(t)}}}(e.connection,e):new Ao;let n=new Ro(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,s)=>{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===s||""===s)throw new Error("payload is mandatory");i?i.update({name:e,action:r,payload:s}):i=t.objectMetric(n,{name:e,action:r,payload:s})};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 Mo(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var Do,jo,No="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Fo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Lo=function(){if(jo)return Do;function e(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 s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.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 s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}return jo=1,e.default=e,Do=e}(),$o=Fo(Lo);class Wo{gw;registry=$o();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 Ho{logger;worker;registry=$o();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)}}class Uo{static isNode(){if(void 0!==Uo._isNode)return Uo._isNode;if("undefined"!=typeof window)return Uo._isNode=!1,!1;try{Uo._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){Uo._isNode=!1}return Uo._isNode}static _isNode;static getMethodName(e){return"string"==typeof e?e:e?.name}}class qo{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 Bo={};function Go(e){const t=Bo[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const r=i();let s,o;function a(e,t){const r=t??i();let s=0;n.length>0&&(s=r-n[n.length-1].time),n.push({name:e,time:r,diff:s})}a("start",r);const c={get startTime(){return r},get endTime(){return s},get period(){return o},stop:function(){return s=i(),a("end",s),o=s-r,o},mark:a,marks:n};return Bo[e]=c,c}const Jo=Uo.isNode()?null:window.WebSocket;function zo(e,t,n,i){const r=!1!==i?.includeStack,s=e instanceof Error?e:e?.error;return s instanceof Error?JSON.stringify({name:s.name,message:s.message,code:s.code,stack:r?s.stack:void 0}):JSON.stringify({type:e?.type,readyState:t?.readyState,url:n,message:"string"==typeof e?.message?e.message:void 0})}class Vo{ws;logger;settings;startupTimer=Go("connection");_running=!0;_registry=$o();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 qo;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){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);try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{if(void 0!==t&&t<=0)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);void 0!==t&&this.logger.debug(`will retry ${t-1} more times (every ${e} ms)`),setTimeout(()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)},e)}}initiateSocket(){const e=new qo;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new Jo(this.settings.ws??"");let t=!1;return this.ws.onerror=n=>{const i=zo(n,this.ws,this.settings.ws);this.logger.info(`ws error - ${i}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error"));const r=zo(n,this.ws,this.settings.ws,{includeStack:!1});this.notifyStatusChanged(!1,r)},this.ws.onclose=n=>{var i;this.logger.info("ws closed - "+(i=n,`code: ${i?.code} reason: ${i?.reason||"(none)"} wasClean: ${i?.wasClean}`)),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 Ko{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 Zo=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const Qo=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class Yo{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=$o();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 Qo((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??Zo(10);const i=this.getMyWindowId()||Zo(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||Zo(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(()=>Qo((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():Qo(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=Qo(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-${Zo(10)}`,this.selfAssignedWindowId):void 0}}class Xo{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 ea(e,t,n,i,r){null==e&&(e="global"),i=i??["success"],r=r??["error"];let s,o="global"===e,a=!1,c=!1;const d=$o();t.disconnected(function(){n.debug("connection is down"),c=!1,o=!1,a=!0,Object.keys(l).forEach(e=>{const t=l[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 h(s)}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 l={};function h(t){return s=t,new Promise((i,r)=>{if(o)return void i({});let s;if("global"===e)s=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);s=b({type:"join",destination:e,domain:"global",options:t})}s.then(()=>{!function(){n.debug("did join "+e),o=!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 o&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.error(t)}function g(t){if(t.domain!==e)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.success(t)}function f(){return Zo(10)}let m=[];function b(i,r,s){if(i.type&&-1===["hello","join"].indexOf(i.type)&&!o){console.warn(`trying to send a message (${i.domain} ${i.type}) but not connected, will queue`);const e=new qo;if(m.push({msg:i,tag:r,options:s,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=>{b(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),m=[],e()})}return e.promise}s=s??{},i.request_id=i.request_id??f(),i.domain=i.domain??e,s.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise((e,n)=>{l[a]={success:t=>{delete l[a],t._tag=r,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete l[a],e._tag=r,n(e)}},t.send(i,s).catch(e=>{l[a]?.error({err:e})})})}return{join:h,leave:function(){return"global"===e?Promise.resolve():o?(n.debug("stopping session "+e+"..."),a=!1,b({type:"leave",destination:e,domain:"global"}).then(()=>{o=!1,d.execute("onLeft")}).catch(()=>{o=!1,d.execute("onLeft")})):(a=!1,Promise.resolve())},onJoined:u,onLeft:function(e){return o||e(),d.add("onLeft",e)},send:b,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}}}function ta(e){if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);const t=e,n="string"==typeof t?.message?t.message:void 0,i="string"==typeof t?.reason?t.reason:void 0;return void 0!==n&&n.length>0?new Error(n):void 0!==i&&i.length>0?new Error(i):""===n||""===i?new Error(""):new Error(function(e){try{const t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if("bigint"==typeof n)return`${n.toString()}n`;if("function"==typeof n)return"[Function]";if("symbol"==typeof n)return n.toString();if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return n});if(void 0!==n)return n}catch{}if(null!==e&&"object"==typeof e){const t=e.constructor?.name??"Object";let n=[];try{n=Object.keys(e)}catch{}return n.length>0?`[${t} keys=${n.join(",")}]`:`[${t}]`}return String(e)}(e))}class na{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=$o();_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 Xo;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;reconnectTimeout;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;remainingReconnectAttempts;loginConfig;loginRetryInProgress=!1;reconnectInProgress=!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 Wo(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Ho(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new Yo(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new Vo(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`),Go("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(n)}`),Go("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()),ta(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=ea(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"))}async reconnect(){if(!this.loginConfig)throw new Error("Cannot reconnect - no previous login configuration");if(this.reconnectInProgress)this.logger.debug("reconnect() already in progress, ignoring");else{this.reconnectInProgress=!0;try{for(this.shouldTryLogin=!1,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);this.loginRetryInProgress;)await new Promise(e=>setTimeout(e,50));this._isLoggedIn&&(this.setLoggedIn(!1),this.registry.execute("disconnected")),this.shouldTryLogin=!0,await this.login(this.loginConfig,!0)}finally{this.reconnectInProgress=!1}}}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 Ko(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&(this.remainingReconnectAttempts=this.settings.reconnectAttempts,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.shouldTryLogin)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--}else if(void 0!==this.remainingReconnectAttempts){if(this.remainingReconnectAttempts<=0)return void this.logger.info("maximum reconnect attempts reached, will not try to login again");this.logger.debug(`reconnect attempt, ${this.remainingReconnectAttempts} attempts remaining...`),this.remainingReconnectAttempts--}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),this.shouldTryLogin&&(this.reconnectTimeout=setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3))}finally{this.loginRetryInProgress=!1}}else this.logger.debug("should not try to login, ignoring reconnect attempt...")}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 Qo(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 Vo(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:""});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=ea("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 s=await e.send(t,void 0,n);if("authentication-request"!==s.type){if("welcome"===s.type){r=s;break}throw"error"===s.type?new Error("Authentication failed: "+s.reason):new Error("Unexpected message type during authentication: "+s.type)}{const e=Buffer.from(s.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.setLoggedIn(!1),this.pingTimer&&clearTimeout(this.pingTimer),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);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 ia=["trace","debug","info","warn","error","off"];class ra{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.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}subLogger(e){const t=this.subLoggers.filter(t=>t.name===e)[0];if(void 0!==t)return t;Object.keys(this).forEach(t=>{if(t===e)throw new Error("This sub logger name is not allowed.")});const n=new ra(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}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 ia.indexOf(e)>=ia.indexOf(t||this.consoleLevel()||"trace")}publishMessage(e,t,n){const i=this.loggerFullName;if("error"===e&&!n){const e=new Error;e.stack&&(t=t+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(e,this.publishLevel())){const r=ra.Interop;if(r)try{if(r.methods({name:ra.InteropMethodName}).length>0){const s={msg:t,logger:i,level:e};n&&n instanceof Error&&(s.error={message:n.message,stack:n.stack??""}),r.invoke(ra.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(e)){let r="";if(this.includeTimeAndLevel){const t=new Date;r=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const s=`${r}${i}: ${t}`;switch(e){case"trace":this.logFn.debug(s);break;case"debug":this.logFn.debug?this.logFn.debug(s):this.logFn.log(s);break;case"info":this.logFn.info(s);break;case"warn":this.logFn.warn(s);break;case"error":n?this.logFn.error(s,n):this.logFn.error(s)}}}}const sa="create-context",oa="created",aa="destroyed",ca="context-created",da="context-added",la="subscribe-context",ha="subscribed-context",ua="unsubscribe-context",pa="destroy-context",ga="context-destroyed",fa="update-context",ma="context-updated",ba="joined",ya={get name(){return"context"},get types(){return[sa,oa,aa,ca,da,la,ha,ua,pa,ga,fa,ma,ba]}};var wa,va,Ca="6.10.4";
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).browser=e.browser||{},e.browser.min=t())}(this,function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||function(e){return e.$$typeof===n}(e)}(e)};var n="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function i(e,t){return!1!==t.clone&&t.isMergeableObject(e)?c((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function r(e,t,n){return e.concat(t).map(function(e){return i(e,n)})}function s(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function o(e,t){try{return t in e}catch(e){return!1}}function a(e,t,n){var r={};return n.isMergeableObject(e)&&s(e).forEach(function(t){r[t]=i(e[t],n)}),s(t).forEach(function(s){(function(e,t){return o(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,s)||(o(e,s)&&n.isMergeableObject(t[s])?r[s]=function(e,t){if(!t.customMerge)return c;var n=t.customMerge(e);return"function"==typeof n?n:c}(s,n)(e[s],t[s],n):r[s]=i(t[s],n))}),r}function c(e,n,s){(s=s||{}).arrayMerge=s.arrayMerge||r,s.isMergeableObject=s.isMergeableObject||t,s.cloneUnlessOtherwiseSpecified=i;var o=Array.isArray(n);return o===Array.isArray(e)?o?s.arrayMerge(e,n,s):a(e,n,s):i(n,s)}c.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return c(e,n,t)},{})};var d=e(c),l=function(e){return{ok:!0,result:e}},h=function(e){return{ok:!1,error:e}},u=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:l(e(t.result,n.result))},p=function(e,t){return!0===t.ok?t:h(e(t.error))},g=function(){return g=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},g.apply(this,arguments)};function f(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(!f(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(!f(e[i[n]],t[i[n]]))return!1}return!0}}var m=function(e){return Array.isArray(e)},b=function(e){return"object"==typeof e&&null!==e&&!m(e)},y=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)},w=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},v=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 g({at:e+(n||"")},i)},C=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return p(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?l(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?l(e):h({message:y("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?l(e):h({message:y("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?l(e):h({message:y("a boolean",e)})})},e.constant=function(t){return new e(function(e){return f(e,t)?l(t):h({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(b(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]?h({message:"the key '"+i+"' is required but was not present"}):h(v("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return l(n)}return b(e)?l(e):h({message:y("an object",e)})})},e.array=function(t){return new e(function(e){if(m(e)&&t){return e.reduce(function(e,n,i){return u(function(e,t){return e.concat([t])},e,function(e,n){return p(function(e){return v("["+n+"]",e)},t.decode(e))}(n,i))},l([]))}return m(e)?l(e):h({message:y("an array",e)})})},e.tuple=function(t){return new e(function(e){if(m(e)){if(e.length!==t.length)return h({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 h(v("["+i+"]",r.error));n[i]=r.result}return l(n)}return h({message:y("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 u(Object.assign,t,n.decode(e))},l({}))})},e.anyJson=function(){return new e(function(e){return l(e)})},e.unknownJson=function(){return new e(function(e){return l(e)})},e.dict=function(t){return new e(function(e){if(b(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return h(v("."+i,r.error));n[i]=r.result}return l(n)}return h({message:y("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?l(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 s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return h({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return l(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 h({at:w(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!b(i))return h({at:w(t.slice(0,r+1)),message:y("an object",i)});if("number"==typeof t[r]&&!m(i))return h({at:w(t.slice(0,r+1)),message:y("an array",i)});i=i[t[r]]}return p(function(e){return void 0===i?{at:w(t),message:"path does not exist"}:v(w(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return l(t)})},e.fail=function(t){return new e(function(e){return h({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),I=C.string,S=C.number,_=C.boolean,x=C.anyJson;C.unknownJson;var T=C.constant,k=C.object,P=C.array;C.tuple,C.dict;var O=C.optional,R=C.oneOf,A=C.union,M=C.intersection;C.withDefault,C.valueAt,C.succeed,C.fail;var E=C.lazy;const D={gateway:{webPlatform:{}},libraries:[],exposeAPI:!0},j={awaitFactory:!0,enable:!1,timeout:5e3,restoreLastKnownPosition:!0},N={alerts:{enabled:!1},dialogs:{enabled:!1},awaitFactory:!0,timeout:5e3},F={enable:!1,timeout:5e3,awaitFactory:!0},L={name:"platformUnload"},$={name:"transportSwitchRequest"},W={name:"transportSwitchResponse"},H={name:"getCurrentTransport"},U={name:"getCurrentTransportResponse"},q={name:"checkPreferredLogic"},B={name:"checkPreferredConnection"},G={name:"checkPreferredLogicResponse"},J={name:"checkPreferredConnectionResponse"},z="web-platform",V="latest_fdc3_type",K=new MessageChannel,Z=2147483647,Q={configurable:!1,enumerable:!0,writable:!1},Y=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),X=(e,t)=>{try{return e.runWithException(t)}catch(e){return re.raiseError(e,!0)}},ee=e=>Object.keys(e).filter(t=>e[t].execute),te=(e,t)=>({isSupported:e.some(e=>e.toLowerCase()===t.toLowerCase())}),ne=e=>Math.min(e,Z),ie=()=>{let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}};const re=new class{raiseError(e,t){const n=Y(e);if(K.port1.postMessage(n),t)throw e;throw new Error(n)}},se=["name","title","version","customProperties","icon","caption","type"],oe=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ae=function(e){return{ok:!0,result:e}},ce=function(e){return{ok:!1,error:e}},de=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:ae(e(t.result,n.result))},le=function(e,t){return!0===t.ok?t:ce(e(t.error))},he=function(){return he=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},he.apply(this,arguments)};function ue(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(!ue(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(!ue(e[i[n]],t[i[n]]))return!1}return!0}}var pe=function(e){return Array.isArray(e)},ge=function(e){return"object"==typeof e&&null!==e&&!pe(e)},fe=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)},me=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},be=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 he({at:e+(n||"")},i)},ye=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return le(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?ae(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?ae(e):ce({message:fe("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ae(e):ce({message:fe("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ae(e):ce({message:fe("a boolean",e)})})},e.constant=function(t){return new e(function(e){return ue(e,t)?ae(t):ce({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ge(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]?ce({message:"the key '"+i+"' is required but was not present"}):ce(be("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return ae(n)}return ge(e)?ae(e):ce({message:fe("an object",e)})})},e.array=function(t){return new e(function(e){if(pe(e)&&t){return e.reduce(function(e,n,i){return de(function(e,t){return e.concat([t])},e,function(e,n){return le(function(e){return be("["+n+"]",e)},t.decode(e))}(n,i))},ae([]))}return pe(e)?ae(e):ce({message:fe("an array",e)})})},e.tuple=function(t){return new e(function(e){if(pe(e)){if(e.length!==t.length)return ce({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 ce(be("["+i+"]",r.error));n[i]=r.result}return ae(n)}return ce({message:fe("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 de(Object.assign,t,n.decode(e))},ae({}))})},e.anyJson=function(){return new e(function(e){return ae(e)})},e.unknownJson=function(){return new e(function(e){return ae(e)})},e.dict=function(t){return new e(function(e){if(ge(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return ce(be("."+i,r.error));n[i]=r.result}return ae(n)}return ce({message:fe("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ae(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 s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return ce({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return ae(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 ce({at:me(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ge(i))return ce({at:me(t.slice(0,r+1)),message:fe("an object",i)});if("number"==typeof t[r]&&!pe(i))return ce({at:me(t.slice(0,r+1)),message:fe("an array",i)});i=i[t[r]]}return le(function(e){return void 0===i?{at:me(t),message:"path does not exist"}:be(me(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return ae(t)})},e.fail=function(t){return new e(function(e){return ce({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),we=ye.string,ve=ye.number,Ce=ye.boolean,Ie=ye.anyJson;ye.unknownJson;var Se=ye.constant,_e=ye.object,xe=ye.array;ye.tuple;var Te=ye.dict,ke=ye.optional,Pe=ye.oneOf;ye.union,ye.intersection,ye.withDefault,ye.valueAt,ye.succeed;var Oe=ye.fail;ye.lazy;const Re=we().where(e=>e.length>0,"Expected a non-empty string"),Ae=ve().where(e=>e>=0,"Expected a non-negative number"),Me=Ie().andThen(e=>e instanceof RegExp?Ie():Oe("expected a regex, got a "+typeof e)),Ee=Re.andThen(e=>{try{const{protocol:t}=new URL(e),n=["data:","javascript:","vbscript:"];return n.includes(t)?Oe(`Expected a URL with a safe protocol, got: ${t} (disallowed protocols: ${n.join(", ")})`):Re}catch{return Oe("Expected a valid URL")}}),De=_e({name:Re,displayName:ke(we()),contexts:ke(xe(we())),customConfig:ke(_e())}),je=Pe(Se("web"),Se("native"),Se("citrix"),Se("onlineNative"),Se("other")),Ne=_e({url:Ee}),Fe=_e({src:Re,size:ke(Re),type:ke(Re)}),Le=_e({src:Re,size:ke(Re),type:ke(Re),label:ke(Re)}),$e=_e({contexts:xe(Re),displayName:ke(Re),resultType:ke(Re),customConfig:ke(Ie())}),We=_e({listensFor:ke(Te($e)),raises:ke(Te(xe(Re)))}),He=_e({broadcasts:ke(xe(Re)),listensFor:ke(xe(Re))}),Ue=_e({name:ke(Re),id:ke(Re),description:ke(Re),broadcasts:ke(xe(Re)),listensFor:ke(xe(Re))}).where(e=>Boolean(e.name||e.id),"Expected at least a name or an id property to be present in the app channel definition"),qe=_e({intents:ke(We),userChannels:ke(He),appChannels:ke(xe(Ue))}),Be=_e({url:ke(Ee),top:ke(ve()),left:ke(ve()),width:ke(Ae),height:ke(Ae)}),Ge=_e({name:ke(Re),type:ke(Re.where(e=>"window"===e,"Expected a value of window")),title:ke(Re),version:ke(Re),customProperties:ke(Ie()),icon:ke(we()),caption:ke(we()),details:ke(Be),intents:ke(xe(De)),hidden:ke(Ce())}),Je=_e({name:Re,appId:Re,title:ke(Re),version:ke(Re),manifest:Re,manifestType:Re,tooltip:ke(Re),description:ke(Re),contactEmail:ke(Re),supportEmail:ke(Re),publisher:ke(Re),images:ke(xe(_e({url:ke(Re)}))),icons:ke(xe(_e({icon:ke(Re)}))),customConfig:Ie(),intents:ke(xe(De))}),ze=_e({appId:ke(Re),name:ke(Re),details:ke(Ne),version:ke(Re),title:ke(Re),tooltip:ke(Re),lang:ke(Re),description:ke(Re),categories:ke(xe(Re)),icons:ke(xe(Fe)),screenshots:ke(xe(Le)),contactEmail:ke(Re),supportEmail:ke(Re),moreInfo:ke(Re),publisher:ke(Re),customConfig:ke(xe(Ie())),hostManifests:ke(Ie()),interop:ke(qe)}),Ve=_e({appId:Re,name:ke(Re),type:je,details:Ne,version:ke(Re),title:ke(Re),tooltip:ke(Re),lang:ke(Re),description:ke(Re),categories:ke(xe(Re)),icons:ke(xe(Fe)),screenshots:ke(xe(Le)),contactEmail:ke(Re),supportEmail:ke(Re),moreInfo:ke(Re),publisher:ke(Re),customConfig:ke(xe(Ie())),hostManifests:ke(Ie()),interop:ke(qe),localizedVersions:ke(Te(ze))}),Ke=Pe(Je,Ve),Ze=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class Qe{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=Ke.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:Ze(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=Ke.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ze(i.error)}`);const r=this.getUserPropertiesFromDefinition(e,n),s={url:this.getUrl(e,n)},o={name:e.appId,type:"window",createOptions:s,userProperties:{...r,intents:"1.2"===n?r.intents:this.getIntentsFromV2AppDefinition(e),details:s},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 o;const c=Ge.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ze(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(o,c.result):o}parseToDesktopAppConfig(e){const{isFdc3:t,version:n}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const i=Ke.run(e);if(!i.ok)throw new Error(`Invalid FDC3 ${n} definition. Error: ${Ze(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,s={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"}},o=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!o)return s;if("object"!=typeof o||Array.isArray(o))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(s,o)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!se.includes(e)&&!oe.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.customProperties&&(n.userProperties={...e.userProperties,...t.customProperties}),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 Ye={common:{nonEmptyStringDecoder:Re,nonNegativeNumberDecoder:Ae,regexDecoder:Me,urlDecoder:Ee},fdc3:{allDefinitionsDecoder:Ke,v1DefinitionDecoder:Je,v2DefinitionDecoder:Ve}};var Xe;!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"}(Xe||(Xe={}));const et=new class{_fdc3;_decoders=Ye;_errors={intents:Xe};get fdc3(){return this._fdc3||(this._fdc3=(new Qe).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};et.fdc3;const tt=et.decoders;et.errors;const nt=tt.common.nonEmptyStringDecoder,it=tt.common.nonNegativeNumberDecoder,rt=O(nt),st=tt.common.urlDecoder,ot=R(T("system"),T("windows"),T("appManager"),T("layouts"),T("intents"),T("notifications"),T("channels"),T("extension"),T("themes"),T("prefs"),T("ui")),at=R(T("openWindow"),T("windowHello"),T("windowAdded"),T("windowRemoved"),T("getBounds"),T("getFrameBounds"),T("getUrl"),T("moveResize"),T("focus"),T("close"),T("getTitle"),T("setTitle"),T("focusChange"),T("getChannel"),T("notifyChannelsChanged"),T("setZoomFactor"),T("zoomFactorChange"),T("refresh"),T("operationCheck")),ct=R(T("appHello"),T("appDirectoryStateChange"),T("instanceStarted"),T("instanceStopped"),T("applicationStart"),T("instanceStop"),T("clear"),T("operationCheck")),dt=R(T("layoutAdded"),T("layoutChanged"),T("layoutRemoved"),T("layoutRenamed"),T("get"),T("getAll"),T("export"),T("import"),T("remove"),T("rename"),T("clientSaveRequest"),T("getGlobalPermissionState"),T("checkGlobalActivated"),T("requestGlobalPermission"),T("getDefaultGlobal"),T("setDefaultGlobal"),T("clearDefaultGlobal"),T("updateMetadata"),T("operationCheck"),T("getCurrent"),T("defaultLayoutChanged"),T("layoutRestored")),lt=R(T("raiseNotification"),T("requestPermission"),T("notificationShow"),T("notificationClick"),T("getPermission"),T("list"),T("notificationRaised"),T("notificationClosed"),T("click"),T("clear"),T("clearAll"),T("configure"),T("getConfiguration"),T("configurationChanged"),T("setState"),T("clearOld"),T("activeCountChange"),T("stateChange"),T("operationCheck"),T("getActiveCount")),ht=R(T("getEnvironment"),T("getBase"),T("platformShutdown"),T("isFdc3DataWrappingSupported"),T("clientError"),T("systemHello"),T("operationCheck")),ut=R(T("top"),T("left"),T("right"),T("bottom")),pt=k({top:S(),left:S(),width:it,height:it}),gt=O(k({top:O(S()),left:O(S()),width:O(it),height:O(it),context:O(x()),relativeTo:O(nt),relativeDirection:O(ut),windowId:O(nt),layoutComponentId:O(nt)})),ft=k({name:nt,url:st,options:gt}),mt=k({windowId:O(nt)}),bt=k({windowId:nt,name:nt}),yt=k({windowId:nt}),wt=k({windows:P(bt),isWorkspaceFrame:_()}),vt=k({windowId:nt,title:I()}),Ct=k({windowId:nt,hasFocus:_()}),It=k({windowId:nt,top:O(S()),left:O(S()),width:O(it),height:O(it),relative:O(_())}),St=k({windowId:nt,bounds:k({top:S(),left:S(),width:it,height:it})}),_t=k({bounds:k({top:S(),left:S(),width:it,height:it})}),xt=k({windowId:nt,url:st}),Tt=k({windowId:nt,factorIndex:it}),kt=x(),Pt=k({top:O(S()),left:O(S()),width:O(it),height:O(it)}),Ot=k({id:nt,applicationName:nt}),Rt=k({flags:I()}),At=k({flags:I()}),Mt=k({windowId:nt,channelsNames:P(nt)}),Et=k({enabled:_()}),Dt=k({url:st,top:O(S()),left:O(S()),width:O(it),height:O(it),workspacesSandbox:O(At),channelSelector:O(Et),iframePermissionsPolicy:O(Rt)}),jt=k({name:nt,displayName:O(I()),contexts:O(P(I())),customConfig:O(k()),resultType:O(I())}),Nt=k({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),title:O(nt),version:O(nt),customProperties:O(x()),icon:O(I()),caption:O(I()),details:Dt,intents:O(P(jt)),hidden:O(_()),fdc3:O(tt.fdc3.v2DefinitionDecoder)}),Ft=k({name:nt}),Lt=k({definitions:P(Nt)}),$t=k({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),instances:P(Ot),userProperties:O(x()),title:O(nt),version:O(nt),icon:O(I()),caption:O(nt),fdc3:O(x())}),Wt=k({name:nt,type:nt.where(e=>"window"===e,"Expected a value of window"),userProperties:x(),title:O(nt),version:O(nt),icon:O(I()),caption:O(nt),fdc3:O(x())}),Ht=k({appsAdded:P(Wt),appsChanged:P(Wt),appsRemoved:P(Wt)}),Ut=k({apps:P($t),initialChannelId:O(nt)}),qt=k({id:nt}),Bt=R(T("Global"),T("Activity"),T("ApplicationDefault"),T("Swimlane"),T("Workspace")),Gt=R(T("application"),T("activity")),Jt=k({context:O(x()),bounds:pt,createArgs:k({name:O(nt),url:O(st),context:O(x())}),windowState:O(nt),restoreState:O(nt),instanceId:nt,isCollapsed:O(_()),isSticky:O(_()),restoreSettings:k({groupId:O(nt),groupZOrder:O(S())}),channelId:O(nt)}),zt=k({type:T("window"),componentType:O(Gt),application:nt,state:Jt}),Vt=k({type:T("window"),config:k({appName:nt,url:O(st),title:O(I()),allowExtract:O(_()),allowReorder:O(_()),showCloseButton:O(_()),isMaximized:O(_()),instanceId:O(nt)})}),Kt=k({type:T("group"),config:x(),children:P(R(Vt))}),Zt=k({type:T("column"),config:x(),children:P(R(Kt,Vt,E(()=>Zt),E(()=>Qt)))}),Qt=k({type:T("row"),config:x(),children:P(R(Zt,Kt,Vt,E(()=>Qt)))}),Yt=k({config:x(),context:x(),children:P(R(Qt,Zt,Kt,Vt))}),Xt=k({type:T("Workspace"),application:O(nt),state:Yt}),en=k({bounds:pt,instanceId:nt,selectedWorkspace:it,workspaces:P(Yt),windowState:O(nt),restoreState:O(nt),context:O(x())}),tn=k({type:T("workspaceFrame"),application:nt,componentType:O(Gt),state:en}),nn=k({name:nt,type:Bt,token:O(nt),components:P(R(zt,Xt,tn)),context:O(x()),metadata:O(x()),version:O(S())}),rn=k({name:nt,type:Bt,token:O(nt),components:P(R(zt,Xt,tn)),context:O(x()),metadata:O(x()),version:O(S()),prevName:nt}),sn=k({name:nt,context:O(x()),metadata:O(x()),instances:O(P(nt)),ignoreInstances:O(P(nt)),setAsCurrent:O(_()),ignoreContexts:O(_()),saveWindowContexts:O(_())}),on=k({name:nt,context:O(x()),closeRunningInstance:O(_()),closeMe:O(_()),timeout:O(it)}),an=k({name:nt,type:Bt,context:O(x()),metadata:O(x())}),cn=k({name:nt,type:Bt}),dn=k({layout:sn}),ln=k({layout:nn,newName:nt}),hn=k({status:nt}),un=k({layout:nn}),pn=k({layout:on}),gn=k({type:Bt}),fn=k({layouts:P(nn)}),mn=O(k({name:nt})),bn=R(T("replace"),T("merge")),yn=k({layouts:P(nn),mode:bn,skipManagerRequest:O(_())}),wn=k({summaries:P(an)}),vn=k({layout:nn}),Cn=k({layout:O(nn)}),In=k({name:nt}),Sn=R(T("findIntent"),T("getIntents"),T("getIntentsByHandler"),T("raise"),T("filterHandlers")),_n=k({applicationName:nt,applicationTitle:O(I()),applicationDescription:O(I()),applicationIcon:O(I()),type:R(T("app"),T("instance")),displayName:O(I()),contextTypes:O(P(nt)),instanceId:O(I()),instanceTitle:O(I()),resultType:O(I()),customConfig:O(k())});k({applicationName:I(),applicationIcon:O(I()),instanceId:O(I())}),k({intent:nt,handler:_n});const xn=k({name:nt,handlers:P(_n)}),Tn=R(T("startNew"),T("reuse"),k({app:O(nt),instance:O(nt)})),kn=k({type:O(nt),data:O(x())}),Pn=P(xn),On=k({intents:Pn}),Rn=k({name:O(nt),contextType:O(nt),resultType:O(nt)}),An=R(nt,Rn),Mn=k({filter:O(Rn)}),En=k({top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),waitForAGMReady:O(_()),channelId:O(nt)}),Dn=k({intent:nt,target:O(Tn),context:O(kn),options:O(En),handlers:O(P(_n)),timeout:O(it),waitUserResponseIndefinitely:O(_()),clearSavedHandler:O(_())}),jn=k({interopInstance:nt,name:O(nt)}),Nn=k({originApp:jn,intentRequest:O(Dn)}),Fn=k({name:nt,waitForAGMReady:_(),id:O(nt),context:O(x()),top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),forceChromeTab:O(_()),layoutComponentId:O(nt),channelId:O(nt),startReason:Nn}),Ln=R(nt,Dn),$n=k({enabled:_(),appName:nt,waitResponseTimeout:S()}),Wn=R(k({applicationName:nt}),k({instanceId:nt})),Hn=k({title:O(nt),openResolver:O(_()),timeout:O(it),intent:O(nt),contextTypes:O(P(nt)),resultType:O(nt),applicationNames:O(P(nt)),excludeList:O(P(Wn))}),Un=k({enabled:_(),initialCaller:k({instanceId:nt})}),qn=k({intentRequest:Dn,resolverConfig:$n,embeddedResolverConfig:O(Un)}),Bn=k({request:Dn,handler:_n,result:x()}),Gn=k({handlers:P(_n)}),Jn=k({filterHandlersRequest:Hn,resolverConfig:$n,embeddedResolverConfig:O(Un)}),zn=k({intent:nt,contextTypes:O(P(nt)),displayName:O(I()),icon:O(I()),description:O(I()),resultType:O(I()),customConfig:O(k())}),Vn=R(nt,zn),Kn=k({intent:nt,contextTypes:O(P(nt)),description:O(nt),displayName:O(nt),icon:O(nt),resultType:O(nt)}),Zn=k({intents:P(Kn)}),Qn=e=>nt.where(t=>e.includes(t),"Expected a valid channel name"),Yn=k({contextType:O(nt)}),Xn=O(R(nt,k({name:O(nt),fdc3:O(_())}))),ei=k({windowId:rt,channel:rt}),ti=x().where(e=>"string"==typeof e.type,"Expected a valid FDC3 Context with compulsory 'type' field"),ni=k({method:nt,arguments:O(x()),target:O(R(T("all"),T("best")))}),ii=k({action:I(),title:nt,icon:O(I()),interop:O(ni)}),ri=R(T("Active"),T("Acknowledged"),T("Seen"),T("Closed"),T("Stale"),T("Snoozed"),T("Processing")),si=k({count:S()}),oi=k({badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(P(S()))}),ai=k({title:nt,clickInterop:O(ni),actions:O(P(ii)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(P(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ri)}),ci=k({id:nt,state:ri});k().where(e=>!e.fdc3||"string"==typeof e.fdc3.type,"Expected a valid FDC3 Context with compulsory 'type' field");const di=k({color:O(nt),icon:O(nt),name:O(nt),glyph:O(nt)}),li=k({id:nt,displayMetadata:O(di)}),hi=k({color:nt,fdc3:O(li)}),ui=k({name:nt,meta:hi,data:O(k())}),pi=k({path:nt,value:x()}),gi=P(pi),fi=k({name:nt}),mi=k({name:nt,read:_(),write:_(),windowId:O(nt)}),bi=k({name:nt,read:_(),write:_(),windowId:nt}),yi=k({config:bi}),wi=k({channels:P(mi)}),vi=k({windowId:nt}),Ci=k({read:_(),write:_(),windowId:O(nt)}),Ii=k({restrictions:Ci}),Si=k({settings:ai,id:nt}),_i=k({settings:ai}),xi=k({permissionGranted:_()}),Ti=k({permission:R(T("default"),T("granted"),T("denied"))}),ki=k({definition:oi,action:O(I()),id:O(nt)}),Pi=k({allowed:O(P(nt)),blocked:O(P(nt))}),Oi=k({enable:O(_()),enableToasts:O(_()),sourceFilter:O(Pi),showNotificationBadge:O(_())}),Ri=k({configuration:Oi}),Ai=k({configuration:k({enable:_(),enableToasts:_(),sourceFilter:k({allowed:P(nt),blocked:P(nt)})})}),Mi=k({layoutType:R(T("Global"),T("Workspace")),layoutName:nt,context:O(x())}),Ei=k({windowContext:O(x())}),Di=k({state:R(T("prompt"),T("denied"),T("granted"))}),ji=k({isAvailable:_()}),Ni=k({itemId:nt}),Fi=k({isSupported:_()}),Li=k({operation:nt}),$i=k({bounds:pt}),Wi=k({displayName:nt,name:nt}),Hi=k({theme:Wi}),Ui=k({themes:P(Wi)}),qi=k({name:nt}),Bi=k({id:nt,title:nt,clickInterop:O(ni),actions:O(P(ii)),focusPlatformOnDefaultClick:O(_()),badge:O(I()),body:O(I()),data:O(x()),dir:O(R(T("auto"),T("ltr"),T("rtl"))),icon:O(I()),image:O(I()),lang:O(I()),renotify:O(_()),requireInteraction:O(_()),silent:O(_()),tag:O(I()),timestamp:O(it),vibrate:O(P(S())),severity:O(R(T("Low"),T("None"),T("Medium"),T("High"),T("Critical"))),showToast:O(_()),showInPanel:O(_()),state:O(ri)}),Gi=k({notification:Bi}),Ji=k({notifications:P(Bi)}),zi=k({id:nt}),Vi=k({channel:nt}),Ki=k({windowIds:P(nt)}),Zi=R(T("appHello"),T("addChannel"),T("getMyChannel"),T("getWindowIdsOnChannel"),T("getWindowIdsWithChannels"),T("joinChannel"),T("restrict"),T("getRestrictions"),T("restrictAll"),T("notifyChannelsChanged"),T("leaveChannel"),T("getMode"),T("operationCheck")),Qi=R(T("single"),T("multi")),Yi=k({mode:Qi}),Xi=k({windowId:nt}),er=k({mode:Qi,channels:P(nt),restrictions:P(mi)}),tr=k({channel:O(nt)}),nr=k({application:O(nt),channels:O(P(nt)),windowIds:O(P(nt))}),ir=k({filter:O(nr)}),rr=k({windowIdsWithChannels:P(k({application:nt,channel:O(nt),windowId:nt}))}),sr=O(x()),or=O(k({top:O(S()),left:O(S()),width:O(it),height:O(it),relativeTo:O(nt),relativeDirection:O(ut),waitForAGMReady:O(_()),channelId:O(nt),reuseId:O(nt),originIntentRequest:O(Dn)})),ar=k({channel:nt,windowId:nt}),cr=k({windowId:nt,channelName:O(nt)}),dr=k({windowId:nt,channelNames:P(nt)}),lr=k({channel:O(nt)}),hr=R(T("clear"),T("clearAll"),T("get"),T("getAll"),T("set"),T("update"),T("prefsChanged"),T("prefsHello"),T("operationCheck"),T("registerSubscriber")),ur=k({app:nt,data:k(),lastUpdate:O(nt)}),pr=k({app:nt}),gr=k({prefs:ur}),fr=k({all:P(ur)}),mr=k({interopId:nt,appName:O(nt)}),br=k({app:nt,data:k()}),yr=k({platform:k({app:nt}),validNonExistentApps:O(P(nt)),isAppValidationEnabled:O(_())}),wr=k({message:nt}),vr=k({isClientErrorOperationSupported:_()}),Cr=tt.common.nonEmptyStringDecoder,Ir=tt.common.nonNegativeNumberDecoder,Sr=k({bundle:Cr,styles:P(Cr),fonts:O(P(Cr))}),_r=k({bundle:Cr,styles:P(Cr),fonts:O(P(Cr))}),xr=k({bundle:Cr,styles:P(Cr),fonts:O(P(Cr))}),Tr=R(T("directional"),T("default")),kr=k({type:O(Tr),enable:O(_())}),Pr=R(T("top-left"),T("top-center"),T("top-right"),T("center-left"),T("center-right"),T("bottom-left"),T("bottom-center"),T("bottom-right")),Or=R(T("all"),T("fdc3")),Rr=k({selector:O(kr),displayMode:O(Or)}),Ar=k({channels:O(Rr),position:O(Pr),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),Mr=k({enable:_(),awaitFactory:O(_()),timeout:O(Ir),channels:O(Rr),position:O(Pr),displayInWorkspace:O(_()),restoreLastKnownPosition:O(_())}),Er=k({alerts:O(k({enabled:_()})),dialogs:O(k({enabled:_()})),awaitFactory:O(_()),timeout:O(Ir)}),Dr=R(T("getResources"),T("operationCheck"),T("showAlert"),T("showDialog"),T("alertInteropAction"),T("showResolver")),jr=k({origin:Cr}),Nr=k({blockedOrigin:T(!0)}),Fr=A(Nr,k({blockedOrigin:T(!1),config:Ar,sources:Sr})),Lr=A(Nr,k({blockedOrigin:T(!1),sources:_r})),$r=A(Nr,k({blockedOrigin:T(!1),sources:xr})),Wr=k({widget:O(Fr),modals:O(Lr),intentResolver:O($r)}),Hr=k({resources:Wr}),Ur=k({method:Cr,arguments:O(x()),target:O(R(T("best"),T("all"),Cr))}),qr=R(T("Global"),T("WindowContainer"),Cr),Br=k({instance:Cr,container:O(R(T("Global"),T("WindowContainer")))}),Gr=k({variant:R(T("default"),T("success"),T("critical"),T("info"),T("warning")),text:Cr,showCloseButton:O(_()),clickInterop:O(Ur),onCloseInterop:O(Ur),actions:O(P(k({id:Cr,title:Cr,clickInterop:Ur}))),data:O(x()),ttl:O(Ir),target:O(qr)}),Jr=k({config:Gr,target:Br}),zr=k({templateName:Cr,variables:x(),target:O(qr),timer:O(k({duration:Ir})),size:O(k({width:Ir,height:Ir})),movable:O(_()),transparent:O(_())}),Vr=k({isExpired:O(_()),isClosed:O(_()),isEnterPressed:O(_()),responseButtonClicked:O(k({id:Cr,text:Cr})),inputs:O(P(k({type:R(T("checkbox"),T("email"),T("number"),T("password"),T("text")),id:Cr,checked:O(_()),value:O(I())})))});k({result:Vr});const Kr=k({config:zr,target:Br}),Zr=k({id:Cr}),Qr=k({id:Cr,responsePromise:x()}),Yr=k({response:Vr}),Xr=k({name:Cr,settings:Ur}),es=k({interopAction:Xr}),ts=k({interopAction:Xr}),ns=k({enable:_(),awaitFactory:O(_()),timeout:O(Ir)}),is=k({id:Cr}),rs=k({preserveChoice:_()}),ss=k({intent:Cr,handler:_n,userSettings:rs}),os=k({isExpired:O(_()),isClosed:O(_()),userChoice:O(ss)}),as=k({response:os}),cs=M(A(k({intentRequest:Dn}),k({handlerFilter:Hn})),k({timeout:Ir})),ds=k({config:cs}),ls=k({result:os}),hs={openWindow:{name:"openWindow",dataDecoder:ft,resultDecoder:bt},windowHello:{name:"windowHello",dataDecoder:mt,resultDecoder:wt},windowAdded:{name:"windowAdded",dataDecoder:bt},windowRemoved:{name:"windowRemoved",dataDecoder:yt},getBounds:{name:"getBounds",dataDecoder:yt,resultDecoder:St},getFrameBounds:{name:"getFrameBounds",dataDecoder:yt,resultDecoder:_t},getUrl:{name:"getUrl",dataDecoder:yt,resultDecoder:xt},moveResize:{name:"moveResize",dataDecoder:It},focus:{name:"focus",dataDecoder:yt},close:{name:"close",dataDecoder:yt},getTitle:{name:"getTitle",dataDecoder:yt,resultDecoder:vt},setTitle:{name:"setTitle",dataDecoder:vt},focusChange:{name:"focusChange",dataDecoder:Ct},getChannel:{name:"getChannel",dataDecoder:yt,resultDecoder:lr},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:dr},setZoomFactor:{name:"setZoomFactor",dataDecoder:Tt},zoomFactorChange:{name:"zoomFactorChange",dataDecoder:Tt},refresh:{name:"refresh",dataDecoder:yt},operationCheck:{name:"operationCheck"}};function us(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 s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.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 s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}us.default=us;var ps=e(us);const gs=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class fs{_id;_name;_bridge;_logger;registry=ps();myCtxKey;ctxUnsubscribe;zoomFactorIndex=7;me;constructor(e,t,n,i){this._id=e,this._name=t,this._bridge=n,this._logger=i,this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}get zoomFactor(){return gs[this.zoomFactorIndex]}clean(){this.ctxUnsubscribe&&this.ctxUnsubscribe()}processSelfFocusEvent(e){this.me.isFocused=e,this.registry.execute("focus-change",this.me)}processChannelsChangedEvent(e){this.registry.execute("channels-changed",e)}processSelfZoomFactorChangedEvent(e){this.zoomFactorIndex=e,this.registry.execute("zoom-factor-changed",this.me)}async toApi(){return this.ctxUnsubscribe=await this._bridge.contextLib.subscribe(this.myCtxKey,e=>this.registry.execute("context-updated",e)),this.me={id:this.id,name:this.name,isFocused:!1,zoomFactor:this.zoomFactor,getURL:this.getURL.bind(this),moveResize:this.moveResize.bind(this),resizeTo:this.resizeTo.bind(this),moveTo:this.moveTo.bind(this),focus:this.focus.bind(this),close:this.close.bind(this),getTitle:this.getTitle.bind(this),setTitle:this.setTitle.bind(this),getBounds:this.getBounds.bind(this),getContext:this.getContext.bind(this),updateContext:this.updateContext.bind(this),setContext:this.setContext.bind(this),refresh:this.refresh.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),zoomIn:this.zoomIn.bind(this),zoomOut:this.zoomOut.bind(this),setZoomFactor:this.setZoomFactor.bind(this),onZoomFactorChanged:this.onZoomFactorChanged.bind(this)},Object.defineProperties(this.me,{id:Q,name:Q,zoomFactor:{get:()=>this.zoomFactor,enumerable:!0}}),this.me}async getURL(){return(await this._bridge.send("windows",hs.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"):this.registry.add("focus-change",e)}async moveResize(e){const t=X(Pt,e),n=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",hs.moveResize,n),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(it,e),void 0!==t&&X(it,t);const n=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",hs.moveResize,n),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&X(S(),e),void 0!==t&&X(S(),t);const n=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",hs.moveResize,n),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",hs.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",hs.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",hs.getTitle,{windowId:this.id})).title}async setTitle(e){const t=X(nt,e);return await this._bridge.send("windows",hs.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",hs.getBounds,{windowId:this.id})).bounds}async getContext(){const e=await this._bridge.contextLib.get(this.myCtxKey),{___io___:t,...n}=e;return n}async updateContext(e){const t=X(kt,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=X(kt,e),n=await this._bridge.contextLib.get(this.myCtxKey),i=n.___io___?{...t,___io___:n.___io___}:t;return await this._bridge.contextLib.set(this.myCtxKey,i),this.me}onContextUpdated(e){if("function"!=typeof e)return re.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",t=>{const{___io___:n,...i}=t;e(i,this.me)})}async getChannel(){return(await this._bridge.send("windows",hs.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}getClosestZoomFactorIndex(e){const t=Object.entries(gs).reduce((t,[n,i])=>Math.abs(i-e)<=Math.abs(gs[t]-e)?parseInt(n):t,0),n=gs[t];return n!==e&&this._logger.warn(`Zoom factor ${e} is not available, using closest value ${n} instead.`),t}async zoom(e){e!==this.zoomFactorIndex&&e in gs&&(await this._bridge.send("windows",hs.setZoomFactor,{windowId:this.id,factorIndex:e},void 0,{includeOperationCheck:!0}),this.zoomFactorIndex=e)}async zoomIn(){return await this.zoom(this.zoomFactorIndex+1),this.me}async zoomOut(){return await this.zoom(this.zoomFactorIndex-1),this.me}async setZoomFactor(e){const t=X(S(),e),n=this.getClosestZoomFactorIndex(t);return await this.zoom(n),this.me}onZoomFactorChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"):this.registry.add("zoom-factor-changed",e)}async refresh(){return await this._bridge.send("windows",hs.refresh,{windowId:this.id},void 0,{includeOperationCheck:!0}),this.me}}const ms={operationCheck:{name:"operationCheck",dataDecoder:Li,resultDecoder:Fi},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:$i,dataDecoder:Ni}},bs=(e,t,n)=>new Promise((i,r)=>{let s=!0;const o=setTimeout(()=>{if(!s)return;s=!1;r(n||`Promise timeout hit: ${t}`)},t);e().then(e=>{s&&(s=!1,clearTimeout(o),i(e))}).catch(e=>{s&&(s=!1,clearTimeout(o),r(e))})}),ys=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class ws{supportedOperationsNames=[];focusEventHandler;registry=ps();platformRegistration;ioc;bridge;publicWindowId;allWindowProjections=[];me;logger;isWorkspaceFrame;instanceId;channelsController;async start(e,t){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=t.publicWindowId,this.addWindowOperationExecutors(),this.ioc=t,this.bridge=t.bridge,this.instanceId=e.interop.instance.instance,this.channelsController=t.channelsController,this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`),this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,await this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const n=this.toApi();e.windows=n}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}async handleBridgeMessage(e){await this.platformRegistration;const t=X(at,e.operation),n=hs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async open(e,t,n){X(nt,e),X(st,t);const i=X(gt,n),r=await this.bridge.send("windows",hs.openWindow,{name:e,url:t,options:i});return this.waitForWindowAdded(r.windowId)}list(){return this.allWindowProjections.map(e=>e.api)}findById(e){return X(nt,e),this.allWindowProjections.find(t=>t.id===e)?.api}toApi(){return{open:this.open.bind(this),my:this.my.bind(this),list:this.list.bind(this),findById:this.findById.bind(this),onWindowAdded:this.onWindowAdded.bind(this),onWindowRemoved:this.onWindowRemoved.bind(this),onWindowGotFocus:this.onWindowGotFocus.bind(this),onWindowLostFocus:this.onWindowLostFocus.bind(this)}}addWindowOperationExecutors(){hs.focusChange.execute=this.handleFocusChangeEvent.bind(this),hs.windowAdded.execute=this.handleWindowAdded.bind(this),hs.windowRemoved.execute=this.handleWindowRemoved.bind(this),hs.getBounds.execute=this.handleGetBounds.bind(this),hs.getFrameBounds.execute=this.handleGetBounds.bind(this),hs.getTitle.execute=this.handleGetTitle.bind(this),hs.getUrl.execute=this.handleGetUrl.bind(this),hs.moveResize.execute=this.handleMoveResize.bind(this),hs.setTitle.execute=this.handleSetTitle.bind(this),hs.getChannel.execute=this.handleGetChannel.bind(this),hs.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this),hs.setZoomFactor.execute=this.handleSetZoomFactor.bind(this),hs.zoomFactorChange.execute=this.handleZoomFactorChanged.bind(this),hs.refresh.execute=this.handleRefresh.bind(this),hs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(hs)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"):this.registry.add("window-added",e)}onWindowRemoved(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"):this.registry.add("window-removed",e)}onWindowGotFocus(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"):this.registry.add("window-got-focus",e)}onWindowLostFocus(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"):this.registry.add("window-lost-focus",e)}async sayHello(){return await this.bridge.send("windows",hs.windowHello,{windowId:this.publicWindowId})}async registerWithPlatform(){const{windows:e,isWorkspaceFrame:t}=await this.sayHello();if(this.isWorkspaceFrame=t,this.logger.trace("the platform responded to the hello message"),!this.isWorkspaceFrame&&this.publicWindowId){this.logger.trace("i am not treated as a workspace frame, setting my window");const t=e.find(e=>e.windowId===this.publicWindowId);if(!t){const t=e.map(e=>`${e.windowId}:${e.name}`).join(", ");return re.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${t}`)}const n=await this.ioc.buildWebWindow(this.publicWindowId,t.name,this.logger);this.me=n.api,this.allWindowProjections.push(n)}const n=await Promise.all(e.filter(e=>e.windowId!==this.publicWindowId).map(e=>this.ioc.buildWebWindow(e.windowId,e.name,this.logger)));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...n)}async handleFocusChangeEvent(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);if(!t)return;t.model.processSelfFocusEvent(e.hasFocus);const n=e.hasFocus?"window-got-focus":"window-lost-focus";this.registry.execute(n,t.api)}async handleWindowAdded(e){if(this.allWindowProjections.some(t=>t.id===e.windowId))return;const t=await this.ioc.buildWebWindow(e.windowId,e.name,this.logger);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}async handleWindowRemoved(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&(this.allWindowProjections=this.allWindowProjections.filter(t=>t.id!==e.windowId),t.model.clean(),this.registry.execute("window-removed",t.api))}async handleGetBounds(){return this.me||this.isWorkspaceFrame?{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}:re.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe")}async handleGetTitle(){return this.me?{windowId:this.me.id,title:document.title}:re.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe")}async handleGetUrl(){return this.me?{windowId:this.me.id,url:window.location.href}:re.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe")}async handleMoveResize(e){const t="number"==typeof e.top?e.top:e.relative?0:window.screenTop,n="number"==typeof e.left?e.left:e.relative?0:window.screenLeft,i="number"==typeof e.height?e.height:e.relative?0:window.innerHeight,r="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,s=e.relative?window.moveBy:window.moveTo,o=e.relative?window.resizeBy:window.resizeTo;s(n,t),o(r,i)}async handleSetTitle(e){document.title=e.title}async initializeFocusTracking(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{await this.bridge.send("windows",ms.operationCheck,{operation:"focusChange"})}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client.")}const e=document.hasFocus();await this.transmitFocusChange(!0),e||await this.transmitFocusChange(!1),this.defineEventListeners()}processFocusEvent(){const e=document.hasFocus();this.transmitFocusChange(e)}waitForWindowAdded(e){const t=this.allWindowProjections.find(t=>t.id===e);return t?Promise.resolve(t.api):ys(t=>{const n=this.onWindowAdded(i=>{i.id===e&&(n(),t(i))})},3e4,`Timed out waiting for ${e} to be announced`)}async transmitFocusChange(e){const t={windowId:this.me?.id||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),await this.bridge.send("windows",hs.focusChange,t)}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}async handleGetChannel(){if(!this.me)return re.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleRefresh(){if(!this.me)return re.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe");setTimeout(()=>{window.location.reload()},0)}async handleChannelsChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t?.model.processChannelsChangedEvent(e.channelNames)}async handleSetZoomFactor(e){if(!this.me)return re.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe");document.body.style.zoom=`${gs[e.factorIndex]}%`}async handleZoomFactorChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&t.model.processSelfZoomFactorChangedEvent(e.factorIndex)}}const vs="T42.Web.Platform.Control",Cs="T42.Web.Platform.Stream",Is="T42.Web.Client.Control",Ss="T42.Core.Plus.Themes.Stream";class _s{coreGlue;communicationId;platformMethodTimeoutMs=1e4;controllers;sub;running;constructor(e,t){this.coreGlue=e,this.communicationId=t}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}async stop(){this.running=!1,this.sub.close(),await this.coreGlue.interop.unregister(Is)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(vs),this.checkWaitMethod(Cs)]);const t=this.communicationId,[n]=await Promise.all([this.coreGlue.interop.subscribe(Cs,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(Is,(e,t,n,i)=>this.passMessageController(e,n,i))]);this.sub=n,this.sub.onData(e=>this.passMessageController(e.data))}getInteropInstance(e){const t=this.coreGlue.interop.servers().find(t=>t.windowId&&t.windowId===e);return{application:t?.application,applicationName:t?.applicationName,peerId:t?.peerId,instance:t?.instance,windowId:t?.windowId}}async send(e,t,n,i,r){if(t.dataDecoder)try{t.dataDecoder.runWithException(n)}catch(e){return re.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!r?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return re.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const r=await this.transmitMessage(e,t,n,i);return t.resultDecoder&&t.resultDecoder.runWithException(r),r}catch(e){return e?.kind?re.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):re.raiseError(e)}}async createThemesSubscription(){return this.coreGlue.interop.methods().some(e=>e.name===Ss)?this.coreGlue.interop.subscribe(Ss,this.communicationId?{target:{instance:this.communicationId}}:void 0):re.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.")}async checkOperationSupported(e,t){try{return await this.send(e,ms.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return ys(t=>{if(this.coreGlue.interop.methods().some(t=>{const n=t.name===e,i=!this.communicationId||t.getServers().some(e=>e.instance===this.communicationId);return n&&i}))return t();const n=this.coreGlue.interop.serverMethodAdded(i=>{const r=i.method,s=i.server,o=!this.communicationId||s.instance===this.communicationId;r.name===e&&o&&(n(),t())})},this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,n){const i=ot.run(e.domain);if(!i.ok)return void(n&&n(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(i.error)}`));const r=i.result;this.controllers[r].handleBridgeMessage(e).then(e=>{t&&t(e)}).catch(e=>{n&&n(e),console.warn(e)})}async transmitMessage(e,t,n,i){const r={domain:e,data:n,operation:t.name};let s;const o=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(t.name)} with data: ${JSON.stringify(n)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(s=await this.coreGlue.interop.invoke(vs,r,a?{instance:this.communicationId}:void 0,i),!s)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(s.all_return_values)||0===s.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;throw new Error(`${o} -> Inner message: ${t}`)}throw new Error(`${o} -> Inner message: ${e.message}`)}return s.all_return_values[0].returned}}const xs={appHello:{name:"appHello",dataDecoder:mt,resultDecoder:Ut},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:Ht},instanceStarted:{name:"instanceStarted",dataDecoder:Ot},instanceStopped:{name:"instanceStopped",dataDecoder:Ot},applicationStart:{name:"applicationStart",dataDecoder:Fn,resultDecoder:Ot},instanceStop:{name:"instanceStop",dataDecoder:qt},import:{name:"import"},remove:{name:"remove",dataDecoder:Ft},export:{name:"export",resultDecoder:Lt},clear:{name:"clear"},operationCheck:{name:"operationCheck"}};class Ts{me;supportedOperationsNames=[];baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=ps();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;interop;initialChannelId;handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}async start(e,t){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=t.publicWindowId,this.addOperationsExecutors(),this.ioc=t,this.bridge=t.bridge,this.channelsController=t.channelsController,this.interop=e.interop,this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const n=this.toApi();e.appManager=n}async postStart(){this.initialChannelId&&await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId)}async handleBridgeMessage(e){await this.platformRegistration;const t=X(ct,e.operation),n=xs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}onInstanceStarted(e){return"function"!=typeof e?re.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?re.raiseError("onInstanceStopped requires a single argument of type function"):this.registry.add("instance-stopped",e)}async startApplication(e,t,n){const i=await this.channelsController.all();if(n?.channelId&&!i.includes(n.channelId))return re.raiseError(`The channel with name "${n.channelId}" doesn't exist!`);const r={name:e,waitForAGMReady:n?.waitForAGMReady??!0,context:t,top:n?.top,left:n?.left,width:n?.width,height:n?.height,relativeTo:n?.relativeTo,relativeDirection:n?.relativeDirection,id:n?.reuseId,forceChromeTab:n?.forceTab,layoutComponentId:n?.layoutComponentId,channelId:n?.channelId,startReason:{originApp:{name:this.me?.application.name,interopInstance:this.interop.instance.instance}}};n?.originIntentRequest&&(r.startReason.intentRequest=n.originIntentRequest);const s=await this.bridge.send("appManager",xs.applicationStart,r),o=this.applications.find(e=>e.name===s.applicationName);return this.ioc.buildInstance(s,o)}getApplication(e){const t=X(nt,e);return this.applications.find(e=>e.name===t)}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?re.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?re.raiseError("onAppRemoved requires a single argument of type function"):this.registry.add("application-removed",e)}toApi(){return{myInstance:this.me,inMemory:{import:this.importApps.bind(this),remove:this.remove.bind(this),export:this.exportApps.bind(this),clear:this.clear.bind(this)},application:this.getApplication.bind(this),applications:this.getApplications.bind(this),instances:this.getInstances.bind(this),onAppAdded:this.onAppAdded.bind(this),onAppChanged:this.onAppChanged.bind(this),onAppRemoved:this.onAppRemoved.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)}}addOperationsExecutors(){xs.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),xs.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),xs.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this),xs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(xs)}async handleAppDirectoryStateChange(e){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}onAppChanged(e){return"function"!=typeof e?re.raiseError("onAppChanged requires a single argument of type function"):this.registry.add("application-changed",e)}async handleApplicationAddedMessage(e){if(this.applications.some(t=>t.name===e.name))return;const t=await this.ioc.buildApplication(e,[]),n=this.instances.filter(e=>e.application.name===t.name);t.instances.push(...n),this.applications.push(t),this.registry.execute("application-added",t)}async handleApplicationRemovedMessage(e){const t=this.applications.findIndex(t=>t.name===e.name);if(t<0)return;const n=this.applications[t];this.applications.splice(t,1),this.registry.execute("application-removed",n)}async handleApplicationChangedMessage(e){const t=this.applications.find(t=>t.name===e.name);if(!t)return this.handleApplicationAddedMessage(e);t.title=e.title,t.version=e.version,t.icon=e.icon,t.caption=e.caption,t.userProperties=e.userProperties,this.registry.execute("application-changed",t)}async handleInstanceStartedMessage(e){if(this.instances.some(t=>t.id===e.id))return;const t=this.applications.find(t=>t.name===e.applicationName);if(!t)return re.raiseError(`Cannot add instance: ${e.id}, because there is no application definition associated with it`);const n=this.ioc.buildInstance(e,t);this.instances.push(n),t.instances.push(n),this.registry.execute("instance-started",n)}async handleInstanceStoppedMessage(e){const t=this.instances.find(t=>t.id===e.id);if(t){const t=this.instances.findIndex(t=>t.id===e.id);this.instances.splice(t,1)}const n=this.applications.find(t=>t.instances.some(t=>t.id===e.id));if(n){const t=n.instances.findIndex(t=>t.id===e.id);n.instances.splice(t,1)}t&&this.registry.execute("instance-stopped",t)}async importApps(e,t="replace"){if(X(bn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return re.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const n=e.reduce((e,t)=>{const{isValid:n,error:i}=this.isValidDefinition(t);return n?e.valid.push(t):e.invalid.push({app:t?.name,error:i??`Provided definition is invalid ${JSON.stringify(t)}`}),e},{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*n.valid.length;return await this.bridge.send("appManager",xs.import,{definitions:n.valid,mode:t},{methodResponseTimeoutMs:i}),{imported:n.valid.map(e=>e.name),errors:n.invalid}}isValidDefinition(e){if(e?.appId&&e?.details){const t=tt.fdc3.v2DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v2 definition. Error: ${JSON.stringify(t.error)}`}}if(e?.appId&&e?.manifest){const t=tt.fdc3.v1DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v1 definition. Error: ${JSON.stringify(t.error)}`}}const t=Nt.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid definition. Error: ${JSON.stringify(t.error)}`}}async remove(e){X(nt,e),await this.bridge.send("appManager",xs.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",xs.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",xs.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async registerWithPlatform(){const e=await this.bridge.send("appManager",xs.appHello,{windowId:this.publicWindowId},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS});this.logger.trace("the platform responded to the hello message with a full list of apps"),this.applications=await Promise.all(e.apps.map(e=>this.ioc.buildApplication(e,e.instances))),this.instances=this.applications.reduce((e,t)=>(e.push(...t.instances),e),[]),this.me=this.findMyInstance(),this.logger.trace(`all applications were parsed and saved. I am ${this.me?"NOT a":"a"} valid instance`),this.initialChannelId=e.initialChannelId}findMyInstance(){for(const e of this.applications){const t=e.instances.find(e=>e.id===this.publicWindowId);if(t)return t}}}class ks{data;bridge;application;me;myCtxKey;constructor(e,t,n){this.data=e,this.bridge=t,this.application=n,this.myCtxKey=`___instance___${this.data.id}`}toApi(){const e=this.bridge.getInteropInstance(this.data.id),t={id:this.data.id,agm:e,application:this.application,stop:this.stop.bind(this),getContext:this.getContext.bind(this)};return this.me=Object.freeze(t),this.me}async getContext(){return this.bridge.contextLib.get(this.myCtxKey)}async stop(){await this.bridge.send("appManager",xs.instanceStop,{id:this.data.id})}}class Ps{data;instances;controller;me;constructor(e,t,n){this.data=e,this.instances=t,this.controller=n}toApi(){const e={name:this.data.name,title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,userProperties:this.data.userProperties,instances:this.instances,start:this.start.bind(this),getConfiguration:this.getConfiguration.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?re.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStarted(t=>{t.application.name===this.data.name&&e(t)})}onInstanceStopped(e){return"function"!=typeof e?re.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStopped(t=>{t.application.name===this.data.name&&e(t)})}async start(e,t){const n=X(sr,e),i=X(or,t);return this.controller.startApplication(this.data.name,n,i)}async getConfiguration(){const{details:e,intents:t,hidden:n,...i}=this.data.userProperties,r={name:this.data.name,type:this.data.type,details:e,customProperties:i},s={title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,intents:t,hidden:n,fdc3:this.data.fdc3};for(const[e,t]of Object.entries(s))void 0!==t&&(r[e]=t);return r}}const Os={layoutAdded:{name:"layoutAdded",dataDecoder:nn},layoutChanged:{name:"layoutChanged",dataDecoder:nn},layoutRemoved:{name:"layoutRemoved",dataDecoder:nn},layoutRestored:{name:"layoutRestored",dataDecoder:nn},defaultLayoutChanged:{name:"defaultLayoutChanged",dataDecoder:mn},layoutRenamed:{name:"layoutRenamed",dataDecoder:rn},get:{name:"get",dataDecoder:cn,resultDecoder:Cn},getAll:{name:"getAll",dataDecoder:gn,resultDecoder:wn},export:{name:"export",dataDecoder:gn,resultDecoder:fn},import:{name:"import",dataDecoder:yn},remove:{name:"remove",dataDecoder:cn},rename:{name:"rename",dataDecoder:ln,resultDecoder:hn},save:{name:"save",dataDecoder:dn,resultDecoder:vn},restore:{name:"restore",dataDecoder:pn},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:Mi,resultDecoder:Ei},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:Di},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:ji},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:ji},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:Cn},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:In},clearDefaultGlobal:{name:"clearDefaultGlobal"},getCurrent:{name:"getCurrent",resultDecoder:Cn},updateMetadata:{name:"updateMetadata",dataDecoder:un},operationCheck:{name:"operationCheck"}};class Rs{supportedOperationsNames=[];defaultLayoutRestoreTimeoutMS=12e4;registry=ps();bridge;logger;windowsController;saveRequestSubscription;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=t.bridge,this.windowsController=t.windowsController,this.addOperationsExecutors();const n=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=n}async handleBridgeMessage(e){const t=X(dt,e.operation),n=Os[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),getCurrentLayout:this.getCurrentLayout.bind(this),export:this.exportLayouts.bind(this),import:this.importLayouts.bind(this),save:this.save.bind(this),restore:this.restore.bind(this),remove:this.remove.bind(this),onAdded:this.onAdded.bind(this),onChanged:this.onChanged.bind(this),onRemoved:this.onRemoved.bind(this),onDefaultGlobalChanged:this.onDefaultGlobalChanged.bind(this),onSaveRequested:this.subscribeOnSaveRequested.bind(this),getMultiScreenPermissionState:this.getGlobalPermissionState.bind(this),requestMultiScreenPermission:this.requestGlobalPermission.bind(this),getGlobalTypeState:this.checkGlobalActivated.bind(this),getDefaultGlobal:this.getDefaultGlobal.bind(this),setDefaultGlobal:this.setDefaultGlobal.bind(this),clearDefaultGlobal:this.clearDefaultGlobal.bind(this),rename:this.rename.bind(this),onRenamed:this.onRenamed.bind(this),onRestored:this.onRestored.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){Os.layoutAdded.execute=this.handleOnAdded.bind(this),Os.layoutChanged.execute=this.handleOnChanged.bind(this),Os.layoutRemoved.execute=this.handleOnRemoved.bind(this),Os.layoutRenamed.execute=this.handleOnRenamed.bind(this),Os.layoutRestored.execute=this.handleOnRestored.bind(this),Os.defaultLayoutChanged.execute=this.handleOnDefaultChanged.bind(this),Os.clientSaveRequest.execute=this.handleSaveRequest.bind(this),Os.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Os)}async get(e,t){X(nt,e),X(Bt,t);return(await this.bridge.send("layouts",Os.get,{name:e,type:t})).layout}async getCurrentLayout(){return(await this.bridge.send("layouts",Os.getCurrent,void 0)).layout}async getAll(e){X(Bt,e);return(await this.bridge.send("layouts",Os.getAll,{type:e})).summaries}async exportLayouts(e){X(Bt,e);return(await this.bridge.send("layouts",Os.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(X(bn,t),!Array.isArray(e))return re.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return re.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const n=e.reduce((e,t)=>{const n=nn.run(t);return n.ok?e.valid.push(t):this.logger.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(n.error)}`),e},{valid:[]}),i=e.filter(e=>n.valid.some(t=>t.name===e.name));await this.bridge.send("layouts",Os.import,{layouts:i,mode:t})}async save(e){X(sn,e);return(await this.bridge.send("layouts",Os.save,{layout:e})).layout}async restore(e){X(on,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",Os.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){X(Bt,e),X(nt,t),await this.bridge.send("layouts",Os.remove,{type:e,name:t})}async handleSaveRequest(e){const t={};if(this.saveRequestSubscription)try{const n=this.saveRequestSubscription(e);t.windowContext=n?.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}async getGlobalPermissionState(){return await this.bridge.send("layouts",Os.getGlobalPermissionState,void 0)}async requestGlobalPermission(){const e=(await this.getGlobalPermissionState()).state;if("denied"===e)return{permissionGranted:!1};if("granted"===e)return{permissionGranted:!0};const t=this.windowsController.my(),n=(window.glue42core||window.iobrowser).isPlatformFrame;if("Platform"!==t.name&&!n)return re.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",Os.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",Os.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",Os.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){X(nt,e),await this.bridge.send("layouts",Os.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",Os.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){X(nn,e),X(nt,t);return await this.bridge.send("layouts",Os.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){X(nn,e),await this.bridge.send("layouts",Os.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"):(this.exportLayouts("Global").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.exportLayouts("Workspace").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.registry.add(Os.layoutAdded.name,e))}onChanged(e){return this.registry.add(Os.layoutChanged.name,e)}onDefaultGlobalChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"):(this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.registry.add(Os.defaultLayoutChanged.name,e))}onRemoved(e){return this.registry.add(Os.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(Os.layoutRenamed.name,e)}onRestored(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"):this.registry.add(Os.layoutRestored.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?re.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."):(this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription})}async handleOnAdded(e){this.registry.execute(Os.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(Os.layoutChanged.name,e)}async handleOnDefaultChanged(e){this.registry.execute(Os.defaultLayoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(Os.layoutRemoved.name,e)}async handleOnRestored(e){this.registry.execute(Os.layoutRestored.name,e)}async handleOnRenamed(e){const{prevName:t,...n}=e;this.registry.execute(Os.layoutRenamed.name,n,{name:t})}}const As={raiseNotification:{name:"raiseNotification",dataDecoder:Si,resultDecoder:_i},requestPermission:{name:"requestPermission",resultDecoder:xi},notificationShow:{name:"notificationShow",dataDecoder:ki},notificationClick:{name:"notificationClick",dataDecoder:ki},getPermission:{name:"getPermission",resultDecoder:Ti},list:{name:"list",resultDecoder:Ji},notificationRaised:{name:"notificationRaised",dataDecoder:Gi},notificationClosed:{name:"notificationClosed",dataDecoder:zi},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:Ri},getConfiguration:{name:"getConfiguration",resultDecoder:Ai},getActiveCount:{name:"getActiveCount",resultDecoder:si},configurationChanged:{name:"configurationChanged",resultDecoder:Ai},setState:{name:"setState",dataDecoder:ci},activeCountChange:{name:"activeCountChange",resultDecoder:si},stateChange:{name:"stateChange",resultDecoder:ci},operationCheck:{name:"operationCheck"}};let Ms=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};class Es{supportedOperationsNames=[];registry=ps();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;notificationsConfiguration;notificationsActiveCount=0;handlePlatformShutdown(){this.notifications={},this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=t.bridge,this.coreGlue=e,this.notificationsSettings=t.config.notifications,this.buildNotificationFunc=t.buildNotification,this.notificationsConfiguration=await this.getConfiguration(),this.notificationsActiveCount=await this.getActiveCount();const n=this.toApi();this.addOperationExecutors(),e.notifications=n,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=X(lt,e.operation),n=As[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){const e={raise:this.raise.bind(this),requestPermission:this.requestPermission.bind(this),getPermission:this.getPermission.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onClosed:this.onClosed.bind(this),click:this.click.bind(this),clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),getFilter:this.getFilter.bind(this),setFilter:this.setFilter.bind(this),setState:this.setState.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onActiveCountChanged:this.onActiveCountChanged.bind(this),onCounterChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",As.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",As.requestPermission,void 0)).permissionGranted}async raise(e){const t=X(ai,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return re.raiseError("Cannot raise the notification, because the user has declined the permission request");const n=Ms(10),i=await this.bridge.send("notifications",As.raiseNotification,{settings:t,id:n}),r=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=r,r}async list(){return(await this.bridge.send("notifications",As.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?re.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?re.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){X(nt,e),t&&X(nt,t),await this.bridge.send("notifications",As.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){X(nt,e),await this.bridge.send("notifications",As.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",As.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",As.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=X(Oi,e);await this.bridge.send("notifications",As.configure,{configuration:t},void 0,{includeOperationCheck:!0})}async getConfiguration(){return(await this.bridge.send("notifications",As.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getActiveCount(){try{return(await this.bridge.send("notifications",As.getActiveCount,void 0,void 0,{includeOperationCheck:!0})).count}catch(e){return console.warn("Failed to get accurate active notifications count",e),0}}async getFilter(){return(await this.bridge.send("notifications",As.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=X(Pi,e);return await this.bridge.send("notifications",As.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){X(nt,e),X(ri,t),await this.bridge.send("notifications",As.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):(setTimeout(()=>e(this.notificationsConfiguration),0),this.registry.add("notifications-config-changed",e))}onActiveCountChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):(setTimeout(()=>e({count:this.notificationsActiveCount}),0),this.registry.add("notifications-active-count-changed",e))}onStateChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){As.notificationShow.execute=this.handleNotificationShow.bind(this),As.notificationClick.execute=this.handleNotificationClick.bind(this),As.notificationRaised.execute=this.handleNotificationRaised.bind(this),As.notificationClosed.execute=this.handleNotificationClosed.bind(this),As.configurationChanged.execute=this.handleConfigurationChanged.bind(this),As.activeCountChange.execute=this.handleActiveCountChanged.bind(this),As.stateChange.execute=this.handleNotificationStateChanged.bind(this),As.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(As)}async handleConfigurationChanged(e){this.notificationsConfiguration=e.configuration,this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.notificationsActiveCount=e.count,this.registry.execute("notifications-active-count-changed",e)}async handleNotificationStateChanged(e){this.registry.execute("notification-state-changed",{id:e.id},e.state)}async handleNotificationShow(e){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}async handleNotificationClick(e){if(!e.action&&this.notificationsSettings?.defaultClick&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&this.notificationsSettings?.actionClicks?.some(t=>t.action===e.action)){const t=this.notificationsSettings?.actionClicks?.find(t=>t.action===e.action);t.handler(this.coreGlue,e.definition)}if(!e.id)return;const t=this.notifications[e.id];t&&t.onclick&&(t.onclick(),delete this.notifications[e.id])}async handleNotificationRaised(e){this.registry.execute("notification-raised",e.notification)}async handleNotificationClosed(e){this.registry.execute("notification-closed",e)}}const Ds={getIntents:{name:"getIntents",resultDecoder:On},findIntent:{name:"findIntent",dataDecoder:Mn,resultDecoder:On},raise:{name:"raise",dataDecoder:qn,resultDecoder:Bn},filterHandlers:{name:"filterHandlers",dataDecoder:Jn,resultDecoder:Gn},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:_n,resultDecoder:Zn}},js="Tick42.FDC3.Intents.";class Ns{bridge;logger;interop;appManagerController;windowsController;myIntents=new Set;prefsController;uiController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout=6e4;unregisterIntentPromises=[];async start(e,t){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=t.bridge,this.interop=e.interop,this.appManagerController=t.appManagerController,this.windowsController=t.windowsController,this.prefsController=t.prefsController,this.uiController=t.uiController,this.checkIfIntentsResolverIsEnabled(t.config);const n=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=n}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}async handleBridgeMessage(e){const t=X(Sn,e.operation),n=Ds[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}toApi(){return{raise:this.raise.bind(this),all:this.all.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),find:this.find.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntentsByHandler.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}async raise(e){const t=X(Ln,e),n="string"==typeof t?{intent:t}:t;await Promise.all(this.unregisterIntentPromises),n.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${n.intent}`),await this.removeRememberedHandler(n.intent));const i=await this.checkHandleRaiseWithRememberedHandler(n);if(i)return i;const r={intentRequest:n,resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:n}),embeddedResolverConfig:this.getEmbeddedResolverConfig()},s=n.waitUserResponseIndefinitely?Z:(n.timeout||this.intentResolverResponseTimeout)+3e4;this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${s}ms`);const o=await this.bridge.send("intents",Ds.raise,r,{methodResponseTimeoutMs:s,waitTimeoutMs:s});return this.logger.trace(`Raise operation completed with response: ${JSON.stringify(o)}`),o}getLegacyResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||9e4};const t=e.intentRequest?.waitUserResponseIndefinitely?Z:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}getEmbeddedResolverConfig(){return{enabled:this.uiController.isIntentResolverEnabled(),initialCaller:{instanceId:this.interop.instance.instance}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",Ds.getIntents,void 0)).intents}addIntentListener(e,t){if(X(Vn,e),"function"!=typeof t)return re.raiseError("Cannot add intent listener, because the provided handler is not a function!");let n;const i="string"==typeof e?e:e.intent,r=this.buildInteropMethodName(i);if(this.myIntents.has(i))return re.raiseError(`Intent listener for intent ${i} already registered!`);this.myIntents.add(i);const s={unsubscribe:()=>{this.myIntents.delete(i),n.then(()=>this.interop.unregister(r)).catch(e=>this.logger.trace(`Unregistration of a method with name ${r} failed with reason: ${e}`))}};let o={};if("object"==typeof e){const{intent:t,...n}=e;o=n}return n=this.interop.register({name:r,flags:{intent:o}},e=>{if(this.myIntents.has(i)){const{_initialCallerId:n,...i}=e;return t(i)}}),n.catch(e=>{this.myIntents.delete(i),this.logger.warn(`Registration of a method with name ${r} failed with reason: ${e}`)}),s}async register(e,t){if(X(Vn,e),"function"!=typeof t)return re.raiseError("Cannot add intent listener, because the provided handler is not a function!");await Promise.all(this.unregisterIntentPromises);const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);if(this.myIntents.has(n))return re.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);let r={};if("object"==typeof e){const{intent:t,...n}=e;r=n}try{await this.interop.register({name:i,flags:{intent:r}},e=>{if(this.myIntents.has(n)){const{_initialCallerId:n,...i}=e,r=this.interop.servers().find(e=>e.instance===n);return t(i,r)}})}catch(e){return this.myIntents.delete(n),re.raiseError(`Registration of a method with name ${i} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(n)}}async find(e){let t;if(void 0!==e){const n=X(An,e);"string"==typeof n?t={filter:{name:n}}:"object"==typeof n&&(t={filter:n})}await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",Ds.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return re.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppAdded",e),n=this.subscribeForServerMethodEvent("serverMethodAdded",e);return()=>{t(),n()}}onHandlerRemoved(e){if("function"!=typeof e)return re.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppRemoved",e),n=this.subscribeForServerMethodEvent("serverMethodRemoved",e);return()=>{t(),n()}}subscribeForAppEvent(e,t){return this.appManagerController[e](e=>{const n=e.userProperties.intents;n?.length&&n.forEach(n=>{const i=this.buildIntentHandlerFromApp(e,n);t(i,n.name)})})}subscribeForServerMethodEvent(e,t){return this.interop[e](async({server:n,method:i})=>{if(!i.name.startsWith(js))return;const r=i.name.replace(js,""),s=await this.buildIntentHandlerFromServerMethod(e,n,i,r);t(s,r)})}buildIntentHandlerFromApp(e,t){return{applicationName:e.name,type:"app",applicationDescription:e.caption,applicationIcon:e.icon,applicationTitle:e.title,contextTypes:t.contexts,displayName:t.displayName,resultType:t.resultType,customConfig:t.customConfig}}async buildIntentHandlerFromServerMethod(e,t,n,i){const r=n.flags.intent,s=this.appManagerController.getApplication(t.application||t.applicationName);let o;"serverMethodAdded"===e&&t.windowId&&(o=await(this.windowsController.findById(t.windowId)?.getTitle()));const a=s?.userProperties?.intents?.find(e=>e.name===i);return{applicationName:t.application||t.applicationName||"",instanceId:t.windowId||t.instance,type:"instance",applicationIcon:r?.icon||s?.icon,applicationTitle:s?.title,applicationDescription:r?.description||s?.caption,contextTypes:r?.contextTypes||a?.contexts,instanceTitle:o,displayName:r?.displayName||a?.displayName,resultType:r?.resultType||a?.resultType,customConfig:r?.customConfig}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}checkIfIntentsResolverIsEnabled(e){this.useIntentsResolverUI="boolean"!=typeof e.intents?.enableIntentsResolverUI||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=e.intents?.intentsResolverAppName??"intentsResolver",this.intentResolverResponseTimeout=e.intents?.methodResponseTimeoutMs??6e4}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter(t=>t!==e)}buildInteropMethodName(e){return`${js}${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)})}async filterHandlers(e){X(Hn,e),this.checkIfAtLeastOneFilterIsPresent(e);const t=this.getEmbeddedResolverConfig();if(e.openResolver&&!this.useIntentsResolverUI&&!t.enabled)return re.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const n=(e.timeout||9e4)+3e4,i={filterHandlersRequest:e,resolverConfig:this.getLegacyResolverConfigByRequest({handlerFilter:e}),embeddedResolverConfig:t};return await this.bridge.send("intents",Ds.filterHandlers,i,{methodResponseTimeoutMs:n,waitTimeoutMs:n},{includeOperationCheck:!0})}checkIfAtLeastOneFilterIsPresent(e){const t="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)return re.raiseError(t);const{intent:n,resultType:i,contextTypes:r,applicationNames:s}=e,o=r?.length,a=s?.length;return n||i||o||a?void 0:re.raiseError(t)}async getIntentsByHandler(e){X(_n,e);return await this.bridge.send("intents",Ds.getIntentsByHandler,e,void 0,{includeOperationCheck:!0})}async removeRememberedHandler(e){let t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const n=t.data?.intents;if(!n)return void this.logger.trace("No app prefs found for current app");delete n[e];const i={...t.data,intents:n};try{await this.prefsController.update(i)}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${e}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){let t;try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const n=t.data?.intents?.[e.intent];return n?.handler}async checkHandleRaiseWithRememberedHandler(e){if(e.target)return;const t=await this.checkForRememberedHandler(e);if(!t)return;const n={intentRequest:{...e,target:{app:t.applicationName,instance:t.instanceId}},resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:e}),embeddedResolverConfig:this.getEmbeddedResolverConfig()};try{return await this.bridge.send("intents",Ds.raise,n)}catch(t){this.logger.trace(`Could not raise intent to remembered handler. Reason: ${t}. Removing it from Prefs store`),await this.removeRememberedHandler(e.intent)}}}const Fs={appHello:{name:"appHello",dataDecoder:Xi,resultDecoder:er},addChannel:{name:"addChannel",dataDecoder:ui},removeChannel:{name:"removeChannel",dataDecoder:fi},getMyChannel:{name:"getMyChannel",resultDecoder:tr},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:Vi,resultDecoder:Ki},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:ir,resultDecoder:rr},joinChannel:{name:"joinChannel",dataDecoder:ar},restrict:{name:"restrict",dataDecoder:yi},getRestrictions:{name:"getRestrictions",dataDecoder:vi,resultDecoder:wi},restrictAll:{name:"restrictAll",dataDecoder:Ii},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:dr},leaveChannel:{name:"leaveChannel",dataDecoder:cr},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:Mt},getMode:{name:"getMode",resultDecoder:Yi},operationCheck:{name:"operationCheck"}},Ls="___channel___",$s="subs",Ws="changed",Hs="channels_changed",Us="io_connect_channels",qs="inMemory";class Bs{supportedOperationsNames=[];registry=ps();logger;contexts;interop;bridge;windowsController;_mode;myWindowId;storage;handlePlatformShutdown(){this.registry.clear(),this.storage.clear()}addOperationsExecutors(){Fs.getMyChannel.execute=this.handleGetMyChannel.bind(this),Fs.joinChannel.execute=this.handleJoinChannel.bind(this),Fs.leaveChannel.execute=this.handleLeaveChannel.bind(this),Fs.restrict.execute=this.handleRestrict.bind(this),Fs.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),Fs.restrictAll.execute=this.handleRestrictAll.bind(this),Fs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Fs)}async start(e,t){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.interop=e.interop,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.storage=t.channelsStorage,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this.myWindowId=this.windowsController.my().id??this.interop.instance.instance,await this.initialize();const n=this.toApi();e.channels=n}async postStart(e,t){try{await this.requestChannelSelector(e.appManager.myInstance)}catch(e){this.logger.warn(`Failed to display channel selector: ${Y(e)}`)}}async handleBridgeMessage(e){const t=X(Zi,e.operation),n=Fs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async list(){const e=this.getAllChannelNames();return await Promise.all(e.map(e=>this.get(e)))}my(){return this.current()}async handleGetMyChannel(){const e=this.my();return e?{channel:e}:{}}async join(e,t){const n=this.getAllChannelNames();X(Qn(n),e),X(rt,t);const i={channel:e,windowId:t??this.myWindowId};await this.bridge.send("channels",Fs.joinChannel,i,void 0,{includeOperationCheck:!0})}handleJoinChannel({channel:e}){return"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}onChanged(e){return this.changed(e)}async leave(e={}){if(X(ei,e),e.channel){const t=this.getAllChannelNames();X(Qn(t),e.channel)}const t={channelName:e.channel,windowId:e.windowId??this.myWindowId};await this.bridge.send("channels",Fs.leaveChannel,t,void 0,{includeOperationCheck:!0})}async handleAppManagerInitialChannelId(e){if("inMemory"!==this.storage.mode&&!this.storage.getSessionStorageData())return this.handleJoinChannel({channel:e,windowId:this.myWindowId})}async handleLeaveChannel({channelName:e}){const t=e?[e]:this.storage.channels;t.forEach(e=>this.storage.invokeUnsubscribes(e)),this.storage.channels=this.storage.channels.filter(e=>!t.includes(e)),this.executeChangedEvents(),await this.notifyChannelsChanged()}toApi(){const e={mode:this._mode,subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),publish:this.publish.bind(this),all:this.all.bind(this),list:this.list.bind(this),get:this.get.bind(this),getMyChannels:this.getMyChannels.bind(this),myChannels:this.myChannels.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),join:this.join.bind(this),leave:this.leave.bind(this),current:this.current.bind(this),my:this.my.bind(this),changed:this.changed.bind(this),onChanged:this.onChanged.bind(this),add:this.add.bind(this),remove:this.remove.bind(this),getMy:this.getMy.bind(this),getWindowsOnChannel:this.getWindowsOnChannel.bind(this),getWindowsWithChannels:this.getWindowsWithChannels.bind(this),restrict:this.restrict.bind(this),getRestrictions:this.getRestrictions.bind(this),restrictAll:this.restrictAll.bind(this),clearChannelData:this.clearChannelData.bind(this),setPath:this.setPath.bind(this),setPaths:this.setPaths.bind(this)};return Object.freeze(e)}createContextName(e){return`${Ls}${e}`}getAllChannelNames(){return this.contexts.all().filter(e=>e.startsWith(Ls)).map(e=>e.replace(Ls,""))}async joinAdditionalChannel(e){if(this.storage.channels.includes(e))return;this.storage.channels=[...this.storage.channels,e];const t=this.createContextName(e),n=await this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute($s,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,n),this.executeChangedEvents(e),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.storage.channels[0];if(e===t)return;this.storage.invokeUnsubscribes(t),this.storage.channels=[e];const n=this.createContextName(e),i=await this.contexts.subscribe(n,(e,t,n,i,r)=>{this.registry.execute($s,e.data,e,t,r?.updaterId)});this.storage.addUnsubscribe(e,i),this.executeChangedEvents(e),await this.notifyChannelsChanged()}executeChangedEvents(e){this.registry.execute(Ws,e),this.registry.execute(Hs,this.storage.channels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",Fs.notifyChannelsChanged,{channelNames:this.storage.channels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${Y(e)}`)}}async 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]}));i&&e.push({path:V,value:i}),await this.contexts.setPaths(n,e)}else i&&(t[V]=i),await this.contexts.update(n,{data:t})}getFDC3Type(e){const t=Object.keys(e).filter(e=>0===e.indexOf("fdc3_"));if(0!==t.length)return t.length>1?re.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return re.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&X(Yn,t);const n=this.current(),i=t?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(e,t.contextType):this.getWrappedSubscribeCallback(e);return n&&this.replaySubscribe(i,n),this.registry.add($s,i)}async subscribeFor(e,t,n){const i=this.getAllChannelNames();if(X(Qn(i),e),"function"!=typeof t)return re.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);n&&X(Yn,n);const r=this.createContextName(e),s=n?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,n.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(r,(e,t,n,i,r)=>{s(e.data,e,t,r?.updaterId)})}async publish(e,t){if("object"!=typeof e)return re.raiseError("Cannot publish to channel, because the provided data is not an object!");if(X(Xn,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();X(Qn(e),t)}if(!t&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e);const n="string"==typeof t?t:this.storage.channels[0];if(!n)return re.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?this.updateData(n,e):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const n=this.getAllChannelNames();X(Qn(n),e),t&&X(Yn,t);const i=this.createContextName(e),r=await this.contexts.get(i);return t?.contextType?this.getContextForFdc3Type(r,t.contextType):r.latest_fdc3_type?this.getContextWithFdc3Data(r):r}async getMyChannels(e){return Promise.all(this.storage.channels.map(t=>this.get(t,e)))}myChannels(){return this.storage.channels}getContextForFdc3Type(e,t){const n=`fdc3_${t.split(".").join("&")}`;if(!e.data[n])return{name:e.name,meta:e.meta,data:{}};const i={type:t,...e.data[n]};return{name:e.name,meta:e.meta,data:{fdc3:i}}}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}}}current(){return this.storage.channels[0]}changed(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(Ws,e)}async add(e){const t=X(ui,e);return this.getAllChannelNames().includes(t.name)?re.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",Fs.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){X(nt,e);if(!this.getAllChannelNames().includes(e))return re.raiseError("There's no channel with such name");await this.bridge.send("channels",Fs.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then(t=>{if(!t)return;const n=this.createContextName(t.name);return this.contexts.subscribe(n,(t,n,i,r,s)=>{e(t.data,t,n,s?.updaterId)})}).then(e=>e?.()).catch(e=>this.logger.trace(e))};async getMy(e){if(this.storage.channels.length)return e&&X(Yn,e),this.get(this.storage.channels[this.storage.channels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();X(Qn(t),e);const{windowIds:n}=await this.bridge.send("channels",Fs.getWindowIdsOnChannel,{channel:e},void 0,{includeOperationCheck:!0});return n.reduce((e,t)=>{const n=this.windowsController.findById(t);return n?[...e,n]:e},[])}async getWindowsWithChannels(e){const t=void 0!==e?{filter:X(nr,e)}:{},{windowIdsWithChannels:n}=await this.bridge.send("channels",Fs.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0});return n.reduce((e,{application:t,channel:n,windowId:i})=>{const r=this.windowsController.findById(i);return r?[...e,{application:t,channel:n,window:r}]:e},[])}async clearChannelData(e){await this.handleSetPaths("clearChannelData",[{path:"data",value:{}},{path:"latest_fdc3_type",value:null}],e)}async restrict(e){X(mi,e);const t=this.getAllChannelNames();X(Qn(t),e.name);const n={config:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",Fs.restrict,n,void 0,{includeOperationCheck:!0})}async handleRestrict({config:e}){const t=await this.getMy();if(!t)return this.updateRestriction(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateRestriction(e);e.name===t.name&&!n&&e.read&&this.replaySubscribeCallback(e.name)}updateRestriction(e){const t=this.storage.restrictions.some(t=>t.name===e.name);this.storage.restrictions=t?this.storage.restrictions.map(t=>t.name===e.name?e:t):this.storage.restrictions.concat(e)}updateAllRestrictions(e){const t=this.getAllChannelNames();this.storage.restrictions=t.map(t=>({name:t,...e}))}async getRestrictions(e){X(rt,e);const t=e&&e!==this.interop.instance.instance;return e&&t?this.bridge.send("channels",Fs.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):{channels:this.storage.restrictions}}async restrictAll(e){X(Ci,e);const t={restrictions:{...e,windowId:e.windowId??this.myWindowId}};return this.bridge.send("channels",Fs.restrictAll,t,void 0,{includeOperationCheck:!0})}async handleRestrictAll({restrictions:e}){const t=await this.getMy();if(!t)return this.updateAllRestrictions(e);const n=this.isAllowedByRestrictions(t.name,"read");this.updateAllRestrictions(e),!n&&e.read&&this.replaySubscribeCallback(t.name)}async setPath(e,t){const n=X(pi,e),i=[{path:`data.${n.path}`,value:n.value}];await this.handleSetPaths("setPath",i,t)}async setPaths(e,t){const n=X(gi,e).map(({path:e,value:t})=>({path:`data.${e}`,value:t}));await this.handleSetPaths("setPaths",n,t)}async handleSetPaths(e,t,n){const i=n?[n]:this.storage.channels;if(!i.length)return re.raiseError(`Cannot complete ${e} operation, because channel is not specified. Either join one or pass a channel name as second argument!`);this.validateChannelNames(i);const{allowed:r,forbidden:s}=this.groupChannelsByPermission("write",i);if(i.length===s.length)return re.raiseError(`Cannot complete ${e} operation due to write restrictions to the following channels: ${i.join(", ")}`);s.length&&this.logger.warn(`Cannot set paths on channel${s.length>1?"s":""}: ${s.join(", ")} due to write restrictions`),await Promise.all(r.map(e=>{const n=this.createContextName(e);return this.contexts.setPaths(n,t)}))}validateChannelNames(e){const t=this.getAllChannelNames();e.forEach(e=>X(Qn(t),e))}groupChannelsByPermission(e,t){return t.reduce((t,n)=>(this.isAllowedByRestrictions(n,e)?t.allowed.push(n):t.forbidden.push(n),t),{allowed:[],forbidden:[]})}isAllowedByRestrictions(e,t){const n=this.storage.restrictions.find(t=>t.name===e);return!n||n[t]}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,(e,t,n,i,r)=>{this.registry.execute($s,e.data,e,t,r?.updaterId)}).then(e=>{e&&"function"==typeof e&&e()}).catch(e=>this.logger.error(e))}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();X(Qn(e),t.name)}if(!t.name&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const n=t.name||this.storage.channels[0];if(!n)return re.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(n,"write")?t.fdc3?this.publishFdc3Data(n,e):this.updateData(n,e):re.raiseError(`Cannot publish on channel ${n} due to restrictions`)}async publishOnMultipleChannels(e,t){const{allowed:n,forbidden:i}=this.groupChannelsByPermission("write",this.storage.channels);if(this.storage.channels.length===i.length)return re.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`);i.length&&this.logger.warn(`Data on channel${i.length>1?"s":""}: ${i.join(", ")} won't be published due to write restrictions`);const r=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(n.map(t=>r(t,e)))}async publishFdc3Data(e,t){X(ti,t);const{type:n,...i}=t,r=n.split(".").join("&"),s={[`fdc3_${r}`]:i};return this.updateData(e,s)}getWrappedSubscribeCallback(e){return(t,n,i,r)=>{if(!this.isAllowedByRestrictions(n.name,"read"))return;const{data:s,latest_fdc3_type:o}=n,a=`fdc3_${o}`;if(!o||i.data&&!i.data[a])return void e(t,n,r);const c={type:o.split("&").join("."),...s[a]},{[a]:d,...l}=t;e({...l,fdc3:c},n,r)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const n={replayed:!1};return(i,r,s,o)=>{if(!this.isAllowedByRestrictions(r.name,"read"))return;const{data:a,latest_fdc3_type:c}=r,d=`fdc3_${t.split(".").join("&")}`;if(!a[d]||s.data&&!s.data[d])return;if(n.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:c,searchedType:t,callback:e,context:r,updaterId:o});const l={type:t,...a[d]};e({fdc3:l},r,o),n.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:n,callback:i,context:r,updaterId:s}=e;if(t.split("&").join(".")!==n)return;i({fdc3:{type:n,...r.data[`fdc3_${t}`]}},r,s)}async requestChannelSelector(e){if(!e)return;const t=e.application,n=t.userProperties?.details;if(!n)return;if(!n?.channelSelector?.enabled)return;const i={windowId:e.id,channelsNames:this.storage.channels};await this.bridge.send("channels",Fs.requestChannelSelector,i,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",Fs.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),"single"}}onChannelsChanged(e){return"function"!=typeof e?re.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add(Hs,e)}async initialize(){if(!await this.checkIfAppHelloSupported())return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions");const{success:e,error:t}=await this.sendAppHello();if(t)return this.handleAppHelloFailure(t);this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(e)}`);const{mode:n,channels:i,restrictions:r}=e;this.storage.mode="inMemory",this._mode=n,this.storage.channels=i,this.storage.restrictions=r}async handleAppHelloFailure(e){this.logger.trace(e),this.storage.mode="sessionStorage",this._mode=await this.getPlatformChannelsMode()}async sendAppHello(){try{return{success:await this.bridge.send("channels",Fs.appHello,{windowId:this.myWindowId},void 0,{includeOperationCheck:!0}),error:void 0}}catch(e){return{error:`Failed to get initial state from platform. Error: ${Y(e)}`,success:void 0}}}async checkIfAppHelloSupported(){try{const{isSupported:e}=await this.bridge.send("channels",Fs.operationCheck,{operation:Fs.appHello.name},void 0,{includeOperationCheck:!0});return e}catch(e){return this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${Y(e)}`),!1}}}const Gs={getEnvironment:{name:"getEnvironment",resultDecoder:kt},getBase:{name:"getBase",resultDecoder:kt},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:wr},systemHello:{name:"systemHello",resultDecoder:vr},operationCheck:{name:"operationCheck"}};class Js{supportedOperationsNames=[];bridge;ioc;logger;errorPort=K.port2;async start(e,t){this.logger=e.logger.subLogger("system.controller.web"),this.logger.trace("starting the web system controller"),this.bridge=t.bridge,this.ioc=t,this.addOperationsExecutors();let n=!1;try{const e=await this.bridge.send("system",Gs.systemHello,void 0,void 0,{includeOperationCheck:!0});n=e.isClientErrorOperationSupported}catch(e){this.logger.warn("The platform of this client is outdated and does not support some system operations.")}this.errorPort.onmessage=async e=>{n&&await this.bridge.send("system",Gs.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=X(ht,e.operation),n=Gs[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async processPlatformShutdown(){Object.values(this.ioc.controllers).forEach(e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),await this.bridge.stop()}async setEnvironment(){const e=await this.bridge.send("system",Gs.getEnvironment,void 0),t=await this.bridge.send("system",Gs.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",r=Object.assign({},n,t,{environment:e});window[i]=r}addOperationsExecutors(){Gs.platformShutdown.execute=this.processPlatformShutdown.bind(this),Gs.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this),Gs.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(Gs)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}}class zs{onclick=()=>{};onshow=()=>{};id;title;badge;body;data;dir;icon;image;lang;renotify;requireInteraction;silent;tag;timestamp;vibrate;clickInterop;actions;focusPlatformOnDefaultClick;severity;showToast;showInPanel;state;constructor(e,t){this.id=t,this.badge=e.badge,this.body=e.body,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.vibrate=e.vibrate,this.title=e.title,this.clickInterop=e.clickInterop,this.actions=e.actions,this.focusPlatformOnDefaultClick=e.focusPlatformOnDefaultClick,this.severity=e.severity,this.showToast=e.showToast,this.showInPanel=e.showInPanel,this.state=e.state}}R(T("clientHello"));const Vs={clientHello:{name:"clientHello",resultDecoder:k({widget:k({inject:_()})})}};class Ks{windowId;logger;bridge;eventsDispatcher;channelsController;config;channels=[];unsubFuncs=[];contentCommands={widgetVisualizationPermission:{name:"widgetVisualizationPermission",handle:this.handleWidgetVisualizationPermission.bind(this)},changeChannel:{name:"changeChannel",handle:this.handleChangeChannel.bind(this)}};handlePlatformShutdown(){this.unsubFuncs.forEach(e=>e()),this.channels=[],this.unsubFuncs=[]}async start(e,t){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=t.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=t.bridge,this.channelsController=t.channelsController,this.eventsDispatcher=t.eventsDispatcher;try{await this.registerWithPlatform()}catch(e){return}this.channels=await this.channelsController.list();const n=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),i=this.channelsController.onChanged(e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})});this.unsubFuncs.push(n),this.unsubFuncs.push(i)}async handleBridgeMessage(e){}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}async registerWithPlatform(){this.logger.trace("registering with the platform"),this.config=await this.bridge.send("extension",Vs.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}async handleWidgetVisualizationPermission(){if(!this.config?.widget.inject)return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const e=this.channels.find(e=>e.name===this.channelsController.my());this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:e})}async handleChangeChannel(e){"no-channel"!==e.name?await this.channelsController.join(e.name):await this.channelsController.leave()}}class Zs{config;glue;registry=ps();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;_resolveModalsUIFactoryReadyPromise;_resolveIntentResolverUIFactoryReadyPromise;constructor(e){this.config=e}events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},contentInc:{name:"contentInc",handle:this.handleContentInc.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)},widgetFactoryReady:{name:"widgetFactoryReady",handle:this.handleWidgetReady.bind(this)},modalsUIFactoryReady:{name:"modalsUIFactoryReady",handle:this.handleModalsUIFactoryReady.bind(this)},intentResolverUIFactoryReady:{name:"intentResolverUIFactoryReady",handle:this.handleIntentResolverUIFactoryReady.bind(this)}};stop(){window.removeEventListener(this.glue42EventName,this._handleMessage)}start(e){this.glue=e,this.wireCustomEventListener(),this.announceStarted()}sendContentMessage(e){this.send("contentOut","glue42core",e)}onContentMessage(e){return this.registry.add("content-inc",e)}async widgetReady(){const e=new Promise(e=>{this._resolveWidgetReadyPromise=e});return this.requestWidgetReady(),e}async modalsUIFactoryReady(){const e=new Promise(e=>{this._resolveModalsUIFactoryReadyPromise=e});return this.requestModalsUIFactoryReady(),e}async intentResolverUIFactoryReady(){const e=new Promise(e=>{this._resolveIntentResolverUIFactoryReadyPromise=e});return this.requestIntentResolverUIFactoryReady(),e}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){const t=e.detail,n=t?.glue42??t?.glue42core;if(!n)return;const i=n.event,r=this.events[i];r&&r.handle(n.message)}announceStarted(){this.send("start","glue42")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse","glue42",{glue:this.glue}):this.send("requestGlueResponse","glue42",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}handleContentInc(e){this.registry.execute("content-inc",e)}requestWidgetReady(){this.send("requestWidgetFactoryReady","glue42")}handleWidgetReady(){this._resolveWidgetReadyPromise?.()}requestModalsUIFactoryReady(){this.send("requestModalsUIFactoryReady","glue42")}handleModalsUIFactoryReady(){this._resolveModalsUIFactoryReadyPromise?.()}requestIntentResolverUIFactoryReady(){this.send("requestIntentResolverUIFactoryReady","glue42")}handleIntentResolverUIFactoryReady(){this._resolveIntentResolverUIFactoryReadyPromise?.()}send(e,t,n){const i={};i[t]={event:e,message:n};const r=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(r)}}class Qs{coreGlue;transactionTimeout=15e3;transactionLocks={};webPlatformTransport;webPlatformMessagesUnsubscribe;reconnectCounter=0;logger;constructor(e){this.coreGlue=e,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}async start(e){if(e.isPlatformInternal)return void this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic.");if(!(this.coreGlue.connection.transport.name()===z))return re.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport.");if(!this.coreGlue.connection.transport.isPreferredActivated)return void this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization.");this.webPlatformTransport=this.coreGlue.connection.transport,this.webPlatformMessagesUnsubscribe=this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this));const t=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(t)}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===z,n=e.type,i=e.args,r=e.transactionId;return n===$.name?this.handleTransportSwitchRequest(i,r):n!==L.name||t?n===U.name?this.handleGetCurrentTransportResponse(i,r):n===q.name?this.handleCheckPreferredLogic(r):n===B.name?this.handleCheckPreferredConnection(i,r):void 0:this.handlePlatformUnload()}async reEstablishPlatformPort(){try{await this.webPlatformTransport.connect()}catch(e){if(this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(e)}`),--this.reconnectCounter,this.reconnectCounter>0)return this.reEstablishPlatformPort();this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform.")}this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."),this.reconnectCounter=0,this.webPlatformTransport.close();const e=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(e)}async checkSwitchTransport(e){const t=this.coreGlue.connection.transport.name();if(t===e.transportName)return void this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary");this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${t}, but it should reconnect to ${JSON.stringify(e)}`);const n=await this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(n)}`)}async getCurrentPlatformTransportState(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(H.name);this.sendPlatformMessage(H.name,e.id);const t=await e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}setTransaction(e){const t={},n=Ms(10),i=new Promise((i,r)=>{let s=!0;t.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{s=!1,delete this.transactionLocks[n],r(e)},setTimeout(()=>{s&&(s=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],r(`Transaction for operation: ${e} timed out.`))},this.transactionTimeout)});return t.lock=i,t.id=n,this.transactionLocks[n]=t,t}sendPlatformMessage(e,t,n){this.logger.trace(`Sending a platform message of type: ${e}, id: ${t} and args: ${JSON.stringify(n)}`),this.webPlatformTransport.sendObject({glue42core:{type:e,args:n,transactionId:t}})}handleTransportSwitchRequest(e,t){this.logger.trace(`Received a transport switch request with id: ${t} and data: ${JSON.stringify(e)}`),this.coreGlue.connection.switchTransport(e.switchSettings).then(e=>{this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(e)}`),this.setConnected(),this.sendPlatformMessage(W.name,t,{success:e.success})}).catch(e=>{this.logger.error(e),this.sendPlatformMessage(W.name,t,{success:!1})})}handlePlatformUnload(){this.reconnectCounter=5,this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."),this.reEstablishPlatformPort()}handleGetCurrentTransportResponse(e,t){this.logger.trace(`Got a current transport response from the platform with id: ${t} and data: ${JSON.stringify(e)}`);const n=e.transportState,i=this.transactionLocks[t];i?.lift(n)}handleCheckPreferredLogic(e){setTimeout(()=>this.sendPlatformMessage(G.name,e),0)}handleCheckPreferredConnection(e,t){const n=e.url;this.logger.trace(`Testing the possible connection to: ${n}`),this.checkPreferredConnection(n).then(e=>{this.logger.trace(`The connection to ${n} is possible`),this.sendPlatformMessage(J.name,t,e)}).catch(e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(J.name,t,{error:e})})}checkPreferredConnection(e){return new Promise(t=>{const n=new WebSocket(e);n.onerror=()=>t({live:!1}),n.onopen=()=>{n.close(),t({live:!0})}})}setConnected(){this.webPlatformTransport.manualSetReadyState()}}const Ys={getCurrent:{name:"getCurrent",resultDecoder:Hi},list:{name:"list",resultDecoder:Ui},select:{name:"select",dataDecoder:qi}};class Xs{logger;bridge;registry=ps();themesSubscription;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge,await this.setupSubscription(),this.logger.trace("themes subscription is ready");const n=this.toApi();e.themes=n,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),this.themesSubscription?.close(),delete this.themesSubscription}async handleBridgeMessage(){}toApi(){const e={getCurrent:this.getCurrent.bind(this),list:this.list.bind(this),select:this.select.bind(this),onChanged:this.onChanged.bind(this)};return Object.freeze(e)}async getCurrent(){return(await this.bridge.send("themes",Ys.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",Ys.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){X(nt,e),await this.bridge.send("themes",Ys.select,{name:e},void 0,{includeOperationCheck:!0})}onChanged(e){return"function"!=typeof e?re.raiseError("onChanged requires a callback of type function"):this.registry.add("on-theme-change",e)}async setupSubscription(){this.themesSubscription=await this.bridge.createThemesSubscription(),this.themesSubscription.onData(this.handleStreamData.bind(this)),this.themesSubscription.onClosed(this.handleStreamClosure.bind(this))}handleStreamData(e){const t=e.data,n=Hi.run(t);if(!n.ok)return void this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(n.error)}`);const i=n.result;this.registry.execute("on-theme-change",i.theme)}handleStreamClosure(){this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),delete this.themesSubscription}}class eo{sessionStorage=window.sessionStorage;_mode=qs;inMemoryChannels=[];inMemoryRestrictions=[];_unsubscribeDict={};clear(){this._mode=qs,this.inMemoryChannels=[],this.inMemoryRestrictions=[],this._unsubscribeDict={},this.sessionStorage.setItem(Us,JSON.stringify([]))}get mode(){return this._mode}set mode(e){this._mode=e}get channels(){return"inMemory"===this.mode?this.inMemoryChannels.slice():this.getSessionStorageData()?.channels??[]}set channels(e){"inMemory"===this.mode&&(this.inMemoryChannels=e),this.setSessionStorageChannels(e)}get restrictions(){return"inMemory"===this.mode?this.inMemoryRestrictions.slice():this.getSessionStorageData()?.restrictions??[]}set restrictions(e){"inMemory"===this.mode&&(this.inMemoryRestrictions=e),this.setSessionStorageRestrictions(e)}getSessionStorageData(){return JSON.parse(this.sessionStorage.getItem(Us)||"null")}addUnsubscribe(e,t){this._unsubscribeDict[e]=t}invokeUnsubscribes(e){if(e)return this._unsubscribeDict[e]?.(),void delete this._unsubscribeDict[e];Object.values(this._unsubscribeDict).forEach(e=>e()),this._unsubscribeDict={}}setSessionStorageChannels(e){const t=this.getSessionStorageData();if(t?.channels)return t.channels=e,this.setSessionStorageData(t);const n={channels:e,restrictions:t?.restrictions??[]};return this.setSessionStorageData(n)}setSessionStorageRestrictions(e){const t=this.getSessionStorageData();if(t?.restrictions)return t.restrictions=e,this.setSessionStorageData(t);const n={channels:t?.channels??[],restrictions:e};return this.setSessionStorageData(n)}setSessionStorageData(e){this.sessionStorage.setItem(Us,JSON.stringify(e))}}const to={clear:{name:"clear",dataDecoder:pr},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:pr,resultDecoder:gr},getAll:{name:"getAll",resultDecoder:fr},set:{name:"set",dataDecoder:br},update:{name:"update",dataDecoder:br},prefsChanged:{name:"prefsChanged",dataDecoder:gr},prefsHello:{name:"prefsHello",resultDecoder:yr},operationCheck:{name:"operationCheck"},registerSubscriber:{name:"registerSubscriber",dataDecoder:mr}};class no{supportedOperationsNames=[];bridge;config;logger;appManagerController;platformAppName;registry=ps();validNonExistentApps;signaledSubscription=!1;interopId;isAppValidationEnabled;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("prefs.controller.web"),this.logger.trace("starting the web prefs controller"),this.addOperationsExecutors(),this.interopId=e.interop.instance.instance,this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",to.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[],this.isAppValidationEnabled=e.isAppValidationEnabled??!0}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support Prefs API.")}this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning");const n=this.toApi();e.prefs=n}async handleBridgeMessage(e){const t=X(hr,e.operation),n=to[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async get(e){const t=null==e?this.getMyAppName():X(nt,e),{prefs:n}=await this.bridge.send("prefs",to.get,{app:t},void 0,{includeOperationCheck:!0});return n}async update(e,t){const n=X(O(pr),t),i=n?.app??this.getMyAppName();await this.updateFor(i,e)}addOperationsExecutors(){to.prefsChanged.execute=this.handleOnChanged.bind(this),to.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=ee(to)}toApi(){return{clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearFor:this.clearFor.bind(this),get:this.get.bind(this),getAll:this.getAll.bind(this),set:this.set.bind(this),setFor:this.setFor.bind(this),subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),update:this.update.bind(this),updateFor:this.updateFor.bind(this)}}async clear(){const e=this.getMyAppName();await this.clearFor(e)}async clearAll(){await this.bridge.send("prefs",to.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=X(nt,e);await this.bridge.send("prefs",to.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",to.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const n=X(O(pr),t),i=n?.app??this.getMyAppName();await this.setFor(i,e)}async setFor(e,t){const n=X(nt,e),i=X(k(),t);await this.bridge.send("prefs",to.set,{app:n,data:i},void 0,{includeOperationCheck:!0})}subscribe(e){const t=this.getMyAppName();return this.subscribeFor(t,e)}subscribeFor(e,t){const n=X(nt,e),i=this.appManagerController.getApplications();if(!(!this.isAppValidationEnabled||(n===this.platformAppName||i.some(e=>e.name===n)||this.validNonExistentApps.includes(n))))return re.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return re.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");this.signaledSubscription||(this.bridge.send("prefs",to.registerSubscriber,{interopId:this.interopId,appName:n},void 0,{includeOperationCheck:!0}).catch(e=>{this.logger.warn("Failed to register subscriber for prefs"),this.logger.error(e)}),this.signaledSubscription=!0);const r=this.getSubscriptionKey(n);return this.get(n).then(t),this.registry.add(r,t)}async updateFor(e,t){const n=X(nt,e),i=X(k(),t);await this.bridge.send("prefs",to.update,{app:n,data:i},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||re.raiseError("App Preferences operations can not be executed for windows that do not have app!")}getSubscriptionKey(e){return`prefs-changed-${e}`}async handleOnChanged({prefs:e}){const t=this.getSubscriptionKey(e.app);this.registry.execute(t,e)}}const io={getResources:{name:"getResources",dataDecoder:jr,resultDecoder:Hr},operationCheck:{name:"operationCheck",dataDecoder:Li,resultDecoder:Fi},showAlert:{name:"showAlert",dataDecoder:Jr},showDialog:{name:"showDialog",dataDecoder:Kr},alertInteropAction:{name:"alertInteropAction",dataDecoder:ts},showResolver:{name:"showResolver",dataDecoder:ds,resultDecoder:ls}},ro="io-modals-shadow-host",so="io-widget-shadow-host",oo="io-intent-resolver-shadow-host";class ao{ioc;supportedOperationsNames=[];logger;bridge;config;zIndexDictionary={[so]:"100",[ro]:"101",[oo]:"100"};widgetResources;modalsResources;intentResolverResources;rootElements=[];modalsUiApi;isDialogOpen=!1;intentResolverUiApi;isIntentResolverOpen=!1;constructor(e){this.ioc=e}async start(e,t){this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.addOperationsExecutors();const n=await this.getResources();n?(this.logger.trace(`Received UI resources from platform: ${JSON.stringify(n)}`),this.setResources(n)):this.logger.trace("No UI elements to display - platform is not initialized with any UI resources")}async handleBridgeMessage(e){const t=X(Dr,e.operation),n=io[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=X(n.dataDecoder,e.data)),await n.execute(i)}async showComponents(e){const t=this.widgetResources?this.initializeWidget(e,this.widgetResources):Promise.resolve(),n=this.modalsResources?this.initializeModalsUi(e,this.modalsResources):Promise.resolve(),i=this.intentResolverResources?this.initializeIntentResolverUI(e,this.intentResolverResources):Promise.resolve();this.subscribeForThemeChanges(e),await Promise.all([this.config.widget.awaitFactory?t:Promise.resolve(),this.config.modals.awaitFactory?n:Promise.resolve(),this.config.intentResolver.awaitFactory?i:Promise.resolve()])}isIntentResolverEnabled(){return!!this.intentResolverResources&&this.config.intentResolver.enable}addOperationsExecutors(){io.operationCheck.execute=async e=>te(this.supportedOperationsNames,e.operation),io.showAlert.execute=this.handleShowAlert.bind(this),io.showDialog.execute=this.handleShowDialog.bind(this),io.showResolver.execute=this.handleShowResolver.bind(this),this.supportedOperationsNames=ee(io)}async handleShowAlert({config:e}){if(!this.config.modals.alerts.enabled)return re.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showAlert operation because modalsUiApi is missing.");const{promise:n,resolve:i}=ie(),r=e=>{const t=es.run(e);if(!t.ok)return void this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(t.error)}.`);const{interopAction:n}=t.result;this.bridge.send("ui",io.alertInteropAction,{interopAction:n},void 0,{includeOperationCheck:!0}).catch(e=>this.logger.warn(Y(e)))};let s;try{this.logger.trace(`Open alert with config: ${JSON.stringify(e)}`),s=t.alerts.open({...e,onClick:r,onClose:i})}catch(e){return re.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${Y(e)}.`)}const o=Zr.run(s);if(!o.ok)return re.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);const a=setTimeout(()=>{i()},ne(e.ttl??5e3));n.then(()=>{clearTimeout(a);try{t.alerts.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close alert with id ${o.result.id}. Reason: ${Y(e)}`)}})}async handleShowDialog({config:e}){if(!this.config.modals.dialogs.enabled)return re.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return re.raiseError("Unable to perform showDialog operation because modalsUiApi is missing.");if(this.isDialogOpen)return re.raiseError("Cannot open a dialog because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open dialog with config: ${JSON.stringify(e)}`),r=t.dialogs.open({...e,onCompletion:i})}catch(e){return re.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${Y(e)}.`)}const s=Qr.run(r);if(!s.ok)return re.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);let o;this.isDialogOpen=!0,e.timer&&(o=setTimeout(()=>{i({response:{isExpired:!0}})},ne(e.timer.duration)));const a=await n;clearTimeout(o),this.isDialogOpen=!1;try{t.dialogs.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close dialog with id ${s.result.id}. Reason: ${Y(e)}`)}const c=Yr.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async handleShowResolver({config:e}){if(this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(e)}`),!this.config.intentResolver.enable)return re.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config.");const t=this.intentResolverUiApi;if(!t)return re.raiseError("Unable to perform showResolver operation because intentResolverApi is missing.");if(this.isIntentResolverOpen)return re.raiseError("Cannot open the intent resolver because another one is already open.");const{promise:n,resolve:i}=ie();let r;try{this.logger.trace(`Open intent resolver with config: ${JSON.stringify(e)}`),r=t.open({...e,onUserResponse:i})}catch(e){return re.raiseError(`intentResolverUI.open() failed. Reason: ${Y(e)}.`)}const s=is.run(r);if(!s.ok)return re.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);const o=setTimeout(()=>i({response:{isExpired:!0}}),ne(e.timeout)),a=await n;clearTimeout(o),this.isIntentResolverOpen=!1;try{t.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close intent resolver with id ${s.result.id}. Reason: ${Y(e)}`)}const c=as.run(a);return c.ok?{result:c.result.response}:re.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",io.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}appendModalsResources(e){return this.logger.trace("Appending modals resources"),this.appendResources(ro,"io-modals-root",e.sources)}appendWidgetResources(e){return this.logger.trace("Appending widget resources"),this.appendResources(so,"io-widget-root",e.sources)}appendIntentResolverResources(e){return this.logger.trace("Appending intent resolver resources"),this.appendResources(oo,"io-intent-resolver-root",e.sources)}appendResources(e,t,n){const{bundle:i,fonts:r=[],styles:s}=n,o=document.createElement("div");o.id=e,o.style.position="fixed",o.style.zIndex=this.zIndexDictionary[e];const a=o.attachShadow({mode:"open"}),c=document.createElement("script");c.src=i,c.type="module",a.appendChild(c);const d=document.createElement("div");return d.id=t,d.className="io-body io-variables",a.appendChild(d),s.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,a.appendChild(t)}),r.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.insertBefore(t,document.head.firstChild)}),document.body.appendChild(o),{rootElement:d}}async initializeWidget(e,t){this.logger.trace("Initializing IOBrowserWidget.");const{rootElement:n}=this.appendWidgetResources(t);this.rootElements.push(n);const i={...d(t.config,this.config.widget),rootElement:n};return bs(async()=>{await this.ioc.eventsDispatcher.widgetReady(),this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(i)}`),await window.IOBrowserWidget(e,i),this.logger.trace("IOBrowserWidget was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserWidget to initialize.`)}async initializeModalsUi(e,t){this.logger.trace("Initializing IOBrowserModalsUI.");const{rootElement:n}=this.appendModalsResources(t);this.rootElements.push(n);const i={...this.config.modals,rootElement:n};return bs(async()=>{await this.ioc.eventsDispatcher.modalsUIFactoryReady(),this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.modalsUiApi=await window.IOBrowserModalsUI(e,i),this.logger.trace("IOBrowserModalsUI was initialized successfully.")},i.timeout,`Timeout of ${i.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`)}async initializeIntentResolverUI(e,t){this.logger.trace("Initializing IOBrowserIntentResolverUI.");const{rootElement:n}=this.appendIntentResolverResources(t);this.rootElements.push(n);const i={...this.config.intentResolver,rootElement:n},r=i.timeout;return bs(async()=>{await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(),this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(i)}`),this.intentResolverUiApi=await window.IOBrowserIntentResolverUI(e,i),this.logger.trace("IOBrowserIntentResolverUI initialized successfully.")},r,`Timeout of ${r}ms hit waiting for IOBrowserIntentResolverUI to initialize.`)}setResources(e){this.setWidgetResources(e.widget),this.setModalsUiResources(e.modals),this.setIntentResolverResources(e.intentResolver)}setWidgetResources(e){const t="Widget won't be displayed. Reason: ",n=Mr.run(this.config.widget);n.ok?this.config.widget.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`):this.widgetResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'widget: { enable: false }' config`):this.logger.warn(`${t} invalid widget config. Error: ${n.error}`)}setModalsUiResources(e){const t="Modals won't be displayed. Reason: ",n=Er.run(this.config.modals);n.ok?this.config.modals.alerts.enabled||this.config.modals.dialogs.enabled?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`):this.modalsResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`):this.logger.warn(`${t} invalid modals config. Error: ${n.error}`)}setIntentResolverResources(e){const t="Intent Resolver UI won't be displayed. Reason: ",n=ns.run(this.config.intentResolver);n.ok?this.config.intentResolver.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`):this.intentResolverResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'intentResolver: { enable: false }' config`):this.logger.warn(`${t} invalid intent resolver config. Error: ${JSON.stringify(n.error)}`)}subscribeForThemeChanges(e){const t=e.themes;if(!t)return;const n=async e=>{await Promise.all(this.rootElements.map(n=>this.applyThemeToElement(n,t,e)))};t.onChanged(n),t.getCurrent().then(n)}async applyThemeToElement(e,t,n){if(e.classList.contains(n.name))return;const i=await t.list();e.classList.remove(...i.map(({name:e})=>e)),e.classList.add(n.name)}}class co{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_channelsStorage;_prefsControllerInstance;_uiController;controllers={windows:this.windowsController,appManager:this.appManagerController,layouts:this.layoutsController,notifications:this.notificationsController,intents:this.intentsController,channels:this.channelsController,system:this.systemController,extension:this.extensionController,themes:this.themesController,prefs:this.prefsController,ui:this.uiController};get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new ws),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new ao(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new Ts),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Rs),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new Xs),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new Es),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new Ns),this._intentsControllerInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new Js),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new Bs),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new no),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new Ks),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new Zs(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new _s(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new Qs(this._coreGlue)),this._preferredConnectionController}get channelsStorage(){return this._channelsStorage||(this._channelsStorage=new eo),this._channelsStorage}get config(){return this._webConfig}defineGlue(e){this._coreGlue=e,this._publicWindowId=e.connection.transport.publicWindowId;const t=window.glue42core||window.iobrowser;this._communicationId=e.connection.transport.communicationId||t.communicationId}defineConfig(e){this._webConfig=e}async buildWebWindow(e,t,n){const i=new fs(e,t,this.bridge,n),r=await i.toApi();return{id:e,model:i,api:r}}buildNotification(e,t){return new zs(e,t)}async buildApplication(e,t){const n=new Ps(e,[],this.appManagerController).toApi(),i=t.map(e=>this.buildInstance(e,n));return n.instances.push(...i),n}buildInstance(e,t){return new ks(e,this.bridge,t).toApi()}}var lo="4.5.0-beta.0";const ho=(e,t)=>({getContainerInfo:async()=>{if(window!==window.parent)return window.name.includes("#wsp")?{workspaceFrame:{id:"N/A"}}:window.parent===window.top?{top:{}}:{parent:{}}},getProfileData:async()=>{if(!t)throw new Error("Bridge is not available and cannot fetch the profile data");return await t.send("system",{name:"getProfileData"},void 0)}});var uo=1,po=2,go=3,fo=4;function mo(e){return e.type===go?"timestamp":e.type===po?"number":e.type===uo?"string":e.type===fo?"object":"unknown"}function bo(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function yo(e){const t={},n=mo(e);if("object"===n){const n=Object.keys(e.value).reduce((t,n)=>{const i=bo(e.value[n]);if("object"===i){const i=wo(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=vo(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function wo(e){return Object.keys(e).reduce((t,n)=>{const i=bo(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:wo(e[n])}:{type:i,description:"",context:{}},t},{})}function vo(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function Co(e){return"timestamp"===mo(e)?Date.now():Io(e.value)}function Io(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]=Io(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t},{})}function So(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?So(t):t),[])}function _o(e){const t=So(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 xo=(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 To{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,xo(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 ko extends To{constructor(e,t,n,i){super(e,t,n,i,po)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class Po extends To{constructor(e,t,n,i){super(e,t,n,i,fo)}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 Oo extends To{constructor(e,t,n,i){super(e,t,n,i,uo)}}class Ro extends To{constructor(e,t,n,i){super(e,t,n,i,go)}now(){this.update(new Date)}}function Ao(e,t,n,i,r){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");const s=n,o=e,a=r||"",c=t,d=i,l=function e(t){if(!t||!t.parent)return[];const n=e(t.parent);return n.push(t.name),n}(i);let h={};const u=(g="/",((p=l)&&p.length>0?p.join(g):"")+e);var p,g;const f=t.root,m=[],b=[];function y(e,t,n,i){let r={name:""};r="string"==typeof e?{name:e}:e;const s=b.filter(e=>e.name===r.name);if(s.length>0){const e=s[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 o=i(r);return b.push(o),o}const w={get name(){return o},get description(){return a},get repo(){return c},get parent(){return d},path:l,id:u,root:f,get subSystems(){return m},get metrics(){return b},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const n=m.filter(t=>t.name===e);if(n.length>0)return n[0];const i=Ao(e,c,s,w,t);return m.push(i),i},getState:()=>h,setState:function(e,t){h={state:e,description:t},s.updateSystem(w,h)},stringMetric:function(e,t){return y(e,uo,t,e=>new Oo(e,w,s,t))},timestampMetric:function(e,t){return y(e,go,t,e=>new Ro(e,w,s,t))},objectMetric:function(e,t){return y(e,fo,t,e=>new Po(e,w,s,t))},numberMetric:function(e,t){return y(e,po,t,e=>new ko(e,w,s,t))},getAggregateState:function(){const e=[];return Object.keys(h).length>0&&e.push({name:o,path:l,state:h.state,description:h.description}),m.forEach(t=>{const n=t.getAggregateState();n.length>0&&e.push(...n)}),e}};return s.createSystem(w),w}class Mo{root;constructor(e,t){t.init(this),this.root=Ao("",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 Eo{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class Do{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;if(!e||!e.memory)return;const t=e.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:t.totalJSHeapSize,usedJSHeapSize:t.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 jo=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=>{s(e.root)},s=e=>{o(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{s(e)})},o=async e=>{if(void 0===e.parent)return;await n;const r={type:"define",metrics:[{name:vo(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)}`)})},a=async e=>{const r=d(e);await n;const s={type:"define",metrics:[yo(r)]};i.sendFireAndForget(s).catch(n=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(n)}`)}),void 0!==r.value&&c(r)},c=e=>{if(l()){const n=Co(e),r={type:"publish",values:[{name:vo(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()},d=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},l=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:s=>{let o;n=new Promise(e=>{o=e}),i=e.domain("metrics"),i.onJoined(e=>{!e&&o&&(o(),o=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(s)}),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:o,updateSystem:async(r,s)=>{await n;const o={type:"publish",values:[{name:vo(r.path.join("/")+"/"+r.name+"/State"),value:{Description:s.description,Value:s.state},timestamp:Date.now()}]};i.sendFireAndForget(o).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${r.name}: ${JSON.stringify(e)}`)});const a=_o(r),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};i.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${r.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=d(e);await n,c(t)}}}(e.connection,e):new Eo;let n=new Mo(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,s)=>{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===s||""===s)throw new Error("payload is mandatory");i?i.update({name:e,action:r,payload:s}):i=t.objectMetric(n,{name:e,action:r,payload:s})};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 Do(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var No,Fo,Lo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function $o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Wo=function(){if(Fo)return No;function e(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 s='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+r.stack;if(e)switch(e.errorHandling){case"log":return console.error(s);case"silent":return;case"throw":throw new Error(s)}console.error(s)}}return{add:function(e,t,r){var s=n[e];return s||(s=[],n[e]=s),s.push(t),r&&setTimeout(function(){r.forEach(function(r){var s;if(null===(s=n[e])||void 0===s?void 0:s.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 s=n[e];if(!s||0===s.length)return[];var o=[];return s.forEach(function(n){try{var r=n.apply(void 0,t);o.push(r)}catch(t){o.push(void 0),i(t,e)}}),o},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}return Fo=1,e.default=e,No=e}(),Ho=$o(Wo);class Uo{gw;registry=Ho();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 qo{logger;worker;registry=Ho();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)}}class Bo{static isNode(){if(void 0!==Bo._isNode)return Bo._isNode;if("undefined"!=typeof window)return Bo._isNode=!1,!1;try{Bo._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){Bo._isNode=!1}return Bo._isNode}static _isNode;static getMethodName(e){return"string"==typeof e?e:e?.name}}class Go{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 Jo={};function zo(e){const t=Jo[e];if(t)return t;const n=[];function i(){return(new Date).getTime()}const r=i();let s,o;function a(e,t){const r=t??i();let s=0;n.length>0&&(s=r-n[n.length-1].time),n.push({name:e,time:r,diff:s})}a("start",r);const c={get startTime(){return r},get endTime(){return s},get period(){return o},stop:function(){return s=i(),a("end",s),o=s-r,o},mark:a,marks:n};return Jo[e]=c,c}const Vo=Bo.isNode()?null:window.WebSocket;function Ko(e,t,n,i){const r=!1!==i?.includeStack,s=e instanceof Error?e:e?.error;return s instanceof Error?JSON.stringify({name:s.name,message:s.message,code:s.code,stack:r?s.stack:void 0}):JSON.stringify({type:e?.type,readyState:t?.readyState,url:n,message:"string"==typeof e?.message?e.message:void 0})}class Zo{ws;logger;settings;startupTimer=zo("connection");_running=!0;_registry=Ho();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 Go;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){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);try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{if(void 0!==t&&t<=0)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);void 0!==t&&this.logger.debug(`will retry ${t-1} more times (every ${e} ms)`),setTimeout(()=>{const n=void 0===t?void 0:t-1;this.openSocket(e,n)},e)}}initiateSocket(){const e=new Go;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new Vo(this.settings.ws??"");let t=!1;return this.ws.onerror=n=>{const i=Ko(n,this.ws,this.settings.ws);this.logger.info(`ws error - ${i}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error"));const r=Ko(n,this.ws,this.settings.ws,{includeStack:!1});this.notifyStatusChanged(!1,r)},this.ws.onclose=n=>{var i;this.logger.info("ws closed - "+(i=n,`code: ${i?.code} reason: ${i?.reason||"(none)"} wasClean: ${i?.wasClean}`)),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 Qo{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 Yo=(e=21)=>{let t="",n=0|e;for(;n--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t};const Xo=(e,t,n)=>new Promise((i,r)=>{const s=setTimeout(()=>{r(n||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(s),i(e)}).catch(e=>{clearTimeout(s),r(e)})});class ea{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=Ho();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 Xo((t,n)=>{this.connectionResolve=t,this.connectionReject=n,this.myClientId=this.myClientId??Yo(10);const i=this.getMyWindowId()||Yo(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||Yo(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(()=>Xo((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():Xo(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=Xo(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-${Yo(10)}`,this.selfAssignedWindowId):void 0}}class ta{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 na(e,t,n,i,r){null==e&&(e="global"),i=i??["success"],r=r??["error"];let s,o="global"===e,a=!1,c=!1;const d=Ho();t.disconnected(function(){n.debug("connection is down"),c=!1,o=!1,a=!0,Object.keys(l).forEach(e=>{const t=l[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 h(s)}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 l={};function h(t){return s=t,new Promise((i,r)=>{if(o)return void i({});let s;if("global"===e)s=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{n.debug(`joining domain ${e}`);s=b({type:"join",destination:e,domain:"global",options:t})}s.then(()=>{!function(){n.debug("did join "+e),o=!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 o&&e(!1),d.add("onJoined",e)}function p(t){if(e!==t.domain)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.error(t)}function g(t){if(t.domain!==e)return;const n=t.request_id;if(!n)return;const i=l[n];i&&i.success(t)}function f(){return Yo(10)}let m=[];function b(i,r,s){if(i.type&&-1===["hello","join"].indexOf(i.type)&&!o){console.warn(`trying to send a message (${i.domain} ${i.type}) but not connected, will queue`);const e=new Go;if(m.push({msg:i,tag:r,options:s,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=>{b(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),m=[],e()})}return e.promise}s=s??{},i.request_id=i.request_id??f(),i.domain=i.domain??e,s.skipPeerId||(i.peer_id=t.peerId);const a=i.request_id;return new Promise((e,n)=>{l[a]={success:t=>{delete l[a],t._tag=r,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete l[a],e._tag=r,n(e)}},t.send(i,s).catch(e=>{l[a]?.error({err:e})})})}return{join:h,leave:function(){return"global"===e?Promise.resolve():o?(n.debug("stopping session "+e+"..."),a=!1,b({type:"leave",destination:e,domain:"global"}).then(()=>{o=!1,d.execute("onLeft")}).catch(()=>{o=!1,d.execute("onLeft")})):(a=!1,Promise.resolve())},onJoined:u,onLeft:function(e){return o||e(),d.add("onLeft",e)},send:b,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}}}function ia(e){if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);const t=e,n="string"==typeof t?.message?t.message:void 0,i="string"==typeof t?.reason?t.reason:void 0;return void 0!==n&&n.length>0?new Error(n):void 0!==i&&i.length>0?new Error(i):""===n||""===i?new Error(""):new Error(function(e){try{const t=new WeakSet,n=JSON.stringify(e,(e,n)=>{if("bigint"==typeof n)return`${n.toString()}n`;if("function"==typeof n)return"[Function]";if("symbol"==typeof n)return n.toString();if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return n});if(void 0!==n)return n}catch{}if(null!==e&&"object"==typeof e){const t=e.constructor?.name??"Object";let n=[];try{n=Object.keys(e)}catch{}return n.length>0?`[${t} keys=${n.join(",")}]`:`[${t}]`}return String(e)}(e))}class ra{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=Ho();_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 ta;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;reconnectTimeout;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;remainingReconnectAttempts;loginConfig;loginRetryInProgress=!1;reconnectInProgress=!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 Uo(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new qo(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new ea(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new Zo(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`),zo("connection").mark("transport-opened");const n=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(n)}`),zo("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()),ia(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=na(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"))}async reconnect(){if(!this.loginConfig)throw new Error("Cannot reconnect - no previous login configuration");if(this.reconnectInProgress)this.logger.debug("reconnect() already in progress, ignoring");else{this.reconnectInProgress=!0;try{for(this.shouldTryLogin=!1,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);this.loginRetryInProgress;)await new Promise(e=>setTimeout(e,50));this._isLoggedIn&&(this.setLoggedIn(!1),this.registry.execute("disconnected")),this.shouldTryLogin=!0,await this.login(this.loginConfig,!0)}finally{this.reconnectInProgress=!1}}}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 Qo(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&(this.remainingReconnectAttempts=this.settings.reconnectAttempts,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.shouldTryLogin)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--}else if(void 0!==this.remainingReconnectAttempts){if(this.remainingReconnectAttempts<=0)return void this.logger.info("maximum reconnect attempts reached, will not try to login again");this.logger.debug(`reconnect attempt, ${this.remainingReconnectAttempts} attempts remaining...`),this.remainingReconnectAttempts--}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),this.shouldTryLogin&&(this.reconnectTimeout=setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3))}finally{this.loginRetryInProgress=!1}}else this.logger.debug("should not try to login, ignoring reconnect attempt...")}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 Xo(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 Zo(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:""});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=na("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 s=await e.send(t,void 0,n);if("authentication-request"!==s.type){if("welcome"===s.type){r=s;break}throw"error"===s.type?new Error("Authentication failed: "+s.reason):new Error("Unexpected message type during authentication: "+s.type)}{const e=Buffer.from(s.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.setLoggedIn(!1),this.pingTimer&&clearTimeout(this.pingTimer),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0);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 sa=["trace","debug","info","warn","error","off"];class oa{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.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}subLogger(e){const t=this.subLoggers.filter(t=>t.name===e)[0];if(void 0!==t)return t;Object.keys(this).forEach(t=>{if(t===e)throw new Error("This sub logger name is not allowed.")});const n=new oa(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}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 sa.indexOf(e)>=sa.indexOf(t||this.consoleLevel()||"trace")}publishMessage(e,t,n){const i=this.loggerFullName;if("error"===e&&!n){const e=new Error;e.stack&&(t=t+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(e,this.publishLevel())){const r=oa.Interop;if(r)try{if(r.methods({name:oa.InteropMethodName}).length>0){const s={msg:t,logger:i,level:e};n&&n instanceof Error&&(s.error={message:n.message,stack:n.stack??""}),r.invoke(oa.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(e)){let r="";if(this.includeTimeAndLevel){const t=new Date;r=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const s=`${r}${i}: ${t}`;switch(e){case"trace":this.logFn.debug(s);break;case"debug":this.logFn.debug?this.logFn.debug(s):this.logFn.log(s);break;case"info":this.logFn.info(s);break;case"warn":this.logFn.warn(s);break;case"error":n?this.logFn.error(s,n):this.logFn.error(s)}}}}const aa="create-context",ca="created",da="destroyed",la="context-created",ha="context-added",ua="subscribe-context",pa="subscribed-context",ga="unsubscribe-context",fa="destroy-context",ma="context-destroyed",ba="update-context",ya="context-updated",wa="joined",va={get name(){return"context"},get types(){return[aa,ca,da,la,ha,ua,pa,ga,fa,ma,ba,ya,wa]}};var Ca,Ia,Sa="6.10.4";
2
2
  /*!
3
3
  * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
4
4
  *
5
5
  * Copyright (c) 2014-2017, Jon Schlinkert.
6
6
  * Released under the MIT License.
7
- */function Ia(e){return"[object Object]"===Object.prototype.toString.call(e)}function Sa(e){let t,n;return!1!==Ia(e)&&(t=e.constructor,void 0===t||(n=t.prototype,!1!==Ia(n)&&!1!==n.hasOwnProperty("isPrototypeOf")))}var _a,xa=function(){if(va)return wa;va=1;var e=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var n=Object.prototype.toString.call(e);return"[object RegExp]"===n||"[object Date]"===n||function(e){return e.$$typeof===t}(e)}(e)},t="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function i(e,t,i){return e.concat(t).map(function(e){return n(e,i)})}function r(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}function o(e,t,i){var o={};return i.isMergeableObject(e)&&r(e).forEach(function(t){o[t]=n(e[t],i)}),r(t).forEach(function(r){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,r)||(s(e,r)&&i.isMergeableObject(t[r])?o[r]=function(e,t){if(!t.customMerge)return a;var n=t.customMerge(e);return"function"==typeof n?n:a}(r,i)(e[r],t[r],i):o[r]=n(t[r],i))}),o}function a(t,r,s){(s=s||{}).arrayMerge=s.arrayMerge||i,s.isMergeableObject=s.isMergeableObject||e,s.cloneUnlessOtherwiseSpecified=n;var a=Array.isArray(r);return a===Array.isArray(t)?a?s.arrayMerge(t,r,s):o(t,r,s):n(r,s)}return a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return a(e,n,t)},{})},wa=a}(),Ta=Fo(xa),ka={},Pa={},Oa={},Ra={},Aa={};function Ma(){if(_a)return Aa;_a=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.NullManager=void 0;return Aa.NullManager=class{constructor(){this.started=!1}waitForFinalExport(e){return Promise.resolve()}get settings(){return{}}start(){return this.started=!0,Promise.resolve()}stop(){return this.started=!1,Promise.resolve()}},Aa}var Ea,Da,ja={},Na={};function Fa(){if(Da)return ja;Da=1,Object.defineProperty(ja,"__esModule",{value:!0}),ja.safeStringify=function(t){if(!t)return JSON.stringify(t);return JSON.stringify(t,(t,n)=>n&&"object"==typeof n?(0,e.isPlainObject)(n)?n:Object.prototype.toString.call(n):n)};const e=function(){if(Ea)return Na;
7
+ */function _a(e){return"[object Object]"===Object.prototype.toString.call(e)}function xa(e){let t,n;return!1!==_a(e)&&(t=e.constructor,void 0===t||(n=t.prototype,!1!==_a(n)&&!1!==n.hasOwnProperty("isPrototypeOf")))}var Ta,ka=function(){if(Ia)return Ca;Ia=1;var e=function(e){return function(e){return!!e&&"object"==typeof e}(e)&&!function(e){var n=Object.prototype.toString.call(e);return"[object RegExp]"===n||"[object Date]"===n||function(e){return e.$$typeof===t}(e)}(e)},t="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function n(e,t){return!1!==t.clone&&t.isMergeableObject(e)?a((n=e,Array.isArray(n)?[]:{}),e,t):e;var n}function i(e,t,i){return e.concat(t).map(function(e){return n(e,i)})}function r(e){return Object.keys(e).concat(function(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}(e))}function s(e,t){try{return t in e}catch(e){return!1}}function o(e,t,i){var o={};return i.isMergeableObject(e)&&r(e).forEach(function(t){o[t]=n(e[t],i)}),r(t).forEach(function(r){(function(e,t){return s(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))})(e,r)||(s(e,r)&&i.isMergeableObject(t[r])?o[r]=function(e,t){if(!t.customMerge)return a;var n=t.customMerge(e);return"function"==typeof n?n:a}(r,i)(e[r],t[r],i):o[r]=n(t[r],i))}),o}function a(t,r,s){(s=s||{}).arrayMerge=s.arrayMerge||i,s.isMergeableObject=s.isMergeableObject||e,s.cloneUnlessOtherwiseSpecified=n;var a=Array.isArray(r);return a===Array.isArray(t)?a?s.arrayMerge(t,r,s):o(t,r,s):n(r,s)}return a.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,n){return a(e,n,t)},{})},Ca=a}(),Pa=$o(ka),Oa={},Ra={},Aa={},Ma={},Ea={};function Da(){if(Ta)return Ea;Ta=1,Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.NullManager=void 0;return Ea.NullManager=class{constructor(){this.started=!1}waitForFinalExport(e){return Promise.resolve()}get settings(){return{}}start(){return this.started=!0,Promise.resolve()}stop(){return this.started=!1,Promise.resolve()}},Ea}var ja,Na,Fa={},La={};function $a(){if(Na)return Fa;Na=1,Object.defineProperty(Fa,"__esModule",{value:!0}),Fa.safeStringify=function(t){if(!t)return JSON.stringify(t);return JSON.stringify(t,(t,n)=>n&&"object"==typeof n?(0,e.isPlainObject)(n)?n:Object.prototype.toString.call(n):n)};const e=function(){if(ja)return La;
8
8
  /*!
9
9
  * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
10
10
  *
11
11
  * Copyright (c) 2014-2017, Jon Schlinkert.
12
12
  * Released under the MIT License.
13
13
  */
14
- function e(e){return"[object Object]"===Object.prototype.toString.call(e)}return Ea=1,Object.defineProperty(Na,"__esModule",{value:!0}),Na.isPlainObject=function(t){let n,i;return!1!==e(t)&&(n=t.constructor,void 0===n||(i=n.prototype,!1!==e(i)&&!1!==i.hasOwnProperty("isPrototypeOf")))},Na}();return ja}var La,$a,Wa,Ha={};function Ua(){if(La)return Ha;La=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.NullMetric=void 0;return Ha.NullMetric=class{constructor(e,t){this.settings=e,this.logger=t,this.started=!1}start(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been started instead of ${this.settings.type} one`),this.started=!0,Promise.resolve()}stop(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been stopped instead of ${this.settings.type} one`),this.started=!1,Promise.resolve()}add(){}record(){}},Ha}function qa(){if($a)return Ra;$a=1,Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.NullMetricsManager=void 0;const e=Ma(),t=Fa(),n=Ua();class i extends e.NullManager{constructor(e,n,i){!1!==(null==n?void 0:n.logSettingsOnStartup)&&(null==i||i.info(`Starting NullMetrcsManager with settings ${(0,t.safeStringify)(e)}`)),super()}waitForFinalExport(e){return Promise.resolve()}getFromSettings(e){return new n.NullMetric(e)}get(e){return new n.NullMetric({name:e,type:e,enabled:!1,description:e})}}return Ra.NullMetricsManager=i,Ra}var Ba,Ga={},Ja={},za={};function Va(){if(Ba)return za;Ba=1,Object.defineProperty(za,"__esModule",{value:!0});return za.default=class{constructor(e,t,n){this.source=e,this.propagationInfo=t,this.disablePropagation=n,this.currentSpanStatus={code:0},this.level="OFF"}endSpan(){return Promise.resolve()}get enabled(){return!1}get id(){}get traceId(){}set status(e){this.currentSpanStatus=Object.assign({},e)}get status(){return this.currentSpanStatus}addEvent(e,t,n){return this}recordException(e,t){}isRecording(){return!1}updateName(e){return this}spanContext(){}addData(e,t){}end(){}getPropagationInfo(){return this.propagationInfo?this.propagationInfo:null}injectPropagationInfo(e){this.propagationInfo&&!this.disablePropagation&&(e.__interopIOTracePropagationInfo=this.propagationInfo)}},za}var Ka,Za,Qa,Ya,Xa,ec={},tc={},nc={};function ic(){if(Ka)return nc;Ka=1;var e=nc&&nc.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})};Object.defineProperty(nc,"__esModule",{value:!0}),nc.Container=void 0;const t=Fa();class n{static get instance(){var e,t;return null!==(e=n._instance)&&void 0!==e?e:null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.instance}static get settings(){var e;return null!==(e=n._settings)&&void 0!==e?e:n.instance.settings}static set settings(e){n._settings=e}static errorless(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return n.handleErrorlessMode(e,t)}}static errorlessDefined(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return n.handleErrorlessMode(e,t)}}static errorlessAsync(t,i){return e(this,void 0,void 0,function*(){try{if("function"!=typeof t)return t;return(yield t)()}catch(e){return n.handleErrorlessMode(e,i)}})}static handleErrorlessMode(e,i){var r,s,o,a,c;let d;try{if((null==e?void 0:e.message)&&(d=(null==e?void 0:e.message)+" "+(null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:(new Error).stack)),!d)try{d=(0,t.safeStringify)(e)+" "+(new Error).stack}catch(e){}if(!d)try{d=(null==e?void 0:e.toString())+" "+(new Error).stack}catch(e){}}catch(e){}d||(d="unknown "+(new Error).stack);try{if(!(null===(o=null===(s=n.instance)||void 0===s?void 0:s.settings)||void 0===o?void 0:o.errorlessMode))throw null===(a=n.instance.logger)||void 0===a||a.error("Observed error "+d),e}catch(t){throw e}try{return null===(c=n.instance.logger)||void 0===c||c.warn("Caught error "+d),i}catch(e){return i}}constructor(e,t,i,r,s){var o;this._settings=e,this._traces=t,this.metrics=i,this.logs=r,this.logger=s,this.started=!1,n._instance=this,globalThis.ioInsightsInternals=null!==(o=globalThis.ioInsightsInternals)&&void 0!==o?o:{},globalThis.ioInsightsInternals.instance=this}get traces(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:this._traces}waitForFinalExport(e){var t,n,i;return Promise.allSettled([null===(t=this.traces)||void 0===t?void 0:t.waitForFinalExport(e),null===(n=this.metrics)||void 0===n?void 0:n.waitForFinalExport(e),null===(i=this.logs)||void 0===i?void 0:i.waitForFinalExport(e)])}get settings(){return this._settings}start(){return e(this,void 0,void 0,function*(){const e=this.metrics.settings.enabled?this.metrics.start():Promise.resolve(),t=this.traces.settings.enabled?this.traces.start():Promise.resolve(),n=this.logs.settings.enabled?this.logs.start():Promise.resolve();yield Promise.all([e,t,n]),this.started=!0})}stop(){return e(this,void 0,void 0,function*(){const e=this.metrics.started?this.metrics.stop():Promise.resolve(),t=this.traces.started?this.traces.stop():Promise.resolve(),n=this.logs.started?this.logs.stop():Promise.resolve();yield Promise.all([e,t,n]),this.started=!1})}}return nc.Container=n,nc}function rc(){return Za||(Za=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extractFilteringContextFromArgs=e.deep_value=e.getOTELData=e.flattenOtelAtributes=void 0;const t=ic();e.flattenOtelAtributes=(t,n)=>{if(null==t)return{};"object"!=typeof t&&(t={unknownAttribute:t});const i={};for(const[r,s]of Object.entries(t)){const t=(0,e.getOTELData)(r,s,0,n);for(const[e,n]of t)i[e]=n}return i};e.getOTELData=(e,t,r,s)=>{if((r+=1)>s)return[[e,"<depth exceeded>"]];const o=Boolean(t&&"object"==typeof t);return"number"==typeof t||"string"==typeof t||"boolean"==typeof t?[[e,t]]:i(t)?[[e,t]].concat(n(e,t,r,s)):o?n(e,t,r,s):"function"==typeof t?[]:t?[[e,t+""]]:[]};const n=(t,n,i,r)=>{const s=[];for(const[o,a]of Object.entries(n))for(const[n,c]of(0,e.getOTELData)(o,a,i,r))s.push([t+"."+n,c]);return s},i=e=>!!Array.isArray(e)&&e.every(e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e);e.deep_value=function(e,t){if(!t)return null;for(var n=0,i=(t=t.split(".")).length;n<i;n++){if(null==e)return;e=e[t[n]]}return e};e.extractFilteringContextFromArgs=(n,i,r)=>{let s={};return"function"==typeof n.thisMapping?s=Object.assign(Object.assign({},s),t.Container.errorless(()=>n.thisMapping.apply(r,[r]))):Object.keys(n.thisMapping||{}).forEach(t=>{if(!t||!n.thisMapping)return;const i=n.thisMapping[t];s[i]=(0,e.deep_value)(r,t)}),"function"==typeof n.argMapping?s=Object.assign(Object.assign({},s),t.Container.errorless(()=>n.argMapping.apply(r,i))):Object.keys(n.argMapping||{}).forEach(t=>{if(!t||!n.argMapping)return;const r=n.argMapping[t],o=(0,e.deep_value)(i,t);"string"!=typeof o&&"number"!=typeof o||(s[r]=o)}),s}}(tc)),tc}function sc(){if(Qa)return ec;Qa=1;var e=ec&&ec.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})},t=ec&&ec.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ec,"__esModule",{value:!0}),ec.withSpan=void 0;const n=rc(),i=oc(),r=t(Va());class s{static get instance(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:(s._instance||(s._instance=new i.NullTracesManager(void 0,void 0,void 0)),s._instance)}static set instance(e){s._instance=e}static get currentTracingState(){var e;return(null===(e=s.instance)||void 0===e?void 0:e.currentTracingState)||new r.default("unknown",null,!0)}static set currentTracingState(e){s.instance&&(s.instance.currentTracingState=e)}static removePropagationInfo(e){return s.extractPropagationInfo(e,!0),e}static extractPropagationInfo(e,t){if(null==e?void 0:e.traceparent)return e;const n=null==e?void 0:e.__interopIOTracePropagationInfo;return n?(!0===t&&delete e.__interopIOTracePropagationInfo,n):null}withSequenceSpanEx(t,n,i,r,o){return e(this,void 0,void 0,function*(){return s.instance.withSequenceSpanEx(t,n,i,r,o)})}withSequenceSpan(t,n,i,r){return e(this,void 0,void 0,function*(){return s.instance.withSequenceSpan(t,n,i,r)})}static withSpan(e,t,i,r,o){return t instanceof Function||t&&!t.argMapping&&!t.thisMapping&&!t.defaults||i||r||o?s.instance.withSpan(e,t,i,r,o):function(i,r,o){let a;a=o?o.value:i;let c=function(...i){return s.withSpan(e,t?(0,n.extractFilteringContextFromArgs)(t,i,this):{},null,t,()=>a.apply(this,i))};if(s.isAsyncFunction(a)){const e=c;c=function(...t){return e.apply(this,t)},Object.defineProperty(c,Symbol.toStringTag,{value:"AsyncFunction",configurable:!0})}if(!o)return c;o.value=c}}static isAsyncFunction(e){return e&&"[object AsyncFunction]"==={}.toString.call(e)}static withSpans(e,t){for(const n in e)if("function"==typeof t[n]){const i=t[n],r=e[n];if(!r)continue;let o;o="string"==typeof r?s.withSpan(r):s.withSpan(r.source,r.decoratorOptions),t[n]=o(i)}return t}}return ec.default=s,ec.withSpan=s.withSpan,ec}function oc(){if(Ya)return Ja;Ya=1;var e=Ja&&Ja.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})},t=Ja&&Ja.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.NullTracesManager=void 0;const n=t(Va()),i=t(sc()),r=Ma(),s=Fa();class o extends r.NullManager{get settings(){return this._settings||{}}set settings(e){this._settings=e}constructor(e,t,n){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==n||n.info(`Starting NullTracesManager with settings ${(0,s.safeStringify)(e)}`)),super(),this._settings=e,this.logger=n}withSequenceSpan(t,n,i,r){return e(this,void 0,void 0,function*(){return this.withSequenceSpanEx(t,t+".start",n,i,r)})}withSequenceSpanEx(t,n,i,r,s){return e(this,void 0,void 0,function*(){return this.withSpan(t,i,null,r,s)})}get currentTracingState(){return new n.default("nullTracingState",null,!0)}set currentTracingState(e){}waitForFinalExport(e){return Promise.resolve()}withSpan(e,t,r,s,o){const a="function"==typeof t?t:"function"==typeof r?r:"function"==typeof s?s:o;if(!a)throw new Error("callback must be provided");if("function"!=typeof a)throw new Error("Callback must be a function, received "+typeof a);const c=new n.default(e,null,!0);i.default.currentTracingState=c;try{return a(c)}finally{i.default.currentTracingState=null}}setFilterConfig(e){}get startupTraceFinished(){return()=>{}}get userJourneyMarker(){return()=>{}}setUserJourneyMarker(e){}get clickstreamMarker(){return()=>{}}}return Ja.NullTracesManager=o,Ja}var ac,cc={};var dc,lc={};function hc(){if(dc)return lc;dc=1,Object.defineProperty(lc,"__esModule",{value:!0}),lc.NullLogsManager=void 0;const e=Ma(),t=Fa();class n extends e.NullManager{constructor(e,n,i){!1!==(null==n?void 0:n.logSettingsOnStartup)&&(null==i||i.info(`Starting NullLogsManager with settings ${(0,t.safeStringify)(e)}`)),super()}emit(e){return null}}return lc.NullLogsManager=n,lc}var uc,pc={};var gc,fc={};var mc,bc,yc={};function wc(){if(bc)return Pa;bc=1,Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.Builder=void 0;const e=function(){if(Wa)return Oa;Wa=1,Object.defineProperty(Oa,"__esModule",{value:!0}),Oa.MetricsManagerBuilder=void 0;const e=qa(),t=Dc();return Oa.MetricsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}withMeterProvider(e){return this.meterProviderCreateFunc=e,this}withDependencyContainer(e){return this.dependencyContainer=e,this}build(){var e,t,n,i;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.metrics)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.metrics;const r=this.buildCore();return globalThis.ioInsightsInternals=null!==(n=globalThis.ioInsightsInternals)&&void 0!==n?n:{},globalThis.ioInsightsInternals.metrics&&!(null===(i=this.settings)||void 0===i?void 0:i.definitiveInstance)||(globalThis.ioInsightsInternals.metrics=r),r}buildCore(){var n,i,r,s;let o;return!0===(null===(n=this.settings)||void 0===n?void 0:n.enabled)&&!0===(null===(r=null===(i=this.settings)||void 0===i?void 0:i.metrics)||void 0===r?void 0:r.enabled)&&(o=(0,t.loadInsightsPlugin)("metrics",this.logger))?o.newMetricsManager(this.settings,this.dependencyContainer,this.meterProviderCreateFunc,this.logger):new e.NullMetricsManager(null===(s=this.settings)||void 0===s?void 0:s.metrics,this.settings,this.logger)}},Oa}(),t=function(){if(Xa)return Ga;Xa=1,Object.defineProperty(Ga,"__esModule",{value:!0}),Ga.TracesManagerBuilder=void 0;const e=oc(),t=Dc();return Ga.TracesManagerBuilder=class{constructor(){this.traceLogger=null}withLogger(e){return this.logger=e,this}withTraceLogger(e){return this.traceLogger=e,this}withSettings(e){return this.settings=e,this}withMetrics(e){return this.metrics=e,this}withTracerProvider(e){return this.tracerProvider=e,this}withContextManager(e){var t,n;return this.settings=null!==(t=this.settings)&&void 0!==t?t:{enabled:!1},this.settings.traces=null!==(n=this.settings.traces)&&void 0!==n?n:{enabled:!1},this.settings.traces.contextManager=()=>e,this.settings.traces.useOTELContextManager=!0,this}withPropagationInfoStorage(e,t){return this.store=e,this.read=t,this}build(){var e,t,n,i;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.traces;const r=this.buildCore();return globalThis.ioInsightsInternals=null!==(n=globalThis.ioInsightsInternals)&&void 0!==n?n:{},globalThis.ioInsightsInternals.traces&&!(null===(i=this.settings)||void 0===i?void 0:i.definitiveInstance)||(globalThis.ioInsightsInternals.traces=r),r}buildCore(){var n,i,r,s,o,a,c,d;let l;return this.settings.traces=null!==(n=this.settings.traces)&&void 0!==n?n:{enabled:!1},this.settings.traces.otlpExporterConfig=null!==(i=this.settings.traces.exporterSettings)&&void 0!==i?i:this.settings.traces.otlpExporterConfig,this.settings.traces.exporterSettings=null!==(r=this.settings.traces.exporterSettings)&&void 0!==r?r:this.settings.traces.otlpExporterConfig,!0===(null===(s=this.settings)||void 0===s?void 0:s.enabled)&&!0===(null===(a=null===(o=this.settings)||void 0===o?void 0:o.traces)||void 0===a?void 0:a.enabled)&&(l=(0,t.loadInsightsPlugin)("traces",this.logger))?l.newTracesManager(this.logger,this.settings,null!==(d=this.traceLogger)&&void 0!==d?d:this.logger,this.metrics,this.store,this.read):new e.NullTracesManager(null===(c=this.settings)||void 0===c?void 0:c.traces,this.settings,this.logger)}},Ga}(),n=(ac||(ac=1,Object.defineProperty(cc,"__esModule",{value:!0}),cc.NullLogger=void 0,cc.NullLogger=class{get level(){return 60}error(){}warn(){}info(){}debug(){}verbose(){}}),cc),i=ic(),r=qa(),s=oc(),o=hc(),a=(uc||(uc=1,Object.defineProperty(pc,"__esModule",{value:!0}),pc.Defaults=void 0,pc.Defaults={DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version"}),pc),c=(gc||(gc=1,Object.defineProperty(fc,"__esModule",{value:!0}),fc.LogWrapper=void 0,fc.LogWrapper=class{constructor(e,t){this.logger=e,this.dropLog=t}get level(){var e;return null!==(e=this.logger.level)&&void 0!==e?e:0}error(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,50,e))||this.logger.warn(e,...t)}warn(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,50,e))||this.logger.warn(e,...t)}info(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,60,e))||this.logger.info(e,...t)}debug(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,70,e))||this.logger.debug(e,...t)}verbose(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,80,e))||this.logger.verbose(e,...t)}}),fc),d=Dc(),l=Fa(),h=function(){if(mc)return yc;mc=1,Object.defineProperty(yc,"__esModule",{value:!0}),yc.LogsManagerBuilder=void 0;const e=Dc(),t=hc();return yc.LogsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}build(){var e,t,n,i;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.logs)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.logs;const r=this.buildCore();return globalThis.ioInsightsInternals=null!==(n=globalThis.ioInsightsInternals)&&void 0!==n?n:{},globalThis.ioInsightsInternals.logs&&!(null===(i=this.settings)||void 0===i?void 0:i.definitiveInstance)||(globalThis.ioInsightsInternals.logs=r),r}buildCore(){var n,i,r,s;let o;return!0===(null===(n=this.settings)||void 0===n?void 0:n.enabled)&&!0===(null===(r=null===(i=this.settings)||void 0===i?void 0:i.logs)||void 0===r?void 0:r.enabled)&&(o=(0,e.loadInsightsPlugin)("logs",this.logger))?o.newLogsManager(this.logger,this.settings.logs,this.settings):new t.NullLogsManager(null===(s=this.settings)||void 0===s?void 0:s.logs,this.settings,this.logger)}},yc}();class u{constructor(){this.logger=new n.NullLogger}withLogger(e){var t;e&&(this.logger=new c.LogWrapper(e,(e,t)=>{var n,i,r;return!(!(null===(n=this.settings)||void 0===n?void 0:n.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("@opentelemetry/api: Attempted duplicate registration of API"))||(!(!(null===(i=this.settings)||void 0===i?void 0:i.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will overwrite one already registered"))||!(!(null===(r=this.settings)||void 0===r?void 0:r.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will be overwritten")))}));const n=(0,d.loadInsightsPlugin)("base",this.logger);if(n)if(this.logger.level){const e=null===(t=this.logger.level)||void 0===t?void 0:t.valueOf();n.diag.setLogger(this.logger,e)}else n.diag.setLogger(this.logger,70);return this}withSettings(e){return this.settings=e,i.Container.settings=e,this}withMetrics(){return this.metricsBuilder=new e.MetricsManagerBuilder,this.metricsBuilder.withLogger(this.logger),this.metricsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.metricsBuilder}withTraces(){return this.tracesBuilder=new t.TracesManagerBuilder,this.tracesBuilder.withLogger(this.logger),this.tracesBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.tracesBuilder}withLogs(){return this.logsBuilder=new h.LogsManagerBuilder,this.logsBuilder.withLogger(this.logger),this.logsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.logsBuilder}build(){var e,t,n,c,h,p,g,f,m;this.settings=null!==(e=this.settings)&&void 0!==e?e:{enabled:!1};const b=Object.assign({enabled:!1},this.settings);if(!1!==(null===(t=this.settings)||void 0===t?void 0:t.logSettingsOnStartup)&&this.logger.info(`Starting interop.io OTEL with settings ${(0,l.safeStringify)(this.settings)}`),0==(null===(n=this.settings)||void 0===n?void 0:n.enabled)||!(0,d.loadInsightsPlugin)("base",this.logger))return new i.Container(b,new s.NullTracesManager(this.settings.traces,b,this.logger),new r.NullMetricsManager(this.settings.metrics,b,this.logger),new o.NullLogsManager(this.settings.logs,b,this.logger),this.logger);if((null===(h=null===(c=this.settings)||void 0===c?void 0:c.metrics)||void 0===h?void 0:h.enabled)&&(null===(p=this.settings)||void 0===p?void 0:p.metrics.platformMetricsEnabled)&&!this.metricsBuilder)throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");const y=this.settings.additionalResourceAttributes;this.settings.additionalResourceAttributes=()=>{var e,t,n,r,s,o,c,d,l,h,u,p,g,f,m,b,w,v,C,I,S,_,x,T;const k=null!==(e=i.Container.errorlessDefined(y,{}))&&void 0!==e?e:{};return Object.assign(Object.assign({},k),{user:null!==(s=null!==(r=null!==(t=k.userId)&&void 0!==t?t:null===(n=this.settings)||void 0===n?void 0:n.userId)&&void 0!==r?r:k["user.id"])&&void 0!==s?s:a.Defaults.DEFAULT_USER,"user.id":null!==(l=null!==(d=null!==(o=k.userId)&&void 0!==o?o:null===(c=this.settings)||void 0===c?void 0:c.userId)&&void 0!==d?d:k["user.id"])&&void 0!==l?l:a.Defaults.DEFAULT_USER,"service.name":null!==(g=null!==(p=null!==(h=k.serviceName)&&void 0!==h?h:null===(u=this.settings)||void 0===u?void 0:u.serviceName)&&void 0!==p?p:k["service.name"])&&void 0!==g?g:a.Defaults.DEFAULT_SERVICE_NAME,"service.instance.id":null!==(w=null!==(b=null!==(f=k.serviceId)&&void 0!==f?f:null===(m=this.settings)||void 0===m?void 0:m.serviceId)&&void 0!==b?b:k["service.instance.id"])&&void 0!==w?w:a.Defaults.DEFAULT_SERVICE_ID,"service.version":null!==(S=null!==(I=null!==(v=k.serviceVersion)&&void 0!==v?v:null===(C=this.settings)||void 0===C?void 0:C.serviceVersion)&&void 0!==I?I:k["service.version"])&&void 0!==S?S:a.Defaults.DEFAULT_SERVICE_VERSION,platformVersion:null!==(T=null!==(_=k.platformVersion)&&void 0!==_?_:null===(x=this.settings)||void 0===x?void 0:x.platformVersion)&&void 0!==T?T:a.Defaults.DEFAULT_PLATFORM_VERSION})},u.maybeAddResourceAttributesToAttributes(this.settings),u.maybeAddResourceAttributesToAttributes(this.settings.logs),u.maybeAddResourceAttributesToAttributes(this.settings.metrics),u.maybeAddResourceAttributesToAttributes(this.settings.traces),u.propagateAttributeDown("useSSOAuth",this.settings,this.settings.logs),u.propagateAttributeDown("useSSOAuth",this.settings,this.settings.metrics),u.propagateAttributeDown("useSSOAuth",this.settings,this.settings.traces),u.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.logs),u.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.metrics),u.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.traces),u.propagateAttributesDown("headers",this.settings,this.settings.logs),u.propagateAttributesDown("headers",this.settings,this.settings.metrics),u.propagateAttributesDown("headers",this.settings,this.settings.traces),u.propagateAttributesDown("additionalAttributes",this.settings,this.settings.logs),u.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.logs),u.propagateAttributesDown("additionalAttributes",this.settings,this.settings.metrics),u.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.metrics),u.propagateAttributesDown("additionalAttributes",this.settings,this.settings.traces),u.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.traces);const w=(null!==(g=this.metricsBuilder)&&void 0!==g?g:this.withMetrics()).withLogger(this.logger).withSettings(this.settings).build(),v=(null!==(f=this.tracesBuilder)&&void 0!==f?f:this.withTraces()).withLogger(this.logger).withSettings(this.settings).withMetrics(w).build();d.Traces.instance=v;const C=(null!==(m=this.logsBuilder)&&void 0!==m?m:this.withLogs()).withLogger(this.logger).withSettings(this.settings).build();return d.Logs.instance=C,new i.Container(b,v,w,C,this.logger)}static propagateAttributeDown(e,t,n){var i;n&&(n[e]=null!==(i=n[e])&&void 0!==i?i:t[e])}static propagateAttributesDown(e,t,n){var r,s;if(!n)return;const o=null!==(r=t[e])&&void 0!==r?r:{},a=null!==(s=n[e])&&void 0!==s?s:{};n[e]=()=>Object.assign(Object.assign({},i.Container.errorless(o)),i.Container.errorless(a))}static maybeAddResourceAttributesToAttributes(e){if(null==e?void 0:e.addResourceAttributesToAttributes){const t=e.additionalResourceAttributes,n=e.additionalAttributes;e.additionalAttributes=()=>Object.assign(Object.assign({},i.Container.errorless(t)),i.Container.errorless(n))}}}return Pa.Builder=u,Pa}var vc,Cc={};var Ic,Sc,_c={},xc={};function Tc(){if(Sc)return _c;Sc=1,Object.defineProperty(_c,"__esModule",{value:!0}),_c.MetricsDependencyBuilder=void 0;const e=(Ic||(Ic=1,Object.defineProperty(xc,"__esModule",{value:!0}),xc.NullPerformanceProvider=void 0,xc.NullPerformanceProvider=class{getAppsCPU(){return Promise.resolve(void 0)}getAppsMemory(){return Promise.resolve(void 0)}getSystemCPU(){return Promise.resolve(void 0)}getSystemMemory(){return Promise.resolve(void 0)}}),xc);return _c.MetricsDependencyBuilder=class{constructor(){this.performanceProvider=new e.NullPerformanceProvider,this.instanceFocusedHandler=()=>()=>{},this.instanceStartedHandler=()=>()=>{},this.instanceStoppedHandler=()=>()=>{},this.instanceReadyHandler=()=>()=>{},this.instanceErrorHandler=()=>()=>{},this.instanceCrashHandler=()=>()=>{},this.layoutRestoredHandler=()=>()=>{},this.platformStartedHandler=()=>()=>{},this.platformErrorHandler=()=>()=>{},this.workspaceLoadedHandler=()=>()=>{},this.workspaceRestoredHandler=()=>()=>{},this.workspaceSavedHandler=()=>()=>{},this.workspaceStoppedHandler=()=>()=>{},this.workspaceSelectedHandler=()=>()=>{},this.workspaceStartedHandler=()=>()=>{},this.workspaceFrameCreatedHandler=()=>()=>{},this.workspaceFrameInitHandler=()=>()=>{},this.workspaceFramePageLoadHandler=()=>()=>{},this.workspaceFrameWorkspaceRenderHandler=()=>()=>{},this.workspaceComponentCreatedHandler=()=>()=>{},this.workspaceAppsStartedHandler=()=>()=>{},this.workspaceStartupHandler=()=>()=>{}}build(){return{performanceProvider:this.performanceProvider,instanceStartedHandler:this.instanceStartedHandler,instanceStoppedHandler:this.instanceStoppedHandler,instanceReadyHandler:this.instanceReadyHandler,instanceFocusedHandler:this.instanceFocusedHandler,instanceErrorHandler:this.instanceErrorHandler,instanceCrashHandler:this.instanceCrashHandler,layoutRestoredHandler:this.layoutRestoredHandler,platformStartedHandler:this.platformStartedHandler,platformErrorHandler:this.platformErrorHandler,workspaceLoadedHandler:this.workspaceLoadedHandler,workspaceSavedHandler:this.workspaceSavedHandler,workspaceStoppedHandler:this.workspaceStoppedHandler,workspaceSelectedHandler:this.workspaceSelectedHandler,workspaceRestoredHandler:this.workspaceRestoredHandler,workspaceStartedHandler:this.workspaceStartedHandler,workspaceStartupHandler:this.workspaceStartupHandler,workspaceFrameCreatedHandler:this.workspaceFrameCreatedHandler,workspaceFrameInitHandler:this.workspaceFrameInitHandler,workspaceFramePageLoadHandler:this.workspaceFramePageLoadHandler,workspaceFrameWorkspaceRenderHandler:this.workspaceFrameWorkspaceRenderHandler,workspaceComponentCreatedHandler:this.workspaceComponentCreatedHandler,workspaceAppsStartedHandler:this.workspaceAppsStartedHandler}}withInstanceStartedHandler(e){return this.instanceStartedHandler=e,this}withInstanceStoppedHandler(e){return this.instanceStoppedHandler=e,this}withInstanceReadyHandler(e){return this.instanceReadyHandler=e,this}withInstanceFocusedHandler(e){return this.instanceFocusedHandler=e,this}withInstanceErrorHandler(e){return this.instanceErrorHandler=e,this}withInstanceCrashHandler(e){return this.instanceCrashHandler=e,this}withLayoutRestoredHandler(e){return this.layoutRestoredHandler=e,this}withWorkspaceLoadedHandler(e){return this.workspaceLoadedHandler=e,this}withWorkspaceSavedHandler(e){return this.workspaceSavedHandler=e,this}withWorkspaceStartedHandler(e){return this.workspaceRestoredHandler=()=>()=>{},this.workspaceStartedHandler=e,this}withWorkspaceStoppedHandler(e){return this.workspaceStoppedHandler=e,this}withWorkspaceSelectedHandler(e){return this.workspaceSelectedHandler=e,this}withPlatformStartedHandler(e){return this.platformStartedHandler=e,this}withPlatformErrorHandler(e){return this.platformErrorHandler=e,this}withPerfProvider(e){return this.performanceProvider=e,this}withWorkspaceRestoredHandler(e){return this.workspaceRestoredHandler=e,this.workspaceStartedHandler=()=>()=>{},this}withWorkspaceStartupHandler(e){return this.workspaceStartupHandler=e,this}withWorkspaceFrameCreatedHandler(e){return this.workspaceFrameCreatedHandler=e,this}withWorkspaceFrameInitHandler(e){return this.workspaceFrameInitHandler=e,this}withWorkspaceFramePageLoadHandler(e){return this.workspaceFramePageLoadHandler=e,this}withWorkspaceFrameWorkspaceRenderHandler(e){return this.workspaceFrameWorkspaceRenderHandler=e,this}withWorkspaceComponentCreatedHandler(e){return this.workspaceComponentCreatedHandler=e,this}withWorkspaceAppsStartedHandler(e){return this.workspaceAppsStartedHandler=e,this}},_c}var kc,Pc={};var Oc,Rc={};var Ac,Mc,Ec={};function Dc(){return Mc||(Mc=1,function(e){var t,n=ka&&ka.__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]}),i=ka&&ka.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=ka&&ka.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var s=t(e),o=0;o<s.length;o++)"default"!==s[o]&&n(r,e,s[o]);return i(r,e),r}),s=ka&&ka.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.SpanStatusCode=e.deep_value=e.extractFilteringContextFromArgs=e.getOTELData=e.flattenOtelAtributes=e.safeStringify=e.isNode=e.loadInsightsPlugin=e.registerInsightsPlugin=e.Logs=e.NullTracingState=e.OTEL_PI_KEY=e.withSpan=e.Traces=e.MetricsDependencyBuilder=e.NullMetric=e.Container=e.Log4jsWrapper=e.Builder=void 0;var o=wc();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return o.Builder}});var a=(vc||(vc=1,Object.defineProperty(Cc,"__esModule",{value:!0}),Cc.Log4jsWrapper=void 0,Cc.Log4jsWrapper=class{constructor(e){this.logger=e}get level(){return this.convert("level"in this.logger?this.logger.level:this.logger.publishLevel())}error(e,...t){this.logger.warn(e,...t)}warn(e,...t){this.logger.warn(e,...t)}info(e,...t){this.logger.info(e,...t)}debug(e,...t){this.logger.debug(e,...t)}verbose(e,...t){this.logger.trace(e,...t)}convert(e){if(void 0===e)return 60;switch("string"!=typeof e?e.levelStr.toLowerCase():e.toLowerCase()){case"off":return 0;case"error":return 30;case"warn":return 50;case"info":default:return 60;case"debug":return 70;case"trace":return 80}}}),Cc);Object.defineProperty(e,"Log4jsWrapper",{enumerable:!0,get:function(){return a.Log4jsWrapper}});var c=ic();Object.defineProperty(e,"Container",{enumerable:!0,get:function(){return c.Container}});var d=Ua();Object.defineProperty(e,"NullMetric",{enumerable:!0,get:function(){return d.NullMetric}});var l=Tc();Object.defineProperty(e,"MetricsDependencyBuilder",{enumerable:!0,get:function(){return l.MetricsDependencyBuilder}});const h=r(sc());e.Traces=h.default,Object.defineProperty(e,"withSpan",{enumerable:!0,get:function(){return h.withSpan}}),e.OTEL_PI_KEY="__interopIOTracePropagationInfo";const u=s(Va());e.NullTracingState=u.default;var p=function(){if(kc)return Pc;kc=1,Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.Logs=void 0;const e=hc();class t{static get instance(){var n,i;return(null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===n?void 0:n.logs)?null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===i?void 0:i.logs:(t._instance||(t._instance=new e.NullLogsManager(void 0,void 0,void 0)),t._instance)}static set instance(e){t._instance=e}static emit(e){return t.instance.emit(e)}}return Pc.Logs=t,Pc}();Object.defineProperty(e,"Logs",{enumerable:!0,get:function(){return p.Logs}});const g=function(){if(Oc)return Rc;Oc=1,Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.loadInsightsPlugin=function(t,n){if(void 0!==e.get(t))return e.get(t);if(void 0===globalThis.ioInsightsPlugins)return null;let i=globalThis.ioInsightsPlugins[t];if(!i)return null;if("function"==typeof i)try{i=i()}catch(i){return null==n||n.error(`Error loading io.Insights plugin ${t}`,i),e.set(t,null),null}return e.set(t,i),i},Rc.registerInsightsPlugin=function(e,t){void 0===globalThis.ioInsightsPlugins&&(globalThis.ioInsightsPlugins={}),globalThis.ioInsightsPlugins[e]=t};const e=new Map;return Rc}();Object.defineProperty(e,"registerInsightsPlugin",{enumerable:!0,get:function(){return g.registerInsightsPlugin}}),Object.defineProperty(e,"loadInsightsPlugin",{enumerable:!0,get:function(){return g.loadInsightsPlugin}});const f=function(){if(Ac)return Ec;let e;return Ac=1,Object.defineProperty(Ec,"__esModule",{value:!0}),Ec.isNode=function(){if(void 0!==e)return e;if("undefined"!=typeof window)return e=!1,!1;try{e="[object process]"===Object.prototype.toString.call(No.process)}catch(t){e=!1}return e},Ec}();Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return f.isNode}});const m=Fa();Object.defineProperty(e,"safeStringify",{enumerable:!0,get:function(){return m.safeStringify}});const b=rc();var y;Object.defineProperty(e,"getOTELData",{enumerable:!0,get:function(){return b.getOTELData}}),Object.defineProperty(e,"flattenOtelAtributes",{enumerable:!0,get:function(){return b.flattenOtelAtributes}}),Object.defineProperty(e,"extractFilteringContextFromArgs",{enumerable:!0,get:function(){return b.extractFilteringContextFromArgs}}),Object.defineProperty(e,"deep_value",{enumerable:!0,get:function(){return b.deep_value}}),"undefined"!=typeof Promise&&(Promise.allSettled=Promise.allSettled||(e=>Promise.all(e.map(e=>e.then(e=>({status:"fulfilled",value:e})).catch(e=>({status:"rejected",reason:e})))))),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(y||(e.SpanStatusCode=y={}))}(ka)),ka}var jc=Dc();function Nc(e,t,n){let i;if(Uo.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=Zo(10);return Uo.isNode()?i?i.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const s=function(){const s=e.gateway,o=s?.protocolVersion??3,a=s?.reconnectInterval,c=s?.reconnectAttempts;let d=s?.ws;const l=s?.sharedWorker,h=s?.inproc,u=s?.webPlatform??void 0;let p,g,f,m,b;n&&(d=n.gwURL),Uo.isNode()&&i&&i.gwURL&&(d=i.gwURL),d||l||h||(d="ws://localhost:8385");const y=r();let w=y;void 0!==n?(g=n.windowId,f=n.pid,n.env&&(m=n.env.env,b=n.env.region),w=n.application??"glue-app",p=n.appInstanceId):Uo.isNode()?(f=process.pid,i&&(m=i.env,b=i.region,p=i.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,f=window?.glue42electron.pid,m=window?.glue42electron.env,b=window?.glue42electron.region,w=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(ya);let C={application:w,applicationName:y,windowId:g,instance:p,process:f,region:b,environment:m,api:t.version||Ca};return e.identity&&(C=Object.assign(C,e.identity)),{identity:C,reconnectInterval:a,ws:d,sharedWorker:l,webPlatform:u,inproc:h,protocolVersion:o,reconnectAttempts:c,replaySpecs:v}}();let o=r();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(o=t)}return{bus:e.bus??!1,application:o,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Uo.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:s,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||Ca,libs:t.libs??[],customLogger:e.customLogger,getInsights:async function(r,s,o){const a=e.insights;if("object"!=typeof a&&"boolean"!=typeof a&&void 0!==a)throw new Error("insights/otel property should be boolean, object or unspecified");if(!1===a)return{enabled:!1};let c,d;return r?c=r.insights:Uo.isNode()&&!1!==e?.insights&&!1!==e?.insights?.enabled&&!1!==e?.insights?.requestSettings&&(c=await(s?.invoke("T42.Otel.GetConfig",void 0,i?{environment:i.env,region:i.region}:void 0,{waitTimeoutMs:0}).then(e=>e.returned).catch(e=>o?.warn("Unable to retrieve base io.Insights settings: "+(e?.message??e))))),c&&(r||i||Uo.isNode()&&("boolean"==typeof a||!a?.platformInstance))&&(c={...c,metrics:{...c?.metrics,enabled:!!c?.metrics?.enabled,platformMetricsEnabled:!1}}),d=!0===a||void 0===a?c??{enabled:!1}:Ta(c||{},a,{isMergeableObject:Sa}),function(e,t,n,i){let r=e.applicationName??"unknown-app";n&&(r=e.applicationName??n?.appName??r),i&&(r=e.applicationName??i.applicationConfig.name??r),e.applicationName=r,e.traces?.closeTrace&&n?.addCloseHandler(()=>jc.Traces.withSpan("interopio.api.application.close",()=>{}));const s=n?.sid,o=n?.user,a=(Uo.isNode()&&process?.env?.USERNAME)??n?.env?.windowsUserName,c=(Uo.isNode()&&process?.env?.COMPUTERNAME)??n?.env?.machineName,d=i?.env??n?.env?.env,l=i?.region??n?.env?.region,h=i?.instanceId??n?.appInstanceId??"",u=n?.windowId,p={interopioCoreVersion:Ca,interopioLibVersion:t.version||Ca,host:"io.api",tracingAppName:r,tracingAppInstanceId:h,user:o,osUser:a,machine:c,env:d,region:l,windowId:u,sid:s};let g=e.additionalResourceAttributes;if("function"!=typeof g){const t=e.additionalResourceAttributes;g=()=>t}e.additionalResourceAttributes=()=>({...p,...g()})}(d,t,n,i),d.traces?.enabled&&function(e){e.traces&&(e.traces.defaultFilters??=[],e.traces.defaultFilters.push({source:"interopio.api.instrumentation.fetch",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.instrumentation.xhr",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.prefs",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.layouts",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.windows",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"apps.command"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"___insights_pi_storage___"},enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^__.*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.appManager",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.notifications",canBeRoot:!1}))}(d),d}}}function Fc(e,t,n,i){var r,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,n,o):r(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}"function"==typeof SuppressedError&&SuppressedError;class Lc{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 qo}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 qo}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var $c,Wc={exports:{}};var Hc=($c||($c=1,function(e,t){var n="__lodash_hash_undefined__",i=9007199254740991,r="[object Arguments]",s="[object Boolean]",o="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",l="[object Number]",h="[object Object]",u="[object Promise]",p="[object RegExp]",g="[object Set]",f="[object String]",m="[object Symbol]",b="[object WeakMap]",y="[object ArrayBuffer]",w="[object DataView]",v="[object Float32Array]",C="[object Float64Array]",I="[object Int8Array]",S="[object Int16Array]",_="[object Int32Array]",x="[object Uint8Array]",T="[object Uint8ClampedArray]",k="[object Uint16Array]",P="[object Uint32Array]",O=/\w*$/,R=/^\[object .+?Constructor\]$/,A=/^(?:0|[1-9]\d*)$/,M={};M[r]=M["[object Array]"]=M[y]=M[w]=M[s]=M[o]=M[v]=M[C]=M[I]=M[S]=M[_]=M[d]=M[l]=M[h]=M[p]=M[g]=M[f]=M[m]=M[x]=M[T]=M[k]=M[P]=!0,M["[object Error]"]=M[a]=M[b]=!1;var E="object"==typeof No&&No&&No.Object===Object&&No,D="object"==typeof self&&self&&self.Object===Object&&self,j=E||D||Function("return this")(),N=t&&!t.nodeType&&t,F=N&&e&&!e.nodeType&&e,L=F&&F.exports===N;function $(e,t){return e.set(t[0],t[1]),e}function W(e,t){return e.add(t),e}function H(e,t,n,i){for(var r=-1,s=e?e.length:0;++r<s;)n=t(n,e[r],r,e);return n}function U(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function q(e){var t=-1,n=Array(e.size);return e.forEach(function(e,i){n[++t]=[i,e]}),n}function B(e,t){return function(n){return e(t(n))}}function G(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}var J,z=Array.prototype,V=Function.prototype,K=Object.prototype,Z=j["__core-js_shared__"],Q=(J=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Y=V.toString,X=K.hasOwnProperty,ee=K.toString,te=RegExp("^"+Y.call(X).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=L?j.Buffer:void 0,ie=j.Symbol,re=j.Uint8Array,se=B(Object.getPrototypeOf,Object),oe=Object.create,ae=K.propertyIsEnumerable,ce=z.splice,de=Object.getOwnPropertySymbols,le=ne?ne.isBuffer:void 0,he=B(Object.keys,Object),ue=Fe(j,"DataView"),pe=Fe(j,"Map"),ge=Fe(j,"Promise"),fe=Fe(j,"Set"),me=Fe(j,"WeakMap"),be=Fe(Object,"create"),ye=Ue(ue),we=Ue(pe),ve=Ue(ge),Ce=Ue(fe),Ie=Ue(me),Se=ie?ie.prototype:void 0,_e=Se?Se.valueOf:void 0;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 Te(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 Pe(e){this.__data__=new Te(e)}function Oe(e,t){var n=Be(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ge(e)}(e)&&X.call(e,"callee")&&(!ae.call(e,"callee")||ee.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,s=!!i;for(var o in e)!X.call(e,o)||s&&("length"==o||We(o,i))||n.push(o);return n}function Re(e,t,n){var i=e[t];X.call(e,t)&&qe(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Ae(e,t){for(var n=e.length;n--;)if(qe(e[n][0],t))return n;return-1}function Me(e,t,n,i,u,b,R){var A;if(i&&(A=b?i(e,u,b,R):i(e)),void 0!==A)return A;if(!Ve(e))return e;var E=Be(e);if(E){if(A=function(e){var t=e.length,n=e.constructor(t);return t&&"string"==typeof e[0]&&X.call(e,"index")&&(n.index=e.index,n.input=e.input),n}(e),!t)return function(e,t){var n=-1,i=e.length;for(t||(t=Array(i));++n<i;)t[n]=e[n];return t}(e,A)}else{var D=$e(e),j=D==a||D==c;if(Je(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(D==h||D==r||j&&!b){if(U(e))return b?e:{};if(A=function(e){return"function"!=typeof e.constructor||He(e)?{}:Ve(t=se(e))?oe(t):{};var t}(j?{}:e),!t)return function(e,t){return je(e,Le(e),t)}(e,function(e,t){return e&&je(t,Ke(t),e)}(A,e))}else{if(!M[D])return b?e:{};A=function(e,t,n,i){var r,a=e.constructor;switch(t){case y:return De(e);case s:case o:return new a(+e);case w:return function(e,t){var n=t?De(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case v:case C:case I:case S:case _:case x:case T:case k:case P:return function(e,t){var n=t?De(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(q(e),!0):q(e);return H(i,$,new e.constructor)}(e,i,n);case l:case f:return new a(e);case p:return function(e){var t=new e.constructor(e.source,O.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(G(e),!0):G(e);return H(i,W,new e.constructor)}(e,i,n);case m:return r=e,_e?Object(_e.call(r)):{}}}(e,D,Me,t)}}R||(R=new Pe);var N=R.get(e);if(N)return N;if(R.set(e,A),!E)var F=n?function(e){return function(e,t,n){var i=t(e);return Be(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,Ke,Le)}(e):Ke(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(F||e,function(r,s){F&&(r=e[s=r]),Re(A,s,Me(r,t,n,i,s,e,R))}),A}function Ee(e){return!(!Ve(e)||(t=e,Q&&Q in t))&&(ze(e)||U(e)?te:R).test(Ue(e));var t}function De(e){var t=new e.constructor(e.byteLength);return new re(t).set(new re(e)),t}function je(e,t,n,i){n||(n={});for(var r=-1,s=t.length;++r<s;){var o=t[r];Re(n,o,e[o])}return n}function Ne(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 Fe(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Ee(n)?n:void 0}xe.prototype.clear=function(){this.__data__=be?be(null):{}},xe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},xe.prototype.get=function(e){var t=this.__data__;if(be){var i=t[e];return i===n?void 0:i}return X.call(t,e)?t[e]:void 0},xe.prototype.has=function(e){var t=this.__data__;return be?void 0!==t[e]:X.call(t,e)},xe.prototype.set=function(e,t){return this.__data__[e]=be&&void 0===t?n:t,this},Te.prototype.clear=function(){this.__data__=[]},Te.prototype.delete=function(e){var t=this.__data__,n=Ae(t,e);return!(n<0||(n==t.length-1?t.pop():ce.call(t,n,1),0))},Te.prototype.get=function(e){var t=this.__data__,n=Ae(t,e);return n<0?void 0:t[n][1]},Te.prototype.has=function(e){return Ae(this.__data__,e)>-1},Te.prototype.set=function(e,t){var n=this.__data__,i=Ae(n,e);return i<0?n.push([e,t]):n[i][1]=t,this},ke.prototype.clear=function(){this.__data__={hash:new xe,map:new(pe||Te),string:new xe}},ke.prototype.delete=function(e){return Ne(this,e).delete(e)},ke.prototype.get=function(e){return Ne(this,e).get(e)},ke.prototype.has=function(e){return Ne(this,e).has(e)},ke.prototype.set=function(e,t){return Ne(this,e).set(e,t),this},Pe.prototype.clear=function(){this.__data__=new Te},Pe.prototype.delete=function(e){return this.__data__.delete(e)},Pe.prototype.get=function(e){return this.__data__.get(e)},Pe.prototype.has=function(e){return this.__data__.has(e)},Pe.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Te){var i=n.__data__;if(!pe||i.length<199)return i.push([e,t]),this;n=this.__data__=new ke(i)}return n.set(e,t),this};var Le=de?B(de,Object):function(){return[]},$e=function(e){return ee.call(e)};function We(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||A.test(e))&&e>-1&&e%1==0&&e<t}function He(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||K)}function Ue(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function qe(e,t){return e===t||e!=e&&t!=t}(ue&&$e(new ue(new ArrayBuffer(1)))!=w||pe&&$e(new pe)!=d||ge&&$e(ge.resolve())!=u||fe&&$e(new fe)!=g||me&&$e(new me)!=b)&&($e=function(e){var t=ee.call(e),n=t==h?e.constructor:void 0,i=n?Ue(n):void 0;if(i)switch(i){case ye:return w;case we:return d;case ve:return u;case Ce:return g;case Ie:return b}return t});var Be=Array.isArray;function Ge(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}(e.length)&&!ze(e)}var Je=le||function(){return!1};function ze(e){var t=Ve(e)?ee.call(e):"";return t==a||t==c}function Ve(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ke(e){return Ge(e)?Oe(e):function(e){if(!He(e))return he(e);var t=[];for(var n in Object(e))X.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Me(e,!0,!0)}}(Wc,Wc.exports)),Wc.exports),Uc=Fo(Hc);function qc(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=Bc(e,void 0),t.commands){for(const n of t.commands)"remove"===n.type?Kc(e,n.path):"set"===n.type&&zc(e,n.value,n.path);return e}const i=t.added,r=t.updated,s=t.removed;return i&&Object.keys(i).forEach(t=>{e[t]=i[t]}),r&&Object.keys(r).forEach(t=>{Gc(t,e,r)}),s&&s.forEach(t=>{delete e[t]}),jc.Traces.removePropagationInfo(e),e}catch(i){return n?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,i),e}}function Bc(e,t){return Uc(e)}const Gc=(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 Jc(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(!Jc(e[n],t[n]))return!1}}for(const n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function zc(e,t,n){const i=n.split("."),r=["__proto__","constructor","prototype"];let s;for(s=0;s<i.length-1;s++){const t=i[s];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[s]]=t}function Vc(e,t){return Object.keys(t).every(n=>"object"==typeof t[n]?Vc(e?.[n]||{},t[n]||{}):t[n]===e?.[n])}function Kc(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]]}class Zc{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",[ca,ha,ga,ma]),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(ya.name,e=>{const t=e.type;t&&(t===ca||t===da||t===oa?this.handleContextCreatedMessage(e):t===ha||t===ma||t===ba?this.handleContextUpdatedMessage(e):t!==ga&&t!==aa||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){if(e in this._creationPromises)return this._creationPromises[e];const n=jc.Traces.currentTracingState;return n.addData("INFO",{context:e}),n.addData("DIAGNOSTIC",{data:t}),t=Bc(t),n.injectPropagationInfo(t),this._creationPromises[e]=this._gw3Session.send({type:sa,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 Lc(n.context_id,e,!0,void 0);return i.isAnnounced=!0,i.name=e,i.contextId=n.context_id,i.context=n.data||Bc(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=Bc(t));const n=jc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],jc.Traces.currentTracingState=n);const i=this._contextNameToData[e];if(n.addData("DIAGNOSTIC",{data:i}),n.addData("DEBUG",{delta:t}),!i||!i.isAnnounced)return void await this.createContext(e,t);const r=await this.get(i.name);jc.Traces.currentTracingState=n,jc.Traces.removePropagationInfo(r);const s=this.setPathSupported?this.calculateContextDeltaV2(r,t):this.calculateContextDeltaV1(r,t);if(!(Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||s.commands?.length))return Promise.resolve();const o=Bc(s);n.injectPropagationInfo(o);const a=await this._gw3Session.send({type:fa,domain:"global",context_id:i.contextId,delta:o},{},{skipPeerId:!1});jc.Traces.currentTracingState=n,!this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId)&&(await i.snapshotPromise,jc.Traces.currentTracingState=n,this.handleUpdated(i,s,{updaterId:a.peer_id}))}async set(e,t){t&&(t=Bc(t));const n=jc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],jc.Traces.currentTracingState=n);const i=this._contextNameToData[e];if(n.addData("DIAGNOSTIC",{data:i}),n.injectPropagationInfo(t),!i||!i.isAnnounced)return this.createContext(e,t);const r=await this._gw3Session.send({type:fa,domain:"global",context_id:i.contextId,delta:{reset:t}},{},{skipPeerId:!1});jc.Traces.currentTracingState=n,!this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId)&&this.handleUpdated(i,{reset:t,added:{},removed:[],updated:{}},{updaterId:r.peer_id})}setPath(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject(new Error("contexts.setPath operation is not supported, use version 3.10 or later"))}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject(new Error("contexts.setPaths operation is not supported, use version 3.10 or later"));t&&(t=Bc(t));const n=jc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],jc.Traces.currentTracingState=n);const i=this._contextNameToData[e];n.addData("DIAGNOSTIC",{data:i}),n.addData("DEBUG",{pathValues:t});const r={[jc.OTEL_PI_KEY]:void 0};if(n.injectPropagationInfo(r),r[jc.OTEL_PI_KEY]&&t.push({path:jc.OTEL_PI_KEY,value:r[jc.OTEL_PI_KEY]}),!i||!i.isAnnounced){const n={};for(const e of t)zc(n,e.value,e.path);return this.createContext(e,n)}const s=[];for(const e of t)null===e.value?s.push({type:"remove",path:e.path}):s.push({type:"set",path:e.path,value:e.value});const o=await this._gw3Session.send({type:fa,domain:"global",context_id:i.contextId,delta:{commands:s}},{},{skipPeerId:!1});jc.Traces.currentTracingState=n,!this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId)&&(await i.snapshotPromise,jc.Traces.currentTracingState=n,this.handleUpdated(i,{added:{},removed:[],updated:{},commands:s},{updaterId:o.peer_id}))}async get(e){const t=jc.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],jc.Traces.currentTracingState=t);const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return!n&&this._subscribeOnGet&&this.subscribeInner(e,()=>{}),Promise.resolve({});if(n&&!n.sentExplicitSubscription)return new Promise((t,n)=>{this.subscribeInner(e,(e,n,i,r)=>{jc.Traces.removePropagationInfo(e),this._subscribeOnGet||this.unsubscribe(r),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):n(e)})});await n.snapshotPromise;const i=n?.context??{};return jc.Traces.removePropagationInfo(i),Promise.resolve(Bc(i))}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 subscribeInner(e,t,n){const i=jc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],jc.Traces.currentTracingState=i);const r=void 0===n?this._nextCallbackSubscriptionNumber:n;void 0===n&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:r,callback:t}));let s=this._contextNameToData[e];if(!s||!s.isAnnounced)return s=s||new Lc(void 0,e,!1,void 0),this._contextNameToData[e]=s,s.updateCallbacks[r]=t,Promise.resolve(r);const o=s.hasCallbacks();if(s.updateCallbacks[r]=t,o){if(s.hasReceivedSnapshot&&!n){const e=Bc(s.context);t(e,e,[],r)}return Promise.resolve(r)}if(s.joinedActivity||s.createdByUs){if(s.hasReceivedSnapshot&&!n){const e=Bc(s.context);t(e,e,[],r)}return Promise.resolve(r)}if(s.context&&s.sentExplicitSubscription){if(s.hasReceivedSnapshot&&!n){const e=Bc(s.context);t(e,e,[],r)}return Promise.resolve(r)}return this.sendSubscribe(s).then(()=>r,()=>(this.unsubscribe(r,!0),r))}async subscribe(e,t,n){const i=this.all().includes(e);jc.Traces.currentTracingState.addData("INFO",{context:e,contextExists:i});return this.subscribeInner(e,async(...n)=>jc.withSpan("interopio.api.contexts.bridge.subscribe.callback",{context:e},n?.[5],i=>(jc.Traces.removePropagationInfo(n?.[0]),jc.Traces.removePropagationInfo(n?.[1]),i.addData("INFO",{context:e}),i.addData("DEBUG",{delta:n?.[1]}),i.addData("DEBUG",{removed:n?.[2]}),i.addData("DIAGNOSTIC",{data:n?.[0]}),t(n?.[0],n?.[1],n?.[2],n?.[3],n?.[4]))),n)}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){const t=jc.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],jc.Traces.currentTracingState=t);const n=this._contextNameToData[e],i=n?.contextId;return n&&i?this._gw3Session.send({type:pa,domain:"global",context_id:n.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,n){const i=e.context;e.context=qc(e.context,t,this._logger),this._contextNameToData[e.name]!==e||Jc(i,e.context)||this.invokeUpdateCallbacks(e,t,n)}subscribeToContextCreatedMessages(){const e=[da,ca,oa];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===oa?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===da&&(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]=new Lc(e.context_id,n,!0,e.activity_id),this._trackAllContexts&&this.subscribe(n,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[ma,ha,ba];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===ba)i||(i=this._contextNameToData[e.activity_id]||new Lc(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===ha?(i=i||new Lc(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 s=i.context;if(i.hasReceivedSnapshot=!0,t===ha)i.context=e.data??{};else if(t===ba)i.context=e.context_snapshot??{};else{if(t!==ma)throw new Error("Unrecognized context update message "+t);i.context=qc(i.context,e.delta,this._logger)}!r&&Jc(i.context,s)&&t!==ha||this.invokeUpdateCallbacks(i,e.delta??e.data,{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),zc(t.updated,null,e.path)):"set"===e.type&&zc(t.updated,e.value,e.path)}for(const i in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(i))try{const r=e.updateCallbacks[i],s=Bc({...t.added,...t.updated,...t.reset});r(Bc(e.context),s,t.removed,parseInt(i,10),n,jc.Traces.extractPropagationInfo(t))}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[ga,aa];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===aa){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:la,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:ua,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]||Jc(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]){Jc(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(ya.name,e=>{const t=e.type;t&&(t===ca||t===da||t===oa?this.handleContextCreatedMessage(e):t===ha||t===ma||t===ba?this.handleContextUpdatedMessage(e):t!==ga&&t!==aa||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))}}Fc([jc.withSpan("interopio.api.contexts.bridge.create",{argMapping:["context"]})],Zc.prototype,"createContext",null),Fc([jc.withSpan("interopio.api.contexts.bridge.update",{argMapping:["context"]})],Zc.prototype,"update",null),Fc([jc.withSpan("interopio.api.contexts.bridge.set",{argMapping:["context"]})],Zc.prototype,"set",null),Fc([jc.withSpan("interopio.api.contexts.bridge.setPaths",{argMapping:["context"]})],Zc.prototype,"setPaths",null),Fc([jc.withSpan("interopio.api.contexts.bridge.get",{argMapping:["context"]})],Zc.prototype,"get",null),Fc([jc.withSpan("interopio.api.contexts.bridge.subscribe",{argMapping:["context"]})],Zc.prototype,"subscribe",null),Fc([jc.withSpan("interopio.api.contexts.bridge.destroy",{argMapping:["context"]})],Zc.prototype,"destroy",null);class Qc{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new Zc(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,s)=>t(e,n,i,()=>this._bridge.unsubscribe(r),s)).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 Yc(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n))}function Xc(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)})}Fc([jc.withSpan("interopio.api.contexts.module.update",{argMapping:["context"]})],Qc.prototype,"update",null),Fc([jc.withSpan("interopio.api.contexts.module.set",{argMapping:["context"]})],Qc.prototype,"set",null),Fc([jc.withSpan("interopio.api.contexts.module.setPaths",{argMapping:["context"]})],Qc.prototype,"setPaths",null),Fc([jc.withSpan("interopio.api.contexts.module.subscribe",{argMapping:["context"]})],Qc.prototype,"subscribe",null),Fc([jc.withSpan("interopio.api.contexts.module.destroy",{argMapping:["context"]})],Qc.prototype,"destroy",null);var ed=function(e){return{ok:!0,result:e}},td=function(e){return{ok:!1,error:e}},nd=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:ed(e(t.result,n.result))},id=function(e,t){return!0===t.ok?t:td(e(t.error))},rd=function(){return rd=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},rd.apply(this,arguments)};function sd(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(!sd(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(!sd(e[i[n]],t[i[n]]))return!1}return!0}}var od=function(e){return Array.isArray(e)},ad=function(e){return"object"==typeof e&&null!==e&&!od(e)},cd=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)},dd=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},ld=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 rd({at:e+(n||"")},i)},hd=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return id(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?ed(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?ed(e):td({message:cd("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?ed(e):td({message:cd("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?ed(e):td({message:cd("a boolean",e)})})},e.constant=function(t){return new e(function(e){return sd(e,t)?ed(t):td({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(ad(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]?td({message:"the key '"+i+"' is required but was not present"}):td(ld("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return ed(n)}return ad(e)?ed(e):td({message:cd("an object",e)})})},e.array=function(t){return new e(function(e){if(od(e)&&t){return e.reduce(function(e,n,i){return nd(function(e,t){return e.concat([t])},e,function(e,n){return id(function(e){return ld("["+n+"]",e)},t.decode(e))}(n,i))},ed([]))}return od(e)?ed(e):td({message:cd("an array",e)})})},e.tuple=function(t){return new e(function(e){if(od(e)){if(e.length!==t.length)return td({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 td(ld("["+i+"]",r.error));n[i]=r.result}return ed(n)}return td({message:cd("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 nd(Object.assign,t,n.decode(e))},ed({}))})},e.anyJson=function(){return new e(function(e){return ed(e)})},e.unknownJson=function(){return new e(function(e){return ed(e)})},e.dict=function(t){return new e(function(e){if(ad(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return td(ld("."+i,r.error));n[i]=r.result}return ed(n)}return td({message:cd("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?ed(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 s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return td({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return ed(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 td({at:dd(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!ad(i))return td({at:dd(t.slice(0,r+1)),message:cd("an object",i)});if("number"==typeof t[r]&&!od(i))return td({at:dd(t.slice(0,r+1)),message:cd("an array",i)});i=i[t[r]]}return id(function(e){return void 0===i?{at:dd(t),message:"path does not exist"}:ld(dd(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return ed(t)})},e.fail=function(t){return new e(function(e){return td({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),ud=hd.string,pd=hd.number,gd=hd.boolean,fd=hd.anyJson;hd.unknownJson;var md=hd.constant,bd=hd.object,yd=hd.array;hd.tuple,hd.dict;var wd=hd.optional;hd.oneOf;var vd=hd.union;hd.intersection,hd.withDefault,hd.valueAt,hd.succeed;var Cd=hd.fail;hd.lazy;const Id=(e,t)=>{const n=typeof e;return"function"===n?fd():Cd(`The provided argument as ${t} should be of type function, provided: ${n}`)},Sd=ud().where(e=>e.length>0,"Expected a non-empty string"),_d=pd().where(e=>e>=0,"Expected a non-negative number or 0"),xd=vd(Sd,bd({name:Sd,objectTypes:wd(yd(Sd)),displayName:wd(ud()),accepts:wd(ud()),returns:wd(ud()),description:wd(ud()),version:wd(_d),supportsStreaming:wd(gd()),flags:wd(bd()),getServers:wd(fd().andThen(e=>Id(e,"method definition getServers")))})),Td=bd({application:wd(Sd),applicationName:wd(Sd),pid:wd(_d),machine:wd(Sd),user:wd(Sd),environment:wd(Sd),region:wd(Sd),service:wd(Sd),instance:wd(Sd),windowId:wd(Sd),peerId:wd(Sd),isLocal:wd(gd()),api:wd(Sd),getMethods:wd(fd().andThen(e=>Id(e,"instance getMethods"))),getStreams:wd(fd().andThen(e=>Id(e,"instance getStreams")))}),kd=vd(md("best"),md("all"),md("skipMine"),Td,yd(Td)),Pd=bd({waitTimeoutMs:wd(_d),methodResponseTimeoutMs:wd(_d)});var Od;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Od||(Od={}));class Rd{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 s=jc.Traces.currentTracingState;s.addData("INFO",{stream:Uo.getMethodName(e)}),s.addData("INFO",{options:t});const o=(e,n,i,s)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(n,t,e,i,s,r)},a=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,l=this.getServerMethodsByFilterAndTarget(a,c);if(l.length>0)o(l,l[0].methods[0],r,s);else{const n=()=>{if(c&&t.waitTimeoutMs)if(d+=500,l=this.getServerMethodsByFilterAndTarget(a,c),l.length>0){const e=l[0].methods[0];o(l,e,r,s)}else if(d>=t.waitTimeoutMs){o(l,"string"==typeof e?{name:e}:e,r,s)}else setTimeout(n,500)};setTimeout(n,500)}});return Yc(a,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,s){const o=jc.Traces.currentTracingState;o.addData("INFO",{method:Uo.getMethodName(e)}),o.addData("INFO",{target:n,additionalOptions:i}),o.addData("DIAGNOSTIC",{arguments:t});return Yc((async()=>{const o="string"==typeof e?{name:e}:{...e};t||(t={}),n||(n="best"),i||(i={});const a=xd.run(o);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,o,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,o,t))}const c=kd.run(n);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,o,t))}const d=Pd.run(i);if(!d.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(d.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,o,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,o,t))}if(s&&"function"!=typeof s){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,o,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 l=this.getServerMethodsByFilterAndTarget(o,n);if(0===l.length)try{l=await this.tryToAwaitForMethods(o,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,o,t))}const h=i.methodResponseTimeoutMs??3e4,u=i,p=l.map(e=>this.getServerInvokePromise(e.methods[0],e.server,t,u,h)),g=await Promise.all(p),f=this.getInvocationResultObj(g,o,t);return g.every(e=>e.status===Od.Error)?Promise.reject(f):f})(),r,s)}async getServerInvokePromise(e,t,n,i,r){const s=Zo(10),o=jc.Traces.currentTracingState;n&&(n=Bc(n),o.injectPropagationInfo(n)),o.addData("INFO",{server:t?.id,instance:t?.instance}),o.addData("INFO",{invocationId:s});const a=this.protocol.client.invoke(s,e,n,t,i),c=await Promise.race([a,Xc(r,a,{invocationId:s,message:`Invocation timeout (${r} ms) reached for method name: ${e?.name}, target instance: ${JSON.stringify(t.instance)}, options: ${JSON.stringify(i)}`,status:Od.Error})]);return o.addData("DIAGNOSTIC",{returnValue:c}),c}generateInvalidInputInvocationResult(e,t,n){const i={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},r={invocationId:Zo(10),status:Od.Error,message:e};return this.getInvocationResultObj([r],i,n)}getInvocationResultObj(e,t,n){jc.Traces.removePropagationInfo(n);const i=e.filter(e=>e.status===Od.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===Od.Error).reduce((e,i)=>e=[...e,{executed_by:i.instance,called_with:n,name:t.name,message:i.message}],[]),s=e[0];return{method:t,called_with:n,returned:s.result,executed_by:s.instance,all_return_values:i,all_errors:r,message:s.message,status:s.status}}tryToAwaitForMethods(e,t,n){return new Promise((i,r)=>{if(0===n.waitTimeoutMs)return void r();let s=0;const o=setInterval(()=>{s+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(o),i(a);else if(s>=(n.waitTimeoutMs||1e4))return clearInterval(o),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],s=t[n];switch(n){case"objectTypes":i=(r||[]).every(e=>(s||[]).includes(e));break;case"flags":i=Vc(s||{},r||{});break;default:i=String(r).toLowerCase()===String(s).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)}}Fc([jc.withSpan("interopio.api.interop.stream.subscribe",{argMapping:e=>({stream:Uo.getMethodName(e)})})],Rd.prototype,"subscribe",null),Fc([jc.withSpan("interopio.api.interop.invoke",{argMapping:e=>({method:Uo.getMethodName(e)})})],Rd.prototype,"invoke",null),Fc([jc.withSpan("interopio.api.interop.invoke.server",{argMapping:{"0.name":"method"}})],Rd.prototype,"getServerInvokePromise",null);class Ad{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 Md{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 Ed=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 Md(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const n=new Ad(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const n=new Ad(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}};class Dd{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 Ad(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 jd{_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 Dd(e,this._protocol,this._repoMethod):void 0:t.map(e=>new Dd(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new Ad(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}}async close(){return 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.");const n=jc.Traces.currentTracingState;n.addData("INFO",{stream:this?.name,branches:t}),n.addData("DIAGNOSTIC",{data:e}),e=Bc(e),n.injectPropagationInfo(e),this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}Fc([jc.withSpan("interopio.api.interop.stream.close",{thisMapping:{name:"stream"}})],jd.prototype,"close",null),Fc([jc.withSpan("interopio.api.interop.stream.push",{thisMapping:{name:"stream"}})],jd.prototype,"push",null);class Nd{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new Ed(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,n,i,r){const s=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 s;if(s="string"==typeof e?{name:""+e}:{...e},!s.name)return i(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(s)}`);if(this.serverRepository.getList().some(e=>e.definition.name===s.name))return i(`A stream with the name "${s.name}" already exists! Please, provide a unique name for the stream.`);s.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const o=this.serverRepository.add({definition:s,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(o).then(()=>{let e;r?(e=r,r.updateRepoMethod(o)):e=new jd(this.protocol,o,this),o.stream=e,n(e)}).catch(e=>{o.repoId&&this.serverRepository.remove(o.repoId),i(e)})});return Yc(s,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(jc.Traces.currentTracingState.addData("INFO",{method:Uo.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Uo.getMethodName(e)}`);const n=async(e,n)=>{try{const i=t(e.args,e.instance);if(i&&"function"==typeof i.then){const e=jc.Traces.currentTracingState,t=await i;jc.Traces.currentTracingState=e,n(void 0,t)}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(jc.Traces.currentTracingState.addData("INFO",{method:Uo.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Uo.getMethodName(e)}`);const n=async(e,n)=>{try{let i=!1;const r=e=>{i||n(void 0,e),i=!0},s=e=>{i||(e||(e=""),n(e,e)),i=!0},o=t(e.args,e.instance,r,s);o&&"function"==typeof o.then&&o.then(r).catch(s)}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(jc.Traces.currentTracingState.addData("INFO",{method:Uo.getMethodName(e)}),"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)}`);await this.currentlyUnregistering[n.name];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 i=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}});return this.protocol.server.register(i).catch(e=>{throw i?.repoId&&this.serverRepository.remove(i.repoId),e})}onMethodInvoked(e,t,n){const i=jc.Traces.extractPropagationInfo(n.args,!0);jc.withSpan("interopio.api.interop.register.callback",{method:e?.definition?.name},i,i=>{if(i.addData("INFO",{method:e?.definition?.name}),i.addData("INFO",{invocationId:t}),i.addData("INFO",{invoker:n?.instance}),i.addData("DIAGNOSTIC",{arguments:n?.args}),!e||!e.theFunction)return void(i.status={code:jc.SpanStatusCode.ERROR,message:"Required argument 'methodToExecute' is missing."});let r;const s=new Promise(e=>{r=e});return e.theFunction(n,(n,s)=>{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.status={code:jc.SpanStatusCode.ERROR,message:n},i.recordException(n)}s?("object"!=typeof s||Array.isArray(s))&&(s={_value:s}):s={},i.addData("DIAGNOSTIC",{returnValue:s}),this.protocol.server.methodInvocationResult(e,t,n,s),r()}),s})}}Fc([jc.withSpan("interopio.api.interop.stream.create",{argMapping:e=>({stream:Uo.getMethodName(e)})})],Nd.prototype,"createStream",null),Fc([jc.withSpan("interopio.api.interop.register",{argMapping:e=>({method:Uo.getMethodName(e)})})],Nd.prototype,"register",null),Fc([jc.withSpan("interopio.api.interop.register.async",{argMapping:e=>({method:Uo.getMethodName(e)})})],Nd.prototype,"registerAsync",null),Fc([jc.withSpan("interopio.api.interop.unregister",{argMapping:e=>({method:Uo.getMethodName(e)})})],Nd.prototype,"unregister",null);class Fd{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??Zo(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 Ld=e=>({...e,flags:e.flags.metadata||{}});class $d{logger;API;servers={};myServer;methodsCount={};callbacks=$o();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 Fd(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={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:()=>this.getServersByMethod(i)};r.object_types=r.objectTypes,r.display_name=r.displayName,n.methods[t.id]=r;const s=Ld(r);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),r}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=Ld(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(Ld)}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]=Ld(n)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class Wd{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 Hd="onSubscriptionRequest",Ud="onSubscriptionAdded",qd="onSubscriptionRemoved";class Bd{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=$o();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,s={id:r,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[r]=s,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(Ud,s,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)}`)}),this.callbacks.execute(qd,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(Ud,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(Hd,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(qd,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(qd,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(Hd,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 Gd{session;clientRepository;serverRepository;logger;callbacks=$o();streaming;constructor(e,t,n,i){this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.streaming=new Bd(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,s=this.serverRepository.getList().filter(e=>e.repoId===i)[0];if(void 0===s)return;const o=this.clientRepository.getServerById(n)?.instance,a={args:r,instance:o};this.callbacks.execute("onInvoked",s,t,a)}}class Jd{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 zd{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=Zo(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 Vd="awaitingAccept",Kd="subscribed",Zd="Subscription failed.",Qd="ClientInitiated";class Yd{session;repository;logger;subscriptionsList={};timedCache=new zd({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,s){if(jc.Traces.removePropagationInfo(t.arguments),0===n.length)return void r({method:e,called_with:t.arguments,message:Zd+" No available servers matched the target params."});const o=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(o,e,t,i,r,t.methodResponseTimeout||1e4,s);"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 s={type:"subscribe",server_id:i,method_id:r.gatewayId,arguments_kv:t.arguments};this.session.send(s,{serverId:i,subLocalKey:o}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):r({method:e,called_with:t.arguments,message:Zd+" 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,s,o){const a={localKey:e,status:Vd,method:t,params:n,success:i,error:r,trackedServers:[],handlers:{onData:o?.handlers.onData||[],onClosed:o?.handlers.onClosed||[],onConnected:o?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:o?.subscription};return o||(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===Vd?(r({method:t,called_with:n.arguments,message:Zd+" Subscription attempt timed out after "+s+" ms."}),delete this.subscriptionsList[e]):i.status===Kd&&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]))},s),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===Vd){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:jc.Traces.removePropagationInfo(i.params.arguments),method:i.method})}else i.status===Kd&&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 s=n.status===Vd;if(n.status=Kd,s){let e=!1,t=n.subscription;t?(t.setNewSubscription(n),n.success(t),e=!0):(t=new Jd(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,s=i[0].serverId,o=this.repository.getServerById(s),a=n.handlers.onData,c=n.queued.data,d={data:e.data,server:o?.instance??{},requestArguments:n.params.arguments,message:void 0,private:r},l=jc.Traces.extractPropagationInfo(d.data,!0),h=n?.method?.name;jc.withSpan("interopio.api.interop.stream.onData",{method:h,stream:h},l,()=>{const e=jc.Traces.currentTracingState;e.addData("INFO",{method:h}),e.addData("INFO",{stream:h}),e.addData("INFO",{handlerCount:a?.length}),e.addData("DIAGNOSTIC",{data:d}),a.length>0?a.forEach(e=>{"function"==typeof e&&e(Bc(d))}):c.push(Bc(d))})};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:Qd}).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,Qd),delete this.subscriptionsList[e])}}class Xd{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 Yd(e,t,n)}subscribe(e,t,n,i,r,s){this.streaming.subscribe(e,t,n,i,r,s)}invoke(e,t,n,i){const r=i.id,s={type:"call",server_id:r,method_id:t.gatewayId,arguments_kv:n};return this.session.send(s,{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),s={...n,pid:isNaN(r)?n.process:r,peerId:t,isLocal:i};this.repository.addServer(s,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:Od.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:Od.Error,message:r}}return{invocationId:"",message:e.message,status:Od.Error,error:e}}}function el(e,t,n,i,r,s){const o=r.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),d=t.domain("agm",["subscribed"]),l=new Gd(d,n,i,o.subLogger("server")),h=new Xd(d,n,o.subLogger("client"));return d.onJoined(r=>{n.addServer(e,t.peerId),r?async function(){o.info("reconnected - will replay registered methods and subscriptions"),h.drainSubscriptionsCache().forEach(e=>{const t=e.method,n=Object.assign({},e.params);o.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),s.client.subscribe(t,n,void 0,void 0,e).then(()=>o.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>o.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=h.drainSubscriptions();for(const n of t){const t=n.method,i=Object.assign({},n.params);o.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),e.push(s.client.subscribe(t,i,void 0,void 0,n).then(()=>o.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(s.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then(()=>o.info(`subscribing to method ${n.name} DONE`)).catch(()=>o.warn(`subscribing to method ${n.name} FAILED`))):t?.theFunction?.userCallback?e.push(s.register(n,t.theFunction.userCallback).then(()=>o.info(`registering method ${n.name} DONE`)).catch(()=>o.warn(`registering method ${n.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(s.registerAsync(n,t.theFunction.userCallbackAsync).then(()=>o.info(`registering method ${n.name} DONE`)).catch(()=>o.warn(`registering method ${n.name} FAILED`)))}await Promise.all(e),o.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>o.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:h,server:l}),a=void 0)}),d.onLeft(()=>{n.reset()}),d.join(),c}class tl{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 Fd(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new $d(e.logger.subLogger("cRep"),this),this.serverRepository=new Wd,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);n=el(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then(t=>(this.protocol=t,this.client=new Rd(this.protocol,this.clientRepository,this.instance,e),this.server=new Nd(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,s){return this.client.invoke(e,t,n,i,r,s)}waitForMethod(e){const t=new qo,n=this.client.methodAdded(i=>{i.name===e&&(n(),t.resolve(i))});return t.promise}}const nl=["subscribed","success"],il=1e4;class rl{connection;logger;session;subscriptions;readyPromise;resubscribeInProgress;pendingPublishes=[];canDrain=!1;drainInProgress=!1;sessionGeneration=0;constructor(e,t){this.connection=e,this.logger=t,this.subscriptions=[],this.session=e.domain("bus",nl),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()}),this.session.onLeft(()=>{this.canDrain=!1,this.sessionGeneration++}),this.session.onJoined(e=>{this.sessionGeneration++;const t=this.sessionGeneration,n=this.resubscribeInProgress??Promise.resolve();this.resubscribeInProgress=n.then(async()=>{try{if(e&&(await this.resubscribe(),await this.sleep(500)),this.sessionGeneration!==t)return;this.canDrain=!0,this.tryDrain()}catch(e){this.logger.error(`bus: error during onJoined chain: ${JSON.stringify(e)}`)}})})}sleep(e){return new Promise(t=>setTimeout(t,e))}ready(){return this.readyPromise}publish=(e,t,n)=>{this.publishCore(e,t,n)};publishCore(e,t,n){const{routingKey:i,target:r}=n||{},s=jc.Traces.currentTracingState;if(s.addData("INFO",{topic:e}),s.addData("DIAGNOSTIC",{data:t}),s.addData("INFO",{routingKey:i,target:r}),t=Bc(t),s.injectPropagationInfo(t),this.pendingPublishes.push({topic:e,data:t,options:n?Bc(n):void 0}),this.pendingPublishes.length>il){const e=this.pendingPublishes.length-il;this.pendingPublishes.splice(0,e),this.logger.warn(`bus: outbox exceeded 10000, dropped ${e} oldest publish(es)`)}1!==this.pendingPublishes.length||this.canDrain?this.canDrain||this.logger.debug(`bus: queued publish to ${e} (${this.pendingPublishes.length} pending)`):this.logger.info(`bus: started buffering publishes (first topic: ${e})`),this.tryDrain()}isTransportError(e){return null!=e&&("object"!=typeof e||!e.request_id&&!e.domain)}async tryDrain(){if(!this.drainInProgress&&this.canDrain){this.drainInProgress=!0;try{let e=0;for(;this.pendingPublishes.length>0&&this.canDrain;){const t=this.pendingPublishes[0],{routingKey:n,target:i}=t.options||{},r=this.removeEmptyValues({type:"publish",topic:t.topic,data:t.data,peer_id:this.connection.peerId,routing_key:n,target_identity:i});try{await this.session.sendFireAndForget(r),this.pendingPublishes.shift(),e++}catch(e){if(this.isTransportError(e)){this.logger.info(`bus: drain paused at ${t.topic} due to transport error (${this.pendingPublishes.length} pending)`);break}this.pendingPublishes.shift(),this.logger.error(`bus: failed to publish to ${t.topic}: ${JSON.stringify(e)}`)}}e>0&&0===this.pendingPublishes.length&&this.logger.debug(`bus: drained ${e} publish(es)`)}finally{this.drainInProgress=!1}}}subscribe=(e,t,n)=>this.subscribeCore(e,t,n);subscribeCore(e,t,n){return new Promise((i,r)=>{const{routingKey:s,target:o}=n||{},a=jc.Traces.currentTracingState;a.addData("INFO",{topic:e}),a.addData("INFO",{routingKey:s,target:o});const c=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.connection.peerId,routing_key:s,source:o});this.session.send(c).then(n=>{const{subscription_id:r}=n;a.addData("INFO",{subscription_id:r});const c={subscription_id:r,topic:e,routingKey:s,source:o,callback:function(...n){const i=jc.Traces.extractPropagationInfo(n?.[0],!0);jc.withSpan("interopio.api.bus.subscribe.callback",{topic:e},i,i=>{i.addData("INFO",{topic:e,subscription_id:c.subscription_id}),i.addData("DIAGNOSTIC",{data:n?.[0]}),t.apply(this,n)})}};this.subscriptions.push(c),i({unsubscribe:()=>{const e=c.subscription_id;return this.subscriptions=this.subscriptions.filter(t=>t.subscription_id!==e),this.session.send({type:"unsubscribe",subscription_id:e,peer_id:this.connection.peerId}).catch(t=>{this.logger.warn(`Failed to send unsubscribe request for ${e}: ${JSON.stringify(t)}`)}),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))})};async resubscribe(){const e=[...this.subscriptions];this.logger.info(`bus: re-subscribing ${e.length} subscription(s) after reconnect`);for(const t of e)if(this.subscriptions.includes(t))try{const e=this.removeEmptyValues({type:"subscribe",topic:t.topic,peer_id:this.connection.peerId,routing_key:t.routingKey,source:t.source}),n=await this.session.send(e);t.subscription_id=n.subscription_id}catch(e){this.logger.error(`bus: failed to re-subscribe to topic "${t.topic}": ${JSON.stringify(e)}`)}}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}}function sl(e){if(!ol(e))for(const t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;const n=e[t];ol(n)||(Sa(n)||Array.isArray(n)?sl(n):e[t]=n?.constructor?.name||n.toString())}}function ol(e){return!e||(e!==Object(e)||"function"==typeof e)}Fc([jc.withSpan("interopio.api.bus.publish",{argMapping:["topic"]})],rl.prototype,"publishCore",null),Fc([jc.withSpan("interopio.api.bus.subscribe",{argMapping:["topic"]})],rl.prototype,"subscribeCore",null);const al=(e,t)=>{const n="object"==typeof window?window.iodesktop??window.glue42gd:void 0,i="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),r=new qo,s=Go("glue"),o=Nc(e=e||{},t=t||{},n);let a,c,d,l,h,u,p,g;const f={};function m(e,t,n){g=d.canPublish("trace"),g&&d.trace(`registering ${e} module`);const i=i=>{if(t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,!g)return;const r=i?`${e} failed - ${i.message}`:`${e} is ready - ${n.endTime-n.startTime}`;d.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=>{f[e]=t,al[e]=t})}function b(){const e=Go("metrics"),t=o.metrics,i=n?.getMetricsPublishingEnabled,r=o.connection.identity,s=i||(()=>!0),c=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return l=Eo({connection:t?a:void 0,logger:d.subLogger("metrics"),canUpdateMetric:s,system:"Glue42",service:r?.service??n?.applicationName??o.application,instance:r?.instance??r?.windowId??Zo(10),disableAutoAppSystem:c,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),m("metrics",l,e),Promise.resolve()}function y(){const e=Go("interop"),t={connection:a,logger:d.subLogger("interop")};return c=new tl(t),ra.Interop=c,m(["interop","agm"],c,e),Promise.resolve()}function w(){const e=o.activities&&3===a.protocolVersion;if(o.contexts||e){const e=Go("contexts");h=new Qc({connection:a,logger:d.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}),m("contexts",h,e)}else{const e=a.replayer;e&&e.drain(ya.name)}return Promise.resolve()}async function v(){if(!o.bus)return Promise.resolve();const e=Go("bus");return u=new rl(a,d.subLogger("bus")),m("bus",u,e),Promise.resolve()}async function C(t){const i=Go("insights"),s=await o.getInsights(n,t,d);o.insights=s;try{const e=new jc.Builder,t=d.subLogger("insights");s.enabled&&await async function(e,t){try{(await Promise.resolve().then(function(){return hl})).init()}catch{e.warn("@interopio/insights-base plugin failed to load, insights will be disabled")}if(t.metrics?.enabled)try{(await Promise.resolve().then(function(){return hl})).init()}catch{e.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled")}if(t.traces?.enabled)try{(await Promise.resolve().then(function(){return hl})).init()}catch{e.warn("@interopio/insights-traces plugin failed to load, insights traces functionality will be disabled")}}(t,s),e.withSettings(s),e.withLogger(new jc.Log4jsWrapper(t)),e.withMetrics();const n="___insights_pi_storage___";e.withTraces().withTraceLogger(new jc.Log4jsWrapper(t.subLogger("traces"))).withPropagationInfoStorage((e,t)=>h?.update(n,{[e.replace(/[.]/g,"_!_")]:{pi:t}}),e=>h?.get(n)?.then(t=>t[e.replace(/[.]/g,"_!_")]?.pi)??Promise.resolve(null));const o=e.build();return await o.start(),m("insights",o,i),jc.Traces.withSpan("interopio.api.startup",()=>r.promise),p=o,Promise.resolve()}catch(e){if(i.stop(),d?.error("Error initializing insights",e),s.failOnInitError)throw e;return Promise.resolve()}finally{sl(o?.insights),sl(e?.insights)}}function I(e){try{return e.forEach(e=>{!function(e,t){const n=Go(e),i=t(f);i&&m(e,i,n)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return i.then(function(){const e=Go("logger");return d=new ra(`${o.connection.identity?.application}`,void 0,o.customLogger),d.consoleLevel(o.logger.console),d.publishLevel(o.logger.publish),d.canPublish("debug")&&d.debug("initializing glue..."),m("logger",d,e),Promise.resolve(void 0)}).then(function(){const e=Go("connection");a=new na(o.connection,d.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,a.login(n)}).then(()=>(m("connection",a,e),o)).catch(e=>{throw a&&a.logout(),e})}).then(()=>Promise.all([b(),y(),w(),v()])).then(()=>c.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Uo.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&c.methods({name:t}).length>0)try{await c.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;d.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>C(c)).then(()=>I(o.libs||[])).then(function(){const e=Object.keys(f).map(e=>{const t=f[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const i={coreVersion:Ca,version:o.version};s.stop();const g={feedback:e=>{c&&c.invoke("T42.ACS.Feedback",e,"best")},info:i,logger:d,interop:c,agm:c,connection:a,metrics:l,contexts:h,insights:p,bus:u,version:o.version,userConfig:e,done:()=>(d?.info("done called by user..."),a.logout())};if(g.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=Bo;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(f).forEach(e=>{const t=f[e];g[e]=t}),g.config={},Object.keys(o).forEach(e=>{g.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{g.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(g),n&&n.updatePerfData&&n.updatePerfData(g.performance),g.agm){const e=(e,t,n)=>function(){return g.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${n}' instead.`),e.apply(g.agm,arguments)},t=g.agm;t.method_added=e(g.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(g.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(g.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(g.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(g.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return r.resolve(),g}).catch(e=>(r.reject({err:e}),Promise.reject({err:e,libs:f})))};"undefined"!=typeof window&&(window.IOConnectCore=al),al.version=Ca,al.default=al;const cl=(e=>{let t;return n=>{if(window.glue42gd||window.iodesktop)return(e=>{const t={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:e?.libraries??[],logger:e?.systemLogger?.level??"warn"};return(window.IODesktop||window.Glue)(t)})(n);const i=((e={})=>{const t=!!e?.gateway?.webPlatform?.port,n=O(Rr).run(e.widget);if(!n.ok)throw re.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(n.error)}`);const i=O(Ar).run(e.modals);if(!i.ok)throw re.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(i.error)}`);const r=O(es).run(e.intentResolver);if(!r.ok)throw re.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(r.error)}`);return{...D,...e,isPlatformInternal:t,logger:e.systemLogger?.level??"info",customLogger:e.systemLogger?.customLogger,widget:d(j,n.result??{}),modals:d(N,i.result??{}),intentResolver:d(F,r.result??{})}})(n);try{(()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)return re.raiseError("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}})()}catch(e){return void 0===t?Promise.reject(new Error(e)):t}const r=(async t=>{const n=new oo,i=await fs(()=>e(t,{version:ao}),3e4,"Glue Web initialization timed out, because core didn't resolve"),r=i.logger.subLogger("web.main.controller");n.defineGlue(i),await n.preferredConnectionController.start(t),await n.bridge.start(n.controllers),n.defineConfig(t),r.trace("the bridge has been started, initializing all controllers"),await Promise.all(Object.values(n.controllers).map(e=>e.start(i,n))),r.trace("all controllers reported started, starting all additional libraries");try{return await Promise.all(t.libraries.map(e=>e(i,t))),r.trace("all libraries were started"),n.eventsDispatcher.start(i),r.trace("start event dispatched, glue is ready, returning it"),await n.uiController.showComponents(i).catch(e=>r.warn(e?.message?e.message:JSON.stringify(e))),await Promise.all(Object.values(n.controllers).map(e=>e.postStart?e.postStart(i,n):Promise.resolve())),window.iobrowser.system=co(0,n.bridge),window.iobrowser=Object.freeze({...window.iobrowser}),i}catch(e){return re.raiseError(e,!0)}})(i);return t=n?.memoizeAPI?r:void 0,r}})(al);if("undefined"!=typeof window){const e=window;e.IOBrowser=cl,delete e.GlueCore,delete e.IOConnectCore}const dl=window.glue42gd||window.glue42core,ll=window.iodesktop||window.iobrowser;dl||ll||(window.iobrowser={webStarted:!1}),window.iodesktop||window.iobrowser.system||(window.iobrowser.system=co()),cl.version=ao;var hl=Object.freeze({__proto__:null});return cl});
14
+ function e(e){return"[object Object]"===Object.prototype.toString.call(e)}return ja=1,Object.defineProperty(La,"__esModule",{value:!0}),La.isPlainObject=function(t){let n,i;return!1!==e(t)&&(n=t.constructor,void 0===n||(i=n.prototype,!1!==e(i)&&!1!==i.hasOwnProperty("isPrototypeOf")))},La}();return Fa}var Wa,Ha,Ua,qa={};function Ba(){if(Wa)return qa;Wa=1,Object.defineProperty(qa,"__esModule",{value:!0}),qa.NullMetric=void 0;return qa.NullMetric=class{constructor(e,t){this.settings=e,this.logger=t,this.started=!1}start(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been started instead of ${this.settings.type} one`),this.started=!0,Promise.resolve()}stop(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been stopped instead of ${this.settings.type} one`),this.started=!1,Promise.resolve()}add(){}record(){}},qa}function Ga(){if(Ha)return Ma;Ha=1,Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.NullMetricsManager=void 0;const e=Da(),t=$a(),n=Ba();class i extends e.NullManager{constructor(e,n,i){!1!==(null==n?void 0:n.logSettingsOnStartup)&&(null==i||i.info(`Starting NullMetrcsManager with settings ${(0,t.safeStringify)(e)}`)),super()}waitForFinalExport(e){return Promise.resolve()}getFromSettings(e){return new n.NullMetric(e)}get(e){return new n.NullMetric({name:e,type:e,enabled:!1,description:e})}}return Ma.NullMetricsManager=i,Ma}var Ja,za={},Va={},Ka={};function Za(){if(Ja)return Ka;Ja=1,Object.defineProperty(Ka,"__esModule",{value:!0});return Ka.default=class{constructor(e,t,n){this.source=e,this.propagationInfo=t,this.disablePropagation=n,this.currentSpanStatus={code:0},this.level="OFF"}endSpan(){return Promise.resolve()}get enabled(){return!1}get id(){}get traceId(){}set status(e){this.currentSpanStatus=Object.assign({},e)}get status(){return this.currentSpanStatus}addEvent(e,t,n){return this}recordException(e,t){}isRecording(){return!1}updateName(e){return this}spanContext(){}addData(e,t){}end(){}getPropagationInfo(){return this.propagationInfo?this.propagationInfo:null}injectPropagationInfo(e){this.propagationInfo&&!this.disablePropagation&&(e.__interopIOTracePropagationInfo=this.propagationInfo)}},Ka}var Qa,Ya,Xa,ec,tc,nc={},ic={},rc={};function sc(){if(Qa)return rc;Qa=1;var e=rc&&rc.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})};Object.defineProperty(rc,"__esModule",{value:!0}),rc.Container=void 0;const t=$a();class n{static get instance(){var e,t;return null!==(e=n._instance)&&void 0!==e?e:null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.instance}static get settings(){var e;return null!==(e=n._settings)&&void 0!==e?e:n.instance.settings}static set settings(e){n._settings=e}static errorless(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return n.handleErrorlessMode(e,t)}}static errorlessDefined(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return n.handleErrorlessMode(e,t)}}static errorlessAsync(t,i){return e(this,void 0,void 0,function*(){try{if("function"!=typeof t)return t;return(yield t)()}catch(e){return n.handleErrorlessMode(e,i)}})}static handleErrorlessMode(e,i){var r,s,o,a,c;let d;try{if((null==e?void 0:e.message)&&(d=(null==e?void 0:e.message)+" "+(null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:(new Error).stack)),!d)try{d=(0,t.safeStringify)(e)+" "+(new Error).stack}catch(e){}if(!d)try{d=(null==e?void 0:e.toString())+" "+(new Error).stack}catch(e){}}catch(e){}d||(d="unknown "+(new Error).stack);try{if(!(null===(o=null===(s=n.instance)||void 0===s?void 0:s.settings)||void 0===o?void 0:o.errorlessMode))throw null===(a=n.instance.logger)||void 0===a||a.error("Observed error "+d),e}catch(t){throw e}try{return null===(c=n.instance.logger)||void 0===c||c.warn("Caught error "+d),i}catch(e){return i}}constructor(e,t,i,r,s){var o;this._settings=e,this._traces=t,this.metrics=i,this.logs=r,this.logger=s,this.started=!1,n._instance=this,globalThis.ioInsightsInternals=null!==(o=globalThis.ioInsightsInternals)&&void 0!==o?o:{},globalThis.ioInsightsInternals.instance=this}get traces(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:this._traces}waitForFinalExport(e){var t,n,i;return Promise.allSettled([null===(t=this.traces)||void 0===t?void 0:t.waitForFinalExport(e),null===(n=this.metrics)||void 0===n?void 0:n.waitForFinalExport(e),null===(i=this.logs)||void 0===i?void 0:i.waitForFinalExport(e)])}get settings(){return this._settings}start(){return e(this,void 0,void 0,function*(){const e=this.metrics.settings.enabled?this.metrics.start():Promise.resolve(),t=this.traces.settings.enabled?this.traces.start():Promise.resolve(),n=this.logs.settings.enabled?this.logs.start():Promise.resolve();yield Promise.all([e,t,n]),this.started=!0})}stop(){return e(this,void 0,void 0,function*(){const e=this.metrics.started?this.metrics.stop():Promise.resolve(),t=this.traces.started?this.traces.stop():Promise.resolve(),n=this.logs.started?this.logs.stop():Promise.resolve();yield Promise.all([e,t,n]),this.started=!1})}}return rc.Container=n,rc}function oc(){return Ya||(Ya=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extractFilteringContextFromArgs=e.deep_value=e.getOTELData=e.flattenOtelAtributes=void 0;const t=sc();e.flattenOtelAtributes=(t,n)=>{if(null==t)return{};"object"!=typeof t&&(t={unknownAttribute:t});const i={};for(const[r,s]of Object.entries(t)){const t=(0,e.getOTELData)(r,s,0,n);for(const[e,n]of t)i[e]=n}return i};e.getOTELData=(e,t,r,s)=>{if((r+=1)>s)return[[e,"<depth exceeded>"]];const o=Boolean(t&&"object"==typeof t);return"number"==typeof t||"string"==typeof t||"boolean"==typeof t?[[e,t]]:i(t)?[[e,t]].concat(n(e,t,r,s)):o?n(e,t,r,s):"function"==typeof t?[]:t?[[e,t+""]]:[]};const n=(t,n,i,r)=>{const s=[];for(const[o,a]of Object.entries(n))for(const[n,c]of(0,e.getOTELData)(o,a,i,r))s.push([t+"."+n,c]);return s},i=e=>!!Array.isArray(e)&&e.every(e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e);e.deep_value=function(e,t){if(!t)return null;for(var n=0,i=(t=t.split(".")).length;n<i;n++){if(null==e)return;e=e[t[n]]}return e};e.extractFilteringContextFromArgs=(n,i,r)=>{let s={};return"function"==typeof n.thisMapping?s=Object.assign(Object.assign({},s),t.Container.errorless(()=>n.thisMapping.apply(r,[r]))):Object.keys(n.thisMapping||{}).forEach(t=>{if(!t||!n.thisMapping)return;const i=n.thisMapping[t];s[i]=(0,e.deep_value)(r,t)}),"function"==typeof n.argMapping?s=Object.assign(Object.assign({},s),t.Container.errorless(()=>n.argMapping.apply(r,i))):Object.keys(n.argMapping||{}).forEach(t=>{if(!t||!n.argMapping)return;const r=n.argMapping[t],o=(0,e.deep_value)(i,t);"string"!=typeof o&&"number"!=typeof o||(s[r]=o)}),s}}(ic)),ic}function ac(){if(Xa)return nc;Xa=1;var e=nc&&nc.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})},t=nc&&nc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nc,"__esModule",{value:!0}),nc.withSpan=void 0;const n=oc(),i=cc(),r=t(Za());class s{static get instance(){var e,t;return(null===(e=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)?null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===t?void 0:t.traces:(s._instance||(s._instance=new i.NullTracesManager(void 0,void 0,void 0)),s._instance)}static set instance(e){s._instance=e}static get currentTracingState(){var e;return(null===(e=s.instance)||void 0===e?void 0:e.currentTracingState)||new r.default("unknown",null,!0)}static set currentTracingState(e){s.instance&&(s.instance.currentTracingState=e)}static removePropagationInfo(e){return s.extractPropagationInfo(e,!0),e}static extractPropagationInfo(e,t){if(null==e?void 0:e.traceparent)return e;const n=null==e?void 0:e.__interopIOTracePropagationInfo;return n?(!0===t&&delete e.__interopIOTracePropagationInfo,n):null}withSequenceSpanEx(t,n,i,r,o){return e(this,void 0,void 0,function*(){return s.instance.withSequenceSpanEx(t,n,i,r,o)})}withSequenceSpan(t,n,i,r){return e(this,void 0,void 0,function*(){return s.instance.withSequenceSpan(t,n,i,r)})}static withSpan(e,t,i,r,o){return t instanceof Function||t&&!t.argMapping&&!t.thisMapping&&!t.defaults||i||r||o?s.instance.withSpan(e,t,i,r,o):function(i,r,o){let a;a=o?o.value:i;let c=function(...i){return s.withSpan(e,t?(0,n.extractFilteringContextFromArgs)(t,i,this):{},null,t,()=>a.apply(this,i))};if(s.isAsyncFunction(a)){const e=c;c=function(...t){return e.apply(this,t)},Object.defineProperty(c,Symbol.toStringTag,{value:"AsyncFunction",configurable:!0})}if(!o)return c;o.value=c}}static isAsyncFunction(e){return e&&"[object AsyncFunction]"==={}.toString.call(e)}static withSpans(e,t){for(const n in e)if("function"==typeof t[n]){const i=t[n],r=e[n];if(!r)continue;let o;o="string"==typeof r?s.withSpan(r):s.withSpan(r.source,r.decoratorOptions),t[n]=o(i)}return t}}return nc.default=s,nc.withSpan=s.withSpan,nc}function cc(){if(ec)return Va;ec=1;var e=Va&&Va.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})},t=Va&&Va.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Va,"__esModule",{value:!0}),Va.NullTracesManager=void 0;const n=t(Za()),i=t(ac()),r=Da(),s=$a();class o extends r.NullManager{get settings(){return this._settings||{}}set settings(e){this._settings=e}constructor(e,t,n){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==n||n.info(`Starting NullTracesManager with settings ${(0,s.safeStringify)(e)}`)),super(),this._settings=e,this.logger=n}withSequenceSpan(t,n,i,r){return e(this,void 0,void 0,function*(){return this.withSequenceSpanEx(t,t+".start",n,i,r)})}withSequenceSpanEx(t,n,i,r,s){return e(this,void 0,void 0,function*(){return this.withSpan(t,i,null,r,s)})}get currentTracingState(){return new n.default("nullTracingState",null,!0)}set currentTracingState(e){}waitForFinalExport(e){return Promise.resolve()}withSpan(e,t,r,s,o){const a="function"==typeof t?t:"function"==typeof r?r:"function"==typeof s?s:o;if(!a)throw new Error("callback must be provided");if("function"!=typeof a)throw new Error("Callback must be a function, received "+typeof a);const c=new n.default(e,null,!0);i.default.currentTracingState=c;try{return a(c)}finally{i.default.currentTracingState=null}}setFilterConfig(e){}get startupTraceFinished(){return()=>{}}get userJourneyMarker(){return()=>{}}setUserJourneyMarker(e){}get clickstreamMarker(){return()=>{}}}return Va.NullTracesManager=o,Va}var dc,lc={};var hc,uc={};function pc(){if(hc)return uc;hc=1,Object.defineProperty(uc,"__esModule",{value:!0}),uc.NullLogsManager=void 0;const e=Da(),t=$a();class n extends e.NullManager{constructor(e,n,i){!1!==(null==n?void 0:n.logSettingsOnStartup)&&(null==i||i.info(`Starting NullLogsManager with settings ${(0,t.safeStringify)(e)}`)),super()}emit(e){return null}}return uc.NullLogsManager=n,uc}var gc,fc={};var mc,bc={};var yc,wc,vc={};function Cc(){if(wc)return Ra;wc=1,Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.Builder=void 0;const e=function(){if(Ua)return Aa;Ua=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.MetricsManagerBuilder=void 0;const e=Ga(),t=Nc();return Aa.MetricsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}withMeterProvider(e){return this.meterProviderCreateFunc=e,this}withDependencyContainer(e){return this.dependencyContainer=e,this}build(){var e,t,n,i;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.metrics)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.metrics;const r=this.buildCore();return globalThis.ioInsightsInternals=null!==(n=globalThis.ioInsightsInternals)&&void 0!==n?n:{},globalThis.ioInsightsInternals.metrics&&!(null===(i=this.settings)||void 0===i?void 0:i.definitiveInstance)||(globalThis.ioInsightsInternals.metrics=r),r}buildCore(){var n,i,r,s;let o;return!0===(null===(n=this.settings)||void 0===n?void 0:n.enabled)&&!0===(null===(r=null===(i=this.settings)||void 0===i?void 0:i.metrics)||void 0===r?void 0:r.enabled)&&(o=(0,t.loadInsightsPlugin)("metrics",this.logger))?o.newMetricsManager(this.settings,this.dependencyContainer,this.meterProviderCreateFunc,this.logger):new e.NullMetricsManager(null===(s=this.settings)||void 0===s?void 0:s.metrics,this.settings,this.logger)}},Aa}(),t=function(){if(tc)return za;tc=1,Object.defineProperty(za,"__esModule",{value:!0}),za.TracesManagerBuilder=void 0;const e=cc(),t=Nc();return za.TracesManagerBuilder=class{constructor(){this.traceLogger=null}withLogger(e){return this.logger=e,this}withTraceLogger(e){return this.traceLogger=e,this}withSettings(e){return this.settings=e,this}withMetrics(e){return this.metrics=e,this}withTracerProvider(e){return this.tracerProvider=e,this}withContextManager(e){var t,n;return this.settings=null!==(t=this.settings)&&void 0!==t?t:{enabled:!1},this.settings.traces=null!==(n=this.settings.traces)&&void 0!==n?n:{enabled:!1},this.settings.traces.contextManager=()=>e,this.settings.traces.useOTELContextManager=!0,this}withPropagationInfoStorage(e,t){return this.store=e,this.read=t,this}build(){var e,t,n,i;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.traces)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.traces;const r=this.buildCore();return globalThis.ioInsightsInternals=null!==(n=globalThis.ioInsightsInternals)&&void 0!==n?n:{},globalThis.ioInsightsInternals.traces&&!(null===(i=this.settings)||void 0===i?void 0:i.definitiveInstance)||(globalThis.ioInsightsInternals.traces=r),r}buildCore(){var n,i,r,s,o,a,c,d;let l;return this.settings.traces=null!==(n=this.settings.traces)&&void 0!==n?n:{enabled:!1},this.settings.traces.otlpExporterConfig=null!==(i=this.settings.traces.exporterSettings)&&void 0!==i?i:this.settings.traces.otlpExporterConfig,this.settings.traces.exporterSettings=null!==(r=this.settings.traces.exporterSettings)&&void 0!==r?r:this.settings.traces.otlpExporterConfig,!0===(null===(s=this.settings)||void 0===s?void 0:s.enabled)&&!0===(null===(a=null===(o=this.settings)||void 0===o?void 0:o.traces)||void 0===a?void 0:a.enabled)&&(l=(0,t.loadInsightsPlugin)("traces",this.logger))?l.newTracesManager(this.logger,this.settings,null!==(d=this.traceLogger)&&void 0!==d?d:this.logger,this.metrics,this.store,this.read):new e.NullTracesManager(null===(c=this.settings)||void 0===c?void 0:c.traces,this.settings,this.logger)}},za}(),n=(dc||(dc=1,Object.defineProperty(lc,"__esModule",{value:!0}),lc.NullLogger=void 0,lc.NullLogger=class{get level(){return 60}error(){}warn(){}info(){}debug(){}verbose(){}}),lc),i=sc(),r=Ga(),s=cc(),o=pc(),a=(gc||(gc=1,Object.defineProperty(fc,"__esModule",{value:!0}),fc.Defaults=void 0,fc.Defaults={DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version"}),fc),c=(mc||(mc=1,Object.defineProperty(bc,"__esModule",{value:!0}),bc.LogWrapper=void 0,bc.LogWrapper=class{constructor(e,t){this.logger=e,this.dropLog=t}get level(){var e;return null!==(e=this.logger.level)&&void 0!==e?e:0}error(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,50,e))||this.logger.warn(e,...t)}warn(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,50,e))||this.logger.warn(e,...t)}info(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,60,e))||this.logger.info(e,...t)}debug(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,70,e))||this.logger.debug(e,...t)}verbose(e,...t){var n;(null===(n=this.dropLog)||void 0===n?void 0:n.call(this,80,e))||this.logger.verbose(e,...t)}}),bc),d=Nc(),l=$a(),h=function(){if(yc)return vc;yc=1,Object.defineProperty(vc,"__esModule",{value:!0}),vc.LogsManagerBuilder=void 0;const e=Nc(),t=pc();return vc.LogsManagerBuilder=class{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}build(){var e,t,n,i;if((null===(e=globalThis.ioInsightsInternals)||void 0===e?void 0:e.logs)&&!0!==(null===(t=this.settings)||void 0===t?void 0:t.definitiveInstance))return globalThis.ioInsightsInternals.logs;const r=this.buildCore();return globalThis.ioInsightsInternals=null!==(n=globalThis.ioInsightsInternals)&&void 0!==n?n:{},globalThis.ioInsightsInternals.logs&&!(null===(i=this.settings)||void 0===i?void 0:i.definitiveInstance)||(globalThis.ioInsightsInternals.logs=r),r}buildCore(){var n,i,r,s;let o;return!0===(null===(n=this.settings)||void 0===n?void 0:n.enabled)&&!0===(null===(r=null===(i=this.settings)||void 0===i?void 0:i.logs)||void 0===r?void 0:r.enabled)&&(o=(0,e.loadInsightsPlugin)("logs",this.logger))?o.newLogsManager(this.logger,this.settings.logs,this.settings):new t.NullLogsManager(null===(s=this.settings)||void 0===s?void 0:s.logs,this.settings,this.logger)}},vc}();class u{constructor(){this.logger=new n.NullLogger}withLogger(e){var t;e&&(this.logger=new c.LogWrapper(e,(e,t)=>{var n,i,r;return!(!(null===(n=this.settings)||void 0===n?void 0:n.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("@opentelemetry/api: Attempted duplicate registration of API"))||(!(!(null===(i=this.settings)||void 0===i?void 0:i.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will overwrite one already registered"))||!(!(null===(r=this.settings)||void 0===r?void 0:r.suppressDoubleInitializationWarnings)||!~(t+"").indexOf("Current logger will be overwritten")))}));const n=(0,d.loadInsightsPlugin)("base",this.logger);if(n)if(this.logger.level){const e=null===(t=this.logger.level)||void 0===t?void 0:t.valueOf();n.diag.setLogger(this.logger,e)}else n.diag.setLogger(this.logger,70);return this}withSettings(e){return this.settings=e,i.Container.settings=e,this}withMetrics(){return this.metricsBuilder=new e.MetricsManagerBuilder,this.metricsBuilder.withLogger(this.logger),this.metricsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.metricsBuilder}withTraces(){return this.tracesBuilder=new t.TracesManagerBuilder,this.tracesBuilder.withLogger(this.logger),this.tracesBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.tracesBuilder}withLogs(){return this.logsBuilder=new h.LogsManagerBuilder,this.logsBuilder.withLogger(this.logger),this.logsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.logsBuilder}build(){var e,t,n,c,h,p,g,f,m;this.settings=null!==(e=this.settings)&&void 0!==e?e:{enabled:!1};const b=Object.assign({enabled:!1},this.settings);if(!1!==(null===(t=this.settings)||void 0===t?void 0:t.logSettingsOnStartup)&&this.logger.info(`Starting interop.io OTEL with settings ${(0,l.safeStringify)(this.settings)}`),0==(null===(n=this.settings)||void 0===n?void 0:n.enabled)||!(0,d.loadInsightsPlugin)("base",this.logger))return new i.Container(b,new s.NullTracesManager(this.settings.traces,b,this.logger),new r.NullMetricsManager(this.settings.metrics,b,this.logger),new o.NullLogsManager(this.settings.logs,b,this.logger),this.logger);if((null===(h=null===(c=this.settings)||void 0===c?void 0:c.metrics)||void 0===h?void 0:h.enabled)&&(null===(p=this.settings)||void 0===p?void 0:p.metrics.platformMetricsEnabled)&&!this.metricsBuilder)throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");const y=this.settings.additionalResourceAttributes;this.settings.additionalResourceAttributes=()=>{var e,t,n,r,s,o,c,d,l,h,u,p,g,f,m,b,w,v,C,I,S,_,x,T;const k=null!==(e=i.Container.errorlessDefined(y,{}))&&void 0!==e?e:{};return Object.assign(Object.assign({},k),{user:null!==(s=null!==(r=null!==(t=k.userId)&&void 0!==t?t:null===(n=this.settings)||void 0===n?void 0:n.userId)&&void 0!==r?r:k["user.id"])&&void 0!==s?s:a.Defaults.DEFAULT_USER,"user.id":null!==(l=null!==(d=null!==(o=k.userId)&&void 0!==o?o:null===(c=this.settings)||void 0===c?void 0:c.userId)&&void 0!==d?d:k["user.id"])&&void 0!==l?l:a.Defaults.DEFAULT_USER,"service.name":null!==(g=null!==(p=null!==(h=k.serviceName)&&void 0!==h?h:null===(u=this.settings)||void 0===u?void 0:u.serviceName)&&void 0!==p?p:k["service.name"])&&void 0!==g?g:a.Defaults.DEFAULT_SERVICE_NAME,"service.instance.id":null!==(w=null!==(b=null!==(f=k.serviceId)&&void 0!==f?f:null===(m=this.settings)||void 0===m?void 0:m.serviceId)&&void 0!==b?b:k["service.instance.id"])&&void 0!==w?w:a.Defaults.DEFAULT_SERVICE_ID,"service.version":null!==(S=null!==(I=null!==(v=k.serviceVersion)&&void 0!==v?v:null===(C=this.settings)||void 0===C?void 0:C.serviceVersion)&&void 0!==I?I:k["service.version"])&&void 0!==S?S:a.Defaults.DEFAULT_SERVICE_VERSION,platformVersion:null!==(T=null!==(_=k.platformVersion)&&void 0!==_?_:null===(x=this.settings)||void 0===x?void 0:x.platformVersion)&&void 0!==T?T:a.Defaults.DEFAULT_PLATFORM_VERSION})},u.maybeAddResourceAttributesToAttributes(this.settings),u.maybeAddResourceAttributesToAttributes(this.settings.logs),u.maybeAddResourceAttributesToAttributes(this.settings.metrics),u.maybeAddResourceAttributesToAttributes(this.settings.traces),u.propagateAttributeDown("useSSOAuth",this.settings,this.settings.logs),u.propagateAttributeDown("useSSOAuth",this.settings,this.settings.metrics),u.propagateAttributeDown("useSSOAuth",this.settings,this.settings.traces),u.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.logs),u.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.metrics),u.propagateAttributeDown("useSSOAuthRawToken",this.settings,this.settings.traces),u.propagateAttributesDown("headers",this.settings,this.settings.logs),u.propagateAttributesDown("headers",this.settings,this.settings.metrics),u.propagateAttributesDown("headers",this.settings,this.settings.traces),u.propagateAttributesDown("additionalAttributes",this.settings,this.settings.logs),u.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.logs),u.propagateAttributesDown("additionalAttributes",this.settings,this.settings.metrics),u.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.metrics),u.propagateAttributesDown("additionalAttributes",this.settings,this.settings.traces),u.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.traces);const w=(null!==(g=this.metricsBuilder)&&void 0!==g?g:this.withMetrics()).withLogger(this.logger).withSettings(this.settings).build(),v=(null!==(f=this.tracesBuilder)&&void 0!==f?f:this.withTraces()).withLogger(this.logger).withSettings(this.settings).withMetrics(w).build();d.Traces.instance=v;const C=(null!==(m=this.logsBuilder)&&void 0!==m?m:this.withLogs()).withLogger(this.logger).withSettings(this.settings).build();return d.Logs.instance=C,new i.Container(b,v,w,C,this.logger)}static propagateAttributeDown(e,t,n){var i;n&&(n[e]=null!==(i=n[e])&&void 0!==i?i:t[e])}static propagateAttributesDown(e,t,n){var r,s;if(!n)return;const o=null!==(r=t[e])&&void 0!==r?r:{},a=null!==(s=n[e])&&void 0!==s?s:{};n[e]=()=>Object.assign(Object.assign({},i.Container.errorless(o)),i.Container.errorless(a))}static maybeAddResourceAttributesToAttributes(e){if(null==e?void 0:e.addResourceAttributesToAttributes){const t=e.additionalResourceAttributes,n=e.additionalAttributes;e.additionalAttributes=()=>Object.assign(Object.assign({},i.Container.errorless(t)),i.Container.errorless(n))}}}return Ra.Builder=u,Ra}var Ic,Sc={};var _c,xc,Tc={},kc={};function Pc(){if(xc)return Tc;xc=1,Object.defineProperty(Tc,"__esModule",{value:!0}),Tc.MetricsDependencyBuilder=void 0;const e=(_c||(_c=1,Object.defineProperty(kc,"__esModule",{value:!0}),kc.NullPerformanceProvider=void 0,kc.NullPerformanceProvider=class{getAppsCPU(){return Promise.resolve(void 0)}getAppsMemory(){return Promise.resolve(void 0)}getSystemCPU(){return Promise.resolve(void 0)}getSystemMemory(){return Promise.resolve(void 0)}}),kc);return Tc.MetricsDependencyBuilder=class{constructor(){this.performanceProvider=new e.NullPerformanceProvider,this.instanceFocusedHandler=()=>()=>{},this.instanceStartedHandler=()=>()=>{},this.instanceStoppedHandler=()=>()=>{},this.instanceReadyHandler=()=>()=>{},this.instanceErrorHandler=()=>()=>{},this.instanceCrashHandler=()=>()=>{},this.layoutRestoredHandler=()=>()=>{},this.platformStartedHandler=()=>()=>{},this.platformErrorHandler=()=>()=>{},this.workspaceLoadedHandler=()=>()=>{},this.workspaceRestoredHandler=()=>()=>{},this.workspaceSavedHandler=()=>()=>{},this.workspaceStoppedHandler=()=>()=>{},this.workspaceSelectedHandler=()=>()=>{},this.workspaceStartedHandler=()=>()=>{},this.workspaceFrameCreatedHandler=()=>()=>{},this.workspaceFrameInitHandler=()=>()=>{},this.workspaceFramePageLoadHandler=()=>()=>{},this.workspaceFrameWorkspaceRenderHandler=()=>()=>{},this.workspaceComponentCreatedHandler=()=>()=>{},this.workspaceAppsStartedHandler=()=>()=>{},this.workspaceStartupHandler=()=>()=>{}}build(){return{performanceProvider:this.performanceProvider,instanceStartedHandler:this.instanceStartedHandler,instanceStoppedHandler:this.instanceStoppedHandler,instanceReadyHandler:this.instanceReadyHandler,instanceFocusedHandler:this.instanceFocusedHandler,instanceErrorHandler:this.instanceErrorHandler,instanceCrashHandler:this.instanceCrashHandler,layoutRestoredHandler:this.layoutRestoredHandler,platformStartedHandler:this.platformStartedHandler,platformErrorHandler:this.platformErrorHandler,workspaceLoadedHandler:this.workspaceLoadedHandler,workspaceSavedHandler:this.workspaceSavedHandler,workspaceStoppedHandler:this.workspaceStoppedHandler,workspaceSelectedHandler:this.workspaceSelectedHandler,workspaceRestoredHandler:this.workspaceRestoredHandler,workspaceStartedHandler:this.workspaceStartedHandler,workspaceStartupHandler:this.workspaceStartupHandler,workspaceFrameCreatedHandler:this.workspaceFrameCreatedHandler,workspaceFrameInitHandler:this.workspaceFrameInitHandler,workspaceFramePageLoadHandler:this.workspaceFramePageLoadHandler,workspaceFrameWorkspaceRenderHandler:this.workspaceFrameWorkspaceRenderHandler,workspaceComponentCreatedHandler:this.workspaceComponentCreatedHandler,workspaceAppsStartedHandler:this.workspaceAppsStartedHandler}}withInstanceStartedHandler(e){return this.instanceStartedHandler=e,this}withInstanceStoppedHandler(e){return this.instanceStoppedHandler=e,this}withInstanceReadyHandler(e){return this.instanceReadyHandler=e,this}withInstanceFocusedHandler(e){return this.instanceFocusedHandler=e,this}withInstanceErrorHandler(e){return this.instanceErrorHandler=e,this}withInstanceCrashHandler(e){return this.instanceCrashHandler=e,this}withLayoutRestoredHandler(e){return this.layoutRestoredHandler=e,this}withWorkspaceLoadedHandler(e){return this.workspaceLoadedHandler=e,this}withWorkspaceSavedHandler(e){return this.workspaceSavedHandler=e,this}withWorkspaceStartedHandler(e){return this.workspaceRestoredHandler=()=>()=>{},this.workspaceStartedHandler=e,this}withWorkspaceStoppedHandler(e){return this.workspaceStoppedHandler=e,this}withWorkspaceSelectedHandler(e){return this.workspaceSelectedHandler=e,this}withPlatformStartedHandler(e){return this.platformStartedHandler=e,this}withPlatformErrorHandler(e){return this.platformErrorHandler=e,this}withPerfProvider(e){return this.performanceProvider=e,this}withWorkspaceRestoredHandler(e){return this.workspaceRestoredHandler=e,this.workspaceStartedHandler=()=>()=>{},this}withWorkspaceStartupHandler(e){return this.workspaceStartupHandler=e,this}withWorkspaceFrameCreatedHandler(e){return this.workspaceFrameCreatedHandler=e,this}withWorkspaceFrameInitHandler(e){return this.workspaceFrameInitHandler=e,this}withWorkspaceFramePageLoadHandler(e){return this.workspaceFramePageLoadHandler=e,this}withWorkspaceFrameWorkspaceRenderHandler(e){return this.workspaceFrameWorkspaceRenderHandler=e,this}withWorkspaceComponentCreatedHandler(e){return this.workspaceComponentCreatedHandler=e,this}withWorkspaceAppsStartedHandler(e){return this.workspaceAppsStartedHandler=e,this}},Tc}var Oc,Rc={};var Ac,Mc={};var Ec,Dc,jc={};function Nc(){return Dc||(Dc=1,function(e){var t,n=Oa&&Oa.__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]}),i=Oa&&Oa.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=Oa&&Oa.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var s=t(e),o=0;o<s.length;o++)"default"!==s[o]&&n(r,e,s[o]);return i(r,e),r}),s=Oa&&Oa.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.SpanStatusCode=e.deep_value=e.extractFilteringContextFromArgs=e.getOTELData=e.flattenOtelAtributes=e.safeStringify=e.isNode=e.loadInsightsPlugin=e.registerInsightsPlugin=e.Logs=e.NullTracingState=e.OTEL_PI_KEY=e.withSpan=e.Traces=e.MetricsDependencyBuilder=e.NullMetric=e.Container=e.Log4jsWrapper=e.Builder=void 0;var o=Cc();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return o.Builder}});var a=(Ic||(Ic=1,Object.defineProperty(Sc,"__esModule",{value:!0}),Sc.Log4jsWrapper=void 0,Sc.Log4jsWrapper=class{constructor(e){this.logger=e}get level(){return this.convert("level"in this.logger?this.logger.level:this.logger.publishLevel())}error(e,...t){this.logger.warn(e,...t)}warn(e,...t){this.logger.warn(e,...t)}info(e,...t){this.logger.info(e,...t)}debug(e,...t){this.logger.debug(e,...t)}verbose(e,...t){this.logger.trace(e,...t)}convert(e){if(void 0===e)return 60;switch("string"!=typeof e?e.levelStr.toLowerCase():e.toLowerCase()){case"off":return 0;case"error":return 30;case"warn":return 50;case"info":default:return 60;case"debug":return 70;case"trace":return 80}}}),Sc);Object.defineProperty(e,"Log4jsWrapper",{enumerable:!0,get:function(){return a.Log4jsWrapper}});var c=sc();Object.defineProperty(e,"Container",{enumerable:!0,get:function(){return c.Container}});var d=Ba();Object.defineProperty(e,"NullMetric",{enumerable:!0,get:function(){return d.NullMetric}});var l=Pc();Object.defineProperty(e,"MetricsDependencyBuilder",{enumerable:!0,get:function(){return l.MetricsDependencyBuilder}});const h=r(ac());e.Traces=h.default,Object.defineProperty(e,"withSpan",{enumerable:!0,get:function(){return h.withSpan}}),e.OTEL_PI_KEY="__interopIOTracePropagationInfo";const u=s(Za());e.NullTracingState=u.default;var p=function(){if(Oc)return Rc;Oc=1,Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.Logs=void 0;const e=pc();class t{static get instance(){var n,i;return(null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===n?void 0:n.logs)?null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.ioInsightsInternals)||void 0===i?void 0:i.logs:(t._instance||(t._instance=new e.NullLogsManager(void 0,void 0,void 0)),t._instance)}static set instance(e){t._instance=e}static emit(e){return t.instance.emit(e)}}return Rc.Logs=t,Rc}();Object.defineProperty(e,"Logs",{enumerable:!0,get:function(){return p.Logs}});const g=function(){if(Ac)return Mc;Ac=1,Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.loadInsightsPlugin=function(t,n){if(void 0!==e.get(t))return e.get(t);if(void 0===globalThis.ioInsightsPlugins)return null;let i=globalThis.ioInsightsPlugins[t];if(!i)return null;if("function"==typeof i)try{i=i()}catch(i){return null==n||n.error(`Error loading io.Insights plugin ${t}`,i),e.set(t,null),null}return e.set(t,i),i},Mc.registerInsightsPlugin=function(e,t){void 0===globalThis.ioInsightsPlugins&&(globalThis.ioInsightsPlugins={}),globalThis.ioInsightsPlugins[e]=t};const e=new Map;return Mc}();Object.defineProperty(e,"registerInsightsPlugin",{enumerable:!0,get:function(){return g.registerInsightsPlugin}}),Object.defineProperty(e,"loadInsightsPlugin",{enumerable:!0,get:function(){return g.loadInsightsPlugin}});const f=function(){if(Ec)return jc;let e;return Ec=1,Object.defineProperty(jc,"__esModule",{value:!0}),jc.isNode=function(){if(void 0!==e)return e;if("undefined"!=typeof window)return e=!1,!1;try{e="[object process]"===Object.prototype.toString.call(Lo.process)}catch(t){e=!1}return e},jc}();Object.defineProperty(e,"isNode",{enumerable:!0,get:function(){return f.isNode}});const m=$a();Object.defineProperty(e,"safeStringify",{enumerable:!0,get:function(){return m.safeStringify}});const b=oc();var y;Object.defineProperty(e,"getOTELData",{enumerable:!0,get:function(){return b.getOTELData}}),Object.defineProperty(e,"flattenOtelAtributes",{enumerable:!0,get:function(){return b.flattenOtelAtributes}}),Object.defineProperty(e,"extractFilteringContextFromArgs",{enumerable:!0,get:function(){return b.extractFilteringContextFromArgs}}),Object.defineProperty(e,"deep_value",{enumerable:!0,get:function(){return b.deep_value}}),"undefined"!=typeof Promise&&(Promise.allSettled=Promise.allSettled||(e=>Promise.all(e.map(e=>e.then(e=>({status:"fulfilled",value:e})).catch(e=>({status:"rejected",reason:e})))))),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(y||(e.SpanStatusCode=y={}))}(Oa)),Oa}var Fc=Nc();function Lc(e,t,n){let i;if(Bo.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=Yo(10);return Bo.isNode()?i?i.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const s=function(){const s=e.gateway,o=s?.protocolVersion??3,a=s?.reconnectInterval,c=s?.reconnectAttempts;let d=s?.ws;const l=s?.sharedWorker,h=s?.inproc,u=s?.webPlatform??void 0;let p,g,f,m,b;n&&(d=n.gwURL),Bo.isNode()&&i&&i.gwURL&&(d=i.gwURL),d||l||h||(d="ws://localhost:8385");const y=r();let w=y;void 0!==n?(g=n.windowId,f=n.pid,n.env&&(m=n.env.env,b=n.env.region),w=n.application??"glue-app",p=n.appInstanceId):Bo.isNode()?(f=process.pid,i&&(m=i.env,b=i.region,p=i.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,f=window?.glue42electron.pid,m=window?.glue42electron.env,b=window?.glue42electron.region,w=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(va);let C={application:w,applicationName:y,windowId:g,instance:p,process:f,region:b,environment:m,api:t.version||Sa};return e.identity&&(C=Object.assign(C,e.identity)),{identity:C,reconnectInterval:a,ws:d,sharedWorker:l,webPlatform:u,inproc:h,protocolVersion:o,reconnectAttempts:c,replaySpecs:v}}();let o=r();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(o=t)}return{bus:e.bus??!1,application:o,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Bo.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:s,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||Sa,libs:t.libs??[],customLogger:e.customLogger,getInsights:async function(r,s,o){const a=e.insights;if("object"!=typeof a&&"boolean"!=typeof a&&void 0!==a)throw new Error("insights/otel property should be boolean, object or unspecified");if(!1===a)return{enabled:!1};let c,d;return r?c=r.insights:Bo.isNode()&&!1!==e?.insights&&!1!==e?.insights?.enabled&&!1!==e?.insights?.requestSettings&&(c=await(s?.invoke("T42.Otel.GetConfig",void 0,i?{environment:i.env,region:i.region}:void 0,{waitTimeoutMs:0}).then(e=>e.returned).catch(e=>o?.warn("Unable to retrieve base io.Insights settings: "+(e?.message??e))))),c&&(r||i||Bo.isNode()&&("boolean"==typeof a||!a?.platformInstance))&&(c={...c,metrics:{...c?.metrics,enabled:!!c?.metrics?.enabled,platformMetricsEnabled:!1}}),d=!0===a||void 0===a?c??{enabled:!1}:Pa(c||{},a,{isMergeableObject:xa}),function(e,t,n,i){let r=e.applicationName??"unknown-app";n&&(r=e.applicationName??n?.appName??r),i&&(r=e.applicationName??i.applicationConfig.name??r),e.applicationName=r,e.traces?.closeTrace&&n?.addCloseHandler(()=>Fc.Traces.withSpan("interopio.api.application.close",()=>{}));const s=n?.sid,o=n?.user,a=(Bo.isNode()&&process?.env?.USERNAME)??n?.env?.windowsUserName,c=(Bo.isNode()&&process?.env?.COMPUTERNAME)??n?.env?.machineName,d=i?.env??n?.env?.env,l=i?.region??n?.env?.region,h=i?.instanceId??n?.appInstanceId??"",u=n?.windowId,p={interopioCoreVersion:Sa,interopioLibVersion:t.version||Sa,host:"io.api",tracingAppName:r,tracingAppInstanceId:h,user:o,osUser:a,machine:c,env:d,region:l,windowId:u,sid:s};let g=e.additionalResourceAttributes;if("function"!=typeof g){const t=e.additionalResourceAttributes;g=()=>t}e.additionalResourceAttributes=()=>({...p,...g()})}(d,t,n,i),d.traces?.enabled&&function(e){e.traces&&(e.traces.defaultFilters??=[],e.traces.defaultFilters.push({source:"interopio.api.instrumentation.fetch",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.instrumentation.xhr",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.prefs",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.layouts",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.windows",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{stream:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"#^t42[.].*"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{name:"apps.event"},canBeRoot:!1,enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"apps.command"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.interop",context:{method:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"___insights_pi_storage___"},enabled:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^t42[.].*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.contexts",context:{context:"#^__.*"},canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.appManager",canBeRoot:!1}),e.traces.defaultFilters.push({source:"interopio.api.notifications",canBeRoot:!1}))}(d),d}}}function $c(e,t,n,i){var r,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(s<3?r(o):s>3?r(t,n,o):r(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}"function"==typeof SuppressedError&&SuppressedError;class Wc{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 Go}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 Go}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var Hc,Uc={exports:{}};var qc=(Hc||(Hc=1,function(e,t){var n="__lodash_hash_undefined__",i=9007199254740991,r="[object Arguments]",s="[object Boolean]",o="[object Date]",a="[object Function]",c="[object GeneratorFunction]",d="[object Map]",l="[object Number]",h="[object Object]",u="[object Promise]",p="[object RegExp]",g="[object Set]",f="[object String]",m="[object Symbol]",b="[object WeakMap]",y="[object ArrayBuffer]",w="[object DataView]",v="[object Float32Array]",C="[object Float64Array]",I="[object Int8Array]",S="[object Int16Array]",_="[object Int32Array]",x="[object Uint8Array]",T="[object Uint8ClampedArray]",k="[object Uint16Array]",P="[object Uint32Array]",O=/\w*$/,R=/^\[object .+?Constructor\]$/,A=/^(?:0|[1-9]\d*)$/,M={};M[r]=M["[object Array]"]=M[y]=M[w]=M[s]=M[o]=M[v]=M[C]=M[I]=M[S]=M[_]=M[d]=M[l]=M[h]=M[p]=M[g]=M[f]=M[m]=M[x]=M[T]=M[k]=M[P]=!0,M["[object Error]"]=M[a]=M[b]=!1;var E="object"==typeof Lo&&Lo&&Lo.Object===Object&&Lo,D="object"==typeof self&&self&&self.Object===Object&&self,j=E||D||Function("return this")(),N=t&&!t.nodeType&&t,F=N&&e&&!e.nodeType&&e,L=F&&F.exports===N;function $(e,t){return e.set(t[0],t[1]),e}function W(e,t){return e.add(t),e}function H(e,t,n,i){for(var r=-1,s=e?e.length:0;++r<s;)n=t(n,e[r],r,e);return n}function U(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function q(e){var t=-1,n=Array(e.size);return e.forEach(function(e,i){n[++t]=[i,e]}),n}function B(e,t){return function(n){return e(t(n))}}function G(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}var J,z=Array.prototype,V=Function.prototype,K=Object.prototype,Z=j["__core-js_shared__"],Q=(J=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+J:"",Y=V.toString,X=K.hasOwnProperty,ee=K.toString,te=RegExp("^"+Y.call(X).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=L?j.Buffer:void 0,ie=j.Symbol,re=j.Uint8Array,se=B(Object.getPrototypeOf,Object),oe=Object.create,ae=K.propertyIsEnumerable,ce=z.splice,de=Object.getOwnPropertySymbols,le=ne?ne.isBuffer:void 0,he=B(Object.keys,Object),ue=Fe(j,"DataView"),pe=Fe(j,"Map"),ge=Fe(j,"Promise"),fe=Fe(j,"Set"),me=Fe(j,"WeakMap"),be=Fe(Object,"create"),ye=Ue(ue),we=Ue(pe),ve=Ue(ge),Ce=Ue(fe),Ie=Ue(me),Se=ie?ie.prototype:void 0,_e=Se?Se.valueOf:void 0;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 Te(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 Pe(e){this.__data__=new Te(e)}function Oe(e,t){var n=Be(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&Ge(e)}(e)&&X.call(e,"callee")&&(!ae.call(e,"callee")||ee.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,s=!!i;for(var o in e)!X.call(e,o)||s&&("length"==o||We(o,i))||n.push(o);return n}function Re(e,t,n){var i=e[t];X.call(e,t)&&qe(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Ae(e,t){for(var n=e.length;n--;)if(qe(e[n][0],t))return n;return-1}function Me(e,t,n,i,u,b,R){var A;if(i&&(A=b?i(e,u,b,R):i(e)),void 0!==A)return A;if(!Ve(e))return e;var E=Be(e);if(E){if(A=function(e){var t=e.length,n=e.constructor(t);return t&&"string"==typeof e[0]&&X.call(e,"index")&&(n.index=e.index,n.input=e.input),n}(e),!t)return function(e,t){var n=-1,i=e.length;for(t||(t=Array(i));++n<i;)t[n]=e[n];return t}(e,A)}else{var D=$e(e),j=D==a||D==c;if(Je(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(D==h||D==r||j&&!b){if(U(e))return b?e:{};if(A=function(e){return"function"!=typeof e.constructor||He(e)?{}:Ve(t=se(e))?oe(t):{};var t}(j?{}:e),!t)return function(e,t){return je(e,Le(e),t)}(e,function(e,t){return e&&je(t,Ke(t),e)}(A,e))}else{if(!M[D])return b?e:{};A=function(e,t,n,i){var r,a=e.constructor;switch(t){case y:return De(e);case s:case o:return new a(+e);case w:return function(e,t){var n=t?De(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case v:case C:case I:case S:case _:case x:case T:case k:case P:return function(e,t){var n=t?De(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(q(e),!0):q(e);return H(i,$,new e.constructor)}(e,i,n);case l:case f:return new a(e);case p:return function(e){var t=new e.constructor(e.source,O.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(G(e),!0):G(e);return H(i,W,new e.constructor)}(e,i,n);case m:return r=e,_e?Object(_e.call(r)):{}}}(e,D,Me,t)}}R||(R=new Pe);var N=R.get(e);if(N)return N;if(R.set(e,A),!E)var F=n?function(e){return function(e,t,n){var i=t(e);return Be(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,Ke,Le)}(e):Ke(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(F||e,function(r,s){F&&(r=e[s=r]),Re(A,s,Me(r,t,n,i,s,e,R))}),A}function Ee(e){return!(!Ve(e)||(t=e,Q&&Q in t))&&(ze(e)||U(e)?te:R).test(Ue(e));var t}function De(e){var t=new e.constructor(e.byteLength);return new re(t).set(new re(e)),t}function je(e,t,n,i){n||(n={});for(var r=-1,s=t.length;++r<s;){var o=t[r];Re(n,o,e[o])}return n}function Ne(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 Fe(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Ee(n)?n:void 0}xe.prototype.clear=function(){this.__data__=be?be(null):{}},xe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},xe.prototype.get=function(e){var t=this.__data__;if(be){var i=t[e];return i===n?void 0:i}return X.call(t,e)?t[e]:void 0},xe.prototype.has=function(e){var t=this.__data__;return be?void 0!==t[e]:X.call(t,e)},xe.prototype.set=function(e,t){return this.__data__[e]=be&&void 0===t?n:t,this},Te.prototype.clear=function(){this.__data__=[]},Te.prototype.delete=function(e){var t=this.__data__,n=Ae(t,e);return!(n<0||(n==t.length-1?t.pop():ce.call(t,n,1),0))},Te.prototype.get=function(e){var t=this.__data__,n=Ae(t,e);return n<0?void 0:t[n][1]},Te.prototype.has=function(e){return Ae(this.__data__,e)>-1},Te.prototype.set=function(e,t){var n=this.__data__,i=Ae(n,e);return i<0?n.push([e,t]):n[i][1]=t,this},ke.prototype.clear=function(){this.__data__={hash:new xe,map:new(pe||Te),string:new xe}},ke.prototype.delete=function(e){return Ne(this,e).delete(e)},ke.prototype.get=function(e){return Ne(this,e).get(e)},ke.prototype.has=function(e){return Ne(this,e).has(e)},ke.prototype.set=function(e,t){return Ne(this,e).set(e,t),this},Pe.prototype.clear=function(){this.__data__=new Te},Pe.prototype.delete=function(e){return this.__data__.delete(e)},Pe.prototype.get=function(e){return this.__data__.get(e)},Pe.prototype.has=function(e){return this.__data__.has(e)},Pe.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Te){var i=n.__data__;if(!pe||i.length<199)return i.push([e,t]),this;n=this.__data__=new ke(i)}return n.set(e,t),this};var Le=de?B(de,Object):function(){return[]},$e=function(e){return ee.call(e)};function We(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||A.test(e))&&e>-1&&e%1==0&&e<t}function He(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||K)}function Ue(e){if(null!=e){try{return Y.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function qe(e,t){return e===t||e!=e&&t!=t}(ue&&$e(new ue(new ArrayBuffer(1)))!=w||pe&&$e(new pe)!=d||ge&&$e(ge.resolve())!=u||fe&&$e(new fe)!=g||me&&$e(new me)!=b)&&($e=function(e){var t=ee.call(e),n=t==h?e.constructor:void 0,i=n?Ue(n):void 0;if(i)switch(i){case ye:return w;case we:return d;case ve:return u;case Ce:return g;case Ie:return b}return t});var Be=Array.isArray;function Ge(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}(e.length)&&!ze(e)}var Je=le||function(){return!1};function ze(e){var t=Ve(e)?ee.call(e):"";return t==a||t==c}function Ve(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ke(e){return Ge(e)?Oe(e):function(e){if(!He(e))return he(e);var t=[];for(var n in Object(e))X.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Me(e,!0,!0)}}(Uc,Uc.exports)),Uc.exports),Bc=$o(qc);function Gc(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=Jc(e,void 0),t.commands){for(const n of t.commands)"remove"===n.type?Qc(e,n.path):"set"===n.type&&Kc(e,n.value,n.path);return e}const i=t.added,r=t.updated,s=t.removed;return i&&Object.keys(i).forEach(t=>{e[t]=i[t]}),r&&Object.keys(r).forEach(t=>{zc(t,e,r)}),s&&s.forEach(t=>{delete e[t]}),Fc.Traces.removePropagationInfo(e),e}catch(i){return n?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,i),e}}function Jc(e,t){return Bc(e)}const zc=(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 Vc(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(!Vc(e[n],t[n]))return!1}}for(const n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function Kc(e,t,n){const i=n.split("."),r=["__proto__","constructor","prototype"];let s;for(s=0;s<i.length-1;s++){const t=i[s];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[s]]=t}function Zc(e,t){return Object.keys(t).every(n=>"object"==typeof t[n]?Zc(e?.[n]||{},t[n]||{}):t[n]===e?.[n])}function Qc(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]]}class Yc{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",[la,pa,ma,ya]),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(va.name,e=>{const t=e.type;t&&(t===la||t===ha||t===ca?this.handleContextCreatedMessage(e):t===pa||t===ya||t===wa?this.handleContextUpdatedMessage(e):t!==ma&&t!==da||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){if(e in this._creationPromises)return this._creationPromises[e];const n=Fc.Traces.currentTracingState;return n.addData("INFO",{context:e}),n.addData("DIAGNOSTIC",{data:t}),t=Jc(t),n.injectPropagationInfo(t),this._creationPromises[e]=this._gw3Session.send({type:aa,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 Wc(n.context_id,e,!0,void 0);return i.isAnnounced=!0,i.name=e,i.contextId=n.context_id,i.context=n.data||Jc(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=Jc(t));const n=Fc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],Fc.Traces.currentTracingState=n);const i=this._contextNameToData[e];if(n.addData("DIAGNOSTIC",{data:i}),n.addData("DEBUG",{delta:t}),!i||!i.isAnnounced)return void await this.createContext(e,t);const r=await this.get(i.name);Fc.Traces.currentTracingState=n,Fc.Traces.removePropagationInfo(r);const s=this.setPathSupported?this.calculateContextDeltaV2(r,t):this.calculateContextDeltaV1(r,t);if(!(Object.keys(s.added).length||Object.keys(s.updated).length||s.removed.length||s.commands?.length))return Promise.resolve();const o=Jc(s);n.injectPropagationInfo(o);const a=await this._gw3Session.send({type:ba,domain:"global",context_id:i.contextId,delta:o},{},{skipPeerId:!1});Fc.Traces.currentTracingState=n,!this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId)&&(await i.snapshotPromise,Fc.Traces.currentTracingState=n,this.handleUpdated(i,s,{updaterId:a.peer_id}))}async set(e,t){t&&(t=Jc(t));const n=Fc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],Fc.Traces.currentTracingState=n);const i=this._contextNameToData[e];if(n.addData("DIAGNOSTIC",{data:i}),n.injectPropagationInfo(t),!i||!i.isAnnounced)return this.createContext(e,t);const r=await this._gw3Session.send({type:ba,domain:"global",context_id:i.contextId,delta:{reset:t}},{},{skipPeerId:!1});Fc.Traces.currentTracingState=n,!this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId)&&this.handleUpdated(i,{reset:t,added:{},removed:[],updated:{}},{updaterId:r.peer_id})}setPath(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject(new Error("contexts.setPath operation is not supported, use version 3.10 or later"))}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject(new Error("contexts.setPaths operation is not supported, use version 3.10 or later"));t&&(t=Jc(t));const n=Fc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],Fc.Traces.currentTracingState=n);const i=this._contextNameToData[e];n.addData("DIAGNOSTIC",{data:i}),n.addData("DEBUG",{pathValues:t});const r={[Fc.OTEL_PI_KEY]:void 0};if(n.injectPropagationInfo(r),r[Fc.OTEL_PI_KEY]&&t.push({path:Fc.OTEL_PI_KEY,value:r[Fc.OTEL_PI_KEY]}),!i||!i.isAnnounced){const n={};for(const e of t)Kc(n,e.value,e.path);return this.createContext(e,n)}const s=[];for(const e of t)null===e.value?s.push({type:"remove",path:e.path}):s.push({type:"set",path:e.path,value:e.value});const o=await this._gw3Session.send({type:ba,domain:"global",context_id:i.contextId,delta:{commands:s}},{},{skipPeerId:!1});Fc.Traces.currentTracingState=n,!this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||i.sentExplicitSubscription||i.activityId)&&(await i.snapshotPromise,Fc.Traces.currentTracingState=n,this.handleUpdated(i,{added:{},removed:[],updated:{},commands:s},{updaterId:o.peer_id}))}async get(e){const t=Fc.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],Fc.Traces.currentTracingState=t);const n=this._contextNameToData[e];if(!n||!n.isAnnounced)return!n&&this._subscribeOnGet&&this.subscribeInner(e,()=>{}),Promise.resolve({});if(n&&!n.sentExplicitSubscription)return new Promise((t,n)=>{this.subscribeInner(e,(e,n,i,r)=>{Fc.Traces.removePropagationInfo(e),this._subscribeOnGet||this.unsubscribe(r),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):n(e)})});await n.snapshotPromise;const i=n?.context??{};return Fc.Traces.removePropagationInfo(i),Promise.resolve(Jc(i))}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 subscribeInner(e,t,n){const i=Fc.Traces.currentTracingState;e in this._creationPromises&&(await this._creationPromises[e],Fc.Traces.currentTracingState=i);const r=void 0===n?this._nextCallbackSubscriptionNumber:n;void 0===n&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:r,callback:t}));let s=this._contextNameToData[e];if(!s||!s.isAnnounced)return s=s||new Wc(void 0,e,!1,void 0),this._contextNameToData[e]=s,s.updateCallbacks[r]=t,Promise.resolve(r);const o=s.hasCallbacks();if(s.updateCallbacks[r]=t,o){if(s.hasReceivedSnapshot&&!n){const e=Jc(s.context);t(e,e,[],r)}return Promise.resolve(r)}if(s.joinedActivity||s.createdByUs){if(s.hasReceivedSnapshot&&!n){const e=Jc(s.context);t(e,e,[],r)}return Promise.resolve(r)}if(s.context&&s.sentExplicitSubscription){if(s.hasReceivedSnapshot&&!n){const e=Jc(s.context);t(e,e,[],r)}return Promise.resolve(r)}return this.sendSubscribe(s).then(()=>r,()=>(this.unsubscribe(r,!0),r))}async subscribe(e,t,n){const i=this.all().includes(e);Fc.Traces.currentTracingState.addData("INFO",{context:e,contextExists:i});return this.subscribeInner(e,async(...n)=>Fc.withSpan("interopio.api.contexts.bridge.subscribe.callback",{context:e},n?.[5],i=>(Fc.Traces.removePropagationInfo(n?.[0]),Fc.Traces.removePropagationInfo(n?.[1]),i.addData("INFO",{context:e}),i.addData("DEBUG",{delta:n?.[1]}),i.addData("DEBUG",{removed:n?.[2]}),i.addData("DIAGNOSTIC",{data:n?.[0]}),t(n?.[0],n?.[1],n?.[2],n?.[3],n?.[4]))),n)}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){const t=Fc.Traces.currentTracingState;t.addData("INFO",{context:e}),e in this._creationPromises&&(await this._creationPromises[e],Fc.Traces.currentTracingState=t);const n=this._contextNameToData[e],i=n?.contextId;return n&&i?this._gw3Session.send({type:fa,domain:"global",context_id:n.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,n){const i=e.context;e.context=Gc(e.context,t,this._logger),this._contextNameToData[e.name]!==e||Vc(i,e.context)||this.invokeUpdateCallbacks(e,t,n)}subscribeToContextCreatedMessages(){const e=[ha,la,ca];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===ca?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===ha&&(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]=new Wc(e.context_id,n,!0,e.activity_id),this._trackAllContexts&&this.subscribe(n,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[ya,pa,wa];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===wa)i||(i=this._contextNameToData[e.activity_id]||new Wc(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===pa?(i=i||new Wc(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 s=i.context;if(i.hasReceivedSnapshot=!0,t===pa)i.context=e.data??{};else if(t===wa)i.context=e.context_snapshot??{};else{if(t!==ya)throw new Error("Unrecognized context update message "+t);i.context=Gc(i.context,e.delta,this._logger)}!r&&Vc(i.context,s)&&t!==pa||this.invokeUpdateCallbacks(i,e.delta??e.data,{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),Kc(t.updated,null,e.path)):"set"===e.type&&Kc(t.updated,e.value,e.path)}for(const i in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(i))try{const r=e.updateCallbacks[i],s=Jc({...t.added,...t.updated,...t.reset});r(Jc(e.context),s,t.removed,parseInt(i,10),n,Fc.Traces.extractPropagationInfo(t))}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[ma,da];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===da){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:ua,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:ga,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]||Vc(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]){Vc(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(va.name,e=>{const t=e.type;t&&(t===la||t===ha||t===ca?this.handleContextCreatedMessage(e):t===pa||t===ya||t===wa?this.handleContextUpdatedMessage(e):t!==ma&&t!==da||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))}}$c([Fc.withSpan("interopio.api.contexts.bridge.create",{argMapping:["context"]})],Yc.prototype,"createContext",null),$c([Fc.withSpan("interopio.api.contexts.bridge.update",{argMapping:["context"]})],Yc.prototype,"update",null),$c([Fc.withSpan("interopio.api.contexts.bridge.set",{argMapping:["context"]})],Yc.prototype,"set",null),$c([Fc.withSpan("interopio.api.contexts.bridge.setPaths",{argMapping:["context"]})],Yc.prototype,"setPaths",null),$c([Fc.withSpan("interopio.api.contexts.bridge.get",{argMapping:["context"]})],Yc.prototype,"get",null),$c([Fc.withSpan("interopio.api.contexts.bridge.subscribe",{argMapping:["context"]})],Yc.prototype,"subscribe",null),$c([Fc.withSpan("interopio.api.contexts.bridge.destroy",{argMapping:["context"]})],Yc.prototype,"destroy",null);class Xc{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new Yc(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,s)=>t(e,n,i,()=>this._bridge.unsubscribe(r),s)).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 ed(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=()=>{}:"function"!=typeof n&&(n=()=>{}),e.then(t,n))}function td(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)})}$c([Fc.withSpan("interopio.api.contexts.module.update",{argMapping:["context"]})],Xc.prototype,"update",null),$c([Fc.withSpan("interopio.api.contexts.module.set",{argMapping:["context"]})],Xc.prototype,"set",null),$c([Fc.withSpan("interopio.api.contexts.module.setPaths",{argMapping:["context"]})],Xc.prototype,"setPaths",null),$c([Fc.withSpan("interopio.api.contexts.module.subscribe",{argMapping:["context"]})],Xc.prototype,"subscribe",null),$c([Fc.withSpan("interopio.api.contexts.module.destroy",{argMapping:["context"]})],Xc.prototype,"destroy",null);var nd=function(e){return{ok:!0,result:e}},id=function(e){return{ok:!1,error:e}},rd=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:nd(e(t.result,n.result))},sd=function(e,t){return!0===t.ok?t:id(e(t.error))},od=function(){return od=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},od.apply(this,arguments)};function ad(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(!ad(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(!ad(e[i[n]],t[i[n]]))return!1}return!0}}var cd=function(e){return Array.isArray(e)},dd=function(e){return"object"==typeof e&&null!==e&&!cd(e)},ld=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)},hd=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},ud=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 od({at:e+(n||"")},i)},pd=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return sd(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?nd(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?nd(e):id({message:ld("a string",e)})})},e.number=function(){return new e(function(e){return"number"==typeof e?nd(e):id({message:ld("a number",e)})})},e.boolean=function(){return new e(function(e){return"boolean"==typeof e?nd(e):id({message:ld("a boolean",e)})})},e.constant=function(t){return new e(function(e){return ad(e,t)?nd(t):id({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})})},e.object=function(t){return new e(function(e){if(dd(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]?id({message:"the key '"+i+"' is required but was not present"}):id(ud("."+i,r.error));void 0!==r.result&&(n[i]=r.result)}return nd(n)}return dd(e)?nd(e):id({message:ld("an object",e)})})},e.array=function(t){return new e(function(e){if(cd(e)&&t){return e.reduce(function(e,n,i){return rd(function(e,t){return e.concat([t])},e,function(e,n){return sd(function(e){return ud("["+n+"]",e)},t.decode(e))}(n,i))},nd([]))}return cd(e)?nd(e):id({message:ld("an array",e)})})},e.tuple=function(t){return new e(function(e){if(cd(e)){if(e.length!==t.length)return id({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 id(ud("["+i+"]",r.error));n[i]=r.result}return nd(n)}return id({message:ld("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 rd(Object.assign,t,n.decode(e))},nd({}))})},e.anyJson=function(){return new e(function(e){return nd(e)})},e.unknownJson=function(){return new e(function(e){return nd(e)})},e.dict=function(t){return new e(function(e){if(dd(e)){var n={};for(var i in e)if(e.hasOwnProperty(i)){var r=t.decode(e[i]);if(!0!==r.ok)return id(ud("."+i,r.error));n[i]=r.result}return nd(n)}return id({message:ld("an object",e)})})},e.optional=function(t){return new e(function(e){return null==e?nd(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 s=n.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return id({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})})},e.withDefault=function(t,n){return new e(function(e){return nd(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 id({at:hd(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!dd(i))return id({at:hd(t.slice(0,r+1)),message:ld("an object",i)});if("number"==typeof t[r]&&!cd(i))return id({at:hd(t.slice(0,r+1)),message:ld("an array",i)});i=i[t[r]]}return sd(function(e){return void 0===i?{at:hd(t),message:"path does not exist"}:ud(hd(t),e)},n.decode(i))})},e.succeed=function(t){return new e(function(e){return nd(t)})},e.fail=function(t){return new e(function(e){return id({message:t})})},e.lazy=function(t){return new e(function(e){return t().decode(e)})},e}(),gd=pd.string,fd=pd.number,md=pd.boolean,bd=pd.anyJson;pd.unknownJson;var yd=pd.constant,wd=pd.object,vd=pd.array;pd.tuple,pd.dict;var Cd=pd.optional;pd.oneOf;var Id=pd.union;pd.intersection,pd.withDefault,pd.valueAt,pd.succeed;var Sd=pd.fail;pd.lazy;const _d=(e,t)=>{const n=typeof e;return"function"===n?bd():Sd(`The provided argument as ${t} should be of type function, provided: ${n}`)},xd=gd().where(e=>e.length>0,"Expected a non-empty string"),Td=fd().where(e=>e>=0,"Expected a non-negative number or 0"),kd=Id(xd,wd({name:xd,objectTypes:Cd(vd(xd)),displayName:Cd(gd()),accepts:Cd(gd()),returns:Cd(gd()),description:Cd(gd()),version:Cd(Td),supportsStreaming:Cd(md()),flags:Cd(wd()),getServers:Cd(bd().andThen(e=>_d(e,"method definition getServers")))})),Pd=wd({application:Cd(xd),applicationName:Cd(xd),pid:Cd(Td),machine:Cd(xd),user:Cd(xd),environment:Cd(xd),region:Cd(xd),service:Cd(xd),instance:Cd(xd),windowId:Cd(xd),peerId:Cd(xd),isLocal:Cd(md()),api:Cd(xd),getMethods:Cd(bd().andThen(e=>_d(e,"instance getMethods"))),getStreams:Cd(bd().andThen(e=>_d(e,"instance getStreams")))}),Od=Id(yd("best"),yd("all"),yd("skipMine"),Pd,vd(Pd)),Rd=wd({waitTimeoutMs:Cd(Td),methodResponseTimeoutMs:Cd(Td)});var Ad;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Ad||(Ad={}));class Md{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 s=Fc.Traces.currentTracingState;s.addData("INFO",{stream:Bo.getMethodName(e)}),s.addData("INFO",{options:t});const o=(e,n,i,s)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(n,t,e,i,s,r)},a=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,l=this.getServerMethodsByFilterAndTarget(a,c);if(l.length>0)o(l,l[0].methods[0],r,s);else{const n=()=>{if(c&&t.waitTimeoutMs)if(d+=500,l=this.getServerMethodsByFilterAndTarget(a,c),l.length>0){const e=l[0].methods[0];o(l,e,r,s)}else if(d>=t.waitTimeoutMs){o(l,"string"==typeof e?{name:e}:e,r,s)}else setTimeout(n,500)};setTimeout(n,500)}});return ed(a,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,s){const o=Fc.Traces.currentTracingState;o.addData("INFO",{method:Bo.getMethodName(e)}),o.addData("INFO",{target:n,additionalOptions:i}),o.addData("DIAGNOSTIC",{arguments:t});return ed((async()=>{const o="string"==typeof e?{name:e}:{...e};t||(t={}),n||(n="best"),i||(i={});const a=kd.run(o);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,o,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,o,t))}const c=Od.run(n);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,o,t))}const d=Rd.run(i);if(!d.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(d.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,o,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,o,t))}if(s&&"function"!=typeof s){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,o,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 l=this.getServerMethodsByFilterAndTarget(o,n);if(0===l.length)try{l=await this.tryToAwaitForMethods(o,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,o,t))}const h=i.methodResponseTimeoutMs??3e4,u=i,p=l.map(e=>this.getServerInvokePromise(e.methods[0],e.server,t,u,h)),g=await Promise.all(p),f=this.getInvocationResultObj(g,o,t);return g.every(e=>e.status===Ad.Error)?Promise.reject(f):f})(),r,s)}async getServerInvokePromise(e,t,n,i,r){const s=Yo(10),o=Fc.Traces.currentTracingState;n&&(n=Jc(n),o.injectPropagationInfo(n)),o.addData("INFO",{server:t?.id,instance:t?.instance}),o.addData("INFO",{invocationId:s});const a=this.protocol.client.invoke(s,e,n,t,i),c=await Promise.race([a,td(r,a,{invocationId:s,message:`Invocation timeout (${r} ms) reached for method name: ${e?.name}, target instance: ${JSON.stringify(t.instance)}, options: ${JSON.stringify(i)}`,status:Ad.Error})]);return o.addData("DIAGNOSTIC",{returnValue:c}),c}generateInvalidInputInvocationResult(e,t,n){const i={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},r={invocationId:Yo(10),status:Ad.Error,message:e};return this.getInvocationResultObj([r],i,n)}getInvocationResultObj(e,t,n){Fc.Traces.removePropagationInfo(n);const i=e.filter(e=>e.status===Ad.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===Ad.Error).reduce((e,i)=>e=[...e,{executed_by:i.instance,called_with:n,name:t.name,message:i.message}],[]),s=e[0];return{method:t,called_with:n,returned:s.result,executed_by:s.instance,all_return_values:i,all_errors:r,message:s.message,status:s.status}}tryToAwaitForMethods(e,t,n){return new Promise((i,r)=>{if(0===n.waitTimeoutMs)return void r();let s=0;const o=setInterval(()=>{s+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(o),i(a);else if(s>=(n.waitTimeoutMs||1e4))return clearInterval(o),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],s=t[n];switch(n){case"objectTypes":i=(r||[]).every(e=>(s||[]).includes(e));break;case"flags":i=Zc(s||{},r||{});break;default:i=String(r).toLowerCase()===String(s).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)}}$c([Fc.withSpan("interopio.api.interop.stream.subscribe",{argMapping:e=>({stream:Bo.getMethodName(e)})})],Md.prototype,"subscribe",null),$c([Fc.withSpan("interopio.api.interop.invoke",{argMapping:e=>({method:Bo.getMethodName(e)})})],Md.prototype,"invoke",null),$c([Fc.withSpan("interopio.api.interop.invoke.server",{argMapping:{"0.name":"method"}})],Md.prototype,"getServerInvokePromise",null);class Ed{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 Dd{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 jd=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 Dd(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const n=new Ed(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const n=new Ed(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}};class Nd{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 Ed(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 Fd{_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 Nd(e,this._protocol,this._repoMethod):void 0:t.map(e=>new Nd(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new Ed(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}}async close(){return 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.");const n=Fc.Traces.currentTracingState;n.addData("INFO",{stream:this?.name,branches:t}),n.addData("DIAGNOSTIC",{data:e}),e=Jc(e),n.injectPropagationInfo(e),this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}$c([Fc.withSpan("interopio.api.interop.stream.close",{thisMapping:{name:"stream"}})],Fd.prototype,"close",null),$c([Fc.withSpan("interopio.api.interop.stream.push",{thisMapping:{name:"stream"}})],Fd.prototype,"push",null);class Ld{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new jd(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,n,i,r){const s=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 s;if(s="string"==typeof e?{name:""+e}:{...e},!s.name)return i(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(s)}`);if(this.serverRepository.getList().some(e=>e.definition.name===s.name))return i(`A stream with the name "${s.name}" already exists! Please, provide a unique name for the stream.`);s.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const o=this.serverRepository.add({definition:s,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(o).then(()=>{let e;r?(e=r,r.updateRepoMethod(o)):e=new Fd(this.protocol,o,this),o.stream=e,n(e)}).catch(e=>{o.repoId&&this.serverRepository.remove(o.repoId),i(e)})});return ed(s,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(Fc.Traces.currentTracingState.addData("INFO",{method:Bo.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Bo.getMethodName(e)}`);const n=async(e,n)=>{try{const i=t(e.args,e.instance);if(i&&"function"==typeof i.then){const e=Fc.Traces.currentTracingState,t=await i;Fc.Traces.currentTracingState=e,n(void 0,t)}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(Fc.Traces.currentTracingState.addData("INFO",{method:Bo.getMethodName(e)}),"function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${Bo.getMethodName(e)}`);const n=async(e,n)=>{try{let i=!1;const r=e=>{i||n(void 0,e),i=!0},s=e=>{i||(e||(e=""),n(e,e)),i=!0},o=t(e.args,e.instance,r,s);o&&"function"==typeof o.then&&o.then(r).catch(s)}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(Fc.Traces.currentTracingState.addData("INFO",{method:Bo.getMethodName(e)}),"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)}`);await this.currentlyUnregistering[n.name];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 i=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}});return this.protocol.server.register(i).catch(e=>{throw i?.repoId&&this.serverRepository.remove(i.repoId),e})}onMethodInvoked(e,t,n){const i=Fc.Traces.extractPropagationInfo(n.args,!0);Fc.withSpan("interopio.api.interop.register.callback",{method:e?.definition?.name},i,i=>{if(i.addData("INFO",{method:e?.definition?.name}),i.addData("INFO",{invocationId:t}),i.addData("INFO",{invoker:n?.instance}),i.addData("DIAGNOSTIC",{arguments:n?.args}),!e||!e.theFunction)return void(i.status={code:Fc.SpanStatusCode.ERROR,message:"Required argument 'methodToExecute' is missing."});let r;const s=new Promise(e=>{r=e});return e.theFunction(n,(n,s)=>{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.status={code:Fc.SpanStatusCode.ERROR,message:n},i.recordException(n)}s?("object"!=typeof s||Array.isArray(s))&&(s={_value:s}):s={},i.addData("DIAGNOSTIC",{returnValue:s}),this.protocol.server.methodInvocationResult(e,t,n,s),r()}),s})}}$c([Fc.withSpan("interopio.api.interop.stream.create",{argMapping:e=>({stream:Bo.getMethodName(e)})})],Ld.prototype,"createStream",null),$c([Fc.withSpan("interopio.api.interop.register",{argMapping:e=>({method:Bo.getMethodName(e)})})],Ld.prototype,"register",null),$c([Fc.withSpan("interopio.api.interop.register.async",{argMapping:e=>({method:Bo.getMethodName(e)})})],Ld.prototype,"registerAsync",null),$c([Fc.withSpan("interopio.api.interop.unregister",{argMapping:e=>({method:Bo.getMethodName(e)})})],Ld.prototype,"unregister",null);class $d{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??Yo(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 Wd=e=>({...e,flags:e.flags.metadata||{}});class Hd{logger;API;servers={};myServer;methodsCount={};callbacks=Ho();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 $d(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={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:()=>this.getServersByMethod(i)};r.object_types=r.objectTypes,r.display_name=r.displayName,n.methods[t.id]=r;const s=Wd(r);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),r}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=Wd(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(Wd)}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]=Wd(n)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class Ud{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 qd="onSubscriptionRequest",Bd="onSubscriptionAdded",Gd="onSubscriptionRemoved";class Jd{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=Ho();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,s={id:r,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[r]=s,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(Bd,s,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)}`)}),this.callbacks.execute(Gd,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(Bd,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(qd,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(Gd,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(Gd,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(qd,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 zd{session;clientRepository;serverRepository;logger;callbacks=Ho();streaming;constructor(e,t,n,i){this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.streaming=new Jd(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,s=this.serverRepository.getList().filter(e=>e.repoId===i)[0];if(void 0===s)return;const o=this.clientRepository.getServerById(n)?.instance,a={args:r,instance:o};this.callbacks.execute("onInvoked",s,t,a)}}class Vd{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 Kd{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=Yo(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 Zd="awaitingAccept",Qd="subscribed",Yd="Subscription failed.",Xd="ClientInitiated";class el{session;repository;logger;subscriptionsList={};timedCache=new Kd({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,s){if(Fc.Traces.removePropagationInfo(t.arguments),0===n.length)return void r({method:e,called_with:t.arguments,message:Yd+" No available servers matched the target params."});const o=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(o,e,t,i,r,t.methodResponseTimeout||1e4,s);"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 s={type:"subscribe",server_id:i,method_id:r.gatewayId,arguments_kv:t.arguments};this.session.send(s,{serverId:i,subLocalKey:o}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):r({method:e,called_with:t.arguments,message:Yd+" 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,s,o){const a={localKey:e,status:Zd,method:t,params:n,success:i,error:r,trackedServers:[],handlers:{onData:o?.handlers.onData||[],onClosed:o?.handlers.onClosed||[],onConnected:o?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:o?.subscription};return o||(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===Zd?(r({method:t,called_with:n.arguments,message:Yd+" Subscription attempt timed out after "+s+" ms."}),delete this.subscriptionsList[e]):i.status===Qd&&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]))},s),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===Zd){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:Fc.Traces.removePropagationInfo(i.params.arguments),method:i.method})}else i.status===Qd&&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 s=n.status===Zd;if(n.status=Qd,s){let e=!1,t=n.subscription;t?(t.setNewSubscription(n),n.success(t),e=!0):(t=new Vd(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,s=i[0].serverId,o=this.repository.getServerById(s),a=n.handlers.onData,c=n.queued.data,d={data:e.data,server:o?.instance??{},requestArguments:n.params.arguments,message:void 0,private:r},l=Fc.Traces.extractPropagationInfo(d.data,!0),h=n?.method?.name;Fc.withSpan("interopio.api.interop.stream.onData",{method:h,stream:h},l,()=>{const e=Fc.Traces.currentTracingState;e.addData("INFO",{method:h}),e.addData("INFO",{stream:h}),e.addData("INFO",{handlerCount:a?.length}),e.addData("DIAGNOSTIC",{data:d}),a.length>0?a.forEach(e=>{"function"==typeof e&&e(Jc(d))}):c.push(Jc(d))})};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:Xd}).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,Xd),delete this.subscriptionsList[e])}}class tl{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 el(e,t,n)}subscribe(e,t,n,i,r,s){this.streaming.subscribe(e,t,n,i,r,s)}invoke(e,t,n,i){const r=i.id,s={type:"call",server_id:r,method_id:t.gatewayId,arguments_kv:n};return this.session.send(s,{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),s={...n,pid:isNaN(r)?n.process:r,peerId:t,isLocal:i};this.repository.addServer(s,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:Ad.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:Ad.Error,message:r}}return{invocationId:"",message:e.message,status:Ad.Error,error:e}}}function nl(e,t,n,i,r,s){const o=r.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),d=t.domain("agm",["subscribed"]),l=new zd(d,n,i,o.subLogger("server")),h=new tl(d,n,o.subLogger("client"));return d.onJoined(r=>{n.addServer(e,t.peerId),r?async function(){o.info("reconnected - will replay registered methods and subscriptions"),h.drainSubscriptionsCache().forEach(e=>{const t=e.method,n=Object.assign({},e.params);o.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),s.client.subscribe(t,n,void 0,void 0,e).then(()=>o.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>o.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=h.drainSubscriptions();for(const n of t){const t=n.method,i=Object.assign({},n.params);o.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(i)}`),e.push(s.client.subscribe(t,i,void 0,void 0,n).then(()=>o.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(s.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then(()=>o.info(`subscribing to method ${n.name} DONE`)).catch(()=>o.warn(`subscribing to method ${n.name} FAILED`))):t?.theFunction?.userCallback?e.push(s.register(n,t.theFunction.userCallback).then(()=>o.info(`registering method ${n.name} DONE`)).catch(()=>o.warn(`registering method ${n.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(s.registerAsync(n,t.theFunction.userCallbackAsync).then(()=>o.info(`registering method ${n.name} DONE`)).catch(()=>o.warn(`registering method ${n.name} FAILED`)))}await Promise.all(e),o.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>o.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:h,server:l}),a=void 0)}),d.onLeft(()=>{n.reset()}),d.join(),c}class il{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 $d(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new Hd(e.logger.subLogger("cRep"),this),this.serverRepository=new Ud,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);n=nl(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then(t=>(this.protocol=t,this.client=new Md(this.protocol,this.clientRepository,this.instance,e),this.server=new Ld(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,s){return this.client.invoke(e,t,n,i,r,s)}waitForMethod(e){const t=new Go,n=this.client.methodAdded(i=>{i.name===e&&(n(),t.resolve(i))});return t.promise}}const rl=["subscribed","success"],sl=1e4;class ol{connection;logger;session;subscriptions;readyPromise;resubscribeInProgress;pendingPublishes=[];canDrain=!1;drainInProgress=!1;sessionGeneration=0;constructor(e,t){this.connection=e,this.logger=t,this.subscriptions=[],this.session=e.domain("bus",rl),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()}),this.session.onLeft(()=>{this.canDrain=!1,this.sessionGeneration++}),this.session.onJoined(e=>{this.sessionGeneration++;const t=this.sessionGeneration,n=this.resubscribeInProgress??Promise.resolve();this.resubscribeInProgress=n.then(async()=>{try{if(e&&(await this.resubscribe(),await this.sleep(500)),this.sessionGeneration!==t)return;this.canDrain=!0,this.tryDrain()}catch(e){this.logger.error(`bus: error during onJoined chain: ${JSON.stringify(e)}`)}})})}sleep(e){return new Promise(t=>setTimeout(t,e))}ready(){return this.readyPromise}publish=(e,t,n)=>{this.publishCore(e,t,n)};publishCore(e,t,n){const{routingKey:i,target:r}=n||{},s=Fc.Traces.currentTracingState;if(s.addData("INFO",{topic:e}),s.addData("DIAGNOSTIC",{data:t}),s.addData("INFO",{routingKey:i,target:r}),t=Jc(t),s.injectPropagationInfo(t),this.pendingPublishes.push({topic:e,data:t,options:n?Jc(n):void 0}),this.pendingPublishes.length>sl){const e=this.pendingPublishes.length-sl;this.pendingPublishes.splice(0,e),this.logger.warn(`bus: outbox exceeded 10000, dropped ${e} oldest publish(es)`)}1!==this.pendingPublishes.length||this.canDrain?this.canDrain||this.logger.debug(`bus: queued publish to ${e} (${this.pendingPublishes.length} pending)`):this.logger.info(`bus: started buffering publishes (first topic: ${e})`),this.tryDrain()}isTransportError(e){return null!=e&&("object"!=typeof e||!e.request_id&&!e.domain)}async tryDrain(){if(!this.drainInProgress&&this.canDrain){this.drainInProgress=!0;try{let e=0;for(;this.pendingPublishes.length>0&&this.canDrain;){const t=this.pendingPublishes[0],{routingKey:n,target:i}=t.options||{},r=this.removeEmptyValues({type:"publish",topic:t.topic,data:t.data,peer_id:this.connection.peerId,routing_key:n,target_identity:i});try{await this.session.sendFireAndForget(r),this.pendingPublishes.shift(),e++}catch(e){if(this.isTransportError(e)){this.logger.info(`bus: drain paused at ${t.topic} due to transport error (${this.pendingPublishes.length} pending)`);break}this.pendingPublishes.shift(),this.logger.error(`bus: failed to publish to ${t.topic}: ${JSON.stringify(e)}`)}}e>0&&0===this.pendingPublishes.length&&this.logger.debug(`bus: drained ${e} publish(es)`)}finally{this.drainInProgress=!1}}}subscribe=(e,t,n)=>this.subscribeCore(e,t,n);subscribeCore(e,t,n){return new Promise((i,r)=>{const{routingKey:s,target:o}=n||{},a=Fc.Traces.currentTracingState;a.addData("INFO",{topic:e}),a.addData("INFO",{routingKey:s,target:o});const c=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.connection.peerId,routing_key:s,source:o});this.session.send(c).then(n=>{const{subscription_id:r}=n;a.addData("INFO",{subscription_id:r});const c={subscription_id:r,topic:e,routingKey:s,source:o,callback:function(...n){const i=Fc.Traces.extractPropagationInfo(n?.[0],!0);Fc.withSpan("interopio.api.bus.subscribe.callback",{topic:e},i,i=>{i.addData("INFO",{topic:e,subscription_id:c.subscription_id}),i.addData("DIAGNOSTIC",{data:n?.[0]}),t.apply(this,n)})}};this.subscriptions.push(c),i({unsubscribe:()=>{const e=c.subscription_id;return this.subscriptions=this.subscriptions.filter(t=>t.subscription_id!==e),this.session.send({type:"unsubscribe",subscription_id:e,peer_id:this.connection.peerId}).catch(t=>{this.logger.warn(`Failed to send unsubscribe request for ${e}: ${JSON.stringify(t)}`)}),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))})};async resubscribe(){const e=[...this.subscriptions];this.logger.info(`bus: re-subscribing ${e.length} subscription(s) after reconnect`);for(const t of e)if(this.subscriptions.includes(t))try{const e=this.removeEmptyValues({type:"subscribe",topic:t.topic,peer_id:this.connection.peerId,routing_key:t.routingKey,source:t.source}),n=await this.session.send(e);t.subscription_id=n.subscription_id}catch(e){this.logger.error(`bus: failed to re-subscribe to topic "${t.topic}": ${JSON.stringify(e)}`)}}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}}function al(e){if(!cl(e))for(const t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;const n=e[t];cl(n)||(xa(n)||Array.isArray(n)?al(n):e[t]=n?.constructor?.name||n.toString())}}function cl(e){return!e||(e!==Object(e)||"function"==typeof e)}$c([Fc.withSpan("interopio.api.bus.publish",{argMapping:["topic"]})],ol.prototype,"publishCore",null),$c([Fc.withSpan("interopio.api.bus.subscribe",{argMapping:["topic"]})],ol.prototype,"subscribeCore",null);const dl=(e,t)=>{const n="object"==typeof window?window.iodesktop??window.glue42gd:void 0,i="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),r=new Go,s=zo("glue"),o=Lc(e=e||{},t=t||{},n);let a,c,d,l,h,u,p,g;const f={};function m(e,t,n){g=d.canPublish("trace"),g&&d.trace(`registering ${e} module`);const i=i=>{if(t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,!g)return;const r=i?`${e} failed - ${i.message}`:`${e} is ready - ${n.endTime-n.startTime}`;d.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=>{f[e]=t,dl[e]=t})}function b(){const e=zo("metrics"),t=o.metrics,i=n?.getMetricsPublishingEnabled,r=o.connection.identity,s=i||(()=>!0),c=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return l=jo({connection:t?a:void 0,logger:d.subLogger("metrics"),canUpdateMetric:s,system:"Glue42",service:r?.service??n?.applicationName??o.application,instance:r?.instance??r?.windowId??Yo(10),disableAutoAppSystem:c,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),m("metrics",l,e),Promise.resolve()}function y(){const e=zo("interop"),t={connection:a,logger:d.subLogger("interop")};return c=new il(t),oa.Interop=c,m(["interop","agm"],c,e),Promise.resolve()}function w(){const e=o.activities&&3===a.protocolVersion;if(o.contexts||e){const e=zo("contexts");h=new Xc({connection:a,logger:d.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}),m("contexts",h,e)}else{const e=a.replayer;e&&e.drain(va.name)}return Promise.resolve()}async function v(){if(!o.bus)return Promise.resolve();const e=zo("bus");return u=new ol(a,d.subLogger("bus")),m("bus",u,e),Promise.resolve()}async function C(t){const i=zo("insights"),s=await o.getInsights(n,t,d);o.insights=s;try{const e=new Fc.Builder,t=d.subLogger("insights");s.enabled&&await async function(e,t){try{(await Promise.resolve().then(function(){return pl})).init()}catch{e.warn("@interopio/insights-base plugin failed to load, insights will be disabled")}if(t.metrics?.enabled)try{(await Promise.resolve().then(function(){return pl})).init()}catch{e.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled")}if(t.traces?.enabled)try{(await Promise.resolve().then(function(){return pl})).init()}catch{e.warn("@interopio/insights-traces plugin failed to load, insights traces functionality will be disabled")}}(t,s),e.withSettings(s),e.withLogger(new Fc.Log4jsWrapper(t)),e.withMetrics();const n="___insights_pi_storage___";e.withTraces().withTraceLogger(new Fc.Log4jsWrapper(t.subLogger("traces"))).withPropagationInfoStorage((e,t)=>h?.update(n,{[e.replace(/[.]/g,"_!_")]:{pi:t}}),e=>h?.get(n)?.then(t=>t[e.replace(/[.]/g,"_!_")]?.pi)??Promise.resolve(null));const o=e.build();return await o.start(),m("insights",o,i),Fc.Traces.withSpan("interopio.api.startup",()=>r.promise),p=o,Promise.resolve()}catch(e){if(i.stop(),d?.error("Error initializing insights",e),s.failOnInitError)throw e;return Promise.resolve()}finally{al(o?.insights),al(e?.insights)}}function I(e){try{return e.forEach(e=>{!function(e,t){const n=zo(e),i=t(f);i&&m(e,i,n)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return i.then(function(){const e=zo("logger");return d=new oa(`${o.connection.identity?.application}`,void 0,o.customLogger),d.consoleLevel(o.logger.console),d.publishLevel(o.logger.publish),d.canPublish("debug")&&d.debug("initializing glue..."),m("logger",d,e),Promise.resolve(void 0)}).then(function(){const e=zo("connection");a=new ra(o.connection,d.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,a.login(n)}).then(()=>(m("connection",a,e),o)).catch(e=>{throw a&&a.logout(),e})}).then(()=>Promise.all([b(),y(),w(),v()])).then(()=>c.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Bo.isNode()&&void 0===process.env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&c.methods({name:t}).length>0)try{await c.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;d.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>C(c)).then(()=>I(o.libs||[])).then(function(){const e=Object.keys(f).map(e=>{const t=f[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const i={coreVersion:Sa,version:o.version};s.stop();const g={feedback:e=>{c&&c.invoke("T42.ACS.Feedback",e,"best")},info:i,logger:d,interop:c,agm:c,connection:a,metrics:l,contexts:h,insights:p,bus:u,version:o.version,userConfig:e,done:()=>(d?.info("done called by user..."),a.logout())};if(g.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=Jo;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(f).forEach(e=>{const t=f[e];g[e]=t}),g.config={},Object.keys(o).forEach(e=>{g.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{g.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(g),n&&n.updatePerfData&&n.updatePerfData(g.performance),g.agm){const e=(e,t,n)=>function(){return g.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${n}' instead.`),e.apply(g.agm,arguments)},t=g.agm;t.method_added=e(g.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(g.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(g.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(g.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(g.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return r.resolve(),g}).catch(e=>(r.reject({err:e}),Promise.reject({err:e,libs:f})))};"undefined"!=typeof window&&(window.IOConnectCore=dl),dl.version=Sa,dl.default=dl;const ll=(e=>{let t;return n=>{if(window.glue42gd||window.iodesktop)return(e=>{const t={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:e?.libraries??[],logger:e?.systemLogger?.level??"warn"};return(window.IODesktop||window.Glue)(t)})(n);const i=((e={})=>{const t=!!e?.gateway?.webPlatform?.port,n=O(Mr).run(e.widget);if(!n.ok)throw re.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(n.error)}`);const i=O(Er).run(e.modals);if(!i.ok)throw re.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(i.error)}`);const r=O(ns).run(e.intentResolver);if(!r.ok)throw re.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(r.error)}`);return{...D,...e,isPlatformInternal:t,logger:e.systemLogger?.level??"info",customLogger:e.systemLogger?.customLogger,widget:d(j,n.result??{}),modals:d(N,i.result??{}),intentResolver:d(F,r.result??{})}})(n);try{(()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)return re.raiseError("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}})()}catch(e){return void 0===t?Promise.reject(new Error(e)):t}const r=(async t=>{const n=new co,i=await bs(()=>e(t,{version:lo}),3e4,"Glue Web initialization timed out, because core didn't resolve"),r=i.logger.subLogger("web.main.controller");n.defineGlue(i),await n.preferredConnectionController.start(t),await n.bridge.start(n.controllers),n.defineConfig(t),r.trace("the bridge has been started, initializing all controllers"),await Promise.all(Object.values(n.controllers).map(e=>e.start(i,n))),r.trace("all controllers reported started, starting all additional libraries");try{return await Promise.all(t.libraries.map(e=>e(i,t))),r.trace("all libraries were started"),n.eventsDispatcher.start(i),r.trace("start event dispatched, glue is ready, returning it"),await n.uiController.showComponents(i).catch(e=>r.warn(e?.message?e.message:JSON.stringify(e))),await Promise.all(Object.values(n.controllers).map(e=>e.postStart?e.postStart(i,n):Promise.resolve())),window.iobrowser.system=ho(0,n.bridge),window.iobrowser=Object.freeze({...window.iobrowser}),i}catch(e){return re.raiseError(e,!0)}})(i);return t=n?.memoizeAPI?r:void 0,r}})(dl);if("undefined"!=typeof window){const e=window;e.IOBrowser=ll,delete e.GlueCore,delete e.IOConnectCore}const hl=window.glue42gd||window.glue42core,ul=window.iodesktop||window.iobrowser;hl||ul||(window.iobrowser={webStarted:!1}),window.iodesktop||window.iobrowser.system||(window.iobrowser.system=ho()),ll.version=lo;var pl=Object.freeze({__proto__:null});return ll});